Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

- Require a complete SSE `[DONE]` event as well as a normal finish reason before accepting success. Report missing markers and unfinished trailing frames as protocol diagnostics while preserving received text.
- Observe framing through the existing custom fetch seam, keeping the pinned SDK for payload parsing and validation, with bounded framing state and source-reader cleanup.
- Add completion-framing regressions and correct the distinction between numeric Chat Completions error codes and string Responses API codes.

## 0.1.1 — 2026-11-12

- Reject malformed API-key header values as input diagnostics before transport, with CLI exit 2 and no credential disclosure. Fixes [#1](https://github.com/dannymitchelldev/streamcheck/issues/1).
Expand Down
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ Omit `--env-file` when `OPENROUTER_API_KEY` is already in the environment. This

| Outcome | Meaning | Default CLI exit |
| --- | --- | ---: |
| `success` | Normal completion accepted through the SDK | 0 |
| `success` | Normal finish and complete `[DONE]` event observed | 0 |
| `failed` | Failure before receiving text | 1 |
| `interrupted` | Failure with received text preserved | 3 |
| `cancelled` | Caller cancellation, with any text preserved | 130 |
Expand All @@ -132,7 +132,7 @@ Every input/configuration diagnostic exits **2**. Timeout exits **124**, includi
`schemaVersion: 1` results include exact text, timing, observed HTTP status, first finish reason, and warnings. Unknown metadata is `null`. Failed/interrupted results add `error: { kind, phase, message, code? }`; cancellation records `reason: 'caller'`. See the [public TypeScript types](src/types.ts) for every field.

- **Partial output:** true exactly when text is nonempty and normal completion was not accepted. Successful `length` and `content_filter` results set it false and carry `token_limit` / `content_filter` warnings. The flag does not judge answer quality.
- **Completion:** a normal finish reason is provisional while accounting frames drain. A later observable error, conflict, cancellation, or deadline can still win. Identical repeated reasons are harmless. Tool calls are unsupported.
- **Completion:** success requires a normal finish reason and a complete SSE `[DONE]` event. A normal finish remains provisional while accounting frames drain; EOF without `[DONE]` or with an unfinished trailing frame is a protocol diagnostic, with received text retained. A later provider error, conflict, cancellation, or deadline can still win. Identical repeated reasons are harmless. Tool calls are unsupported.
- **Cancellation:** first accepted terminal outcome wins. Deadline and caller-abort handlers record their cause before aborting transport. A pre-aborted signal sends no request. Accepted success survives later cancellation.
- **Callbacks:** each text delta is accumulated before synchronous `onText`. A thrown callback preserves its triggering delta. The first observed finish reason is retained even when a callback throws or cancels on the same frame. Do not pass async callbacks; promises and asynchronous rejections are outside this contract.
- **Timing:** first-token time means time to the first nonempty text delta. It excludes initial module loading and is not a tokenizer measurement. Elapsed time ends when a terminal outcome is accepted, before final cleanup.
Expand All @@ -143,11 +143,13 @@ Every input/configuration diagnostic exits **2**. Timeout exits **124**, includi
| --- | --- |
| HTTP 401 / 429 | Request failed before streaming: authentication / rate limiting |
| HTTP 200 plus provider diagnostic | Valid provider error arrived inside the stream, possibly before any text |
| Protocol diagnostic | SDK rejected a payload, finish reason was missing/conflicting, or tool calls appeared |
| Protocol diagnostic | SDK rejected a payload, a finish reason or `[DONE]` was missing, a trailing frame was unfinished, finish reasons conflicted, or tool calls appeared |
| Timeout after a finish reason | The finish remained provisional while the stream drained |
| Null HTTP status | No response metadata was available; StreamCheck never assumes 200 |

The SDK is pinned to **1.5.91**. It accepts numeric chat-stream error codes; a documented string-code shape is rejected as a protocol error. Received text is still retained. The SDK also hides `[DONE]` and discards unfinished trailing SSE frames: after a valid finish reason, a truncated trailing error may remain undetectable. This is SDK-observed completion, not verified complete transport.
The SDK is pinned to **1.5.91**. It accepts numeric Chat Completions error codes; a string-valued `error.code` in a chat-stream chunk is rejected as a protocol diagnostic, with previously received text retained. Current [OpenRouter documentation](https://openrouter.ai/docs/api_reference/errors-and-debugging) specifies numeric codes for Chat Completions and string codes for the separate Responses API.

StreamCheck observes SSE framing through its custom fetch seam while the official SDK parses and validates payloads. This detects a missing `[DONE]` or unfinished event at EOF. Observation ends at the first complete `[DONE]`, matching the SDK's cancellation behavior; it does not establish HTTP EOF, inspect bytes after that terminal event, or prove an upstream root cause.

Configured API keys, authorization headers, and raw SDK exceptions are never logged. User prompts and model text are not automatically redacted and may themselves contain secrets. There is no telemetry or output persistence.

Expand Down
10 changes: 6 additions & 4 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,21 @@ One ESM TypeScript package, one text-stream operation through the official OpenR

`runStreamCheck(LiveOptions): Promise<RunResult>` and `runDemo(DemoOptions?): Promise<RunResult>` expose success, failure without text, interruption with text, and caller cancellation. The CLI consumes these public functions. Defaults: 30,000 ms overall deadline, 256 maximum output tokens, interrupted demo.

Normal finish reasons are provisional until SDK iteration ends. Stop succeeds; length and content_filter succeed with warnings. Identical repeated normal reasons are accounting duplicates; conflicting normal reasons are protocol failures. Valid provider errors are provider failures. Tool calls are unsupported protocol failures. Schema-rejected events are protocol failures, with no attempt to mine rejected payloads for provider codes.
Normal finish reasons are provisional until SDK iteration ends and a complete SSE [DONE] event has been observed. Stop succeeds; length and content_filter succeed with warnings. EOF without [DONE] or with an unfinished trailing event is a protocol failure. Identical repeated normal reasons are accounting duplicates; conflicting normal reasons are protocol failures. Valid provider errors are provider failures. Tool calls are unsupported protocol failures. Schema-rejected events are protocol failures, with no attempt to mine rejected payloads for provider codes.

Only completion choice index zero is supported. An unexpected index or duplicate choice entry is a protocol failure; text from an ambiguous frame is not merged into the selected stream. Previously accepted text is retained. Empty-choice accounting frames are allowed.

`partialOutput` means nonempty received text exists and normal completion was not accepted. It is false for successful length/content_filter results; warnings describe their limitation. Text is appended before calling synchronous onText, including the delta whose callback throws. Async callbacks/rejections are outside the contract.

First accepted terminal outcome wins. Timeout and caller cancellation record their origin before aborting transport. A pre-aborted caller signal returns cancellation before a request. Success is accepted only at SDK iterator exhaustion, so an earlier observable error or timeout while draining wins. First-token latency is time to first nonempty text delta, not a tokenizer measurement.
First accepted terminal outcome wins. Timeout and caller cancellation record their origin before aborting transport. A pre-aborted caller signal returns cancellation before a request. Success is accepted only at SDK iterator exhaustion with both a normal finish and a complete [DONE], so an earlier observable error or timeout while draining wins. Framing checks at exhaustion do not override accepted provider, network, consumer, timeout, or cancellation outcomes. First-token latency is time to first nonempty text delta, not a tokenizer measurement.

## SDK boundary

Pin @openrouter/sdk 1.5.91. Disable retries and inject a no-op debug logger. Observe real response status without consuming or changing responses; use null when unavailable. Never infer 200. Preserve exact decoded text, not raw SDK exceptions or HTTP request metadata.
Pin @openrouter/sdk 1.5.91. Disable retries and inject a no-op debug logger. Observe real response status; use null when unavailable and never infer 200. The internal custom fetcher wraps successful SSE bodies with pull-based byte forwarding, preserving response status/headers and SDK input bytes. Forward cancellation and transport errors and release the source reader at EOF, error, or cancellation. Preserve exact decoded text, not raw SDK exceptions or HTTP request metadata.

The SDK hides whether [DONE] arrived and drops incomplete trailing frames at EOF. An observed normal reason followed by an incomplete trailing error frame can therefore succeed. StreamCheck reports SDK-observed completion, not verified complete transport. Numeric typed provider codes may be retained; rejected string-code errors are protocol diagnostics.
The SDK hides whether [DONE] arrived and drops incomplete trailing events at EOF. A separate bounded framing observer closes that visibility gap: it handles UTF-8/BOM and LF, CRLF, or CR line endings incrementally, retaining only a short line prefix and event flags. It requires an exact single data value [DONE] terminated by a blank line; matching text inside content, comments, or unrelated fields does not certify completion. JSON decoding and validation remain with the SDK. There is no tee or full-body buffering.

The application boundary is the first complete [DONE] event, where the SDK cancels its reader. Bytes after that boundary and full HTTP EOF are not verified. Numeric typed Chat Completions provider codes may be retained; rejected string-code errors remain protocol diagnostics. Current OpenRouter documentation uses numeric codes for Chat Completions and string codes for the separate Responses API.

## CLI and boundaries

Expand Down
35 changes: 33 additions & 2 deletions docs/testing-runbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,43 @@ Tests release timers/readers/listeners. The package-consumer check removes only
- Report actual platform/version checks separately from authored CI jobs.
- CLI subprocess cases intentionally pay the SDK's cold import cost; the final 93-test suite took 54.60 seconds locally. Do not replace subprocess checks with assertions on a fake CLI.
- SIGINT tests use an IPC harness to emit the Node process event portably, including after partial text. This establishes handler behavior, not physical Windows console Ctrl+C behavior.
- Tests exercise SDK-observable EOF semantics; no test can establish that the hidden [DONE] marker or a discarded partial frame was received.
- The SDK gate characterizes its hidden [DONE]/unfinished-event behavior. StreamCheck's completion regressions separately verify its raw framing observer: normal success requires a complete terminal event, and unfinished frames at EOF produce protocol diagnostics.
- When changing argument parsing, cover missing option values before standalone --json, literal --prompt=--json, and the -- terminator. Strict and permissive Node argument parsing interpret missing values differently.
- SDK fixtures must not let another choice's finish certify choice zero. Unexpected/duplicate choice entries are protocol failures; already retained text must survive.
- A cold npm cache exposed an old ENOTCACHED failure: npm ci cached package files without all registry manifests needed by a separate --offline install. Consumer dependency installation now permits npm access. Runtime provider access remains blocked, and installed CLI resolution remains offline.
- Cancellation fixtures must match native fetch signal precedence: `init?.signal ?? request.signal`. SDK 1.5.91 supplies a strongly retained signal through `RequestInit`; observing only the request's weakly linked signal can hang after Node garbage collection. This reproduced an intermittent 10-second compatibility-test timeout without any provider traffic; the fixture now observes the effective signal.

## SDK completion and error-code boundaries

Last verified: 2026-11-14, using the installed `@openrouter/sdk` 1.5.91. Before the observer was added, the targeted regressions reproduced 13 failures, including false success and a source-reader lock left held after cancellation.

### Purpose

Reproduce the distinction between SDK-observed completion and verified receipt of the Chat Completions terminal event, and check error-code classification.

### Setup and safe actions

Use locked dependencies and synthetic HTTP/SSE fixtures. The commands below make no provider requests, need no credentials, and do not modify runtime code. No cleanup is required.

### Verification commands

```sh
npm run test:sdk
npm exec --offline -- vitest run tests/stream-completion.test.ts tests/runner.test.ts
```

Expected: the SDK gate passes 7 tests; the completion/runner command passes 78 tests. All 85 targeted checks passed after adding the observer. The completion file covers missing markers with and without text, unfinished JSON and marker framing, literal markers in unrelated fields/comments/text, fragmented UTF-8/BOM and LF/CRLF/CR, default fetch, source-reader cleanup, and provider/network precedence.

Full verification on Windows / Node 24.18.0 / npm 11.16.0 passed `npm run check`: type checks, build, all 136 tests, and the actual packed-package consumer. `npm run example:demo` also passed. These are offline fixtures; no new live provider verification or cross-platform result is claimed.

### Interpretation

- Success requires an observed normal finish reason and a complete `[DONE]` data event. Missing `[DONE]` or EOF with an unfinished event produces a protocol failure without text, or interruption with exact previously accepted text preserved. Complete provider errors, source transport errors, consumer failures, cancellation, and deadlines retain their existing precedence.
- The SDK alone still hides the distinction between `[DONE]`, EOF, and EOF with an unfinished trailing event. StreamCheck now observes raw framing before SDK parsing. Even valid JSON without the event's final blank line is unfinished. Discarding an unfinished event follows the [SSE standard](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation); StreamCheck reports the missing framing instead of accepting normal completion.
- A string-valued `error.code` in a Chat Completions chunk causes SDK schema rejection and a StreamCheck protocol diagnostic. Prior accepted text survives. This behavior alone does not establish rejection of a documented Chat Completions response: the current [OpenRouter error documentation](https://openrouter.ai/docs/api_reference/errors-and-debugging) specifies numeric codes for Chat Completions and string codes for the Responses API. Recheck the endpoint-specific documentation before claiming a schema mismatch.
- `createSdk` injects an `HTTPClient` and wraps either the native or injected fetcher. Its pull-based observer forwards original body bytes, cancellation, errors, and actual response metadata; it keeps bounded framing state without a tee, full-body buffer, or JSON parser. A substring search for `[DONE]` is insufficient.
- Observation ends at the first complete terminal event, matching SDK cancellation; it does not wait for HTTP EOF or inspect bytes after `[DONE]`. The underlying source reader must be released after EOF, transport errors, and cancellation. No raw frames or SDK exceptions are added to diagnostics or logs.

## Release artifact verification

### Purpose
Expand Down Expand Up @@ -206,7 +237,7 @@ Keep nonsecret evidence needed for review. Credential files and raw scratch outp
- Missing or malformed credentials are setup diagnostics and do not verify provider connectivity. HTTP 401, 402, and 429 require inspecting credential validity, available credit, or rate limits respectively.
- Record failed/interrupted outcomes as observed. A timeout, transport failure, or protocol rejection is not a passing provider check.
- One successful generation establishes the observed model/platform combination at that time. Provider interruption recovery, rate limits, physical console Ctrl+C, other operating systems, and sustained reliability require separate evidence.
- Completion remains SDK-observed. The SDK's documented trailing-frame limitation still applies.
- This saved live receipt predates raw terminal-framing observation. It establishes SDK-observed completion on its recorded commit; the new terminal-event gate is verified separately by the offline completion regressions above.

## Manual live interruption checks

Expand Down
10 changes: 7 additions & 3 deletions src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Fetcher } from '@openrouter/sdk/lib/http.js';
import type { ChatStreamChunk } from '@openrouter/sdk/models';
import { validateHeaderValue } from 'node:http';
import { createSdk } from './sdk.js';
import { SseCompletionObserver } from './sse-completion.js';
import type { Diagnostic, FailureResult, LiveOptions, ResultBase, RunResult, RunSource, WarningCode } from './types.js';

const DEFAULT_TIMEOUT = 30_000;
Expand Down Expand Up @@ -59,6 +60,7 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher,
let normalReason: string | null = null;
let phase: Diagnostic['phase'] = 'request';
const warnings: WarningCode[] = [];
const completion = new SseCompletionObserver();

const cancelReader = () => {
if (reader && !cancelling) cancelling = reader.cancel().catch(() => { /* preserve the accepted outcome */ });
Expand Down Expand Up @@ -87,7 +89,7 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher,
const sdk = createSdk(options.apiKey, fetcher, response => {
httpStatus = response.status;
if (response.ok && response.headers.get('content-type')?.toLowerCase().includes('text/event-stream')) phase = 'stream';
});
}, completion);
const stream = await sdk.chat.send({
chatRequest: {
model: options.model,
Expand All @@ -106,8 +108,10 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher,
const next = await reader.read();
if (terminal) break;
if (next.done) {
if (normalReason) accept({ outcome: 'success' });
else fail('protocol', 'Stream ended without an observed normal finish reason');
if (completion.truncated) fail('protocol', 'Stream ended with an unfinished SSE frame');
else if (!completion.done) fail('protocol', 'Stream ended without an observed [DONE] event');
else if (!normalReason) fail('protocol', 'Stream ended without an observed normal finish reason');
else accept({ outcome: 'success' });
break;
}
const value = next.value;
Expand Down
Loading
Loading