From cdb1ac82b4b8eb72eaf124c555563fb75861d1c9 Mon Sep 17 00:00:00 2001 From: Danny Mitchell Date: Sat, 14 Nov 2026 23:24:28 -0600 Subject: [PATCH] feat: support conversations and verify packed package in Workers --- README.md | 42 ++- docs/design.md | 8 + docs/testing-runbook.md | 57 +++- examples/conversation.ts | 17 + package-lock.json | 594 ++++++++++++++++++++++++++++++++++- package.json | 5 +- scripts/package-smoke.mjs | 21 +- scripts/workers-smoke.mjs | 62 ++++ scripts/workers/config.capnp | 20 ++ scripts/workers/consumer.mjs | 210 +++++++++++++ src/index.ts | 2 +- src/runner.ts | 20 +- src/types.ts | 15 +- tests/conversation.test.ts | 73 +++++ 14 files changed, 1131 insertions(+), 15 deletions(-) create mode 100644 examples/conversation.ts create mode 100644 scripts/workers-smoke.mjs create mode 100644 scripts/workers/config.capnp create mode 100644 scripts/workers/consumer.mjs create mode 100644 tests/conversation.test.ts diff --git a/README.md b/README.md index 802bacd..8f56868 100644 --- a/README.md +++ b/README.md @@ -84,10 +84,47 @@ runStreamCheck(options: LiveOptions): Promise runDemo(options?: DemoOptions): Promise ``` -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 -- +``` + +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 | @@ -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. diff --git a/docs/design.md b/docs/design.md index 9eb11a4..914a779 100644 --- a/docs/design.md +++ b/docs/design.md @@ -6,6 +6,10 @@ One ESM TypeScript package, one text-stream operation through the official OpenR `runStreamCheck(LiveOptions): Promise` and `runDemo(DemoOptions?): Promise` 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. @@ -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. diff --git a/docs/testing-runbook.md b/docs/testing-runbook.md index 42df1fa..81b712d 100644 --- a/docs/testing-runbook.md +++ b/docs/testing-runbook.md @@ -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 @@ -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 -- +npm run test:workers -- +``` + +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 diff --git a/examples/conversation.ts b/examples/conversation.ts new file mode 100644 index 0000000..bcc1e1d --- /dev/null +++ b/examples/conversation.ts @@ -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 { + 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); +} diff --git a/package-lock.json b/package-lock.json index af0328d..5f5a2ac 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,13 +16,100 @@ }, "devDependencies": { "@types/node": "^22.0.0", + "esbuild": "0.28.2", "typescript": "7.0.2", - "vitest": "5.1.0" + "vitest": "5.1.0", + "workerd": "1.20260730.1" }, "engines": { "node": ">=22.12.0" } }, + "node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260730.1.tgz", + "integrity": "sha512-+MBHmPaiTe2KajryW0T24rZvWFxb41hD3d8anNzQqHzft6vSEb18+sp0znSwxgij7ApPhSM1+vhkNg4f3YMguA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260730.1.tgz", + "integrity": "sha512-SBHKntPkKvNPgaCrTe99xC1CAl8ygJDzlYfK0LbuJ1muKadIw35WnhO0wu894fKBtllsVQdNzDLee+cm0ppLSQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260730.1.tgz", + "integrity": "sha512-ouyPOSMbiKPeSwUJUvxtMcxGAXs2J4aPE4T5ABIYX5ClcQx5j5bbHTmnqOQEY8sAuLTPjH7dY+iB6UI5ISlwwA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260730.1.tgz", + "integrity": "sha512-YQ+Mi78U3TPdgBPtwq+Sm6rJU+Ihl2y0pjYtuuKkdmUbYzL7oLR6Xqq9wljhasnuCFICssDJaqhMep5WizYoEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260730.1.tgz", + "integrity": "sha512-27fAN+vUECW1oYVc1KOcHYpkL8COM2Uxtxql7TL595kxbjoqS5yckw7NLz7bTf2pALFCZWjqXDjZGJ/xbG4ZKQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, "node_modules/@emnapi/core": { "version": "2.0.0-beta.2", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", @@ -60,6 +147,448 @@ "tslib": "^2.4.0" } }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@jridgewell/resolve-uri": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", @@ -911,6 +1440,48 @@ "dev": true, "license": "MIT" }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, "node_modules/estree-walker": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", @@ -1662,6 +2233,27 @@ "node": ">=20.11" } }, + "node_modules/workerd": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260730.1.tgz", + "integrity": "sha512-zmfNIjwYSWFY5chGBOjWtH3xAE7p97FTC6vR4Ep98290ho6AeAR/NVcBD274YCLEUYzqm8yxdtZlxMybU8a3jA==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20260730.1", + "@cloudflare/workerd-darwin-arm64": "1.20260730.1", + "@cloudflare/workerd-linux-64": "1.20260730.1", + "@cloudflare/workerd-linux-arm64": "1.20260730.1", + "@cloudflare/workerd-windows-64": "1.20260730.1" + } + }, "node_modules/zod": { "version": "4.6.7", "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", diff --git a/package.json b/package.json index b2e5bea..e7f2fa4 100644 --- a/package.json +++ b/package.json @@ -21,8 +21,9 @@ "test": "vitest run", "test:sdk": "vitest run tests/sdk-boundary.test.ts", "test:package": "node scripts/package-smoke.mjs", + "test:workers": "npm run build && node scripts/workers-smoke.mjs", "test:live:interruptions": "npm run build && node scripts/live-interruptions.mjs", - "check": "npm run typecheck && npm test && npm run test:package", + "check": "npm run typecheck && npm test && npm run test:package && npm run test:workers", "demo": "node dist/bin.js demo interrupted", "record:demo": "npm run build && node scripts/record-demo.mjs", "checksum": "node scripts/checksum.mjs", @@ -30,5 +31,5 @@ "example:live": "npm run build && tsc -p examples/tsconfig.json && node .work/examples/live.js" }, "dependencies": { "@openrouter/sdk": "1.5.91" }, - "devDependencies": { "@types/node": "^22.0.0", "typescript": "7.0.2", "vitest": "5.1.0" } + "devDependencies": { "@types/node": "^22.0.0", "esbuild": "0.28.2", "typescript": "7.0.2", "vitest": "5.1.0", "workerd": "1.20260730.1" } } diff --git a/scripts/package-smoke.mjs b/scripts/package-smoke.mjs index 986cb66..d6c6506 100644 --- a/scripts/package-smoke.mjs +++ b/scripts/package-smoke.mjs @@ -66,8 +66,23 @@ assert.equal(result.text, 'Webhooks send HTTP notifications when an event'); `); run(process.execPath, ['consumer.mjs'], temporary); writeFileSync(join(temporary, 'consumer.ts'), ` -import {runDemo, runStreamCheck, type RunResult, type LiveOptions, type DemoScenario} from 'streamcheck'; +import {runDemo, runStreamCheck, type RunResult, type LiveOptions, type TextMessage, type DemoScenario} from 'streamcheck'; const options: LiveOptions = {apiKey:'synthetic', model:'example/model', prompt:'example', onText(delta) { delta.toUpperCase(); }}; +const history: readonly [TextMessage, ...TextMessage[]] = [{role:'system', content:'Keep text'}, {role:'user', content:'Question'}, {role:'assistant', content:'Answer'}]; +const conversation: LiveOptions = {apiKey:'synthetic', model:'example/model', messages:history}; +const next: Promise = runStreamCheck(conversation); +// @ts-expect-error Both input forms must be rejected by the packed declarations. +const both: LiveOptions = {apiKey:'synthetic', model:'example/model', prompt:'example', messages:history}; +// @ts-expect-error One input form is required. +const neither: LiveOptions = {apiKey:'synthetic', model:'example/model'}; +// @ts-expect-error Conversation input must be nonempty. +const empty: LiveOptions = {apiKey:'synthetic', model:'example/model', messages:[]}; +// @ts-expect-error Exact optional property checking forbids the other input even as undefined. +const explicitUndefined: LiveOptions = {apiKey:'synthetic', model:'example/model', prompt:'example', messages:undefined}; +// @ts-expect-error Only text messages with supported roles are exposed. +const tool: TextMessage = {role:'tool', content:'unsupported'}; +// @ts-expect-error String content is required. +const multimodal: TextMessage = {role:'user', content:[{type:'text', text:'unsupported'}]}; const live: Promise = runStreamCheck(options); const result: RunResult = await runDemo({scenario:'interrupted'}); const first: number | null = result.firstTokenMs; @@ -75,9 +90,9 @@ if(result.outcome === 'failed' || result.outcome === 'interrupted') { result.err if(result.outcome === 'cancelled') { const reason: 'caller' = result.reason; } // @ts-expect-error Invalid scenarios must remain a type error. const invalid: DemoScenario = 'invented'; -void live; void first; void invalid; +void live; void first; void invalid; void next; void both; void neither; void empty; void explicitUndefined; void tool; void multimodal; `); - run(process.execPath, [join(root, 'node_modules/typescript/bin/tsc'), '--noEmit', '--strict', '--module', 'NodeNext', '--target', 'ES2023', '--skipLibCheck', 'consumer.ts'], temporary); + run(process.execPath, [join(root, 'node_modules/typescript/bin/tsc'), '--noEmit', '--strict', '--exactOptionalPropertyTypes', '--module', 'NodeNext', '--target', 'ES2023', '--skipLibCheck', 'consumer.ts'], temporary); const cli = JSON.parse(run(process.execPath, [npmCli, 'exec', '--offline', '--', 'streamcheck', 'demo', 'interrupted', '--json'], temporary, 3)); assert.equal(cli.outcome, 'interrupted'); assert.equal(cli.partialOutput, true); diff --git a/scripts/workers-smoke.mjs b/scripts/workers-smoke.mjs new file mode 100644 index 0000000..83eed24 --- /dev/null +++ b/scripts/workers-smoke.mjs @@ -0,0 +1,62 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { basename, dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { build } from 'esbuild'; +import workerd from 'workerd'; + +const root = fileURLToPath(new URL('..', import.meta.url)); +const npmCli = process.env.npm_execpath; +assert(npmCli, 'Run through npm run test:workers'); +assert(process.argv.length <= 3, 'Usage: npm run test:workers -- [artifact.tgz]'); +const supplied = process.argv[2] ? resolve(process.argv[2]) : null; +if (supplied) assert(existsSync(supplied) && statSync(supplied).isFile(), 'Candidate artifact does not exist'); +const temporary = mkdtempSync(join(tmpdir(), 'streamcheck-workers-')); +const compatibilityDate = '2026-07-30'; +const compatibilityFlags = ['nodejs_compat']; +const digest = file => createHash('sha256').update(readFileSync(file)).digest('hex'); +function run(args, cwd = temporary) { + const result = spawnSync(process.execPath, args, { cwd, encoding: 'utf8', timeout: 60_000, windowsHide: true }); + assert.ifError(result.error); + assert.equal(result.status, 0, `${args.join(' ')}\n${result.stderr}\n${result.stdout}`); + return result.stdout; +} + +try { + const tarball = supplied ?? join(temporary, JSON.parse(run([npmCli, 'pack', '--json', '--pack-destination', temporary], root))[0].filename); + const sha256 = digest(tarball); + writeFileSync(join(temporary, 'package.json'), JSON.stringify({ name: 'streamcheck-workers-consumer', private: true, type: 'module' })); + // Only installation uses npm/network. No source aliases or internal package imports. + run([npmCli, 'install', '--ignore-scripts', '--no-audit', '--no-fund', tarball]); + const bundle = await build({ + stdin: { contents: readFileSync(new URL('./workers/consumer.mjs', import.meta.url), 'utf8'), resolveDir: temporary, sourcefile: 'consumer-worker.mjs' }, + absWorkingDir: temporary, bundle: true, write: false, metafile: true, + format: 'esm', platform: 'neutral', conditions: ['workerd', 'worker', 'browser'], + mainFields: ['module', 'main'], external: ['node:*'], target: 'es2023', + }); + assert(Object.keys(bundle.metafile.inputs).some(file => file.replaceAll('\\', '/').endsWith('node_modules/streamcheck/dist/index.js')), 'Must bundle installed public ESM export'); + writeFileSync(join(temporary, 'consumer.mjs'), bundle.outputFiles[0].text); + writeFileSync(join(temporary, 'config.capnp'), readFileSync(new URL('./workers/config.capnp', import.meta.url))); + const executed = spawnSync(workerd.default, ['test', 'config.capnp', 'streamcheck'], { + cwd: temporary, encoding: 'utf8', timeout: 60_000, windowsHide: true, + }); + assert.ifError(executed.error); + assert.equal(executed.status, 0, `${executed.stdout}\n${executed.stderr}`); + const output = `${executed.stdout}\n${executed.stderr}`; + const externalRequests = output.split('STREAMCHECK_FORBIDDEN_EGRESS').length - 1; + assert.equal(externalRequests, 0, 'Unexpected runtime egress attempt'); + const report = JSON.parse(output.split(/\r?\n/).find(line => line.startsWith('STREAMCHECK_REPORT='))?.slice('STREAMCHECK_REPORT='.length) ?? 'null'); + assert(report?.passed?.length, `Missing workerd acceptance report: ${output}`); + assert.equal(digest(tarball), sha256, 'Verification must not modify the archive'); + const installed = JSON.parse(readFileSync(join(temporary, 'node_modules/streamcheck/package.json'), 'utf8')); + const version = name => JSON.parse(readFileSync(join(root, 'node_modules', name, 'package.json'), 'utf8')).version; + const sdk = JSON.parse(readFileSync(join(temporary, 'node_modules/@openrouter/sdk/package.json'), 'utf8')).version; + console.log(JSON.stringify({ package: `streamcheck@${installed.version}`, sdk, workerd: version('workerd'), esbuild: version('esbuild'), node: process.version, compatibilityDate, compatibilityFlags, sha256, externalRequests, ...report }, null, 2)); +} finally { + assert.equal(dirname(resolve(temporary)), resolve(tmpdir())); + assert(basename(temporary).startsWith('streamcheck-workers-')); + rmSync(temporary, { recursive: true, force: true }); +} diff --git a/scripts/workers/config.capnp b/scripts/workers/config.capnp new file mode 100644 index 0000000..5a92417 --- /dev/null +++ b/scripts/workers/config.capnp @@ -0,0 +1,20 @@ +using Workerd = import "/workerd/workerd.capnp"; + +const config :Workerd.Config = ( + services = [ + (name = "streamcheck", worker = ( + modules = [(name = "consumer.mjs", esModule = embed "consumer.mjs")], + compatibilityDate = "2026-07-30", + compatibilityFlags = ["nodejs_compat"], + globalOutbound = "internet" + )), + # Defining internet explicitly replaces workerd's implicit public network. + # No network service, external service, listening socket, or disk binding exists. + (name = "internet", worker = ( + modules = [(name = "deny.mjs", esModule = "export default { fetch() { console.error('STREAMCHECK_FORBIDDEN_EGRESS'); throw new Error('External network forbidden'); } };")], + compatibilityDate = "2026-07-30", + globalOutbound = "internet" + )) + ], + sockets = [] +); diff --git a/scripts/workers/consumer.mjs b/scripts/workers/consumer.mjs new file mode 100644 index 0000000..2f78913 --- /dev/null +++ b/scripts/workers/consumer.mjs @@ -0,0 +1,210 @@ +import assert from 'node:assert/strict'; +import { runDemo, runStreamCheck } from 'streamcheck'; + +// This entire suite runs in workerd. Import only the installed public package. +const setup = { apiKey: 'synthetic', model: 'offline/model' }; +const history = [ + { role: 'system', content: ' Keep whitespace.\n' }, + { role: 'user', content: 'Question 🌍' }, + { role: 'assistant', content: 'Earlier answer' }, + { role: 'user', content: 'Follow up' }, +]; +const chunk = (content = '', finish_reason = null, extra = {}) => ({ + id: 'gen-offline', object: 'chat.completion.chunk', created: 1, model: setup.model, + choices: [{ index: 0, delta: { content }, finish_reason }], ...extra, +}); +const frame = value => `data: ${typeof value === 'string' ? value : JSON.stringify(value)}\n\n`; +const response = wire => new Response(wire, { headers: { 'content-type': 'text/event-stream' } }); +const sse = (...events) => response(events.map(frame).join('')); +const normal = () => sse(chunk('Hello ', null), chunk('🌍', 'stop'), '[DONE]'); + +function controlled() { + let controller; + let cancellations = 0; + const body = new ReadableStream({ + start(value) { controller = value; }, + cancel() { cancellations++; }, + }, { highWaterMark: 0 }); + return { + response: response(body), + emit(value) { controller.enqueue(new TextEncoder().encode(frame(value))); }, + fail() { controller.error(new TypeError('Synthetic connection reset')); }, + get cancellations() { return cancellations; }, + }; +} + +export default { + async test() { + const passed = []; + let totalRequests = 0; + const pendingTimers = new Set(); + const startTimer = globalThis.setTimeout; + const stopTimer = globalThis.clearTimeout; + globalThis.setTimeout = (callback, delay, ...args) => { + const timer = startTimer(() => { pendingTimers.delete(timer); callback(...args); }, delay); + pendingTimers.add(timer); + return timer; + }; + globalThis.clearTimeout = timer => { pendingTimers.delete(timer); stopTimer(timer); }; + async function check(name, { + input = { messages: history }, makeResponse = normal, expected, + expectedMessages = input.messages ?? [{ role: 'user', content: input.prompt }], + afterText, requests: expectedRequests = 1, fixture, after, + }) { + let requests = 0; + let received = ''; + let effectiveSignal; + let transportFailure; + const callerSignal = input.signal; + let added = 0; + let removed = 0; + // Observe the runner's caller listener without changing its behavior. + if (callerSignal) { + const add = callerSignal.addEventListener.bind(callerSignal); + const remove = callerSignal.removeEventListener.bind(callerSignal); + callerSignal.addEventListener = (...args) => { if (args[0] === 'abort') added++; return add(...args); }; + callerSignal.removeEventListener = (...args) => { if (args[0] === 'abort') removed++; return remove(...args); }; + } + globalThis.fetch = async (input, init) => { + requests++; + totalRequests++; + try { + assert.equal(requests, 1, 'Retries are forbidden'); + const request = input instanceof Request ? input : new Request(input, init); + assert.equal(request.url, 'https://openrouter.ai/api/v1/chat/completions'); + assert.equal(request.method, 'POST'); + assert.equal(request.headers.get('authorization'), 'Bearer synthetic'); + const body = await request.json(); + assert.deepEqual(body.messages, expectedMessages); + assert.equal(body.model, setup.model); + assert.equal(body.stream, true); + assert.equal(body.max_tokens, 256); + // RequestInit.signal overrides Request.signal in the pinned SDK. + effectiveSignal = init?.signal ?? request.signal; + assert(effectiveSignal instanceof AbortSignal); + return await makeResponse(effectiveSignal); + } catch (error) { + if (error?.code === 'ERR_ASSERTION') transportFailure = error; + throw error; + } + }; + const result = await runStreamCheck({ + ...setup, ...input, + onText(delta) { received += delta; afterText?.(delta); }, + }); + // Transport assertion failures must not hide inside normalized diagnostics. + assert.ifError(transportFailure); + assert.equal(requests, expectedRequests, name); + for (const [key, value] of Object.entries(expected)) assert.deepEqual(result[key], value, `${name}: ${key}`); + assert.equal(result.text, received, `${name}: accumulation before synchronous callback`); + assert.equal(result.partialOutput, result.text.length > 0 && result.outcome !== 'success'); + assert.equal(result.schemaVersion, 1); + assert.equal(result.source, 'live'); + assert(Number.isFinite(result.elapsedMs) && result.elapsedMs >= 0); + if (result.text) assert(Number.isFinite(result.firstTokenMs) && result.firstTokenMs >= 0 && result.firstTokenMs <= result.elapsedMs); + else assert.equal(result.firstTokenMs, null); + if (callerSignal) assert.equal(removed, added, `${name}: caller listener cleanup`); + assert.equal(pendingTimers.size, 0, `${name}: deadline/retry timer cleanup`); + if (fixture) { + assert.equal(fixture.response.body.locked, false, `${name}: source reader released`); + assert.equal(fixture.cancellations, 1, `${name}: upstream cancellation`); + } + after?.(result, effectiveSignal); + passed.push(name); + } + + const success = { outcome: 'success', text: 'Hello 🌍', finishReason: 'stop', httpStatus: 200, warnings: [] }; + await check('prompt compatibility', { input: { prompt: ' Legacy prompt\n' }, expected: success }); + await check('conversation roles/order/content', { expected: success }); + await check('normalized header', { input: { messages: history, apiKey: 'synthetic \r\n\t' }, expected: success }); + for (const [reason, warning] of [['length', 'token_limit'], ['content_filter', 'content_filter']]) { + await check(`${reason} warning success`, { makeResponse: () => sse(chunk('Text', reason), '[DONE]'), expected: { outcome: 'success', text: 'Text', finishReason: reason, warnings: [warning] } }); + } + await check('empty normal success', { makeResponse: () => sse(chunk('', 'stop'), '[DONE]'), expected: { outcome: 'success', text: '', finishReason: 'stop', warnings: [] } }); + for (const status of [401, 503]) { + await check(`HTTP ${status} without retries`, { + makeResponse: () => new Response(JSON.stringify({ error: { code: status, message: 'Synthetic failure' } }), { status, headers: { 'content-type': 'application/json' } }), + expected: { outcome: 'failed', text: '', httpStatus: status, error: { kind: 'http', phase: 'request', message: `HTTP request failed (${status})` } }, + }); + } + for (const text of ['', 'Retained']) { + await check(`HTTP 200 provider error ${text ? 'after text' : 'before text'}`, { + makeResponse: () => sse(chunk(text, text ? 'stop' : null), chunk('', 'error', { error: { code: 502, message: 'Private upstream detail' } })), + expected: { outcome: text ? 'interrupted' : 'failed', text, httpStatus: 200, finishReason: text ? 'stop' : 'error', error: { kind: 'provider', phase: 'stream', code: 502, message: 'Provider error during streaming' } }, + }); + } + for (const [name, wire, text, finishReason, message] of [ + ['missing finish', frame('[DONE]'), '', null, 'Stream ended without an observed normal finish reason'], + ['missing DONE', frame(chunk('Retained', 'stop')), 'Retained', 'stop', 'Stream ended without an observed [DONE] event'], + ['unfinished frame', frame(chunk('Retained', 'stop')) + 'data: {"error":', 'Retained', 'stop', 'Stream ended with an unfinished SSE frame'], + ['malformed stream', frame(chunk('Retained', 'stop')) + frame('not-json'), 'Retained', 'stop', 'The SDK rejected a malformed or unsupported response'], + ]) { + await check(name, { makeResponse: () => response(wire), expected: { outcome: text ? 'interrupted' : 'failed', text, finishReason, error: { kind: 'protocol', phase: 'stream', message } } }); + } + // Reset only after decoded text so a buffered failure cannot pass this case. + const reset = controlled(); + reset.emit(chunk('Retained', 'stop')); + await check('transport interruption after finish', { + makeResponse: () => reset.response, afterText: () => reset.fail(), + expected: { outcome: 'interrupted', text: 'Retained', finishReason: 'stop', error: { kind: 'network', phase: 'stream', message: 'Stream connection interrupted' } }, + after: () => assert.equal(reset.response.body.locked, false), + }); + for (const action of ['throw', 'abort', 'abort-and-throw']) { + const caller = new AbortController(); + const fixture = controlled(); + fixture.emit(chunk('Retained', 'stop')); + await check(`callback ${action}`, { + input: { messages: history, signal: caller.signal }, makeResponse: () => fixture.response, fixture, + afterText() { if (action !== 'throw') caller.abort(); if (action !== 'abort') throw new Error('Private consumer detail'); }, + expected: { outcome: action === 'throw' ? 'interrupted' : 'cancelled', text: 'Retained', finishReason: 'stop', ...(action === 'throw' ? { error: { kind: 'consumer', phase: 'stream', message: 'The synchronous onText callback failed' } } : { reason: 'caller' }) }, + after: (_result, signal) => assert.equal(signal.aborted, true), + }); + } + const stalled = controlled(); + stalled.emit(chunk('Retained', 'stop')); + await check('deadline while draining provisional finish', { + input: { messages: history, timeoutMs: 100 }, makeResponse: () => stalled.response, fixture: stalled, + expected: { outcome: 'interrupted', text: 'Retained', finishReason: 'stop', error: { kind: 'timeout', phase: 'stream', message: 'Overall streaming deadline exceeded' } }, + after: (_result, signal) => assert.equal(signal.aborted, true), + }); + for (const cause of ['caller', 'timeout']) { + const caller = new AbortController(); + await check(`pending request ${cause}`, { + input: { messages: history, signal: caller.signal, timeoutMs: 100 }, + makeResponse: signal => new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => reject(new DOMException('Synthetic abort', 'AbortError')), { once: true }); + if (cause === 'caller') caller.abort(); + }), + expected: { outcome: cause === 'caller' ? 'cancelled' : 'failed', text: '', httpStatus: null, ...(cause === 'caller' ? { reason: 'caller' } : { error: { kind: 'timeout', phase: 'request', message: 'Overall streaming deadline exceeded' } }) }, + after(_result, signal) { assert.equal(signal.aborted, true); caller.abort(); }, + }); + } + const later = new AbortController(); + await check('accepted success survives later abort', { input: { messages: history, signal: later.signal }, expected: success, after: result => { later.abort(); assert.equal(result.outcome, 'success'); } }); + + const invalidInputs = [ + {}, { prompt: 'hello', messages: history }, { prompt: undefined, messages: history }, + { messages: [] }, { messages: null }, { messages: undefined }, { messages: 'hello' }, + { messages: [null] }, { messages: ['hello'] }, { messages: Array(1) }, + { messages: [{ role: 'tool', content: 'hello' }] }, { messages: [{ role: 'developer', content: 'hello' }] }, + { messages: [{ role: 'user', content: ' \n\t' }] }, { messages: [{ role: 'assistant', content: 42 }] }, + { messages: [{ role: 'user', content: [{ type: 'image_url', image_url: 'synthetic' }] }] }, + { messages: [{ role: 'assistant', content: 'hello', tool_calls: [] }] }, + ]; + for (const [index, input] of invalidInputs.entries()) { + await check(`invalid conversation ${index + 1}`, { input, requests: 0, expected: { outcome: 'failed', text: '', httpStatus: null }, after: result => { assert.equal(result.error.kind, 'input'); assert.equal(result.error.phase, 'setup'); } }); + } + for (const [index, apiKey] of [undefined, '', ' ', 'synthetic\nkey', 'synthetic\rkey', 'synthetic\0key', 'synthetic\u0001key', 'synthetic\u000bkey', 'synthetic\u007fkey', 'synthetic\u0100key'].entries()) { + await check(`invalid credential ${index + 1}`, { input: { messages: history, apiKey }, requests: 0, expected: { outcome: 'failed', text: '', httpStatus: null }, after: result => { assert.equal(result.error.kind, 'input'); assert.equal(result.error.phase, 'setup'); } }); + } + const preAborted = new AbortController(); + preAborted.abort(); + await check('pre-aborted invalid input', { input: { apiKey: '', messages: [], signal: preAborted.signal }, requests: 0, expected: { outcome: 'cancelled', reason: 'caller', text: '', httpStatus: null } }); + const demo = await runDemo({ scenario: 'interrupted' }); + assert.equal(demo.outcome, 'interrupted'); + assert.equal(demo.text, 'Webhooks send HTTP notifications when an event'); + assert.equal(pendingTimers.size, 0, 'demo timer cleanup'); + passed.push('public demo compatibility'); + console.log('STREAMCHECK_REPORT=' + JSON.stringify({ passed, requests: totalRequests })); + }, +}; diff --git a/src/index.ts b/src/index.ts index e89f61d..4df23b7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ export { runStreamCheck } from './runner.js'; export { runDemo } from './demo.js'; export type { - CommonOptions, LiveOptions, DemoOptions, DemoScenario, Diagnostic, ErrorKind, + CommonOptions, LiveOptions, TextMessage, DemoOptions, DemoScenario, Diagnostic, ErrorKind, RunResult, SuccessResult, FailureResult, CancelledResult, ResultBase, RunSource, WarningCode, } from './types.js'; diff --git a/src/runner.ts b/src/runner.ts index 7d4ea66..83fde62 100644 --- a/src/runner.ts +++ b/src/runner.ts @@ -26,7 +26,21 @@ function validate(options: LiveOptions): string | null { } 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 (('prompt' in options) === ('messages' in options)) return 'Provide exactly one of prompt or messages'; + if ('prompt' in options) { + if (typeof options.prompt !== 'string' || !options.prompt.trim()) return 'A nonempty prompt is required'; + } else { + if (!Array.isArray(options.messages) || options.messages.length === 0) return 'Messages must be a nonempty array'; + for (const message of options.messages) { + if (!message || typeof message !== 'object' || Array.isArray(message) + || (Object.getPrototypeOf(message) !== Object.prototype && Object.getPrototypeOf(message) !== null) + || Object.keys(message).some(key => key !== 'role' && key !== 'content') + || !['system', 'user', 'assistant'].includes(message.role) + || typeof message.content !== 'string' || !message.content.trim()) { + return 'Each message must be a plain text object with a system, user, or assistant role and nonblank content'; + } + } + } 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'; if (options.maxTokens !== undefined && (!Number.isSafeInteger(options.maxTokens) || options.maxTokens <= 0)) return 'Maximum tokens must be a positive safe integer'; if (options.signal !== undefined && !(options.signal instanceof AbortSignal)) return 'Signal must be an AbortSignal'; @@ -93,7 +107,9 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher, const stream = await sdk.chat.send({ chatRequest: { model: options.model, - messages: [{ role: 'user', content: options.prompt }], + messages: options.messages + ? options.messages.map(({ role, content }) => ({ role, content })) + : [{ role: 'user', content: options.prompt! }], stream: true, maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, }, diff --git a/src/types.ts b/src/types.ts index f1cef3f..1911c46 100644 --- a/src/types.ts +++ b/src/types.ts @@ -11,13 +11,22 @@ export interface CommonOptions { onText?: (delta: string) => void; } -export interface LiveOptions extends CommonOptions { +/** One plain text conversation entry. Tool calls and multimodal content are unsupported. */ +export interface TextMessage { + role: 'system' | 'user' | 'assistant'; + content: string; +} + +export type LiveOptions = CommonOptions & { apiKey: string; model: string; - prompt: string; /** Positive safe integer; default 256. Provider-specific limits still apply. */ maxTokens?: number; -} +} & ( + // Enable exactOptionalPropertyTypes to also reject an explicit undefined opposite input. + | { prompt: string; messages?: never } + | { prompt?: never; messages: readonly [TextMessage, ...TextMessage[]] } +); export interface DemoOptions extends CommonOptions { scenario?: DemoScenario; diff --git a/tests/conversation.test.ts b/tests/conversation.test.ts new file mode 100644 index 0000000..597c300 --- /dev/null +++ b/tests/conversation.test.ts @@ -0,0 +1,73 @@ +import { afterEach, expect, it, vi } from 'vitest'; +import { runStreamCheck, type LiveOptions, type TextMessage } from '../src/index.js'; +import { chunk, sse } from './helpers.js'; + +afterEach(() => vi.unstubAllGlobals()); +const setup = { apiKey: 'synthetic', model: 'offline/model' }; +const messages = [ + { role: 'system', content: ' Keep whitespace.\n' }, + { role: 'user', content: 'First question 🌍' }, + { role: 'assistant', content: 'Earlier answer' }, + { role: 'user', content: 'Follow up' }, +] as const satisfies readonly TextMessage[]; + +it('sends conversation roles, order, and exact content through the public API and real SDK', async () => { + let body: unknown; + const fetcher = vi.fn(async (input: RequestInfo | URL) => { + body = await (input as Request).json(); + return sse(chunk('Answer', 'stop'), '[DONE]'); + }); + vi.stubGlobal('fetch', fetcher); + const result = await runStreamCheck({ ...setup, messages }); + expect(result).toMatchObject({ outcome: 'success', text: 'Answer', finishReason: 'stop' }); + expect(body).toMatchObject({ messages, model: setup.model, stream: true, max_tokens: 256 }); + expect(fetcher).toHaveBeenCalledOnce(); +}); + +it.each([ + {}, { prompt: 'hello', messages }, { prompt: undefined, messages }, + { messages: undefined }, { messages: null }, { messages: [] }, { messages: 'hello' }, + { messages: [null] }, { messages: ['hello'] }, { messages: [new Date()] }, + { messages: [{ role: 'tool', content: 'hello' }] }, + { messages: [{ role: 'developer', content: 'hello' }] }, + { messages: [{ role: 'user', content: '' }] }, + { messages: [{ role: 'assistant', content: ' \n\t' }] }, + { messages: [{ role: 'user', content: 42 }] }, + { messages: [{ role: 'user', content: [{ type: 'text', text: 'hello' }] }] }, + { messages: [{ role: 'assistant', content: 'hello', tool_calls: [] }] }, + { messages: [{ role: 'user', content: 'hello', images: [] }] }, + { messages: Array(1) }, +])('rejects malformed or ambiguous conversation input before fetch: %j', async input => { + const fetcher = vi.fn(); + vi.stubGlobal('fetch', fetcher); + expect(await runStreamCheck({ ...setup, ...input } as unknown as LiveOptions)).toMatchObject({ + outcome: 'failed', text: '', partialOutput: false, httpStatus: null, + error: { kind: 'input', phase: 'setup' }, + }); + expect(fetcher).not.toHaveBeenCalled(); +}); + +it('retains pre-aborted cancellation precedence over invalid conversation and credential input', async () => { + const controller = new AbortController(); + controller.abort(); + const fetcher = vi.fn(); + vi.stubGlobal('fetch', fetcher); + expect(await runStreamCheck({ apiKey: '', model: '', messages: [], signal: controller.signal } as unknown as LiveOptions)) + .toMatchObject({ outcome: 'cancelled', reason: 'caller', text: '', httpStatus: null }); + expect(fetcher).not.toHaveBeenCalled(); +}); + +// These are compiled by npm run typecheck, never executed as provider calls. +const promptOptions: LiveOptions = { ...setup, prompt: 'hello' }; +const conversationOptions: LiveOptions = { ...setup, messages }; +// @ts-expect-error Exactly one input is required. +const neither: LiveOptions = setup; +// @ts-expect-error Both input forms are forbidden. +const both: LiveOptions = { ...setup, prompt: 'hello', messages }; +// @ts-expect-error A conversation must be nonempty. +const empty: LiveOptions = { ...setup, messages: [] }; +// @ts-expect-error Only supported text roles are public. +const tool: TextMessage = { role: 'tool', content: 'hello' }; +// @ts-expect-error Multimodal content is unsupported. +const image: TextMessage = { role: 'user', content: [{ type: 'image_url' }] }; +void [promptOptions, conversationOptions, neither, both, empty, tool, image];