@hmharness/kernel 0.23.52 → 0.23.55

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.
@@ -73,7 +73,7 @@ export class CapabilityRegistry {
73
73
  capabilities = new Map();
74
74
  rules;
75
75
  constructor(rules = DEFAULT_POLICY_RULES) {
76
- this.rules = [...rules].sort((a, b) => a.priority - b.priority);
76
+ this.rules = rules.toSorted((a, b) => a.priority - b.priority);
77
77
  }
78
78
  /** Register a capability. Duplicate ids are rejected (supply-chain safety). */
79
79
  register(manifest) {
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @hmharness/kernel - deadline
3
+ *
4
+ * A deadline signal for a configured timeout value — the declarative form of
5
+ * `const ctrl = new AbortController(); setTimeout(() => ctrl.abort(), ms)`,
6
+ * with no timer to clear in a `finally`.
7
+ *
8
+ * Values a hand-edited config.json can hold are coerced the way `setTimeout`
9
+ * used to coerce them (NaN, negative and non-numeric values become an
10
+ * immediate deadline; values beyond the platform range are clamped): left
11
+ * raw they make `AbortSignal.timeout()` throw instead.
12
+ */
13
+ export declare function deadlineSignal(ms: number): AbortSignal;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @hmharness/kernel - deadline
3
+ *
4
+ * A deadline signal for a configured timeout value — the declarative form of
5
+ * `const ctrl = new AbortController(); setTimeout(() => ctrl.abort(), ms)`,
6
+ * with no timer to clear in a `finally`.
7
+ *
8
+ * Values a hand-edited config.json can hold are coerced the way `setTimeout`
9
+ * used to coerce them (NaN, negative and non-numeric values become an
10
+ * immediate deadline; values beyond the platform range are clamped): left
11
+ * raw they make `AbortSignal.timeout()` throw instead.
12
+ */
13
+ const MAX_TIMEOUT_MS = 0xFFFF_FFFF; // WebIDL unsigned long: the largest delay AbortSignal.timeout accepts
14
+ export function deadlineSignal(ms) {
15
+ const n = Number(ms);
16
+ return AbortSignal.timeout(Number.isFinite(n) && n > 0 ? Math.min(Math.floor(n), MAX_TIMEOUT_MS) : 0);
17
+ }
@@ -93,7 +93,7 @@ function nodeFetch(url, init) {
93
93
  target = new URL(url);
94
94
  }
95
95
  catch (err) {
96
- reject(new Error(`fetch failed invalid URL: ${String(err)}`));
96
+ reject(new Error(`fetch failed invalid URL: ${String(err)}`, { cause: err }));
97
97
  return;
98
98
  }
99
99
  const secure = target.protocol === 'https:';
package/dist/index.d.ts CHANGED
@@ -14,3 +14,4 @@ export * from './goal.js';
14
14
  export * from './mcp2026.js';
15
15
  export * from './adaptive-router.js';
16
16
  export * from './qrcode.js';
17
+ export * from './deadline.js';
package/dist/index.js CHANGED
@@ -14,3 +14,4 @@ export * from "./goal.js";
14
14
  export * from "./mcp2026.js";
15
15
  export * from "./adaptive-router.js";
16
16
  export * from "./qrcode.js";
17
+ export * from "./deadline.js";
package/dist/loop.d.ts CHANGED
@@ -65,15 +65,20 @@ export declare function sanitizeToolCalls<T extends {
65
65
  arguments: string;
66
66
  };
67
67
  }>(calls: T[]): T[];
68
+ /** Appended to a final answer the output cap severed (finish_reason 'length'):
69
+ * the one place the user learns the reply is not whole. */
70
+ export declare const TRUNCATED_TAIL = "\n\n[Reply truncated: the model hit its output length limit. Send \"continue\" to have it pick up where it stopped.]";
68
71
  export declare function runLoop(opts: {
69
72
  provider: ProviderConfig;
70
73
  registry: RegistryLike;
71
74
  messages: ChatMessage[];
72
75
  ctx: ToolContext;
73
76
  maxTurns?: number;
74
- /** AbortSignal: when fired, the loop stops at the next turn boundary and
75
- * returns with reason "interrupted". Use for user-initiated cancellation
76
- * (Esc key, /queue skip, web API interrupt). */
77
+ /** AbortSignal: when fired, the loop stops and returns with reason
78
+ * "interrupted" - at the next turn boundary, or right away if the model
79
+ * call is in flight (the call is cut and the stop is honoured at once).
80
+ * Use for user-initiated cancellation (Esc key, /queue skip, web API
81
+ * interrupt). */
77
82
  signal?: AbortSignal;
78
83
  /** Explicit transcript budget override (chars). Default: scales with the
79
84
  * model's context window (window.ts registry / provider.contextWindow). */
package/dist/loop.js CHANGED
@@ -41,6 +41,9 @@ export function sanitizeToolCalls(calls) {
41
41
  }
42
42
  });
43
43
  }
