@hmharness/kernel 0.23.45 → 0.23.47

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.
@@ -0,0 +1,49 @@
1
+ export interface TransportRequest {
2
+ method?: string;
3
+ headers?: Record<string, string>;
4
+ body?: string;
5
+ signal?: AbortSignal;
6
+ }
7
+ /** The subset of the WHATWG Response shape the kernel actually uses. Native
8
+ * fetch responses satisfy it structurally; the node:http fallback wraps an
9
+ * IncomingMessage to satisfy it by hand. */
10
+ export interface TransportResponse {
11
+ status: number;
12
+ ok: boolean;
13
+ headers: {
14
+ get(name: string): string | null;
15
+ };
16
+ text(): Promise<string>;
17
+ json(): Promise<unknown>;
18
+ body: {
19
+ getReader(): TransportReader;
20
+ } | null;
21
+ }
22
+ export interface TransportReader {
23
+ read(): Promise<{
24
+ done: boolean;
25
+ value?: Uint8Array;
26
+ }>;
27
+ cancel(): Promise<void>;
28
+ releaseLock(): void;
29
+ }
30
+ export type TransportMode = 'fetch' | 'node';
31
+ /** The raw probe: fetch must be a function AND WebAssembly must exist
32
+ * (undici depends on wasm; jitless builds compile it out - exactly the
33
+ * on-board failure this module exists for). */
34
+ export declare function detectTransportMode(): TransportMode;
35
+ /** All kernel outbound HTTP goes through here. The transport is probed once
36
+ * per process (memoized); the fetch path re-resolves globalThis.fetch on
37
+ * every call so tests and loaders can still substitute it after startup. */
38
+ export declare function httpFetch(url: string, init?: TransportRequest): Promise<TransportResponse>;
39
+ /** Tests only: drop the memo so a mutated globalThis gets re-probed. */
40
+ export declare function __resetTransportForTests(): void;
41
+ /** Tests only: pin the transport. Poisoning globalThis.WebAssembly to steer
42
+ * the probe is NOT CI-safe across node versions (on 22, an import-time
43
+ * fetch's deferred undici wasm parse can land inside the poisoned window and
44
+ * crash the process); pinning exercises the exact same code path without
45
+ * touching globals. */
46
+ export declare function __forceTransportForTests(mode: TransportMode): void;
47
+ /** Uniform reader entry for every SSE pump: the fetch path returns the
48
+ * body's own reader unchanged; the node fallback hands back its adapter. */
49
+ export declare function getReader(res: TransportResponse): TransportReader;
@@ -0,0 +1,234 @@
1
+ /**
2
+ * @hmharness/kernel - http-transport
3
+ * Transport selection for every outbound HTTP call in the kernel: native
4
+ * fetch (undici) when usable, a node:http/https fallback when it is not.
5
+ *
6
+ * Why a fallback exists (device forensics, 2026-10-29): the KaihongOS board
7
+ * must run node with --jitless (RWX pages are forbidden there; a normal
8
+ * build dies instantly). That node build (v24.19.0 musl, jitless) has
9
+ * `typeof WebAssembly === 'undefined'`, and undici's fetch depends on wasm -
10
+ * so EVERY fetch() call throws "fetch failed WebAssembly is not defined"
11
+ * within ~80ms, even to plain localhost HTTP. The kernel's provider
12
+ * chat/chatVision only spoke fetch, so on-board tasks hung forever in the
13
+ * retry loop (runner at 0% CPU). node:http's request() works fine there;
14
+ * this module routes to it automatically whenever fetch is unusable.
15
+ *
16
+ * The fallback deliberately mirrors fetch semantics: same request shape,
17
+ * WHATWG-reader-shaped response bodies (the SSE pumps in provider.ts and
18
+ * mcp.ts consume `getReader(res)` and never learn which transport answered),
19
+ * and network errors normalized to undici's `fetch failed ...` message shape
20
+ * so TRANSIENT_RE retry behavior is identical on both transports.
21
+ * packages/web's own server/tunnel/MCP fetches are out of scope here.
22
+ */
23
+ import * as http from 'node:http';
24
+ import * as https from 'node:https';
25
+ /** The raw probe: fetch must be a function AND WebAssembly must exist
26
+ * (undici depends on wasm; jitless builds compile it out - exactly the
27
+ * on-board failure this module exists for). */
28
+ export function detectTransportMode() {
29
+ return typeof globalThis.fetch === 'function' && typeof globalThis.WebAssembly !== 'undefined'
30
+ ? 'fetch'
31
+ : 'node';
32
+ }
33
+ let active;
34
+ /** All kernel outbound HTTP goes through here. The transport is probed once
35
+ * per process (memoized); the fetch path re-resolves globalThis.fetch on
36
+ * every call so tests and loaders can still substitute it after startup. */
37
+ export function httpFetch(url, init = {}) {
38
+ if (!active) {
39
+ if (detectTransportMode() === 'fetch') {
40
+ active = (u, i) => globalThis.fetch(u, i);
41
+ }
42
+ else {
43
+ // one-shot, for on-board forensics: proves which transport is live
44
+ console.warn('[chat] fetch unavailable (jitless/no-wasm) — using node:http transport');
45
+ active = nodeFetch;
46
+ }
47
+ }
48
+ return active(url, init);
49
+ }
50
+ /** Tests only: drop the memo so a mutated globalThis gets re-probed. */
51
+ export function __resetTransportForTests() {
52
+ active = undefined;
53
+ }
54
+ /** Tests only: pin the transport. Poisoning globalThis.WebAssembly to steer
55
+ * the probe is NOT CI-safe across node versions (on 22, an import-time
56
+ * fetch's deferred undici wasm parse can land inside the poisoned window and
57
+ * crash the process); pinning exercises the exact same code path without
58
+ * touching globals. */
59
+ export function __forceTransportForTests(mode) {
60
+ if (mode === 'node') {
61
+ console.warn('[chat] fetch unavailable (jitless/no-wasm) — using node:http transport');
62
+ active = nodeFetch;
63
+ }
64
+ else {
65
+ active = (u, i) => globalThis.fetch(u, i);
66
+ }
67
+ }
68
+ /** Uniform reader entry for every SSE pump: the fetch path returns the
69
+ * body's own reader unchanged; the node fallback hands back its adapter. */
70
+ export function getReader(res) {
71
+ if (!res.body)
72
+ throw new TypeError('provider: no response body (streaming requested)');
73
+ return res.body.getReader();
74
+ }
75
+ // One keep-alive agent per scheme, shared by every call, so the fallback
76
+ // matches fetch's connection-reuse behavior (no fresh TCP+TLS handshake per
77
+ // chat request).
78
+ const keepAliveHttp = new http.Agent({ keepAlive: true });
79
+ const keepAliveHttps = new https.Agent({ keepAlive: true });
80
+ function normalizeNetError(err) {
81
+ const cause = err instanceof Error ? err.message : String(err);
82
+ return new Error(`fetch failed ${cause}`);
83
+ }
84
+ /** node:http(s) request() shaped like fetch(). Network-level failures reject
85
+ * with undici's `fetch failed <cause>` message shape so TRANSIENT_RE /
86
+ * isTransientTransport retry matching sees identical text on both
87
+ * transports. Redirects are NOT followed (fetch would follow them), but a
88
+ * redirect on a chat/completions POST is not a real-world shape. */
89
+ function nodeFetch(url, init) {
90
+ return new Promise((resolve, reject) => {
91
+ let target;
92
+ try {
93
+ target = new URL(url);
94
+ }
95
+ catch (err) {
96
+ reject(new Error(`fetch failed invalid URL: ${String(err)}`));
97
+ return;
98
+ }
99
+ const secure = target.protocol === 'https:';
100
+ const req = (secure ? https : http).request({
101
+ protocol: target.protocol,
102
+ hostname: target.hostname,
103
+ port: target.port || (secure ? 443 : 80),
104
+ path: `${target.pathname}${target.search}`,
105
+ method: init.method ?? 'GET',
106
+ headers: init.headers,
107
+ agent: secure ? keepAliveHttps : keepAliveHttp,
108
+ });
109
+ // AbortSignal semantics mirror fetch. Destroying the request alone does
110
+ // NOT reliably emit 'error' on the response stream (a clean local close
111
+ // only emits 'close', which the reader adapter would read as a normal
112
+ // end-of-body and the chat would silently return an empty answer), so
113
+ // the destroy error is also pushed onto the response the moment one
114
+ // exists - the reader then surfaces it as an error through read(), the
115
+ // same way undici surfaces AbortError.
116
+ let resRef;
117
+ const onAbort = () => {
118
+ const err = new Error('operation aborted');
119
+ req.destroy(err);
120
+ resRef?.destroy(err);
121
+ };
122
+ const { signal } = init;
123
+ if (signal) {
124
+ if (signal.aborted)
125
+ onAbort();
126
+ else
127
+ signal.addEventListener('abort', onAbort, { once: true });
128
+ }
129
+ req.on('response', (res) => {
130
+ resRef = res;
131
+ // the abort listener deliberately STAYS: fetch's signal covers the
132
+ // whole body-consumption phase, not just until headers arrive (a
133
+ // keep-alive SSE stream must still be pierceable mid-read). The
134
+ // listener dies with the caller's per-request AbortController, so a
135
+ // request that completes without aborting leaks nothing.
136
+ resolve(wrapNodeResponse(res));
137
+ });
138
+ req.on('error', (err) => {
139
+ reject(normalizeNetError(err)); // no-op if the response already resolved; body cuts surface via the reader
140
+ });
141
+ if (init.body !== undefined)
142
+ req.write(init.body);
143
+ req.end();
144
+ });
145
+ }
146
+ /** Adapt an IncomingMessage to the TransportResponse shape: status/headers
147
+ * pass through, text()/json() buffer the whole body, and body.getReader()
148
+ * attaches the flowing-mode adapter on first use. A response is consumed
149
+ * exactly once - buffered OR streamed, never both - the same contract as a
150
+ * fetch Response. (One exception: a 401 renegotiate in provider.ts drops
151
+ * the body unread, so that one keep-alive socket is never returned to the
152
+ * pool - rare, self-limiting, and exactly what the fetch path does too.) */
153
+ function wrapNodeResponse(res) {
154
+ const raw = res.headers;
155
+ const get = (name) => {
156
+ const v = raw[name.toLowerCase()];
157
+ return v === undefined ? null : Array.isArray(v) ? v.join(', ') : v;
158
+ };
159
+ const readAll = () => new Promise((resolve, reject) => {
160
+ const chunks = [];
161
+ res.on('data', (c) => chunks.push(c));
162
+ res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
163
+ res.on('error', (e) => reject(normalizeNetError(e)));
164
+ });
165
+ let reader;
166
+ return {
167
+ status: res.statusCode ?? 0,
168
+ ok: (res.statusCode ?? 0) >= 200 && (res.statusCode ?? 0) < 300,
169
+ headers: { get },
170
+ text: readAll,
171
+ json: async () => JSON.parse(await readAll()),
172
+ body: {
173
+ getReader: () => {
174
+ if (!reader)
175
+ reader = nodeStreamReader(res);
176
+ return reader;
177
+ },
178
+ },
179
+ };
180
+ }
181
+ /** WHATWG reader adapter over a node stream: chunks land in a queue that
182
+ * read() drains; 'end'/'close'/cancel() settle pending and future reads as
183
+ * done (fetch's reader.cancel() resolves pending reads the same way), while
184
+ * 'error' rejects them with the normalized net-error shape so a mid-stream
185
+ * cut keeps matching TRANSIENT_RE. Buffer IS a Uint8Array; the SSE pumps
186
+ * hand the bytes straight to TextDecoder and never retain them, so no copy
187
+ * is made. */
188
+ function nodeStreamReader(stream) {
189
+ const queue = [];
190
+ let wake;
191
+ let finished = false;
192
+ const push = (item) => {
193
+ if (finished)
194
+ return;
195
+ if (item instanceof Error || item.done === true)
196
+ finished = true;
197
+ queue.push(item);
198
+ wake?.();
199
+ wake = undefined;
200
+ };
201
+ stream.on('data', (c) => push({ value: c }));
202
+ stream.on('end', () => push({ done: true }));
203
+ // destroy() mid-body emits no 'error', but reads must not hang either
204
+ stream.on('close', () => push({ done: true }));
205
+ // premature server cut: undici raises `terminated` for this exact shape
206
+ // (TRANSIENT_RE matches it, so the retry loop kicks in on node too)
207
+ stream.on('aborted', () => push(new Error('fetch failed terminated')));
208
+ stream.on('error', (e) => push(normalizeNetError(e)));
209
+ const stop = () => {
210
+ finished = true;
211
+ wake?.();
212
+ wake = undefined;
213
+ };
214
+ return {
215
+ async read() {
216
+ for (;;) {
217
+ const item = queue.shift();
218
+ if (item !== undefined) {
219
+ if (item instanceof Error)
220
+ throw item;
221
+ return item.done === true ? { done: true, value: undefined } : { done: false, value: item.value };
222
+ }
223
+ if (finished)
224
+ return { done: true, value: undefined };
225
+ await new Promise((r) => { wake = r; });
226
+ }
227
+ },
228
+ async cancel() {
229
+ stop();
230
+ stream.destroy(); // free the keep-alive socket instead of leaking it on a half-read body
231
+ },
232
+ releaseLock: stop,
233
+ };
234
+ }
package/dist/mcp.js CHANGED
@@ -7,6 +7,7 @@
7
7
  * 5800+-server ecosystem instead of rebuilding it is the whole point.
