Skip to content

feat(api): introduce RequestConfigBuilder for SDK-agnostic abort signal support - #1008

Merged
edelauna merged 15 commits into
Zoo-Code-Org:mainfrom
easonLiangWorldedtech:feat/abort-signal-core/config-builder-base
Aug 18, 2026
Merged

edelauna merged 15 commits into
Zoo-Code-Org:mainfrom
easonLiangWorldedtech:feat/abort-signal-core/config-builder-base

Conversation

@easonLiangWorldedtech

@easonLiangWorldedtech easonLiangWorldedtech commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

feat(api): introduce RequestConfigBuilder for SDK-agnostic abort signal support

Problem

Currently each provider manually constructs its request config by spreading { signal: metadata?.abortSignal, headers: ... } — a repetitive pattern that:

  1. Duplicates logic across every provider implementation
  2. Is error-prone — easy to forget or mistype the spread
  3. Doesn't handle SDK differences well — OpenAI uses queryParams, Bedrock uses body, Anthropic uses apiVersion
  4. Lacks immutability guarantees — direct spreading can accidentally mutate original config objects

Proposed Solution

Introduce RequestConfigBuilder — a generic, SDK-agnostic request configuration builder that provides a fluent API for building type-safe request configurations.

Usage Example

const config = new RequestConfigBuilder()
    .addAbortSignal(metadata)
    .addHeaders({ "X-Custom-Header": "value" })
    .setOption("modelId", "claude-3-opus")
    .build()

Key Features

  • Fluent chainable API — concise, readable code
  • Generic type safety — TOptions extends Record<string, any> ensures compile-time correctness per SDK
  • Zero runtime overhead — Generics erased at compile time; mergeAbortSignals() returns primary directly when no secondary provided
  • Immutability guaranteed — build() returns shallow copy
  • Defensive by default — undefined/empty values are silently skipped, never thrown

API Methods

Instance Methods (all chainable)

  • addAbortSignal(metadata?) — Extracts abort signal from metadata and adds it to config
  • addHeaders(headers?) — Merges custom headers (empty objects skipped, no default param overhead)
  • setOption(key, value) — Type-safe single option setter
  • getOption(key) — Get an option by key
  • build() — Returns shallow copy for immutability; undefined if no options set
  • addMergedSignal(internalController, metadata?, timeoutMs?) — Merge internal controller + external signal with timeout support (for providers that maintain their own AbortController)

Static Methods

  • fromMetadata(metadata?, extraOptions?) — Quick factory for simple signal + options scenarios
  • mergeAbortSignals(primary, secondary?) — Combines two signals (returns primary directly when no secondary — zero overhead)

Files to Add/Modify

File Description
src/api/providers/config-builder/request-config-builder.ts Core builder class (~147 lines) with generic type support, chainable methods, and static utilities
src/api/providers/utils/abort-signal.ts Shared utility functions: mergeAbortSignalAndTimeout() + mergeAbortSignals() (~49 lines)
src/api/providers/__tests__/request-config-builder.spec.ts Comprehensive test suite (~523 lines) covering all methods and edge cases
src/api/providers/utils/__tests__/abort-signal.spec.ts Utility function tests (~93 lines)
src/api/providers/config-builder/README.md Full documentation with architecture diagram, usage examples for OpenAI/Bedrock/Anthropic, and extension guide (~503 lines)
src/api/providers/index.ts Export RequestConfigBuilder from the providers barrel

Design Principles

  1. Immutability — build() returns a shallow copy; constructor copies defaultOptions
  2. Defensive programming — undefined/empty values are silently skipped, never thrown
  3. Generic type safety — TOptions extends Record<string, any> ensures compile-time correctness per SDK
  4. Zero runtime overhead — Generics erased at compile time; mergeAbortSignals() returns primary directly when no secondary provided
  5. Extensibility — New SDKs extend the base class and add only their specific methods

Key Improvements vs Original PR #701 Draft

Issue Status
addHeaders(headers: Record<string, string> = {}) default param overhead ✅ Fixed — changed to optional param headers?: Record<string, string>
mergeAbortSignals([single]) creates unnecessary AbortController ✅ Fixed — returns primary directly when no secondary
No provider-specific merge method ✅ Added addMergedSignal() for providers with internal AbortController
timeoutMs ≤ 0 behavior inconsistent across providers ✅ Fixed in utility function — treated as "disabled" not "abort immediately"

Relationship to Other PRs/Issues

Next Steps (after merge)

  1. Refactor existing providers (bedrock.ts, openai-codex.ts, etc.) to use addMergedSignal() instead of manual signal merging
  2. Create SDK-specific builder classes (OpenAiRequestConfigBuilder, BedrockRequestConfigBuilder) with provider-specific methods like addPath(), addQueryParams(), setApiVersion()
  3. Add integration tests verifying builders work correctly with actual SDK calls

Related

Related to #404 — provides the infrastructure foundation for consistent abort signal handling across all providers. Actual fix will be implemented when refactoring individual providers in a follow-up PR.
Closes #1007

Summary by CodeRabbit

  • New Features
    • Added a fluent request configuration builder for composing headers, options, and abort signals.
    • Added support for merging external cancellation signals with provider-controlled signals and optional timeouts.
    • Added automatic timeout cleanup to prevent unnecessary pending timers.
    • Added helpers for creating request configurations from metadata and extra options.
    • Exposed the request configuration builder through the providers API.
  • Bug Fixes
    • Improved cancellation behavior so requests respond consistently when any associated signal aborts.

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Changes

Request configuration and abort-signal support

Layer / File(s) Summary
Abort-signal composition utilities
src/api/providers/utils/abort-signal.ts, src/api/providers/utils/__tests__/abort-signal.spec.ts
Adds timeout-aware signal merging, multi-signal composition, cleanup callbacks, and coverage for timeout and abort propagation behavior.
Typed request builder and option assembly
src/api/providers/config-builder/request-config-builder.ts, src/api/providers/__tests__/request-config-builder.spec.ts, src/api/providers/index.ts
Adds fluent typed option, header, metadata, factory, and shallow-build behavior, then exports the builder from the providers barrel.
Merged signal wiring and lifecycle cleanup
src/api/providers/config-builder/request-config-builder.ts, src/api/providers/__tests__/request-config-builder.spec.ts
Combines internal, metadata, and timeout signals, chains cleanup callbacks, and tests composed abort behavior and end-to-end builder chaining.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Provider
  participant RequestConfigBuilder
  participant AbortSignalUtilities
  participant RequestConfig
  Provider->>RequestConfigBuilder: add options, headers, and metadata
  RequestConfigBuilder->>AbortSignalUtilities: merge internal and external signals
  AbortSignalUtilities-->>RequestConfigBuilder: return signal and cleanup
  RequestConfigBuilder-->>RequestConfig: build shallow-copied configuration
Loading

Possibly related PRs

Suggested labels: awaiting-review

Suggested reviewers: navedmerchant

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: introducing RequestConfigBuilder for SDK-agnostic abort-signal handling.
Description check ✅ Passed The description is detailed and largely matches the template, with most required information present despite a missing explicit test procedure section.
Linked Issues check ✅ Passed The builder, abort-signal utilities, tests, and barrel export align with issue #1007's requirements for fluent, immutable, defensive request config building.
Out of Scope Changes check ✅ Passed The changes stay focused on the builder, abort-signal utilities, tests, and export, with no unrelated code additions evident.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/api/providers/config-builder/README.md (2)

196-221: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Documented mergeAbortSignals implementation doesn't match the actual code.

This section shows a hand-written implementation (manual AbortController + addEventListener, with a special case returning primarySignal unchanged when secondarySignal is already aborted). The real implementation in abort-signal.ts delegates to native AbortSignal.any(), which behaves differently — notably, it will immediately reflect an already-aborted secondary signal, the opposite of what this doc claims. This will mislead anyone extending the builder based on this doc.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/api/providers/config-builder/README.md` around lines 196 - 221, Update
the “How mergeAbortSignals Works” section to accurately document the actual
implementation in mergeAbortSignals and its use of native AbortSignal.any().
Remove the hand-written AbortController example and state that any
already-aborted input, including secondarySignal, causes the returned signal to
be aborted immediately.

479-495: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

API reference is missing addMergedSignal / mergeAbortSignalAndTimeout.

The Instance/Static Methods tables don't document addMergedSignal, even though it's the method intended to address issue #404 (merging a provider's internal controller with an external abort signal and optional timeout). Worth adding given it's a key part of this PR's purpose.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/api/providers/config-builder/README.md` around lines 479 - 495, Update
the README API reference tables for the configuration builder to document the
missing addMergedSignal instance method and mergeAbortSignalAndTimeout static
method, including their parameters, return types, and behavior for combining
provider/external abort signals with an optional timeout. Keep the descriptions
aligned with the actual method signatures and implementation.
src/api/providers/config-builder/request-config-builder.ts (1)

42-50: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Header merge is case-sensitive; HTTP header names are not.

addHeaders merges via plain object spread on raw key strings. Differently-cased keys (e.g. "x-custom" vs "X-Custom") won't be recognized as the same header, so a later addHeaders call intended to override an earlier one could instead add a duplicate header with different casing sent to the wire.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/api/providers/config-builder/request-config-builder.ts` around lines 42 -
50, Update addHeaders to merge HTTP header names case-insensitively, so
differently-cased keys are treated as the same header and later values override
earlier ones. Preserve the existing headers and options behavior while ensuring
the resulting headers do not contain duplicate names differing only by casing.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/api/providers/config-builder/request-config-builder.ts`:
- Around line 63-73: Update RequestConfigBuilder.addMergedSignal and build so
the internal cleanup handle is not stored in or returned as part of the SDK
options object. Expose cleanup separately through the builder’s public result or
accessor, while preserving the merged signal in the built options and existing
behavior when no merged signal was added.

---

Nitpick comments:
In `@src/api/providers/config-builder/README.md`:
- Around line 196-221: Update the “How mergeAbortSignals Works” section to
accurately document the actual implementation in mergeAbortSignals and its use
of native AbortSignal.any(). Remove the hand-written AbortController example and
state that any already-aborted input, including secondarySignal, causes the
returned signal to be aborted immediately.
- Around line 479-495: Update the README API reference tables for the
configuration builder to document the missing addMergedSignal instance method
and mergeAbortSignalAndTimeout static method, including their parameters, return
types, and behavior for combining provider/external abort signals with an
optional timeout. Keep the descriptions aligned with the actual method
signatures and implementation.

In `@src/api/providers/config-builder/request-config-builder.ts`:
- Around line 42-50: Update addHeaders to merge HTTP header names
case-insensitively, so differently-cased keys are treated as the same header and
later values override earlier ones. Preserve the existing headers and options
behavior while ensuring the resulting headers do not contain duplicate names
differing only by casing.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b693b2e0-7220-4c8d-8f69-b87c93c8adb4

📥 Commits

Reviewing files that changed from the base of the PR and between 2634d5c and cf41486.

📒 Files selected for processing (6)
  • src/api/providers/__tests__/request-config-builder.spec.ts
  • src/api/providers/config-builder/README.md
  • src/api/providers/config-builder/request-config-builder.ts
  • src/api/providers/index.ts
  • src/api/providers/utils/__tests__/abort-signal.spec.ts
  • src/api/providers/utils/abort-signal.ts

@easonLiangWorldedtech
easonLiangWorldedtech force-pushed the feat/abort-signal-core/config-builder-base branch from 7e9d8d4 to c0a7e12 Compare July 24, 2026 18:43
@github-actions github-actions Bot added the awaiting-review PR changes are ready and waiting for maintainer re-review label Jul 24, 2026
@github-actions github-actions Bot added awaiting-author PR is waiting for the author to address requested changes and removed awaiting-review PR changes are ready and waiting for maintainer re-review labels Jul 26, 2026
@easonLiangWorldedtech
easonLiangWorldedtech force-pushed the feat/abort-signal-core/config-builder-base branch from c0a7e12 to 7335967 Compare July 27, 2026 13:37

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/api/providers/__tests__/request-config-builder.spec.ts (1)

348-365: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Fake timers aren't restored on assertion failure.

vi.useRealTimers() (Line 364) only runs if every prior assertion passes. If e.g. the assertion on Line 358 or 362 throws, fake timers leak into subsequent tests in the file.

♻️ Guarantee timer cleanup
-		test("should merge internal controller signal with timeout", async () => {
-			vi.useFakeTimers()
+		test("should merge internal controller signal with timeout", async () => {
+			vi.useFakeTimers()
+			try {
 				const internalController = new AbortController()
 				const builder = new RequestConfigBuilder()
 
 				builder.addMergedSignal(internalController, undefined, 100)
 
 				const config = builder.build() as { signal?: AbortSignal; _cleanup?: () => void }
 				expect(config.signal).not.toBe(internalController.signal)
 				expect(config).not.toHaveProperty("_cleanup")
 				expect(config.signal?.aborted).toBe(false)
 
 				await vi.advanceTimersByTimeAsync(100)
 
 				expect(config.signal?.aborted).toBe(true)
 				builder.getCleanup()()
-			vi.useRealTimers()
-		})
+			} finally {
+				vi.useRealTimers()
+			}
+		})
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/api/providers/__tests__/request-config-builder.spec.ts` around lines 348
- 365, Ensure the “should merge internal controller signal with timeout” test
always restores real timers and performs signal cleanup, including when an
assertion or timer advancement fails. Wrap the test body using the existing
setup/cleanup pattern or a try/finally block, keeping vi.useFakeTimers() setup
and vi.useRealTimers() restoration paired.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/api/providers/__tests__/request-config-builder.spec.ts`:
- Around line 348-365: Ensure the “should merge internal controller signal with
timeout” test always restores real timers and performs signal cleanup, including
when an assertion or timer advancement fails. Wrap the test body using the
existing setup/cleanup pattern or a try/finally block, keeping
vi.useFakeTimers() setup and vi.useRealTimers() restoration paired.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: a6c91bd5-e42c-4c4a-844e-e6532ee56f96

📥 Commits

Reviewing files that changed from the base of the PR and between c0a7e12 and 7335967.

📒 Files selected for processing (6)
  • src/api/providers/__tests__/request-config-builder.spec.ts
  • src/api/providers/config-builder/README.md
  • src/api/providers/config-builder/request-config-builder.ts
  • src/api/providers/index.ts
  • src/api/providers/utils/__tests__/abort-signal.spec.ts
  • src/api/providers/utils/abort-signal.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/api/providers/index.ts
  • src/api/providers/utils/tests/abort-signal.spec.ts
  • src/api/providers/utils/abort-signal.ts
  • src/api/providers/config-builder/README.md

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/api/providers/config-builder/request-config-builder.ts`:
- Around line 23-24: Update the constructor of the request config builder to
remove entries whose default option values are undefined when initializing
this.options. Preserve defined defaults and ensure build() treats entirely
undefined defaults as absent, returning undefined rather than an object
containing undefined-valued keys.
- Around line 14-18: Update RequestConfigOptions and the generic constraints
used by RequestConfigBuilder and RequestConfigBuilder.fromMetadata so the public
constraint requires only optional headers and signal fields, removing the
mandatory Record<string, unknown> index signature. Preserve arbitrary-key
support through the default generic type rather than the shared constraint.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: fde9c2f2-617e-422a-acb8-3cabcc1e3522

📥 Commits

Reviewing files that changed from the base of the PR and between 7335967 and b616910.

📒 Files selected for processing (2)
  • src/api/providers/__tests__/request-config-builder.spec.ts
  • src/api/providers/config-builder/request-config-builder.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/api/providers/tests/request-config-builder.spec.ts

@github-actions github-actions Bot added awaiting-review PR changes are ready and waiting for maintainer re-review and removed awaiting-author PR is waiting for the author to address requested changes labels Jul 27, 2026
@github-actions github-actions Bot added awaiting-author PR is waiting for the author to address requested changes and removed awaiting-review PR changes are ready and waiting for maintainer re-review labels Jul 30, 2026
…nfiguration

Body: Implement generic request configuration builder with chainable methods (addAbortSignal, addHeaders, setOption), static factory methods (fromMetadata, mergeAbortSignals), and 40 unit tests.
…ls early-abort

- Fix README TOC: change #how-mergesignals-works to
  #how-mergeabortsignals-works to match the actual heading anchor
- Simplify mergeAbortSignals: return primarySignal directly when it's
  already aborted instead of creating a new AbortController
…onfigBuilder (Zoo-Code-Org#615)

- Add default empty object parameter to addHeaders() so calling with
  undefined no longer throws TypeError from Object.keys(undefined)
- Reorder mergeAbortSignals to check primarySignal.aborted before
  allocating AbortController, preventing unnecessary controller creation
easonLiangWorldedtech pushed a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Sep 16, 2026
- createMessage: bridge metadata.abortSignal to a per-request
  AbortController (Bedrock pattern: pre-aborted guard, once-listener,
  detached on completion so a task-scoped signal does not accumulate
  listeners); model resolution runs inside the shared
  resolveModelWithAbort cancellation scope (pre-aborted fast-fail,
  mid-resolution race)
- aborted/timeout requests normalize to the provider AbortError on all
  three wire formats (anthropic /v1/messages, responses /v1/responses,
  openai chat completions), both pre-stream and mid-stream; non-abort
  failures keep the wrapped "Opencode Go completion error:" identity
- the OpenAI branch runs message conversion and request construction
  inside the same cleanup scope as the Anthropic and Responses branches,
  so a conversion failure (e.g. an unstringifiable tool input) still
  detaches the bridged abort listener (CodeRabbit fix on this PR)
- completePrompt: forwards abortSignal/timeoutMs to all three SDK
  paths (timeoutMs <= 0 omits the SDK timeout option, since the SDK
  treats timeout: 0 as an immediate abort); aborted completions and
  APIConnectionTimeoutError/APITimeoutError normalize to the provider
  AbortError (series standard)

The two inner pre-stream guard mutants (the abort-normalization
condition and its provider-name literal) are documented as provably
equivalent with mutator-specific Stryker directives: createMessage's
outer catch applies the identical isRequestAborted check to the same
controller signal and re-standardizes, so the inner layer's only
unique behavior is the non-abort completion-error wrap (stays
kill-tested).

The cleanup-scope re-indentation made the gate instrument pre-existing
request-construction lines for the first time; their previously
unobservable mutants are kill-tested: R1 tool-result merge shape for
preserveReasoning models and the plain shape for non-preserveReasoning
models, the includeMaxTokens on/off branches with a ceiling-bounded
model, and the parallel_tool_calls default/explicit-false.

Unit 2/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util unit.
Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.
myk1yt pushed a commit to myk1yt/Zoo-Code that referenced this pull request Oct 3, 2026
…rg#1651)

* feat(api): add abort-signal cancellation-scope helpers to the shared utils

Extend src/api/providers/utils/abort-signal.ts with the abort-signal
series helpers used by the gateway providers:

- isRequestAborted(error, signal): wider abort detection - an aborted
  signal, a DOM AbortError, the OpenAI/Anthropic SDK APIUserAbortError
  (name check), or the exact SDK abort message "Request was aborted." -
  trusting name/message only on real Error instances so a plain object
  that merely looks like an abort propagates unchanged
- createAbortError(providerName): fresh error satisfying the Task.ts
  abort contract (name "AbortError", message ending in "aborted")
- rejectOnAbort(pending, signal, providerName): settle a signal-less
  async phase (model discovery) on the provider AbortError when the
  signal fires first; the abort listener detaches when pending settles
- resolveModelWithAbort(fetchModel, signal, providerName): run model
  resolution inside a cancellation scope - entry fast-fail for a
  pre-aborted signal, the rejectOnAbort race while the lookup is
  pending, and normalization of abort-flavored lookup failures; any
  other resolution failure propagates unchanged

Includes direct unit tests for the resolveModelWithAbort cancellation
scope (pre-aborted fast-fail, no-signal pass-through, mid-resolution
race, abort normalization, non-abort propagation), the
isRequestAborted instanceof tightening tests, and the settle-guard
test utility.

Unit 1/3 of the Zoo-Code-Org#1295 split (content source: 62f596c).
Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

* fix: restore throwIfAborted export dropped by the util rewrite (+ tests)

* fix(abort-r1): handle a rejecting pending promise in rejectOnAbort's pre-aborted branch

* test(abort-r1): remove the process listener on every exit path

* chore: trigger CodeRabbit re-review (findings already addressed)

---------

Co-authored-by: Eason Liang <easonliang28@gmail.com>
Co-authored-by: easonLiangWorldedtech <eason.liang@worldedtech.com>
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
- createMessage: bridge metadata.abortSignal to a per-request
  AbortController (Bedrock pattern: pre-aborted guard, once-listener,
  detached on completion so a task-scoped signal does not accumulate
  listeners); model resolution runs inside the shared
  resolveModelWithAbort cancellation scope (pre-aborted fast-fail,
  mid-resolution race)
- aborted/timeout requests normalize to the provider AbortError on all
  three wire formats (anthropic /v1/messages, responses /v1/responses,
  openai chat completions), both pre-stream and mid-stream; non-abort
  failures keep the wrapped "Opencode Go completion error:" identity
- the OpenAI branch runs message conversion and request construction
  inside the same cleanup scope as the Anthropic and Responses branches,
  so a conversion failure (e.g. an unstringifiable tool input) still
  detaches the bridged abort listener (CodeRabbit fix on this PR)
- completePrompt: forwards abortSignal/timeoutMs to all three SDK
  paths (timeoutMs <= 0 omits the SDK timeout option, since the SDK
  treats timeout: 0 as an immediate abort); aborted completions and
  APIConnectionTimeoutError/APITimeoutError normalize to the provider
  AbortError (series standard)

The two inner pre-stream guard mutants (the abort-normalization
condition and its provider-name literal) are documented as provably
equivalent with mutator-specific Stryker directives: createMessage's
outer catch applies the identical isRequestAborted check to the same
controller signal and re-standardizes, so the inner layer's only
unique behavior is the non-abort completion-error wrap (stays
kill-tested).

The cleanup-scope re-indentation made the gate instrument pre-existing
request-construction lines for the first time; their previously
unobservable mutants are kill-tested: R1 tool-result merge shape for
preserveReasoning models and the plain shape for non-preserveReasoning
models, the includeMaxTokens on/off branches with a ceiling-bounded
model, and the parallel_tool_calls default/explicit-false.

Unit 2/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util unit.
Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on 41ef0e0): the Chat Completions stream loop now
breaks on the request signal at the top of each iteration and re-checks that signal after
the loop, so an SDK that swallows the body-read abort and closes the iterator normally
cannot report a cancelled turn as completed. The new test parks the iterator after the
first chunk, hands back a getter-counting chunk once the caller cancels, and asserts both
the standardized AbortError and zero post-cancel chunk reads; flipping either guard to a
false condition fails exactly that test (1 failed | 195 passed). The Responses pre-stream
abort arm had no live-signal delivery, so one is added: with no caller signal nothing
aborts, only the error-name arm can normalize, and the ConditionalExpression mutant dies
with it (same control). The provider-name literals at the two stream catches and at the
three completePrompt races were re-measured: each survives the full 196-test suite, which
matches the equivalence argument above. The detach tests now require exactly two abort
registrations on the caller's signal, name the bridge's by position, require it to differ
from the model-resolution race's callback, and assert both removals by reference in that
order. The SDK abort and timeout deliveries now reject from inside the SDK mock with no
caller signal (the automocked openai module's error classes are not Error instances, so
the name/message arm is exercised with the real class taken from the actual module), a
caller cancel landing inside the SDK call is classified across all three formats, and the
parked-lookup gate is the typed getModels fetcher rather than a spy on the private
resolveModel.

Verification on this tree: src tsc --noEmit exit 0 apart from the two known donor-store
integrations/misc/export-markdown.ts rows; vitest 196 passed (196) in declaration order and
in shuffled order; eslint . --ext=ts --max-warnings=0 without --prune-suppressions exit 0
with src/eslint-suppressions.json byte-identical (a prune run found zero decreases for this
unit); prettier 3.9.10 --check clean on the staged blobs extracted with core.autocrlf=false.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
…ateway