44
+ /** Appended to a final answer the output cap severed (finish_reason 'length'):
45
+ * the one place the user learns the reply is not whole. */
46
+ export const TRUNCATED_TAIL = '\n\n[Reply truncated: the model hit its output length limit. Send "continue" to have it pick up where it stopped.]';
44
47
  export async function runLoop(opts) {
45
48
  const { provider, registry, ctx, events } = opts;
46
49
  const modelCall = opts.chatImpl ?? chat;
@@ -130,12 +133,27 @@ export async function runLoop(opts) {
130
133
  content: `[turn checkpoint] You have been working for ${turn} turns. If the task is substantially complete, give your final answer. If not, continue — there is no turn limit; work until done.`,
131
134
  });
132
135
  }
133
- const chatRes = await modelCall(provider, compacted, tools, {
134
- onDelta: events?.onDelta,
135
- // the abort must pierce the in-flight call, not just turn boundaries -
136
- // a hung provider stream otherwise holds the session busy forever
137
- ...(opts.signal ? { signal: opts.signal } : {}),
138
- });
136
+ let chatRes;
137
+ try {
138
+ chatRes = await modelCall(provider, compacted, tools, {
139
+ onDelta: events?.onDelta,
140
+ // the abort must pierce the in-flight call, not just turn boundaries -
141
+ // a hung provider stream otherwise holds the session busy forever
142
+ ...(opts.signal ? { signal: opts.signal } : {}),
143
+ });
144
+ }
145
+ catch (err) {
146
+ // The abort pierces this call by design, so a stop that lands while the model
147
+ // is streaming arrives HERE as a rejected request. Until 0.23.55 it escaped the
148
+ // loop as a provider failure: the web UI showed "provider: request aborted …
149
+ // task child exit 1" for a stop the user had pressed on purpose. It is the same
150
+ // stop as one noticed at a turn boundary - keep what was built and say so.
151
+ if (opts.signal?.aborted) {
152
+ reason = 'interrupted';
153
+ break;
154
+ }
155
+ throw err;
156
+ }
139
157
  usage.promptTokens += chatRes.usage?.prompt_tokens ?? 0;
140
158
  usage.completionTokens += chatRes.usage?.completion_tokens ?? 0;
141
159
  // Usage fallback: many OpenAI-compatible gateways never report usage
