reliable-requests 0.0.0-stage → 0.2.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 ADDED
@@ -0,0 +1,13 @@
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.
package/LICENSE ADDED
@@ -0,0 +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.
package/README.md CHANGED
@@ -1,3 +1,99 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
package/docs/USAGE.md ADDED
@@ -0,0 +1,295 @@
1
+ > Detailed documentation preserved from the initial development phase. Run commands from the repository root.
2
+
3
+ # Complete usage guide for reliable-requests
4
+
5
+ [![Node 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)
6
+ ![Node 18+](https://img.shields.io/badge/Node.js-18%2B-3cba83)
7
+ [![MIT](https://img.shields.io/badge/license-MIT-8bc4ef)](../LICENSE)
8
+
9
+ **Recover from interrupted local AI streams without mixing two different answers.**
10
+
11
+ A small, dependency-free JavaScript toolkit for Node.js 18+ and modern browsers. Built for text generation with Ollama, LM Studio, and llama.cpp. Works with any compatible installed model, including Qwen.
12
+
13
+ ## Try the visual demo
14
+
15
+ ```bash
16
+ npm run demo
17
+ ```
18
+
19
+ Open **http://127.0.0.1:4173**. Choose **Simulate interruption** (default), click **Start stream**, and watch the partial answer get discarded before a fresh one appears. **No neural model, GPU, or internet required** for this simulation.
20
+
21
+ Switch to **Live local model** after starting Ollama, LM Studio, or llama.cpp. The demo runs in your browser and connects to your own local model directly, so the model server must allow the page origin through CORS. The static demo server neither stores messages nor proxies requests. The live demo accepts loopback endpoints only.
22
+
23
+ ## How recovery works
24
+
25
+ ```mermaid
26
+ flowchart LR
27
+ A[Start generation] --> B{Stream completed?}
28
+ B -->|Yes| C[Done]
29
+ B -->|Interrupted| D{Retry budget left?}
30
+ D -->|No| E[Report error]
31
+ D -->|Yes| F[Retry and emit reset]
32
+ F --> G[Discard partial answer]
33
+ G --> A
34
+ ```
35
+
36
+ **Important:** restarting is not continuing the same generation. The model might produce different words. The library emits `reset` so callers **replace**, not append to, the interrupted response. Only text-only requests are supported; tool calls are not automatically executed.
37
+
38
+ ## Four ways to try it
39
+
40
+ | Goal | Command |
41
+ | --- | --- |
42
+ | Run unit + real HTTP fault tests | `npm test` |
43
+ | Open the interactive browser demo | `npm run demo` |
44
+ | Test an installed Ollama model | `MODEL_NAME=qwen2.5:0.5b npm run test:model` |
45
+ | Test a forced real Ollama disconnect | `MODEL_NAME=qwen2.5:0.5b npm run test:ollama:recovery` |
46
+
47
+ The model name shown is an example: install a model with Ollama first, or use a model already present. For OpenAI-compatible local servers, see the [real-model instructions](#test-on-a-real-model-optional). On Windows PowerShell, use the environment-variable examples in that section.
48
+
49
+ ## Local model streams
50
+
51
+ `streamLocalChat` is the distinctive part of this project: it can restart a **text-only** local-model stream after a partial answer. Before the next attempt it emits `reset`, so the caller replaces the old answer instead of appending a second generation to it. It works with any model name served by Ollama's native chat API or an OpenAI-compatible chat-completions endpoint (for example, LM Studio or llama.cpp). The model does not need to be Qwen.
52
+
53
+ ```js
54
+ import { streamLocalChat } from 'reliable-requests';
55
+
56
+ let shown = '';
57
+ await streamLocalChat({
58
+ endpoint: 'http://localhost:11434',
59
+ protocol: 'ollama',
60
+ model: 'qwen2.5:7b',
61
+ messages: [{ role: 'user', content: 'Explain recursion simply.' }],
62
+ timeoutMs: 60_000,
63
+ onEvent(event) {
64
+ if (event.type === 'reset') shown = '';
65
+ if (event.type === 'delta') shown += event.text;
66
+ if (event.type === 'retry') console.log('Restarting generation:', event.error.message);
67
+ if (event.type === 'done') console.log(shown);
68
+ },
69
+ });
70
+ ```
71
+
72
+ For an OpenAI-compatible local server, set `protocol: 'openai'` (the default) and `endpoint: 'http://localhost:1234/v1'` for LM Studio or your llama.cpp server URL. The function adds `/v1/chat/completions` itself, preserving any proxy path prefix; if the endpoint already ends in `/v1`, it adds only `/chat/completions`. `fetchImpl` and `headers` are optional. `signal` cancels the operation.
73
+
74
+ The parser limits each NDJSON or SSE protocol line to **262,144 JavaScript characters** by default. This bounds the pending line buffer without limiting the total length of a completed answer. Override with `maxLineChars` (between 1 and 4,194,304), e.g. `maxLineChars: 524288` for an unusually large event. A line exceeding the limit fails with `StreamLineTooLongError` and `code === 'STREAM_LINE_TOO_LONG'`; this is **not automatically retried**. OpenAI-compatible SSE data is dispatched at a blank line, with multiple data fields joined by a newline. LF, CRLF and CR endings, UTF-8 split across chunks, comments and non-data fields are supported. An event without its terminating blank line at EOF is discarded, including an incomplete [DONE] marker; the stream is treated as interrupted. SSE reconnection, Last-Event-ID and server event retry fields are not used: retries restart the model generation. Ollama retains its NDJSON behavior, including a final line without a newline.
75
+
76
+ The joined SSE data payload also has a limit, maxEventChars (default: maxLineChars; range 1 to 4,194,304). An oversized event fails with StreamEventTooLongError and code STREAM_EVENT_TOO_LONG, without a retry. Both errors are exported from reliable-requests. These limits describe parser memory, not model token limits.
77
+
78
+ The callback receives `attempt`, `delta`, `retry`, `reset`, and `done` events. Its work should be synchronous. A retry begins only for a transient HTTP status (429, 500, 502, 503, 504), a retryable fetch or stream-read error, or a stream ending before its completion marker. Malformed protocol events (including invalid UTF-8), unsupported outputs, parser limits and callback errors are not retried. Invalid UTF-8 detected while decoding incoming bytes raises InvalidStreamEventError with field UTF-8 instead of silently replacing damaged bytes. An incomplete UTF-8 character detected only at EOF before completion raises StreamInterruptedError: the connection may have ended prematurely, so the usual retry budget, deadline, cancellation, and remote opt-in rules apply. If text was already emitted, a retry resets it before the next attempt. Known text and completion fields must have valid types; nullable optional text, empty choices and unknown metadata are accepted. OpenAI requests explicitly set n: 1. Only a single choice with index 0 (or an omitted index) is supported per event; multiple choices or a nonzero index raise InvalidStreamEventError, including when different indexes arrive in separate events. Ollama request bodies are unchanged. Invalid structures raise InvalidStreamEventError (INVALID_STREAM_EVENT), exported from reliable-requests. The monotonic deadline is checked while processing chunks and immediately before invoking event callbacks; synchronous user callbacks cannot be preempted. Some invalid fetch configurations can also raise TypeError; see the shared retry policy below. The same total deadline covers the stream and retry waits. The function returns `{ attempts }` on success. When the server reports a completion reason, both the result and the `done` event also include `finishReason`: for example, `length` signals an output truncated by a model limit. Servers may omit the reason; its absence is not proof of a complete answer. Tool calls fail with `UnsupportedModelOutputError` rather than being silently discarded. Exceptions from `onEvent` propagate without retrying the model.
79
+
80
+ A restart runs the model again and may produce different text. Local inference uses extra compute; remote services may charge again. For that reason automatic retries are enabled by default only for loopback addresses. Only HTTP(S) endpoints without URL credentials are accepted. Automatic retries recognize exactly localhost, IPv6 ::1, and normalized IPv4 addresses in 127.0.0.0/8 (not domain names with a similar prefix). To permit retries for a remote endpoint, explicitly set `allowRemoteRetries: true`. Model requests always use redirect: 'manual'; configure the final endpoint directly. An HTTP redirect response (including the browser's opaque redirect response) fails with ModelRedirectError (MODEL_REDIRECT) without retrying or following the target. A browser may still hide some cross-origin/CORS failures behind a generic Fetch TypeError before a response is exposed; such indistinguishable failures remain subject to shouldRetryError. Set shouldRetryError: () => false to disable these transport retries if needed. Custom fetch implementations must honor redirect and signal options; this is a URL policy, not DNS or proxy verification. Ordinary reliableRequest leaves the redirect option to its caller. This is **not** an exactly-once guarantee. This first version accepts text messages only and does not execute model tool calls. Browser apps also need their local server to allow the browser origin through CORS.
81
+
82
+ ## General fetch wrapper
83
+
84
+ It gives one deadline to the whole operation: attempts, pauses before retries, and response reading **when you provide a `consume` function**. It uses `AbortSignal` for cancellation and retries only `GET` and `HEAD` by default.
85
+
86
+ Version 0.2.0 is being prepared for npm. Build an archive with `npm pack` and install that archive in your application; see the [installation instructions](../README.md#use-in-javascript). The package is ESM-only and includes TypeScript declarations. Its public entry is `reliable-requests`; internal `src/` paths are not package exports.
87
+
88
+ ## Try it
89
+
90
+ ```js
91
+ import { reliableRequest } from 'reliable-requests';
92
+
93
+ const user = await reliableRequest('https://example.com/api/user', {
94
+ timeoutMs: 8_000,
95
+ retries: 2,
96
+ consume: response => response.json(),
97
+ });
98
+ console.log(user);
99
+ ```
100
+
101
+ Without `consume`, the function returns a normal `Response` as soon as headers arrive. The deadline then ends, so later reads of `response.body` are **not** covered. Use `consume` whenever the full body or a stream must finish within the deadline.
102
+
103
+ ## Optional stream metrics
104
+
105
+ Track the connection without changing request or retry behavior. No analytics are sent anywhere; the counters stay in your application.
106
+
107
+ ```js
108
+ import { createStreamMetrics } from 'reliable-requests';
109
+ import { streamLocalChat } from 'reliable-requests';
110
+
111
+ const metrics = createStreamMetrics();
112
+ try {
113
+ await streamLocalChat({
114
+ endpoint: 'http://127.0.0.1:11434',
115
+ protocol: 'ollama',
116
+ model: 'your-installed-model',
117
+ messages: [{ role: 'user', content: 'Hello!' }],
118
+ onEvent(event) {
119
+ metrics.record(event);
120
+ // Render reset/delta events in your UI here.
121
+ },
122
+ });
123
+ } finally {
124
+ metrics.finish();
125
+ console.log(metrics.snapshot());
126
+ }
127
+ ```
128
+
129
+ Metrics include attempts, retries, resets, text delta events, visible characters after the last reset, total received characters, first-text latency, and elapsed time. **Characters are not tokens**, and these measurements are not benchmarks of model inference speed. Results are read-only snapshots.
130
+
131
+ ## Cancellation
132
+
133
+ ```js
134
+ const controller = new AbortController();
135
+ const pending = reliableRequest('https://example.com/api/user', {
136
+ signal: controller.signal,
137
+ consume: response => response.text(),
138
+ });
139
+ controller.abort();
140
+ await pending; // rejects with AbortError
141
+ ```
142
+
143
+ An already aborted signal sends no request. Cancellation also interrupts retry delays. A timeout rejects with `RequestTimeoutError` and `code === 'REQUEST_TIMEOUT'`. The wrapper aborts its own fetch signal and rejects on time even if a custom fetch implementation ignores abort.
144
+
145
+ ## Streaming
146
+
147
+ Keep the reader inside `consume` and release it when finished. The wrapper's signal tells you when to stop. This example collects chunks; a UI can process each chunk as it arrives.
148
+
149
+ ```js
150
+ const chunks = await reliableRequest('https://example.com/events', {
151
+ timeoutMs: 30_000,
152
+ consume: async (response, signal) => {
153
+ const reader = response.body.getReader();
154
+ const chunks = [];
155
+ const onAbort = () => { reader.cancel().catch(() => {}); };
156
+ signal.addEventListener('abort', onAbort, { once: true });
157
+ try {
158
+ while (true) {
159
+ const { value, done } = await reader.read();
160
+ if (done) return chunks;
161
+ chunks.push(new TextDecoder().decode(value, { stream: true }));
162
+ }
163
+ } finally {
164
+ signal.removeEventListener('abort', onAbort);
165
+ reader.releaseLock();
166
+ }
167
+ },
168
+ });
169
+ ```
170
+
171
+ The deadline includes the entire stream. If it expires after some chunks were delivered, the promise rejects; those chunks may already have reached your UI. Do not silently retry a partially delivered stream. For SSE, parse events in your consumer and treat a protocol marker such as `[DONE]` according to the server's rules.
172
+
173
+ ## Retry policy and errors
174
+
175
+ `retries` means additional attempts (default 2); `timeoutMs` defaults to 30,000 ms. Only `GET` and `HEAD` retry. A fetch TypeError or HTTP 429, 500, 502, 503, or 504 may retry. HTTP 4xx errors such as 401 and 404 fail immediately. Both APIs use the same exponential backoff with bounded jitter (250 ms initial base, 5 s maximum base). A valid Retry-After value (seconds or HTTP date) is treated as a minimum delay, with small nonnegative jitter; it is never shortened to an earlier retry. Every delay consumes the same total time budget. If the next delay cannot fit, the operation rejects immediately with RequestTimeoutError rather than sending another request.
176
+
177
+ Both APIs accept an optional synchronous shouldRetryError(error, { attempt, method, phase }) predicate. Return true to retry an eligible transport error. The default accepts TypeError, which Fetch uses for network failures but also for some invalid request options; browsers do not reliably distinguish them. For example, shouldRetryError: () => false disables transport-error retries. In reliableRequest the predicate is called only for a fetch rejection on GET/HEAD, never for errors in consume. In streamLocalChat it may also receive phase: 'read' for a rejected stream read. It does not override HTTP-status rules, retry budgets, method safety, remote opt-in, or the interrupted-stream policy. It is not called for malformed SSE/NDJSON, callback errors, cancellation, or timeouts. Exceptions from the predicate propagate without another attempt. The streaming retry event also exposes delayMs.
178
+
179
+ `POST`, `PUT`, `PATCH`, and `DELETE` are never retried. Repeating one could create a duplicate operation or charge twice. If your API has an idempotency key contract, put a separate, explicit retry policy around that operation.
180
+
181
+ An unsuccessful final response throws `HttpError` with `status`, `response`, and `attempts`. The response body remains available for diagnosis. Transport errors retain their original error. Errors thrown by `consume` propagate and are not retried, because the body or a stream may already have been partly read.
182
+
183
+ Pass ordinary `fetch` options such as `headers`, `credentials`, and `method` alongside the options above. The first argument must be a URL string or `URL`; `Request` objects are not supported because their bodies may be one-shot. `fetchImpl` is available for tests or a compatible custom implementation.
184
+
185
+ ## Run tests
186
+
187
+ ```sh
188
+ npm test
189
+ ```
190
+
191
+ The automated tests use Node's built-in test runner and require no dependency installation or AI model.
192
+
193
+ ## Tests over real HTTP
194
+
195
+ Run all automated tests with:
196
+
197
+ npm test
198
+
199
+ The integration tests start an actual HTTP server on your computer (not a fake fetch). They test both Ollama NDJSON and OpenAI-compatible SSE, break connections after the first words, stall streams, send transient server errors, and verify cancellation, deadline enforcement, and safe retry boundaries. You do not need to install a model, GPU drivers, or extra dependencies.
200
+
201
+ ## Test against an installed local model
202
+
203
+ First start your existing Ollama, LM Studio, or llama.cpp server. Then use the optional smoke test. It sends a short text prompt, prints the streamed answer, and reports whether the protocol completed.
204
+
205
+ For Ollama, first run ollama list to find your installed model. For example:
206
+
207
+ MODEL_PROTOCOL=ollama MODEL_NAME=qwen2.5:7b npm run test:model
208
+
209
+ The model name is an example; use one you actually have installed. The default Ollama endpoint is http://127.0.0.1:11434. If it is not running, start it normally (for example with ollama serve).
210
+
211
+ For an OpenAI-compatible endpoint in LM Studio or llama.cpp:
212
+
213
+ MODEL_PROTOCOL=openai MODEL_ENDPOINT=http://127.0.0.1:1234/v1 MODEL_NAME=your-installed-model npm run test:model
214
+
215
+ Replace the model and address with your server settings. For slow local models you can specify a larger deadline in milliseconds, for example MODEL_TIMEOUT_MS=300000.
216
+
217
+ On Windows PowerShell, an Ollama example is:
218
+
219
+ $env:MODEL_PROTOCOL = 'ollama'
220
+ $env:MODEL_NAME = 'qwen2.5:7b'
221
+ npm run test:model
222
+
223
+ The smoke test does not retry a real model call automatically: it only checks that one generation succeeds. To test interrupted streams and automatic recovery without breaking your own model server, run npm test. Those tests simulate failures predictably and confirm that reset replaces the partial output. A restarted generation is not a continuation of the old text.
224
+
225
+ ## Optional long-stream Ollama stress check
226
+
227
+ After the normal live-model and recovery checks pass, you can sample repeated, longer responses with a real local Ollama model. **Git Bash**:
228
+
229
+ ```bash
230
+ MODEL_NAME=qwen2.5:0.5b npm run test:ollama:stress
231
+ ```
232
+
233
+ The test runs two regular generations by default, counts text chunks and characters without retaining the answer, and prints a few JavaScript heap snapshots. It does **not** deliberately interrupt the model. A 240-second total deadline is applied **per generation**, and `Ctrl+C` stops the script.
234
+
235
+ Set `STRESS_ROUNDS=1` for one run, or `MODEL_TIMEOUT_MS=300000` for a slower model. This uses only your local Ollama instance at `127.0.0.1`. CPU/GPU use will increase during generation. The sampled JavaScript heap **does not measure Ollama's own memory**, and passing the test does not prove that there are no memory leaks. If your model generates less than 500 characters, the script warns that the run was too short to be a strong long-answer stress sample.
236
+
237
+ ## One-shot real Ollama connection-drop test
238
+
239
+ After the normal live-model test succeeds, you can check **recovery from an actual broken TCP stream** while Ollama stays running. This is an optional manual test and is not run automatically in CI because it requires a real installed model.
240
+
241
+ In **Git Bash** on Windows (or a macOS/Linux shell):
242
+
243
+ ```bash
244
+ MODEL_NAME=qwen2.5:0.5b npm run test:ollama:recovery
245
+ ```
246
+
247
+ Choose a model from `ollama list`. The default is `qwen2.5:0.5b`. For a different local Ollama port, set `OLLAMA_ENDPOINT=http://127.0.0.1:YOUR_PORT`. To allow a slow model more time, set `MODEL_TIMEOUT_MS=300000`.
248
+
249
+ In **Windows PowerShell**:
250
+
251
+ ```powershell
252
+ $env:MODEL_NAME = 'qwen2.5:0.5b'
253
+ npm run test:ollama:recovery
254
+ ```
255
+
256
+ The script checks that the model is installed, then starts a **temporary, random-port proxy bound only to 127.0.0.1**. It allows only two authenticated, text-only Ollama chat requests. On the first, it forwards the first real generated text event and deliberately drops the TCP connection. `streamLocalChat` should retry, emit `reset` to discard the partial answer, and complete a second fresh generation. The proxy does not stop Ollama, change your network settings, or send prompts to an outside server. It closes automatically at the end.
257
+
258
+ Expected success:
259
+
260
+ ```text
261
+ Generation attempt 1
262
+ First connection interrupted: retrying safely
263
+ RESET: discarded partial text before the new answer
264
+ Generation attempt 2
265
+ Second generation completed
266
+
267
+ PASS: 2 attempts, 1 real connection cut, 1 retry, 1 reset.
268
+ ```
269
+
270
+ **Limits:** this generates twice, using extra local compute. It does **not** resume the interrupted generation or guarantee identical text. Do not use the fault proxy with remote or billable inference endpoints. The automatic CI test uses a fake local Ollama upstream with real TCP sockets, while this manual command checks against your actual installed model.
271
+
272
+ ## Why another wrapper?
273
+
274
+ [Ky](https://github.com/sindresorhus/ky) is a more complete fetch client and already has a `totalTimeout` option. [p-retry](https://github.com/sindresorhus/p-retry) retries arbitrary async work with a time budget and cancellation. [Got](https://github.com/sindresorhus/got) is a capable Node.js HTTP client. Use one of them when you need its broader features. This project focuses on local text-model streams that can restart after partial output with an explicit reset event. The general fetch wrapper remains available for ordinary HTTP calls.
275
+
276
+ The design was informed by a timeout fix in [helper-with-conspects](https://github.com/Stairrax/helper-with-conspects). This implementation is written independently; no source code was copied from that GPL-3.0-only project.
277
+
278
+ ## Project status and contributing
279
+
280
+ This is a **draft API**, not a published package. The code is in the [draft PR](https://github.com/Stairrax/reliable-requests/pull/1). No release has been published and `package.json` is intentionally `private: true`.
281
+
282
+ - [CONTRIBUTING.md](../CONTRIBUTING.md) — how to run tests and propose changes
283
+ - [ROADMAP.md](../ROADMAP.md) — steps before the first release
284
+ - [GitHub Issues](https://github.com/Stairrax/reliable-requests/issues) — bug reports and features; remove access tokens and private prompts
285
+ - [SECURITY.md](../SECURITY.md) — security disclosure guidance
286
+
287
+ Node 18 and 22 are tested in CI. Real installed models and different browsers still need hands-on verification; passing automation does not prove universal compatibility.
288
+
289
+ ## License
290
+
291
+ Copyright (c) 2026 Stairrax.
292
+
293
+ This project uses the MIT License (SPDX: MIT). See the complete terms in [LICENSE](../LICENSE).
294
+
295
+ You may use, modify, and distribute the 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.
package/index.d.ts ADDED
@@ -0,0 +1,127 @@
1
+ export type ModelProtocol = 'openai' | 'ollama';
2
+
3
+ export interface RetryContext {
4
+ attempt: number;
5
+ method: string;
6
+ phase: 'fetch' | 'read';
7
+ }
8
+
9
+ export type RetryPredicate = (error: unknown, context: RetryContext) => boolean;
10
+ export type FetchImplementation = (input: string | URL, init?: RequestInit) => Promise<Response>;
11
+
12
+ export interface RequestOptions extends RequestInit {
13
+ timeoutMs?: number;
14
+ retries?: number;
15
+ fetchImpl?: FetchImplementation;
16
+ shouldRetryError?: RetryPredicate;
17
+ }
18
+
19
+ export interface ConsumingRequestOptions<T> extends RequestOptions {
20
+ consume: (response: Response, signal: AbortSignal) => T | PromiseLike<T>;
21
+ }
22
+
23
+ export function reliableRequest<T>(input: string | URL, options: ConsumingRequestOptions<T>): Promise<T>;
24
+ export function reliableRequest(input: string | URL, options?: RequestOptions & { consume?: undefined }): Promise<Response>;
25
+
26
+ export type StreamEvent =
27
+ | { type: 'attempt'; attempt: number }
28
+ | { type: 'delta'; attempt: number; text: string }
29
+ | { type: 'retry'; attempt: number; error: unknown; partial: boolean; delayMs: number }
30
+ | { type: 'reset'; attempt: number }
31
+ | { type: 'done'; attempt: number; finishReason?: string };
32
+
33
+ export interface ChatMessage {
34
+ role: string;
35
+ content: string;
36
+ }
37
+
38
+ export interface StreamLocalChatOptions {
39
+ endpoint: string | URL;
40
+ protocol?: ModelProtocol;
41
+ model: string;
42
+ messages: ChatMessage[];
43
+ timeoutMs?: number;
44
+ retries?: number;
45
+ signal?: AbortSignal;
46
+ onEvent: (event: StreamEvent) => void;
47
+ headers?: HeadersInit;
48
+ fetchImpl?: FetchImplementation;
49
+ shouldRetryError?: RetryPredicate;
50
+ allowRemoteRetries?: boolean;
51
+ maxLineChars?: number;
52
+ maxEventChars?: number;
53
+ }
54
+
55
+ export interface StreamResult {
56
+ attempts: number;
57
+ finishReason?: string;
58
+ }
59
+
60
+ export function streamLocalChat(options: StreamLocalChatOptions): Promise<StreamResult>;
61
+
62
+ export interface StreamMetricsSnapshot {
63
+ readonly attempts: number;
64
+ readonly retries: number;
65
+ readonly resets: number;
66
+ readonly deltaEvents: number;
67
+ readonly receivedCharacters: number;
68
+ readonly visibleCharacters: number;
69
+ readonly timeToFirstDeltaMs: number | null;
70
+ readonly completed: boolean;
71
+ readonly elapsedMs: number;
72
+ }
73
+
74
+ export interface StreamMetrics {
75
+ record(event: StreamEvent): void;
76
+ finish(): void;
77
+ snapshot(): StreamMetricsSnapshot;
78
+ }
79
+
80
+ export function createStreamMetrics(options?: { now?: () => number }): StreamMetrics;
81
+
82
+ export class RequestTimeoutError extends Error {
83
+ constructor(timeoutMs: number, message?: string);
84
+ code: 'REQUEST_TIMEOUT';
85
+ timeoutMs: number;
86
+ }
87
+
88
+ export class HttpError extends Error {
89
+ constructor(response: Response, attempts: number);
90
+ code: 'HTTP_ERROR';
91
+ status: number;
92
+ response: Response;
93
+ attempts: number;
94
+ }
95
+
96
+ export class StreamInterruptedError extends Error {
97
+ constructor(message?: string);
98
+ code: 'STREAM_INTERRUPTED';
99
+ }
100
+
101
+ export class ModelRedirectError extends Error {
102
+ constructor();
103
+ code: 'MODEL_REDIRECT';
104
+ }
105
+
106
+ export class UnsupportedModelOutputError extends Error {
107
+ constructor();
108
+ code: 'UNSUPPORTED_MODEL_OUTPUT';
109
+ }
110
+
111
+ export class InvalidStreamEventError extends Error {
112
+ constructor(protocol: ModelProtocol, field?: string);
113
+ code: 'INVALID_STREAM_EVENT';
114
+ field: string | undefined;
115
+ }
116
+
117
+ export class StreamLineTooLongError extends Error {
118
+ constructor(maxLineChars: number);
119
+ code: 'STREAM_LINE_TOO_LONG';
120
+ maxLineChars: number;
121
+ }
122
+
123
+ export class StreamEventTooLongError extends Error {
124
+ constructor(maxEventChars: number);
125
+ code: 'STREAM_EVENT_TOO_LONG';
126
+ maxEventChars: number;
127
+ }
package/index.js ADDED
@@ -0,0 +1,11 @@
1
+ export { reliableRequest, RequestTimeoutError, HttpError } from './src/index.js';
2
+ export {
3
+ streamLocalChat,
4
+ StreamInterruptedError,
5
+ ModelRedirectError,
6
+ UnsupportedModelOutputError,
7
+ InvalidStreamEventError,
8
+ StreamLineTooLongError,
9
+ StreamEventTooLongError,
10
+ } from './src/local-chat.js';
11
+ export { createStreamMetrics } from './src/metrics.js';
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
- {
2
- "name": "reliable-requests",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "reliable-requests",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "engines": {
6
+ "node": ">=18"
7
+ },
8
+ "scripts": {
9
+ "test": "node --test",
10
+ "test:model": "node examples/verify-local-model.mjs",
11
+ "demo": "node examples/demo/server.mjs",
12
+ "test:browser": "node scripts/browser-smoke.mjs",
13
+ "test:ollama:recovery": "node examples/verify-ollama-recovery.mjs",
14
+ "test:ollama:stress": "node examples/verify-ollama-stress.mjs",
15
+ "test:package": "node scripts/verify-package.mjs",
16
+ "check": "npm test && npm run test:package"
17
+ },
18
+ "license": "MIT",
19
+ "description": "Resilient local-model text streams with explicit reset on retry",
20
+ "main": "./index.js",
21
+ "types": "./index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./index.d.ts",
25
+ "import": "./index.js"
26
+ }
27
+ },
28
+ "files": [
29
+ "index.js",
30
+ "index.d.ts",
31
+ "src/",
32
+ "docs/USAGE.md",
33
+ "CHANGELOG.md"
34
+ ],
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/Stairrax/reliable-requests.git"
38
+ },
39
+ "bugs": {
40
+ "url": "https://github.com/Stairrax/reliable-requests/issues"
41
+ },
42
+ "homepage": "https://github.com/Stairrax/reliable-requests#readme",
43
+ "devDependencies": {
44
+ "typescript": "5.9.3"
45
+ }
46
+ }
@@ -0,0 +1,17 @@
1
+ const HTTP_PROTOCOLS = new Set(['http:', 'https:']);
2
+
3
+ export function parseEndpoint(endpoint) {
4
+ const url = new URL(endpoint);
5
+ if (!HTTP_PROTOCOLS.has(url.protocol)) throw new TypeError('endpoint must use HTTP or HTTPS');
6
+ if (url.username || url.password) throw new TypeError('endpoint must not contain credentials');
7
+ return url;
8
+ }
9
+
10
+ export function isLoopback(url) {
11
+ if (!HTTP_PROTOCOLS.has(url.protocol)) return false;
12
+ const host = url.hostname;
13
+ if (host === 'localhost' || host === '[::1]') return true;
14
+ const octets = host.split('.');
15
+ if (octets.length !== 4 || octets[0] !== '127') return false;
16
+ return octets.every(octet => /^(0|[1-9][0-9]{0,2})$/.test(octet) && Number(octet) <= 255);
17
+ }