reliable-requests 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,13 +1,33 @@
1
- # Changelog
2
-
3
- ## 0.2.0 — Unreleased
4
-
5
- - Add the public `reliable-requests` entry for HTTP requests, local model streams, metrics, and public error classes. Internal module paths are not package exports.
6
- - Include TypeScript declarations with inferred `consume` results and discriminated stream events. Runtime code remains JavaScript with no runtime dependencies.
7
- - Define the ESM package contents and verify an installed npm archive in a clean consumer project, including NodeNext and Bundler type resolution.
8
- - Use MIT for the current source and forthcoming package. The existing v0.1.0 tag and release retain GPL-3.0-only.
9
- - Preserve the existing request, retry, reset, and cancellation behavior.
10
-
11
- ## 0.1.0
12
-
13
- Initial GitHub release: HTTP request deadlines and retries, Ollama/OpenAI-compatible streams, reset events, metrics, and the browser demo. Released under GPL-3.0-only; not published to npm.
1
+ # Changelog
2
+
3
+ ## 0.3.0 — prepared 2026-12-02
4
+
5
+ - Add optional first-text and text-idle deadlines for model streams with a distinct public `StreamTimeoutError`, leaving existing timeout and retry behavior unchanged when omitted.
6
+ - Include TypeScript declarations and package consumer checks for the new timeout options and error.
7
+ - Add optional live browser verification with Stop, late-event checks and a subsequent completed generation.
8
+ - Add bounded cross-protocol model stress diagnostics, including a reduced profile for slower models, overlapping clients, repeated cancellations and client memory observations.
9
+ - Record manual Windows recovery, phase-timeout and CORS preflight observations on Ollama, LM Studio and llama.cpp. Default stress runs passed on Ollama and llama.cpp; LM Studio passed the reduced workload after a default-profile timeout.
10
+ - Add release-only npm trusted publishing validation and archive verification, with no publishing on pull requests.
11
+ - Run core CI on test and documentation branches.
12
+
13
+ ## 0.2.1 — prepared 2026-12-02
14
+
15
+ - Unify the local recovery test proxy and CLI across Ollama and OpenAI-compatible servers; preserve the original Ollama command.
16
+ - Document and test completion markers, retry/reset ordering, cancellation, callback failures and fresh attempt metadata.
17
+ - Verify one-choice requests and real TCP fault recovery against fake upstream servers. Live LM Studio and llama.cpp recovery is still pending.
18
+
19
+ - Keep fault-proxy requests text-only by forwarding only role and content fields.
20
+ - Include the model compatibility and stream contract guides in the npm archive and verify packaged documentation links.
21
+ - Verify archive, installed package and lockfile versions against the source manifest instead of hard-coding the previous release number.
22
+
23
+ ## 0.2.0 — 2026-11-30
24
+
25
+ - Add the public `reliable-requests` entry for HTTP requests, local model streams, metrics, and public error classes. Internal module paths are not package exports.
26
+ - Include TypeScript declarations with inferred `consume` results and discriminated stream events. Runtime code remains JavaScript with no runtime dependencies.
27
+ - Define the ESM package contents and verify an installed npm archive in a clean consumer project, including NodeNext and Bundler type resolution.
28
+ - Use MIT for the current source and published package. The existing v0.1.0 tag and release retain GPL-3.0-only.
29
+ - Preserve the existing request, retry, reset, and cancellation behavior.
30
+
31
+ ## 0.1.0
32
+
33
+ Initial GitHub release: HTTP request deadlines and retries, Ollama/OpenAI-compatible streams, reset events, metrics, and the browser demo. Released under GPL-3.0-only; not published to npm.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Stairrax
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Stairrax
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,99 +1,207 @@
1
- # reliable-requests
2
-
3
- [![Tests](https://github.com/Stairrax/reliable-requests/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/Stairrax/reliable-requests/actions/workflows/test.yml)
4
- [![Browser demo](https://github.com/Stairrax/reliable-requests/actions/workflows/browser.yml/badge.svg?branch=main)](https://github.com/Stairrax/reliable-requests/actions/workflows/browser.yml)
5
- [![MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
6
-
7
- **Small JavaScript helpers for reliable HTTP requests and interrupted local AI streams.** Runs in modern browsers and Node.js 18+, with no runtime dependencies.
8
-
9
- When a text stream breaks, `streamLocalChat` can start a fresh generation and emit **`reset`**, so an app does not mix the unfinished old answer with the new one.
10
-
11
- - Ollama and OpenAI-compatible endpoints (LM Studio, llama.cpp).
12
- - One total deadline, cancellation, and a shared jittered retry policy that respects Retry-After.
13
- - Incremental SSE event parsing with multiline data and bounded line/event sizes.
14
- - Interactive demo, diagnostic metrics, and real-HTTP failure tests.
15
-
16
- > A retry **restarts** the generation; it cannot continue the same answer or guarantee identical text. Model calls may use additional compute or cost money. Remote automatic retries require explicit opt-in. The first version handles text only.
17
-
18
- ## Quick start
19
-
20
- Clone the repository and switch to the project directory:
21
-
22
- ```bash
23
- git clone https://github.com/Stairrax/reliable-requests.git
24
- cd reliable-requests
25
- npm ci
26
- npm run check
27
- npm run demo
28
- ```
29
-
30
- Open **http://127.0.0.1:4173**. Select **Simulate interruption** to see a partial response discarded and replaced. No model or GPU is required for the demo.
31
-
32
- To test a real model, start Ollama and install a model (for example `ollama pull qwen2.5:0.5b`):
33
-
34
- ```bash
35
- MODEL_NAME=qwen2.5:0.5b npm run test:model
36
- MODEL_NAME=qwen2.5:0.5b npm run test:ollama:recovery
37
- ```
38
-
39
- The second command deliberately breaks one **local** Ollama connection, then checks for a retry and reset. It does not stop Ollama. These examples use **Git Bash** on Windows, macOS, or Linux; see the guide for PowerShell.
40
-
41
- ## Use in JavaScript
42
-
43
- Version **0.2.0 is being prepared for npm**. Until publication, create an installable archive from this branch:
44
-
45
- ```bash
46
- npm ci
47
- npm run check
48
- npm pack
49
- ```
50
-
51
- In a separate application, install that archive:
52
-
53
- ```bash
54
- npm install /path/to/reliable-requests-0.2.0.tgz
55
- ```
56
-
57
- The package is ESM-only. Use an ES module (`.mjs` or a project with `"type": "module"`):
58
-
59
- ```js
60
- import { streamLocalChat } from 'reliable-requests';
61
-
62
- let answer = '';
63
- await streamLocalChat({
64
- endpoint: 'http://127.0.0.1:11434',
65
- protocol: 'ollama',
66
- model: 'qwen2.5:0.5b',
67
- messages: [{ role: 'user', content: 'Hello!' }],
68
- onEvent(event) {
69
- if (event.type === 'reset') answer = '';
70
- if (event.type === 'delta') answer += event.text;
71
- if (event.type === 'done') console.log(answer);
72
- },
73
- });
74
- ```
75
-
76
- Also included: `reliableRequest` for regular fetch calls and `createStreamMetrics` for local diagnostics. All public functions and errors are exported from `reliable-requests`; imports into `src/` are not supported by the package.
77
-
78
- For LM Studio, use `protocol: 'openai'`, `endpoint: 'http://127.0.0.1:1234/v1'`, and your installed model's identifier. Browser applications also need the local server to allow their origin through CORS. Use a bundler or an import map for browser package imports.
79
-
80
- To cancel, pass an `AbortController`'s `signal` and call `controller.abort()`. The promise rejects with `AbortError`. Keep the `reset` handler: a retry starts a new answer.
81
-
82
- TypeScript declarations ship with the package; no TypeScript runtime or compilation of this library is needed. Consumer projects need Fetch API types, usually `"lib": ["ES2022", "DOM", "DOM.Iterable"]` in their TypeScript configuration.
83
-
84
- ## Documentation
85
-
86
- - [Changes in 0.2.0](CHANGELOG.md) · [Release checklist](docs/RELEASING.md)
87
- - [Detailed usage, API, and PowerShell instructions](docs/USAGE.md)
88
- - [Live model checks: Ollama and LM Studio, 2026-11-29](docs/LIVE_TESTS_2026-11-29.md)
89
- - [Roadmap](ROADMAP.md) · [Contributing](CONTRIBUTING.md) · [Security](SECURITY.md)
90
-
91
- **Status:** early open-source implementation. Automated tests cover Node.js 18/22 and simulated demo flows in Chromium, Firefox, and WebKit. A Windows user verified live Qwen 2.5 0.5B responses, Stop, and recovery from a deliberately cut TCP connection, plus a normal streamed llama.cpp response with Qwen 2.5 0.5B. On 2026-11-29, manual Windows checks also confirmed LM Studio text streaming with `qwen2.5-7b-instruct-uncensored` in Node.js, plus browser Stop and a subsequent completed request; see the [run record and its limits](docs/LIVE_TESTS_2026-11-29.md). Live interruption recovery with LM Studio and llama.cpp, live cross-browser inference, other models, and very long responses still need testing.
92
-
93
- ## Acknowledgements
94
-
95
- Thanks to [TaKeSh13](https://github.com/TaKeSh13) for helping discuss and develop solutions for local stream completion and callback reliability in [PR #4](https://github.com/Stairrax/reliable-requests/pull/4).
96
-
97
- ## License
98
-
99
- [MIT](LICENSE) © 2026 Stairrax. You may use, modify, and distribute this code, including in commercial and closed-source applications, provided you preserve the copyright and permission notices required by the license. The software is provided without warranty.
1
+ <div align="center">
2
+
3
+ <h1>reliable-requests</h1>
4
+
5
+ <strong>Recover from interrupted AI streams without mixing two different answers.</strong>
6
+
7
+ A small JavaScript toolkit for resilient HTTP requests and local AI streaming.<br>
8
+ No runtime dependencies. No telemetry. No framework required.
9
+
10
+ [![npm](https://img.shields.io/npm/v/reliable-requests)](https://www.npmjs.com/package/reliable-requests)
11
+ [![License](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
12
+ [![Dependencies](https://img.shields.io/badge/runtime%20dependencies-0-brightgreen)](package.json)
13
+ [![Node.js](https://img.shields.io/badge/Node.js-18%2B-339933)](package.json)
14
+ [![TypeScript](https://img.shields.io/badge/TypeScript-types%20included-3178C6)](index.d.ts)
15
+
16
+ [![Tests](https://github.com/Stairrax/reliable-requests/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/Stairrax/reliable-requests/actions/workflows/test.yml)
17
+ [![Browser demo](https://github.com/Stairrax/reliable-requests/actions/workflows/browser.yml/badge.svg?branch=main)](https://github.com/Stairrax/reliable-requests/actions/workflows/browser.yml)
18
+
19
+ [Quick start](#quick-start) &bull; [Demo](#try-the-demo) &bull; [Documentation](#documentation) &bull; [Contributing](#contributing)
20
+
21
+ </div>
22
+
23
+ ---
24
+
25
+ ## Why reliable-requests?
26
+
27
+ Local AI servers can stop responding halfway through an answer. Retrying without clearing the partial output can leave two unrelated generations mixed together.
28
+
29
+ reliable-requests makes recovery explicit: when a retry starts a new generation after partial output, the application receives a `reset` event.
30
+
31
+ - **Recover cleanly.** Discard the old partial answer before displaying the new one.
32
+ - **Stop waiting forever.** Keep one deadline across attempts, response reading and retry delays when using the streaming API.
33
+ - **Stay in control.** Cancel generation at any time. Remote model retries require explicit opt-in.
34
+ - **Keep it lightweight.** Native Fetch API, ESM, zero runtime dependencies.
35
+
36
+ ## Features
37
+
38
+ - 🔄 Automatic restart of interrupted text streams with an explicit reset event
39
+ - 🔌 Ollama NDJSON and OpenAI-compatible SSE support
40
+ - ⏱️ Shared total deadline, optional first-text and idle deadlines, cancellation and jittered retries with Retry-After support
41
+ - 🧩 Incremental parsing of multiline SSE events and fragmented UTF-8
42
+ - 🛡️ Bounded protocol line and event sizes
43
+ - 📊 Optional local stream metrics without telemetry
44
+ - 📦 TypeScript declarations included
45
+ - 🧪 Automated tests, real HTTP fault injection and an interactive browser demo
46
+
47
+ ## Requirements
48
+
49
+ - Node.js 18+ or a modern browser with Fetch API support
50
+ - An ES module environment; browser npm imports need a bundler or import map
51
+ - A running model server and an installed model for live AI requests only
52
+
53
+ The simulated demo and core automated tests do not require a model or GPU.
54
+
55
+ ## Quick start
56
+
57
+ ### 1. Install
58
+
59
+ ```bash
60
+ npm install reliable-requests
61
+ ```
62
+
63
+ ### 2. Stream a local model
64
+
65
+ Start Ollama with an installed model, then run this example in an ES module:
66
+
67
+ ```js
68
+ import { streamLocalChat } from 'reliable-requests';
69
+
70
+ let answer = '';
71
+
72
+ await streamLocalChat({
73
+ endpoint: 'http://127.0.0.1:11434',
74
+ protocol: 'ollama',
75
+ model: 'qwen2.5:0.5b',
76
+ messages: [{ role: 'user', content: 'Hello!' }],
77
+ onEvent(event) {
78
+ if (event.type === 'reset') answer = '';
79
+ if (event.type === 'delta') answer += event.text;
80
+ if (event.type === 'done') console.log(answer);
81
+ },
82
+ });
83
+ ```
84
+
85
+ Replace the model name with one you have installed. For LM Studio or llama.cpp, use `protocol: 'openai'` and your server's endpoint.
86
+
87
+ For ordinary HTTP requests, the package also exports `reliableRequest`:
88
+
89
+ ```js
90
+ import { reliableRequest } from 'reliable-requests';
91
+
92
+ const data = await reliableRequest('https://example.com/api/data', {
93
+ timeoutMs: 8_000,
94
+ retries: 2,
95
+ consume: response => response.json(),
96
+ });
97
+ ```
98
+
99
+ Without a `consume` callback, the general HTTP wrapper's deadline ends when response headers arrive. See the [usage guide](docs/USAGE.md) for cancellation, TypeScript configuration and metrics.
100
+
101
+ ## Try the demo
102
+
103
+ ```bash
104
+ git clone https://github.com/Stairrax/reliable-requests.git
105
+ cd reliable-requests
106
+ npm run demo
107
+ ```
108
+
109
+ Open [localhost:4173](http://127.0.0.1:4173) and select **Simulate interruption**. Watch an unfinished answer disappear before a fresh generation is displayed.
110
+
111
+ Switch to **Live local model** to connect to your own model server. The server must allow the demo's browser origin through CORS.
112
+
113
+ ## How it works
114
+
115
+ ```mermaid
116
+ flowchart LR
117
+ A[Start generation] --> B[Stream text]
118
+ B --> C{Completed?}
119
+ C -->|Yes| D[Done]
120
+ C -->|Recoverable failure| E{Retry allowed?}
121
+ E -->|Yes| F[Reset if partial text exists]
122
+ F --> A
123
+ E -->|No| G[Report error]
124
+ C -->|Terminal failure| G
125
+ ```
126
+
127
+ A retry starts a **new generation**, not a continuation of the old one. Results may differ, and another request may consume more compute or incur additional charges. Automatic retries of remote model requests require explicit permission.
128
+
129
+ OpenAI-compatible streams require a complete `[DONE]` event; Ollama streams require `done: true`. The library handles text-only generation and does not execute tool calls.
130
+
131
+ ## Compatibility
132
+
133
+ | Server | Protocol | Live streaming | Live interruption recovery |
134
+ | --- | --- | --- | --- |
135
+ | Ollama | NDJSON | Verified | Verified |
136
+ | LM Studio | SSE | Verified | Verified |
137
+ | llama.cpp | SSE | Verified | Verified |
138
+
139
+ Automated tests cover Node.js 18 and 22, both protocols and simulated browser flows in Chromium, Firefox and WebKit. On Windows, live phase-timeout checks passed on all three servers, live llama.cpp browser checks passed in Edge, Chrome, Playwright Firefox and WebKit, and bounded stress checks passed on Ollama and llama.cpp and under a reduced profile on LM Studio (the default profile timed out). These are limited observations with Qwen models, not a guarantee of compatibility with every server, browser or model.
140
+
141
+ See the [November 29 live test record](https://github.com/Stairrax/reliable-requests/blob/main/docs/LIVE_TESTS_2026-11-29.md), [December 2 recovery, browser, timeout and stress results](https://github.com/Stairrax/reliable-requests/blob/main/docs/LIVE_TESTS_2026-12-02.md) and [roadmap](https://github.com/Stairrax/reliable-requests/blob/main/ROADMAP.md) for the exact scope and remaining work.
142
+
143
+ ## Testing
144
+
145
+ ```bash
146
+ npm ci
147
+ npm run check
148
+ ```
149
+
150
+ This runs the automated test suite and verifies the actual npm package, including TypeScript consumer checks.
151
+
152
+ For an installed Ollama model (Git Bash, macOS or Linux):
153
+
154
+ ```bash
155
+ MODEL_NAME=qwen2.5:0.5b npm run test:model
156
+ MODEL_NAME=qwen2.5:0.5b npm run test:ollama:recovery
157
+ ```
158
+
159
+ The recovery test deliberately cuts one local connection without stopping Ollama. For LM Studio and llama.cpp, use `npm run test:model:recovery` with `MODEL_PROTOCOL=openai`, the server endpoint and exact model ID. Use only a local, non-billable server. See the [model compatibility guide](docs/MODEL_COMPATIBILITY.md) for Bash and PowerShell commands.
160
+
161
+ ## Project layout
162
+
163
+ ```text
164
+ reliable-requests/
165
+ ├── index.js Public package entry
166
+ ├── index.d.ts TypeScript declarations
167
+ ├── src/
168
+ │ ├── index.js General HTTP wrapper
169
+ │ ├── local-chat.js Model streaming and recovery
170
+ │ ├── sse.js Incremental stream parsers
171
+ │ ├── stream-events.js Event validation
172
+ │ ├── retry.js Shared retry policy
173
+ │ ├── endpoint.js Endpoint validation
174
+ │ └── metrics.js Local stream metrics
175
+ ├── examples/ Browser demo and live model checks
176
+ ├── test/ Unit and HTTP integration tests
177
+ ├── scripts/ Browser and package checks
178
+ └── docs/ Detailed documentation
179
+ ```
180
+
181
+ ## Documentation
182
+
183
+ | Guide | Description |
184
+ | --- | --- |
185
+ | [Usage](docs/USAGE.md) | API, configuration, errors and examples |
186
+ | [Stream contract](docs/STREAM_CONTRACT.md) | Completion, retries and event ordering |
187
+ | [Model compatibility](docs/MODEL_COMPATIBILITY.md) | Live recovery checks for both protocols |
188
+ | [Roadmap](https://github.com/Stairrax/reliable-requests/blob/main/ROADMAP.md) | Current progress and planned improvements |
189
+ | [Changelog](CHANGELOG.md) | Release history |
190
+ | [Release checklist](https://github.com/Stairrax/reliable-requests/blob/main/docs/RELEASING.md) | Package release process |
191
+ | [Live test record](https://github.com/Stairrax/reliable-requests/blob/main/docs/LIVE_TESTS_2026-11-29.md) | Recorded model compatibility checks |
192
+
193
+ ## Contributing
194
+
195
+ Issues and pull requests are welcome. Bug reports, reproducible stream failures, tests and documentation improvements are especially useful.
196
+
197
+ Keep the runtime dependency-free, preserve explicit retry semantics, and read [CONTRIBUTING.md](https://github.com/Stairrax/reliable-requests/blob/main/CONTRIBUTING.md) before opening a PR. For vulnerability reports, see [SECURITY.md](https://github.com/Stairrax/reliable-requests/blob/main/SECURITY.md).
198
+
199
+ ## Acknowledgements
200
+
201
+ Thanks to [TaKeSh13](https://github.com/GiTakeshi) for helping discuss and develop solutions for local stream completion and callback reliability in [PR #4](https://github.com/Stairrax/reliable-requests/pull/4).
202
+
203
+ ## License
204
+
205
+ [MIT](LICENSE) &copy; 2026 Stairrax.
206
+
207
+ Free to use, modify and distribute, including in commercial and closed-source applications, subject to the MIT license. Provided without warranty.
@@ -0,0 +1,90 @@
1
+ # Model compatibility and recovery checks
2
+
3
+ Compatibility depends on the server's streaming protocol, not the model family. The library sends text chat messages and reads text deltas from Ollama NDJSON or OpenAI-compatible Chat Completions SSE. A different model name does not require a separate adapter when the server keeps that contract.
4
+
5
+ ## Evidence so far
6
+
7
+ | Server | Protocol | Recorded live model | Normal response | Forced-disconnect recovery |
8
+ | --- | --- | --- | --- | --- |
9
+ | Ollama | `ollama` | `qwen2.5:0.5b` | Passed on Windows | Passed on Windows |
10
+ | LM Studio | `openai` | `qwen2.5-7b-instruct-uncensored` | Passed in Node and browser on Windows | Passed on Windows (2026-12-02) |
11
+ | llama.cpp | `openai` | Qwen 2.5 0.5B | Passed on Windows, build 12212 | Passed on Windows (2026-12-02) |
12
+
13
+ These are limited observations, not certification of every server version or model. See [the recorded live checks](https://github.com/Stairrax/reliable-requests/blob/main/docs/LIVE_TESTS_2026-11-29.md), [the December 2 recovery results](https://github.com/Stairrax/reliable-requests/blob/main/docs/LIVE_TESTS_2026-12-02.md) and [the roadmap](https://github.com/Stairrax/reliable-requests/blob/main/ROADMAP.md). Automated fake-server checks verify both protocols and the recovery command without loading a model.
14
+
15
+ ## Additional Windows observations
16
+
17
+ | Server | First-text and idle deadlines | Bounded stress workload |
18
+ | --- | --- | --- |
19
+ | Ollama | Passed | Default profile passed |
20
+ | llama.cpp | Passed | Default profile passed |
21
+ | LM Studio | Passed | Reduced profile passed; default profile timed out |
22
+
23
+ Live llama.cpp cross-origin streaming, client Stop and a new request passed in Edge, Chrome, Playwright Firefox and WebKit. Playwright WebKit on Windows does not verify Safari on Apple platforms. The recorded workload does not establish server-side cancellation, leak freedom or production performance.
24
+
25
+ ## Browser CORS diagnostics
26
+
27
+ A browser origin includes scheme, host and port. The demo at `http://127.0.0.1:4173` and a model endpoint on another port are different origins. A JSON POST generally requires a successful CORS preflight. For an OpenAI-compatible local server, inspect it without generating text:
28
+
29
+ ```bash
30
+ curl -i --max-time 10 -X OPTIONS http://127.0.0.1:1234/v1/chat/completions \
31
+ -H "Origin: http://127.0.0.1:4173" \
32
+ -H "Access-Control-Request-Method: POST" \
33
+ -H "Access-Control-Request-Headers: content-type"
34
+ ```
35
+
36
+ For llama.cpp substitute its port; for Ollama use `http://127.0.0.1:11434/api/chat`. A successful preflight should permit the demo origin, POST and the requested headers. Actual responses must also permit the origin. Curl itself does not enforce browser CORS, and a successful preflight alone does not establish live browser compatibility. Check the browser network panel and the server's own CORS settings if the request fails. Keep servers bound to loopback and prefer narrowly scoped allowed origins rather than disabling browser security or exposing the server to the network.
37
+
38
+ ### Recorded preflight results (2026-12-02)
39
+
40
+ | Server/configuration | HTTP status | Allow-Origin | Allow-Headers | POST allowed |
41
+ | --- | --- | --- | --- | --- |
42
+ | Ollama | 204 | http://127.0.0.1:4173 | Includes Content-Type | Yes |
43
+ | LM Studio before enabling CORS | 400 | Absent | Absent | Not confirmed |
44
+ | LM Studio after enabling CORS | 200 | * | * | Yes |
45
+ | llama.cpp | 200 | http://127.0.0.1:4173 | * | Yes |
46
+
47
+ llama.cpp also returned Access-Control-Allow-Credentials: true. Wildcard header permissions are sufficient for the tested non-credentialed JSON request; credentialed requests have additional CORS requirements. The observed origin values do not prove that other origins are denied. These are configuration-specific observations, not universal server defaults. The separate live browser checks are recorded in the [December 2 results](https://github.com/Stairrax/reliable-requests/blob/main/docs/LIVE_TESTS_2026-12-02.md).
48
+
49
+ ## Run the same recovery check against your server
50
+
51
+ Run these commands from a repository checkout after `npm ci`. Test helpers are not shipped in the npm package. Start your local server and load a text chat model first. Use the exact model ID reported by that server.
52
+
53
+ Git Bash, Linux, or macOS:
54
+
55
+ ```bash
56
+ MODEL_PROTOCOL=ollama MODEL_ENDPOINT=http://127.0.0.1:11434 MODEL_NAME=qwen2.5:0.5b npm run test:model:recovery
57
+ ```
58
+
59
+ LM Studio, using the model from the recorded checks:
60
+
61
+ ```bash
62
+ MODEL_PROTOCOL=openai MODEL_ENDPOINT=http://127.0.0.1:1234/v1 MODEL_NAME=qwen2.5-7b-instruct-uncensored MODEL_TIMEOUT_MS=300000 npm run test:model:recovery
63
+ ```
64
+
65
+ For llama.cpp or another compatible server, set `MODEL_ENDPOINT` to its actual address and `MODEL_NAME` to its served model ID. The OpenAI endpoint may include `/v1`; a prefix such as `/inference/v1` is preserved.
66
+
67
+ PowerShell:
68
+
69
+ ```powershell
70
+ $env:MODEL_PROTOCOL = 'openai'
71
+ $env:MODEL_ENDPOINT = 'http://127.0.0.1:1234/v1'
72
+ $env:MODEL_NAME = 'qwen2.5-7b-instruct-uncensored'
73
+ $env:MODEL_TIMEOUT_MS = '300000'
74
+ npm run test:model:recovery
75
+ ```
76
+
77
+ The command starts a temporary proxy on a random loopback port. It forwards the first text event, interrupts that connection, and lets the second response complete. It checks for exactly two attempts, one cut, one retry, and one reset. The server stays running. The old `test:ollama:recovery` command remains available.
78
+
79
+ The proxy only connects to HTTP on `127.0.0.1`, requires its generated token, rejects browser-origin requests, and forwards at most two model requests. It does not forward upstream credentials or follow redirects. This is a local development helper, not a production proxy. `MODEL_TIMEOUT_MS` covers generation and retry together; the helper does not speed up inference.
80
+
81
+ ## What to record
82
+
83
+ Save the commit SHA (`git rev-parse HEAD`), Node version (`node --version`), OS, server version, model ID, command, and PASS/FAIL output. Note whether the run was in Node or a browser. Do not include private prompts or credentials. A failed test needs its error and event sequence; it must not be recorded as verified support.
84
+
85
+ ## Limits
86
+
87
+ - Text chat only: tool calls, image/audio inputs, and separate reasoning output are not supported by this check.
88
+ - The model may produce a different answer after retry. The earlier partial answer must be discarded on `reset`.
89
+ - A successful Node check does not verify browser CORS or browser access to local servers. Those require a separate live browser check.
90
+ - Slower or larger models need a suitable timeout and enough local memory. No model weights are installed or changed by these commands.
@@ -0,0 +1,72 @@
1
+ # Stream completion and recovery contract
2
+
3
+ This document records the current behavior of `streamLocalChat`. It does not introduce a new completion mode.
4
+
5
+ ## Completion
6
+
7
+ | Input | Result |
8
+ | --- | --- |
9
+ | OpenAI SSE: fully framed `data: [DONE]` event | Success |
10
+ | OpenAI SSE: `finish_reason` followed by EOF, without a complete DONE event | Interrupted stream |
11
+ | OpenAI SSE: partial DONE event or partial data event at EOF | Interrupted stream; incomplete event is discarded |
12
+ | Ollama NDJSON: valid event with `done: true`, including a final line without a newline | Success |
13
+ | Ollama NDJSON: `done_reason` without `done: true`, followed by EOF | Interrupted stream |
14
+ | Both: malformed event, unsupported tool output or protocol limit | Failure, no automatic retry |
15
+
16
+ A completion reason is metadata, not a substitute for the completion marker. A successful protocol completion can still represent truncated text (for example, reason `length`). No reason is fabricated when the server omits it. Each attempt starts with a fresh parser and completion state.
17
+
18
+ ## Retry decisions
19
+
20
+ | Failure | Eligible for another attempt? |
21
+ | --- | --- |
22
+ | HTTP 429, 500, 502, 503, 504 | Yes |
23
+ | Other HTTP errors | No |
24
+ | Fetch or reader failure | Only if the transport predicate accepts it (default: TypeError) |
25
+ | EOF without completion, missing body, incomplete UTF-8 at EOF | Yes |
26
+ | Invalid UTF-8 detected while decoding, invalid JSON or event fields | No |
27
+ | Model-reported error, unsupported output, redirect, parser limit | No |
28
+ | Exception from an event callback or retry predicate | No |
29
+ | Cancellation, total deadline or optional stream phase timeout reached | No |
30
+
31
+ Eligibility is not a guarantee of a retry. The remaining retry budget, total deadline, Retry-After delay and explicit remote-retry permission still apply. The transport predicate cannot override other safety rules. A fresh generation is not a continuation and can produce different text or incur another charge.
32
+
33
+ ## Event ordering
34
+
35
+ With visible text followed by a recoverable failure, the normal sequence is:
36
+
37
+ `attempt(1) -> delta(1)* -> retry(1) -> reset(2) -> attempt(2) -> delta(2)* -> done(2)`
38
+
39
+ The reset is emitted after the retry delay, before the next attempt and before its first delta. If no text was emitted, reset is omitted. If cancelled during the delay, no reset or next attempt is emitted. If a callback throws, the exception is propagated without another request. A terminal failure does not automatically clear visible text; the application must choose how to mark or remove a failed answer. The UI must process reset synchronously before appending later deltas.
40
+
41
+ ## Timeout scope
42
+
43
+ The default streaming timeout is 120,000 ms; the general request wrapper defaults to 30,000 ms. Both cover their respective total operations, including retry delays (and response consumption when applicable). A synchronous callback cannot be preempted.
44
+
45
+ Optional `firstTextTimeoutMs` measures from each attempt's request start (including response headers) to the first nonempty text delta. Optional `idleTimeoutMs` starts after the first nonempty text delta and restarts at each subsequent nonempty text delta. It also covers waiting for the completion marker after the last text. Heartbeats, role metadata, empty deltas and incomplete protocol frames do not restart either clock. A valid completion without any text succeeds if received within the active deadlines.
46
+
47
+ Both options are disabled when omitted and otherwise require integer milliseconds from 1 to 2147483647. Phase clocks are per attempt and inactive during retry backoff. The total deadline always remains active. A phase timeout aborts the operation with `StreamTimeoutError` (`code: 'STREAM_TIMEOUT'`, `phase: 'first-text' | 'idle'`, `timeoutMs`); it is terminal and does not trigger a retry or reset. Already emitted text stays visible. Total timeout and caller cancellation keep their existing error types. No change is made to `reliableRequest` options.
48
+
49
+ ## Optional live recovery check
50
+
51
+ The existing Ollama test remains available. The shared Node.js-only command exercises both Ollama and OpenAI-compatible servers through a temporary loopback HTTP proxy. It forwards the first valid text event and cuts the first TCP connection; the second request is passed through. The proxy accepts only authenticated requests from the test client, rejects browser origins, allows at most two requests, and only connects to an HTTP server at 127.0.0.1. The first text event is re-framed using its original protocol; the second response is forwarded unchanged. Do not use this test against remote or billable endpoints. Authentication to the upstream model server is not supported by this test.
52
+
53
+ PowerShell, LM Studio (set the exact loaded model identifier):
54
+
55
+ ```powershell
56
+ $env:MODEL_PROTOCOL = 'openai'
57
+ $env:MODEL_ENDPOINT = 'http://127.0.0.1:1234/v1'
58
+ $env:MODEL_NAME = 'your-loaded-model-id'
59
+ npm run test:model:recovery
60
+ ```
61
+
62
+ For Ollama, set MODEL_PROTOCOL to ollama and use the Ollama endpoint and model ID. For llama.cpp, use its actual listening port (for example 8080) and served model identifier. Increase `MODEL_TIMEOUT_MS` for slow inference if necessary. Expected result: two attempts, one TCP cut, one retry, one reset, a nonempty second answer and a valid completion marker.
63
+
64
+ ## Live validation record template
65
+
66
+ | Server / build | Model ID | Node / OS | Checkout SHA | Normal | TCP recovery | Cancel | Timeout | CORS / browser |
67
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- |
68
+ | LM Studio | | | | | | | | |
69
+ | llama.cpp | | | | | | | | |
70
+ | Ollama | | | | | | | | |
71
+
72
+ Record PASS, FAIL, or NOT RUN separately for each check; include observed event order and errors. The synthetic TCP test uses a mock upstream. It is not evidence that a real model server passed.