@@ -154,7 +172,7 @@ export async function runLoop(opts) {
154
172
  events?.onAssistant?.(message);
155
173
  const calls = message.tool_calls ?? [];
156
174
  if (calls.length === 0) {
157
- const text = message.content ?? '';
175
+ let text = message.content ?? '';
158
176
  // A runtime-steering injection may have arrived while this turn was in
159
177
  // flight; honor it by continuing instead of ending (codex Enter while
160
178
  // the last answer streams). Only end when the queue is empty.
@@ -165,6 +183,17 @@ export async function runLoop(opts) {
165
183
  world++;
166
184
  continue;
167
185
  }
186
+ // The output cap cut the answer mid-sentence (finish_reason 'length').
187
+ // Nothing else on the wire says so, and until 0.23.55 the severed text
188
+ // reached every surface dressed as a complete reply. The marker travels
189
+ // as a text delta: the web UI, the TUI and the one-shot task render the
190
+ // STREAM and never the returned text, so a tail appended to the return
191
+ // value alone was seen nowhere. This also keeps the return equal to what
192
+ // was streamed. The stored transcript keeps the raw message.
193
+ if (chatRes.finishReason === 'length') {
194
+ events?.onDelta?.('text', TRUNCATED_TAIL);
195
+ text += TRUNCATED_TAIL;
196
+ }
168
197
  events?.onFinal?.(text, turn);
169
198
  return { text, turns: turn, toolUses, messages: working, usage, reason: 'final' };
170
199
  }
@@ -209,9 +238,11 @@ export async function runLoop(opts) {
209
238
  p.skip = true;
210
239
  }
211
240
  else if (badArgs) {
212
- p.output = rawArgs
213
- ? `unparseable tool arguments for ${name} (arguments must be valid JSON — repeat the call with complete JSON): ${rawArgs.slice(0, 200)}`
214
- : `empty tool arguments for ${name} (arguments must be valid JSON — repeat the call with complete JSON)`;
241
+ p.output = chatRes.finishReason === 'length'
242
+ ? `the ${name} call was cut off by the model's output length limit before its JSON arguments were complete. Repeat it with a much smaller payload (split a long file into several smaller writes).`
243
+ : rawArgs
244
+ ? `unparseable tool arguments for ${name} (arguments must be valid JSON — repeat the call with complete JSON): ${rawArgs.slice(0, 200)}`
245
+ : `empty tool arguments for ${name} (arguments must be valid JSON — repeat the call with complete JSON)`;
215
246
  p.isError = true;
216
247
  p.skip = true;
217
248
  }
package/dist/mcp.js CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import { spawn } from 'node:child_process';
10
10
  import { httpFetch, getReader } from "./http-transport.js";
11
+ import { deadlineSignal } from "./deadline.js";
11
12
  const PROTOCOL_VERSION = '2025-06-18';
12
13
  const CLIENT_INFO = { name: 'hmharness', version: '0.1.0' };
13
14
  /** Call-local incremental id; the wire only needs uniqueness per session. */
@@ -164,8 +165,8 @@ export class McpClient {
164
165
  };
165
166
  if (this.sessionId)
166
167
  headers['Mcp-Session-Id'] = this.sessionId;
167
- const ctrl = new AbortController();
168
- const timer = setTimeout(() => ctrl.abort(), timeoutMs);
168
+ // deadline covers the POST and the body read alike; nothing to clear
169
+ const signal = deadlineSignal(timeoutMs);
169
170
  try {
170
171
  // one retry for transient transport failures: a dead/restarting MCP
171
172
  // server used to surface a bare "TypeError: fetch failed" straight to
@@ -173,7 +174,7 @@ export class McpClient {
173
174
  let res;
174
175
  for (let attempt = 0; attempt < 2; attempt++) {
175
176
  try {
176
- res = await httpFetch(cfg.url, { method: 'POST', headers, body: JSON.stringify(payload), signal: ctrl.signal });
177
+ res = await httpFetch(cfg.url, { method: 'POST', headers, body: JSON.stringify(payload), signal });
177
178
  break;
178
179
  }
179
180
  catch (err) {
@@ -208,10 +209,9 @@ export class McpClient {
208
209
  const hint = isTransientTransport(msg)
209
210
  ? ` - the MCP server at ${cfg.url} is unreachable or cut the connection`
210
211
  : '';
211
- throw new Error(`mcp/${this.serverName}: request failed (${msg})${hint}`);
212
- }
213
- finally {
214
- clearTimeout(timer);
212
+ // message unchanged (the model sees String(err): annotation + hint only); the
213
+ // transport error is chained for logs and programmatic callers
214
+ throw new Error(`mcp/${this.serverName}: request failed (${msg})${hint}`, { cause: err });
215
215
  }
216
216
  }
217
217
  /** Read an SSE body up to the first `data:` JSON message, then stop. */
@@ -13,6 +13,12 @@ export interface ChatResponse {
13
13
  prompt_tokens?: number;
14
14
  completion_tokens?: number;
15
15
  };
16
+ /** Why the model stopped, as the provider reports it: 'stop' (natural end),
17
+ * 'length' (the output cap CUT the reply or a tool call's JSON mid-way),
18
+ * 'content_filter', 'tool_calls', ... Absent when the provider reports none.
19
+ * Until 0.23.55 both parse paths dropped it, so a truncated reply reached
20
+ * every caller dressed as a complete one. */
21
+ finishReason?: string;
16
22
  }
17
23
  export type DeltaKind = 'text' | 'reasoning' | 'reset';
18
24
  /** Permanent provider-side auth/payment failures: 401 (bad key), 402
package/dist/provider.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { httpFetch, getReader } from "./http-transport.js";
2
+ import { deadlineSignal } from "./deadline.js";
2
3
  /** Transient failures worth retrying. `terminated` is undici's TypeError for
3
4
  * a socket cut mid-body (gateway dropped a long stream, proxy reset, server
4
5
  * restart) - the case that used to kill the whole task with a raw
@@ -147,6 +148,7 @@ export async function chat(cfg, messages, tools, opts = {}) {
147
148
  ...(choice.message?.tool_calls ? { tool_calls: choice.message.tool_calls } : {}),
148
149
  },
149
150
  usage: data.usage,
151
+ ...(choice.finish_reason ? { finishReason: String(choice.finish_reason) } : {}),
150
152
  };
151
153
  }
152
154
  catch (err) {
@@ -185,6 +187,7 @@ async function consumeStream(res, onDelta) {
185
187
  let text = '';
186
188
  let reasoning = '';
187
189
  let usage;
190
+ let finishReason;
188
191
  // tool_calls accumulate across deltas, keyed by their index in the stream.
189
192
  const calls = new Map();
190
193
  // Idle guard rather than a total cap: generation length is unbounded.
@@ -222,6 +225,11 @@ async function consumeStream(res, onDelta) {
222
225
  }
223
226
  if (chunk.usage)
224
227
  usage = chunk.usage;
228
+ // the reason rides the LAST choice - usually one whose delta is empty,
229
+ // so it has to be read before the empty-delta skip below
230
+ const reason = chunk.choices?.[0]?.finish_reason;
231
+ if (reason)
232
+ finishReason = String(reason);
225
233
  const delta = chunk.choices?.[0]?.delta;
226
234
  if (!delta)
227
235
  continue;
@@ -273,6 +281,7 @@ async function consumeStream(res, onDelta) {
273
281
  ...(ordered.length > 0 ? { tool_calls: ordered } : {}),
274
282
  },
275
283
  usage,
284
+ ...(finishReason ? { finishReason } : {}),
276
285
  };
277
286
  }
278
287
  /** Accept bases with any /vN suffix (v1 OpenAI convention, v4 zhipu coding
@@ -304,8 +313,9 @@ export async function chatVision(cfg, prompt, imageDataUrl, opts = {}) {
304
313
  // same auth negotiation as chat(): explicit header, Bearer, then X-Api-Key
305
314
  let vAuth = cfg.authHeader ?? 'bearer';
306
315
  for (let attempt = 0; attempt < 2; attempt++) {
307
- const ctrl = new AbortController();
308
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? cfg.timeoutMs ?? 120_000);
316
+ // one deadline per attempt, nothing to clear in a finally; a timeout now
317
+ // surfaces as TimeoutError ("...aborted due to timeout") instead of AbortError
318
+ const signal = deadlineSignal(opts.timeoutMs ?? cfg.timeoutMs ?? 120_000);
309
319
  try {
310
320
  const vHeaders = vAuth === 'bearer'
311
321
  ? { 'Content-Type': 'application/json', Authorization: `Bearer ${cfg.apiKey}` }
@@ -314,7 +324,7 @@ export async function chatVision(cfg, prompt, imageDataUrl, opts = {}) {
314
324
  method: 'POST',
315
325
  headers: vHeaders,
316
326
  body: JSON.stringify(body),
317
- signal: ctrl.signal,
327
+ signal,
318
328
  });
319
329
  if (res.status === 401 && !cfg.authHeader && vAuth === 'bearer' && cfg.apiKey) {
320
330
  vAuth = 'X-Api-Key';
@@ -340,9 +350,6 @@ export async function chatVision(cfg, prompt, imageDataUrl, opts = {}) {
340
350
  throw err;
341
351
  await sleep(1500 * (attempt + 1));
342
352
  }
343
- finally {
344
- clearTimeout(timer);
345
- }
346
353
  }
347
354
  throw new Error(`provider: vision call failed after retry (${cfg.baseUrl}): ${lastError}`);
348
355
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/kernel",
3
- "version": "0.23.52",
3
+ "version": "0.23.55",
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",