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

## 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).
- Preserve the first observed finish reason when `onText` throws or synchronously cancels on a combined text/finish frame, while retaining text and terminal-outcome precedence. Fixes [#2](https://github.com/dannymitchelldev/streamcheck/issues/2).
- Add regression and normalization-control coverage, and block provider network access in CLI test subprocesses.

## 0.1.0 — 2026-11-12

Initial release.
Expand Down
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ Human mode sends exact received text to stdout and its summary to stderr. JSON m

## Library

From another ESM project, install the [GitHub release](https://github.com/dannymitchelldev/streamcheck/releases/tag/v0.1.0):
From another ESM project, install the [GitHub release](https://github.com/dannymitchelldev/streamcheck/releases/tag/v0.1.1):

```sh
npm install --ignore-scripts https://github.com/dannymitchelldev/streamcheck/releases/download/v0.1.0/streamcheck-0.1.0.tgz
npm install --ignore-scripts https://github.com/dannymitchelldev/streamcheck/releases/download/v0.1.1/streamcheck-0.1.1.tgz
```

```typescript
Expand Down Expand Up @@ -86,6 +86,8 @@ runDemo(options?: DemoOptions): Promise<RunResult>

Live options require `apiKey`, `model`, and `prompt`; both operations accept `signal`, `timeoutMs`, and synchronous `onText`. Defaults are a 30,000 ms overall deadline and, for live runs, 256 maximum output tokens. No retries or automatic continuation occur.

An API key that cannot form a valid HTTP authorization header returns an input diagnostic before any request is sent.

## Why these decisions?

| Decision | Reason |
Expand Down Expand Up @@ -124,7 +126,7 @@ Every input/configuration diagnostic exits **2**. Timeout exits **124**, includi
- **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.
- **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. Do not pass async callbacks; promises and asynchronous rejections are outside this contract.
- **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.

## Troubleshooting and limits
Expand Down
15 changes: 14 additions & 1 deletion docs/engineering-log.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Implementation and review record

## Implementation
## v0.1.0 implementation

AI-assisted implementation from an explicitly reviewed, bounded design. Product code is TypeScript; one package contains the library and CLI. The initial build was local; the first public release adds packaging and distribution checks without changing the library contract.

Expand Down Expand Up @@ -60,3 +60,16 @@ Release regression tests were observed failing before these changes. The checksu
Independent publication review (2026-11-12): completed by a separate AI reviewer over the 37-file public inventory, release scripts, metadata, workflow, tests, examples, and documentation. No Critical, Important, or Minor release defects were found. Core runtime correctness was outside this publication pass and remains covered by the earlier implementation review.

Local publication validation passed on Windows / Node 24.18.0 / npm 11.16.0 with a newly populated npm cache: type checks, build, **95/95 tests** (55.69 seconds), and archive/fresh-consumer checks. Locked dependency versions were unchanged. Two release tests were observed failing before implementation and passing afterward. The public release notes provide the exact-commit CI and downloaded-artifact receipts; this local result alone is not cross-platform evidence.

## v0.1.1 patch

The final public-release review reproduced two minor runtime defects, tracked as [#1](https://github.com/dannymitchelldev/streamcheck/issues/1) and [#2](https://github.com/dannymitchelldev/streamcheck/issues/2). Eight initial regression cases were observed failing against the v0.1.0 implementation before either fix.

- Validate the authorization-header value before SDK construction. Invalid embedded control characters and non-ByteString characters now return input/setup diagnostics without invoking transport or exposing the key. A genuine connection TypeError retains its network classification; a built-CLI regression checks JSON and exit 2.
- Record the first observed finish reason before invoking onText. Callback throw, synchronous caller abort, and abort-then-throw now retain the same frame's finish metadata and exact text. Finish reasons remain provisional; this does not accept success earlier or change which terminal outcome wins.

CLI test subprocesses now preload a provider-fetch guard. The patch changes no locked dependency versions and adds no public API fields.

Independent patch review caught a gap in Headers-only validation: SOH, vertical tab, and DEL are accepted by Headers but rejected by the Node transport. Four additional library/CLI cases were observed failing before adding Node's HTTP field-value validation after header normalization. A separate control preserves the SDK's existing trailing-whitespace normalization. The reviewer also caught a missing fetch guard on the SIGINT subprocess; it now uses the same preload as the other CLI tests.

All 14 targeted regression/control checks passed after these corrections. Final local `npm run check` passed type checks, build, **108/108 tests**, and the fresh packed-consumer check on Windows / Node 24.18.0. Independent AI patch re-review confirmed both review findings resolved, with no remaining runtime findings; additional offline probes covered malformed headers, normalization, genuine connection failure, callback races, and built-CLI JSON/exit codes. Release notes identify the final exact-commit CI run and archive verification. Human implementation review, live providers, macOS, and physical console Ctrl+C remain unverified.
51 changes: 49 additions & 2 deletions docs/testing-runbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ Packing writes the archive; checksum generation writes SHA256SUMS beside it. The
### Verification Commands

```sh
npm run test:package -- <path-to-streamcheck-0.1.0.tgz>
npm run checksum -- <path-to-streamcheck-0.1.0.tgz>
npm run test:package -- <path-to-streamcheck-0.1.1.tgz>
npm run checksum -- <path-to-streamcheck-0.1.1.tgz>
npm run checksum -- --check <path-to-SHA256SUMS>
```

Expand All @@ -105,6 +105,53 @@ Keep published artifacts/checksums as release evidence. Remove only task-owned t

Explicit LF compiler output removes host newline ambiguity. Archive source-map paths must resolve to shipped src files. A raw .cast source is linked, not expected to render inline. MacOS and physical console Ctrl+C are not established by the four-job matrix.

## Patch regressions (v0.1.1)

Last verified: 2026-11-12. Eight initial cases reproduced the two defects against v0.1.0. Independent review added four failing control-character library/CLI cases and a previously passing header-normalization control. All 14 targeted regression/control checks and the full 108-test check passed after correction, including type checks, build, and the fresh package consumer.

### Purpose

Check malformed credential classification and retention of finish metadata when a synchronous text callback terminates a run.

### Setup / Seed Data

Use the locked dependencies and synthetic credentials only. Library cases inject HTTP/SSE fixtures; CLI subprocesses preload a fetch guard that forbids provider network access.

### Safe Actions

The regression commands below send no provider requests. Valid-credential connection failures must remain network diagnostics.

### Destructive / Mutating Actions

The build writes ignored dist files. A full check also creates and cleans up its own isolated package consumer. Neither command publishes a release.

### Steps

1. Build the CLI so subprocess tests use the current runner.
2. Run the targeted regressions and the genuine-connection-failure control.
3. Run the full check; the expected suite is 108 tests.

### Verification Commands

```sh
npm run build
npm exec --offline -- vitest run tests/runner.test.ts tests/cli.test.ts -t 'API key containing|malformed credential headers|finish reason from the triggering frame|authorization-header normalization|returns null HTTP status'
npm run check
```

Expected: the targeted command passes 14 cases. Malformed header values produce input/setup diagnostics before transport, and the built CLI returns one JSON result with exit 2. Callback throw, caller abort, and abort-then-throw retain the same frame's finish reason and text while preserving the accepted outcome.

### Cleanup

No service, credentials, or persistent output is created. Generated build and check artifacts remain ignored.

### Troubleshooting Notes

- Cover embedded LF, CR, NUL, SOH, vertical tab, DEL, and a character outside the HTTP header ByteString range; do not use a real credential in a fixture or test name.
- Headers alone accepts some characters that the Node transport rejects. Validate the normalized HTTP field value too, while retaining the SDK's trailing-whitespace normalization.
- Use a combined text/finish frame. A later finish frame does not reproduce the callback metadata defect.
- Keep finish metadata separate from accepting normal completion: later observable failures while draining must still win.

## Recording

Last verified: 2026-11-11.
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "streamcheck",
"version": "0.1.0",
"version": "0.1.1",
"description": "Diagnose OpenRouter streaming failures without losing partial output.",
"private": true,
"type": "module",
Expand Down
2 changes: 1 addition & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export async function main(args: string[] = process.argv.slice(2)): Promise<numb
const { values, positionals } = parsed;
if (json && (values.help || values.version || !command)) return await invalid('--json requires a run or demo command');
if (values.help || args.length === 0) { await write(process.stdout, HELP); return 0; }
if (values.version) { await write(process.stdout, '0.1.0\n'); return 0; }
if (values.version) { await write(process.stdout, '0.1.1\n'); return 0; }
if (command !== 'run' && command !== 'demo') return await invalid('Choose run or demo; see --help');
if (positionals.length > (command === 'run' ? 1 : 2)) return await invalid('Unexpected positional arguments; see --help');
if (command === 'demo' && (values.model !== undefined || values.prompt !== undefined || values['max-tokens'] !== undefined)) return await invalid('--model, --prompt, and --max-tokens apply only to run');
Expand Down
11 changes: 9 additions & 2 deletions src/runner.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
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 type { Diagnostic, FailureResult, LiveOptions, ResultBase, RunResult, RunSource, WarningCode } from './types.js';

Expand All @@ -18,6 +19,11 @@ export function inputFailure(message: string, source: RunSource | null = null, m
function validate(options: LiveOptions): string | null {
if (!options || typeof options !== 'object') return 'Run options are required';
if (typeof options.apiKey !== 'string' || !options.apiKey.trim()) return 'An OpenRouter API key is required';
try {
const headers = new Headers({ authorization: `Bearer ${options.apiKey}` });
validateHeaderValue('authorization', headers.get('authorization') ?? '');
}
catch { return 'The OpenRouter API key contains invalid HTTP header characters'; }
if (typeof options.model !== 'string' || !options.model.trim()) return 'A nonempty model is required';
if (typeof options.prompt !== 'string' || !options.prompt.trim()) return 'A nonempty prompt is required';
if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs <= 0 || options.timeoutMs > MAX_TIMEOUT)) return 'Timeout must be an integer from 1 to 2147483647 milliseconds';
Expand Down Expand Up @@ -112,6 +118,9 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher,
break;
}
const selected = value.choices[0];
// Keep observed metadata even if the text callback ends this run.
const observedReason = selected?.finishReason;
if (finishReason === null && observedReason) finishReason = observedReason;
const delta = selected?.delta.content;
if (typeof delta === 'string' && delta.length > 0) {
if (firstTokenMs === null) firstTokenMs = performance.now() - startedAt;
Expand All @@ -120,8 +129,6 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher,
catch { fail('consumer', 'The synchronous onText callback failed'); }
}
if (terminal) break;
const observedReason = selected?.finishReason;
if (finishReason === null && observedReason) finishReason = observedReason;
if (value.error) {
fail('provider', 'Provider error during streaming', value.error.code);
break;
Expand Down
20 changes: 17 additions & 3 deletions tests/cli.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { spawn, fork } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { expect, it } from 'vitest';
import { exitCodeFor } from '../src/cli.js';
import { inputFailure } from '../src/runner.js';

const bin = fileURLToPath(new URL('../dist/bin.js', import.meta.url));
const offlinePreload = new URL('./offline-cli.mjs', import.meta.url).href;
function invoke(args: string[], envOverrides: NodeJS.ProcessEnv = {}) {
return new Promise<{ code: number | null; out: string; err: string }>((resolve, reject) => {
const child = spawn(process.execPath, [bin, ...args], {
const child = spawn(process.execPath, ['--import', offlinePreload, bin, ...args], {
env: { ...process.env, OPENROUTER_API_KEY: 'synthetic-key-never-log', OPENROUTER_DEBUG: 'true', ...envOverrides },
stdio: ['ignore', 'pipe', 'pipe'],
});
Expand Down Expand Up @@ -85,6 +87,17 @@ it('reports missing credentials as a JSON input diagnostic with exit 2', async (
expect(JSON.parse(actual.out)).toMatchObject({ source: 'live', httpStatus: null, error: { kind: 'input', phase: 'setup' } });
});

it.each([
['line feed', 'synthetic-invalid\nkey'],
['DEL', 'synthetic-invalid\u007fkey'],
] as const)('reports malformed credential headers (%s) as a JSON input diagnostic with exit 2', async (_label, apiKey) => {
const actual = await invoke(['run', '--model', 'offline/model', '--prompt', 'hello', '--json'], { OPENROUTER_API_KEY: apiKey });
expect(actual.code).toBe(2);
expect(actual.err).toBe('');
expect(JSON.parse(actual.out)).toMatchObject({ source: 'live', outcome: 'failed', httpStatus: null, error: { kind: 'input', phase: 'setup' } });
expect(actual.out).not.toContain('synthetic-invalid');
});

it.each(['1', '150'])('uses timeout exit 124 with one JSON result at %s ms', async timeout => {
const actual = await invoke(['demo', 'interrupted', '--timeout', timeout, '--json']);
expect(actual.code).toBe(124);
Expand All @@ -103,12 +116,13 @@ it.each([[], ['--help'], ['run', '--help']])('prints help without requiring cred
});

it('prints the package version', async () => {
expect(await invoke(['--version'])).toEqual({ code: 0, out: '0.1.0\n', err: '' });
const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
expect(await invoke(['--version'])).toEqual({ code: 0, out: `${version}\n`, err: '' });
});

it.each([true, false])('maps the SIGINT handler to cancellation and exit 130 (json=%s)', async json => {
const actual = await new Promise<{ code: number | null; out: string; err: string }>((resolve, reject) => {
const child = fork(fileURLToPath(new URL('./interrupt-child.mjs', import.meta.url)), ['demo', 'interrupted', ...(json ? ['--json'] : [])], { silent: true });
const child = fork(fileURLToPath(new URL('./interrupt-child.mjs', import.meta.url)), ['demo', 'interrupted', ...(json ? ['--json'] : [])], { silent: true, execArgv: ['--import', offlinePreload] });
let out = ''; let err = ''; let interrupted = false;
const interrupt = () => { if (!interrupted) { interrupted = true; child.send('interrupt'); } };
child.on('message', message => { if (json && message === 'running') interrupt(); });
Expand Down
2 changes: 2 additions & 0 deletions tests/offline-cli.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// CLI regressions must fail closed if validation accidentally reaches transport.
globalThis.fetch = () => { throw new Error('Provider network forbidden in CLI tests'); };
Loading
Loading