Skip to content

Commit b945cef

Browse files
authored
feat: support transcription replay and API key validation (#345)
## Final Timing Contract Coverage Commit `b5ce7df` is test coverage only; it does not change replay behavior. The fake-clock writer test now proves no frame arrives one millisecond before each scheduled 40/20 ms boundary, each expected frame arrives at its boundary in order, and the stream stays open until the final frame. The route test spies on the real writer boundary and asserts the fixture forwards its exact `recordedTimings` object and `replaySpeed: 2`. Focused timing tests passed 20/20 repeated runs. Full pre-push validation passed: format, lint, TypeScript, 4,794 tests (3 skipped), build, and export checks. ## Timing Determinism Correction Commit `4b6cedb` fixes a completion-gate flake in the replay-speed integration test without changing replay behavior. The real HTTP test had a 200 ms ceiling even though its actual 8-frame schedule is 180 ms before HTTP, event-loop, and timer-resolution overhead: role + 6 content + finish frames receive `[40, 20, 20, 20, 20, 20, 20, 20]` ms at 2x speed. The upper bound is replaced by a fake-timer writer assertion of that exact schedule; the HTTP test remains to prove the route wires `replaySpeed` into the writer. ### Local Red-Green Proof Red, clean `c45bc66`, actual target test repeated 30 times: ```text 10/30 failures expected 204 to be less than 200 expected 203 to be less than 200 expected 259 to be less than 200 ``` Green, `4b6cedb`, same actual target test repeated 30 times: ```text summary: 30/30 passes ``` The deterministic writer contract and real route both pass. Full suite: 166 files, 4,794 passed, 3 skipped; format, lint, TypeScript check, build, and export checks pass. ## Nested GA Output Correction Commit `c45bc66` accepts and round-trips nested GA `session.audio.output.voice` and its complete PCM `format` object without changing Beta or legacy session translation. The recorder integration now explicitly proves fixture persistence and replay of terminal `languages` and `usage` metadata after the client closes. ### Direct Local Red-Green Proof A standalone real local recorder and WebSocket probe ran against clean `ead88d4` before the change, then against this commit. Red (`ead88d4`): ```text RECORDER {"persisted":true,"savedResponse":{"transcription":{"text":"typed terminal","languages":[{"code":"en"}],"usage":{"input_tokens":4,"output_tokens":5}}},"replayStatus":200} WEBSOCKET {"betaDefault":null,"betaNested":{"type":"server_vad","threshold":0.7},"betaLegacy":{"type":"semantic_vad"},"gaFormat":{"type":"audio/pcm","rate":24000},"gaOutput":{"format":null,"voice":null}} ``` Green (`c45bc66`): ```text RECORDER {"persisted":true,"savedResponse":{"transcription":{"text":"typed terminal","languages":[{"code":"en"}],"usage":{"input_tokens":4,"output_tokens":5}}},"replayStatus":200} WEBSOCKET {"betaDefault":null,"betaNested":{"type":"server_vad","threshold":0.7},"betaLegacy":{"type":"semantic_vad"},"gaFormat":{"type":"audio/pcm","rate":24000},"gaOutput":{"format":{"type":"audio/pcm","rate":24000},"voice":"alloy"}} ``` Focused real integration coverage: 168 tests passed. Full pre-push suite: 4,793 passed, 3 skipped. ## Post-Rebase Corrections `ead88d4` closes the rebase-review gaps without changing the release version: typed transcription terminals are now treated as complete on client close; Beta session events retain root `turn_detection`; GA retains the documented PCM `rate`. ### Direct Local Red-Green Proof The same standalone probe used a real upstream SSE recorder proxy, client abort, persisted-fixture local replay, and live WebSocket connections. Red (`89d4e5c`): ```text RECORDER {"persisted":false,"replayStatus":502,"replayBody":"{\"error\":{\"message\":\"Proxy to upstream failed: connect ECONNREFUSED 127.0.0.1:53771\",\"type\":\"proxy_error\"}}"} WEBSOCKET {"gaFormat":{"type":"audio/pcm"}} ``` Green (`ead88d4`): ```text RECORDER {"persisted":true,"replayStatus":200,"replayBody":"data: {\"type\":\"transcript.text.delta\",\"delta\":\"typed terminal\"}\n\ndata: {\"type\":\"transcript.text.done\",\"text\":\"typed terminal\",\"languages\":[{\"code\":\"en\"}]}\n\n"} WEBSOCKET {"betaDefault":null,"betaNested":{"type":"server_vad","threshold":0.7},"betaLegacy":{"type":"semantic_vad"},"gaFormat":{"type":"audio/pcm","rate":24000}} ``` The red JSON omits Beta keys because JavaScript omits `undefined` object properties. The green output verifies default null, nested GA update, and legacy flat update independently. ## Release / Rebase Status Rebased the transcription implementation and its contract coverage onto current `main` (`9ce3107`) without changing the intended runtime behavior. The PR now releases `@copilotkit/aimock` `1.38.0` and aligns its publish surfaces: root package, dated changelog entry, Helm `appVersion`, pytest default pin plus pytest package `0.5.1`, and Claude plugin metadata/range. Current branch commits: - `3cf3956 feat: support OpenAI transcription replay` - `cfbbe0a test: cover transcription replay contracts` - `89d4e5c chore: release v1.38.0` The retained proof below was captured against the original behavior branch; the rebased branch passed the focused 400-test transcription suite, full 4,746-test npm suite, format, lint, explicit TypeScript check, build, exports, frozen-lockfile validation, pytest 17/17, and pytest package build. ## Summary Aligns OpenAI transcription HTTP, Realtime, recorder, and replay behavior with the current nested GA wire contract. - Dedicated `intent=transcription` sockets ignore regular realtime query models. - GA session events serialize `audio.input.format` and `audio.input.transcription`; Beta keeps its flat shim. - Current input-transcription configuration emits progressive transcript events, retains languages, preserves empty transcript fixtures, honors stream timing and interruption controls, and ends at typed `transcript.text.done` without a `[DONE]` sentinel. ## Baseline vs Candidate Local Proof The exact probe ran against a clean detached `8d425a4` worktree and the isolated candidate worktree. It used real local HTTP, WebSocket, recorder proxy, persisted fixture, and replay paths. ### Red: clean `8d425a4` ```text INTENT_MODELS gpt-realtime-2 wrong-model CURRENT_GA {"voice":null,"input_audio_format":"audio/pcm","output_audio_format":null,"input_audio_noise_reduction":null,"input_audio_transcription":{"model":"gpt-transcribe"}} session.created,session.updated,input_audio_buffer.committed INVALID_MODEL Model gpt-realtime-2 does not support session type transcription HTTP interrupt 200 "data: {\"type\":\"transcript.text.delta\",\"delta\":\"ab\"} ... data: {\"type\":\"transcript.text.done\",\"text\":\"abcdefgh\"}\n\nevent: done\ndata: [DONE]\n\n" HTTP missing 404 "{\"error\":{\"message\":\"No fixture matched\",\"type\":\"invalid_request_error\",\"code\":\"no_fixture_match\"}}" HTTP error 422 "{\"error\":{\"message\":\"bad transcription\",\"type\":\"invalid_request_error\",\"param\":null,\"code\":null}}" RECORDED_FIXTURES ... "response":{"transcription":{"text":"hello"}} ``` ### Green: candidate `6ae6ec4` ```text INTENT_MODELS gpt-transcribe gpt-transcribe CURRENT_GA {"input":{"format":{"type":"audio/pcm"},"noise_reduction":null,"transcription":{"model":"gpt-transcribe"}},"output":{"format":null,"voice":null}} session.created,session.updated,input_audio_buffer.committed,conversation.item.added,conversation.item.input_audio_transcription.delta...,conversation.item.input_audio_transcription.completed INVALID_MODEL Model wrong-model does not support session type transcription HTTP interrupt FETCH_ERROR TypeError: terminated HTTP missing 404 "{\"error\":{\"message\":\"No fixture matched\",\"type\":\"invalid_request_error\",\"code\":\"no_fixture_match\"}}" HTTP error 422 "{\"error\":{\"message\":\"bad transcription\",\"type\":\"invalid_request_error\",\"param\":null,\"code\":null}}" RECORDED_FIXTURES ... "response":{"transcription":{"text":"hello","languages":[{"code":"en"}]}} ``` ## Validation ```text prettier --check PASS eslint PASS tsc --noEmit PASS Focused protocol suites: 312 tests PASS Full pnpm test and pnpm build completed after the GA conformance update with no failure output. ``` ## Fourth-Pass Red-Green Red: terminal reported four stale GA expectations (legacy audio transcription field and missing ). Green: RUN v3.2.4 /private/tmp/aimock-live-transcribe-pr.0mGErr ✓ src/__tests__/ws-realtime.test.ts (83 tests) 7614ms Test Files 1 passed (1) Tests 83 passed (83) Start at 14:39:20 Duration 8.13s (transform 235ms, setup 0ms, collect 300ms, tests 7.61s, environment 0ms, prepare 44ms) passed 83/83. Direct clean-baseline vs candidate VAD probe changed into nested , progressive live deltas, and journal interruption before completion. Full format, lint, typecheck, 145-file test suite, and build passed. Fourth-pass proof: red terminal ws-realtime test had four stale GA audio expectation failures. Green exact file: 83 of 83 passed. Clean baseline VAD emitted an error; candidate returned nested audio.input.turn_detection server_vad, progressive deltas, and truncateAfterChunks journal interruption. Full format, lint, typecheck, 145-file tests, and build passed. Fifth-pass red-green: baseline emitted GA session type conversation, top-level turn_detection, and accepted model mutation. Candidate emits realtime for normal GA sessions, keeps VAD under audio.input, rejects established model mutation, and preserves explicit transcription/translation session types. Red conformance test at ws-api-conformance line 618 is now green (66/66); full format, lint, tsc, tests, and build passed. ## Sixth-Pass Red-Green Red: clean baseline 2871866 accepted a real WebSocket mixed model/type update and persisted `gpt-4o-transcribe transcription must-not-mutate`. Green: candidate returned `error invalid_session_config`; its next valid update reported `gpt-realtime-mini realtime safe`, proving rejection occurs before any session mutation. Live-transcription interruption now uses socket destruction and journals the interruption. Validation: focused ws-realtime suite 83/83 passed. Full format check, lint, typecheck, test suite, and build passed locally. ## P2 Coverage Hardening Commit f2ffc7e adds tests only; it does not change runtime behavior. The clean 71452a7 baseline already demonstrated the documented intent=transcription strict no-match and ErrorResponse paths, versioned model matching, abrupt interrupted socket termination with journal details, and scheduled inter-frame delivery. The new direct tests cover those established paths, HTTP stream=true JSON errors, and JSON/SSE recorder-to-local-replay preservation of languages and usage. Applied as a test-only diff to detached 71452a7, the focused suite passed 132/132; the candidate focused suite also passed 132/132. Full format, lint, typecheck, test, and build passed on the candidate. ## API-key validation and proxy isolation This PR also adds opt-in, server-wide inbound API-key validation for the pending `1.38.0` Node release, plus the `aimock-pytest` `0.5.2` helper support. No major-version change is included. - Validates `Authorization: Bearer`, `X-API-Key`, `X-Goog-API-Key`, `Api-Key`, and `xi-api-key` before fixture, proxy, control, and WebSocket handling. - Leaves `/health`, `/ready`, and `/metrics` public; validates auth-enabled bare `OPTIONS` requests and WebSocket upgrades before mount routing. - Treats test credentials as inbound-only: direct-recording paths remove them before egress and use configured provider credentials. Missing provider credentials fail locally with `502`, without calling upstream. - Adds `api_key` and `--aimock-api-key` support to the pytest helper, injected through the child environment rather than command-line arguments. ## Local API-key red-green proof Observed against the real server before the implementation: ```text HTTP_RED 200 {"id":"chatcmpl-EjY1_yI49ir9kGx0","object":"chat.completion","created":1785787642,"model":"gpt-4","choices":[{"index":0,"message":{"role":"assistant","content":"fixture-content","refusal":null},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":2,"completion_tokens":4,"total_tokens":6}} WS_RED HTTP/1.1 101 Switching Protocols ``` The same raw HTTP/WebSocket probe after the implementation: ```text HTTP_CANDIDATE wrong-key 401 {"error":{"message":"Invalid API key","type":"authentication_error","code":"invalid_api_key"}} HTTP_VALID 200 fixture-content WS_CANDIDATE wrong-key HTTP/1.1 401 Unauthorized HTTP_CANDIDATE test-key 200 {"id":"chatcmpl-ULZ9ObI2WG8hJhas","object":"chat.completion","created":1785788256,"model":"gpt-4","choices":[{"index":0,"message":{"role":"assistant","content":"fixture-content","refusal":null},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":2,"completion_tokens":4,"total_tokens":6}} HTTP_VALID 200 fixture-content WS_CANDIDATE test-key HTTP/1.1 101 Switching Protocols ``` ## Value checks - HTTP completion: a wrong key changed from `200` to `401`; the configured key remains `200` with the recorded fixture. - Realtime WebSocket: a wrong key changed from `101 Switching Protocols` to literal `401`; the configured key still upgrades with `101`. - Generic recorder/proxy: an inbound test key is stripped and replaced with the configured provider key; with no provider key it returns local `502` and the fake upstream receives zero requests. - Pytest helper: the child and control request both receive the configured key; `PYTHONPATH=src AIMOCK_CLI_PATH=../../dist/cli.js pytest -q -p aimock_pytest.plugin` passed all 18 tests. ## Validation ```text pnpm format:check PASS pnpm lint PASS pnpm exec tsc --noEmit PASS pnpm build PASS pnpm test:exports PASS pnpm test 167 files passed, 4802 passed, 3 skipped pytest helper integration 18 passed git diff --check PASS ``` ## CR repair: request-scoped API-key egress This follow-up removes the process-global record-config auth marker. The egress policy is now tied to the authenticated incoming request, so servers that reuse a `RecordConfig` cannot affect one another. It also accepts `bearer` and `key` schemes case-insensitively, removes `Authorization` case-insensitively before OpenRouter off-origin unsigned-URL fetches, and applies the same no-implicit-provider-key policy to AG-UI, fal, and video egress. The release remains Node `1.38.0` and pytest `0.5.2`; no major or additional root-version bump is included. PyPI publishing is now gated on the pinned npm release existing first, enforcing npm `1.38.0` before pytest `0.5.2`. ### Local red-green proof Clean `f3a21fb` baseline, exercised against live local server sockets and a local proxy upstream: ```text LOWERCASE_HTTP_RED 401 LOWERCASE_WS_RED HTTP/1.1 401 Unauthorized SERVER_ISOLATION_RED 502 NO_EGRESS OFF_ORIGIN_RED expected 'Bearer provider-key' to be undefined ``` The identical raw HTTP/WebSocket/proxy probes after the repair: ```text LOWERCASE_HTTP_GREEN 200 LOWERCASE_WS_GREEN HTTP/1.1 101 Switching Protocols SERVER_ISOLATION_GREEN 200 Bearer external-client-key OFF_ORIGIN_GREEN undefined ``` ### Coverage added - Real raw duplicate credential lines and lowercase `bearer` / `key` WebSocket upgrade coverage. - Two-server shared-`RecordConfig` isolation regression. - Foreign-host OpenRouter capture that asserts a configured provider `Authorization` is absent. - Direct authenticated AG-UI and fal egress: `502` with zero upstream requests when no provider key exists; OpenRouter video path is covered by the foreign-host capture. - CLI config-file auth plus `AIMOCK_API_KEYS` override integration. - Real pytest subprocess using `--aimock-api-key` and the plugin fixture. ### Final validation ```text pnpm format:check PASS pnpm lint PASS pnpm exec tsc --noEmit PASS pnpm test 167 files passed, 4806 passed, 3 skipped pnpm build PASS pnpm test:exports PASS pytest helper integration 19 passed pnpm install --frozen-lockfile --ignore-scripts PASS actionlint publish-pytest.yml PASS docker buildx (native default context) PASS git diff --check PASS ``` ### Pytest CI repair The release test subprocess now disables automatic plugin discovery before it explicitly loads `aimock_pytest.plugin`. This prevents installed pytest entry point discovery from registering the same plugin a second time. Local installed-package red-green proof (Python 3.12): ```text RED: ValueError: Plugin already registered under a different name: aimock=<module 'aimock_pytest.plugin' ...> GREEN: 1 passed, 13 deselected in 0.43s GREEN full installed-package suite: 19 passed in 5.85s ``` The repeated final gate is green: format, lint, TypeScript, full Node suite (167 files, 4,806 passed, 3 skipped), build, exports, and source-tree pytest integration (19 passed). ### Publish-workflow security repair `actions/setup-node` v7 enabled package-manager caching by default in the PyPI publish workflow. Caching is unnecessary for this small `npm view` release ordering check, so the workflow now explicitly sets `package-manager-cache: false`. ```text RED: error[cache-poisoning] at publish-pytest.yml:25 GREEN: zizmor: No findings to report GREEN: actionlint publish-pytest.yml PASS ``` ### Shipper repair: release ordering and credential journals Commit `0e74e57` removes the independent PyPI workflow. PyPI publication now runs as a `Release` job after the npm publish job succeeds (or after the already-published npm version is confirmed), then verifies the pinned npm version before a wheel can be built. Unit CI builds before the CLI suite, so the CLI auth integration is no longer skipped. The pytest plugin clears an inherited `AIMOCK_API_KEYS` value unless `--aimock-api-key` explicitly sets one. Journal header redaction now calls the same accepted-inbound-credential registry as authentication, including Google and ElevenLabs API-key headers. Local red-green proof from `29645e1`: ```text RED release workflow: missing release-after-npm contract and unit pnpm build step RED journal guard: x-goog-api-key and xi-api-key retained their credential values RED live journal: x-goog-api-key: primary; xi-api-key: primary RED pytest fixture: ambient AIMOCK_API_KEYS made its unauthenticated control health check fail GREEN release/auth targeted suite: 15 passed GREEN built CLI integration suite: 26 passed, including config auth and AIMOCK_API_KEYS override GREEN pytest subprocess cases: 2 passed GREEN pytest package suite: 20 passed GREEN actionlint + zizmor release/unit workflows: PASS ``` Final validation repeated: `pnpm format:check`, `pnpm lint`, `pnpm exec tsc --noEmit`, `pnpm test`, `pnpm build`, `pnpm test:exports`, pytest `20 passed`, `pnpm install --frozen-lockfile --ignore-scripts`, `actionlint`, `zizmor`, and `git diff --check` all passed.
2 parents 3d65dc1 + fcd8d56 commit b945cef

46 files changed

Lines changed: 3083 additions & 305 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.claude-plugin/marketplace.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"source": {
1010
"source": "npm",
1111
"package": "@copilotkit/aimock",
12-
"version": "^1.35.1"
12+
"version": "^1.38.0"
1313
},
1414
"description": "Fixture authoring skill for @copilotkit/aimock — LLM, multimedia (image/TTS/transcription/video), MCP, A2A, AG-UI, vector, embeddings, structured output, sequential responses, streaming physics, record/replay, agent loop patterns, and debugging"
1515
}