Each provider's createMessage bridges metadata.abortSignal to a
per-request AbortController (Bedrock pattern: pre-aborted guard,
{ once: true } listener, detached on completion so a task-scoped
signal does not accumulate listeners) and runs model resolution inside
the shared resolveModelWithAbort cancellation scope; aborted requests
(pre-aborted, mid-resolution, mid-stream) normalize to the provider
AbortError while non-abort failures propagate or wrap unchanged.
completePrompt forwards abortSignal/timeoutMs to the OpenAI SDK
(timeoutMs <= 0 omits the SDK timeout option); aborted completions and
APIConnectionTimeoutError normalize to the provider AbortError (series
standard).

Zoo Gateway places the entry fast-fail before ensureAuthenticated() so
a pre-aborted task surfaces the AbortError instead of an auth failure
(pinned by an unauthenticated pre-abort test).

Unit 3/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util and opencode-go units. Three sibling OpenAI-SDK gateway
providers with an identical abort-wiring shape are kept as one unit to
avoid tripling the review surface for mechanically identical changes
(a+d soft-cap rationale per the split budget; the mutation gate is
measured on the unit delta and is green).

Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on b1bd578, disposition recorded on each thread): each provider now races the SDK promise it awaits against the bridged signal through `settleOnAbort` — unbound's stream create and its completion, vercel-ai-gateway's completion, zoo-gateway's completion — because the OpenAI SDK sleeps out a Retry-After / retry delay without observing the signal, and the post-await `bridgedSignal?.aborted` guards that used to trail those awaits are gone, since `raceAbort` rejects synchronously at `abort()` and nothing after the await can read the flag first. Each streaming loop breaks on the caller signal at the top of an iteration, re-checks it before emitting a just-received chunk, and checks it once more before the generator returns, so a cancel the SDK swallows — the iterator ends normally without a throw — can neither emit the rest of a chunk nor report a partial turn as completed. The caller's signal is bridged rather than handed to the SDK directly and the bridge is disposed in `finally`; the detach tests name the bridge's listener by registration position, require it to differ from the model-lookup race's callback, and assert both removals by reference. Absence proofs drain the provider's own continuation instead of sleeping.

The two Opencode Go files are Zoo-Code-Org#1652's blobs, byte for byte: provider `8efbbc5315c5aededc008f119c06e17a5acefe75`, spec `04c0528ccda0a8f655a16e6900ef5c627beb23ad`; `git diff eb162c4 -- <those two paths>` is empty with `core.autocrlf=false` and the blob ids are re-verified against this commit. Once Zoo-Code-Org#1652 lands on main this unit rebases onto it and both files drop out of this diff.

Verification on this tree: vitest over the opencode-go, unbound, vercel-ai-gateway and zoo-gateway specs from `src` — 393 passed (393) in declaration order and 393 passed with `--sequence.shuffle`; `tsc --noEmit -p tsconfig.json` leaves only the two known donor-store `integrations/misc/export-markdown.ts` rows; `eslint . --ext=ts --max-warnings=0` without `--prune-suppressions` exits 0 with `src/eslint-suppressions.json` byte-identical (a prune run over the eight touched paths reported zero count decreases); prettier 3.9.10 `--check` clean on the staged blobs extracted with `core.autocrlf=false`. Negative controls per new guard: flipping each added condition or deleting each added arm fails the specific guard test that names it — 1 failed | 195 passed for either Opencode Go chat-stream arm, 1 failed for the Responses pre-stream condition, 2 failed for the Anthropic stream condition, and the same shape for the gateway guards.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
- createMessage: bridge metadata.abortSignal to a per-request
  AbortController (Bedrock pattern: pre-aborted guard, once-listener,
  detached on completion so a task-scoped signal does not accumulate
  listeners); model resolution runs inside the shared
  resolveModelWithAbort cancellation scope (pre-aborted fast-fail,
  mid-resolution race)
- aborted/timeout requests normalize to the provider AbortError on all
  three wire formats (anthropic /v1/messages, responses /v1/responses,
  openai chat completions), both pre-stream and mid-stream; non-abort
  failures keep the wrapped "Opencode Go completion error:" identity
- the OpenAI branch runs message conversion and request construction
  inside the same cleanup scope as the Anthropic and Responses branches,
  so a conversion failure (e.g. an unstringifiable tool input) still
  detaches the bridged abort listener (CodeRabbit fix on this PR)
- completePrompt: forwards abortSignal/timeoutMs to all three SDK
  paths (timeoutMs <= 0 omits the SDK timeout option, since the SDK
  treats timeout: 0 as an immediate abort); aborted completions and
  APIConnectionTimeoutError/APITimeoutError normalize to the provider
  AbortError (series standard)

The inner pre-stream provider-name literal is provably equivalent
and documented as such in the PR body; no Stryker disable directive is
added anywhere in the tree. createMessage's outer catch applies the
identical isRequestAborted check to the same controller signal and
re-standardizes the error, so the inner layer's only unique behavior is
the non-abort completion-error wrap (stays kill-tested), and the
abort-normalization condition beside that literal is killed by a
live-signal delivery added in the second review round.

The cleanup-scope re-indentation made the gate instrument pre-existing
request-construction lines for the first time; their previously
unobservable mutants are kill-tested: R1 tool-result merge shape for
preserveReasoning models and the plain shape for non-preserveReasoning
models, the includeMaxTokens on/off branches with a ceiling-bounded
model, and the parallel_tool_calls default/explicit-false.

Unit 2/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util unit.
Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on 41ef0e0): the Chat Completions stream loop now
breaks on the request signal at the top of each iteration and re-checks that signal after
the loop, so an SDK that swallows the body-read abort and closes the iterator normally
cannot report a cancelled turn as completed. The new test parks the iterator after the
first chunk, hands back a getter-counting chunk once the caller cancels, and asserts both
the standardized AbortError and zero post-cancel chunk reads; flipping either guard to a
false condition fails exactly that test (1 failed | 195 passed). The Responses pre-stream
abort arm had no live-signal delivery, so one is added: with no caller signal nothing
aborts, only the error-name arm can normalize, and the ConditionalExpression mutant dies
with it (same control). The provider-name literals at the two stream catches and at the
three completePrompt races were re-measured: each survives the full 196-test suite, which
matches the equivalence argument above. The detach tests now require exactly two abort
registrations on the caller's signal, name the bridge's by position, require it to differ
from the model-resolution race's callback, and assert both removals by reference in that
order. The SDK abort and timeout deliveries now reject from inside the SDK mock with no
caller signal (the automocked openai module's error classes are not Error instances, so
the name/message arm is exercised with the real class taken from the actual module), a
caller cancel landing inside the SDK call is classified across all three formats, and the
parked-lookup gate is the typed getModels fetcher rather than a spy on the private
resolveModel.

Review round 2 (CodeRabbit pre-merge checks): completePrompt gained a parameterized timeout-option
test per wire format (Anthropic messages, Responses, chat completions) that proves each call site
applies the shared hasUsableTimeout/toSdkTimeoutMs contract rather than only testing the helper:
NaN, Infinity and -5 leave no timeout key, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards
MAX_TIMEOUT_MS, and every row also asserts the caller's signal reached the SDK options, so dropping
the budget can never drop the cancel. Controls: deleting the forward arm fails two rows per format,
forcing it to always forward fails the three disabled-budget rows, and replacing
toSdkTimeoutMs(timeoutMs) with the raw value fails exactly the two forwarding rows. The five
provider-name literals on the abort paths were re-measured at this head: all five survive the full
211-test suite, which is the measured half of the equivalence argument in the PR body.

Verification on this tree: src tsc --noEmit exit 0 apart from the two known donor-store
integrations/misc/export-markdown.ts rows; vitest 211 passed (211) in declaration order and
in shuffled order; eslint . --ext=ts --max-warnings=0 without --prune-suppressions exit 0
with src/eslint-suppressions.json byte-identical (a prune run found zero decreases for this
unit); prettier 3.9.10 --check clean on the staged blobs extracted with core.autocrlf=false.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
…ateway

Each provider's createMessage bridges metadata.abortSignal to a
per-request AbortController (Bedrock pattern: pre-aborted guard,
{ once: true } listener, detached on completion so a task-scoped
signal does not accumulate listeners) and runs model resolution inside
the shared resolveModelWithAbort cancellation scope; aborted requests
(pre-aborted, mid-resolution, mid-stream) normalize to the provider
AbortError while non-abort failures propagate or wrap unchanged.
completePrompt forwards abortSignal/timeoutMs to the OpenAI SDK
(timeoutMs <= 0 omits the SDK timeout option); aborted completions and
APIConnectionTimeoutError normalize to the provider AbortError (series
standard).

Zoo Gateway places the entry fast-fail before ensureAuthenticated() so
a pre-aborted task surfaces the AbortError instead of an auth failure
(pinned by an unauthenticated pre-abort test).

Unit 3/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util and opencode-go units. Three sibling OpenAI-SDK gateway
providers with an identical abort-wiring shape are kept as one unit to
avoid tripling the review surface for mechanically identical changes
(a+d soft-cap rationale per the split budget; the mutation gate is
measured on the unit delta and is green).

Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on b1bd578, disposition recorded on each thread): each provider now races the SDK promise it awaits against the bridged signal through `settleOnAbort` — unbound's stream create and its completion, vercel-ai-gateway's completion, zoo-gateway's completion — because the OpenAI SDK sleeps out a Retry-After / retry delay without observing the signal, and the post-await `bridgedSignal?.aborted` guards that used to trail those awaits are gone, since `raceAbort` rejects synchronously at `abort()` and nothing after the await can read the flag first. Each streaming loop breaks on the caller signal at the top of an iteration, re-checks it before emitting a just-received chunk, and checks it once more before the generator returns, so a cancel the SDK swallows — the iterator ends normally without a throw — can neither emit the rest of a chunk nor report a partial turn as completed. The caller's signal is bridged rather than handed to the SDK directly and the bridge is disposed in `finally`; the detach tests name the bridge's listener by registration position, require it to differ from the model-lookup race's callback, and assert both removals by reference. Absence proofs drain the provider's own continuation instead of sleeping.

The two Opencode Go files are Zoo-Code-Org#1652's blobs, byte for byte: provider `8efbbc5315c5aededc008f119c06e17a5acefe75`, spec `4654b728043f9c7ed2e30f46e8543a1a29bfe6cf`; `git diff e88d290 -- <those two paths>` is empty with `core.autocrlf=false` and the blob ids are re-verified against this commit. Once Zoo-Code-Org#1652 lands on main this unit rebases onto it and both files drop out of this diff.

Review round 2 (CodeRabbit pre-merge checks): each gateway completePrompt now pins the disabled-budget boundary at -5 — the SDK options carry no timeout key and the bridged per-request signal is still handed over (the zoo variant is one of the tests that also catches a dropped signal arm). The ported Opencode Go spec brings its own parameterized timeout-option test per wire format: NaN, Infinity and -5 omit the option, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards MAX_TIMEOUT_MS, and the caller signal is asserted on every row. Those rows kill the forward arms at opencode-go.ts:886/944/1027 in both directions (deleting the arm fails two rows per format, forcing it always-forward fails the three disabled-budget rows) and the toSdkTimeoutMs call sites; forcing the gateway arms to always forward fails the new -5 rows on all three providers.

Verification on this tree: vitest over the opencode-go, unbound, vercel-ai-gateway and zoo-gateway specs from `src` — 411 passed (411) in declaration order and 411 passed with `--sequence.shuffle`; `tsc --noEmit -p tsconfig.json` leaves only the two known donor-store `integrations/misc/export-markdown.ts` rows; `eslint . --ext=ts --max-warnings=0` without `--prune-suppressions` exits 0 with `src/eslint-suppressions.json` byte-identical (a prune run over the eight touched paths reported zero count decreases); prettier 3.9.10 `--check` clean on the staged blobs extracted with `core.autocrlf=false`. Negative controls per new guard: flipping each added condition or deleting each added arm fails the specific guard test that names it — 1 failed | 195 passed for either Opencode Go chat-stream arm, 1 failed for the Responses pre-stream condition, 2 failed for the Anthropic stream condition, and the same shape for the gateway guards.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
- createMessage: bridge metadata.abortSignal to a per-request
  AbortController (Bedrock pattern: pre-aborted guard, once-listener,
  detached on completion so a task-scoped signal does not accumulate
  listeners); model resolution runs inside the shared
  resolveModelWithAbort cancellation scope (pre-aborted fast-fail,
  mid-resolution race)
- aborted/timeout requests normalize to the provider AbortError on all
  three wire formats (anthropic /v1/messages, responses /v1/responses,
  openai chat completions), both pre-stream and mid-stream; non-abort
  failures keep the wrapped "Opencode Go completion error:" identity
- the OpenAI branch runs message conversion and request construction
  inside the same cleanup scope as the Anthropic and Responses branches,
  so a conversion failure (e.g. an unstringifiable tool input) still
  detaches the bridged abort listener (CodeRabbit fix on this PR)
- completePrompt: forwards abortSignal/timeoutMs to all three SDK
  paths (timeoutMs <= 0 omits the SDK timeout option, since the SDK
  treats timeout: 0 as an immediate abort); aborted completions and
  APIConnectionTimeoutError/APITimeoutError normalize to the provider
  AbortError (series standard)

The inner pre-stream provider-name literal is provably equivalent
and documented as such in the PR body; no Stryker disable directive is
added anywhere in the tree. createMessage's outer catch applies the
identical isRequestAborted check to the same controller signal and
re-standardizes the error, so the inner layer's only unique behavior is
the non-abort completion-error wrap (stays kill-tested), and the
abort-normalization condition beside that literal is killed by a
live-signal delivery added in the second review round.

The cleanup-scope re-indentation made the gate instrument pre-existing
request-construction lines for the first time; their previously
unobservable mutants are kill-tested: R1 tool-result merge shape for
preserveReasoning models and the plain shape for non-preserveReasoning
models, the includeMaxTokens on/off branches with a ceiling-bounded
model, and the parallel_tool_calls default/explicit-false.

Unit 2/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util unit.
Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on 41ef0e0): the Chat Completions stream loop now
breaks on the request signal at the top of each iteration and re-checks that signal after
the loop, so an SDK that swallows the body-read abort and closes the iterator normally
cannot report a cancelled turn as completed. The new test parks the iterator after the
first chunk, hands back a getter-counting chunk once the caller cancels, and asserts both
the standardized AbortError and zero post-cancel chunk reads; flipping either guard to a
false condition fails exactly that test (1 failed | 195 passed). The Responses pre-stream
abort arm had no live-signal delivery, so one is added: with no caller signal nothing
aborts, only the error-name arm can normalize, and the ConditionalExpression mutant dies
with it (same control). The provider-name literals at the two stream catches and at the
three completePrompt races were re-measured: each survives the full 196-test suite, which
matches the equivalence argument above. The detach tests now require exactly two abort
registrations on the caller's signal, name the bridge's by position, require it to differ
from the model-resolution race's callback, and assert both removals by reference in that
order. The SDK abort and timeout deliveries now reject from inside the SDK mock with no
caller signal (the automocked openai module's error classes are not Error instances, so
the name/message arm is exercised with the real class taken from the actual module), a
caller cancel landing inside the SDK call is classified across all three formats, and the
parked-lookup gate is the typed getModels fetcher rather than a spy on the private
resolveModel.

Review round 2 (CodeRabbit pre-merge checks): completePrompt gained a parameterized timeout-option
test per wire format (Anthropic messages, Responses, chat completions) that proves each call site
applies the shared hasUsableTimeout/toSdkTimeoutMs contract rather than only testing the helper:
NaN, Infinity and -5 leave no timeout key, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards
MAX_TIMEOUT_MS, and every row also asserts the caller's signal reached the SDK options, so dropping
the budget can never drop the cancel. Controls: deleting the forward arm fails two rows per format,
forcing it to always forward fails the three disabled-budget rows, and replacing
toSdkTimeoutMs(timeoutMs) with the raw value fails exactly the two forwarding rows. The five
provider-name literals on the abort paths were re-measured at this head: all five survive the full
211-test suite, which is the measured half of the equivalence argument in the PR body.

Verification on this tree: src tsc --noEmit exit 0 apart from the two known donor-store
integrations/misc/export-markdown.ts rows; vitest 211 passed (211) in declaration order and
in shuffled order; eslint . --ext=ts --max-warnings=0 without --prune-suppressions exit 0
with src/eslint-suppressions.json byte-identical (a prune run found zero decreases for this
unit); prettier 3.9.10 --check clean on the staged blobs extracted with core.autocrlf=false.

Review round 3 (CodeRabbit pre-merge checks, six Minor rows): the Chat Completions streaming loop now re-checks the request signal in front of every buffered item of a frame — the text item after a reasoning item, each tool-call partial inside the per-item loop, and the usage item — because a consumer that takes the first item, cancels and pulls the next one resumes this generator inside the same iteration, where the top-of-loop guard has already run. The three stream-open awaits (Anthropic /v1/messages, Responses /v1/responses and chat completions) now go through settleOnAbort with the signal still handed to the SDK, so a 429 with Retry-After plus a caller cancel no longer holds the pending first next() and the bridge cleanup until the sleep ends. Regression evidence: one parameterized test for the three stream-open races plus three manual-iteration tests that abort between two items of one frame (the buffered-text variant also asserts the bridge listener is detached by reference). Negative controls: removing each open wrapper fails exactly that format's row (1 failed | 216 passed each), disabling each buffered-item guard fails exactly that item's test, and reverting the OpenAI-path fixture key from opencodeGoModelId to the ignored apiModelId fails the five assertions that now pin model "glm-5.1" instead of expect.any(String). The parked-lookup test releases its gate in a finally so an assertion throw cannot strand the promise the provider awaits; measured with a probe: a release placed after the throwing assertion leaves the promise unresolved, the same release in a finally settles it.

Verification on this round: vitest 217 passed (217) in declaration order and with --sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical (a prune run over the two unit files reported zero count decreases); prettier 3.9.10 --check: clean.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
…ateway

Each provider's createMessage bridges metadata.abortSignal to a
per-request AbortController (Bedrock pattern: pre-aborted guard,
{ once: true } listener, detached on completion so a task-scoped
signal does not accumulate listeners) and runs model resolution inside
the shared resolveModelWithAbort cancellation scope; aborted requests
(pre-aborted, mid-resolution, mid-stream) normalize to the provider
AbortError while non-abort failures propagate or wrap unchanged.
completePrompt forwards abortSignal/timeoutMs to the OpenAI SDK
(timeoutMs <= 0 omits the SDK timeout option); aborted completions and
APIConnectionTimeoutError normalize to the provider AbortError (series
standard).

Zoo Gateway places the entry fast-fail before ensureAuthenticated() so
a pre-aborted task surfaces the AbortError instead of an auth failure
(pinned by an unauthenticated pre-abort test).

Unit 3/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util and opencode-go units. Three sibling OpenAI-SDK gateway
providers with an identical abort-wiring shape are kept as one unit to
avoid tripling the review surface for mechanically identical changes
(a+d soft-cap rationale per the split budget; the mutation gate is
measured on the unit delta and is green).

Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on b1bd578, disposition recorded on each thread): each provider now races the SDK promise it awaits against the bridged signal through `settleOnAbort` — unbound's stream create and its completion, vercel-ai-gateway's completion, zoo-gateway's completion — because the OpenAI SDK sleeps out a Retry-After / retry delay without observing the signal, and the post-await `bridgedSignal?.aborted` guards that used to trail those awaits are gone, since `raceAbort` rejects synchronously at `abort()` and nothing after the await can read the flag first. Each streaming loop breaks on the caller signal at the top of an iteration, re-checks it before emitting a just-received chunk, and checks it once more before the generator returns, so a cancel the SDK swallows — the iterator ends normally without a throw — can neither emit the rest of a chunk nor report a partial turn as completed. The caller's signal is bridged rather than handed to the SDK directly and the bridge is disposed in `finally`; the detach tests name the bridge's listener by registration position, require it to differ from the model-lookup race's callback, and assert both removals by reference. Absence proofs drain the provider's own continuation instead of sleeping.

The two Opencode Go files are Zoo-Code-Org#1652's blobs, byte for byte: provider `23348a501e9f31d0c72bffa6eefb6030bb6149a3`, spec `5dbe3382d1f1d6af8d22e7637a088c546988ef18`; `git diff df29307 -- <those two paths>` is empty with `core.autocrlf=false` and the blob ids are re-verified against this commit. Once Zoo-Code-Org#1652 lands on main this unit rebases onto it and both files drop out of this diff.

Review round 2 (CodeRabbit pre-merge checks): each gateway completePrompt now pins the disabled-budget boundary at -5 — the SDK options carry no timeout key and the bridged per-request signal is still handed over (the zoo variant is one of the tests that also catches a dropped signal arm). The ported Opencode Go spec brings its own parameterized timeout-option test per wire format: NaN, Infinity and -5 omit the option, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards MAX_TIMEOUT_MS, and the caller signal is asserted on every row. Those rows kill the forward arms at opencode-go.ts:886/944/1027 in both directions (deleting the arm fails two rows per format, forcing it always-forward fails the three disabled-budget rows) and the toSdkTimeoutMs call sites; forcing the gateway arms to always forward fails the new -5 rows on all three providers.

Verification on this tree: vitest over the opencode-go, unbound, vercel-ai-gateway and zoo-gateway specs from `src` — 411 passed (411) in declaration order and 411 passed with `--sequence.shuffle`; `tsc --noEmit -p tsconfig.json` leaves only the two known donor-store `integrations/misc/export-markdown.ts` rows; `eslint . --ext=ts --max-warnings=0` without `--prune-suppressions` exits 0 with `src/eslint-suppressions.json` byte-identical (a prune run over the eight touched paths reported zero count decreases); prettier 3.9.10 `--check` clean on the staged blobs extracted with `core.autocrlf=false`. Negative controls per new guard: flipping each added condition or deleting each added arm fails the specific guard test that names it — 1 failed | 195 passed for either Opencode Go chat-stream arm, 1 failed for the Responses pre-stream condition, 2 failed for the Anthropic stream condition, and the same shape for the gateway guards.

Review round 3: the mutation-diff report at 313cf0e listed 20 blocking rows (21 survived mutants plus one uncovered arm) over 338 changed executable lines. Five of them are now killed by four tests added here: unbound.ts:349 and vercel-ai-gateway.ts:280 (detachExternalAbortSignal() -> ; in the completePrompt finally) by a detach test per provider that identifies the bridge listener by the { once: true } registration and asserts its removal by reference; zoo-gateway.ts:337 (classification gate -> false) by a streaming test that feeds a name-only AbortError with a live-but-not-aborted caller signal and asserts the contract identity, that the add-credits notification never ran, and that nothing was logged; zoo-gateway.ts:346 in both directions by a streaming test where the notification itself rejects while the caller signal is live (the log must name the surfacing failure and the original 402 must still reach the caller) plus the existing cancel-while-prompt-open test, which also puts that line under coverage. Each of those four mutants was applied alone and restored: 1 failed | 414 passed, killed by the named test in every case. The remaining sixteen rows are all StringLiteral -> "" on a provider-name label inside createAbortError/settleOnAbort/rejectOnAbort; each one sits inside a catch or race whose enclosing handler re-throws with its own unmutated literal, so the provider-visible error name and message are identical through the public API and no assertion can distinguish the mutant from the code (measured: full suite green with each mutant in place). No Stryker directive was added; the equivalence is argued in the PR discussion for a maintainer to weigh.

Verification on this tree: vitest 421 passed (421) across the four provider specs in declaration order and with --sequence.shuffle (the six new opencode-go tests arrive with the re-ported blobs); tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical; prettier 3.9.10 --check on the touched files: clean. The opencode-go blobs are re-ported from df29307 and remain byte-identical to that head (git diff --quiet against it for those two paths: exit 0), so after a maintainer merges Zoo-Code-Org#1652 these lines drop out of this diff on rebase.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
- createMessage: bridge metadata.abortSignal to a per-request
  AbortController (Bedrock pattern: pre-aborted guard, once-listener,
  detached on completion so a task-scoped signal does not accumulate
  listeners); model resolution runs inside the shared
  resolveModelWithAbort cancellation scope (pre-aborted fast-fail,
  mid-resolution race)
- aborted/timeout requests normalize to the provider AbortError on all
  three wire formats (anthropic /v1/messages, responses /v1/responses,
  openai chat completions), both pre-stream and mid-stream; non-abort
  failures keep the wrapped "Opencode Go completion error:" identity
- the OpenAI branch runs message conversion and request construction
  inside the same cleanup scope as the Anthropic and Responses branches,
  so a conversion failure (e.g. an unstringifiable tool input) still
  detaches the bridged abort listener (CodeRabbit fix on this PR)
- completePrompt: forwards abortSignal/timeoutMs to all three SDK
  paths (timeoutMs <= 0 omits the SDK timeout option, since the SDK
  treats timeout: 0 as an immediate abort); aborted completions and
  APIConnectionTimeoutError/APITimeoutError normalize to the provider
  AbortError (series standard)

The inner pre-stream provider-name literal is provably equivalent
and documented as such in the PR body; no Stryker disable directive is
added anywhere in the tree. createMessage's outer catch applies the
identical isRequestAborted check to the same controller signal and
re-standardizes the error, so the inner layer's only unique behavior is
the non-abort completion-error wrap (stays kill-tested), and the
abort-normalization condition beside that literal is killed by a
live-signal delivery added in the second review round.

The cleanup-scope re-indentation made the gate instrument pre-existing
request-construction lines for the first time; their previously
unobservable mutants are kill-tested: R1 tool-result merge shape for
preserveReasoning models and the plain shape for non-preserveReasoning
models, the includeMaxTokens on/off branches with a ceiling-bounded
model, and the parallel_tool_calls default/explicit-false.

Unit 2/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util unit.
Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on 41ef0e0): the Chat Completions stream loop now
breaks on the request signal at the top of each iteration and re-checks that signal after
the loop, so an SDK that swallows the body-read abort and closes the iterator normally
cannot report a cancelled turn as completed. The new test parks the iterator after the
first chunk, hands back a getter-counting chunk once the caller cancels, and asserts both
the standardized AbortError and zero post-cancel chunk reads; flipping either guard to a
false condition fails exactly that test (1 failed | 195 passed). The Responses pre-stream
abort arm had no live-signal delivery, so one is added: with no caller signal nothing
aborts, only the error-name arm can normalize, and the ConditionalExpression mutant dies
with it (same control). The provider-name literals at the two stream catches and at the
three completePrompt races were re-measured: each survives the full 196-test suite, which
matches the equivalence argument above. The detach tests now require exactly two abort
registrations on the caller's signal, name the bridge's by position, require it to differ
from the model-resolution race's callback, and assert both removals by reference in that
order. The SDK abort and timeout deliveries now reject from inside the SDK mock with no
caller signal (the automocked openai module's error classes are not Error instances, so
the name/message arm is exercised with the real class taken from the actual module), a
caller cancel landing inside the SDK call is classified across all three formats, and the
parked-lookup gate is the typed getModels fetcher rather than a spy on the private
resolveModel.

Review round 2 (CodeRabbit pre-merge checks): completePrompt gained a parameterized timeout-option
test per wire format (Anthropic messages, Responses, chat completions) that proves each call site
applies the shared hasUsableTimeout/toSdkTimeoutMs contract rather than only testing the helper:
NaN, Infinity and -5 leave no timeout key, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards
MAX_TIMEOUT_MS, and every row also asserts the caller's signal reached the SDK options, so dropping
the budget can never drop the cancel. Controls: deleting the forward arm fails two rows per format,
forcing it to always forward fails the three disabled-budget rows, and replacing
toSdkTimeoutMs(timeoutMs) with the raw value fails exactly the two forwarding rows. The five
provider-name literals on the abort paths were re-measured at this head: all five survive the full
211-test suite, which is the measured half of the equivalence argument in the PR body.

Verification on this tree: src tsc --noEmit exit 0 apart from the two known donor-store
integrations/misc/export-markdown.ts rows; vitest 211 passed (211) in declaration order and
in shuffled order; eslint . --ext=ts --max-warnings=0 without --prune-suppressions exit 0
with src/eslint-suppressions.json byte-identical (a prune run found zero decreases for this
unit); prettier 3.9.10 --check clean on the staged blobs extracted with core.autocrlf=false.

Review round 3 (CodeRabbit pre-merge checks, six Minor rows): the Chat Completions streaming loop now re-checks the request signal in front of every buffered item of a frame — the text item after a reasoning item, each tool-call partial inside the per-item loop, and the usage item — because a consumer that takes the first item, cancels and pulls the next one resumes this generator inside the same iteration, where the top-of-loop guard has already run. The three stream-open awaits (Anthropic /v1/messages, Responses /v1/responses and chat completions) now go through settleOnAbort with the signal still handed to the SDK, so a 429 with Retry-After plus a caller cancel no longer holds the pending first next() and the bridge cleanup until the sleep ends. Regression evidence: one parameterized test for the three stream-open races plus three manual-iteration tests that abort between two items of one frame (the buffered-text variant also asserts the bridge listener is detached by reference). Negative controls: removing each open wrapper fails exactly that format's row (1 failed | 216 passed each), disabling each buffered-item guard fails exactly that item's test, and reverting the OpenAI-path fixture key from opencodeGoModelId to the ignored apiModelId fails the five assertions that now pin model "glm-5.1" instead of expect.any(String). The parked-lookup test releases its gate in a finally so an assertion throw cannot strand the promise the provider awaits; measured with a probe: a release placed after the throwing assertion leaves the promise unresolved, the same release in a finally settles it.

Verification on this round: vitest 217 passed (217) in declaration order and with --sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical (a prune run over the two unit files reported zero count decreases); prettier 3.9.10 --check: clean.

Review round 4 (CodeRabbit pre-merge checks, one Major and nine Minor rows, handled in a single pass): the
Responses and Anthropic helpers no longer let a normally-ending SDK iterator read as a completed turn. The
Responses helper re-checks the bridged signal after processResponsesApiStream returns; the Anthropic helper
re-checks it at the top of each event dispatch, between the separator item and the block body of an indexed
content_block_start, and after the loop before the terminal cost chunk, so a cancel cannot emit the rest of
an event or bill a turn the caller already cancelled. Four tests drive the shape the pinned SDKs actually
produce - hand the consumer one item, cancel, then let the mock iterator report done instead of throwing -
and each one also runs the identical fixture with a live caller signal, which still delivers its text and
its terminal cost. Negative controls, each against the full suite: the Responses post-stream check (1 failed
| 223 passed), the Anthropic after-loop check (killed by the test that cancels after the last event was
delivered), the event-dispatch check (killed by the quiet-close test) and the separator checks (killed by the
two-yields-of-one-event test) each fail their own test and nothing else that matters.
The Responses pre-stream abort test no longer certifies itself through the provider's own catch: the mock
captures the signal the SDK actually received and then throws a plain failure, so the only evidence left is
that the captured signal is an AbortSignal that had already flipped; handing the SDK an unrelated signal
instead of the bridge fails seven tests, including that one. The timeout matrix now pins signal identity
rather than signal type - with no usable budget the SDK must hold the caller's own signal, with a usable one
it must hold the merged deadline - and a new parameterized test parks each format's request under a 5000 ms
budget, cancels the caller long before the deadline and requires the merged signal to flip and the completion
to reject with the contract AbortError; replacing the merged deadline with the caller's own signal on the
chat-completions completion fails 26 tests, including those rows. Three tests that polled for readiness
before observing the rejection now attach the handler when the promise is created, so a model lookup or
stream open that rejects during the poll cannot go unobserved.
Verification on this round: vitest 224 passed (224) in declaration order and with --sequence.shuffle; tsc
--noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without
--prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical (a prune run over the two unit
files found zero decreases, so the rewritten file was reverted); prettier 3.9.10 --check: clean.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
…ateway

Each provider's createMessage bridges metadata.abortSignal to a
per-request AbortController (Bedrock pattern: pre-aborted guard,
{ once: true } listener, detached on completion so a task-scoped
signal does not accumulate listeners) and runs model resolution inside
the shared resolveModelWithAbort cancellation scope; aborted requests
(pre-aborted, mid-resolution, mid-stream) normalize to the provider
AbortError while non-abort failures propagate or wrap unchanged.
completePrompt forwards abortSignal/timeoutMs to the OpenAI SDK
(timeoutMs <= 0 omits the SDK timeout option); aborted completions and
APIConnectionTimeoutError normalize to the provider AbortError (series
standard).

Zoo Gateway places the entry fast-fail before ensureAuthenticated() so
a pre-aborted task surfaces the AbortError instead of an auth failure
(pinned by an unauthenticated pre-abort test).

Unit 3/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util and opencode-go units. Three sibling OpenAI-SDK gateway
providers with an identical abort-wiring shape are kept as one unit to
avoid tripling the review surface for mechanically identical changes
(a+d soft-cap rationale per the split budget; the mutation gate is
measured on the unit delta and is green).

Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on b1bd578, disposition recorded on each thread): each provider now races the SDK promise it awaits against the bridged signal through `settleOnAbort` — unbound's stream create and its completion, vercel-ai-gateway's completion, zoo-gateway's completion — because the OpenAI SDK sleeps out a Retry-After / retry delay without observing the signal, and the post-await `bridgedSignal?.aborted` guards that used to trail those awaits are gone, since `raceAbort` rejects synchronously at `abort()` and nothing after the await can read the flag first. Each streaming loop breaks on the caller signal at the top of an iteration, re-checks it before emitting a just-received chunk, and checks it once more before the generator returns, so a cancel the SDK swallows — the iterator ends normally without a throw — can neither emit the rest of a chunk nor report a partial turn as completed. The caller's signal is bridged rather than handed to the SDK directly and the bridge is disposed in `finally`; the detach tests name the bridge's listener by registration position, require it to differ from the model-lookup race's callback, and assert both removals by reference. Absence proofs drain the provider's own continuation instead of sleeping.

The two Opencode Go files are Zoo-Code-Org#1652's blobs, byte for byte: provider `23348a501e9f31d0c72bffa6eefb6030bb6149a3`, spec `5dbe3382d1f1d6af8d22e7637a088c546988ef18`; `git diff df29307 -- <those two paths>` is empty with `core.autocrlf=false` and the blob ids are re-verified against this commit. Once Zoo-Code-Org#1652 lands on main this unit rebases onto it and both files drop out of this diff.

Review round 2 (CodeRabbit pre-merge checks): each gateway completePrompt now pins the disabled-budget boundary at -5 — the SDK options carry no timeout key and the bridged per-request signal is still handed over (the zoo variant is one of the tests that also catches a dropped signal arm). The ported Opencode Go spec brings its own parameterized timeout-option test per wire format: NaN, Infinity and -5 omit the option, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards MAX_TIMEOUT_MS, and the caller signal is asserted on every row. Those rows kill the forward arms at opencode-go.ts:886/944/1027 in both directions (deleting the arm fails two rows per format, forcing it always-forward fails the three disabled-budget rows) and the toSdkTimeoutMs call sites; forcing the gateway arms to always forward fails the new -5 rows on all three providers.

Verification on this tree: vitest over the opencode-go, unbound, vercel-ai-gateway and zoo-gateway specs from `src` — 411 passed (411) in declaration order and 411 passed with `--sequence.shuffle`; `tsc --noEmit -p tsconfig.json` leaves only the two known donor-store `integrations/misc/export-markdown.ts` rows; `eslint . --ext=ts --max-warnings=0` without `--prune-suppressions` exits 0 with `src/eslint-suppressions.json` byte-identical (a prune run over the eight touched paths reported zero count decreases); prettier 3.9.10 `--check` clean on the staged blobs extracted with `core.autocrlf=false`. Negative controls per new guard: flipping each added condition or deleting each added arm fails the specific guard test that names it — 1 failed | 195 passed for either Opencode Go chat-stream arm, 1 failed for the Responses pre-stream condition, 2 failed for the Anthropic stream condition, and the same shape for the gateway guards.

Review round 3: the mutation-diff report at 313cf0e listed 20 blocking rows (21 survived mutants plus one uncovered arm) over 338 changed executable lines. Five of them are now killed by four tests added here: unbound.ts:349 and vercel-ai-gateway.ts:280 (detachExternalAbortSignal() -> ; in the completePrompt finally) by a detach test per provider that identifies the bridge listener by the { once: true } registration and asserts its removal by reference; zoo-gateway.ts:337 (classification gate -> false) by a streaming test that feeds a name-only AbortError with a live-but-not-aborted caller signal and asserts the contract identity, that the add-credits notification never ran, and that nothing was logged; zoo-gateway.ts:346 in both directions by a streaming test where the notification itself rejects while the caller signal is live (the log must name the surfacing failure and the original 402 must still reach the caller) plus the existing cancel-while-prompt-open test, which also puts that line under coverage. Each of those four mutants was applied alone and restored: 1 failed | 414 passed, killed by the named test in every case. The remaining sixteen rows are all StringLiteral -> "" on a provider-name label inside createAbortError/settleOnAbort/rejectOnAbort; each one sits inside a catch or race whose enclosing handler re-throws with its own unmutated literal, so the provider-visible error name and message are identical through the public API and no assertion can distinguish the mutant from the code (measured: full suite green with each mutant in place). No Stryker directive was added; the equivalence is argued in the PR discussion for a maintainer to weigh.

Verification on this tree: vitest 421 passed (421) across the four provider specs in declaration order and with --sequence.shuffle (the six new opencode-go tests arrive with the re-ported blobs); tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical; prettier 3.9.10 --check on the touched files: clean. The opencode-go blobs are re-ported from df29307 and remain byte-identical to that head (git diff --quiet against it for those two paths: exit 0), so after a maintainer merges Zoo-Code-Org#1652 these lines drop out of this diff on rebase.

Review round 4 (CodeRabbit pre-merge checks, six Major and 26 Minor rows, handled in one pass): three sibling
stream loops no longer hand a cancelled turn their last item - Unbound re-checks the caller signal in front of
the text item of a frame whose reasoning item was already delivered, and both Vercel AI Gateway and Zoo Gateway
re-check it in front of the usage item of a frame whose text was already delivered, so a cancel between the two
items of one chunk rejects instead of emitting or billing the remainder. The three "does not emit the rest of a
tool-call chunk" tests are now consumer-driven (take the first partial, cancel, require the next call to reject
without building the second one) because the getter variant aborted before either partial existed and could not
tell a per-partial check from a per-frame check. Unbound's retained usage is typed as
OpenAI.Completions.CompletionUsage | undefined, which drops its @typescript-eslint/no-explicit-any suppression
from 3 to 2 (the only suppression change in this unit). The non-array tool_calls fixture now carries a truthy
value instead of null, so the Array.isArray check is what the test pins. The Zoo Gateway SDK-timeout
classification test no longer carries a 50 ms provider deadline, and the deadline test's mock refuses to run
without the per-request signal, so a provider that stops forwarding the deadline fails loudly instead of
throwing immediately. The two add-credits streaming tests wrap their whole body in a try/finally so the console
spy is restored even when an early assertion throws. The opencode-go provider and spec are the byte-identical
blobs from Zoo-Code-Org#1652 at d4ce1ce (opencode-go.ts 970de27, opencode-go.spec.ts 8c34bbb), which carry
the Responses/Anthropic quiet-close guards, the terminal-usage guard, the captured-SDK-signal assertions and
the merged-deadline cancel rows that close this unit's opencode-go rows; on rebase over the merged Zoo-Code-Org#1652 those
lines drop out.
Not changed in this unit, with the reasoning recorded on the threads: Unbound's timeout is enforced through the
merged deadline signal rather than response-body consumption (helper-side, tracked on Zoo-Code-Org#2486), the completion
races still return a response that won the race before the cancel, and the completion paths keep using the
shared mergeAbortSignalAndTimeout signal rather than a request-local bridge.
Verification on this round: vitest 431 passed (431) across the four provider specs in declaration order and with
--sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0
without --prune-suppressions: exit 0, with src/eslint-suppressions.json updated only for the unbound.ts decrease
(3 -> 2) that the prune run reported; prettier 3.9.10 --check: clean. Negative controls against the suite, each
disabling one guard: the Unbound text-item guard, the Vercel usage-item guard and the Zoo usage-item guard each
fail exactly their own new test (1 failed | 45, 56 and 103 passed respectively), the three per-partial guards
each fail exactly their rewritten tool-call test, dropping the Zoo completion's per-request signal arm fails the
seven timeout and abort-delivery tests that read it, and dropping the timeout arm fails the two option-forwarding
tests.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
- createMessage: bridge metadata.abortSignal to a per-request
  AbortController (Bedrock pattern: pre-aborted guard, once-listener,
  detached on completion so a task-scoped signal does not accumulate
  listeners); model resolution runs inside the shared
  resolveModelWithAbort cancellation scope (pre-aborted fast-fail,
  mid-resolution race)
- aborted/timeout requests normalize to the provider AbortError on all
  three wire formats (anthropic /v1/messages, responses /v1/responses,
  openai chat completions), both pre-stream and mid-stream; non-abort
  failures keep the wrapped "Opencode Go completion error:" identity
- the OpenAI branch runs message conversion and request construction
  inside the same cleanup scope as the Anthropic and Responses branches,
  so a conversion failure (e.g. an unstringifiable tool input) still
  detaches the bridged abort listener (CodeRabbit fix on this PR)
- completePrompt: forwards abortSignal/timeoutMs to all three SDK
  paths (timeoutMs <= 0 omits the SDK timeout option, since the SDK
  treats timeout: 0 as an immediate abort); aborted completions and
  APIConnectionTimeoutError/APITimeoutError normalize to the provider
  AbortError (series standard)

The inner pre-stream provider-name literal is provably equivalent
and documented as such in the PR body; no Stryker disable directive is
added anywhere in the tree. createMessage's outer catch applies the
identical isRequestAborted check to the same controller signal and
re-standardizes the error, so the inner layer's only unique behavior is
the non-abort completion-error wrap (stays kill-tested), and the
abort-normalization condition beside that literal is killed by a
live-signal delivery added in the second review round.

The cleanup-scope re-indentation made the gate instrument pre-existing
request-construction lines for the first time; their previously
unobservable mutants are kill-tested: R1 tool-result merge shape for
preserveReasoning models and the plain shape for non-preserveReasoning
models, the includeMaxTokens on/off branches with a ceiling-bounded
model, and the parallel_tool_calls default/explicit-false.

Unit 2/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util unit.
Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on 41ef0e0): the Chat Completions stream loop now
breaks on the request signal at the top of each iteration and re-checks that signal after
the loop, so an SDK that swallows the body-read abort and closes the iterator normally
cannot report a cancelled turn as completed. The new test parks the iterator after the
first chunk, hands back a getter-counting chunk once the caller cancels, and asserts both
the standardized AbortError and zero post-cancel chunk reads; flipping either guard to a
false condition fails exactly that test (1 failed | 195 passed). The Responses pre-stream
abort arm had no live-signal delivery, so one is added: with no caller signal nothing
aborts, only the error-name arm can normalize, and the ConditionalExpression mutant dies
with it (same control). The provider-name literals at the two stream catches and at the
three completePrompt races were re-measured: each survives the full 196-test suite, which
matches the equivalence argument above. The detach tests now require exactly two abort
registrations on the caller's signal, name the bridge's by position, require it to differ
from the model-resolution race's callback, and assert both removals by reference in that
order. The SDK abort and timeout deliveries now reject from inside the SDK mock with no
caller signal (the automocked openai module's error classes are not Error instances, so
the name/message arm is exercised with the real class taken from the actual module), a
caller cancel landing inside the SDK call is classified across all three formats, and the
parked-lookup gate is the typed getModels fetcher rather than a spy on the private
resolveModel.

Review round 2 (CodeRabbit pre-merge checks): completePrompt gained a parameterized timeout-option
test per wire format (Anthropic messages, Responses, chat completions) that proves each call site
applies the shared hasUsableTimeout/toSdkTimeoutMs contract rather than only testing the helper:
NaN, Infinity and -5 leave no timeout key, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards
MAX_TIMEOUT_MS, and every row also asserts the caller's signal reached the SDK options, so dropping
the budget can never drop the cancel. Controls: deleting the forward arm fails two rows per format,
forcing it to always forward fails the three disabled-budget rows, and replacing
toSdkTimeoutMs(timeoutMs) with the raw value fails exactly the two forwarding rows. The five
provider-name literals on the abort paths were re-measured at this head: all five survive the full
211-test suite, which is the measured half of the equivalence argument in the PR body.

Verification on this tree: src tsc --noEmit exit 0 apart from the two known donor-store
integrations/misc/export-markdown.ts rows; vitest 211 passed (211) in declaration order and
in shuffled order; eslint . --ext=ts --max-warnings=0 without --prune-suppressions exit 0
with src/eslint-suppressions.json byte-identical (a prune run found zero decreases for this
unit); prettier 3.9.10 --check clean on the staged blobs extracted with core.autocrlf=false.

Review round 3 (CodeRabbit pre-merge checks, six Minor rows): the Chat Completions streaming loop now re-checks the request signal in front of every buffered item of a frame — the text item after a reasoning item, each tool-call partial inside the per-item loop, and the usage item — because a consumer that takes the first item, cancels and pulls the next one resumes this generator inside the same iteration, where the top-of-loop guard has already run. The three stream-open awaits (Anthropic /v1/messages, Responses /v1/responses and chat completions) now go through settleOnAbort with the signal still handed to the SDK, so a 429 with Retry-After plus a caller cancel no longer holds the pending first next() and the bridge cleanup until the sleep ends. Regression evidence: one parameterized test for the three stream-open races plus three manual-iteration tests that abort between two items of one frame (the buffered-text variant also asserts the bridge listener is detached by reference). Negative controls: removing each open wrapper fails exactly that format's row (1 failed | 216 passed each), disabling each buffered-item guard fails exactly that item's test, and reverting the OpenAI-path fixture key from opencodeGoModelId to the ignored apiModelId fails the five assertions that now pin model "glm-5.1" instead of expect.any(String). The parked-lookup test releases its gate in a finally so an assertion throw cannot strand the promise the provider awaits; measured with a probe: a release placed after the throwing assertion leaves the promise unresolved, the same release in a finally settles it.

Verification on this round: vitest 217 passed (217) in declaration order and with --sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical (a prune run over the two unit files reported zero count decreases); prettier 3.9.10 --check: clean.

Review round 4 (CodeRabbit pre-merge checks, one Major and nine Minor rows, handled in a single pass): the
Responses and Anthropic helpers no longer let a normally-ending SDK iterator read as a completed turn. The
Responses helper re-checks the bridged signal after processResponsesApiStream returns; the Anthropic helper
re-checks it at the top of each event dispatch, between the separator item and the block body of an indexed
content_block_start, and after the loop before the terminal cost chunk, so a cancel cannot emit the rest of
an event or bill a turn the caller already cancelled. Four tests drive the shape the pinned SDKs actually
produce - hand the consumer one item, cancel, then let the mock iterator report done instead of throwing -
and each one also runs the identical fixture with a live caller signal, which still delivers its text and
its terminal cost. Negative controls, each against the full suite: the Responses post-stream check (1 failed
| 223 passed), the Anthropic after-loop check (killed by the test that cancels after the last event was
delivered), the event-dispatch check (killed by the quiet-close test) and the separator checks (killed by the
two-yields-of-one-event test) each fail their own test and nothing else that matters.
The Responses pre-stream abort test no longer certifies itself through the provider's own catch: the mock
captures the signal the SDK actually received and then throws a plain failure, so the only evidence left is
that the captured signal is an AbortSignal that had already flipped; handing the SDK an unrelated signal
instead of the bridge fails seven tests, including that one. The timeout matrix now pins signal identity
rather than signal type - with no usable budget the SDK must hold the caller's own signal, with a usable one
it must hold the merged deadline - and a new parameterized test parks each format's request under a 5000 ms
budget, cancels the caller long before the deadline and requires the merged signal to flip and the completion
to reject with the contract AbortError; replacing the merged deadline with the caller's own signal on the
chat-completions completion fails 26 tests, including those rows. Three tests that polled for readiness
before observing the rejection now attach the handler when the promise is created, so a model lookup or
stream open that rejects during the poll cannot go unobserved.
Verification on this round: vitest 224 passed (224) in declaration order and with --sequence.shuffle; tsc
--noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without
--prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical (a prune run over the two unit
files found zero decreases, so the rewritten file was reverted); prettier 3.9.10 --check: clean.