8
8
  */
9
9
  import { spawn } from 'node:child_process';
10
+ import { httpFetch, getReader } from "./http-transport.js";
10
11
  const PROTOCOL_VERSION = '2025-06-18';
11
12
  const CLIENT_INFO = { name: 'hmharness', version: '0.1.0' };
12
13
  /** Call-local incremental id; the wire only needs uniqueness per session. */
@@ -65,7 +66,7 @@ export class McpClient {
65
66
  };
66
67
  if (this.sessionId)
67
68
  headers['Mcp-Session-Id'] = this.sessionId;
68
- await fetch(cfg.url, {
69
+ await httpFetch(cfg.url, {
69
70
  method: 'POST',
70
71
  headers,
71
72
  body: JSON.stringify({ jsonrpc: '2.0', method }),
@@ -172,7 +173,7 @@ export class McpClient {
172
173
  let res;
173
174
  for (let attempt = 0; attempt < 2; attempt++) {
174
175
  try {
175
- res = await fetch(cfg.url, { method: 'POST', headers, body: JSON.stringify(payload), signal: ctrl.signal });
176
+ res = await httpFetch(cfg.url, { method: 'POST', headers, body: JSON.stringify(payload), signal: ctrl.signal });
176
177
  break;
177
178
  }
178
179
  catch (err) {
@@ -215,7 +216,7 @@ export class McpClient {
215
216
  }
216
217
  /** Read an SSE body up to the first `data:` JSON message, then stop. */
217
218
  async firstSseMessage(res) {
218
- const reader = res.body.getReader();
219
+ const reader = getReader(res);
219
220
  const decoder = new TextDecoder();
220
221
  let buf = '';
221
222
  try {
package/dist/provider.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { httpFetch, getReader } from "./http-transport.js";
1
2
  /** Transient failures worth retrying. `terminated` is undici's TypeError for
2
3
  * a socket cut mid-body (gateway dropped a long stream, proxy reset, server
3
4
  * restart) - the case that used to kill the whole task with a raw
@@ -99,7 +100,10 @@ export async function chat(cfg, messages, tools, opts = {}) {
99
100
  emitted = true; opts.onDelta(kind, chunk); }
100
101
  : undefined;
101
102
  try {
102
- const res = await fetch(endpoint(cfg.baseUrl), {
103
+ // httpFetch: native fetch, or the node:http fallback when fetch is
104
+ // unusable (jitless board builds compile out WebAssembly and undici
105
+ // dies with "fetch failed WebAssembly is not defined" on every call)
106
+ const res = await httpFetch(endpoint(cfg.baseUrl), {
103
107
  method: 'POST',
104
108
  headers: mkHeaders(authScheme),
105
109
  body: JSON.stringify(body),
@@ -173,9 +177,9 @@ export async function chat(cfg, messages, tools, opts = {}) {
173
177
  }
174
178
  /** Assemble a ChatResponse from an SSE stream, emitting deltas as they land. */
175
179
  async function consumeStream(res, onDelta) {
176
- if (!res.body)
177
- throw new TypeError('provider: no response body (streaming requested)');
178
- const reader = res.body.getReader();
180
+ // getReader: the fetch body's own reader, or the node-stream adapter -
181
+ // identical shape either way, so this pump never knows the transport
182
+ const reader = getReader(res);
179
183
  const decoder = new TextDecoder();
180
184
  let buf = '';
181
185
  let text = '';
@@ -306,7 +310,7 @@ export async function chatVision(cfg, prompt, imageDataUrl, opts = {}) {
306
310
  const vHeaders = vAuth === 'bearer'
307
311
  ? { 'Content-Type': 'application/json', Authorization: `Bearer ${cfg.apiKey}` }
308
312
  : { 'Content-Type': 'application/json', [vAuth]: cfg.apiKey };
309
- const res = await fetch(endpoint(cfg.baseUrl), {
313
+ const res = await httpFetch(endpoint(cfg.baseUrl), {
310
314
  method: 'POST',
311
315
  headers: vHeaders,
312
316
  body: JSON.stringify(body),
package/dist/types.d.ts CHANGED
@@ -1,8 +1,3 @@
1
- /**
2
- * @hmharness/kernel - types
3
- * The kernel contract surface. Deliberately small: a Tool, a chat message,
4
- * a provider config. Everything else in hmharness composes from these.
5
- */
6
1
  /** A JSON-Schema-shaped parameter description (OpenAI tool-call format). */
7
2
  export interface JsonSchema {
8
3
  type: string;
package/dist/types.js CHANGED
@@ -3,6 +3,7 @@
3
3
  * The kernel contract surface. Deliberately small: a Tool, a chat message,
4
4
  * a provider config. Everything else in hmharness composes from these.
5
5
  */
6
+ import { httpFetch } from "./http-transport.js";
6
7
  /**
7
8
  * Default-multimodal policy (2026-10-22): the CHAT model is assumed to see
8
9
  * images natively unless its provider is explicitly marked
@@ -179,13 +180,13 @@ export async function detectLocalProviders(cfg, readFileFn) {
179
180
  for (const port of ports) {
180
181
  try {
181
182
  const key = process.env[envVar];
182
- let r = await fetch(`http://127.0.0.1:${port}/v1/models`, {
183
+ let r = await httpFetch(`http://127.0.0.1:${port}/v1/models`, {
183
184
  headers: { Authorization: `Bearer ${key}` },
184
185
  signal: AbortSignal.timeout(800),
185
186
  });
186
187
  let authHeader;
187
188
  if (r.status === 401) {
188
- r = await fetch(`http://127.0.0.1:${port}/v1/models`, {
189
+ r = await httpFetch(`http://127.0.0.1:${port}/v1/models`, {
189
190
  headers: { 'X-Api-Key': key },
190
191
  signal: AbortSignal.timeout(800),
191
192
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/kernel",
3
- "version": "0.23.45",
3
+ "version": "0.23.47",
4
4
  "description": "hmharness kernel: tool registry, provider adapters, the agent loop, session log, config. Zero runtime dependencies (Node >=22 native fetch).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",