‎.claude-plugin/plugin.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "aimock",
3-
"version": "1.35.1",
3+
"version": "1.38.0",
44
"description": "Fixture authoring guidance for @copilotkit/aimock — LLM, multimedia, MCP, A2A, AG-UI, vector, and service mocking",
55
"author": {
66
"name": "CopilotKit"

‎.github/workflows/publish-pytest.yml‎

Lines changed: 0 additions & 48 deletions
This file was deleted.

‎.github/workflows/publish-release.yml‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,3 +155,53 @@ jobs:
155155
curl -s -X POST "$SLACK_WEBHOOK" \
156156
-H "Content-Type: application/json" \
157157
-d "$PAYLOAD"
158+
159+
publish-pytest:
160+
needs: [build, publish]
161+
if: >-
162+
always() &&
163+
(needs.publish.result == 'success' || needs.build.outputs.published == 'true')
164+
runs-on: ubuntu-latest
165+
environment: pypi
166+
permissions:
167+
contents: read
168+
id-token: write
169+
steps:
170+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
171+
with: { persist-credentials: false }
172+
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
173+
with:
174+
python-version: "3.12"
175+
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
176+
with:
177+
node-version: "24"
178+
package-manager-cache: false
179+
180+
- name: Verify pinned npm release is published
181+
run: |
182+
VERSION=$(python -c "import sys; sys.path.insert(0, 'packages/aimock-pytest/src'); from aimock_pytest._version import AIMOCK_VERSION; print(AIMOCK_VERSION)")
183+
npm view "@copilotkit/aimock@${VERSION}" version
184+
185+
- name: Install build tools
186+
run: pip install hatch
187+
188+
- name: Check if pytest version is already published
189+
id: check
190+
run: |
191+
VERSION=$(python -c "import tomllib; print(tomllib.load(open('packages/aimock-pytest/pyproject.toml', 'rb'))['project']['version'])")
192+
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
193+
if pip install "aimock-pytest==$VERSION" --dry-run --no-deps 2>/dev/null; then
194+
echo "published=true" >> "$GITHUB_OUTPUT"
195+
else
196+
echo "published=false" >> "$GITHUB_OUTPUT"
197+
fi
198+
199+
- name: Build pytest package
200+
if: steps.check.outputs.published == 'false'
201+
run: cd packages/aimock-pytest && hatch build
202+
203+
- name: Publish pytest package to PyPI
204+
if: steps.check.outputs.published == 'false'
205+
uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # release/v1
206+
with:
207+
packages-dir: packages/aimock-pytest/dist/

‎.github/workflows/test-unit.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,5 @@ jobs:
2323
node-version: ${{ matrix.node-version }}
2424
cache: pnpm
2525
- run: pnpm install --frozen-lockfile
26+
- run: pnpm build
2627
- run: pnpm test

‎CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,14 @@
22

33
## [Unreleased]
44

5+
## [1.38.0] - 2026-08-03
6+
57
### Added
68

9+
- OpenAI transcription replay for `gpt-transcribe` HTTP streams and `gpt-live-transcribe` Realtime sessions. Recorded responses retain transcript languages and usage metadata; replay supports progressive transcript events, timing controls, strict fixture matching, and interruption behavior.
10+
- Opt-in inbound API-key validation for HTTP, control, mount, and WebSocket boundaries. Validated test credentials are never forwarded by the generic record/proxy path; auth-enabled proxying requires a configured provider credential.
11+
- API-key egress isolation is request-scoped across generic, AG-UI, fal, and video record paths. Authorization schemes are case-insensitive, and OpenRouter off-origin unsigned URLs never receive a configured provider credential.
12+
- `aimock-pytest` `0.5.2` is released by the Release workflow after npm `@copilotkit/aimock` `1.38.0`; the PyPI job verifies the pinned npm package is available before building a wheel.
713
- **Reasoning `encrypted_content` on the Responses API.** aimock now synthesizes an opaque (base64) `reasoning.encrypted_content` blob on the TERMINAL reasoning item (`response.output_item.done` and non-streaming `output[]`). Emitted only when the request wants it: `include: ["reasoning.encrypted_content"]` OR a stateless request (`store: false` / ZDR). Stored / opted-out replays stay byte-identical. A request carrying the EXPLICIT `include: ["reasoning.encrypted_content"]` opt-in, against a reasoning-CAPABLE model, now gets a reasoning item even when the fixture declares NO `reasoning` summary — a `summary: []` item that exists purely to carry the blob, matching what real OpenAI returns when summaries were never requested. This is the shape a fixture recorded from the real stateless agent-framework flow has, so gating the item on a declared summary starved the exact case the feature exists to serve. The synthesized item leads `output[]` / takes `output_index` 0 and shifts the rest, emits `output_item.added` → `output_item.done` with no summary-text events (there is no summary part to describe), and is suppressed for non-reasoning models (gpt-4o etc.), which have no reasoning channel at all. Note the two gates differ in width on purpose: `store: false` still attaches the blob to a reasoning item that a declared summary already produces, but it does NOT synthesize an item where the fixture declares none — creating an output item that did not previously exist is a bigger behavior change than adding a field to one already on the wire, so it takes the gate that is directly observable in the request. `agent-framework-openai` >= 1.11.0 sends `include` and never `store`, so the narrower gate costs the feature nothing. This lets `agent-framework-openai` >= 1.11.0 replay reasoning-paired tool calls on a stateless reasoning + multi-tool chain (related: microsoft/agent-framework#7233). Applies to both the HTTP and WebSocket Responses transports. Known limitations: the blob is withheld from the in-progress `added` item, which is aimock's own simplification rather than upstream parity — real OpenAI populates `added` too (recorded captures carry a shorter blob there beside an empty summary, re-encrypted by `done`), but the field is `anyOf: [string, null]` and non-required, so omitting it is contract-legal and no known consumer requires it; and aimock skips inbound reasoning items, so it cannot reproduce OpenAI's `invalid_encrypted_content` rejection of a mismatched blob/id.
814
- **OpenRouter chat / LLM router simulation.** Requests whose original path starts with `/api/v1/` (point any OpenAI SDK at a `baseURL` ending `/api/v1`) are detected as OpenRouter and shaped to match real OpenRouter bytes: a `gen-` id prefix (a fixture `id` override still wins), a top-level `provider` (default = the winning model slug's author, fixture-overridable via `provider`), both `finish_reason` and `native_finish_reason` on every choice/delta, an always-present `system_fingerprint` and `service_tier` (null by default), `message.reasoning`, and a rich `usage` with a **fixture-scriptable** `cost` + `cost_details` (emitted only when a fixture supplies a cost — never fabricated), plus `is_byok` / `prompt_tokens_details` / `completion_tokens_details` when overridden. Callers on the plain OpenAI `/v1/...` base are byte-for-byte unchanged.
915
- **`models[]` fallback (router failover) simulation.** When the request body carries `models: [...]`, aimock walks `[model, ...models]` in order and serves the first fixture returning a NON-error response; a `429`/`503` error fixture on a candidate simulates a runtime provider failure and falls through to the next. The winning slug is echoed back as the top-level `model`, so a test asserts failover by reading `response.model`. (Deliberate non-goal: an unknown/invalid model is a fixture miss, not OpenRouter's up-front invalid-model 400.)
@@ -12,6 +18,10 @@
1218
- **Opt-in `: OPENROUTER PROCESSING` SSE keepalive** (fixture option `openRouterProcessing`, default off): one comment line emitted before the first data frame, matching real OpenRouter streams.
1319
- OpenRouter request extensions (`provider`, `models`, `route`, `reasoning`, `plugins`, `prediction`, `usage`) and attribution headers (`HTTP-Referer`, `X-OpenRouter-Title`, legacy `X-Title`) are accepted and journaled, never required or rejected.
1420

21+
### Fixed
22+
23+
- **`GET /__aimock/journal` no longer leaks accepted inbound credentials.** Journal header redaction is now derived from the same registry that decides which headers are accepted as credentials, so the two can no longer drift apart. Previously only `authorization`, `x-api-key` and `api-key` were redacted while `x-goog-api-key` and `xi-api-key` were accepted as credentials and journaled **in plaintext** — so a real Gemini / Veo / ElevenLabs key sent on those headers appeared verbatim in the journal, which is unauthenticated unless inbound API-key validation is enabled. Affects 1.37.4 and earlier. A test asserts every accepted header redacts, so adding a new accepted header without redacting it now fails.
24+
1525
## [1.37.4] - 2026-07-20
1626

1727
### Fixed

‎README.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,24 @@ Private and link-local addresses (loopback, RFC1918, CGNAT, cloud metadata, ULA,
127127

128128
On replay, `turnIndex` is a non-fatal disambiguator, not a hard reject gate: a content-matching fixture is served even when its scripted `turnIndex` differs from the request's assistant-message count. This kills false "no fixture matched" misses for multi-bubble agent runs (multi-step agents emit several assistant bubbles per logical turn). When a served fixture diverges from its scripted `turnIndex`, the match diagnostic carries `turnIndexRelaxed: true` and aimock logs a one-shot warning (at the `warn` log level — silent by default). To restore the legacy strict behavior where a defined `turnIndex` must equal the assistant count exactly, set `AIMOCK_STRICT_TURN_INDEX=1`. The record path is always strict regardless of this flag.
129129

130+
## API-key validation
131+
132+
By default aimock accepts all requests. Opt into inbound test-client validation with a programmatic option, top-level `aimock.json` field, or environment-only key list:
133+
134+
```ts
135+
await createServer(fixtures, { auth: { apiKeys: ["test-key"] } });
136+
```
137+
138+
```json
139+
{ "auth": { "apiKeys": ["test-key"] } }
140+
```
141+
142+
```bash
143+
AIMOCK_API_KEYS=test-key,rotated-key npx @copilotkit/aimock --config aimock.json
144+
```
145+
146+
Use `Authorization: Bearer <key>`, `Authorization: Key <key>`, `x-api-key`, `x-goog-api-key`, `api-key`, or `xi-api-key`. Every supplied credential must resolve to one configured key; mismatches return `401` with an OpenAI-compatible authentication error. HTTP routes, control APIs, mounts, and WebSocket upgrades are protected. Genuine CORS preflights plus `GET /health`, `GET /ready`, and `GET /metrics` remain public. This is inbound test access control, distinct from `record.providerKeys`; when enabled, proxying strips test credentials and requires a configured static provider credential before egress.
147+
130148
### aimock-owned upstream keys — `AIMOCK_PROVIDER_*_KEY`
131149

132150
In record or `--proxy-only` mode, aimock forwards the caller's auth header to the real provider unchanged. If your tests can only send a dummy placeholder key (e.g. an SDK that refuses to start without a non-empty API key), aimock can inject its own configured upstream key on a fixture-miss passthrough so the proxied call actually authenticates. Each provider has an independent env var, and the key is applied with the provider-correct wire scheme:

‎charts/aimock/Chart.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@ name: aimock
33
description: Mock infrastructure for AI application testing (OpenAI, Anthropic, Gemini, MCP, A2A, vector)
44
type: application
55
version: 0.1.0
6-
appVersion: "1.35.1"
6+
appVersion: "1.38.0"

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@copilotkit/aimock",
3-
"version": "1.37.4",
3+
"version": "1.38.0",
44
"description": "Mock infrastructure for AI application testing — LLM APIs, image generation, image editing, text-to-speech, transcription, audio translation, audio generation, video generation, embeddings, MCP tools, A2A agents, AG-UI event streams, vector databases, search, rerank, and moderation. One package, one port, zero dependencies.",
55
"license": "MIT",
66
"keywords": [

‎packages/aimock-pytest/README.md‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,14 @@ aimock.reset() # alias for reset_fixtures()
7979

8080
```
8181
--aimock-node PATH Path to node binary
82-
--aimock-version VER aimock npm version (default: 1.35.1)
82+
--aimock-version VER aimock npm version (default: 1.38.0)
83+
--aimock-api-key KEY Inbound API key for the aimock child process
8384
```
8485

86+
## API-key validation
87+
88+
Pass `pytest --aimock-api-key test-key` to protect the aimock child. The helper sends this key on all control API calls, and the child receives it through `AIMOCK_API_KEYS`, never through process arguments. Direct client calls must use `Authorization: Bearer test-key`. For direct construction, use `AIMockServer(node_manager, api_key="test-key")`.
89+
8590
## Environment Variables
8691

8792
| Variable | Description |
@@ -127,8 +132,10 @@ The `test-pytest.yml` workflow:
127132

128133
Tests run across a matrix of Python 3.10--3.13 and Node 20/22.
129134

130-
The `publish-pytest.yml` workflow publishes to PyPI on pushes to `main` when
131-
the version in `pyproject.toml` has not already been published.
135+
The Release workflow publishes `aimock-pytest` to PyPI after its npm publish
136+
job succeeds. Its PyPI job verifies that the `AIMOCK_VERSION` pin exists on
137+
npm before building a wheel, so npm publication completes before the
138+
corresponding `aimock-pytest` release.
132139

133140
## License
134141

0 commit comments

Comments
 (0)