Review round 5 (mutation sticky at d4ce1ce: blocking 23, advisories 0): this round adds no production lines. Three
tests were added, each aimed at a variant the sticky lists: a cancel between the separator and the body of an indexed
thinking block (kills the ConditionalExpression -> false variant at opencode-go.ts:796 and puts line 797 under coverage),
and one run per streaming format that passes no abort signal at all, so every guard in the helper is exercised with an
absent caller signal. Measured against the suite: each of the 17 StringLiteral -> "" rows (357, 380, 391, 407, 424, 567,
574, 626, 717, 725, 743, 797, 809, 858, 976, 1046, 1104) leaves 227/227 green, and each of the 5 OptionalChaining rows
(625, 742, 796, 808, 857) leaves 227/227 green. The reason is structural, not a matter of unasserted detail: at the
OptionalChaining lines the operand is the request-local signal that bridgeExternalAbortSignal/mergeAbortSignalAndTimeout
always hand to the SDK, so it is never nullish there, and an inner createAbortError is replaced by the enclosing catch's
own unmutated literal (for example the stream-open catch at 719 re-throwing at 725, and the completion catch at 981
re-throwing at 992), so the tests that do assert the exact contract message still see "The Opencode Go request was
aborted". The one variant that is observably different is now killed: ConditionalExpression -> false at 796 fails the new
thinking test (1 failed | 226 skipped) where it left the previous suite green.
Verification on this round: vitest 227 passed (227) in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0, with
eslint-suppressions.json unchanged because --prune-suppressions on the two unit files reported no count change; prettier
3.9.10 --check: clean.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
…ateway

Each provider's createMessage bridges metadata.abortSignal to a
per-request AbortController (Bedrock pattern: pre-aborted guard,
{ once: true } listener, detached on completion so a task-scoped
signal does not accumulate listeners) and runs model resolution inside
the shared resolveModelWithAbort cancellation scope; aborted requests
(pre-aborted, mid-resolution, mid-stream) normalize to the provider
AbortError while non-abort failures propagate or wrap unchanged.
completePrompt forwards abortSignal/timeoutMs to the OpenAI SDK
(timeoutMs <= 0 omits the SDK timeout option); aborted completions and
APIConnectionTimeoutError normalize to the provider AbortError (series
standard).

Zoo Gateway places the entry fast-fail before ensureAuthenticated() so
a pre-aborted task surfaces the AbortError instead of an auth failure
(pinned by an unauthenticated pre-abort test).

Unit 3/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util and opencode-go units. Three sibling OpenAI-SDK gateway
providers with an identical abort-wiring shape are kept as one unit to
avoid tripling the review surface for mechanically identical changes
(a+d soft-cap rationale per the split budget; the mutation gate is
measured on the unit delta and is green).

Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on b1bd578, disposition recorded on each thread): each provider now races the SDK promise it awaits against the bridged signal through `settleOnAbort` — unbound's stream create and its completion, vercel-ai-gateway's completion, zoo-gateway's completion — because the OpenAI SDK sleeps out a Retry-After / retry delay without observing the signal, and the post-await `bridgedSignal?.aborted` guards that used to trail those awaits are gone, since `raceAbort` rejects synchronously at `abort()` and nothing after the await can read the flag first. Each streaming loop breaks on the caller signal at the top of an iteration, re-checks it before emitting a just-received chunk, and checks it once more before the generator returns, so a cancel the SDK swallows — the iterator ends normally without a throw — can neither emit the rest of a chunk nor report a partial turn as completed. The caller's signal is bridged rather than handed to the SDK directly and the bridge is disposed in `finally`; the detach tests name the bridge's listener by registration position, require it to differ from the model-lookup race's callback, and assert both removals by reference. Absence proofs drain the provider's own continuation instead of sleeping.

The two Opencode Go files are Zoo-Code-Org#1652's blobs, byte for byte: provider `23348a501e9f31d0c72bffa6eefb6030bb6149a3`, spec `5dbe3382d1f1d6af8d22e7637a088c546988ef18`; `git diff df29307 -- <those two paths>` is empty with `core.autocrlf=false` and the blob ids are re-verified against this commit. Once Zoo-Code-Org#1652 lands on main this unit rebases onto it and both files drop out of this diff.

Review round 2 (CodeRabbit pre-merge checks): each gateway completePrompt now pins the disabled-budget boundary at -5 — the SDK options carry no timeout key and the bridged per-request signal is still handed over (the zoo variant is one of the tests that also catches a dropped signal arm). The ported Opencode Go spec brings its own parameterized timeout-option test per wire format: NaN, Infinity and -5 omit the option, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards MAX_TIMEOUT_MS, and the caller signal is asserted on every row. Those rows kill the forward arms at opencode-go.ts:886/944/1027 in both directions (deleting the arm fails two rows per format, forcing it always-forward fails the three disabled-budget rows) and the toSdkTimeoutMs call sites; forcing the gateway arms to always forward fails the new -5 rows on all three providers.

Verification on this tree: vitest over the opencode-go, unbound, vercel-ai-gateway and zoo-gateway specs from `src` — 411 passed (411) in declaration order and 411 passed with `--sequence.shuffle`; `tsc --noEmit -p tsconfig.json` leaves only the two known donor-store `integrations/misc/export-markdown.ts` rows; `eslint . --ext=ts --max-warnings=0` without `--prune-suppressions` exits 0 with `src/eslint-suppressions.json` byte-identical (a prune run over the eight touched paths reported zero count decreases); prettier 3.9.10 `--check` clean on the staged blobs extracted with `core.autocrlf=false`. Negative controls per new guard: flipping each added condition or deleting each added arm fails the specific guard test that names it — 1 failed | 195 passed for either Opencode Go chat-stream arm, 1 failed for the Responses pre-stream condition, 2 failed for the Anthropic stream condition, and the same shape for the gateway guards.

Review round 3: the mutation-diff report at 313cf0e listed 20 blocking rows (21 survived mutants plus one uncovered arm) over 338 changed executable lines. Five of them are now killed by four tests added here: unbound.ts:349 and vercel-ai-gateway.ts:280 (detachExternalAbortSignal() -> ; in the completePrompt finally) by a detach test per provider that identifies the bridge listener by the { once: true } registration and asserts its removal by reference; zoo-gateway.ts:337 (classification gate -> false) by a streaming test that feeds a name-only AbortError with a live-but-not-aborted caller signal and asserts the contract identity, that the add-credits notification never ran, and that nothing was logged; zoo-gateway.ts:346 in both directions by a streaming test where the notification itself rejects while the caller signal is live (the log must name the surfacing failure and the original 402 must still reach the caller) plus the existing cancel-while-prompt-open test, which also puts that line under coverage. Each of those four mutants was applied alone and restored: 1 failed | 414 passed, killed by the named test in every case. The remaining sixteen rows are all StringLiteral -> "" on a provider-name label inside createAbortError/settleOnAbort/rejectOnAbort; each one sits inside a catch or race whose enclosing handler re-throws with its own unmutated literal, so the provider-visible error name and message are identical through the public API and no assertion can distinguish the mutant from the code (measured: full suite green with each mutant in place). No Stryker directive was added; the equivalence is argued in the PR discussion for a maintainer to weigh.

Verification on this tree: vitest 421 passed (421) across the four provider specs in declaration order and with --sequence.shuffle (the six new opencode-go tests arrive with the re-ported blobs); tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical; prettier 3.9.10 --check on the touched files: clean. The opencode-go blobs are re-ported from df29307 and remain byte-identical to that head (git diff --quiet against it for those two paths: exit 0), so after a maintainer merges Zoo-Code-Org#1652 these lines drop out of this diff on rebase.

Review round 4 (CodeRabbit pre-merge checks, six Major and 26 Minor rows, handled in one pass): three sibling
stream loops no longer hand a cancelled turn their last item - Unbound re-checks the caller signal in front of
the text item of a frame whose reasoning item was already delivered, and both Vercel AI Gateway and Zoo Gateway
re-check it in front of the usage item of a frame whose text was already delivered, so a cancel between the two
items of one chunk rejects instead of emitting or billing the remainder. The three "does not emit the rest of a
tool-call chunk" tests are now consumer-driven (take the first partial, cancel, require the next call to reject
without building the second one) because the getter variant aborted before either partial existed and could not
tell a per-partial check from a per-frame check. Unbound's retained usage is typed as
OpenAI.Completions.CompletionUsage | undefined, which drops its @typescript-eslint/no-explicit-any suppression
from 3 to 2 (the only suppression change in this unit). The non-array tool_calls fixture now carries a truthy
value instead of null, so the Array.isArray check is what the test pins. The Zoo Gateway SDK-timeout
classification test no longer carries a 50 ms provider deadline, and the deadline test's mock refuses to run
without the per-request signal, so a provider that stops forwarding the deadline fails loudly instead of
throwing immediately. The two add-credits streaming tests wrap their whole body in a try/finally so the console
spy is restored even when an early assertion throws. The opencode-go provider and spec are the byte-identical
blobs from Zoo-Code-Org#1652 at d4ce1ce (opencode-go.ts 970de27, opencode-go.spec.ts 8c34bbb), which carry
the Responses/Anthropic quiet-close guards, the terminal-usage guard, the captured-SDK-signal assertions and
the merged-deadline cancel rows that close this unit's opencode-go rows; on rebase over the merged Zoo-Code-Org#1652 those
lines drop out.
Not changed in this unit, with the reasoning recorded on the threads: Unbound's timeout is enforced through the
merged deadline signal rather than response-body consumption (helper-side, tracked on Zoo-Code-Org#2486), the completion
races still return a response that won the race before the cancel, and the completion paths keep using the
shared mergeAbortSignalAndTimeout signal rather than a request-local bridge.
Verification on this round: vitest 431 passed (431) across the four provider specs in declaration order and with
--sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0
without --prune-suppressions: exit 0, with src/eslint-suppressions.json updated only for the unbound.ts decrease
(3 -> 2) that the prune run reported; prettier 3.9.10 --check: clean. Negative controls against the suite, each
disabling one guard: the Unbound text-item guard, the Vercel usage-item guard and the Zoo usage-item guard each
fail exactly their own new test (1 failed | 45, 56 and 103 passed respectively), the three per-partial guards
each fail exactly their rewritten tool-call test, dropping the Zoo completion's per-request signal arm fails the
seven timeout and abort-delivery tests that read it, and dropping the timeout arm fails the two option-forwarding
tests.

Review round 5 (mutation sticky at 41ba1fe: blocking 23, advisories 0): no production line was added or changed in
this round. The opencode-go provider and spec are re-ported byte-identical from Zoo-Code-Org#1652 at 40456d8 (blobs
970de27 and 4afc3ee), which carry the thinking-separator cancel test and the two no-abort-signal runs that
kill and explain the structural variants on that file. Every sibling row was measured by hand in this worktree: the label
mutants at unbound.ts:218/247/257/278/338 and vercel-ai-gateway.ts:136/168/185/267 leave their whole spec green
(46/46 and 57/57) because each inner createAbortError is replaced by the enclosing catch's own unmutated literal, while
mutating those catches' own labels (unbound.ts:224, 289, 349 and vercel-ai-gateway.ts:204, 213, 279) fails 3, 6, 5, 4, 1
and 5 tests - which is what proves the message the tests assert comes from the catch, not from the inner label. The zoo
labels (280, 308, 344) are killed outright by the abort-identity tests, and the zoo console-guard optional chain is
killed by two existing tests.
Verification on this round: vitest 434 passed (434) across the four provider specs in declaration order and with
--sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without
--prune-suppressions: exit 0 with eslint-suppressions.json carrying only the round-4 unbound.ts decrease (3 -> 2);
prettier 3.9.10 --check: clean across all eight unit files.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
- createMessage: bridge metadata.abortSignal to a per-request
  AbortController (Bedrock pattern: pre-aborted guard, once-listener,
  detached on completion so a task-scoped signal does not accumulate
  listeners); model resolution runs inside the shared
  resolveModelWithAbort cancellation scope (pre-aborted fast-fail,
  mid-resolution race)
- aborted/timeout requests normalize to the provider AbortError on all
  three wire formats (anthropic /v1/messages, responses /v1/responses,
  openai chat completions), both pre-stream and mid-stream; non-abort
  failures keep the wrapped "Opencode Go completion error:" identity
- the OpenAI branch runs message conversion and request construction
  inside the same cleanup scope as the Anthropic and Responses branches,
  so a conversion failure (e.g. an unstringifiable tool input) still
  detaches the bridged abort listener (CodeRabbit fix on this PR)
- completePrompt: forwards abortSignal/timeoutMs to all three SDK
  paths (timeoutMs <= 0 omits the SDK timeout option, since the SDK
  treats timeout: 0 as an immediate abort); aborted completions and
  APIConnectionTimeoutError/APITimeoutError normalize to the provider
  AbortError (series standard)

The inner pre-stream provider-name literal is provably equivalent
and documented as such in the PR body; no Stryker disable directive is
added anywhere in the tree. createMessage's outer catch applies the
identical isRequestAborted check to the same controller signal and
re-standardizes the error, so the inner layer's only unique behavior is
the non-abort completion-error wrap (stays kill-tested), and the
abort-normalization condition beside that literal is killed by a
live-signal delivery added in the second review round.

The cleanup-scope re-indentation made the gate instrument pre-existing
request-construction lines for the first time; their previously
unobservable mutants are kill-tested: R1 tool-result merge shape for
preserveReasoning models and the plain shape for non-preserveReasoning
models, the includeMaxTokens on/off branches with a ceiling-bounded
model, and the parallel_tool_calls default/explicit-false.

Unit 2/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util unit.
Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on 41ef0e0): the Chat Completions stream loop now
breaks on the request signal at the top of each iteration and re-checks that signal after
the loop, so an SDK that swallows the body-read abort and closes the iterator normally
cannot report a cancelled turn as completed. The new test parks the iterator after the
first chunk, hands back a getter-counting chunk once the caller cancels, and asserts both
the standardized AbortError and zero post-cancel chunk reads; flipping either guard to a
false condition fails exactly that test (1 failed | 195 passed). The Responses pre-stream
abort arm had no live-signal delivery, so one is added: with no caller signal nothing
aborts, only the error-name arm can normalize, and the ConditionalExpression mutant dies
with it (same control). The provider-name literals at the two stream catches and at the
three completePrompt races were re-measured: each survives the full 196-test suite, which
matches the equivalence argument above. The detach tests now require exactly two abort
registrations on the caller's signal, name the bridge's by position, require it to differ
from the model-resolution race's callback, and assert both removals by reference in that
order. The SDK abort and timeout deliveries now reject from inside the SDK mock with no
caller signal (the automocked openai module's error classes are not Error instances, so
the name/message arm is exercised with the real class taken from the actual module), a
caller cancel landing inside the SDK call is classified across all three formats, and the
parked-lookup gate is the typed getModels fetcher rather than a spy on the private
resolveModel.

Review round 2 (CodeRabbit pre-merge checks): completePrompt gained a parameterized timeout-option
test per wire format (Anthropic messages, Responses, chat completions) that proves each call site
applies the shared hasUsableTimeout/toSdkTimeoutMs contract rather than only testing the helper:
NaN, Infinity and -5 leave no timeout key, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards
MAX_TIMEOUT_MS, and every row also asserts the caller's signal reached the SDK options, so dropping
the budget can never drop the cancel. Controls: deleting the forward arm fails two rows per format,
forcing it to always forward fails the three disabled-budget rows, and replacing
toSdkTimeoutMs(timeoutMs) with the raw value fails exactly the two forwarding rows. The five
provider-name literals on the abort paths were re-measured at this head: all five survive the full
211-test suite, which is the measured half of the equivalence argument in the PR body.

Verification on this tree: src tsc --noEmit exit 0 apart from the two known donor-store
integrations/misc/export-markdown.ts rows; vitest 211 passed (211) in declaration order and
in shuffled order; eslint . --ext=ts --max-warnings=0 without --prune-suppressions exit 0
with src/eslint-suppressions.json byte-identical (a prune run found zero decreases for this
unit); prettier 3.9.10 --check clean on the staged blobs extracted with core.autocrlf=false.

Review round 3 (CodeRabbit pre-merge checks, six Minor rows): the Chat Completions streaming loop now re-checks the request signal in front of every buffered item of a frame — the text item after a reasoning item, each tool-call partial inside the per-item loop, and the usage item — because a consumer that takes the first item, cancels and pulls the next one resumes this generator inside the same iteration, where the top-of-loop guard has already run. The three stream-open awaits (Anthropic /v1/messages, Responses /v1/responses and chat completions) now go through settleOnAbort with the signal still handed to the SDK, so a 429 with Retry-After plus a caller cancel no longer holds the pending first next() and the bridge cleanup until the sleep ends. Regression evidence: one parameterized test for the three stream-open races plus three manual-iteration tests that abort between two items of one frame (the buffered-text variant also asserts the bridge listener is detached by reference). Negative controls: removing each open wrapper fails exactly that format's row (1 failed | 216 passed each), disabling each buffered-item guard fails exactly that item's test, and reverting the OpenAI-path fixture key from opencodeGoModelId to the ignored apiModelId fails the five assertions that now pin model "glm-5.1" instead of expect.any(String). The parked-lookup test releases its gate in a finally so an assertion throw cannot strand the promise the provider awaits; measured with a probe: a release placed after the throwing assertion leaves the promise unresolved, the same release in a finally settles it.

Verification on this round: vitest 217 passed (217) in declaration order and with --sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical (a prune run over the two unit files reported zero count decreases); prettier 3.9.10 --check: clean.

Review round 4 (CodeRabbit pre-merge checks, one Major and nine Minor rows, handled in a single pass): the
Responses and Anthropic helpers no longer let a normally-ending SDK iterator read as a completed turn. The
Responses helper re-checks the bridged signal after processResponsesApiStream returns; the Anthropic helper
re-checks it at the top of each event dispatch, between the separator item and the block body of an indexed
content_block_start, and after the loop before the terminal cost chunk, so a cancel cannot emit the rest of
an event or bill a turn the caller already cancelled. Four tests drive the shape the pinned SDKs actually
produce - hand the consumer one item, cancel, then let the mock iterator report done instead of throwing -
and each one also runs the identical fixture with a live caller signal, which still delivers its text and
its terminal cost. Negative controls, each against the full suite: the Responses post-stream check (1 failed
| 223 passed), the Anthropic after-loop check (killed by the test that cancels after the last event was
delivered), the event-dispatch check (killed by the quiet-close test) and the separator checks (killed by the
two-yields-of-one-event test) each fail their own test and nothing else that matters.
The Responses pre-stream abort test no longer certifies itself through the provider's own catch: the mock
captures the signal the SDK actually received and then throws a plain failure, so the only evidence left is
that the captured signal is an AbortSignal that had already flipped; handing the SDK an unrelated signal
instead of the bridge fails seven tests, including that one. The timeout matrix now pins signal identity
rather than signal type - with no usable budget the SDK must hold the caller's own signal, with a usable one
it must hold the merged deadline - and a new parameterized test parks each format's request under a 5000 ms
budget, cancels the caller long before the deadline and requires the merged signal to flip and the completion
to reject with the contract AbortError; replacing the merged deadline with the caller's own signal on the
chat-completions completion fails 26 tests, including those rows. Three tests that polled for readiness
before observing the rejection now attach the handler when the promise is created, so a model lookup or
stream open that rejects during the poll cannot go unobserved.
Verification on this round: vitest 224 passed (224) in declaration order and with --sequence.shuffle; tsc
--noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without
--prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical (a prune run over the two unit
files found zero decreases, so the rewritten file was reverted); prettier 3.9.10 --check: clean.

Review round 5 (mutation sticky at d4ce1ce: blocking 23, advisories 0): this round adds no production lines. Three
tests were added, each aimed at a variant the sticky lists: a cancel between the separator and the body of an indexed
thinking block (kills the ConditionalExpression -> false variant at opencode-go.ts:796 and puts line 797 under coverage),
and one run per streaming format that passes no abort signal at all, so every guard in the helper is exercised with an
absent caller signal. Measured against the suite: each of the 17 StringLiteral -> "" rows (357, 380, 391, 407, 424, 567,
574, 626, 717, 725, 743, 797, 809, 858, 976, 1046, 1104) leaves 227/227 green, and each of the 5 OptionalChaining rows
(625, 742, 796, 808, 857) leaves 227/227 green. The reason is structural, not a matter of unasserted detail: at the
OptionalChaining lines the operand is the request-local signal that bridgeExternalAbortSignal/mergeAbortSignalAndTimeout
always hand to the SDK, so it is never nullish there, and an inner createAbortError is replaced by the enclosing catch's
own unmutated literal (for example the stream-open catch at 719 re-throwing at 725, and the completion catch at 981
re-throwing at 992), so the tests that do assert the exact contract message still see "The Opencode Go request was
aborted". The one variant that is observably different is now killed: ConditionalExpression -> false at 796 fails the new
thinking test (1 failed | 226 skipped) where it left the previous suite green.
Verification on this round: vitest 227 passed (227) in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0, with
eslint-suppressions.json unchanged because --prune-suppressions on the two unit files reported no count change; prettier
3.9.10 --check: clean.

Review round 6 (ask: kill the StringLiteral family with test-side message assertions before anything else, no new
production code). The spec's two remaining name-only assertions now pin the message too (spec:3824 and spec:3867, in the
two "bounds %s model resolution by the request timeout" groups), so every name assertion in the file carries the contract
message. That changed no survivor, and the reason is worth recording: with the message pinned everywhere, each of the 17
StringLiteral -> "" rows still leaves 227/227 green, because the message those tests read is produced by an enclosing
catch that throws its own unmutated createAbortError("Opencode Go") - the createMessage-level catch at :279 and the Chat
Completions stream helper's catch at :431 - and blanking either of those two literals fails 8 and 7 tests respectively,
while blanking any guard or race label fails none. The five OptionalChaining rows are equivalent for a separate reason:
the streaming helpers are always handed bridgedSignal ?? new AbortController().signal at :260, so their operand is never
nullish; with all five optional chains removed at once the suite is still 227/227, including the two runs that pass no
caller signal at all. No production line changed in either of the last two rounds; the provider blob is unchanged at
970de27.
Verification on this round: vitest 227 passed (227) in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with
eslint-suppressions.json unchanged; prettier 3.9.10 --check: clean.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
…ateway

Each provider's createMessage bridges metadata.abortSignal to a
per-request AbortController (Bedrock pattern: pre-aborted guard,
{ once: true } listener, detached on completion so a task-scoped
signal does not accumulate listeners) and runs model resolution inside
the shared resolveModelWithAbort cancellation scope; aborted requests
(pre-aborted, mid-resolution, mid-stream) normalize to the provider
AbortError while non-abort failures propagate or wrap unchanged.
completePrompt forwards abortSignal/timeoutMs to the OpenAI SDK
(timeoutMs <= 0 omits the SDK timeout option); aborted completions and
APIConnectionTimeoutError normalize to the provider AbortError (series
standard).

Zoo Gateway places the entry fast-fail before ensureAuthenticated() so
a pre-aborted task surfaces the AbortError instead of an auth failure
(pinned by an unauthenticated pre-abort test).

Unit 3/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util and opencode-go units. Three sibling OpenAI-SDK gateway
providers with an identical abort-wiring shape are kept as one unit to
avoid tripling the review surface for mechanically identical changes
(a+d soft-cap rationale per the split budget; the mutation gate is
measured on the unit delta and is green).

Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on b1bd578, disposition recorded on each thread): each provider now races the SDK promise it awaits against the bridged signal through `settleOnAbort` — unbound's stream create and its completion, vercel-ai-gateway's completion, zoo-gateway's completion — because the OpenAI SDK sleeps out a Retry-After / retry delay without observing the signal, and the post-await `bridgedSignal?.aborted` guards that used to trail those awaits are gone, since `raceAbort` rejects synchronously at `abort()` and nothing after the await can read the flag first. Each streaming loop breaks on the caller signal at the top of an iteration, re-checks it before emitting a just-received chunk, and checks it once more before the generator returns, so a cancel the SDK swallows — the iterator ends normally without a throw — can neither emit the rest of a chunk nor report a partial turn as completed. The caller's signal is bridged rather than handed to the SDK directly and the bridge is disposed in `finally`; the detach tests name the bridge's listener by registration position, require it to differ from the model-lookup race's callback, and assert both removals by reference. Absence proofs drain the provider's own continuation instead of sleeping.

