@commonlyai/cli 0.1.360 → 0.1.362

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.
@@ -7,7 +7,7 @@ import { join } from 'path';
7
7
  import { StringDecoder } from 'string_decoder';
8
8
  import { observeSpawn, controlsFromArguments } from '../runtime-observation.js';
9
9
  import { requireSeatModel } from '../seat-model.js';
10
- import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
10
+ import { adapterFailure, markExternalSignal, spawnCredentials } from '../upstream-refusal.js';
11
11
 
12
12
  export const SUPPORTED_HERMES_VERSION_RANGE = '>=0.22.5 <0.23.0';
13
13
  const supportsHermesVersion = (version) => {
@@ -165,20 +165,29 @@ const runHermes = ({ args, prompt, cwd, env, timeoutMs, spawnImpl, credentials,
165
165
  child.stderr.on('data', (chunk) => {
166
166
  stderr = `${stderr}${chunk.toString()}`.slice(-MAX_STDERR_CHARS);
167
167
  });
168
- child.on('close', (code) => {
168
+ child.on('close', (code, signal) => {
169
169
  closed = true;
170
170
  clearTimeout(killTimer);
171
171
  if (settled) return;
172
172
  if (timedOut) return finish(new Error(`Hermes timed out after ${timeoutMs}ms`));
173
173
  buffer += decoder.end();
174
174
  if (buffer.trim()) {
175
- try { readHermesJsonl(buffer.trim(), state); } catch (error) { return finish(error); }
175
+ // A protocol error found mid-stream settled above; one here is a trailing
176
+ // record, which an outside signal may have cut short mid-write (F293).
177
+ try { readHermesJsonl(buffer.trim(), state); } catch (error) {
178
+ const failedResult = state.result && (state.result.error || state.result.exit_code !== 0);
179
+ return finish(failedResult ? error : markExternalSignal(error, { code, signal }));
180
+ }
176
181
  }
177
182
  const result = state.result;
178
- if (!result || !state.started) return finish(new Error('Hermes exited without a complete JSONL result'));
183
+ // `settled` above covers this adapter's own stop(), so a signal here is outside.
184
+ if (!result || !state.started) {
185
+ return finish(markExternalSignal(new Error('Hermes exited without a complete JSONL result'), { code, signal }));
186
+ }
179
187
  if (code !== 0 || result.exit_code !== 0) {
180
188
  return finish(adapterFailure('Hermes', result.error || stderr || `exit ${code}`, {
181
- credentials, exitCode: code,
189
+ // A result that reported its own failure keeps it as the cause.
190
+ credentials, exitCode: code, ...(result.error || result.exit_code !== 0 ? {} : { signal }),
182
191
  }));
183
192
  }
184
193
  if (typeof result.text !== 'string' || !result.session_id) {
@@ -6,7 +6,9 @@ export {
6
6
  trackSupervisedGroup, killSupervisedGroups, armSupervisedGroupDeadline,
7
7
  readProcessTable, readProcess, descendantsOf, killDescendants,
8
8
  } from './process-group.js';
9
- export { adapterFailure, spawnCredentials } from './upstream-refusal.js';
9
+ export {
10
+ adapterFailure, markExternalSignal, namesFailureCause, spawnCredentials,
11
+ } from './upstream-refusal.js';
10
12
  export { default as stub } from './adapters/stub.js';
11
13
  export { createHermesAdapter } from './adapters/hermes.js';
12
14
  export { RunFailure, runFailure, failureKindOf, FAILURE_KINDS } from './failures.js';
@@ -381,7 +381,43 @@ export const providerCodeFrom = (text, { credentials = [] } = {}) => {
381
381
  return null;
382
382
  };
383
383
 
384
- export const adapterFailure = (label, text, { credentials = [], exitCode = null, limit } = {}) => {
384
+ // A child that closed on a polite signal: a person's Ctrl-C, a supervisor's
385
+ // stop, a walk harness cutting a turn short. The adapter knows which kills are
386
+ // its own (timeout, stall, overflow) and returns before it builds a failure, so
387
+ // reaching here with one of these means someone outside the wrapper sent it.
388
+ // SIGKILL stays out: the kernel's OOM killer sends it, and a child that keeps
389
+ // running out of memory should back the seat off like any other fault. A shell
390
+ // in between reports the signal as 128 + its number, so the codes count too.
391
+ const EXTERNAL_SIGNALS = new Set(['SIGTERM', 'SIGHUP', 'SIGINT']);
392
+ const EXTERNAL_SIGNAL_CODES = new Map([[143, 'SIGTERM'], [129, 'SIGHUP'], [130, 'SIGINT']]);
393
+
394
+ /**
395
+ * Mark `error` as a turn cut off by a signal from outside the wrapper (F293),
396
+ * so the run loop retries it without counting it as the provider failing.
397
+ * Call it only on a path whose failure has no cause of its own: a stream that
398
+ * named an error keeps that error's class.
399
+ */
400
+ export const markExternalSignal = (error, { code = null, signal = null } = {}) => {
401
+ const name = EXTERNAL_SIGNALS.has(signal) ? signal : EXTERNAL_SIGNAL_CODES.get(code);
402
+ if (name) {
403
+ error.signal = name;
404
+ error.externalSignal = true;
405
+ }
406
+ return error;
407
+ };
408
+
409
+ /**
410
+ * Whether the failure text names a cause: an upstream status or a provider
411
+ * code. Such a failure keeps its own class and is never marked as an outside
412
+ * signal (F293), however the child then exited.
413
+ */
414
+ export const namesFailureCause = (text, { credentials = [] } = {}) => (
415
+ scrubAdapterFailure(text, { credentials }).status !== null || providerCodeFrom(text, { credentials }) !== null
416
+ );
417
+
418
+ export const adapterFailure = (label, text, {
419
+ credentials = [], exitCode = null, limit, signal,
420
+ } = {}) => {
385
421
  const { status, detail } = scrubAdapterFailure(text, { credentials, limit });
386
422
  const code = exitCode === null ? '' : ` exited with code ${exitCode}`;
387
423
  const named = status === null ? '' : ` (upstream ${status})`;
@@ -389,7 +425,11 @@ export const adapterFailure = (label, text, { credentials = [], exitCode = null,
389
425
  if (status !== null) error.status = status;
390
426
  const providerCode = providerCodeFrom(text, { credentials });
391
427
  if (providerCode !== null) error.providerCode = providerCode;
392
- return error;
428
+ // Only when the caller passed `signal`, so a path that must keep its own
429
+ // cause (a stream's error, the adapter's own kill) never gets the mark, and
430
+ // never over a status or provider code the text named: that is a cause too.
431
+ if (signal === undefined || status !== null || providerCode !== null) return error;
432
+ return markExternalSignal(error, { code: exitCode, signal });
393
433
  };
394
434
 
395
435
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.360",
3
+ "version": "0.1.362",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -134,7 +134,9 @@ import {
134
134
  writeHooksConfig,
135
135
  } from '../lib/hooks-config.js';
136
136
  import {
137
+ EXTERNAL_SIGNAL_GRACE,
137
138
  formatRetryDelay,
139
+ isExternalSignal,
138
140
  spawnRetryJitter,
139
141
  spawnRetryPolicy,
140
142
  } from '../lib/spawn-retry.js';
@@ -2305,6 +2307,16 @@ export const performRun = ({
2305
2307
  const MAX_AUTH_ERRORS = 3;
2306
2308
  let consecutivePollFailures = 0;
2307
2309
  let consecutiveSpawnFailures = 0;
2310
+ // F293: turns cut off by an outside signal since the last good spawn. The
2311
+ // first EXTERNAL_SIGNAL_GRACE of them retry without counting as failures, so
2312
+ // a walk that kills three turns doesn't open the circuit on the fourth ask.
2313
+ let externalSignalStreak = 0;
2314
+ const countSpawnFailure = (err) => {
2315
+ const graced = isExternalSignal(err) && externalSignalStreak < EXTERNAL_SIGNAL_GRACE;
2316
+ if (isExternalSignal(err)) externalSignalStreak += 1;
2317
+ if (!graced) consecutiveSpawnFailures += 1;
2318
+ return graced;
2319
+ };
2308
2320
  let pollStalled = false;
2309
2321
  const pollLiveness = createPollLiveness({
2310
2322
  limitMs: resolvePollLivenessMs(pollLivenessMs),
@@ -3855,13 +3867,16 @@ export const performRun = ({
3855
3867
  // are just as claimed, so they ride along without a strike. `pastCap` events
3856
3868
  // were left out of a turn, which is no failure of theirs: no strike, and
3857
3869
  // PAST_CAP_MAX_CARRIES bounds them instead. A later group's hold in the same
3858
- // tick adds to the carry, never replaces it.
3859
- const holdForRetry = async (failedEvents, untriedEvents = [], pastCap = []) => {
3870
+ // tick adds to the carry, never replaces it. A turn an outside signal cut off
3871
+ // inside its grace (F293) is no failure of the event's either: `strike: false`
3872
+ // carries it without one, or the third kill would release it to the server's
3873
+ // requeue and the answer would wait 10–20 minutes. The grace bounds this.
3874
+ const holdForRetry = async (failedEvents, untriedEvents = [], pastCap = [], { strike = true } = {}) => {
3860
3875
  const released = [];
3861
3876
  let part = null;
3862
3877
  const carry = [];
3863
3878
  const seen = new Set();
3864
- for (const event of failedEvents) {
3879
+ for (const event of strike ? failedEvents : []) {
3865
3880
  const id = String(event._id);
3866
3881
  if (!seen.has(id)) {
3867
3882
  seen.add(id);
@@ -3877,7 +3892,7 @@ export const performRun = ({
3877
3892
  }
3878
3893
  }
3879
3894
  }
3880
- for (const event of untriedEvents) {
3895
+ for (const event of strike ? untriedEvents : [...failedEvents, ...untriedEvents]) {
3881
3896
  const id = String(event._id);
3882
3897
  if (!seen.has(id)) {
3883
3898
  seen.add(id);
@@ -4668,12 +4683,13 @@ export const performRun = ({
4668
4683
  // The unacked items are carried to the retry, not left to the
4669
4684
  // requeue sweep, so the delay below is when they run again.
4670
4685
  const scheduleBatchRetry = async (err, failedEvents) => {
4671
- consecutiveSpawnFailures += 1;
4686
+ const externalSignal = countSpawnFailure(err);
4672
4687
  const retry = spawnRetryPolicy({
4673
4688
  error: err,
4674
4689
  consecutiveFailures: consecutiveSpawnFailures,
4675
4690
  intervalMs,
4676
4691
  jitterRatio: spawnJitterRatio,
4692
+ externalSignal,
4677
4693
  });
4678
4694
  nextPollDelayMs = retry.delayMs;
4679
4695
  retryScheduled = true;
@@ -4687,6 +4703,7 @@ export const performRun = ({
4687
4703
  attempted,
4688
4704
  untriedAfter(groupIndex),
4689
4705
  pastCapEvents,
4706
+ { strike: !externalSignal },
4690
4707
  );
4691
4708
  keepHeldLeases(retry.delayMs);
4692
4709
  const event = group[0];
@@ -4739,6 +4756,7 @@ export const performRun = ({
4739
4756
  ));
4740
4757
  if (batchSpawned) {
4741
4758
  consecutiveSpawnFailures = 0;
4759
+ externalSignalStreak = 0;
4742
4760
  // Notices arriving mid-turn get one bounded collection window.
4743
4761
  // Idle polls and batches with no model turn keep their cadence.
4744
4762
  completedModelTurn = true;
@@ -4808,12 +4826,13 @@ export const performRun = ({
4808
4826
  // at-least-once delivery. Stop this fetched batch immediately —
4809
4827
  // continuing could launch every one of the 10 returned events
4810
4828
  // into the same provider outage before the next poll (#782).
4811
- consecutiveSpawnFailures += 1;
4829
+ const externalSignal = countSpawnFailure(err);
4812
4830
  const retry = spawnRetryPolicy({
4813
4831
  error: err,
4814
4832
  consecutiveFailures: consecutiveSpawnFailures,
4815
4833
  intervalMs,
4816
4834
  jitterRatio: spawnJitterRatio,
4835
+ externalSignal,
4817
4836
  });
4818
4837
  nextPollDelayMs = retry.delayMs;
4819
4838
  retryScheduled = true;
@@ -4825,7 +4844,7 @@ export const performRun = ({
4825
4844
  // eslint-disable-next-line no-await-in-loop
4826
4845
  if (failedTurn?.event === event) await noteFailedTurnPart([event]);
4827
4846
  // eslint-disable-next-line no-await-in-loop
4828
- const hold = await holdForRetry([event], untriedAfter(groupIndex));
4847
+ const hold = await holdForRetry([event], untriedAfter(groupIndex), [], { strike: !externalSignal });
4829
4848
  keepHeldLeases(retry.delayMs);
4830
4849
  const wrapped = new Error(
4831
4850
  `${event.type} processing failed (${retry.failureClass}; `
@@ -4882,7 +4901,10 @@ export const performRun = ({
4882
4901
  // and neither may an enforcement stand-down (cascade cap, lost
4883
4902
  // claim), which returns before any spawn happens.
4884
4903
  const stoodDown = result?.reason === 'cascade-cap' || result?.reason === 'claim-held';
4885
- if (eventWillSpawn && !stoodDown) consecutiveSpawnFailures = 0;
4904
+ if (eventWillSpawn && !stoodDown) {
4905
+ consecutiveSpawnFailures = 0;
4906
+ externalSignalStreak = 0;
4907
+ }
4886
4908
  // Record after successful processing but before ack. If the ack
4887
4909
  // fails, the next delivery is skipped and re-acked instead of
4888
4910
  // burning a second model turn for work that already completed.
@@ -1015,7 +1015,7 @@ const runClaude = ({
1015
1015
  watchdog.stop();
1016
1016
  reject(err);
1017
1017
  });
1018
- proc.on('close', (code) => {
1018
+ proc.on('close', (code, signal) => {
1019
1019
  clearTimeout(timer);
1020
1020
  clearTimeout(stallKill);
1021
1021
  watchdog.stop();
@@ -1046,6 +1046,7 @@ const runClaude = ({
1046
1046
  credentials,
1047
1047
  exitCode: code,
1048
1048
  limit: 2000,
1049
+ signal,
1049
1050
  }));
1050
1051
  }
1051
1052
  resolve(stdout);
@@ -1451,7 +1451,7 @@ const runCodex = ({
1451
1451
  clearTimeout(timer);
1452
1452
  reject(err);
1453
1453
  });
1454
- proc.on('close', (code) => {
1454
+ proc.on('close', (code, signal) => {
1455
1455
  clearTimeout(timer);
1456
1456
  const reaped = describeTurnReap(turn.reap(proc));
1457
1457
  // eslint-disable-next-line no-console
@@ -1472,7 +1472,9 @@ const runCodex = ({
1472
1472
  }));
1473
1473
  }
1474
1474
  if (code !== 0) {
1475
- return reject(adapterFailure('codex', stderr.trim(), { credentials, exitCode: code, limit: 500 }));
1475
+ return reject(adapterFailure('codex', stderr.trim(), {
1476
+ credentials, exitCode: code, limit: 500, signal,
1477
+ }));
1476
1478
  }
1477
1479
  resolve({ threadId: events.threadId, turnCompleted: events.turnCompleted });
1478
1480
  });
@@ -354,6 +354,7 @@ export const runDsh = ({
354
354
  let stderr = '';
355
355
  let timedOut = false;
356
356
  let parseFailure = null;
357
+ let ownKill = false;
357
358
  let settled = false;
358
359
  let killTimer;
359
360
  const finish = (error, result) => {
@@ -372,6 +373,7 @@ export const runDsh = ({
372
373
  state.buffer += chunk.toString();
373
374
  if (state.buffer.length > 1024 * 1024) {
374
375
  parseFailure = new Error('dsh event exceeded 1 MiB');
376
+ ownKill = true;
375
377
  proc.kill('SIGTERM');
376
378
  return;
377
379
  }
@@ -380,21 +382,30 @@ export const runDsh = ({
380
382
  const line = state.buffer.slice(0, end).trim();
381
383
  state.buffer = state.buffer.slice(end + 1);
382
384
  if (line && !parseFailure) {
383
- try { parseEvent(line, state); } catch (error) { parseFailure = error; proc.kill('SIGTERM'); }
385
+ try { parseEvent(line, state); } catch (error) { parseFailure = error; ownKill = true; proc.kill('SIGTERM'); }
384
386
  }
385
387
  }
386
388
  });
387
389
  proc.stderr?.on('data', (chunk) => { stderr = (stderr + chunk.toString()).slice(-8192); });
388
390
  proc.on('error', (error) => finish(error));
389
- proc.on('close', (code) => {
391
+ proc.on('close', (code, signal) => {
390
392
  if (state.buffer.trim() && !parseFailure) {
391
393
  try { parseEvent(state.buffer.trim(), state); } catch (error) { parseFailure = error; }
392
394
  }
395
+ const sandboxDown = /SANDBOX_UNAVAILABLE|sandbox_apply: Operation not permitted/.test(stderr);
393
396
  const failure = parseFailure?.message || state.error || (timedOut ? `timeout after ${timeoutMs}ms` : null)
394
- || (/SANDBOX_UNAVAILABLE|sandbox_apply: Operation not permitted/.test(stderr) ? 'sandbox runner unavailable' : null)
397
+ || (sandboxDown ? 'sandbox runner unavailable' : null)
395
398
  || (code !== 0 ? stderr.trim() || `exit ${code}` : null)
396
399
  || (state.final === null ? 'no final event' : null);
397
- if (failure) return finish(adapterFailure('dsh', failure, { credentials, exitCode: code, limit: 500 }));
400
+ // A parse failure mid-stream and a timeout are this adapter's own SIGTERM,
401
+ // and a stream error names its cause: only a bare cut-off came from outside.
402
+ // A trailing event that won't parse at close is a write the signal cut short.
403
+ const ownCause = Boolean(ownKill || state.error || timedOut || sandboxDown);
404
+ if (failure) {
405
+ return finish(adapterFailure('dsh', failure, {
406
+ credentials, exitCode: code, limit: 500, ...(ownCause ? {} : { signal }),
407
+ }));
408
+ }
398
409
  return finish(null, { text: state.final.trim(), newSessionId: state.sessionId, contextTokens: state.contextTokens });
399
410
  });
400
411
  });
@@ -306,7 +306,7 @@ const runGoose = ({
306
306
  stderr = (stderr + received).slice(-8192);
307
307
  });
308
308
  child.on('error', (error) => finish(error));
309
- child.on('close', (code) => {
309
+ child.on('close', (code, signal) => {
310
310
  stdout += stdoutDecoder.end();
311
311
  if (timedOut) return finish(new Error(`goose adapter: timed out after ${timeoutMs}ms`));
312
312
  if (streamOverflow) return finish(new Error('goose adapter: stream exceeded 2 MiB'));
@@ -315,8 +315,10 @@ const runGoose = ({
315
315
  // lets the model answer without that tool. A Commonly seat cannot silently
316
316
  // lose its only path back to the pod.
317
317
  if (code !== 0 || result.error || !result.complete || extensionFailure) {
318
+ // Only a bare cut-off: an extension or stream error keeps its own class.
319
+ const ownCause = Boolean(extensionFailure || result.error);
318
320
  return finish(adapterFailure('goose', extensionFailure || result.error || stderr.trim() || `exit ${code}; incomplete stream`, {
319
- credentials, exitCode: code, limit: 500,
321
+ credentials, exitCode: code, limit: 500, ...(ownCause ? {} : { signal }),
320
322
  }));
321
323
  }
322
324
  return finish(null, result.text);
@@ -1,4 +1,6 @@
1
1
  import { observeSpawn, controlsFromArguments } from '../runtime-observation.js';
2
+ import { descendantsOf, killProcessTree, readProcessTable } from '@commonlyai/seats/process-group';
3
+ import { killStallSurvivors } from '../first-output-watchdog.js';
2
4
  /**
3
5
  * OpenCode adapter — wraps `opencode run --format json` as a Commonly seat.
4
6
  *
@@ -1028,6 +1030,7 @@ const publicToolFailedError = ({ tool, error }) => {
1028
1030
 
1029
1031
  const runOpenCode = ({
1030
1032
  cmd, args, cwd, env, timeoutMs, credentials, spawnImpl = childSpawn, onSpawn, controls = {}, onFirstStep,
1033
+ terminationGraceMs = TERMINATION_GRACE_MS,
1031
1034
  }) => new Promise((resolve, reject) => {
1032
1035
  let proc;
1033
1036
  try {
@@ -1041,10 +1044,26 @@ const runOpenCode = ({
1041
1044
  let timedOut = false;
1042
1045
  let killTimer = null;
1043
1046
  const events = makeEventParser();
1047
+ // A timed-out turn is killed as a tree (F257): a child of OpenCode (a
1048
+ // launcher's real binary, an MCP server) that ignores SIGTERM would keep the
1049
+ // turn's stdout open, so close never fired and the turn never settled. The
1050
+ // descendants are snapshotted at SIGTERM, because one whose parent exits is
1051
+ // reparented and no tree walk from the spawn finds it again; any still alive
1052
+ // is SIGKILLed on close and at the grace (as claude.js does). At the grace,
1053
+ // dropping our ends of the pipes bounds the turn even if a holder was missed.
1054
+ let survivors = [];
1055
+ const sweepSurvivors = () => { if (survivors.length) killStallSurvivors(survivors); };
1044
1056
  const timer = setTimeout(() => {
1045
1057
  timedOut = true;
1046
- proc.kill('SIGTERM');
1047
- killTimer = setTimeout(() => proc.kill('SIGKILL'), TERMINATION_GRACE_MS);
1058
+ const table = Number.isInteger(proc.pid) ? readProcessTable() : null;
1059
+ if (table) survivors = descendantsOf(table, proc.pid);
1060
+ killProcessTree(proc, 'SIGTERM', { table: () => table });
1061
+ killTimer = setTimeout(() => {
1062
+ killProcessTree(proc, 'SIGKILL');
1063
+ sweepSurvivors();
1064
+ proc.stdout?.destroy?.();
1065
+ proc.stderr?.destroy?.();
1066
+ }, terminationGraceMs);
1048
1067
  }, timeoutMs);
1049
1068
  const clearTimers = () => {
1050
1069
  clearTimeout(timer);
@@ -1073,8 +1092,9 @@ const runOpenCode = ({
1073
1092
  clearTimers();
1074
1093
  reject(err);
1075
1094
  });
1076
- proc.on('close', (code) => {
1095
+ proc.on('close', (code, signal) => {
1077
1096
  clearTimers();
1097
+ if (timedOut) sweepSurvivors();
1078
1098
  events.flush();
1079
1099
  if (stepHookError) return reject(stepHookError);
1080
1100
  if (timedOut) return reject(new Error(`opencode timed out after ${timeoutMs}ms`));
@@ -1086,8 +1106,10 @@ const runOpenCode = ({
1086
1106
  return reject(err);
1087
1107
  }
1088
1108
  if (code !== 0) {
1089
- const err = adapterFailure('opencode', stderr.trim(), {
1090
- credentials, exitCode: code, limit: 500,
1109
+ // A signal exit has no code, so without its name a quiet death read as
1110
+ // just "opencode" (F257).
1111
+ const err = adapterFailure(code === null && signal ? `opencode ended on ${signal}` : 'opencode', stderr.trim(), {
1112
+ credentials, exitCode: code, limit: 500, signal,
1091
1113
  });
1092
1114
  err.staleSession = !events.turnOutput && STALE_SESSION_PATTERN.test(stderr);
1093
1115
  return reject(err);
@@ -1619,6 +1641,7 @@ export default {
1619
1641
  cwd: ctx.cwd,
1620
1642
  env: childEnv,
1621
1643
  timeoutMs: ctx.timeoutMs || DEFAULT_TIMEOUT_MS,
1644
+ ...(ctx._terminationGraceMs ? { terminationGraceMs: ctx._terminationGraceMs } : {}),
1622
1645
  credentials,
1623
1646
  spawnImpl, onSpawn: ctx.onSpawn, controls: controlsFromArguments(args.slice(0, -1), { modelFlag: '-m', effortFlag: '--variant', valueFlags: ['-s', '--dir', '--title', '--format'] }),
1624
1647
  // CodeRabbit #3487, F460: a public seat's credential stops existing
@@ -59,6 +59,8 @@ import { fileURLToPath } from 'url';
59
59
  import {
60
60
  adapterFailure,
61
61
  describeUpstreamRefusal,
62
+ markExternalSignal,
63
+ namesFailureCause,
62
64
  readUpstreamRefusal,
63
65
  spawnCredentials,
64
66
  } from '../upstream-refusal.js';
@@ -590,7 +592,7 @@ export const extractReply = (stdout) => {
590
592
 
591
593
  // A turn that printed an interim message and then ended without finishing. A
592
594
  // crash keeps its cause, so a quota line in stderr or a refusal on the stream
593
- // still classifies. A signal (143, 129, or a null code) has neither: stderr then
595
+ // still classifies. A signal (143, 129, 130, or a null code) has neither: stderr then
594
596
  // holds pi's startup warnings, and a refusal on the stream may be one pi was
595
597
  // recovering from, like an overflow's 400. A clean exit that ended on an error
596
598
  // has only the stream: its stderr is those warnings too, and the refusal stands.
@@ -601,7 +603,7 @@ export const extractReply = (stdout) => {
601
603
  const stoppedTurnFailure = (reply, {
602
604
  code, signal, stderr, credentials,
603
605
  }) => {
604
- const killed = Boolean(signal) || code === 143 || code === 129;
606
+ const killed = Boolean(signal) || code === 143 || code === 129 || code === 130;
605
607
  const cleanExit = code === 0;
606
608
  const upstream = killed ? null : reply.upstream;
607
609
  const failure = adapterFailure(
@@ -616,7 +618,12 @@ const stoppedTurnFailure = (reply, {
616
618
  );
617
619
  if (upstream && cleanExit) failure.status = upstream.status;
618
620
  else if (upstream) failure.status ??= upstream.status;
619
- return failure;
621
+ // A cut-off with no error on the stream came from outside (F293): the
622
+ // timeout and a hook's kill return before this is built.
623
+ // The text above drops stderr on a kill, so a status stderr named is read here.
624
+ const ownCause = reply.errors.length || failure.status !== undefined || failure.providerCode !== undefined
625
+ || namesFailureCause(stderr, { credentials });
626
+ return ownCause ? failure : markExternalSignal(failure, { code, signal });
620
627
  };
621
628
 
622
629
  /**
@@ -710,7 +717,10 @@ const runPi = ({
710
717
  }));
711
718
  }
712
719
  const tail = (reply.errors.join(' | ') || stderr).trim().slice(-600);
713
- return reject(new Error(`pi exited ${code}: ${tail}`));
720
+ const exited = new Error(`pi exited ${code}: ${tail}`);
721
+ // A status stderr named (a 429, say) is a cause too, so it keeps its class.
722
+ const ownCause = reply.errors.length || namesFailureCause(tail, { credentials });
723
+ return reject(ownCause ? exited : markExternalSignal(exited, { code, signal }));
714
724
  }
715
725
  // A refused turn exits 0 too, so here the stream is what says the text was
716
726
  // interim. Posting it would answer with half a turn (F258). The last stop
@@ -288,12 +288,12 @@ const runQwen = ({ cmd, args, cwd, env, timeoutMs, spawnImpl, credentials }) =>
288
288
  });
289
289
  child.stderr?.on('data', (chunk) => { stderr = (stderr + chunk.toString()).slice(-8192); });
290
290
  child.on('error', (error) => finish(error));
291
- child.on('close', (code) => {
291
+ child.on('close', (code, signal) => {
292
292
  if (state.buffer) parseStream(state.buffer, state);
293
293
  if (timedOut) return finish(new Error(`qwen timed out after ${timeoutMs}ms`));
294
294
  if (code !== 0 || state.error) {
295
295
  return finish(adapterFailure('qwen', state.error || stderr.trim() || `exit ${code}`, {
296
- credentials, exitCode: code, limit: 500,
296
+ credentials, exitCode: code, limit: 500, ...(state.error ? {} : { signal }),
297
297
  }));
298
298
  }
299
299
  return finish(null, { text: state.text.trim() });
@@ -24,8 +24,21 @@ export const SPAWN_FAILURE_CLASS = Object.freeze({
24
24
  // first-output window (lib/first-output-watchdog.js). A host condition such as
25
25
  // a locked console, so the circuit opens at once and the probe waits.
26
26
  STALLED: 'stalled',
27
+ // F293: the child closed on a signal from outside the wrapper (a person, a
28
+ // supervisor, a walk). The provider never refused anything, so the retry
29
+ // comes at the normal poll interval and the circuit stays shut.
30
+ SIGNALED: 'signaled',
27
31
  });
28
32
 
33
+ // How many outside signals in a row go uncounted before they count again. A
34
+ // walk that cuts three turns short is a walk; a child killed on every spawn is
35
+ // a fault, and after this many the usual schedule backs the seat off.
36
+ export const EXTERNAL_SIGNAL_GRACE = 3;
37
+
38
+ // Set by the adapter (`markExternalSignal`), only on a failure with no cause of
39
+ // its own: a stream's error or the adapter's own kill never carries it.
40
+ export const isExternalSignal = (error) => error?.externalSignal === true;
41
+
29
42
  // A stalled probe costs one first-output window, so the wait starts short and
30
43
  // doubles to the usual ceiling: 2, 4, 8, then 15 minutes.
31
44
  export const SPAWN_STALL_RETRY_BASE_MS = 2 * 60 * 1000;
@@ -228,9 +241,18 @@ export const spawnRetryPolicy = ({
228
241
  consecutiveFailures,
229
242
  intervalMs,
230
243
  jitterRatio = 0,
244
+ // The run loop's call: an outside signal still inside its grace (F293).
245
+ externalSignal = false,
231
246
  }) => {
232
- const failureClass = classifySpawnFailure(error);
233
247
  const safeIntervalMs = Number.isFinite(intervalMs) && intervalMs > 0 ? intervalMs : 5000;
248
+ if (externalSignal) {
249
+ return {
250
+ failureClass: SPAWN_FAILURE_CLASS.SIGNALED,
251
+ circuitOpen: false,
252
+ delayMs: applyJitter(safeIntervalMs, jitterRatio),
253
+ };
254
+ }
255
+ const failureClass = classifySpawnFailure(error);
234
256
  const failureCount = Number.isInteger(consecutiveFailures) && consecutiveFailures > 0
235
257
  ? consecutiveFailures
236
258
  : 1;