@commonlyai/cli 0.1.361 → 0.1.363

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.361",
3
+ "version": "0.1.363",
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';
@@ -1020,6 +1022,13 @@ const PAST_CAP_MAX_CARRIES = 5;
1020
1022
  // is unchanged, and the can't-answer limit (once per cause per pod per hour)
1021
1023
  // still decides who hears it.
1022
1024
  const CIRCUIT_NOTICE_CHECK_MS = 60 * 1000;
1025
+ // F237: failed turns in a row after which a full carry stops claiming new rows.
1026
+ // One failure keeps the claim, so a person's new message still joins the retry
1027
+ // ahead of carried agent rows; past it the outage looks real, and every row
1028
+ // claimed then rides the carry past the prompt cap, is released after
1029
+ // PAST_CAP_MAX_CARRIES failed turns and claimed again, an attempt each time,
1030
+ // until the requeue cap retires it without its ever being tried.
1031
+ const FULL_CARRY_CLAIM_FAILURES = 2;
1023
1032
 
1024
1033
  // Who gets a slot when a batch is past the cap. 'unknown' counts as a person:
1025
1034
  // only a row the snapshot and the kernel's stamp both can't place reads so, and
@@ -2305,6 +2314,16 @@ export const performRun = ({
2305
2314
  const MAX_AUTH_ERRORS = 3;
2306
2315
  let consecutivePollFailures = 0;
2307
2316
  let consecutiveSpawnFailures = 0;
2317
+ // F293: turns cut off by an outside signal since the last good spawn. The
2318
+ // first EXTERNAL_SIGNAL_GRACE of them retry without counting as failures, so
2319
+ // a walk that kills three turns doesn't open the circuit on the fourth ask.
2320
+ let externalSignalStreak = 0;
2321
+ const countSpawnFailure = (err) => {
2322
+ const graced = isExternalSignal(err) && externalSignalStreak < EXTERNAL_SIGNAL_GRACE;
2323
+ if (isExternalSignal(err)) externalSignalStreak += 1;
2324
+ if (!graced) consecutiveSpawnFailures += 1;
2325
+ return graced;
2326
+ };
2308
2327
  let pollStalled = false;
2309
2328
  const pollLiveness = createPollLiveness({
2310
2329
  limitMs: resolvePollLivenessMs(pollLivenessMs),
@@ -3849,19 +3868,41 @@ export const performRun = ({
3849
3868
  confirmed === null || !deliveryIdOf(event) || confirmed.has(String(event._id))
3850
3869
  );
3851
3870
 
3871
+ // What an inbox read asks for. A carry that fills the prompt during an
3872
+ // outage names its rows (`onlyIds`), and a current server returns only those
3873
+ // it requeued, with their live delivery ids, and claims nothing new (F237).
3874
+ // `limit` keeps today's value, so a server that predates onlyIds claims as
3875
+ // before. `inOutage`: the circuit-wait check, which runs only while the
3876
+ // circuit is open.
3877
+ const inboxQuery = ({ inOutage = false } = {}) => {
3878
+ const carried = [...heldRetry, ...heldGreeting];
3879
+ const carriedCount = carried.filter((event) => event.deliveryMode !== 'digest').length;
3880
+ const full = carriedCount >= batchLimit
3881
+ && (inOutage || consecutiveSpawnFailures >= FULL_CARRY_CLAIM_FAILURES);
3882
+ return {
3883
+ agentName,
3884
+ instanceId,
3885
+ limit: Math.max(1, batchLimit - carriedCount),
3886
+ ...(full ? { onlyIds: [...new Set(carried.map((event) => String(event._id)))].join(',') } : {}),
3887
+ ...(adapter?.name ? { reportedCli: adapter.name } : {}),
3888
+ };
3889
+ };
3852
3890
  // Decide what a failed turn's retry carries. `failedEvents` were attempted
3853
3891
  // and count toward HELD_RETRY_MAX_FAILURES; `untriedEvents` are later groups
3854
3892
  // from the same page that the failure stopped before they ran (#782), and
3855
3893
  // are just as claimed, so they ride along without a strike. `pastCap` events
3856
3894
  // were left out of a turn, which is no failure of theirs: no strike, and
3857
3895
  // 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 = []) => {
3896
+ // tick adds to the carry, never replaces it. A turn an outside signal cut off
3897
+ // inside its grace (F293) is no failure of the event's either: `strike: false`
3898
+ // carries it without one, or the third kill would release it to the server's
3899
+ // requeue and the answer would wait 10–20 minutes. The grace bounds this.
3900
+ const holdForRetry = async (failedEvents, untriedEvents = [], pastCap = [], { strike = true } = {}) => {
3860
3901
  const released = [];
3861
3902
  let part = null;
3862
3903
  const carry = [];
3863
3904
  const seen = new Set();
3864
- for (const event of failedEvents) {
3905
+ for (const event of strike ? failedEvents : []) {
3865
3906
  const id = String(event._id);
3866
3907
  if (!seen.has(id)) {
3867
3908
  seen.add(id);
@@ -3877,7 +3918,7 @@ export const performRun = ({
3877
3918
  }
3878
3919
  }
3879
3920
  }
3880
- for (const event of untriedEvents) {
3921
+ for (const event of strike ? untriedEvents : [...failedEvents, ...untriedEvents]) {
3881
3922
  const id = String(event._id);
3882
3923
  if (!seen.has(id)) {
3883
3924
  seen.add(id);
@@ -4518,12 +4559,8 @@ export const performRun = ({
4518
4559
  // #3511). The overflow pass below stays as the backstop.
4519
4560
  // Only wake events count: the server's page cap is on wakes, and a
4520
4561
  // carried digest row takes no body (CodeRabbit on #3511).
4521
- const carriedCount = [...heldRetry, ...heldGreeting]
4522
- .filter((event) => event.deliveryMode !== 'digest').length;
4523
- const page = await client.get('/api/agents/runtime/events', {
4524
- agentName, instanceId, limit: Math.max(1, batchLimit - carriedCount),
4525
- ...(adapter?.name ? { reportedCli: adapter.name } : {}),
4526
- });
4562
+ // F237: a full carry in an outage claims nothing new (inboxQuery).
4563
+ const page = await client.get('/api/agents/runtime/events', inboxQuery());
4527
4564
  pollLiveness.arm();
4528
4565
  // A stall fired while this request hung: the loop has already given up on
4529
4566
  // it, and `agent run` exits in onStall, so its page is left to the requeue.
@@ -4668,12 +4705,13 @@ export const performRun = ({
4668
4705
  // The unacked items are carried to the retry, not left to the
4669
4706
  // requeue sweep, so the delay below is when they run again.
4670
4707
  const scheduleBatchRetry = async (err, failedEvents) => {
4671
- consecutiveSpawnFailures += 1;
4708
+ const externalSignal = countSpawnFailure(err);
4672
4709
  const retry = spawnRetryPolicy({
4673
4710
  error: err,
4674
4711
  consecutiveFailures: consecutiveSpawnFailures,
4675
4712
  intervalMs,
4676
4713
  jitterRatio: spawnJitterRatio,
4714
+ externalSignal,
4677
4715
  });
4678
4716
  nextPollDelayMs = retry.delayMs;
4679
4717
  retryScheduled = true;
@@ -4687,6 +4725,7 @@ export const performRun = ({
4687
4725
  attempted,
4688
4726
  untriedAfter(groupIndex),
4689
4727
  pastCapEvents,
4728
+ { strike: !externalSignal },
4690
4729
  );
4691
4730
  keepHeldLeases(retry.delayMs);
4692
4731
  const event = group[0];
@@ -4739,6 +4778,7 @@ export const performRun = ({
4739
4778
  ));
4740
4779
  if (batchSpawned) {
4741
4780
  consecutiveSpawnFailures = 0;
4781
+ externalSignalStreak = 0;
4742
4782
  // Notices arriving mid-turn get one bounded collection window.
4743
4783
  // Idle polls and batches with no model turn keep their cadence.
4744
4784
  completedModelTurn = true;
@@ -4808,12 +4848,13 @@ export const performRun = ({
4808
4848
  // at-least-once delivery. Stop this fetched batch immediately —
4809
4849
  // continuing could launch every one of the 10 returned events
4810
4850
  // into the same provider outage before the next poll (#782).
4811
- consecutiveSpawnFailures += 1;
4851
+ const externalSignal = countSpawnFailure(err);
4812
4852
  const retry = spawnRetryPolicy({
4813
4853
  error: err,
4814
4854
  consecutiveFailures: consecutiveSpawnFailures,
4815
4855
  intervalMs,
4816
4856
  jitterRatio: spawnJitterRatio,
4857
+ externalSignal,
4817
4858
  });
4818
4859
  nextPollDelayMs = retry.delayMs;
4819
4860
  retryScheduled = true;
@@ -4825,7 +4866,7 @@ export const performRun = ({
4825
4866
  // eslint-disable-next-line no-await-in-loop
4826
4867
  if (failedTurn?.event === event) await noteFailedTurnPart([event]);
4827
4868
  // eslint-disable-next-line no-await-in-loop
4828
- const hold = await holdForRetry([event], untriedAfter(groupIndex));
4869
+ const hold = await holdForRetry([event], untriedAfter(groupIndex), [], { strike: !externalSignal });
4829
4870
  keepHeldLeases(retry.delayMs);
4830
4871
  const wrapped = new Error(
4831
4872
  `${event.type} processing failed (${retry.failureClass}; `
@@ -4882,7 +4923,10 @@ export const performRun = ({
4882
4923
  // and neither may an enforcement stand-down (cascade cap, lost
4883
4924
  // claim), which returns before any spawn happens.
4884
4925
  const stoodDown = result?.reason === 'cascade-cap' || result?.reason === 'claim-held';
4885
- if (eventWillSpawn && !stoodDown) consecutiveSpawnFailures = 0;
4926
+ if (eventWillSpawn && !stoodDown) {
4927
+ consecutiveSpawnFailures = 0;
4928
+ externalSignalStreak = 0;
4929
+ }
4886
4930
  // Record after successful processing but before ack. If the ack
4887
4931
  // fails, the next delivery is skipped and re-acked instead of
4888
4932
  // burning a second model turn for work that already completed.
@@ -4968,12 +5012,9 @@ export const performRun = ({
4968
5012
  const wait = circuitNotice;
4969
5013
  try {
4970
5014
  pollLiveness.arm();
4971
- const carriedCount = [...heldRetry, ...heldGreeting]
4972
- .filter((event) => event.deliveryMode !== 'digest').length;
4973
- const page = await client.get('/api/agents/runtime/events', {
4974
- agentName, instanceId, limit: Math.max(1, batchLimit - carriedCount),
4975
- ...(adapter?.name ? { reportedCli: adapter.name } : {}),
4976
- });
5015
+ // A full carry here claims nothing new (F237): a pod whose first message
5016
+ // arrives then is told once the carry has room, not by this check.
5017
+ const page = await client.get('/api/agents/runtime/events', inboxQuery({ inOutage: true }));
4977
5018
  pollLiveness.arm();
4978
5019
  if (pollStalled) return;
4979
5020
  const fetched = page?.events || [];
@@ -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);
@@ -1109,7 +1109,7 @@ const runOpenCode = ({
1109
1109
  // A signal exit has no code, so without its name a quiet death read as
1110
1110
  // just "opencode" (F257).
1111
1111
  const err = adapterFailure(code === null && signal ? `opencode ended on ${signal}` : 'opencode', stderr.trim(), {
1112
- credentials, exitCode: code, limit: 500,
1112
+ credentials, exitCode: code, limit: 500, signal,
1113
1113
  });
1114
1114
  err.staleSession = !events.turnOutput && STALE_SESSION_PATTERN.test(stderr);
1115
1115
  return reject(err);
@@ -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;