The two Opencode Go files are Zoo-Code-Org#1652's blobs, byte for byte: provider `23348a501e9f31d0c72bffa6eefb6030bb6149a3`, spec `5dbe3382d1f1d6af8d22e7637a088c546988ef18`; `git diff df29307 -- <those two paths>` is empty with `core.autocrlf=false` and the blob ids are re-verified against this commit. Once Zoo-Code-Org#1652 lands on main this unit rebases onto it and both files drop out of this diff.

Review round 2 (CodeRabbit pre-merge checks): each gateway completePrompt now pins the disabled-budget boundary at -5 — the SDK options carry no timeout key and the bridged per-request signal is still handed over (the zoo variant is one of the tests that also catches a dropped signal arm). The ported Opencode Go spec brings its own parameterized timeout-option test per wire format: NaN, Infinity and -5 omit the option, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards MAX_TIMEOUT_MS, and the caller signal is asserted on every row. Those rows kill the forward arms at opencode-go.ts:886/944/1027 in both directions (deleting the arm fails two rows per format, forcing it always-forward fails the three disabled-budget rows) and the toSdkTimeoutMs call sites; forcing the gateway arms to always forward fails the new -5 rows on all three providers.

Verification on this tree: vitest over the opencode-go, unbound, vercel-ai-gateway and zoo-gateway specs from `src` — 411 passed (411) in declaration order and 411 passed with `--sequence.shuffle`; `tsc --noEmit -p tsconfig.json` leaves only the two known donor-store `integrations/misc/export-markdown.ts` rows; `eslint . --ext=ts --max-warnings=0` without `--prune-suppressions` exits 0 with `src/eslint-suppressions.json` byte-identical (a prune run over the eight touched paths reported zero count decreases); prettier 3.9.10 `--check` clean on the staged blobs extracted with `core.autocrlf=false`. Negative controls per new guard: flipping each added condition or deleting each added arm fails the specific guard test that names it — 1 failed | 195 passed for either Opencode Go chat-stream arm, 1 failed for the Responses pre-stream condition, 2 failed for the Anthropic stream condition, and the same shape for the gateway guards.

Review round 3: the mutation-diff report at 313cf0e listed 20 blocking rows (21 survived mutants plus one uncovered arm) over 338 changed executable lines. Five of them are now killed by four tests added here: unbound.ts:349 and vercel-ai-gateway.ts:280 (detachExternalAbortSignal() -> ; in the completePrompt finally) by a detach test per provider that identifies the bridge listener by the { once: true } registration and asserts its removal by reference; zoo-gateway.ts:337 (classification gate -> false) by a streaming test that feeds a name-only AbortError with a live-but-not-aborted caller signal and asserts the contract identity, that the add-credits notification never ran, and that nothing was logged; zoo-gateway.ts:346 in both directions by a streaming test where the notification itself rejects while the caller signal is live (the log must name the surfacing failure and the original 402 must still reach the caller) plus the existing cancel-while-prompt-open test, which also puts that line under coverage. Each of those four mutants was applied alone and restored: 1 failed | 414 passed, killed by the named test in every case. The remaining sixteen rows are all StringLiteral -> "" on a provider-name label inside createAbortError/settleOnAbort/rejectOnAbort; each one sits inside a catch or race whose enclosing handler re-throws with its own unmutated literal, so the provider-visible error name and message are identical through the public API and no assertion can distinguish the mutant from the code (measured: full suite green with each mutant in place). No Stryker directive was added; the equivalence is argued in the PR discussion for a maintainer to weigh.

Verification on this tree: vitest 421 passed (421) across the four provider specs in declaration order and with --sequence.shuffle (the six new opencode-go tests arrive with the re-ported blobs); tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical; prettier 3.9.10 --check on the touched files: clean. The opencode-go blobs are re-ported from df29307 and remain byte-identical to that head (git diff --quiet against it for those two paths: exit 0), so after a maintainer merges Zoo-Code-Org#1652 these lines drop out of this diff on rebase.

Review round 4 (CodeRabbit pre-merge checks, six Major and 26 Minor rows, handled in one pass): three sibling
stream loops no longer hand a cancelled turn their last item - Unbound re-checks the caller signal in front of
the text item of a frame whose reasoning item was already delivered, and both Vercel AI Gateway and Zoo Gateway
re-check it in front of the usage item of a frame whose text was already delivered, so a cancel between the two
items of one chunk rejects instead of emitting or billing the remainder. The three "does not emit the rest of a
tool-call chunk" tests are now consumer-driven (take the first partial, cancel, require the next call to reject
without building the second one) because the getter variant aborted before either partial existed and could not
tell a per-partial check from a per-frame check. Unbound's retained usage is typed as
OpenAI.Completions.CompletionUsage | undefined, which drops its @typescript-eslint/no-explicit-any suppression
from 3 to 2 (the only suppression change in this unit). The non-array tool_calls fixture now carries a truthy
value instead of null, so the Array.isArray check is what the test pins. The Zoo Gateway SDK-timeout
classification test no longer carries a 50 ms provider deadline, and the deadline test's mock refuses to run
without the per-request signal, so a provider that stops forwarding the deadline fails loudly instead of
throwing immediately. The two add-credits streaming tests wrap their whole body in a try/finally so the console
spy is restored even when an early assertion throws. The opencode-go provider and spec are the byte-identical
blobs from Zoo-Code-Org#1652 at d4ce1ce (opencode-go.ts 970de27, opencode-go.spec.ts 8c34bbb), which carry
the Responses/Anthropic quiet-close guards, the terminal-usage guard, the captured-SDK-signal assertions and
the merged-deadline cancel rows that close this unit's opencode-go rows; on rebase over the merged Zoo-Code-Org#1652 those
lines drop out.
Not changed in this unit, with the reasoning recorded on the threads: Unbound's timeout is enforced through the
merged deadline signal rather than response-body consumption (helper-side, tracked on Zoo-Code-Org#2486), the completion
races still return a response that won the race before the cancel, and the completion paths keep using the
shared mergeAbortSignalAndTimeout signal rather than a request-local bridge.
Verification on this round: vitest 431 passed (431) across the four provider specs in declaration order and with
--sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0
without --prune-suppressions: exit 0, with src/eslint-suppressions.json updated only for the unbound.ts decrease
(3 -> 2) that the prune run reported; prettier 3.9.10 --check: clean. Negative controls against the suite, each
disabling one guard: the Unbound text-item guard, the Vercel usage-item guard and the Zoo usage-item guard each
fail exactly their own new test (1 failed | 45, 56 and 103 passed respectively), the three per-partial guards
each fail exactly their rewritten tool-call test, dropping the Zoo completion's per-request signal arm fails the
seven timeout and abort-delivery tests that read it, and dropping the timeout arm fails the two option-forwarding
tests.

Review round 5 (mutation sticky at 41ba1fe: blocking 23, advisories 0): no production line was added or changed in
this round. The opencode-go provider and spec are re-ported byte-identical from Zoo-Code-Org#1652 at 40456d8 (blobs
970de27 and 4afc3ee), which carry the thinking-separator cancel test and the two no-abort-signal runs that
kill and explain the structural variants on that file. Every sibling row was measured by hand in this worktree: the label
mutants at unbound.ts:218/247/257/278/338 and vercel-ai-gateway.ts:136/168/185/267 leave their whole spec green
(46/46 and 57/57) because each inner createAbortError is replaced by the enclosing catch's own unmutated literal, while
mutating those catches' own labels (unbound.ts:224, 289, 349 and vercel-ai-gateway.ts:204, 213, 279) fails 3, 6, 5, 4, 1
and 5 tests - which is what proves the message the tests assert comes from the catch, not from the inner label. The zoo
labels (280, 308, 344) are killed outright by the abort-identity tests, and the zoo console-guard optional chain is
killed by two existing tests.
Verification on this round: vitest 434 passed (434) across the four provider specs in declaration order and with
--sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without
--prune-suppressions: exit 0 with eslint-suppressions.json carrying only the round-4 unbound.ts decrease (3 -> 2);
prettier 3.9.10 --check: clean across all eight unit files.

Review round 6: the two opencode-go files are re-ported byte-identical from Zoo-Code-Org#1652 at b51323d (blobs 970de27 and
2163ff1), which adds the two message assertions described there and no production line. Verification on this round:
vitest 434 passed (434) across the four provider specs in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with only the
round-4 unbound.ts decrease (3 -> 2) in eslint-suppressions.json; prettier 3.9.10 --check: clean across the eight unit
files. The unit's own content (excluding the 2847 a+d carried byte-identically from Zoo-Code-Org#1652, which drops out on merge plus
rebase) is 3198 a+d.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
- createMessage: bridge metadata.abortSignal to a per-request
  AbortController (Bedrock pattern: pre-aborted guard, once-listener,
  detached on completion so a task-scoped signal does not accumulate
  listeners); model resolution runs inside the shared
  resolveModelWithAbort cancellation scope (pre-aborted fast-fail,
  mid-resolution race)
- aborted/timeout requests normalize to the provider AbortError on all
  three wire formats (anthropic /v1/messages, responses /v1/responses,
  openai chat completions), both pre-stream and mid-stream; non-abort
  failures keep the wrapped "Opencode Go completion error:" identity
- the OpenAI branch runs message conversion and request construction
  inside the same cleanup scope as the Anthropic and Responses branches,
  so a conversion failure (e.g. an unstringifiable tool input) still
  detaches the bridged abort listener (CodeRabbit fix on this PR)
- completePrompt: forwards abortSignal/timeoutMs to all three SDK
  paths (timeoutMs <= 0 omits the SDK timeout option, since the SDK
  treats timeout: 0 as an immediate abort); aborted completions and
  APIConnectionTimeoutError/APITimeoutError normalize to the provider
  AbortError (series standard)

The inner pre-stream provider-name literal is provably equivalent
and documented as such in the PR body; no Stryker disable directive is
added anywhere in the tree. createMessage's outer catch applies the
identical isRequestAborted check to the same controller signal and
re-standardizes the error, so the inner layer's only unique behavior is
the non-abort completion-error wrap (stays kill-tested), and the
abort-normalization condition beside that literal is killed by a
live-signal delivery added in the second review round.

The cleanup-scope re-indentation made the gate instrument pre-existing
request-construction lines for the first time; their previously
unobservable mutants are kill-tested: R1 tool-result merge shape for
preserveReasoning models and the plain shape for non-preserveReasoning
models, the includeMaxTokens on/off branches with a ceiling-bounded
model, and the parallel_tool_calls default/explicit-false.

Unit 2/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util unit.
Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on 41ef0e0): the Chat Completions stream loop now
breaks on the request signal at the top of each iteration and re-checks that signal after
the loop, so an SDK that swallows the body-read abort and closes the iterator normally
cannot report a cancelled turn as completed. The new test parks the iterator after the
first chunk, hands back a getter-counting chunk once the caller cancels, and asserts both
the standardized AbortError and zero post-cancel chunk reads; flipping either guard to a
false condition fails exactly that test (1 failed | 195 passed). The Responses pre-stream
abort arm had no live-signal delivery, so one is added: with no caller signal nothing
aborts, only the error-name arm can normalize, and the ConditionalExpression mutant dies
with it (same control). The provider-name literals at the two stream catches and at the
three completePrompt races were re-measured: each survives the full 196-test suite, which
matches the equivalence argument above. The detach tests now require exactly two abort
registrations on the caller's signal, name the bridge's by position, require it to differ
from the model-resolution race's callback, and assert both removals by reference in that
order. The SDK abort and timeout deliveries now reject from inside the SDK mock with no
caller signal (the automocked openai module's error classes are not Error instances, so
the name/message arm is exercised with the real class taken from the actual module), a
caller cancel landing inside the SDK call is classified across all three formats, and the
parked-lookup gate is the typed getModels fetcher rather than a spy on the private
resolveModel.

Review round 2 (CodeRabbit pre-merge checks): completePrompt gained a parameterized timeout-option
test per wire format (Anthropic messages, Responses, chat completions) that proves each call site
applies the shared hasUsableTimeout/toSdkTimeoutMs contract rather than only testing the helper:
NaN, Infinity and -5 leave no timeout key, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards
MAX_TIMEOUT_MS, and every row also asserts the caller's signal reached the SDK options, so dropping
the budget can never drop the cancel. Controls: deleting the forward arm fails two rows per format,
forcing it to always forward fails the three disabled-budget rows, and replacing
toSdkTimeoutMs(timeoutMs) with the raw value fails exactly the two forwarding rows. The five
provider-name literals on the abort paths were re-measured at this head: all five survive the full
211-test suite, which is the measured half of the equivalence argument in the PR body.

Verification on this tree: src tsc --noEmit exit 0 apart from the two known donor-store
integrations/misc/export-markdown.ts rows; vitest 211 passed (211) in declaration order and
in shuffled order; eslint . --ext=ts --max-warnings=0 without --prune-suppressions exit 0
with src/eslint-suppressions.json byte-identical (a prune run found zero decreases for this
unit); prettier 3.9.10 --check clean on the staged blobs extracted with core.autocrlf=false.

Review round 3 (CodeRabbit pre-merge checks, six Minor rows): the Chat Completions streaming loop now re-checks the request signal in front of every buffered item of a frame — the text item after a reasoning item, each tool-call partial inside the per-item loop, and the usage item — because a consumer that takes the first item, cancels and pulls the next one resumes this generator inside the same iteration, where the top-of-loop guard has already run. The three stream-open awaits (Anthropic /v1/messages, Responses /v1/responses and chat completions) now go through settleOnAbort with the signal still handed to the SDK, so a 429 with Retry-After plus a caller cancel no longer holds the pending first next() and the bridge cleanup until the sleep ends. Regression evidence: one parameterized test for the three stream-open races plus three manual-iteration tests that abort between two items of one frame (the buffered-text variant also asserts the bridge listener is detached by reference). Negative controls: removing each open wrapper fails exactly that format's row (1 failed | 216 passed each), disabling each buffered-item guard fails exactly that item's test, and reverting the OpenAI-path fixture key from opencodeGoModelId to the ignored apiModelId fails the five assertions that now pin model "glm-5.1" instead of expect.any(String). The parked-lookup test releases its gate in a finally so an assertion throw cannot strand the promise the provider awaits; measured with a probe: a release placed after the throwing assertion leaves the promise unresolved, the same release in a finally settles it.

Verification on this round: vitest 217 passed (217) in declaration order and with --sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical (a prune run over the two unit files reported zero count decreases); prettier 3.9.10 --check: clean.

Review round 4 (CodeRabbit pre-merge checks, one Major and nine Minor rows, handled in a single pass): the
Responses and Anthropic helpers no longer let a normally-ending SDK iterator read as a completed turn. The
Responses helper re-checks the bridged signal after processResponsesApiStream returns; the Anthropic helper
re-checks it at the top of each event dispatch, between the separator item and the block body of an indexed
content_block_start, and after the loop before the terminal cost chunk, so a cancel cannot emit the rest of
an event or bill a turn the caller already cancelled. Four tests drive the shape the pinned SDKs actually
produce - hand the consumer one item, cancel, then let the mock iterator report done instead of throwing -
and each one also runs the identical fixture with a live caller signal, which still delivers its text and
its terminal cost. Negative controls, each against the full suite: the Responses post-stream check (1 failed
| 223 passed), the Anthropic after-loop check (killed by the test that cancels after the last event was
delivered), the event-dispatch check (killed by the quiet-close test) and the separator checks (killed by the
two-yields-of-one-event test) each fail their own test and nothing else that matters.
The Responses pre-stream abort test no longer certifies itself through the provider's own catch: the mock
captures the signal the SDK actually received and then throws a plain failure, so the only evidence left is
that the captured signal is an AbortSignal that had already flipped; handing the SDK an unrelated signal
instead of the bridge fails seven tests, including that one. The timeout matrix now pins signal identity
rather than signal type - with no usable budget the SDK must hold the caller's own signal, with a usable one
it must hold the merged deadline - and a new parameterized test parks each format's request under a 5000 ms
budget, cancels the caller long before the deadline and requires the merged signal to flip and the completion
to reject with the contract AbortError; replacing the merged deadline with the caller's own signal on the
chat-completions completion fails 26 tests, including those rows. Three tests that polled for readiness
before observing the rejection now attach the handler when the promise is created, so a model lookup or
stream open that rejects during the poll cannot go unobserved.
Verification on this round: vitest 224 passed (224) in declaration order and with --sequence.shuffle; tsc
--noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without
--prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical (a prune run over the two unit
files found zero decreases, so the rewritten file was reverted); prettier 3.9.10 --check: clean.

Review round 5 (mutation sticky at d4ce1ce: blocking 23, advisories 0): this round adds no production lines. Three
tests were added, each aimed at a variant the sticky lists: a cancel between the separator and the body of an indexed
thinking block (kills the ConditionalExpression -> false variant at opencode-go.ts:796 and puts line 797 under coverage),
and one run per streaming format that passes no abort signal at all, so every guard in the helper is exercised with an
absent caller signal. Measured against the suite: each of the 17 StringLiteral -> "" rows (357, 380, 391, 407, 424, 567,
574, 626, 717, 725, 743, 797, 809, 858, 976, 1046, 1104) leaves 227/227 green, and each of the 5 OptionalChaining rows
(625, 742, 796, 808, 857) leaves 227/227 green. The reason is structural, not a matter of unasserted detail: at the
OptionalChaining lines the operand is the request-local signal that bridgeExternalAbortSignal/mergeAbortSignalAndTimeout
always hand to the SDK, so it is never nullish there, and an inner createAbortError is replaced by the enclosing catch's
own unmutated literal (for example the stream-open catch at 719 re-throwing at 725, and the completion catch at 981
re-throwing at 992), so the tests that do assert the exact contract message still see "The Opencode Go request was
aborted". The one variant that is observably different is now killed: ConditionalExpression -> false at 796 fails the new
thinking test (1 failed | 226 skipped) where it left the previous suite green.
Verification on this round: vitest 227 passed (227) in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0, with
eslint-suppressions.json unchanged because --prune-suppressions on the two unit files reported no count change; prettier
3.9.10 --check: clean.

Review round 6 (ask: kill the StringLiteral family with test-side message assertions before anything else, no new
production code). The spec's two remaining name-only assertions now pin the message too (spec:3824 and spec:3867, in the
two "bounds %s model resolution by the request timeout" groups), so every name assertion in the file carries the contract
message. That changed no survivor, and the reason is worth recording: with the message pinned everywhere, each of the 17
StringLiteral -> "" rows still leaves 227/227 green, because the message those tests read is produced by an enclosing
catch that throws its own unmutated createAbortError("Opencode Go") - the createMessage-level catch at :279 and the Chat
Completions stream helper's catch at :431 - and blanking either of those two literals fails 8 and 7 tests respectively,
while blanking any guard or race label fails none. The five OptionalChaining rows are equivalent for a separate reason:
the streaming helpers are always handed bridgedSignal ?? new AbortController().signal at :260, so their operand is never
nullish; with all five optional chains removed at once the suite is still 227/227, including the two runs that pass no
caller signal at all. No production line changed in either of the last two rounds; the provider blob is unchanged at
970de27.
Verification on this round: vitest 227 passed (227) in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with
eslint-suppressions.json unchanged; prettier 3.9.10 --check: clean.

Review round 7 (authorized: the pre-yield cancel check on the Responses path - one guard, one helper, one push, no
gateway propagation). `streamResponsesMessage` now hands the shared transform an iterator whose
`next()` reports the stream ended when the bridged signal is already aborted, so a pull that lands after the
caller cancelled can no longer deliver the event the pinned decoder had already buffered; the after-loop guard then
produces the contract AbortError. The helper's cleanup forward (`return: streamIterator.return?.bind(streamIterator)`)
preserves the previous delegation behaviour - an early consumer exit still closes the SDK iterator twice, as the
pre-existing cleanup test asserts - and stays callable when the source iterator implements no `return` at all. This
helper's signal parameter is now typed `AbortSignal` (`createMessage` supplies
`bridgedSignal ?? new AbortController().signal`), which is why the after-loop guard no longer needs its optional
chain. Nothing was added to the three gateway helpers, as instructed.

Two tests carry it: the buffered-completion fixture (text delta and `response.completed` from one read, take the
delta, cancel, require the rejection and no usage item) and a next-only source iterator, which proves the cleanup
forward must not assume `return` exists. Controls: against the pre-change provider the buffered fixture fails with
'expected undefined to match object { name: AbortError }' - today the usage chunk is delivered - so this was an
uncovered gap, not a restatement of covered behaviour. For the new code: the pull guard's
`ConditionalExpression -> false` fails exactly the two new tests and `-> true` fails 15; the
`OptionalChaining` on the cleanup forward fails the next-only test; neutering the after-loop guard now fails 3
tests including the buffered fixture, which is the variant that fixture kills.

Verification on this round: vitest 229 passed (229) in declaration order and with `--sequence.shuffle`;
`tsc --noEmit -p tsconfig.json` from `src`: zero errors;`eslint . --ext=ts --max-warnings=0` without
`--prune-suppressions`: exit 0 with `eslint-suppressions.json` unchanged and`--prune-suppressions` reporting
no decrease; prettier 3.9.10 `--check`: clean. Against merge-base `75a93a9d9acc`: opencode-go.spec.ts +2543/-200=2743, opencode-go.ts +390/-91=481 =
3224 a+d.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
…ateway

Each provider's createMessage bridges metadata.abortSignal to a
per-request AbortController (Bedrock pattern: pre-aborted guard,
{ once: true } listener, detached on completion so a task-scoped
signal does not accumulate listeners) and runs model resolution inside
the shared resolveModelWithAbort cancellation scope; aborted requests
(pre-aborted, mid-resolution, mid-stream) normalize to the provider
AbortError while non-abort failures propagate or wrap unchanged.
completePrompt forwards abortSignal/timeoutMs to the OpenAI SDK
(timeoutMs <= 0 omits the SDK timeout option); aborted completions and
APIConnectionTimeoutError normalize to the provider AbortError (series
standard).

Zoo Gateway places the entry fast-fail before ensureAuthenticated() so
a pre-aborted task surfaces the AbortError instead of an auth failure
(pinned by an unauthenticated pre-abort test).

Unit 3/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util and opencode-go units. Three sibling OpenAI-SDK gateway
providers with an identical abort-wiring shape are kept as one unit to
avoid tripling the review surface for mechanically identical changes
(a+d soft-cap rationale per the split budget; the mutation gate is
measured on the unit delta and is green).

Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on b1bd578, disposition recorded on each thread): each provider now races the SDK promise it awaits against the bridged signal through `settleOnAbort` — unbound's stream create and its completion, vercel-ai-gateway's completion, zoo-gateway's completion — because the OpenAI SDK sleeps out a Retry-After / retry delay without observing the signal, and the post-await `bridgedSignal?.aborted` guards that used to trail those awaits are gone, since `raceAbort` rejects synchronously at `abort()` and nothing after the await can read the flag first. Each streaming loop breaks on the caller signal at the top of an iteration, re-checks it before emitting a just-received chunk, and checks it once more before the generator returns, so a cancel the SDK swallows — the iterator ends normally without a throw — can neither emit the rest of a chunk nor report a partial turn as completed. The caller's signal is bridged rather than handed to the SDK directly and the bridge is disposed in `finally`; the detach tests name the bridge's listener by registration position, require it to differ from the model-lookup race's callback, and assert both removals by reference. Absence proofs drain the provider's own continuation instead of sleeping.

The two Opencode Go files are Zoo-Code-Org#1652's blobs, byte for byte: provider `23348a501e9f31d0c72bffa6eefb6030bb6149a3`, spec `5dbe3382d1f1d6af8d22e7637a088c546988ef18`; `git diff df29307 -- <those two paths>` is empty with `core.autocrlf=false` and the blob ids are re-verified against this commit. Once Zoo-Code-Org#1652 lands on main this unit rebases onto it and both files drop out of this diff.

