Skip to content

Providers: public URLSession configuration seam on API (stub/proxy HTTP without @testable) #43

Closed

Description

@odrobnik

Why

API (Sources/Providers/API/API.swift) builds its own session and streamSession in init and keeps them internal. A package that depends on SwiftAgents therefore cannot inject a URLSessionConfiguration with protocolClasses (a URLProtocol stub), a proxy, custom timeouts, or an ephemeral session.

Seen twice on 2026-10-30:

  • MissionControl (labs/MissionControl#720, mc image): to test its image tools without the network, it had to run a loopback HTTP server and point endpointURL at it, because the client's HTTP could not be stubbed.
  • A live Codex test: a CaptureProxy: URLProtocol meant to record request bodies could not be attached ('session' is inaccessible due to 'internal' protection level). SwiftAgents' own ChatGPTCodexLiveTests only work around this with @testable import.

Wanted

A small public seam with no behaviour change for existing callers:

  • public init(credential:endpointURL:versionPath:configuration: URLSessionConfiguration? = nil, streamConfiguration: URLSessionConfiguration? = nil). When given, these build the two sessions; when nil, today's defaults apply (360 s timeouts and so on).
  • Or public var session: URLSession and public var streamSession: URLSession with public internal(set), plus a public func use(sessionConfiguration:). Pick whichever fits the provider subclasses (OpenAI, ChatGPTCodex, Anthropic, Gemini, …) best; every subclass initialiser should pass it through.
  • Works on every CI platform (Linux and Windows via FoundationNetworking).

Acceptance criteria

  • A test in ProvidersTests stubs an Images API call (generateImages) and a streamed Responses call through a URLProtocol set via the new public API, without @testable import. Put it in a separate test file that imports Providers normally.
  • ChatGPTCodexLiveTests uses the public seam instead of @testable for its capture proxy, if that is straightforward.
  • Existing initialisers and behaviour are unchanged; all CI platforms are green.

Activity

  1. added
    status::doing
    on Oct 30, 2026
  2. odrobnik commented on Oct 30, 2026

    @odrobnik
    ContributorAuthor

    🧭 Planner finished — implementation plan ready for approval (via Claude Team [drobnik] · 2% used).

    Plan for #43: public URLSession configuration seam on API

    I could read API.swift, the super.init call sites and the test usages. A second command was refused, so I did not read the full subclass initialisers, Anthropic.swift around line 248, or the @testable lines in ChatGPTCodexLiveTests. The steps below that touch those files are inferred from grep output and need checking when the work starts.

    Chosen design

    I'd take the first option from the issue: initialiser parameters, plus a small public use(sessionConfiguration:) for swapping afterwards.

    • Why parameters: they match the existing credential and endpointURL init style, and they leave session and streamSession internal. session and streamSession are plain vars today and are written directly by the internal tests.
    • Why also use(...): RunConfig.api and ProviderRegistry hand in already-constructed APIs. A caller can then re-point one at a stub without rebuilding it.

    Intended behaviour

    • API.init(credential:endpointURL:versionPath:configuration:streamConfiguration:) gains two trailing parameters, both URLSessionConfiguration? = nil.
    • Both nil: behaviour is exactly as today. The default session has 360 s request and resource timeouts. The stream session has 600 s for both.
    • configuration set: it builds session. The caller owns its timeouts.
    • streamConfiguration set: it builds streamSession.
    • Only configuration set: I'd have streamSession fall back to a copy of configuration with 600 s timeouts. One stub config would then cover both sessions, and a stub's protocolClasses would be inherited. This needs your confirmation (see open questions).
    • Public method: public func use(sessionConfiguration: URLSessionConfiguration, streamConfiguration: URLSessionConfiguration? = nil) rebuilds both sessions with the same rules.
    • No change to existing initialisers, call sites or default behaviour.

    Files and components

    • Sources/Providers/API/API.swift
      • Add the init parameters.
      • Extract a private helper that builds the two sessions from optional configurations plus defaults. init and use(...) both call it.
      • Replace the "test seam" comments on session and streamSession.
      • Keep both properties internal so the existing @testable tests still compile.
    • Subclass initialisers, which each call super.init(...):
      • OpenAI, ChatGPTCodex, Anthropic, GoogleAPI, LMStudio, OllamaAPI, OpenAIResponsesWebSocket
      • Each gets the same two defaulted parameters, passed through. Existing call sites stay source-compatible.
    • Anthropic.swift around line 248
      • It builds a throwaway URLSession(configuration: config) for its own streaming instead of using streamSession.
      • Switch it to streamSession so stubs apply, keeping the same timeouts by default.
      • OpenAI+Responses, OpenAI+Runs and OpenAI streaming already use streamSession.
      • Grep for any other URLSession( or URLSession.shared in Sources/Providers/API that bypasses the seam, since those would silently ignore the injected configuration.
    • OpenAIRealtime* models take their own URLSession and are out of scope.
    • Platforms: URLSessionConfiguration and protocolClasses come from FoundationNetworking on Linux, Windows and Android. API.swift imports Foundation and SwiftCross. I'd confirm that it compiles on those platforms, adding #if canImport(FoundationNetworking) import FoundationNetworking #endif if needed.

    Implementation steps

    1. Add the session-building helper and the new API.init parameters. Add use(sessionConfiguration:streamConfiguration:).
    2. Thread the parameters through every subclass init listed above.
    3. Fix the Anthropic streaming session so it honours the seam.
    4. Add Tests/ProvidersTests/PublicSessionSeamTests.swift.
      • It uses a plain import Providers, with no @testable.
      • It defines a URLProtocol stub with a lock-guarded handler and recorded requests.
      • Test 1: OpenAI(..., configuration:) with the stub calls generateImages. It asserts the request path and body and decodes the canned response.
      • Test 2: a streamed Responses call, using the same stub config for both sessions. The stub returns an SSE body, and the test asserts the events arrive.
      • Test 3: use(sessionConfiguration:) swaps the sessions on an existing instance.
      • Test 4: defaults are unchanged. This can only be checked indirectly without @testable, so a small @testable test in an existing file can assert the 360/600 timeouts.
      • Check which API names the new test needs are public: generateImages, the Responses streaming entry point, and the request and response types.
    5. Update ChatGPTCodexLiveTests (around lines 246–247, where it sets api.session and api.streamSession) to construct the API with the capture-proxy configuration. If anything else in the file needs @testable, leave the import and note it. The issue says "if straightforward".
    6. Optionally migrate the other internal tests (ImagesAPITests, ChatGPTCodexTests, StreamedRunCancellationTests). I'd leave them as they are to keep the diff small.

    Verification

    • Run swift build and swift test with --scratch-path "/Volumes/SSD/SwiftPM/$(basename "$PWD")".
    • Include the traits the repo needs. The SQLite tests need --traits SQLiteVectorStore.
    • Run swiftlint --strict. This is the real gate. file_length warns at 800 lines and that is fatal, so keep API.swift and Runner.swift under the limit. If API.swift is near the limit, put the helper in a new file as an API extension.
    • CI should be green on all five platforms (macOS, Linux, Windows, Android, plus the fifth). Linux and Windows are the ones to watch for the FoundationNetworking import.
    • Per the repo conventions: work on a branch, open a PR, then turn on Auto-fix for it. The branch agent/issue-43 is already checked out.

    Open questions and risks

    1. Fallback for streamConfiguration. When only configuration is passed, should the stream session derive from it (my proposal) or stay on the default? Deriving means one stub covers both sessions, which is what the issue's use cases want. The cost is that it's slightly implicit. I'll go with deriving unless you object.
    2. Subclass API surface. Adding two defaulted parameters to each subclass init is source-compatible. It is not ABI-compatible, but this is a source package, so that should be fine.
    3. URLProtocol and streaming on Linux. URLProtocol stubs with streamed bodies can behave differently in swift-corelibs-foundation. The streaming test may need a single didLoad chunk, or a platform guard. This is the main CI risk.
    4. Bypassing call sites. Anthropic's private session is one example. The grep in step 3 will show whether there are others.

    No subtasks were filed. The work is small enough for a single PR.

    Approve this plan by starting an Implementor for the issue.

  3. added
    status::todo
    status::doing
    and removed
    status::doing
    status::todo
    on Oct 30, 2026
  4. odrobnik commented on Oct 30, 2026

    @odrobnik
    ContributorAuthor

    🚀 Shipped (via Claude Team [drobnik] · 2% used) — opened #44

    I opened PR #44 for issue #43. It adds a public URLSessionConfiguration seam to API and its provider subclasses. The build, the tests I ran (the new seam tests plus the existing Images, Codex, Anthropic and streaming-run suites) and swiftlint --strict pass on macOS. I did not run the full test suite, and Linux, Windows and Android are unchecked until CI runs.

    • New parameters: API.init, OpenAI, ChatGPTCodex, Anthropic, GoogleAPI and LMStudio take configuration: and streamConfiguration:, both URLSessionConfiguration? = nil. API also gets a public use(sessionConfiguration:streamConfiguration:) to swap them on an existing client.
    • Defaults: with neither argument, the 360 s and 600 s timeouts are unchanged.
    • One stub covers both sessions: if only configuration is given, the stream session uses a copy of it with 600 s timeouts. This was the planner's open question; I went with its proposal.
    • Anthropic streaming: it now uses streamSession instead of building its own private session, so a stub applies there too.
    • Tests: PublicSessionSeamTests.swift uses a plain import Providers. It stubs generateImages and a streamed Responses call through init(configuration:), use(sessionConfiguration:) and an explicit streamConfiguration.
    • Live test: ChatGPTCodexLiveTests now passes its capture proxy through the public initialiser and no longer needs @testable.

    Not changed:

    • URLSession.shared calls: the Assistants, Conversations and Traces extensions, Compact, OpenAI+RunSteps and the Google embeddings call still use URLSession.shared and so bypass the seam. Moving them to session would change their timeouts, so I left them for a separate change.
    • WebSocket model: OpenAIResponsesWebSocket keeps its own session handling.
  5. added
    status::shipped
    and removed
    status::doing
    on Oct 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    status::shipped

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions