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
42 changes: 40 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,47 @@ runStreamCheck(options: LiveOptions): Promise<RunResult>
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.
Live options require `apiKey`, `model`, and exactly one of `prompt` or a nonempty `messages` array; 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.

Conversation input and the Workers verification below are **unreleased checkout features**. The linked v0.1.1 release remains prompt-only; downstream consumers need a separately versioned release artifact before adopting these additions.

```typescript
import { runStreamCheck, type TextMessage } from 'streamcheck';

const messages: readonly [TextMessage, ...TextMessage[]] = [
{ role: 'system', content: 'Explain concepts concisely.' },
{ role: 'user', content: 'What is a webhook?' },
{ role: 'assistant', content: 'An HTTP notification sent when an event occurs.' },
{ role: 'user', content: 'How does the receiver acknowledge it?' },
];
// Explicitly calling this makes one potentially billable provider request.
const result = await runStreamCheck({ apiKey, model, messages, onText(delta) { console.log(delta); } });
```

`TextMessage` supports only `system`, `user`, and `assistant` with nonblank string content. Each entry must be a plain object containing only `role` and `content`; tools, images, and extra fields are rejected. Roles, order, whitespace, and content reach the SDK unchanged. The readonly tuple annotation proves nonemptiness in TypeScript; runtime validation also protects JavaScript callers. Supplying both input properties (even an explicit `undefined`) or neither returns an input/setup diagnostic before transport. An already-aborted signal retains cancellation precedence over invalid options.

Enable TypeScript's `exactOptionalPropertyTypes` to reject an explicitly undefined opposite input at compile time too. Runtime validation always rejects it.

The CLI continues to accept `--prompt`; conversation input is a library API. The application owns history and decides whether an interrupted or warning-bearing answer belongs in it. [Conversation example](examples/conversation.ts) is compiled, without executing a provider call, by `npm run example:demo`.

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

A syntactically valid rejected credential requires a provider response: synthetic HTTP 401 is tested as a request failure after one intercepted request.

## Cloudflare Workers runtime

The installed packed ESM package is verified inside **workerd 1.20260730.1**, compatibility date **2026-07-30**, with **`nodejs_compat`**. This flag is required for the library's native `node:http` header validation. The pinned SDK remains **1.5.91**. The library exports work in this tested runtime; the CLI requires Node.js.

```sh
npm run test:workers
# Verify an existing candidate without repacking it:
npm run test:workers -- <path-to-candidate.tgz>
```

This builds, installs a tarball outside the checkout, bundles its public exports with pinned esbuild, and runs HTTP/SSE fixtures through the real SDK inside workerd. It covers conversation/prompt requests, validation, HTTP/provider/protocol failures, provisional completion, interruption, cancellation, deadlines, synchronous callback failures, warnings, empty success, and reader/listener cleanup. The report identifies the archive SHA-256, versions, compatibility settings, cases, intercepted requests, and zero external requests. An explicit deny service replaces workerd's implicit internet service; no provider credentials, network fallback, deployment, or Cloudflare account is used. See the [Workers runbook](docs/testing-runbook.md#packed-package-workers-verification).

This is synthetic local runtime evidence. It does not establish deployed behavior, live-provider reliability, other compatibility dates/flags, or cessation of provider billing after cancellation.

## Why these decisions?

| Decision | Reason |
Expand Down Expand Up @@ -160,9 +197,10 @@ Retrying or resuming after partial output can duplicate text and incur additiona
```sh
npm run check
npm run example:demo
npm run test:workers
```

The full check covers types, library/CLI tests, release checks, and a consumer of the actual packed package outside the checkout. It inspects archive contents, LF shebang, relative source maps, ESM exports, declarations, and the installed CLI. Dependency installation may use npm; provider execution uses fixtures and is blocked from network access. Package verification also requires the standard `tar` command.
The full check includes `test:workers`, types, library/CLI tests, release checks, and consumers of the actual packed package outside the checkout. It inspects archive contents, LF shebang, relative source maps, ESM exports, positive/negative conversation declarations, and the installed CLI. Dependency installation may use npm; provider execution uses fixtures and is blocked from network access. Package verification also requires the standard `tar` command. Keep npm optional dependencies enabled: esbuild and workerd use platform binaries and support the existing `npm ci --ignore-scripts` installation.