Review round 2 (CodeRabbit pre-merge checks): each gateway completePrompt now pins the disabled-budget boundary at -5 — the SDK options carry no timeout key and the bridged per-request signal is still handed over (the zoo variant is one of the tests that also catches a dropped signal arm). The ported Opencode Go spec brings its own parameterized timeout-option test per wire format: NaN, Infinity and -5 omit the option, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards MAX_TIMEOUT_MS, and the caller signal is asserted on every row. Those rows kill the forward arms at opencode-go.ts:886/944/1027 in both directions (deleting the arm fails two rows per format, forcing it always-forward fails the three disabled-budget rows) and the toSdkTimeoutMs call sites; forcing the gateway arms to always forward fails the new -5 rows on all three providers.

Verification on this tree: vitest over the opencode-go, unbound, vercel-ai-gateway and zoo-gateway specs from `src` — 411 passed (411) in declaration order and 411 passed with `--sequence.shuffle`; `tsc --noEmit -p tsconfig.json` leaves only the two known donor-store `integrations/misc/export-markdown.ts` rows; `eslint . --ext=ts --max-warnings=0` without `--prune-suppressions` exits 0 with `src/eslint-suppressions.json` byte-identical (a prune run over the eight touched paths reported zero count decreases); prettier 3.9.10 `--check` clean on the staged blobs extracted with `core.autocrlf=false`. Negative controls per new guard: flipping each added condition or deleting each added arm fails the specific guard test that names it — 1 failed | 195 passed for either Opencode Go chat-stream arm, 1 failed for the Responses pre-stream condition, 2 failed for the Anthropic stream condition, and the same shape for the gateway guards.

Review round 3: the mutation-diff report at 313cf0e listed 20 blocking rows (21 survived mutants plus one uncovered arm) over 338 changed executable lines. Five of them are now killed by four tests added here: unbound.ts:349 and vercel-ai-gateway.ts:280 (detachExternalAbortSignal() -> ; in the completePrompt finally) by a detach test per provider that identifies the bridge listener by the { once: true } registration and asserts its removal by reference; zoo-gateway.ts:337 (classification gate -> false) by a streaming test that feeds a name-only AbortError with a live-but-not-aborted caller signal and asserts the contract identity, that the add-credits notification never ran, and that nothing was logged; zoo-gateway.ts:346 in both directions by a streaming test where the notification itself rejects while the caller signal is live (the log must name the surfacing failure and the original 402 must still reach the caller) plus the existing cancel-while-prompt-open test, which also puts that line under coverage. Each of those four mutants was applied alone and restored: 1 failed | 414 passed, killed by the named test in every case. The remaining sixteen rows are all StringLiteral -> "" on a provider-name label inside createAbortError/settleOnAbort/rejectOnAbort; each one sits inside a catch or race whose enclosing handler re-throws with its own unmutated literal, so the provider-visible error name and message are identical through the public API and no assertion can distinguish the mutant from the code (measured: full suite green with each mutant in place). No Stryker directive was added; the equivalence is argued in the PR discussion for a maintainer to weigh.

Verification on this tree: vitest 421 passed (421) across the four provider specs in declaration order and with --sequence.shuffle (the six new opencode-go tests arrive with the re-ported blobs); tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical; prettier 3.9.10 --check on the touched files: clean. The opencode-go blobs are re-ported from df29307 and remain byte-identical to that head (git diff --quiet against it for those two paths: exit 0), so after a maintainer merges Zoo-Code-Org#1652 these lines drop out of this diff on rebase.

Review round 4 (CodeRabbit pre-merge checks, six Major and 26 Minor rows, handled in one pass): three sibling
stream loops no longer hand a cancelled turn their last item - Unbound re-checks the caller signal in front of
the text item of a frame whose reasoning item was already delivered, and both Vercel AI Gateway and Zoo Gateway
re-check it in front of the usage item of a frame whose text was already delivered, so a cancel between the two
items of one chunk rejects instead of emitting or billing the remainder. The three "does not emit the rest of a
tool-call chunk" tests are now consumer-driven (take the first partial, cancel, require the next call to reject
without building the second one) because the getter variant aborted before either partial existed and could not
tell a per-partial check from a per-frame check. Unbound's retained usage is typed as
OpenAI.Completions.CompletionUsage | undefined, which drops its @typescript-eslint/no-explicit-any suppression
from 3 to 2 (the only suppression change in this unit). The non-array tool_calls fixture now carries a truthy
value instead of null, so the Array.isArray check is what the test pins. The Zoo Gateway SDK-timeout
classification test no longer carries a 50 ms provider deadline, and the deadline test's mock refuses to run
without the per-request signal, so a provider that stops forwarding the deadline fails loudly instead of
throwing immediately. The two add-credits streaming tests wrap their whole body in a try/finally so the console
spy is restored even when an early assertion throws. The opencode-go provider and spec are the byte-identical
blobs from Zoo-Code-Org#1652 at d4ce1ce (opencode-go.ts 970de27, opencode-go.spec.ts 8c34bbb), which carry
the Responses/Anthropic quiet-close guards, the terminal-usage guard, the captured-SDK-signal assertions and
the merged-deadline cancel rows that close this unit's opencode-go rows; on rebase over the merged Zoo-Code-Org#1652 those
lines drop out.
Not changed in this unit, with the reasoning recorded on the threads: Unbound's timeout is enforced through the
merged deadline signal rather than response-body consumption (helper-side, tracked on Zoo-Code-Org#2486), the completion
races still return a response that won the race before the cancel, and the completion paths keep using the
shared mergeAbortSignalAndTimeout signal rather than a request-local bridge.
Verification on this round: vitest 431 passed (431) across the four provider specs in declaration order and with
--sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0
without --prune-suppressions: exit 0, with src/eslint-suppressions.json updated only for the unbound.ts decrease
(3 -> 2) that the prune run reported; prettier 3.9.10 --check: clean. Negative controls against the suite, each
disabling one guard: the Unbound text-item guard, the Vercel usage-item guard and the Zoo usage-item guard each
fail exactly their own new test (1 failed | 45, 56 and 103 passed respectively), the three per-partial guards
each fail exactly their rewritten tool-call test, dropping the Zoo completion's per-request signal arm fails the
seven timeout and abort-delivery tests that read it, and dropping the timeout arm fails the two option-forwarding
tests.

Review round 5 (mutation sticky at 41ba1fe: blocking 23, advisories 0): no production line was added or changed in
this round. The opencode-go provider and spec are re-ported byte-identical from Zoo-Code-Org#1652 at 40456d8 (blobs
970de27 and 4afc3ee), which carry the thinking-separator cancel test and the two no-abort-signal runs that
kill and explain the structural variants on that file. Every sibling row was measured by hand in this worktree: the label
mutants at unbound.ts:218/247/257/278/338 and vercel-ai-gateway.ts:136/168/185/267 leave their whole spec green
(46/46 and 57/57) because each inner createAbortError is replaced by the enclosing catch's own unmutated literal, while
mutating those catches' own labels (unbound.ts:224, 289, 349 and vercel-ai-gateway.ts:204, 213, 279) fails 3, 6, 5, 4, 1
and 5 tests - which is what proves the message the tests assert comes from the catch, not from the inner label. The zoo
labels (280, 308, 344) are killed outright by the abort-identity tests, and the zoo console-guard optional chain is
killed by two existing tests.
Verification on this round: vitest 434 passed (434) across the four provider specs in declaration order and with
--sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without
--prune-suppressions: exit 0 with eslint-suppressions.json carrying only the round-4 unbound.ts decrease (3 -> 2);
prettier 3.9.10 --check: clean across all eight unit files.

Review round 6: the two opencode-go files are re-ported byte-identical from Zoo-Code-Org#1652 at b51323d (blobs 970de27 and
2163ff1), which adds the two message assertions described there and no production line. Verification on this round:
vitest 434 passed (434) across the four provider specs in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with only the
round-4 unbound.ts decrease (3 -> 2) in eslint-suppressions.json; prettier 3.9.10 --check: clean across the eight unit
files. The unit's own content (excluding the 2847 a+d carried byte-identically from Zoo-Code-Org#1652, which drops out on merge plus
rebase) is 3198 a+d.

Review round 7: re-ported the two opencode-go blobs byte-identically from `371445df813b` (Zoo-Code-Org#1652 round 7), which
adds the authorized pre-yield cancel check on the Responses path and the two tests that carry it - the
buffered-completion fixture (text delta and `response.completed` from one read, take the delta, cancel, require
the rejection and no usage item) and the next-only source iterator that proves the cleanup forward must not assume
`return` exists. The three gateway helpers are untouched by that check, as instructed; series consistency of
the check is recorded as a follow-up on Zoo-Code-Org#2486 rather than folded into this unit.

Preflight reading (advisory, run incomplete, no scoring): the local Stryker preflight of the unit delta generated 402
mutants against the 400-mutant preflight limit in the previous round's run, and the added lines push that figure
higher; the run was therefore not scored, and `blocking:0` on the last completed report is an artifact of the
aborted preflight, not a clean mutation result - Zoo-Code-Org#1653's earlier completed head `41ba1fea0524` listed the same
12 `opencode-go.ts` StringLiteral rows as surviving with all three gateway specs present. No scored mutant of
this unit's own gateway code has been left without a disposition.
Decision requested (author/maintainer): either (a) split this unit further so each branch stays under the 400-mutant
preflight limit and the run can be scored, or (b) accept a reasoned narrow exclusion of the carried `opencode-go.ts`
rows from this unit's scoring on the ground that Zoo-Code-Org#1652 owns and scores those lines. Nothing here churns either unit to
force the count under 400.

Verification on this round: vitest 436 passed (436) across the four specs in declaration order and with
`--sequence.shuffle`; `tsc --noEmit -p tsconfig.json` from `src`: zero errors;`eslint . --ext=ts --max-warnings=0`
without `--prune-suppressions`: exit 0 with `eslint-suppressions.json` unchanged from this unit's own
`-1` decrease and `--prune-suppressions` reporting no further decrease; prettier 3.9.10 `--check`: clean.
Against merge-base `75a93a9d9acc`: opencode-go.spec.ts +2543/-200=2743, unbound.spec.ts +1138/-4=1142, vercel-ai-gateway.spec.ts +771/-2=773, zoo-gateway.spec.ts +820/-1=821, opencode-go.ts +390/-91=481, unbound.ts +142/-36=178, vercel-ai-gateway.ts +144/-42=186, zoo-gateway.ts +87/-9=96, eslint-suppressions.json +1/-1=2 = 6422 a+d, of which 3224 is the
byte-identical carry of Zoo-Code-Org#1652's diff, leaving 3198 this unit's own.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
- createMessage: bridge metadata.abortSignal to a per-request
  AbortController (Bedrock pattern: pre-aborted guard, once-listener,
  detached on completion so a task-scoped signal does not accumulate
  listeners); model resolution runs inside the shared
  resolveModelWithAbort cancellation scope (pre-aborted fast-fail,
  mid-resolution race)
- aborted/timeout requests normalize to the provider AbortError on all
  three wire formats (anthropic /v1/messages, responses /v1/responses,
  openai chat completions), both pre-stream and mid-stream; non-abort
  failures keep the wrapped "Opencode Go completion error:" identity
- the OpenAI branch runs message conversion and request construction
  inside the same cleanup scope as the Anthropic and Responses branches,
  so a conversion failure (e.g. an unstringifiable tool input) still
  detaches the bridged abort listener (CodeRabbit fix on this PR)
- completePrompt: forwards abortSignal/timeoutMs to all three SDK
  paths (timeoutMs <= 0 omits the SDK timeout option, since the SDK
  treats timeout: 0 as an immediate abort); aborted completions and
  APIConnectionTimeoutError/APITimeoutError normalize to the provider
  AbortError (series standard)

The inner pre-stream provider-name literal is provably equivalent
and documented as such in the PR body; no Stryker disable directive is
added anywhere in the tree. createMessage's outer catch applies the
identical isRequestAborted check to the same controller signal and
re-standardizes the error, so the inner layer's only unique behavior is
the non-abort completion-error wrap (stays kill-tested), and the
abort-normalization condition beside that literal is killed by a
live-signal delivery added in the second review round.

The cleanup-scope re-indentation made the gate instrument pre-existing
request-construction lines for the first time; their previously
unobservable mutants are kill-tested: R1 tool-result merge shape for
preserveReasoning models and the plain shape for non-preserveReasoning
models, the includeMaxTokens on/off branches with a ceiling-bounded
model, and the parallel_tool_calls default/explicit-false.

Unit 2/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util unit.
Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on 41ef0e0): the Chat Completions stream loop now
breaks on the request signal at the top of each iteration and re-checks that signal after
the loop, so an SDK that swallows the body-read abort and closes the iterator normally
cannot report a cancelled turn as completed. The new test parks the iterator after the
first chunk, hands back a getter-counting chunk once the caller cancels, and asserts both
the standardized AbortError and zero post-cancel chunk reads; flipping either guard to a
false condition fails exactly that test (1 failed | 195 passed). The Responses pre-stream
abort arm had no live-signal delivery, so one is added: with no caller signal nothing
aborts, only the error-name arm can normalize, and the ConditionalExpression mutant dies
with it (same control). The provider-name literals at the two stream catches and at the
three completePrompt races were re-measured: each survives the full 196-test suite, which
matches the equivalence argument above. The detach tests now require exactly two abort
registrations on the caller's signal, name the bridge's by position, require it to differ
from the model-resolution race's callback, and assert both removals by reference in that
order. The SDK abort and timeout deliveries now reject from inside the SDK mock with no
caller signal (the automocked openai module's error classes are not Error instances, so
the name/message arm is exercised with the real class taken from the actual module), a
caller cancel landing inside the SDK call is classified across all three formats, and the
parked-lookup gate is the typed getModels fetcher rather than a spy on the private
resolveModel.

Review round 2 (CodeRabbit pre-merge checks): completePrompt gained a parameterized timeout-option
test per wire format (Anthropic messages, Responses, chat completions) that proves each call site
applies the shared hasUsableTimeout/toSdkTimeoutMs contract rather than only testing the helper:
NaN, Infinity and -5 leave no timeout key, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards
MAX_TIMEOUT_MS, and every row also asserts the caller's signal reached the SDK options, so dropping
the budget can never drop the cancel. Controls: deleting the forward arm fails two rows per format,
forcing it to always forward fails the three disabled-budget rows, and replacing
toSdkTimeoutMs(timeoutMs) with the raw value fails exactly the two forwarding rows. The five
provider-name literals on the abort paths were re-measured at this head: all five survive the full
211-test suite, which is the measured half of the equivalence argument in the PR body.

Verification on this tree: src tsc --noEmit exit 0 apart from the two known donor-store
integrations/misc/export-markdown.ts rows; vitest 211 passed (211) in declaration order and
in shuffled order; eslint . --ext=ts --max-warnings=0 without --prune-suppressions exit 0
with src/eslint-suppressions.json byte-identical (a prune run found zero decreases for this
unit); prettier 3.9.10 --check clean on the staged blobs extracted with core.autocrlf=false.

Review round 3 (CodeRabbit pre-merge checks, six Minor rows): the Chat Completions streaming loop now re-checks the request signal in front of every buffered item of a frame — the text item after a reasoning item, each tool-call partial inside the per-item loop, and the usage item — because a consumer that takes the first item, cancels and pulls the next one resumes this generator inside the same iteration, where the top-of-loop guard has already run. The three stream-open awaits (Anthropic /v1/messages, Responses /v1/responses and chat completions) now go through settleOnAbort with the signal still handed to the SDK, so a 429 with Retry-After plus a caller cancel no longer holds the pending first next() and the bridge cleanup until the sleep ends. Regression evidence: one parameterized test for the three stream-open races plus three manual-iteration tests that abort between two items of one frame (the buffered-text variant also asserts the bridge listener is detached by reference). Negative controls: removing each open wrapper fails exactly that format's row (1 failed | 216 passed each), disabling each buffered-item guard fails exactly that item's test, and reverting the OpenAI-path fixture key from opencodeGoModelId to the ignored apiModelId fails the five assertions that now pin model "glm-5.1" instead of expect.any(String). The parked-lookup test releases its gate in a finally so an assertion throw cannot strand the promise the provider awaits; measured with a probe: a release placed after the throwing assertion leaves the promise unresolved, the same release in a finally settles it.

Verification on this round: vitest 217 passed (217) in declaration order and with --sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical (a prune run over the two unit files reported zero count decreases); prettier 3.9.10 --check: clean.

Review round 4 (CodeRabbit pre-merge checks, one Major and nine Minor rows, handled in a single pass): the
Responses and Anthropic helpers no longer let a normally-ending SDK iterator read as a completed turn. The
Responses helper re-checks the bridged signal after processResponsesApiStream returns; the Anthropic helper
re-checks it at the top of each event dispatch, between the separator item and the block body of an indexed
content_block_start, and after the loop before the terminal cost chunk, so a cancel cannot emit the rest of
an event or bill a turn the caller already cancelled. Four tests drive the shape the pinned SDKs actually
produce - hand the consumer one item, cancel, then let the mock iterator report done instead of throwing -
and each one also runs the identical fixture with a live caller signal, which still delivers its text and
its terminal cost. Negative controls, each against the full suite: the Responses post-stream check (1 failed
| 223 passed), the Anthropic after-loop check (killed by the test that cancels after the last event was
delivered), the event-dispatch check (killed by the quiet-close test) and the separator checks (killed by the
two-yields-of-one-event test) each fail their own test and nothing else that matters.
The Responses pre-stream abort test no longer certifies itself through the provider's own catch: the mock
captures the signal the SDK actually received and then throws a plain failure, so the only evidence left is
that the captured signal is an AbortSignal that had already flipped; handing the SDK an unrelated signal
instead of the bridge fails seven tests, including that one. The timeout matrix now pins signal identity
rather than signal type - with no usable budget the SDK must hold the caller's own signal, with a usable one
it must hold the merged deadline - and a new parameterized test parks each format's request under a 5000 ms
budget, cancels the caller long before the deadline and requires the merged signal to flip and the completion
to reject with the contract AbortError; replacing the merged deadline with the caller's own signal on the
chat-completions completion fails 26 tests, including those rows. Three tests that polled for readiness
before observing the rejection now attach the handler when the promise is created, so a model lookup or
stream open that rejects during the poll cannot go unobserved.
Verification on this round: vitest 224 passed (224) in declaration order and with --sequence.shuffle; tsc
--noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without
--prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical (a prune run over the two unit
files found zero decreases, so the rewritten file was reverted); prettier 3.9.10 --check: clean.

Review round 5 (mutation sticky at d4ce1ce: blocking 23, advisories 0): this round adds no production lines. Three
tests were added, each aimed at a variant the sticky lists: a cancel between the separator and the body of an indexed
thinking block (kills the ConditionalExpression -> false variant at opencode-go.ts:796 and puts line 797 under coverage),
and one run per streaming format that passes no abort signal at all, so every guard in the helper is exercised with an
absent caller signal. Measured against the suite: each of the 17 StringLiteral -> "" rows (357, 380, 391, 407, 424, 567,
574, 626, 717, 725, 743, 797, 809, 858, 976, 1046, 1104) leaves 227/227 green, and each of the 5 OptionalChaining rows
(625, 742, 796, 808, 857) leaves 227/227 green. The reason is structural, not a matter of unasserted detail: at the
OptionalChaining lines the operand is the request-local signal that bridgeExternalAbortSignal/mergeAbortSignalAndTimeout
always hand to the SDK, so it is never nullish there, and an inner createAbortError is replaced by the enclosing catch's
own unmutated literal (for example the stream-open catch at 719 re-throwing at 725, and the completion catch at 981
re-throwing at 992), so the tests that do assert the exact contract message still see "The Opencode Go request was
aborted". The one variant that is observably different is now killed: ConditionalExpression -> false at 796 fails the new
thinking test (1 failed | 226 skipped) where it left the previous suite green.
Verification on this round: vitest 227 passed (227) in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0, with
eslint-suppressions.json unchanged because --prune-suppressions on the two unit files reported no count change; prettier
3.9.10 --check: clean.

Review round 6 (ask: kill the StringLiteral family with test-side message assertions before anything else, no new
production code). The spec's two remaining name-only assertions now pin the message too (spec:3824 and spec:3867, in the
two "bounds %s model resolution by the request timeout" groups), so every name assertion in the file carries the contract
message. That changed no survivor, and the reason is worth recording: with the message pinned everywhere, each of the 17
StringLiteral -> "" rows still leaves 227/227 green, because the message those tests read is produced by an enclosing
catch that throws its own unmutated createAbortError("Opencode Go") - the createMessage-level catch at :279 and the Chat
Completions stream helper's catch at :431 - and blanking either of those two literals fails 8 and 7 tests respectively,
while blanking any guard or race label fails none. The five OptionalChaining rows are equivalent for a separate reason:
the streaming helpers are always handed bridgedSignal ?? new AbortController().signal at :260, so their operand is never
nullish; with all five optional chains removed at once the suite is still 227/227, including the two runs that pass no
caller signal at all. No production line changed in either of the last two rounds; the provider blob is unchanged at
970de27.
Verification on this round: vitest 227 passed (227) in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with
eslint-suppressions.json unchanged; prettier 3.9.10 --check: clean.

Review round 7 (authorized: the pre-yield cancel check on the Responses path - one guard, one helper, one push, no
gateway propagation). `streamResponsesMessage` now hands the shared transform an iterator whose
`next()` reports the stream ended when the bridged signal is already aborted, so a pull that lands after the
caller cancelled can no longer deliver the event the pinned decoder had already buffered; the after-loop guard then
produces the contract AbortError. The helper's cleanup forward (`return: streamIterator.return?.bind(streamIterator)`)
preserves the previous delegation behaviour - an early consumer exit still closes the SDK iterator twice, as the
pre-existing cleanup test asserts - and stays callable when the source iterator implements no `return` at all. This
helper's signal parameter is now typed `AbortSignal` (`createMessage` supplies
`bridgedSignal ?? new AbortController().signal`), which is why the after-loop guard no longer needs its optional
chain. Nothing was added to the three gateway helpers, as instructed.

Two tests carry it: the buffered-completion fixture (text delta and `response.completed` from one read, take the
delta, cancel, require the rejection and no usage item) and a next-only source iterator, which proves the cleanup
forward must not assume `return` exists. Controls: against the pre-change provider the buffered fixture fails with
'expected undefined to match object { name: AbortError }' - today the usage chunk is delivered - so this was an
uncovered gap, not a restatement of covered behaviour. For the new code: the pull guard's
`ConditionalExpression -> false` fails exactly the two new tests and `-> true` fails 15; the
`OptionalChaining` on the cleanup forward fails the next-only test; neutering the after-loop guard now fails 3
tests including the buffered fixture, which is the variant that fixture kills.

Verification on this round: vitest 229 passed (229) in declaration order and with `--sequence.shuffle`;
`tsc --noEmit -p tsconfig.json` from `src`: zero errors;`eslint . --ext=ts --max-warnings=0` without
`--prune-suppressions`: exit 0 with `eslint-suppressions.json` unchanged and`--prune-suppressions` reporting
no decrease; prettier 3.9.10 `--check`: clean. Against merge-base `75a93a9d9acc`: opencode-go.spec.ts +2543/-200=2743, opencode-go.ts +390/-91=481 =
3224 a+d.

Review round 8 (CodeRabbit review 5982073495, line 3872 wall-clock row): the deadline test no longer measures elapsed time.
It parks the SDK promise so it never settles, then asserts the observed abort reason (name AbortError plus the exact contract
message), that the signal handed to the SDK really is an AbortSignal and had already flipped, and that a settled-flag attached
to the parked promise is still false, so the rejection can only come from the provider's race; the 1s bound is gone (it was
the assertion a stalled worker could fail) and the duplicated message assertion was deduplicated. The caller-cancel-under-
budget test now reads the SDK-facing signal immediately before controller.abort() and immediately after it, with no await
between the two reads, and the redundant post-settlement read was removed.

