@shumkov/orchestra 0.11.1 → 0.11.3
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,118 @@
|
|
|
1
|
+
# CLI turns that end in an API error (StopFailure)
|
|
2
|
+
|
|
3
|
+
Orchestra half of Polygram's `docs/0.41-cli-api-error-surfacing-spec.md`,
|
|
4
|
+
which holds the full evidence, the alternatives, and the review record.
|
|
5
|
+
|
|
6
|
+
## Problem
|
|
7
|
+
|
|
8
|
+
When a model request keeps failing, claude 2.1.283 retries it (about three
|
|
9
|
+
minutes by default), writes a synthetic assistant entry
|
|
10
|
+
(`isApiErrorMessage: true`, e.g. `error: "server_error"`), and ends the query
|
|
11
|
+
**without Stop**. It fires the documented `StopFailure` hook instead, but only
|
|
12
|
+
when one is registered. `CliProcess` registered none, so the turn had no end
|
|
13
|
+
signal. It stayed pending until the 30-minute checkpoint, and follow-ups were
|
|
14
|
+
autosteered into it. Production: VPS shumabit, 2026-11-04/05, with CLIProxy's
|
|
15
|
+
Claude credentials expired.
|
|
16
|
+
|
|
17
|
+
## Pinned-CLI facts this relies on
|
|
18
|
+
|
|
19
|
+
Verified on 2.1.283 by binary reading and a real-CLI run against a local
|
|
20
|
+
HTTP-500 stub (Polygram `scripts/spikes/cli-api-error-stub.mjs`).
|
|
21
|
+
Re-check them on every pin bump.
|
|
22
|
+
|
|
23
|
+
- `StopFailure` payload: the common fields plus `error` (enum),
|
|
24
|
+
`error_details`, and `last_assistant_message`. The last field is the
|
|
25
|
+
rendered error, including the gateway host. The hook is fire-and-forget.
|
|
26
|
+
- `prompt_id` identifies the query. The turn's UserPromptSubmit, a folded
|
|
27
|
+
follow-up's extra UserPromptSubmit, its tool hooks, and its final
|
|
28
|
+
Stop/StopFailure all share it. A queued prompt that runs as its own cycle
|
|
29
|
+
gets a new one.
|
|
30
|
+
- Several messages queued while a query runs each fire their own
|
|
31
|
+
UserPromptSubmit, with their own `prompt_id`, when that query ends. Claude
|
|
32
|
+
then runs them as **one** query, and its Stop or StopFailure carries only
|
|
33
|
+
the **last** `prompt_id`. Seen with two and three follow-ups queued during
|
|
34
|
+
the retry window, both when the merged query failed and when it succeeded.
|
|
35
|
+
Their UserPromptSubmit lines arrived in message order, 35–200 ms apart,
|
|
36
|
+
consistent with claude waiting for each UserPromptSubmit hook in turn.
|
|
37
|
+
- A sub-agent whose request fails fires `StopFailure` with `agent_id` and the
|
|
38
|
+
parent's `prompt_id`, and **no SubagentStop**. The main thread carries no
|
|
39
|
+
`agent_id`, even under `--agent`.
|
|
40
|
+
- No StopFailure fires when a retry recovers, or when the user sends C-c
|
|
41
|
+
during the retries.
|
|
42
|
+
- The org-disabled notice that the pane `AUTH_DISABLED` detector matches is
|
|
43
|
+
the content of `error: "oauth_org_not_allowed"`.
|
|
44
|
+
|
|
45
|
+
## Behaviour
|
|
46
|
+
|
|
47
|
+
- `StopFailure` is registered and parsed. `apiError` is clamped to the enum
|
|
48
|
+
(otherwise `'unknown'`), and `promptId` is normalized on every event.
|
|
49
|
+
- A sub-agent StopFailure is handled as that sub-agent's SubagentStop.
|
|
50
|
+
- A main-thread StopFailure is terminal (not activity). It never enters the
|
|
51
|
+
Stop or workflow-completion machinery, which would deliver
|
|
52
|
+
`last_assistant_message` as the answer.
|
|
53
|
+
- **Attribution is by `prompt_id` only.** A pending records the `prompt_id`
|
|
54
|
+
of the UserPromptSubmit that first marked it seen.
|
|
55
|
+
- Without a `prompt_id`, the event is logged and nothing settles; the
|
|
56
|
+
ceilings remain the backstop.
|
|
57
|
+
- A turn that was in flight at the last C-c is left to the interrupt
|
|
58
|
+
resolution. A turn started after the C-c settles normally.
|
|
59
|
+
- **A matched turn**:
|
|
60
|
+
- waits while a reply is still being delivered; the API error then
|
|
61
|
+
outranks any finalize or timeout queued meanwhile;
|
|
62
|
+
- resolves as answered if it already delivered a final reply;
|
|
63
|
+
- otherwise rejects at once: `CLAUDE_API_ERROR` with `err.apiError`, and a
|
|
64
|
+
message free of the class and the provider text. For
|
|
65
|
+
`oauth_org_not_allowed` it rejects with the existing `AUTH_DISABLED`
|
|
66
|
+
error.
|
|
67
|
+
- The rejection happens before `idle` is emitted, so a throwing listener
|
|
68
|
+
cannot strand the turn after its ceilings were cleared.
|
|
69
|
+
- **Open prompts.** Every prompt is remembered from its UserPromptSubmit
|
|
70
|
+
until its query ends, in submission order. The map is bounded like the
|
|
71
|
+
input ledger (64), and an eviction is logged.
|
|
72
|
+
- A prompt a pending turn runs in belongs to that turn, and the turn's
|
|
73
|
+
settlement answers it. That includes a pending turn folded into a prompt
|
|
74
|
+
that started as claude's own cycle: the follow-ups the prompt held are
|
|
75
|
+
dropped.
|
|
76
|
+
- Any other follow-up a prompt picks up (in claude's own cycle, or folded
|
|
77
|
+
into a turn's query after that turn settled) is kept, except ones the
|
|
78
|
+
user cancelled with /stop.
|
|
79
|
+
- A delivered final reply clears the follow-ups of its prompt and every
|
|
80
|
+
older open prompt (claude answers a merged query as a whole), whether it
|
|
81
|
+
is bound to a follow-up or to a pending turn. A reply is recorded before
|
|
82
|
+
claude's reply tool returns, so the next query's prompts are not open
|
|
83
|
+
yet.
|
|
84
|
+
- A C-c (`interrupt()`) closes every open prompt: it ends the query with no
|
|
85
|
+
hook.
|
|
86
|
+
- **The end of prompt P closes P and every older open prompt**, because
|
|
87
|
+
claude runs queued prompts as one query ended under the last `prompt_id`.
|
|
88
|
+
- Stop closes them silently.
|
|
89
|
+
- StopFailure settles every pending turn whose prompt is P or one it
|
|
90
|
+
closed (as above). If a closed prompt still holds follow-ups, or belongs
|
|
91
|
+
to no turn, it emits `api-error { apiError, anchorMsgIds, sessionId,
|
|
92
|
+
backend }` once (`onApiError`), with every follow-up message still
|
|
93
|
+
waiting, oldest first (empty for a wakeup).
|
|
94
|
+
- A late StopFailure whose prompt is no longer open still settles a
|
|
95
|
+
pending turn that ran in it, but closes nothing else. One that matches no
|
|
96
|
+
pending turn and closes no prompt of claude's own is only logged.
|
|
97
|
+
- Known limit: a StopFailure line read after a later query's Stop (the
|
|
98
|
+
StopFailure hook does not block claude; the later query would have to
|
|
99
|
+
finish before its helper writes) is closed silently by that Stop, so its
|
|
100
|
+
follow-ups get no notice. A bridge disconnect drops the process, so prompts
|
|
101
|
+
left open by an ignored StopFailure are never swept into a later query.
|
|
102
|
+
- A turn that rejects (API error, or an idle or absolute ceiling) arms the
|
|
103
|
+
drop-confirm sweep, as any cycle end does, so a follow-up claude never
|
|
104
|
+
picks up is handed back once instead of staying unaccounted. A hard-max
|
|
105
|
+
cut does not: claude is still working and still holds its queued
|
|
106
|
+
follow-ups, so a resend would answer them twice.
|
|
107
|
+
- Nothing is retried or re-sent, and no session is restarted.
|
|
108
|
+
|
|
109
|
+
## Telemetry
|
|
110
|
+
|
|
111
|
+
| Event | Fields |
|
|
112
|
+
|---|---|
|
|
113
|
+
| `cli-turn-api-error` | `turn_id`, `api_error_code`, `api_error_unlisted`, `delivered` / `deferred`, `reply_count`, `duration_ms` |
|
|
114
|
+
| `cli-stop-failure-unattributed` | `reason` (`no-prompt-id`, `own-cycle`, `no-matching-pending`), `api_error_code`, `api_error_unlisted`, `pending_count`, `closed_prompt_count`, `anchor_msg_ids` |
|
|
115
|
+
| `cli-stop-failure-ignored` | `reason` (`closed`, `bridge-disconnecting`), `api_error_code` |
|
|
116
|
+
| `cli-stop-failure-subagent` | `agent_id`, `api_error_code` |
|
|
117
|
+
| `cli-stop-failure-during-interrupt` | `turn_id`, `api_error_code` |
|
|
118
|
+
| `cli-auth-disabled-detected` | `source: 'stop-failure'` |
|
|
@@ -126,6 +126,12 @@ const DEFAULT_QUEUE_CAP = 50; // Parity P2: match SDK/tmux pendin
|
|
|
126
126
|
// ends the turn. This is only an anti-runaway bound.
|
|
127
127
|
const STREAM_CALLS_PER_TURN_CAP = 200;
|
|
128
128
|
|
|
129
|
+
// How many prompts whose query has not ended are remembered. Every Stop or
|
|
130
|
+
// StopFailure closes its prompt and all older ones, and a C-c closes them all,
|
|
131
|
+
// but every message queued during a long retry window opens one at once (a
|
|
132
|
+
// busy group chat), so the bound matches the input ledger's.
|
|
133
|
+
const OPEN_PROMPT_CAP = INPUT_LEDGER_CAP;
|
|
134
|
+
|
|
129
135
|
function validateSessionLauncher(sessionLauncher) {
|
|
130
136
|
if (!sessionLauncher) return null;
|
|
131
137
|
if (typeof sessionLauncher !== 'string' || !path.isAbsolute(sessionLauncher)) {
|
|
@@ -261,6 +267,17 @@ function sanitizeInjectControlChars(text) {
|
|
|
261
267
|
return typeof text === 'string' ? text.replace(INJECT_CONTROL_CHAR_RE, '') : text;
|
|
262
268
|
}
|
|
263
269
|
|
|
270
|
+
// Both account-disabled detectors (the pane notice and an org-disabled
|
|
271
|
+
// StopFailure) reject with this exact error, so consumers handle one shape.
|
|
272
|
+
function authDisabledError() {
|
|
273
|
+
const err = new Error(
|
|
274
|
+
'Claude subscription access has been disabled for this account — ' +
|
|
275
|
+
'the operator needs to re-enable Claude Code access or switch to an API key',
|
|
276
|
+
);
|
|
277
|
+
err.code = 'AUTH_DISABLED';
|
|
278
|
+
return err;
|
|
279
|
+
}
|
|
280
|
+
|
|
264
281
|
class CliProcess extends Process {
|
|
265
282
|
/**
|
|
266
283
|
* @param {object} opts
|
|
@@ -485,9 +502,23 @@ class CliProcess extends Process {
|
|
|
485
502
|
// is the broader surface (hooks + pane heartbeat + bridge tool calls).
|
|
486
503
|
this._lastHookEventAt = 0;
|
|
487
504
|
this._lastActivityAt = 0;
|
|
488
|
-
// Monotonic count of work hooks (all but the terminal Stop) — the rung-2
|
|
505
|
+
// Monotonic count of work hooks (all but the terminal Stop / StopFailure) — the rung-2
|
|
489
506
|
// no-reply backstop snapshots it at Stop capture to detect a later resume.
|
|
490
507
|
this._workHookSeq = 0;
|
|
508
|
+
// Prompts (by prompt_id) whose query has not ended yet, in submission order:
|
|
509
|
+
// promptId → { turnOwned, followUps: [{ msgId, turnId }] }. Opened at the
|
|
510
|
+
// prompt's first UserPromptSubmit; the end of a prompt (Stop/StopFailure)
|
|
511
|
+
// closes it and every older one, because claude runs prompts queued behind
|
|
512
|
+
// a query as ONE query ended under the last prompt_id.
|
|
513
|
+
// - turnOwned: a pending turn of ours runs in it and is settled through
|
|
514
|
+
// that turn, so follow-ups it held when the turn claimed it are dropped.
|
|
515
|
+
// - followUps: the follow-up messages the prompt picked up that no
|
|
516
|
+
// pending turn answers: claude's own cycles (a follow-up autosteered
|
|
517
|
+
// into a turn that then failed runs later as its own cycle; a wakeup),
|
|
518
|
+
// or a fold into a turn's query after that turn settled. If its query
|
|
519
|
+
// ends in an API error, these are the messages to answer; a delivered
|
|
520
|
+
// final reply clears them.
|
|
521
|
+
this._openPrompts = new Map();
|
|
491
522
|
// In-flight sub-agent starts (pushed on Agent PreToolUse, spliced on SubagentStop).
|
|
492
523
|
// Initialized here so a SubagentStop arriving before any Agent start (a lagged/orphan
|
|
493
524
|
// teardown on a fresh proc) reads a length safely instead of throwing.
|
|
@@ -2532,6 +2563,7 @@ class CliProcess extends Process {
|
|
|
2532
2563
|
// resolve its entry, and route it as already-delivered instead.
|
|
2533
2564
|
if (replyTurnId && !this.pendingTurns.has(replyTurnId) && this.inputLedger.has(replyTurnId)) {
|
|
2534
2565
|
const lEntry = this.inputLedger.get(replyTurnId);
|
|
2566
|
+
if (!interim) this._followUpAnswered(replyTurnId);
|
|
2535
2567
|
this._ledgerTransition(replyTurnId, 'resolved');
|
|
2536
2568
|
this._logEvent('cli-late-reply-correlated', { turn_id: replyTurnId, source: lEntry.source });
|
|
2537
2569
|
this.emit('autonomous-assistant-message', {
|
|
@@ -2598,6 +2630,9 @@ class CliProcess extends Process {
|
|
|
2598
2630
|
// missing the autonomous path was a regression caught in production
|
|
2599
2631
|
// (OUT 1148 + 1149 identical-text double-delivery, same timestamp).
|
|
2600
2632
|
if (!target) {
|
|
2633
|
+
// No pending turn: the reply belongs to claude's current own cycle, so
|
|
2634
|
+
// a later API-error end of that cycle must not claim it went unanswered.
|
|
2635
|
+
if (!interim) this._followUpAnswered(null);
|
|
2601
2636
|
this.emit('autonomous-assistant-message', {
|
|
2602
2637
|
text,
|
|
2603
2638
|
sessionId: this.claudeSessionId,
|
|
@@ -2609,6 +2644,9 @@ class CliProcess extends Process {
|
|
|
2609
2644
|
|
|
2610
2645
|
target.replies.push(text);
|
|
2611
2646
|
target.replyCount = (target.replyCount || 0) + 1;
|
|
2647
|
+
// A final answer in a query that also ran older prompts (claude merges
|
|
2648
|
+
// queued ones) answers their follow-ups too.
|
|
2649
|
+
if (!interim) this._clearFollowUpsThrough(target._promptId);
|
|
2612
2650
|
// A status/progress reply (`interim:true`) is delivered but is NOT the turn's
|
|
2613
2651
|
// answer — track it so the finalizer can tell an interim-only turn (a promise
|
|
2614
2652
|
// like "give me a couple min") from a delivered result, and so the ceilings
|
|
@@ -2733,6 +2771,9 @@ class CliProcess extends Process {
|
|
|
2733
2771
|
/** Record text only after the dispatcher confirms that the consuming reply arrived. */
|
|
2734
2772
|
_recordConsumedReplyDelivery(ids, consumingText, interim = false) {
|
|
2735
2773
|
if (!Array.isArray(ids) || typeof consumingText !== 'string') return;
|
|
2774
|
+
if (!interim && consumingText.trim().length > 0) {
|
|
2775
|
+
for (const id of new Set(ids)) this._followUpAnswered(id);
|
|
2776
|
+
}
|
|
2736
2777
|
for (const id of new Set(ids)) {
|
|
2737
2778
|
const pending = this.pendingTurns.get(id);
|
|
2738
2779
|
if (pending && consumingText.length > (pending._consumedByText?.length || 0)) {
|
|
@@ -2767,6 +2808,17 @@ class CliProcess extends Process {
|
|
|
2767
2808
|
if (pending._replyDeliveriesInFlight > 0 || this.pendingTurns.get(turnId) !== pending) {
|
|
2768
2809
|
continue;
|
|
2769
2810
|
}
|
|
2811
|
+
// The turn's query already ended in an API error: that, not a finalize
|
|
2812
|
+
// or timeout queued while the reply was in flight, decides the outcome.
|
|
2813
|
+
if (pending._apiError) {
|
|
2814
|
+
const apiError = pending._apiError;
|
|
2815
|
+
const unlisted = pending._apiErrorUnlisted;
|
|
2816
|
+
pending._apiError = null;
|
|
2817
|
+
pending._finalizeAfterReplyDelivery = false;
|
|
2818
|
+
pending._timeoutAfterReplyDelivery = null;
|
|
2819
|
+
this._settleTurnApiError(turnId, pending, apiError, unlisted);
|
|
2820
|
+
continue;
|
|
2821
|
+
}
|
|
2770
2822
|
if (pending._finalizeAfterReplyDelivery) {
|
|
2771
2823
|
pending._finalizeAfterReplyDelivery = false;
|
|
2772
2824
|
pending._timeoutAfterReplyDelivery = null;
|
|
@@ -2899,7 +2951,7 @@ class CliProcess extends Process {
|
|
|
2899
2951
|
* 3. HOOK-NEVER-ALIVE sessions (rung 3): the pre-D1 reply-quiet re-arm,
|
|
2900
2952
|
* byte-identical.
|
|
2901
2953
|
*
|
|
2902
|
-
* Callers: every hook event except Stop, the pane "esc to interrupt"
|
|
2954
|
+
* Callers: every hook event except Stop and StopFailure, the pane "esc to interrupt"
|
|
2903
2955
|
* thinking heartbeat, bridge tool calls, delivered replies, the question
|
|
2904
2956
|
* keep-alive, and question answers.
|
|
2905
2957
|
*/
|
|
@@ -3350,6 +3402,232 @@ class CliProcess extends Process {
|
|
|
3350
3402
|
}
|
|
3351
3403
|
}
|
|
3352
3404
|
|
|
3405
|
+
/**
|
|
3406
|
+
* A final answer was delivered in a query that is still running: its
|
|
3407
|
+
* follow-ups are no longer waiting, though the query may still end in an
|
|
3408
|
+
* API error. Keep the prompts open (the consumer still ends the cycle's
|
|
3409
|
+
* visuals) and drop their messages to answer. claude answers a merged query
|
|
3410
|
+
* as a whole, so this clears the answered follow-up's prompt and every older
|
|
3411
|
+
* open one. `turnId` names the follow-up the reply was bound to; null means a
|
|
3412
|
+
* reply with no turn of ours to bind to, which belongs to claude's current
|
|
3413
|
+
* query — every open prompt. A delivered reply is recorded before claude's
|
|
3414
|
+
* reply tool returns, so the next query's prompts are not open yet.
|
|
3415
|
+
*/
|
|
3416
|
+
_followUpAnswered(turnId) {
|
|
3417
|
+
let through = null;
|
|
3418
|
+
for (const [id, entry] of this._openPrompts) {
|
|
3419
|
+
if (turnId == null || entry.followUps.some((f) => f.turnId === turnId)) through = id;
|
|
3420
|
+
}
|
|
3421
|
+
this._clearFollowUpsThrough(through);
|
|
3422
|
+
}
|
|
3423
|
+
|
|
3424
|
+
/** Clear the follow-ups of `promptId` and of every older open prompt. */
|
|
3425
|
+
_clearFollowUpsThrough(promptId) {
|
|
3426
|
+
if (promptId == null || !this._openPrompts.has(promptId)) return;
|
|
3427
|
+
for (const [id, entry] of this._openPrompts) {
|
|
3428
|
+
entry.followUps = [];
|
|
3429
|
+
if (id === promptId) break;
|
|
3430
|
+
}
|
|
3431
|
+
}
|
|
3432
|
+
|
|
3433
|
+
/**
|
|
3434
|
+
* The query of `promptId` ended: close that prompt and every older open
|
|
3435
|
+
* one (prompts queued behind a query run as one query, ended under the last
|
|
3436
|
+
* prompt_id only). Returns the closed [promptId, entry] pairs, oldest first;
|
|
3437
|
+
* nothing is closed when `promptId` is not open.
|
|
3438
|
+
*/
|
|
3439
|
+
_closePromptsThrough(promptId) {
|
|
3440
|
+
if (!promptId || !this._openPrompts.has(promptId)) return [];
|
|
3441
|
+
const closed = [];
|
|
3442
|
+
for (const [id, entry] of this._openPrompts) {
|
|
3443
|
+
closed.push([id, entry]);
|
|
3444
|
+
if (id === promptId) break;
|
|
3445
|
+
}
|
|
3446
|
+
for (const [id] of closed) this._openPrompts.delete(id);
|
|
3447
|
+
return closed;
|
|
3448
|
+
}
|
|
3449
|
+
|
|
3450
|
+
/**
|
|
3451
|
+
* A main-thread StopFailure: the query identified by `ev.promptId` ended in
|
|
3452
|
+
* an API error after claude's own retries. That query ran its own prompt
|
|
3453
|
+
* and every older prompt still open (claude runs prompts queued behind a
|
|
3454
|
+
* query as one query, ended under the last prompt_id). Settle the pending
|
|
3455
|
+
* turns that ran in it; if it also ran cycles of claude's own (a follow-up
|
|
3456
|
+
* that runs after a failed turn, a wakeup), tell the consumer once, naming
|
|
3457
|
+
* every follow-up message those cycles still owe an answer.
|
|
3458
|
+
*
|
|
3459
|
+
* Attribution is by prompt_id only, and only ever reaches back (older
|
|
3460
|
+
* prompts), never forward: Stop's looser rule (the single seen pending)
|
|
3461
|
+
* would let a lagged failure of an earlier query fail a turn that is
|
|
3462
|
+
* running fine; without a prompt_id the ceilings stay the backstop.
|
|
3463
|
+
*/
|
|
3464
|
+
_handleStopFailure(ev) {
|
|
3465
|
+
const apiError = ev.apiError || 'unknown';
|
|
3466
|
+
// A class the pinned CLI does not define arrives as 'unknown'; flag it so a
|
|
3467
|
+
// CLI bump that adds classes is visible in telemetry.
|
|
3468
|
+
const unlisted = ev.apiErrorUnlisted === true || undefined;
|
|
3469
|
+
if (this.closed || this._bridgeDisconnecting) {
|
|
3470
|
+
this._logEvent('cli-stop-failure-ignored', {
|
|
3471
|
+
reason: this.closed ? 'closed' : 'bridge-disconnecting',
|
|
3472
|
+
api_error_code: apiError,
|
|
3473
|
+
});
|
|
3474
|
+
return;
|
|
3475
|
+
}
|
|
3476
|
+
const promptId = ev.promptId;
|
|
3477
|
+
if (!promptId) {
|
|
3478
|
+
this._logEvent('cli-stop-failure-unattributed', {
|
|
3479
|
+
reason: 'no-prompt-id',
|
|
3480
|
+
api_error_code: apiError,
|
|
3481
|
+
api_error_unlisted: unlisted,
|
|
3482
|
+
pending_count: this.pendingTurns.size,
|
|
3483
|
+
});
|
|
3484
|
+
return;
|
|
3485
|
+
}
|
|
3486
|
+
|
|
3487
|
+
// Closing first makes a duplicated or late line for these prompts a no-op.
|
|
3488
|
+
const closed = this._closePromptsThrough(promptId);
|
|
3489
|
+
const prompts = new Set([promptId, ...closed.map(([id]) => id)]);
|
|
3490
|
+
const matched = [];
|
|
3491
|
+
for (const [turnId, pending] of this.pendingTurns) {
|
|
3492
|
+
if (pending._promptId != null && prompts.has(pending._promptId)) matched.push([turnId, pending]);
|
|
3493
|
+
}
|
|
3494
|
+
for (const [turnId, pending] of matched) {
|
|
3495
|
+
// An earlier settle's synchronous listeners may have torn things down.
|
|
3496
|
+
if (this.pendingTurns.get(turnId) !== pending) continue;
|
|
3497
|
+
// A /stop is already resolving this turn; its resolution stands.
|
|
3498
|
+
if (pending._interruptRequested) {
|
|
3499
|
+
this._logEvent('cli-stop-failure-during-interrupt', {
|
|
3500
|
+
turn_id: turnId,
|
|
3501
|
+
api_error_code: apiError,
|
|
3502
|
+
});
|
|
3503
|
+
continue;
|
|
3504
|
+
}
|
|
3505
|
+
this._settleTurnApiError(turnId, pending, apiError, unlisted);
|
|
3506
|
+
}
|
|
3507
|
+
|
|
3508
|
+
// Prompts no settled-through turn answers: claude's own cycles, and turn
|
|
3509
|
+
// prompts that picked up a follow-up after their turn settled.
|
|
3510
|
+
const ownCycles = closed.filter(([, entry]) => !entry.turnOwned || entry.followUps.length > 0);
|
|
3511
|
+
if (ownCycles.length === 0) {
|
|
3512
|
+
// Only turns of ours ran in this query (settled above, or already
|
|
3513
|
+
// settled earlier: a late failure of a turn that timed out), or its
|
|
3514
|
+
// prompt is no longer open (a duplicated line).
|
|
3515
|
+
if (matched.length === 0) {
|
|
3516
|
+
this._logEvent('cli-stop-failure-unattributed', {
|
|
3517
|
+
reason: 'no-matching-pending',
|
|
3518
|
+
api_error_code: apiError,
|
|
3519
|
+
api_error_unlisted: unlisted,
|
|
3520
|
+
pending_count: this.pendingTurns.size,
|
|
3521
|
+
closed_prompt_count: closed.length,
|
|
3522
|
+
});
|
|
3523
|
+
}
|
|
3524
|
+
return;
|
|
3525
|
+
}
|
|
3526
|
+
const anchorMsgIds = [...new Set(ownCycles.flatMap(([, entry]) => entry.followUps.map((f) => f.msgId)))];
|
|
3527
|
+
this._logEvent('cli-stop-failure-unattributed', {
|
|
3528
|
+
reason: 'own-cycle',
|
|
3529
|
+
api_error_code: apiError,
|
|
3530
|
+
api_error_unlisted: unlisted,
|
|
3531
|
+
pending_count: this.pendingTurns.size,
|
|
3532
|
+
closed_prompt_count: closed.length,
|
|
3533
|
+
anchor_msg_ids: anchorMsgIds.length > 0 ? anchorMsgIds : undefined,
|
|
3534
|
+
});
|
|
3535
|
+
this.emit('api-error', {
|
|
3536
|
+
apiError,
|
|
3537
|
+
anchorMsgIds,
|
|
3538
|
+
sessionId: this.claudeSessionId,
|
|
3539
|
+
backend: this.backend,
|
|
3540
|
+
});
|
|
3541
|
+
}
|
|
3542
|
+
|
|
3543
|
+
/**
|
|
3544
|
+
* Settle one pending turn whose query ended in an API error.
|
|
3545
|
+
*
|
|
3546
|
+
* - a reply is still being delivered → decide once it settles (the reply
|
|
3547
|
+
* may be the answer); the API error then takes precedence over any
|
|
3548
|
+
* finalize or timeout that queued up meanwhile.
|
|
3549
|
+
* - a final answer was delivered → the user has it: resolve as answered,
|
|
3550
|
+
* as a ceiling resolves a turn with a delivered final answer.
|
|
3551
|
+
* - otherwise (nothing, or only interim status replies) → reject now with
|
|
3552
|
+
* CLAUDE_API_ERROR, or AUTH_DISABLED for an org that disabled
|
|
3553
|
+
* subscription access (the same error the pane detector raises, so the
|
|
3554
|
+
* operator-only handling of that case is kept).
|
|
3555
|
+
*/
|
|
3556
|
+
_settleTurnApiError(turnId, pending, apiError, unlisted = undefined) {
|
|
3557
|
+
if ((pending._replyDeliveriesInFlight || 0) > 0) {
|
|
3558
|
+
pending._apiError = apiError;
|
|
3559
|
+
pending._apiErrorUnlisted = unlisted;
|
|
3560
|
+
if (pending._stopGraceTimer) { clearTimeout(pending._stopGraceTimer); pending._stopGraceTimer = null; }
|
|
3561
|
+
if (pending._onStop) { this.off('stop-hook', pending._onStop); pending._onStop = null; }
|
|
3562
|
+
pending._stopGracePending = false;
|
|
3563
|
+
if (pending._activityQuietTimer) { clearTimeout(pending._activityQuietTimer); pending._activityQuietTimer = null; }
|
|
3564
|
+
this._logEvent('cli-turn-api-error', {
|
|
3565
|
+
turn_id: turnId, api_error_code: apiError, deferred: true,
|
|
3566
|
+
});
|
|
3567
|
+
return;
|
|
3568
|
+
}
|
|
3569
|
+
|
|
3570
|
+
if (this._turnHasFinalReply(pending) || this._turnHasConsumedFinalReply(pending)) {
|
|
3571
|
+
this._logEvent('cli-turn-api-error', {
|
|
3572
|
+
turn_id: turnId, api_error_code: apiError, api_error_unlisted: unlisted, delivered: true,
|
|
3573
|
+
reply_count: pending.replies.length,
|
|
3574
|
+
});
|
|
3575
|
+
// This query ended without a Stop, so any captured Stop text belongs to
|
|
3576
|
+
// another cycle and must not be delivered as this turn's answer.
|
|
3577
|
+
pending._stopHookData = null;
|
|
3578
|
+
this._finalizeTurn(turnId);
|
|
3579
|
+
return;
|
|
3580
|
+
}
|
|
3581
|
+
|
|
3582
|
+
this.pendingTurns.delete(turnId);
|
|
3583
|
+
const qIdx = this.pendingQueue.findIndex(e => e.turnId === turnId);
|
|
3584
|
+
if (qIdx >= 0) this.pendingQueue.splice(qIdx, 1);
|
|
3585
|
+
if (pending.quietTimer) clearTimeout(pending.quietTimer);
|
|
3586
|
+
if (pending.hardTimer) clearTimeout(pending.hardTimer);
|
|
3587
|
+
if (pending.absoluteTimer) clearTimeout(pending.absoluteTimer);
|
|
3588
|
+
if (pending._stopGraceTimer) clearTimeout(pending._stopGraceTimer);
|
|
3589
|
+
if (pending._activityQuietTimer) clearTimeout(pending._activityQuietTimer);
|
|
3590
|
+
if (pending._onStop) { this.off('stop-hook', pending._onStop); pending._onStop = null; }
|
|
3591
|
+
pending._stopGracePending = false;
|
|
3592
|
+
this.inFlight = this.pendingTurns.size > 0;
|
|
3593
|
+
this._ledgerTransition(turnId, 'resolved');
|
|
3594
|
+
// As at any cycle end: follow-ups still 'written' enter the drop-confirm
|
|
3595
|
+
// window, so one claude never picks up is redelivered instead of lost.
|
|
3596
|
+
this._armDropConfirmSweep();
|
|
3597
|
+
const authDisabled = apiError === 'oauth_org_not_allowed';
|
|
3598
|
+
this._logEvent('cli-turn-api-error', {
|
|
3599
|
+
turn_id: turnId, api_error_code: apiError, api_error_unlisted: unlisted, delivered: false,
|
|
3600
|
+
reply_count: pending.replies.length,
|
|
3601
|
+
duration_ms: Date.now() - pending.startedAt,
|
|
3602
|
+
});
|
|
3603
|
+
if (this.pendingTurns.size === 0) {
|
|
3604
|
+
this._purgeStagingDir();
|
|
3605
|
+
this._pendingSubagentStarts = [];
|
|
3606
|
+
}
|
|
3607
|
+
let err;
|
|
3608
|
+
if (authDisabled) {
|
|
3609
|
+
err = authDisabledError();
|
|
3610
|
+
} else {
|
|
3611
|
+
// The class rides on err.apiError only: a consumer that classifies by
|
|
3612
|
+
// message text must not read 'server_error' or 'rate_limit' in it.
|
|
3613
|
+
err = new Error('Claude ended this turn with an API error');
|
|
3614
|
+
err.code = 'CLAUDE_API_ERROR';
|
|
3615
|
+
err.apiError = apiError;
|
|
3616
|
+
}
|
|
3617
|
+
// Reject BEFORE emitting: the turn's ceilings are already cleared, so a
|
|
3618
|
+
// throwing listener must not be able to leave it pending forever.
|
|
3619
|
+
try { pending.reject(err); } catch {}
|
|
3620
|
+
this.emit('idle');
|
|
3621
|
+
if (authDisabled) {
|
|
3622
|
+
this._logEvent('cli-auth-disabled-detected', { drained_pendings: 1, source: 'stop-failure' });
|
|
3623
|
+
this.emit('auth-disabled-detected', {
|
|
3624
|
+
sessionId: this.claudeSessionId,
|
|
3625
|
+
backend: this.backend,
|
|
3626
|
+
drainedPendings: 1,
|
|
3627
|
+
});
|
|
3628
|
+
}
|
|
3629
|
+
}
|
|
3630
|
+
|
|
3353
3631
|
/**
|
|
3354
3632
|
* Empty the per-session file-send staging dir (keep the dir itself).
|
|
3355
3633
|
* Best-effort; never throws. Called when the session goes idle and on kill.
|
|
@@ -3548,6 +3826,11 @@ class CliProcess extends Process {
|
|
|
3548
3826
|
};
|
|
3549
3827
|
if (probeResult) { try { logProbe(probeResult); } catch { /* best-effort */ } }
|
|
3550
3828
|
else this.probeBusyState().then(logProbe).catch(() => { /* telemetry best-effort */ });
|
|
3829
|
+
// A turn that went quiet: follow-ups autosteered into it that claude
|
|
3830
|
+
// never picked up enter the drop-confirm window, as at any cycle end.
|
|
3831
|
+
// Not at the hard cap: claude is still working there and still holds
|
|
3832
|
+
// its queued follow-ups, so a resend would answer them twice.
|
|
3833
|
+
if (reason !== 'hard-max') this._armDropConfirmSweep();
|
|
3551
3834
|
this.emit('idle');
|
|
3552
3835
|
const err = new Error(`turn timeout (${turnTimeoutMs}ms, reason=${reason})`);
|
|
3553
3836
|
err.code = reason === 'hard-max' ? 'TURN_MAX_EXCEEDED' : 'TURN_TIMEOUT';
|
|
@@ -3689,6 +3972,14 @@ class CliProcess extends Process {
|
|
|
3689
3972
|
// resolved that fresh turn as 'interrupted' (lost). send() doesn't clear the
|
|
3690
3973
|
// grace, so the snapshot is the fix.
|
|
3691
3974
|
const interruptedTurnIds = new Set(this.pendingTurns.keys());
|
|
3975
|
+
// The same snapshot tells a racing StopFailure which turns the interrupt
|
|
3976
|
+
// owns; a turn started after this C-c is not one of them.
|
|
3977
|
+
for (const pending of this.pendingTurns.values()) pending._interruptRequested = true;
|
|
3978
|
+
// The C-c ends the running query without a Stop or StopFailure, so its
|
|
3979
|
+
// prompts would otherwise stay open and be swept into a later query's end:
|
|
3980
|
+
// a cancelled follow-up told it failed, a stopped wakeup reported. A
|
|
3981
|
+
// prompt submitted after the C-c opens afresh.
|
|
3982
|
+
this._openPrompts.clear();
|
|
3692
3983
|
this._interruptGraceTimer = setTimeout(() => {
|
|
3693
3984
|
let resolvedAny = false;
|
|
3694
3985
|
for (const [turnId, pending] of this.pendingTurns) {
|
|
@@ -4343,14 +4634,28 @@ class CliProcess extends Process {
|
|
|
4343
4634
|
});
|
|
4344
4635
|
}
|
|
4345
4636
|
|
|
4637
|
+
// A sub-agent whose model request fails ends with StopFailure (carrying its
|
|
4638
|
+
// agent_id) and fires NO SubagentStop. Treat it as that sub-agent's
|
|
4639
|
+
// SubagentStop so its in-flight start is released — otherwise the leaked
|
|
4640
|
+
// start defers the parent's Stop until a ceiling. A sub-agent's failure is
|
|
4641
|
+
// never the parent turn's end; the parent's own failure carries no agent_id.
|
|
4642
|
+
if (ev.type === 'StopFailure' && typeof ev.agentId === 'string' && ev.agentId) {
|
|
4643
|
+
this._logEvent('cli-stop-failure-subagent', {
|
|
4644
|
+
agent_id: ev.agentId,
|
|
4645
|
+
api_error_code: ev.apiError,
|
|
4646
|
+
});
|
|
4647
|
+
ev = { ...ev, type: 'SubagentStop' };
|
|
4648
|
+
}
|
|
4649
|
+
|
|
4346
4650
|
// 0.13 D1: every hook event is same-session ACTIVITY for the finalizer
|
|
4347
4651
|
// ladder (generalizes the 2026-06-08 WA-topic fix, which only extended on
|
|
4348
4652
|
// Pre/PostToolUse) — EXCEPT terminal signals, which are not work: noting them
|
|
4349
4653
|
// as activity would cancel a live attribution grace. parse-error and unknown
|
|
4350
4654
|
// are excluded too (stream noise is not evidence of work).
|
|
4351
4655
|
//
|
|
4352
|
-
// Stop
|
|
4353
|
-
// a late/lagged/foreign teardown hook
|
|
4656
|
+
// Stop and a main-thread StopFailure are always terminal. SubagentStop is
|
|
4657
|
+
// terminal ONLY when it's an ORPHAN — a late/lagged/foreign teardown hook
|
|
4658
|
+
// with no matching in-flight sub-agent start.
|
|
4354
4659
|
// Such an orphan trails the main Stop (or arrives from a prior cycle) and must not
|
|
4355
4660
|
// bump the work-hook counter (the rung-2 no-reply backstop reads a bump as "claude
|
|
4356
4661
|
// resumed", withdrawing the captured Stop's delivery) nor count as activity. A
|
|
@@ -4359,11 +4664,11 @@ class CliProcess extends Process {
|
|
|
4359
4664
|
// a tool-less sub-agent whose only post-boundary signal is its SubagentStop.
|
|
4360
4665
|
const orphanSubagentStop = ev.type === 'SubagentStop'
|
|
4361
4666
|
&& !(this._pendingSubagentStarts && this._pendingSubagentStarts.length);
|
|
4362
|
-
if (ev.type === 'Stop' || orphanSubagentStop) {
|
|
4667
|
+
if (ev.type === 'Stop' || ev.type === 'StopFailure' || orphanSubagentStop) {
|
|
4363
4668
|
this._lastHookEventAt = Date.now();
|
|
4364
4669
|
} else if (ev.type && ev.type !== 'parse-error' && ev.type !== 'unknown') {
|
|
4365
4670
|
this._lastHookEventAt = Date.now();
|
|
4366
|
-
// Monotonic count of WORK hooks (all but terminal Stop / orphan SubagentStop). The
|
|
4671
|
+
// Monotonic count of WORK hooks (all but terminal Stop / StopFailure / orphan SubagentStop). The
|
|
4367
4672
|
// rung-2 no-reply backstop snapshots this at Stop capture; a later increment means
|
|
4368
4673
|
// claude resumed work, withdrawing the stale Stop's finalize eligibility.
|
|
4369
4674
|
this._workHookSeq = (this._workHookSeq || 0) + 1;
|
|
@@ -4390,11 +4695,18 @@ class CliProcess extends Process {
|
|
|
4390
4695
|
// matching pending as picked-up. `seen` is what lets rung 1 tell this
|
|
4391
4696
|
// cycle's Stop from a foreign cycle's. Never log prompt content (L13).
|
|
4392
4697
|
let anchorMsgId = null;
|
|
4698
|
+
// The follow-ups (non-primary inputs with a message id) this prompt
|
|
4699
|
+
// picked up — the messages to answer if this prompt, owning no
|
|
4700
|
+
// pending turn, later ends in an API error.
|
|
4701
|
+
const followUps = [];
|
|
4393
4702
|
if (typeof ev.prompt === 'string' && ev.prompt) {
|
|
4394
4703
|
for (const m of ev.prompt.matchAll(UPS_ENVELOPE_TURN_ID_RE)) {
|
|
4395
4704
|
const seenPending = this.pendingTurns.get(m[1]);
|
|
4396
4705
|
if (seenPending && seenPending.seen !== true) {
|
|
4397
4706
|
seenPending.seen = true;
|
|
4707
|
+
// The query this turn runs in. Its StopFailure carries the same
|
|
4708
|
+
// prompt_id, which is how an API-error end is attributed exactly.
|
|
4709
|
+
if (ev.promptId && !seenPending._promptId) seenPending._promptId = ev.promptId;
|
|
4398
4710
|
this._logEvent('cli-ups-seen', { turn_id: m[1] });
|
|
4399
4711
|
}
|
|
4400
4712
|
// 0.13 D2: pickup transitions the ledger entry too — for injected
|
|
@@ -4410,6 +4722,45 @@ class CliProcess extends Process {
|
|
|
4410
4722
|
}
|
|
4411
4723
|
// 0.13 D3: the picked-up message anchors the cycle's visuals.
|
|
4412
4724
|
if (anchorMsgId == null && lEntry.msgId != null) anchorMsgId = lEntry.msgId;
|
|
4725
|
+
// A follow-up the user cancelled with /stop is not waiting for an
|
|
4726
|
+
// answer, even if claude still runs it.
|
|
4727
|
+
if (lEntry.source !== 'primary' && lEntry.msgId != null && lEntry.state !== 'cancelled') {
|
|
4728
|
+
followUps.push({ msgId: lEntry.msgId, turnId: m[1] });
|
|
4729
|
+
}
|
|
4730
|
+
}
|
|
4731
|
+
}
|
|
4732
|
+
}
|
|
4733
|
+
// Track the prompt until its query ends (see _openPrompts). A prompt a
|
|
4734
|
+
// pending turn runs in is settled through that turn, so it answers no
|
|
4735
|
+
// follow-ups of its own: a late failure of an already-settled turn can
|
|
4736
|
+
// then never send a second reply. Any other prompt (a follow-up that
|
|
4737
|
+
// runs as its own cycle, a wakeup, a self-check) keeps the follow-ups
|
|
4738
|
+
// it picked up, including ones a fold's repeat UserPromptSubmit adds.
|
|
4739
|
+
if (ev.promptId) {
|
|
4740
|
+
let ownedByPending = false;
|
|
4741
|
+
for (const p of this.pendingTurns.values()) {
|
|
4742
|
+
if (p._promptId === ev.promptId) { ownedByPending = true; break; }
|
|
4743
|
+
}
|
|
4744
|
+
const open = this._openPrompts.get(ev.promptId);
|
|
4745
|
+
if (!open) {
|
|
4746
|
+
this._openPrompts.set(ev.promptId, { turnOwned: ownedByPending, followUps: ownedByPending ? [] : followUps });
|
|
4747
|
+
if (this._openPrompts.size > OPEN_PROMPT_CAP) {
|
|
4748
|
+
const [evictedId, evicted] = this._openPrompts.entries().next().value;
|
|
4749
|
+
this._openPrompts.delete(evictedId);
|
|
4750
|
+
this._logEvent('cli-open-prompt-evicted', {
|
|
4751
|
+
turn_owned: evicted.turnOwned,
|
|
4752
|
+
follow_up_count: evicted.followUps.length,
|
|
4753
|
+
});
|
|
4754
|
+
}
|
|
4755
|
+
} else if (ownedByPending) {
|
|
4756
|
+
// A pending turn folded into a prompt that began as claude's own
|
|
4757
|
+
// cycle takes it over: the turn's settlement answers it, so the
|
|
4758
|
+
// follow-ups it held get no error notice of their own later.
|
|
4759
|
+
open.turnOwned = true;
|
|
4760
|
+
open.followUps = [];
|
|
4761
|
+
} else {
|
|
4762
|
+
for (const f of followUps) {
|
|
4763
|
+
if (!open.followUps.some((known) => known.turnId === f.turnId)) open.followUps.push(f);
|
|
4413
4764
|
}
|
|
4414
4765
|
}
|
|
4415
4766
|
}
|
|
@@ -4530,6 +4881,11 @@ class CliProcess extends Process {
|
|
|
4530
4881
|
// single pending on ANY Stop — a foreign cycle's Stop could close a
|
|
4531
4882
|
// queued, never-picked-up user turn and deliver the FOREIGN cycle's
|
|
4532
4883
|
// last_assistant_message as its answer (seam S5's Stop-identity gap).
|
|
4884
|
+
//
|
|
4885
|
+
// A Stop means this prompt's query (and every older prompt merged into
|
|
4886
|
+
// it) ended normally, so a StopFailure that shows up later must not
|
|
4887
|
+
// report their follow-ups as unanswered.
|
|
4888
|
+
if (ev.promptId) this._closePromptsThrough(ev.promptId);
|
|
4533
4889
|
const preStopPendingCount = this.pendingTurns.size;
|
|
4534
4890
|
const workflowSnapshot = preStopPendingCount === 0 && ev.stopHookActive !== true
|
|
4535
4891
|
? this._captureWorkflowCompletionSnapshot(ev)
|
|
@@ -4600,6 +4956,15 @@ class CliProcess extends Process {
|
|
|
4600
4956
|
return;
|
|
4601
4957
|
}
|
|
4602
4958
|
|
|
4959
|
+
case 'StopFailure':
|
|
4960
|
+
// A main-thread query ended in an API error (claude's own retries are
|
|
4961
|
+
// exhausted). Deliberately NOT routed through the Stop machinery: its
|
|
4962
|
+
// last_assistant_message is the rendered provider error (with the
|
|
4963
|
+
// gateway host), which the Stop fallback or the workflow-completion
|
|
4964
|
+
// path would deliver to the user as the answer.
|
|
4965
|
+
this._handleStopFailure(ev);
|
|
4966
|
+
return;
|
|
4967
|
+
|
|
4603
4968
|
case 'PreCompact':
|
|
4604
4969
|
// 0.12.0-rc.13: auto-compaction is the event that detaches the
|
|
4605
4970
|
// channels MCP bridge mid-turn. Record it; and on the dangerous AUTO
|
|
@@ -5394,14 +5759,7 @@ class CliProcess extends Process {
|
|
|
5394
5759
|
* decision, not this shared engine's to make.
|
|
5395
5760
|
*/
|
|
5396
5761
|
_rejectPendingTurnsAuthDisabled() {
|
|
5397
|
-
const makeErr =
|
|
5398
|
-
const err = new Error(
|
|
5399
|
-
'Claude subscription access has been disabled for this account — ' +
|
|
5400
|
-
'the operator needs to re-enable Claude Code access or switch to an API key',
|
|
5401
|
-
);
|
|
5402
|
-
err.code = 'AUTH_DISABLED';
|
|
5403
|
-
return err;
|
|
5404
|
-
};
|
|
5762
|
+
const makeErr = authDisabledError;
|
|
5405
5763
|
const channelsTurnIds = new Set();
|
|
5406
5764
|
let drained = 0;
|
|
5407
5765
|
for (const [turnId, pending] of this.pendingTurns) {
|
|
@@ -25,14 +25,15 @@
|
|
|
25
25
|
*
|
|
26
26
|
* {
|
|
27
27
|
* type: 'PreToolUse' | 'PostToolUse' | 'UserPromptSubmit'
|
|
28
|
-
* | 'Stop' | '
|
|
29
|
-
* | 'parse-error',
|
|
30
|
-
* sessionId, transcriptPath, cwd, permissionMode,
|
|
28
|
+
* | 'Stop' | 'StopFailure' | 'SubagentStop' | 'Notification'
|
|
29
|
+
* | 'unknown' | 'parse-error',
|
|
30
|
+
* sessionId, transcriptPath, cwd, permissionMode, promptId, // common
|
|
31
31
|
* toolName, toolUseId, toolInput, toolResponse, durationMs, // tool events
|
|
32
32
|
* agentId, agentType, // subagent-inner
|
|
33
33
|
* agentTranscriptPath, // SubagentStop
|
|
34
34
|
* prompt, // UserPromptSubmit
|
|
35
35
|
* stopHookActive, lastAssistantMessage, // Stop
|
|
36
|
+
* apiError, // StopFailure
|
|
36
37
|
* receivedAtMs, raw, // always
|
|
37
38
|
* }
|
|
38
39
|
*
|
|
@@ -55,8 +56,34 @@ const KNOWN_EVENT_NAMES = new Set([
|
|
|
55
56
|
// 0.12.0-rc.13: compaction lifecycle (carry `trigger` + custom_instructions).
|
|
56
57
|
'PreCompact',
|
|
57
58
|
'PostCompact',
|
|
59
|
+
// A query that ended in an API error (claude's retries exhausted). Carries
|
|
60
|
+
// the `error` class and the query's `prompt_id`; fires instead of Stop.
|
|
61
|
+
'StopFailure',
|
|
58
62
|
]);
|
|
59
63
|
|
|
64
|
+
// StopFailure `error` classes the pinned CLI defines. Anything else (a newer
|
|
65
|
+
// CLI's new class, a malformed line) is reported as 'unknown' so a free-form
|
|
66
|
+
// value can never travel into errors, telemetry or user-facing copy.
|
|
67
|
+
const STOP_FAILURE_ERROR_KINDS = new Set([
|
|
68
|
+
'authentication_failed',
|
|
69
|
+
'oauth_org_not_allowed',
|
|
70
|
+
'account_on_hold',
|
|
71
|
+
'verification_required',
|
|
72
|
+
'billing_error',
|
|
73
|
+
'rate_limit',
|
|
74
|
+
'overloaded',
|
|
75
|
+
'invalid_request',
|
|
76
|
+
'model_not_found',
|
|
77
|
+
'server_error',
|
|
78
|
+
'unknown',
|
|
79
|
+
'max_output_tokens',
|
|
80
|
+
'cloud_credential_error',
|
|
81
|
+
]);
|
|
82
|
+
|
|
83
|
+
function nonEmptyString(v) {
|
|
84
|
+
return typeof v === 'string' && v.length > 0 ? v : null;
|
|
85
|
+
}
|
|
86
|
+
|
|
60
87
|
/**
|
|
61
88
|
* Normalize one raw hook payload (already JSON.parsed) into the
|
|
62
89
|
* shape downstream code consumes. Unknown shapes pass through as
|
|
@@ -95,6 +122,19 @@ function normalizeHookEvent(raw) {
|
|
|
95
122
|
// compaction; custom_instructions is the `/compact <hint>` text (manual).
|
|
96
123
|
trigger: raw?.trigger ?? null,
|
|
97
124
|
customInstructions: raw?.custom_instructions ?? null,
|
|
125
|
+
// Identifies the query (user prompt) a hook belongs to: shared by its
|
|
126
|
+
// UserPromptSubmit, a follow-up folded into it, its tool hooks and its
|
|
127
|
+
// final Stop/StopFailure; a queued prompt that runs as its own cycle gets
|
|
128
|
+
// a new one.
|
|
129
|
+
promptId: nonEmptyString(raw?.prompt_id),
|
|
130
|
+
apiError: type === 'StopFailure'
|
|
131
|
+
? (STOP_FAILURE_ERROR_KINDS.has(raw?.error) ? raw.error : 'unknown')
|
|
132
|
+
: null,
|
|
133
|
+
// True when StopFailure reported a class outside the enum above (e.g. one a
|
|
134
|
+
// newer CLI added), so 'unknown' here is distinguishable from the CLI's own.
|
|
135
|
+
apiErrorUnlisted: type === 'StopFailure'
|
|
136
|
+
&& typeof raw?.error === 'string' && raw.error.length > 0
|
|
137
|
+
&& !STOP_FAILURE_ERROR_KINDS.has(raw.error),
|
|
98
138
|
receivedAtMs: raw?.polygram_received_at_ms ?? null,
|
|
99
139
|
raw,
|
|
100
140
|
};
|
|
@@ -157,6 +197,7 @@ function createHookTail({ path: filePath, skipExisting = false, logger = console
|
|
|
157
197
|
|
|
158
198
|
module.exports = {
|
|
159
199
|
KNOWN_EVENT_NAMES,
|
|
200
|
+
STOP_FAILURE_ERROR_KINDS,
|
|
160
201
|
normalizeHookEvent,
|
|
161
202
|
pipeHookParser,
|
|
162
203
|
createHookTail,
|
|
@@ -52,6 +52,10 @@ const HOOK_EVENTS = [
|
|
|
52
52
|
// (2.1.142) and carry a `trigger: auto|manual` field.
|
|
53
53
|
'PreCompact',
|
|
54
54
|
'PostCompact',
|
|
55
|
+
// A query that ends in an API error (after claude's own retries) fires
|
|
56
|
+
// StopFailure INSTEAD of Stop / SubagentStop. It only fires when a hook is
|
|
57
|
+
// registered for it; without this entry such a turn has no end signal at all.
|
|
58
|
+
'StopFailure',
|
|
55
59
|
];
|
|
56
60
|
|
|
57
61
|
/**
|
|
@@ -121,7 +125,12 @@ function buildHookSettings({ ndjsonPath, helperPath = HOOK_HELPER_ABS_PATH } = {
|
|
|
121
125
|
for (const evt of HOOK_EVENTS) {
|
|
122
126
|
hooks[evt] = (evt === 'PreToolUse' || evt === 'PostToolUse') ? matched('.*') : unmatched();
|
|
123
127
|
}
|
|
124
|
-
|
|
128
|
+
// Claude Code delivers SendMessage traffic from other same-user sessions
|
|
129
|
+
// into this one unless told otherwise. A bot session takes input only
|
|
130
|
+
// from its own transport, so it refuses that traffic outright. `refuse`
|
|
131
|
+
// from `--settings` outranks user settings; only managed policy can
|
|
132
|
+
// override it.
|
|
133
|
+
return { hooks, crossSessionInbound: 'refuse' };
|
|
125
134
|
}
|
|
126
135
|
|
|
127
136
|
/**
|
|
@@ -317,6 +317,13 @@ const CALLBACK_TO_EVENT = {
|
|
|
317
317
|
// + confirm window, contract observed). polygram redelivers ONCE via the D4
|
|
318
318
|
// tail (lib/handlers/drop-redeliver.js).
|
|
319
319
|
onInputDropped: 'input-dropped',
|
|
320
|
+
// CliProcess emits 'api-error' {apiError, anchorMsgIds, sessionId, backend}
|
|
321
|
+
// once when a failed claude query ran cycles that no pending turn runs in (a
|
|
322
|
+
// follow-up that ran as its own cycle after a failed turn, a wakeup).
|
|
323
|
+
// anchorMsgIds lists every follow-up message those cycles still owe an
|
|
324
|
+
// answer, oldest first; it is empty when no user message is waiting.
|
|
325
|
+
// Failed pending turns reject instead (CLAUDE_API_ERROR / AUTH_DISABLED).
|
|
326
|
+
onApiError: 'api-error',
|
|
320
327
|
onQueueDrop: 'queue-drop',
|
|
321
328
|
onThinking: 'thinking',
|
|
322
329
|
// Tmux backend: TUI shows in-pane approval prompt. SDK backend
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shumkov/orchestra",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.3",
|
|
4
4
|
"description": "Transport-agnostic session engine for Claude Code and the native Codex app-server: spawn, steer, supervise, observe turns, and recover.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "index.js",
|