CI runs **Windows/Ubuntu × Node 22.12.0/24**. [View actual runs](https://github.com/dannymitchelldev/streamcheck/actions/workflows/ci.yml?query=branch%3Amain); release notes link the exact validated commit. macOS, live provider behavior, and physical console Ctrl+C are not established by this matrix.

Expand Down
8 changes: 8 additions & 0 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ 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.

`LiveOptions` is an exclusive union: either a nonblank `prompt` string or a nonempty readonly tuple of `TextMessage` entries. `TextMessage` has `role: 'system' | 'user' | 'assistant'` and nonblank string `content`. Entries must be plain objects containing only those two fields. Validate both/neither input, empty/malformed messages, unsupported roles, extra/tool/image structures, and missing/blank/locally malformed credentials before SDK construction or transport. Explicitly supplying both properties, including an undefined property, is invalid at runtime. A pre-aborted caller signal still returns cancellation before option validation. A syntactically valid rejected credential is an HTTP request failure, not a locally knowable input failure.

The prompt path sends one user message. The conversation path copies the supplied roles and content in order without trimming, flattening, mutating history, or adding messages. Results, defaults, synchronous callbacks, CLI prompt behavior, retries, and terminal precedence are shared. Consumer history policy, tools, images, automatic continuation, persistence, and asynchronous callbacks remain outside the contract.

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.
Expand All @@ -24,6 +28,10 @@ The application boundary is the first complete [DONE] event, where the SDK cance

## CLI and boundaries

The unreleased packed library is exercised in workerd 1.20260730.1 with compatibility date 2026-07-30 and `nodejs_compat`, including native `node:http` header validation. No compatibility shim or SDK upgrade is needed for this tested configuration. The CLI remains Node-only. Other runtime dates/flags and deployed/live-provider behavior require separate evidence.

`npm run test:workers` builds and installs an actual tarball in a temporary consumer outside the checkout. Pinned esbuild bundles only the installed public ESM export and its dependencies, leaving `node:*` native. Workerd's test handler runs synthetic HTTP/SSE fixtures through the public operations and real SDK. Global fetch interception observes the effective signal (`init?.signal ?? request.signal`); an explicit non-network internet service denies any escaped fetch, and the host fails on a denial marker. No socket, external service, or network service is configured. The report binds results to archive SHA-256 and exact tool/runtime settings. An explicit archive argument verifies those same bytes without repacking.

Run explicitly makes a live call using OPENROUTER_API_KEY; demo never uses network or ambient credentials. Human text goes to stdout and summary to stderr. JSON is one complete result on stdout. Exit codes: success 0, failure 1, any input diagnostic 2, interruption 3, timeout 124, caller cancellation 130.

Configured credentials, authorization headers, and raw SDK errors are never logged. Prompts and returned text are not automatically redacted. No automatic retry or resume: these can duplicate output and incur additional charges. Cancelling a local stream does not guarantee provider processing or billing stops.
57 changes: 56 additions & 1 deletion docs/testing-runbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Verify the library, SDK boundary, CLI, and packed consumer without provider cred
### Safe Actions

- `npm run test:sdk`: executable pinned-SDK compatibility gate.
- `npm run check`: type checking, built CLI/library tests, and a local packed-package consumer.
- `npm run check`: type checking, built CLI/library tests, packed-package consumers, and the Workers runtime gate.
- `node dist/bin.js demo interrupted`: expected exit **3**, with retained partial text.

### Destructive / Mutating Actions
Expand Down Expand Up @@ -91,6 +91,61 @@ Full verification on Windows / Node 24.18.0 / npm 11.16.0 passed `npm run check`
- `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.

## Packed-package Workers verification

Last verified: 2026-11-14 on Windows / Node 24.18.0 / npm 11.16.0. Package candidate v0.1.1 (unreleased conversation changes), SDK 1.5.91, workerd 1.20260730.1, esbuild 0.28.2. Compatibility date: **2026-07-30**; flags: **`nodejs_compat`**. Wrangler is not used. These are local results; the unchanged Windows/Ubuntu and Node 22.12.0/24 CI matrix runs the same gate through `npm run check`.

### Purpose

Prove the actual packed ESM library's public exports execute in workerd, rather than substituting a source import, Node-only test, or successful bundle. Verify prompt compatibility, exact conversation serialization, setup validation, outcomes/text/finish metadata, disabled retries, synchronous callbacks, cancellation, deadlines, warnings, and cleanup through the real pinned SDK.

### Setup / Seed Data

- Use Node.js 22.12+ and `npm ci --ignore-scripts` with the lockfile and optional dependencies enabled. The platform-specific esbuild/workerd binaries work without install scripts; missing binaries are a setup failure, never permission to skip the runtime gate.
- Only dependency installation may contact npm. All credentials and HTTP/SSE responses are synthetic. No Cloudflare account, Wrangler, provider key, service, or deployment is required.
- `scripts/workers/config.capnp` pins the runtime settings. Its explicit worker named `internet` replaces workerd's automatic public network service. There are no network services, external services, sockets, or disk bindings.

### Safe Actions

`test:workers` builds and packs the candidate, installs it in a task-owned OS temporary directory outside the checkout, bundles its installed public export, and executes the acceptance handler using `workerd test`. An optional archive argument uses those exact bytes without repacking. It never invokes the live examples or live interruption script.

### Destructive / Mutating Actions

Builds write ignored `dist` output. Packing/installation writes only the allocated temporary consumer and npm cache; the temporary directory is removed in `finally` after verifying its parent/name. No publication, GitHub mutation, credential access, or remote infrastructure is part of this check.

### Steps

1. Install locked dependencies with scripts disabled.
2. Run the direct Workers gate or the full check, which includes it once without recursion.
3. Inspect the JSON report: archive SHA-256, package/SDK/tool/host versions, compatibility settings, passed cases, intercepted request count, and `externalRequests: 0`.
4. For a retained candidate, build/pack into an ignored artifact directory and pass that same `.tgz` to both package and Workers commands. Retain the hash and command output with the source revision/dirty state; a local archive is not a release.

### Verification Commands

```sh
npm ci --ignore-scripts
npm run test:workers
npm run check
npm run example:demo
# Optional exact-artifact verification (does not repack):
npm run test:package -- <candidate.tgz>
npm run test:workers -- <candidate.tgz>
```

Expected: exit 0. The runtime cases include HTTP 401/503 with one request, HTTP 200 provider errors before/after text, malformed/missing-finish/missing-DONE/unfinished-frame diagnostics, a stream reset after decoded text, callback throw/abort/abort-then-throw, a deadline while draining after a normal finish, pending-request abort/deadline, accepted success followed by abort, warning-bearing/empty success, and malformed conversation/credential input with zero requests. Pre-aborted invalid input remains cancellation. Every received delta equals the returned text, applicable finish metadata survives failures, source reader locks are released, and abort listeners are removed. Packed declarations separately compile positive prompt/conversation callers and reject both/neither/empty/multimodal/unsupported-role input. The existing prompt CLI consumer is still executed.

### Cleanup

The workerd child exits after its tests; no server listens or persists. The host timeout is 60 seconds and is a failing guard, not an alternative outcome. Only the harness's own verified temporary allocation is recursively removed. Keep explicitly retained candidate archives/checksums as local evidence; do not clear shared caches.

### Troubleshooting Notes

- Transport interception is harness-only. It replaces global fetch inside workerd, observes `init?.signal ?? request.signal`, and asserts actual SDK URL/method/body/authorization. There is no public transport override. Unexpected transport assertions are rethrown outside StreamCheck's normalized results. Any escaped fetch reaches the deny service, emits `STREAMCHECK_FORBIDDEN_EGRESS`, and fails the host check.
- Native `node:http` validation passed; do not add a shim merely because of a Node import. `nodejs_compat` is required by the tested configuration.
- The initial prompt-only packed proof passed before conversation implementation. The final gate must always run the messages-capable archive; that early proof is insufficient by itself.
- Synthetic runtime results do not establish naturally occurring provider faults, deployed Cloudflare behavior, other compatibility settings, or billing cessation. Success still requires normal finish plus complete `[DONE]`; framing observation ends at that terminal event, not full HTTP EOF.
- Conversation features are unreleased. Do not replace the published v0.1.1 bytes: downstream adoption needs a separately authorized versioned GitHub release artifact and exact-artifact verification.

## Release artifact verification

### Purpose
Expand Down
17 changes: 17 additions & 0 deletions examples/conversation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { runStreamCheck, type LiveOptions, type RunResult, type TextMessage } from 'streamcheck';

// Compile-only example: calling this function explicitly makes one potentially billable request.
// The application owns history and decides whether to retain an interrupted answer.
export function answerFollowUp(apiKey: string, model: string): Promise<RunResult> {
const messages: readonly [TextMessage, ...TextMessage[]] = [
{ role: 'system', content: 'Explain concepts concisely.' },
{ role: 'user', content: 'What is a webhook?' },
{ role: 'assistant', content: 'An HTTP notification sent when an event occurs.' },
{ role: 'user', content: 'How does the receiver acknowledge it?' },
];
const options: LiveOptions = {
apiKey, model, messages,
onText(delta) { process.stdout.write(delta); },
};
return runStreamCheck(options);
}
Loading
Loading