Shared-deadline row: a new test parks the catalog fetcher, releases it, waits for the dispatch, and then asserts by reference
identity that the dispatched request runs on the caller's own cancellation scope (with no timeoutMs, mergeAbortSignalAndTimeout
returns the caller's signal unchanged at utils/abort-signal.ts:42-44), flips it, requires the flip on the SDK-facing signal with
no await in between, and requires the completion to reject with the contract AbortError while the parked SDK promise is still
unsettled. Controls: replacing signal: resolutionAbortSignal in the chat-completions dispatch with a fresh controller fails
exactly that test (AssertionError: expected AbortSignal { aborted: false } to be AbortSignal { aborted: false }, 1 failed |
229 skipped), and forcing the merge's timeout arm off fails all three rows of the deadline test (3 failed). Signal identity for
the timeout shapes was already pinned by assertTimeoutOption (spec:4056), which requires the caller's own object with no usable
budget and a merged deadline distinct from it with a usable one.

Verification on this round: vitest 230 passed (230) in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with
eslint-suppressions.json unchanged (--prune-suppressions on the spec reported no count decrease, so the rewritten file was
reverted); prettier 3.9.10 --check: clean. No production line changed in this round; the provider blob is unchanged at
bb1acfe. Against merge-base 75a93a9: opencode-go.spec.ts +2597/-191=2788, opencode-go.ts +390/-91=481 = 3269 a+d.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
…ateway

Each provider's createMessage bridges metadata.abortSignal to a
per-request AbortController (Bedrock pattern: pre-aborted guard,
{ once: true } listener, detached on completion so a task-scoped
signal does not accumulate listeners) and runs model resolution inside
the shared resolveModelWithAbort cancellation scope; aborted requests
(pre-aborted, mid-resolution, mid-stream) normalize to the provider
AbortError while non-abort failures propagate or wrap unchanged.
completePrompt forwards abortSignal/timeoutMs to the OpenAI SDK
(timeoutMs <= 0 omits the SDK timeout option); aborted completions and
APIConnectionTimeoutError normalize to the provider AbortError (series
standard).

Zoo Gateway places the entry fast-fail before ensureAuthenticated() so
a pre-aborted task surfaces the AbortError instead of an auth failure
(pinned by an unauthenticated pre-abort test).

Unit 3/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util and opencode-go units. Three sibling OpenAI-SDK gateway
providers with an identical abort-wiring shape are kept as one unit to
avoid tripling the review surface for mechanically identical changes
(a+d soft-cap rationale per the split budget; the mutation gate is
measured on the unit delta and is green).

Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on b1bd578, disposition recorded on each thread): each provider now races the SDK promise it awaits against the bridged signal through `settleOnAbort` — unbound's stream create and its completion, vercel-ai-gateway's completion, zoo-gateway's completion — because the OpenAI SDK sleeps out a Retry-After / retry delay without observing the signal, and the post-await `bridgedSignal?.aborted` guards that used to trail those awaits are gone, since `raceAbort` rejects synchronously at `abort()` and nothing after the await can read the flag first. Each streaming loop breaks on the caller signal at the top of an iteration, re-checks it before emitting a just-received chunk, and checks it once more before the generator returns, so a cancel the SDK swallows — the iterator ends normally without a throw — can neither emit the rest of a chunk nor report a partial turn as completed. The caller's signal is bridged rather than handed to the SDK directly and the bridge is disposed in `finally`; the detach tests name the bridge's listener by registration position, require it to differ from the model-lookup race's callback, and assert both removals by reference. Absence proofs drain the provider's own continuation instead of sleeping.

The two Opencode Go files are Zoo-Code-Org#1652's blobs, byte for byte: provider `23348a501e9f31d0c72bffa6eefb6030bb6149a3`, spec `5dbe3382d1f1d6af8d22e7637a088c546988ef18`; `git diff df29307 -- <those two paths>` is empty with `core.autocrlf=false` and the blob ids are re-verified against this commit. Once Zoo-Code-Org#1652 lands on main this unit rebases onto it and both files drop out of this diff.

Review round 2 (CodeRabbit pre-merge checks): each gateway completePrompt now pins the disabled-budget boundary at -5 — the SDK options carry no timeout key and the bridged per-request signal is still handed over (the zoo variant is one of the tests that also catches a dropped signal arm). The ported Opencode Go spec brings its own parameterized timeout-option test per wire format: NaN, Infinity and -5 omit the option, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards MAX_TIMEOUT_MS, and the caller signal is asserted on every row. Those rows kill the forward arms at opencode-go.ts:886/944/1027 in both directions (deleting the arm fails two rows per format, forcing it always-forward fails the three disabled-budget rows) and the toSdkTimeoutMs call sites; forcing the gateway arms to always forward fails the new -5 rows on all three providers.

Verification on this tree: vitest over the opencode-go, unbound, vercel-ai-gateway and zoo-gateway specs from `src` — 411 passed (411) in declaration order and 411 passed with `--sequence.shuffle`; `tsc --noEmit -p tsconfig.json` leaves only the two known donor-store `integrations/misc/export-markdown.ts` rows; `eslint . --ext=ts --max-warnings=0` without `--prune-suppressions` exits 0 with `src/eslint-suppressions.json` byte-identical (a prune run over the eight touched paths reported zero count decreases); prettier 3.9.10 `--check` clean on the staged blobs extracted with `core.autocrlf=false`. Negative controls per new guard: flipping each added condition or deleting each added arm fails the specific guard test that names it — 1 failed | 195 passed for either Opencode Go chat-stream arm, 1 failed for the Responses pre-stream condition, 2 failed for the Anthropic stream condition, and the same shape for the gateway guards.

Review round 3: the mutation-diff report at 313cf0e listed 20 blocking rows (21 survived mutants plus one uncovered arm) over 338 changed executable lines. Five of them are now killed by four tests added here: unbound.ts:349 and vercel-ai-gateway.ts:280 (detachExternalAbortSignal() -> ; in the completePrompt finally) by a detach test per provider that identifies the bridge listener by the { once: true } registration and asserts its removal by reference; zoo-gateway.ts:337 (classification gate -> false) by a streaming test that feeds a name-only AbortError with a live-but-not-aborted caller signal and asserts the contract identity, that the add-credits notification never ran, and that nothing was logged; zoo-gateway.ts:346 in both directions by a streaming test where the notification itself rejects while the caller signal is live (the log must name the surfacing failure and the original 402 must still reach the caller) plus the existing cancel-while-prompt-open test, which also puts that line under coverage. Each of those four mutants was applied alone and restored: 1 failed | 414 passed, killed by the named test in every case. The remaining sixteen rows are all StringLiteral -> "" on a provider-name label inside createAbortError/settleOnAbort/rejectOnAbort; each one sits inside a catch or race whose enclosing handler re-throws with its own unmutated literal, so the provider-visible error name and message are identical through the public API and no assertion can distinguish the mutant from the code (measured: full suite green with each mutant in place). No Stryker directive was added; the equivalence is argued in the PR discussion for a maintainer to weigh.

Verification on this tree: vitest 421 passed (421) across the four provider specs in declaration order and with --sequence.shuffle (the six new opencode-go tests arrive with the re-ported blobs); tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical; prettier 3.9.10 --check on the touched files: clean. The opencode-go blobs are re-ported from df29307 and remain byte-identical to that head (git diff --quiet against it for those two paths: exit 0), so after a maintainer merges Zoo-Code-Org#1652 these lines drop out of this diff on rebase.

Review round 4 (CodeRabbit pre-merge checks, six Major and 26 Minor rows, handled in one pass): three sibling
stream loops no longer hand a cancelled turn their last item - Unbound re-checks the caller signal in front of
the text item of a frame whose reasoning item was already delivered, and both Vercel AI Gateway and Zoo Gateway
re-check it in front of the usage item of a frame whose text was already delivered, so a cancel between the two
items of one chunk rejects instead of emitting or billing the remainder. The three "does not emit the rest of a
tool-call chunk" tests are now consumer-driven (take the first partial, cancel, require the next call to reject
without building the second one) because the getter variant aborted before either partial existed and could not
tell a per-partial check from a per-frame check. Unbound's retained usage is typed as
OpenAI.Completions.CompletionUsage | undefined, which drops its @typescript-eslint/no-explicit-any suppression
from 3 to 2 (the only suppression change in this unit). The non-array tool_calls fixture now carries a truthy
value instead of null, so the Array.isArray check is what the test pins. The Zoo Gateway SDK-timeout
classification test no longer carries a 50 ms provider deadline, and the deadline test's mock refuses to run
without the per-request signal, so a provider that stops forwarding the deadline fails loudly instead of
throwing immediately. The two add-credits streaming tests wrap their whole body in a try/finally so the console
spy is restored even when an early assertion throws. The opencode-go provider and spec are the byte-identical
blobs from Zoo-Code-Org#1652 at d4ce1ce (opencode-go.ts 970de27, opencode-go.spec.ts 8c34bbb), which carry
the Responses/Anthropic quiet-close guards, the terminal-usage guard, the captured-SDK-signal assertions and
the merged-deadline cancel rows that close this unit's opencode-go rows; on rebase over the merged Zoo-Code-Org#1652 those
lines drop out.
Not changed in this unit, with the reasoning recorded on the threads: Unbound's timeout is enforced through the
merged deadline signal rather than response-body consumption (helper-side, tracked on Zoo-Code-Org#2486), the completion
races still return a response that won the race before the cancel, and the completion paths keep using the
shared mergeAbortSignalAndTimeout signal rather than a request-local bridge.
Verification on this round: vitest 431 passed (431) across the four provider specs in declaration order and with
--sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0
without --prune-suppressions: exit 0, with src/eslint-suppressions.json updated only for the unbound.ts decrease
(3 -> 2) that the prune run reported; prettier 3.9.10 --check: clean. Negative controls against the suite, each
disabling one guard: the Unbound text-item guard, the Vercel usage-item guard and the Zoo usage-item guard each
fail exactly their own new test (1 failed | 45, 56 and 103 passed respectively), the three per-partial guards
each fail exactly their rewritten tool-call test, dropping the Zoo completion's per-request signal arm fails the
seven timeout and abort-delivery tests that read it, and dropping the timeout arm fails the two option-forwarding
tests.

Review round 5 (mutation sticky at 41ba1fe: blocking 23, advisories 0): no production line was added or changed in
this round. The opencode-go provider and spec are re-ported byte-identical from Zoo-Code-Org#1652 at 40456d8 (blobs
970de27 and 4afc3ee), which carry the thinking-separator cancel test and the two no-abort-signal runs that
kill and explain the structural variants on that file. Every sibling row was measured by hand in this worktree: the label
mutants at unbound.ts:218/247/257/278/338 and vercel-ai-gateway.ts:136/168/185/267 leave their whole spec green
(46/46 and 57/57) because each inner createAbortError is replaced by the enclosing catch's own unmutated literal, while
mutating those catches' own labels (unbound.ts:224, 289, 349 and vercel-ai-gateway.ts:204, 213, 279) fails 3, 6, 5, 4, 1
and 5 tests - which is what proves the message the tests assert comes from the catch, not from the inner label. The zoo
labels (280, 308, 344) are killed outright by the abort-identity tests, and the zoo console-guard optional chain is
killed by two existing tests.
Verification on this round: vitest 434 passed (434) across the four provider specs in declaration order and with
--sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without
--prune-suppressions: exit 0 with eslint-suppressions.json carrying only the round-4 unbound.ts decrease (3 -> 2);
prettier 3.9.10 --check: clean across all eight unit files.

Review round 6: the two opencode-go files are re-ported byte-identical from Zoo-Code-Org#1652 at b51323d (blobs 970de27 and
2163ff1), which adds the two message assertions described there and no production line. Verification on this round:
vitest 434 passed (434) across the four provider specs in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with only the
round-4 unbound.ts decrease (3 -> 2) in eslint-suppressions.json; prettier 3.9.10 --check: clean across the eight unit
files. The unit's own content (excluding the 2847 a+d carried byte-identically from Zoo-Code-Org#1652, which drops out on merge plus
rebase) is 3198 a+d.

Review round 7: re-ported the two opencode-go blobs byte-identically from `371445df813b` (Zoo-Code-Org#1652 round 7), which
adds the authorized pre-yield cancel check on the Responses path and the two tests that carry it - the
buffered-completion fixture (text delta and `response.completed` from one read, take the delta, cancel, require
the rejection and no usage item) and the next-only source iterator that proves the cleanup forward must not assume
`return` exists. The three gateway helpers are untouched by that check, as instructed; series consistency of
the check is recorded as a follow-up on Zoo-Code-Org#2486 rather than folded into this unit.

Preflight reading (advisory, run incomplete, no scoring): the local Stryker preflight of the unit delta generated 402
mutants against the 400-mutant preflight limit in the previous round's run, and the added lines push that figure
higher; the run was therefore not scored, and `blocking:0` on the last completed report is an artifact of the
aborted preflight, not a clean mutation result - Zoo-Code-Org#1653's earlier completed head `41ba1fea0524` listed the same
12 `opencode-go.ts` StringLiteral rows as surviving with all three gateway specs present. No scored mutant of
this unit's own gateway code has been left without a disposition.
Decision requested (author/maintainer): either (a) split this unit further so each branch stays under the 400-mutant
preflight limit and the run can be scored, or (b) accept a reasoned narrow exclusion of the carried `opencode-go.ts`
rows from this unit's scoring on the ground that Zoo-Code-Org#1652 owns and scores those lines. Nothing here churns either unit to
force the count under 400.

Verification on this round: vitest 436 passed (436) across the four specs in declaration order and with
`--sequence.shuffle`; `tsc --noEmit -p tsconfig.json` from `src`: zero errors;`eslint . --ext=ts --max-warnings=0`
without `--prune-suppressions`: exit 0 with `eslint-suppressions.json` unchanged from this unit's own
`-1` decrease and `--prune-suppressions` reporting no further decrease; prettier 3.9.10 `--check`: clean.
Against merge-base `75a93a9d9acc`: opencode-go.spec.ts +2543/-200=2743, unbound.spec.ts +1138/-4=1142, vercel-ai-gateway.spec.ts +771/-2=773, zoo-gateway.spec.ts +820/-1=821, opencode-go.ts +390/-91=481, unbound.ts +142/-36=178, vercel-ai-gateway.ts +144/-42=186, zoo-gateway.ts +87/-9=96, eslint-suppressions.json +1/-1=2 = 6422 a+d, of which 3224 is the
byte-identical carry of Zoo-Code-Org#1652's diff, leaving 3198 this unit's own.

Review round 8 (carried from Zoo-Code-Org#1652 head 18eea83, spec blob b60a3da byte-identical): the deadline test drops its
elapsed-time bound - a stalled worker could fail it while the behaviour was correct - and now asserts the observed abort
reason (name + exact contract message), that the signal handed to the SDK is an AbortSignal that had already flipped, and
that a settled-flag attached to the parked SDK promise is still false, so the rejection can only come from the provider's
race. The caller-cancel-under-budget test reads the SDK-facing signal immediately before controller.abort() and immediately
after it, with no await between. A new test parks the catalog fetcher, releases it, waits for the dispatch and asserts by
reference identity that the dispatched request runs on the caller's own cancellation scope (no timeoutMs ->
mergeAbortSignalAndTimeout returns the caller's signal unchanged, utils/abort-signal.ts:42-44), then requires the cancel to
flip that same object with no await in between and the completion to reject while the SDK promise is still unsettled.
Controls: swapping signal: resolutionAbortSignal for a fresh controller in the chat-completions dispatch fails exactly that
test (1 failed | 229 skipped); disabling the merge's timeout arm fails all three rows of the deadline test (3 failed).
No gateway helper changed in this round; the four unit specs' own elapsed-time assertions were zero, and they remain zero.

Pre-merge rows answered without a production change: Lifecycle Resource Cleanup - completePrompt already builds one scope at
opencode-go.ts:951 via mergeAbortSignalAndTimeout(options?.abortSignal, options?.timeoutMs) and passes that merged signal to
the Anthropic, Responses and chat-completions SDK calls (:969, :1027, :1110) and to the races (:995, :1065, :1123); the raw
caller signal appears only in isRequestAborted classification. The helper registers no listener on the caller's signal -
utils/abort-signal.ts:42-44 returns it unchanged with no usable budget, :48-50 returns AbortSignal.timeout() alone, :52
returns mergeAbortSignals(external, timeout) which at :62-68 is AbortSignal.any([primary, secondary]) - so there is nothing
for the provider to detach, and the composite leaves with the request scope. The path that does attach a listener is the
streaming bridge at :256, whose dispose runs at :283, :309 and :435. Regression Evidence - the quiet-close tests the row
names already exist: spec:2376 (Anthropic streamAnthropicMessage), spec:2741 (Responses), spec:2785 (buffered completion
event delivered after the cancel), driven by the guards at opencode-go.ts:630, :644, :761 and :877.

Verification on this round: vitest 437 passed (437) across opencode-go.spec.ts, unbound.spec.ts, vercel-ai-gateway.spec.ts
and zoo-gateway.spec.ts in declaration order and with --sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero
errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with eslint-suppressions.json unchanged
(--prune-suppressions over the eight unit files reported no count decrease); prettier 3.9.10 --check: clean on all eight
unit files. Against merge-base 75a93a9 the unit totals are 6467 a+d.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
- createMessage: bridge metadata.abortSignal to a per-request
  AbortController (Bedrock pattern: pre-aborted guard, once-listener,
  detached on completion so a task-scoped signal does not accumulate
  listeners); model resolution runs inside the shared
  resolveModelWithAbort cancellation scope (pre-aborted fast-fail,
  mid-resolution race)
- aborted/timeout requests normalize to the provider AbortError on all
  three wire formats (anthropic /v1/messages, responses /v1/responses,
  openai chat completions), both pre-stream and mid-stream; non-abort
  failures keep the wrapped "Opencode Go completion error:" identity
- the OpenAI branch runs message conversion and request construction
  inside the same cleanup scope as the Anthropic and Responses branches,
  so a conversion failure (e.g. an unstringifiable tool input) still
  detaches the bridged abort listener (CodeRabbit fix on this PR)
- completePrompt: forwards abortSignal/timeoutMs to all three SDK
  paths (timeoutMs <= 0 omits the SDK timeout option, since the SDK
  treats timeout: 0 as an immediate abort); aborted completions and
  APIConnectionTimeoutError/APITimeoutError normalize to the provider
  AbortError (series standard)

The inner pre-stream provider-name literal is provably equivalent
and documented as such in the PR body; no Stryker disable directive is
added anywhere in the tree. createMessage's outer catch applies the
identical isRequestAborted check to the same controller signal and
re-standardizes the error, so the inner layer's only unique behavior is
the non-abort completion-error wrap (stays kill-tested), and the
abort-normalization condition beside that literal is killed by a
live-signal delivery added in the second review round.

The cleanup-scope re-indentation made the gate instrument pre-existing
request-construction lines for the first time; their previously
unobservable mutants are kill-tested: R1 tool-result merge shape for
preserveReasoning models and the plain shape for non-preserveReasoning
models, the includeMaxTokens on/off branches with a ceiling-bounded
model, and the parallel_tool_calls default/explicit-false.

Unit 2/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util unit.
Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on 41ef0e0): the Chat Completions stream loop now
breaks on the request signal at the top of each iteration and re-checks that signal after
the loop, so an SDK that swallows the body-read abort and closes the iterator normally
cannot report a cancelled turn as completed. The new test parks the iterator after the
first chunk, hands back a getter-counting chunk once the caller cancels, and asserts both
the standardized AbortError and zero post-cancel chunk reads; flipping either guard to a
false condition fails exactly that test (1 failed | 195 passed). The Responses pre-stream
abort arm had no live-signal delivery, so one is added: with no caller signal nothing
aborts, only the error-name arm can normalize, and the ConditionalExpression mutant dies
with it (same control). The provider-name literals at the two stream catches and at the
three completePrompt races were re-measured: each survives the full 196-test suite, which
matches the equivalence argument above. The detach tests now require exactly two abort
registrations on the caller's signal, name the bridge's by position, require it to differ
from the model-resolution race's callback, and assert both removals by reference in that
order. The SDK abort and timeout deliveries now reject from inside the SDK mock with no
caller signal (the automocked openai module's error classes are not Error instances, so
the name/message arm is exercised with the real class taken from the actual module), a
caller cancel landing inside the SDK call is classified across all three formats, and the
parked-lookup gate is the typed getModels fetcher rather than a spy on the private
resolveModel.

Review round 2 (CodeRabbit pre-merge checks): completePrompt gained a parameterized timeout-option
test per wire format (Anthropic messages, Responses, chat completions) that proves each call site
applies the shared hasUsableTimeout/toSdkTimeoutMs contract rather than only testing the helper:
NaN, Infinity and -5 leave no timeout key, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards
MAX_TIMEOUT_MS, and every row also asserts the caller's signal reached the SDK options, so dropping
the budget can never drop the cancel. Controls: deleting the forward arm fails two rows per format,
forcing it to always forward fails the three disabled-budget rows, and replacing
toSdkTimeoutMs(timeoutMs) with the raw value fails exactly the two forwarding rows. The five
provider-name literals on the abort paths were re-measured at this head: all five survive the full
211-test suite, which is the measured half of the equivalence argument in the PR body.

Verification on this tree: src tsc --noEmit exit 0 apart from the two known donor-store
integrations/misc/export-markdown.ts rows; vitest 211 passed (211) in declaration order and
in shuffled order; eslint . --ext=ts --max-warnings=0 without --prune-suppressions exit 0
with src/eslint-suppressions.json byte-identical (a prune run found zero decreases for this
unit); prettier 3.9.10 --check clean on the staged blobs extracted with core.autocrlf=false.

Review round 3 (CodeRabbit pre-merge checks, six Minor rows): the Chat Completions streaming loop now re-checks the request signal in front of every buffered item of a frame — the text item after a reasoning item, each tool-call partial inside the per-item loop, and the usage item — because a consumer that takes the first item, cancels and pulls the next one resumes this generator inside the same iteration, where the top-of-loop guard has already run. The three stream-open awaits (Anthropic /v1/messages, Responses /v1/responses and chat completions) now go through settleOnAbort with the signal still handed to the SDK, so a 429 with Retry-After plus a caller cancel no longer holds the pending first next() and the bridge cleanup until the sleep ends. Regression evidence: one parameterized test for the three stream-open races plus three manual-iteration tests that abort between two items of one frame (the buffered-text variant also asserts the bridge listener is detached by reference). Negative controls: removing each open wrapper fails exactly that format's row (1 failed | 216 passed each), disabling each buffered-item guard fails exactly that item's test, and reverting the OpenAI-path fixture key from opencodeGoModelId to the ignored apiModelId fails the five assertions that now pin model "glm-5.1" instead of expect.any(String). The parked-lookup test releases its gate in a finally so an assertion throw cannot strand the promise the provider awaits; measured with a probe: a release placed after the throwing assertion leaves the promise unresolved, the same release in a finally settles it.

Verification on this round: vitest 217 passed (217) in declaration order and with --sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical (a prune run over the two unit files reported zero count decreases); prettier 3.9.10 --check: clean.

Review round 4 (CodeRabbit pre-merge checks, one Major and nine Minor rows, handled in a single pass): the
Responses and Anthropic helpers no longer let a normally-ending SDK iterator read as a completed turn. The
Responses helper re-checks the bridged signal after processResponsesApiStream returns; the Anthropic helper
re-checks it at the top of each event dispatch, between the separator item and the block body of an indexed
content_block_start, and after the loop before the terminal cost chunk, so a cancel cannot emit the rest of
an event or bill a turn the caller already cancelled. Four tests drive the shape the pinned SDKs actually
produce - hand the consumer one item, cancel, then let the mock iterator report done instead of throwing -
and each one also runs the identical fixture with a live caller signal, which still delivers its text and
its terminal cost. Negative controls, each against the full suite: the Responses post-stream check (1 failed
| 223 passed), the Anthropic after-loop check (killed by the test that cancels after the last event was
delivered), the event-dispatch check (killed by the quiet-close test) and the separator checks (killed by the
two-yields-of-one-event test) each fail their own test and nothing else that matters.
The Responses pre-stream abort test no longer certifies itself through the provider's own catch: the mock
captures the signal the SDK actually received and then throws a plain failure, so the only evidence left is
that the captured signal is an AbortSignal that had already flipped; handing the SDK an unrelated signal
instead of the bridge fails seven tests, including that one. The timeout matrix now pins signal identity
rather than signal type - with no usable budget the SDK must hold the caller's own signal, with a usable one
it must hold the merged deadline - and a new parameterized test parks each format's request under a 5000 ms
budget, cancels the caller long before the deadline and requires the merged signal to flip and the completion
to reject with the contract AbortError; replacing the merged deadline with the caller's own signal on the
chat-completions completion fails 26 tests, including those rows. Three tests that polled for readiness
before observing the rejection now attach the handler when the promise is created, so a model lookup or
stream open that rejects during the poll cannot go unobserved.
Verification on this round: vitest 224 passed (224) in declaration order and with --sequence.shuffle; tsc
--noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without
--prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical (a prune run over the two unit
files found zero decreases, so the rewritten file was reverted); prettier 3.9.10 --check: clean.

Review round 5 (mutation sticky at d4ce1ce: blocking 23, advisories 0): this round adds no production lines. Three
tests were added, each aimed at a variant the sticky lists: a cancel between the separator and the body of an indexed
thinking block (kills the ConditionalExpression -> false variant at opencode-go.ts:796 and puts line 797 under coverage),
and one run per streaming format that passes no abort signal at all, so every guard in the helper is exercised with an
absent caller signal. Measured against the suite: each of the 17 StringLiteral -> "" rows (357, 380, 391, 407, 424, 567,
574, 626, 717, 725, 743, 797, 809, 858, 976, 1046, 1104) leaves 227/227 green, and each of the 5 OptionalChaining rows
(625, 742, 796, 808, 857) leaves 227/227 green. The reason is structural, not a matter of unasserted detail: at the
OptionalChaining lines the operand is the request-local signal that bridgeExternalAbortSignal/mergeAbortSignalAndTimeout
always hand to the SDK, so it is never nullish there, and an inner createAbortError is replaced by the enclosing catch's
own unmutated literal (for example the stream-open catch at 719 re-throwing at 725, and the completion catch at 981
re-throwing at 992), so the tests that do assert the exact contract message still see "The Opencode Go request was
aborted". The one variant that is observably different is now killed: ConditionalExpression -> false at 796 fails the new
thinking test (1 failed | 226 skipped) where it left the previous suite green.
Verification on this round: vitest 227 passed (227) in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0, with
eslint-suppressions.json unchanged because --prune-suppressions on the two unit files reported no count change; prettier
3.9.10 --check: clean.

Review round 6 (ask: kill the StringLiteral family with test-side message assertions before anything else, no new
production code). The spec's two remaining name-only assertions now pin the message too (spec:3824 and spec:3867, in the
two "bounds %s model resolution by the request timeout" groups), so every name assertion in the file carries the contract
message. That changed no survivor, and the reason is worth recording: with the message pinned everywhere, each of the 17
StringLiteral -> "" rows still leaves 227/227 green, because the message those tests read is produced by an enclosing
catch that throws its own unmutated createAbortError("Opencode Go") - the createMessage-level catch at :279 and the Chat
Completions stream helper's catch at :431 - and blanking either of those two literals fails 8 and 7 tests respectively,
while blanking any guard or race label fails none. The five OptionalChaining rows are equivalent for a separate reason:
the streaming helpers are always handed bridgedSignal ?? new AbortController().signal at :260, so their operand is never
nullish; with all five optional chains removed at once the suite is still 227/227, including the two runs that pass no
caller signal at all. No production line changed in either of the last two rounds; the provider blob is unchanged at
970de27.
Verification on this round: vitest 227 passed (227) in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with
eslint-suppressions.json unchanged; prettier 3.9.10 --check: clean.

Review round 7 (authorized: the pre-yield cancel check on the Responses path - one guard, one helper, one push, no
gateway propagation). `streamResponsesMessage` now hands the shared transform an iterator whose
`next()` reports the stream ended when the bridged signal is already aborted, so a pull that lands after the
caller cancelled can no longer deliver the event the pinned decoder had already buffered; the after-loop guard then
produces the contract AbortError. The helper's cleanup forward (`return: streamIterator.return?.bind(streamIterator)`)
preserves the previous delegation behaviour - an early consumer exit still closes the SDK iterator twice, as the
pre-existing cleanup test asserts - and stays callable when the source iterator implements no `return` at all. This
helper's signal parameter is now typed `AbortSignal` (`createMessage` supplies
`bridgedSignal ?? new AbortController().signal`), which is why the after-loop guard no longer needs its optional
chain. Nothing was added to the three gateway helpers, as instructed.

Two tests carry it: the buffered-completion fixture (text delta and `response.completed` from one read, take the
delta, cancel, require the rejection and no usage item) and a next-only source iterator, which proves the cleanup
forward must not assume `return` exists. Controls: against the pre-change provider the buffered fixture fails with
'expected undefined to match object { name: AbortError }' - today the usage chunk is delivered - so this was an
uncovered gap, not a restatement of covered behaviour. For the new code: the pull guard's
`ConditionalExpression -> false` fails exactly the two new tests and `-> true` fails 15; the
`OptionalChaining` on the cleanup forward fails the next-only test; neutering the after-loop guard now fails 3
tests including the buffered fixture, which is the variant that fixture kills.

Verification on this round: vitest 229 passed (229) in declaration order and with `--sequence.shuffle`;
`tsc --noEmit -p tsconfig.json` from `src`: zero errors;`eslint . --ext=ts --max-warnings=0` without
`--prune-suppressions`: exit 0 with `eslint-suppressions.json` unchanged and`--prune-suppressions` reporting
no decrease; prettier 3.9.10 `--check`: clean. Against merge-base `75a93a9d9acc`: opencode-go.spec.ts +2543/-200=2743, opencode-go.ts +390/-91=481 =
3224 a+d.

Review round 8 (CodeRabbit review 5982073495, line 3872 wall-clock row): the deadline test no longer measures elapsed time.
It parks the SDK promise so it never settles, then asserts the observed abort reason (name AbortError plus the exact contract
message), that the signal handed to the SDK really is an AbortSignal and had already flipped, and that a settled-flag attached
to the parked promise is still false, so the rejection can only come from the provider's race; the 1s bound is gone (it was
the assertion a stalled worker could fail) and the duplicated message assertion was deduplicated. The caller-cancel-under-
budget test now reads the SDK-facing signal immediately before controller.abort() and immediately after it, with no await
between the two reads, and the redundant post-settlement read was removed.

Shared-deadline row: a new test parks the catalog fetcher, releases it, waits for the dispatch, and then asserts by reference
identity that the dispatched request runs on the caller's own cancellation scope (with no timeoutMs, mergeAbortSignalAndTimeout
returns the caller's signal unchanged at utils/abort-signal.ts:42-44), flips it, requires the flip on the SDK-facing signal with
no await in between, and requires the completion to reject with the contract AbortError while the parked SDK promise is still
unsettled. Controls: replacing signal: resolutionAbortSignal in the chat-completions dispatch with a fresh controller fails
exactly that test (AssertionError: expected AbortSignal { aborted: false } to be AbortSignal { aborted: false }, 1 failed |
229 skipped), and forcing the merge's timeout arm off fails all three rows of the deadline test (3 failed). Signal identity for
the timeout shapes was already pinned by assertTimeoutOption (spec:4056), which requires the caller's own object with no usable
budget and a merged deadline distinct from it with a usable one.

Verification on this round: vitest 230 passed (230) in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with
eslint-suppressions.json unchanged (--prune-suppressions on the spec reported no count decrease, so the rewritten file was
reverted); prettier 3.9.10 --check: clean. No production line changed in this round; the provider blob is unchanged at
bb1acfe. Against merge-base 75a93a9: opencode-go.spec.ts +2597/-191=2788, opencode-go.ts +390/-91=481 = 3269 a+d.
easonLiangWorldedtech added a commit to easonLiangWorldedtech/Zoo-Code that referenced this pull request Nov 19, 2026
…ateway

Each provider's createMessage bridges metadata.abortSignal to a
per-request AbortController (Bedrock pattern: pre-aborted guard,
{ once: true } listener, detached on completion so a task-scoped
signal does not accumulate listeners) and runs model resolution inside
the shared resolveModelWithAbort cancellation scope; aborted requests
(pre-aborted, mid-resolution, mid-stream) normalize to the provider
AbortError while non-abort failures propagate or wrap unchanged.
completePrompt forwards abortSignal/timeoutMs to the OpenAI SDK
(timeoutMs <= 0 omits the SDK timeout option); aborted completions and
APIConnectionTimeoutError normalize to the provider AbortError (series
standard).

Zoo Gateway places the entry fast-fail before ensureAuthenticated() so
a pre-aborted task surfaces the AbortError instead of an auth failure
(pinned by an unauthenticated pre-abort test).

Unit 3/3 of the Zoo-Code-Org#1295 split (content source: 62f596c); stacks on the
shared-util and opencode-go units. Three sibling OpenAI-SDK gateway
providers with an identical abort-wiring shape are kept as one unit to
avoid tripling the review surface for mechanically identical changes
(a+d soft-cap rationale per the split budget; the mutation gate is
measured on the unit delta and is green).

Part of the abort-signal series (round 1). Builds on Zoo-Code-Org#674, Zoo-Code-Org#901, Zoo-Code-Org#1008.
Addresses Zoo-Code-Org#404.

Review round (CodeRabbit threads on b1bd578, disposition recorded on each thread): each provider now races the SDK promise it awaits against the bridged signal through `settleOnAbort` — unbound's stream create and its completion, vercel-ai-gateway's completion, zoo-gateway's completion — because the OpenAI SDK sleeps out a Retry-After / retry delay without observing the signal, and the post-await `bridgedSignal?.aborted` guards that used to trail those awaits are gone, since `raceAbort` rejects synchronously at `abort()` and nothing after the await can read the flag first. Each streaming loop breaks on the caller signal at the top of an iteration, re-checks it before emitting a just-received chunk, and checks it once more before the generator returns, so a cancel the SDK swallows — the iterator ends normally without a throw — can neither emit the rest of a chunk nor report a partial turn as completed. The caller's signal is bridged rather than handed to the SDK directly and the bridge is disposed in `finally`; the detach tests name the bridge's listener by registration position, require it to differ from the model-lookup race's callback, and assert both removals by reference. Absence proofs drain the provider's own continuation instead of sleeping.

The two Opencode Go files are Zoo-Code-Org#1652's blobs, byte for byte: provider `23348a501e9f31d0c72bffa6eefb6030bb6149a3`, spec `5dbe3382d1f1d6af8d22e7637a088c546988ef18`; `git diff df29307 -- <those two paths>` is empty with `core.autocrlf=false` and the blob ids are re-verified against this commit. Once Zoo-Code-Org#1652 lands on main this unit rebases onto it and both files drop out of this diff.

Review round 2 (CodeRabbit pre-merge checks): each gateway completePrompt now pins the disabled-budget boundary at -5 — the SDK options carry no timeout key and the bridged per-request signal is still handed over (the zoo variant is one of the tests that also catches a dropped signal arm). The ported Opencode Go spec brings its own parameterized timeout-option test per wire format: NaN, Infinity and -5 omit the option, 12.5 forwards timeout: 13, MAX_TIMEOUT_MS + 1 forwards MAX_TIMEOUT_MS, and the caller signal is asserted on every row. Those rows kill the forward arms at opencode-go.ts:886/944/1027 in both directions (deleting the arm fails two rows per format, forcing it always-forward fails the three disabled-budget rows) and the toSdkTimeoutMs call sites; forcing the gateway arms to always forward fails the new -5 rows on all three providers.

Verification on this tree: vitest over the opencode-go, unbound, vercel-ai-gateway and zoo-gateway specs from `src` — 411 passed (411) in declaration order and 411 passed with `--sequence.shuffle`; `tsc --noEmit -p tsconfig.json` leaves only the two known donor-store `integrations/misc/export-markdown.ts` rows; `eslint . --ext=ts --max-warnings=0` without `--prune-suppressions` exits 0 with `src/eslint-suppressions.json` byte-identical (a prune run over the eight touched paths reported zero count decreases); prettier 3.9.10 `--check` clean on the staged blobs extracted with `core.autocrlf=false`. Negative controls per new guard: flipping each added condition or deleting each added arm fails the specific guard test that names it — 1 failed | 195 passed for either Opencode Go chat-stream arm, 1 failed for the Responses pre-stream condition, 2 failed for the Anthropic stream condition, and the same shape for the gateway guards.

Review round 3: the mutation-diff report at 313cf0e listed 20 blocking rows (21 survived mutants plus one uncovered arm) over 338 changed executable lines. Five of them are now killed by four tests added here: unbound.ts:349 and vercel-ai-gateway.ts:280 (detachExternalAbortSignal() -> ; in the completePrompt finally) by a detach test per provider that identifies the bridge listener by the { once: true } registration and asserts its removal by reference; zoo-gateway.ts:337 (classification gate -> false) by a streaming test that feeds a name-only AbortError with a live-but-not-aborted caller signal and asserts the contract identity, that the add-credits notification never ran, and that nothing was logged; zoo-gateway.ts:346 in both directions by a streaming test where the notification itself rejects while the caller signal is live (the log must name the surfacing failure and the original 402 must still reach the caller) plus the existing cancel-while-prompt-open test, which also puts that line under coverage. Each of those four mutants was applied alone and restored: 1 failed | 414 passed, killed by the named test in every case. The remaining sixteen rows are all StringLiteral -> "" on a provider-name label inside createAbortError/settleOnAbort/rejectOnAbort; each one sits inside a catch or race whose enclosing handler re-throws with its own unmutated literal, so the provider-visible error name and message are identical through the public API and no assertion can distinguish the mutant from the code (measured: full suite green with each mutant in place). No Stryker directive was added; the equivalence is argued in the PR discussion for a maintainer to weigh.

Verification on this tree: vitest 421 passed (421) across the four provider specs in declaration order and with --sequence.shuffle (the six new opencode-go tests arrive with the re-ported blobs); tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with src/eslint-suppressions.json byte-identical; prettier 3.9.10 --check on the touched files: clean. The opencode-go blobs are re-ported from df29307 and remain byte-identical to that head (git diff --quiet against it for those two paths: exit 0), so after a maintainer merges Zoo-Code-Org#1652 these lines drop out of this diff on rebase.

Review round 4 (CodeRabbit pre-merge checks, six Major and 26 Minor rows, handled in one pass): three sibling
stream loops no longer hand a cancelled turn their last item - Unbound re-checks the caller signal in front of
the text item of a frame whose reasoning item was already delivered, and both Vercel AI Gateway and Zoo Gateway
re-check it in front of the usage item of a frame whose text was already delivered, so a cancel between the two
items of one chunk rejects instead of emitting or billing the remainder. The three "does not emit the rest of a
tool-call chunk" tests are now consumer-driven (take the first partial, cancel, require the next call to reject
without building the second one) because the getter variant aborted before either partial existed and could not
tell a per-partial check from a per-frame check. Unbound's retained usage is typed as
OpenAI.Completions.CompletionUsage | undefined, which drops its @typescript-eslint/no-explicit-any suppression
from 3 to 2 (the only suppression change in this unit). The non-array tool_calls fixture now carries a truthy
value instead of null, so the Array.isArray check is what the test pins. The Zoo Gateway SDK-timeout
classification test no longer carries a 50 ms provider deadline, and the deadline test's mock refuses to run
without the per-request signal, so a provider that stops forwarding the deadline fails loudly instead of
throwing immediately. The two add-credits streaming tests wrap their whole body in a try/finally so the console
spy is restored even when an early assertion throws. The opencode-go provider and spec are the byte-identical
blobs from Zoo-Code-Org#1652 at d4ce1ce (opencode-go.ts 970de27, opencode-go.spec.ts 8c34bbb), which carry
the Responses/Anthropic quiet-close guards, the terminal-usage guard, the captured-SDK-signal assertions and
the merged-deadline cancel rows that close this unit's opencode-go rows; on rebase over the merged Zoo-Code-Org#1652 those
lines drop out.
Not changed in this unit, with the reasoning recorded on the threads: Unbound's timeout is enforced through the
merged deadline signal rather than response-body consumption (helper-side, tracked on Zoo-Code-Org#2486), the completion
races still return a response that won the race before the cancel, and the completion paths keep using the
shared mergeAbortSignalAndTimeout signal rather than a request-local bridge.
Verification on this round: vitest 431 passed (431) across the four provider specs in declaration order and with
--sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0
without --prune-suppressions: exit 0, with src/eslint-suppressions.json updated only for the unbound.ts decrease
(3 -> 2) that the prune run reported; prettier 3.9.10 --check: clean. Negative controls against the suite, each
disabling one guard: the Unbound text-item guard, the Vercel usage-item guard and the Zoo usage-item guard each
fail exactly their own new test (1 failed | 45, 56 and 103 passed respectively), the three per-partial guards
each fail exactly their rewritten tool-call test, dropping the Zoo completion's per-request signal arm fails the
seven timeout and abort-delivery tests that read it, and dropping the timeout arm fails the two option-forwarding
tests.

Review round 5 (mutation sticky at 41ba1fe: blocking 23, advisories 0): no production line was added or changed in
this round. The opencode-go provider and spec are re-ported byte-identical from Zoo-Code-Org#1652 at 40456d8 (blobs
970de27 and 4afc3ee), which carry the thinking-separator cancel test and the two no-abort-signal runs that
kill and explain the structural variants on that file. Every sibling row was measured by hand in this worktree: the label
mutants at unbound.ts:218/247/257/278/338 and vercel-ai-gateway.ts:136/168/185/267 leave their whole spec green
(46/46 and 57/57) because each inner createAbortError is replaced by the enclosing catch's own unmutated literal, while
mutating those catches' own labels (unbound.ts:224, 289, 349 and vercel-ai-gateway.ts:204, 213, 279) fails 3, 6, 5, 4, 1
and 5 tests - which is what proves the message the tests assert comes from the catch, not from the inner label. The zoo
labels (280, 308, 344) are killed outright by the abort-identity tests, and the zoo console-guard optional chain is
killed by two existing tests.
Verification on this round: vitest 434 passed (434) across the four provider specs in declaration order and with
--sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without
--prune-suppressions: exit 0 with eslint-suppressions.json carrying only the round-4 unbound.ts decrease (3 -> 2);
prettier 3.9.10 --check: clean across all eight unit files.

Review round 6: the two opencode-go files are re-ported byte-identical from Zoo-Code-Org#1652 at b51323d (blobs 970de27 and
2163ff1), which adds the two message assertions described there and no production line. Verification on this round:
vitest 434 passed (434) across the four provider specs in declaration order and with --sequence.shuffle; tsc --noEmit -p
tsconfig.json from src: zero errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with only the
round-4 unbound.ts decrease (3 -> 2) in eslint-suppressions.json; prettier 3.9.10 --check: clean across the eight unit
files. The unit's own content (excluding the 2847 a+d carried byte-identically from Zoo-Code-Org#1652, which drops out on merge plus
rebase) is 3198 a+d.

Review round 7: re-ported the two opencode-go blobs byte-identically from `371445df813b` (Zoo-Code-Org#1652 round 7), which
adds the authorized pre-yield cancel check on the Responses path and the two tests that carry it - the
buffered-completion fixture (text delta and `response.completed` from one read, take the delta, cancel, require
the rejection and no usage item) and the next-only source iterator that proves the cleanup forward must not assume
`return` exists. The three gateway helpers are untouched by that check, as instructed; series consistency of
the check is recorded as a follow-up on Zoo-Code-Org#2486 rather than folded into this unit.

Preflight reading (advisory, run incomplete, no scoring): the local Stryker preflight of the unit delta generated 402
mutants against the 400-mutant preflight limit in the previous round's run, and the added lines push that figure
higher; the run was therefore not scored, and `blocking:0` on the last completed report is an artifact of the
aborted preflight, not a clean mutation result - Zoo-Code-Org#1653's earlier completed head `41ba1fea0524` listed the same
12 `opencode-go.ts` StringLiteral rows as surviving with all three gateway specs present. No scored mutant of
this unit's own gateway code has been left without a disposition.
Decision requested (author/maintainer): either (a) split this unit further so each branch stays under the 400-mutant
preflight limit and the run can be scored, or (b) accept a reasoned narrow exclusion of the carried `opencode-go.ts`
rows from this unit's scoring on the ground that Zoo-Code-Org#1652 owns and scores those lines. Nothing here churns either unit to
force the count under 400.

Verification on this round: vitest 436 passed (436) across the four specs in declaration order and with
`--sequence.shuffle`; `tsc --noEmit -p tsconfig.json` from `src`: zero errors;`eslint . --ext=ts --max-warnings=0`
without `--prune-suppressions`: exit 0 with `eslint-suppressions.json` unchanged from this unit's own
`-1` decrease and `--prune-suppressions` reporting no further decrease; prettier 3.9.10 `--check`: clean.
Against merge-base `75a93a9d9acc`: opencode-go.spec.ts +2543/-200=2743, unbound.spec.ts +1138/-4=1142, vercel-ai-gateway.spec.ts +771/-2=773, zoo-gateway.spec.ts +820/-1=821, opencode-go.ts +390/-91=481, unbound.ts +142/-36=178, vercel-ai-gateway.ts +144/-42=186, zoo-gateway.ts +87/-9=96, eslint-suppressions.json +1/-1=2 = 6422 a+d, of which 3224 is the
byte-identical carry of Zoo-Code-Org#1652's diff, leaving 3198 this unit's own.

Review round 8 (carried from Zoo-Code-Org#1652 head 18eea83, spec blob b60a3da byte-identical): the deadline test drops its
elapsed-time bound - a stalled worker could fail it while the behaviour was correct - and now asserts the observed abort
reason (name + exact contract message), that the signal handed to the SDK is an AbortSignal that had already flipped, and
that a settled-flag attached to the parked SDK promise is still false, so the rejection can only come from the provider's
race. The caller-cancel-under-budget test reads the SDK-facing signal immediately before controller.abort() and immediately
after it, with no await between. A new test parks the catalog fetcher, releases it, waits for the dispatch and asserts by
reference identity that the dispatched request runs on the caller's own cancellation scope (no timeoutMs ->
mergeAbortSignalAndTimeout returns the caller's signal unchanged, utils/abort-signal.ts:42-44), then requires the cancel to
flip that same object with no await in between and the completion to reject while the SDK promise is still unsettled.
Controls: swapping signal: resolutionAbortSignal for a fresh controller in the chat-completions dispatch fails exactly that
test (1 failed | 229 skipped); disabling the merge's timeout arm fails all three rows of the deadline test (3 failed).
No gateway helper changed in this round; the four unit specs' own elapsed-time assertions were zero, and they remain zero.

Pre-merge rows answered without a production change: Lifecycle Resource Cleanup - completePrompt already builds one scope at
opencode-go.ts:951 via mergeAbortSignalAndTimeout(options?.abortSignal, options?.timeoutMs) and passes that merged signal to
the Anthropic, Responses and chat-completions SDK calls (:969, :1027, :1110) and to the races (:995, :1065, :1123); the raw
caller signal appears only in isRequestAborted classification. The helper registers no listener on the caller's signal -
utils/abort-signal.ts:42-44 returns it unchanged with no usable budget, :48-50 returns AbortSignal.timeout() alone, :52
returns mergeAbortSignals(external, timeout) which at :62-68 is AbortSignal.any([primary, secondary]) - so there is nothing
for the provider to detach, and the composite leaves with the request scope. The path that does attach a listener is the
streaming bridge at :256, whose dispose runs at :283, :309 and :435. Regression Evidence - the quiet-close tests the row
names already exist: spec:2376 (Anthropic streamAnthropicMessage), spec:2741 (Responses), spec:2785 (buffered completion
event delivered after the cancel), driven by the guards at opencode-go.ts:630, :644, :761 and :877.

Verification on this round: vitest 437 passed (437) across opencode-go.spec.ts, unbound.spec.ts, vercel-ai-gateway.spec.ts
and zoo-gateway.spec.ts in declaration order and with --sequence.shuffle; tsc --noEmit -p tsconfig.json from src: zero
errors; eslint . --ext=ts --max-warnings=0 without --prune-suppressions: exit 0 with eslint-suppressions.json unchanged
(--prune-suppressions over the eight unit files reported no count decrease); prettier 3.9.10 --check: clean on all eight
unit files. Against merge-base 75a93a9 the unit totals are 6467 a+d.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(api): introduce RequestConfigBuilder for SDK-agnostic abort signal support

3 participants