@agentclientprotocol/claude-agent-acp 0.45.0 → 0.46.0
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.
- package/dist/acp-agent.d.ts +83 -16
- package/dist/acp-agent.d.ts.map +1 -1
- package/dist/acp-agent.js +481 -219
- package/dist/elicitation.d.ts +10 -8
- package/dist/elicitation.d.ts.map +1 -1
- package/dist/elicitation.js +71 -26
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +2 -1
- package/package.json +6 -6
package/dist/acp-agent.js
CHANGED
|
@@ -93,6 +93,10 @@ function isMuslLibc() {
|
|
|
93
93
|
function shouldHideClaudeAuth() {
|
|
94
94
|
return process.argv.includes("--hide-claude-auth");
|
|
95
95
|
}
|
|
96
|
+
/** Returned to clients when a prompt or cancel targets a session whose SDK
|
|
97
|
+
* query stream has already ended (ran to `done` or died). The stream is not
|
|
98
|
+
* revivable, so the only recovery is a fresh session. */
|
|
99
|
+
const SESSION_ENDED_MESSAGE = "The Claude Agent session has ended. Please start a new session.";
|
|
96
100
|
// Bypass Permissions doesn't work if we are a root/sudo user
|
|
97
101
|
const IS_ROOT = (process.geteuid?.() ?? process.getuid?.()) === 0;
|
|
98
102
|
const ALLOW_BYPASS = !IS_ROOT || !!process.env.IS_SANDBOX;
|
|
@@ -460,112 +464,273 @@ export class ClaudeAcpAgent {
|
|
|
460
464
|
if (!session) {
|
|
461
465
|
throw new Error("Session not found");
|
|
462
466
|
}
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
467
|
+
// The SDK query stream already terminated (see `queryClosed`); its iterator
|
|
468
|
+
// can't be revived, so enqueueing here would hang on a deferred that never
|
|
469
|
+
// settles. Fail clearly and let the client start a fresh session.
|
|
470
|
+
if (session.queryClosed) {
|
|
471
|
+
throw RequestError.internalError(undefined, SESSION_ENDED_MESSAGE);
|
|
472
|
+
}
|
|
473
|
+
const userMessage = promptToClaude(params);
|
|
474
|
+
const promptUuid = randomUUID();
|
|
475
|
+
userMessage.uuid = promptUuid;
|
|
476
|
+
// Local-only commands (e.g. `/clear`) return a result without replaying the
|
|
477
|
+
// user message, so the consumer can't promote the turn from the echo.
|
|
478
|
+
const firstText = params.prompt[0]?.type === "text" ? params.prompt[0].text : "";
|
|
479
|
+
const isLocalOnlyCommand = firstText.startsWith("/") && LOCAL_ONLY_COMMANDS.has(firstText.split(" ", 1)[0]);
|
|
480
|
+
// Each prompt is a Turn whose deferred the persistent consumer settles once
|
|
481
|
+
// the turn's outcome is known. `prompt()` owns no loop: it enqueues the
|
|
482
|
+
// turn, pushes the user message onto the streaming input, makes sure the
|
|
483
|
+
// consumer is running, and awaits the deferred.
|
|
484
|
+
const turn = {
|
|
485
|
+
promptUuid,
|
|
486
|
+
isLocalOnlyCommand,
|
|
487
|
+
settled: false,
|
|
488
|
+
resolve: () => { },
|
|
489
|
+
reject: () => { },
|
|
469
490
|
};
|
|
491
|
+
const response = new Promise((resolve, reject) => {
|
|
492
|
+
turn.resolve = resolve;
|
|
493
|
+
turn.reject = reject;
|
|
494
|
+
});
|
|
495
|
+
session.turnQueue ??= [];
|
|
496
|
+
session.turnQueue.push(turn);
|
|
497
|
+
session.input.push(userMessage);
|
|
498
|
+
this.ensureConsumer(session, params.sessionId);
|
|
499
|
+
return response;
|
|
500
|
+
}
|
|
501
|
+
/** Lazily start the per-session consumer that drains the SDK query stream for
|
|
502
|
+
* the session's whole life. Idempotent: only the first `prompt()` starts it. */
|
|
503
|
+
ensureConsumer(session, sessionId) {
|
|
504
|
+
if (session.consumer) {
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
// Wake-up channel so cancel() can force the consumer to settle the active
|
|
508
|
+
// turn "cancelled" even when query.next() is wedged and never yields again
|
|
509
|
+
// (issue #680). The consumer re-arms it after each fire.
|
|
510
|
+
session.cancelController = new AbortController();
|
|
511
|
+
session.consumer = this.runConsumer(session, { sessionId });
|
|
512
|
+
session.consumer.catch((error) => {
|
|
513
|
+
this.logger.error(`Session ${sessionId}: consumer terminated unexpectedly: ${error}`);
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
/** The single, long-lived consumer of the SDK query stream for a session. It
|
|
517
|
+
* forwards every message as ACP `sessionUpdate`s (so background/between-turn
|
|
518
|
+
* output streams live, not just while a prompt is awaiting) and settles each
|
|
519
|
+
* Turn's deferred when that turn ends. Replaces the per-prompt message loop;
|
|
520
|
+
* `params` only carries the (session-invariant) `sessionId`. */
|
|
521
|
+
async runConsumer(session, params) {
|
|
522
|
+
// Per-turn scratch, reset whenever a turn becomes active. Kept as consumer
|
|
523
|
+
// locals (rather than per-Turn fields) because they describe the message
|
|
524
|
+
// currently being processed, which is sequential — exactly one turn is
|
|
525
|
+
// active at a time. Mirrors the locals the old per-prompt loop held.
|
|
470
526
|
let lastAssistantTotalUsage = null;
|
|
471
527
|
let lastAssistantUsage = null;
|
|
472
528
|
let lastAssistantModel = null;
|
|
473
529
|
// When the Claude SDK classifies a turn as failed (e.g. rate limit, auth
|
|
474
530
|
// problem, billing), it sets a categorical `error` field on the
|
|
475
|
-
// `SDKAssistantMessage` that precedes the final `result` message. We
|
|
476
|
-
//
|
|
477
|
-
//
|
|
478
|
-
// pattern-matching on the human-readable message text.
|
|
531
|
+
// `SDKAssistantMessage` that precedes the final `result` message. We capture
|
|
532
|
+
// it here so the subsequent `RequestError.internalError` can forward it to
|
|
533
|
+
// clients as structured `data`, sparing them from pattern-matching on text.
|
|
479
534
|
let lastAssistantError;
|
|
480
535
|
// When a streaming classifier refuses a turn, the assistant message carries
|
|
481
536
|
// stop_reason "refusal" and structured stop_details. We capture the
|
|
482
|
-
// human-readable explanation
|
|
483
|
-
// to the user (the refused assistant message itself usually has no content)
|
|
484
|
-
// and report ACP's dedicated `refusal` stop reason.
|
|
537
|
+
// human-readable explanation so the terminal `result` can surface it.
|
|
485
538
|
let lastRefusalExplanation = null;
|
|
486
539
|
// Tracks whether we're inside a compaction. The SDK emits the terminal
|
|
487
540
|
// `status` (compact_result success/failed) twice for a single failed
|
|
488
541
|
// compaction, and the two messages are indistinguishable — so we report the
|
|
489
|
-
// outcome only while a compaction is in progress, then clear this.
|
|
490
|
-
// `compacting` status sets it again, so every distinct compaction (e.g.
|
|
491
|
-
// repeated auto-compactions in a long turn) is still shown.
|
|
542
|
+
// outcome only while a compaction is in progress, then clear this.
|
|
492
543
|
let compactionInProgress = false;
|
|
493
|
-
//
|
|
494
|
-
//
|
|
495
|
-
//
|
|
496
|
-
//
|
|
497
|
-
// consolidated assistant message and in the persisted transcript — so a turn
|
|
498
|
-
// keeps the same ACP `messageId` whether it is streamed live or replayed
|
|
499
|
-
// from history. The per-event uuid is unique per event and never persisted.
|
|
500
|
-
// A single value suffices because every streaming partial arrives with
|
|
501
|
-
// `parent_tool_use_id === null` (subagent work is folded into tool-result
|
|
502
|
-
// messages, never surfaced as partial streams).
|
|
544
|
+
// Anthropic API message id of the assistant message currently being
|
|
545
|
+
// streamed, captured from `message_start` so the streamed chunks that follow
|
|
546
|
+
// (whose delta events don't carry it) can all be tagged with the same,
|
|
547
|
+
// replay-stable id.
|
|
503
548
|
let currentStreamMessageId;
|
|
504
|
-
// Per-message-id record of which assistant content actually streamed live
|
|
505
|
-
// `stream_event` deltas, split by block type
|
|
506
|
-
//
|
|
507
|
-
//
|
|
508
|
-
//
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
//
|
|
512
|
-
//
|
|
513
|
-
// a gateway that streams text but not thinking (or vice versa) doesn't lose
|
|
514
|
-
// the un-streamed block. Only top-level (`parent_tool_use_id === null`)
|
|
515
|
-
// streams are recorded — subagent text is never streamed and must stay
|
|
516
|
-
// filtered, as it is internal to the tool call.
|
|
517
|
-
const streamedTextIds = new Set();
|
|
518
|
-
const streamedThinkingIds = new Set();
|
|
519
|
-
const userMessage = promptToClaude(params);
|
|
520
|
-
const promptUuid = randomUUID();
|
|
521
|
-
userMessage.uuid = promptUuid;
|
|
522
|
-
// These local-only commands return a result without replaying the user
|
|
523
|
-
// message. Mark promptReplayed=true so their result isn't consumed as a
|
|
524
|
-
// background task result.
|
|
525
|
-
const firstText = params.prompt[0]?.type === "text" ? params.prompt[0].text : "";
|
|
526
|
-
const isLocalOnlyCommand = firstText.startsWith("/") && LOCAL_ONLY_COMMANDS.has(firstText.split(" ", 1)[0]);
|
|
527
|
-
if (session.promptRunning) {
|
|
528
|
-
session.input.push(userMessage);
|
|
529
|
-
const order = session.nextPendingOrder++;
|
|
530
|
-
const cancelled = await new Promise((resolve) => {
|
|
531
|
-
session.pendingMessages.set(promptUuid, { resolve, order });
|
|
532
|
-
});
|
|
533
|
-
if (cancelled) {
|
|
534
|
-
return { stopReason: "cancelled" };
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
else {
|
|
538
|
-
session.input.push(userMessage);
|
|
539
|
-
}
|
|
540
|
-
session.promptRunning = true;
|
|
541
|
-
let handedOff = false;
|
|
542
|
-
let errored = false;
|
|
549
|
+
// Per-message-id record of which assistant content actually streamed live
|
|
550
|
+
// via `stream_event` deltas, split by block type, so the consolidated
|
|
551
|
+
// `assistant` message can drop the duplicate blocks that already reached the
|
|
552
|
+
// client as chunks while still forwarding any that a non-streaming gateway
|
|
553
|
+
// delivered only as an assembled block.
|
|
554
|
+
let streamedTextIds = new Set();
|
|
555
|
+
let streamedThinkingIds = new Set();
|
|
556
|
+
// Stop reason accumulated for the active turn (result subtype, refusal,
|
|
557
|
+
// max_tokens, …). Reset per turn; read when the turn settles at idle.
|
|
543
558
|
let stopReason = "end_turn";
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
559
|
+
const resetTurnScratch = () => {
|
|
560
|
+
lastAssistantTotalUsage = null;
|
|
561
|
+
lastAssistantUsage = null;
|
|
562
|
+
lastAssistantModel = null;
|
|
563
|
+
lastAssistantError = undefined;
|
|
564
|
+
lastRefusalExplanation = null;
|
|
565
|
+
compactionInProgress = false;
|
|
566
|
+
currentStreamMessageId = undefined;
|
|
567
|
+
streamedTextIds = new Set();
|
|
568
|
+
streamedThinkingIds = new Set();
|
|
569
|
+
stopReason = "end_turn";
|
|
570
|
+
session.accumulatedUsage = {
|
|
571
|
+
inputTokens: 0,
|
|
572
|
+
outputTokens: 0,
|
|
573
|
+
cachedReadTokens: 0,
|
|
574
|
+
cachedWriteTokens: 0,
|
|
575
|
+
};
|
|
576
|
+
};
|
|
577
|
+
/** Promote a queued turn to active: it becomes the one output is attributed
|
|
578
|
+
* to, and its scratch starts fresh. Clears the cancelled flag so a turn
|
|
579
|
+
* enqueued after a prior cancel isn't treated as cancelled. Also clears any
|
|
580
|
+
* leftover orphan-skip count: since the SDK echoes/runs input FIFO, every
|
|
581
|
+
* orphan from a prior cancel has already arrived by the time a live turn
|
|
582
|
+
* activates, so a non-zero remainder means the SDK dropped a queued turn on
|
|
583
|
+
* interrupt (no orphan emitted) — drop the stale count so a later echo-less
|
|
584
|
+
* result isn't wrongly skipped. */
|
|
585
|
+
const activateTurn = (turn) => {
|
|
586
|
+
session.activeTurn = turn;
|
|
587
|
+
session.cancelled = false;
|
|
588
|
+
session.pendingOrphanResults = 0;
|
|
589
|
+
resetTurnScratch();
|
|
590
|
+
};
|
|
591
|
+
/** Ensure there is an active turn before a user-turn result that carries no
|
|
592
|
+
* echo to activate it, by promoting the queue head. Most turns are
|
|
593
|
+
* activated by their replayed user message before their result, but some
|
|
594
|
+
* legitimately produce a result with no matching echo: local-only commands
|
|
595
|
+
* (e.g. `/context`) and compaction (`/compact`, whose only user messages
|
|
596
|
+
* are the generated summary and a `<local-command-stdout>` replay — neither
|
|
597
|
+
* carries the prompt's uuid). Promoting the head settles those.
|
|
598
|
+
*
|
|
599
|
+
* But an echo-less result can also be an ORPHAN: cancel() settles+removes a
|
|
600
|
+
* queued turn whose user message was already pushed, so the SDK still runs
|
|
601
|
+
* it and emits a result with no uuid to match. Promoting the head for an
|
|
602
|
+
* orphan would misattribute its stop reason/usage to an unrelated later
|
|
603
|
+
* prompt. `session.pendingOrphanResults` counts exactly how many such
|
|
604
|
+
* orphans are still expected (FIFO, they arrive before any live turn's
|
|
605
|
+
* result), so we skip those and only promote once the count is drained. */
|
|
606
|
+
const ensureActiveTurn = () => {
|
|
607
|
+
if (session.activeTurn) {
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
const head = (session.turnQueue ?? []).find((t) => !t.settled);
|
|
611
|
+
if (!head) {
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
if ((session.pendingOrphanResults ?? 0) > 0) {
|
|
615
|
+
session.pendingOrphanResults--;
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
activateTurn(head);
|
|
619
|
+
};
|
|
620
|
+
/** Settle the active turn's deferred exactly once, disarm the force-cancel
|
|
621
|
+
* backstop (the turn is over), and drop it from the queue. */
|
|
622
|
+
const settleActive = (result) => {
|
|
623
|
+
const turn = session.activeTurn;
|
|
624
|
+
if (!turn || turn.settled) {
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
turn.settled = true;
|
|
628
|
+
if (session.forceCancelTimer) {
|
|
629
|
+
clearTimeout(session.forceCancelTimer);
|
|
630
|
+
session.forceCancelTimer = undefined;
|
|
631
|
+
}
|
|
632
|
+
session.turnQueue = (session.turnQueue ?? []).filter((t) => t !== turn);
|
|
633
|
+
session.activeTurn = null;
|
|
634
|
+
turn.resolve(result);
|
|
635
|
+
};
|
|
636
|
+
/** Reject the active turn (auth required, error result, …) without tearing
|
|
637
|
+
* down the consumer: the stream continues to idle and later turns proceed. */
|
|
638
|
+
const failActive = (error) => {
|
|
639
|
+
if (session.forceCancelTimer) {
|
|
640
|
+
clearTimeout(session.forceCancelTimer);
|
|
641
|
+
session.forceCancelTimer = undefined;
|
|
642
|
+
}
|
|
643
|
+
const turn = session.activeTurn;
|
|
644
|
+
if (!turn || turn.settled) {
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
turn.settled = true;
|
|
648
|
+
session.turnQueue = (session.turnQueue ?? []).filter((t) => t !== turn);
|
|
649
|
+
session.activeTurn = null;
|
|
650
|
+
turn.reject(error);
|
|
651
|
+
};
|
|
652
|
+
/** Reject every in-flight turn — used when the stream dies. */
|
|
653
|
+
const failAllTurns = (error) => {
|
|
654
|
+
if (session.forceCancelTimer) {
|
|
655
|
+
clearTimeout(session.forceCancelTimer);
|
|
656
|
+
session.forceCancelTimer = undefined;
|
|
657
|
+
}
|
|
658
|
+
const turns = session.activeTurn
|
|
659
|
+
? [session.activeTurn, ...(session.turnQueue ?? []).filter((t) => t !== session.activeTurn)]
|
|
660
|
+
: [...(session.turnQueue ?? [])];
|
|
661
|
+
session.activeTurn = null;
|
|
662
|
+
session.turnQueue = [];
|
|
663
|
+
for (const turn of turns) {
|
|
664
|
+
if (!turn.settled) {
|
|
665
|
+
turn.settled = true;
|
|
666
|
+
turn.reject(error);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
// The wake-up channel cancel()/teardown aborts to force the active turn to
|
|
671
|
+
// settle "cancelled" even when query.next() is wedged (issue #680). Re-armed
|
|
672
|
+
// after each fire so the consumer keeps serving later turns.
|
|
673
|
+
let cancelController = session.cancelController;
|
|
551
674
|
try {
|
|
552
675
|
while (true) {
|
|
553
676
|
const nextMessage = session.query.next();
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
677
|
+
// Fresh abort listener per iteration, removed when next() wins, so a
|
|
678
|
+
// long-lived session doesn't accumulate listeners on one signal.
|
|
679
|
+
let onAbort;
|
|
680
|
+
const abortRace = new Promise((resolve) => {
|
|
681
|
+
onAbort = () => resolve("abort");
|
|
682
|
+
cancelController.signal.addEventListener("abort", onAbort, { once: true });
|
|
683
|
+
});
|
|
684
|
+
const raced = await Promise.race([
|
|
685
|
+
nextMessage.then((result) => ({ kind: "message", result })),
|
|
686
|
+
abortRace,
|
|
687
|
+
]);
|
|
688
|
+
cancelController.signal.removeEventListener("abort", onAbort);
|
|
689
|
+
if (raced === "abort") {
|
|
690
|
+
// cancel()/teardown woke us. Abandon the in-flight next() (swallowing
|
|
691
|
+
// any later rejection so it can't surface as unhandled) and settle the
|
|
692
|
+
// active turn "cancelled" per the ACP contract. If the session is
|
|
693
|
+
// being torn down, stop; otherwise re-arm and keep consuming.
|
|
560
694
|
void nextMessage.catch(() => { });
|
|
561
|
-
|
|
695
|
+
settleActive({ stopReason: "cancelled" });
|
|
696
|
+
if (!this.sessions[params.sessionId]) {
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
cancelController = new AbortController();
|
|
700
|
+
session.cancelController = cancelController;
|
|
701
|
+
continue;
|
|
562
702
|
}
|
|
563
|
-
const { value: message, done } =
|
|
703
|
+
const { value: message, done } = raced.result;
|
|
564
704
|
if (done || !message) {
|
|
565
|
-
|
|
566
|
-
|
|
705
|
+
// The stream ended. Settle the in-flight turns FIRST, then release the
|
|
706
|
+
// stream resources — same order as the error paths (failAllTurns before
|
|
707
|
+
// closeQueryStream). Settling is the user-facing contract; resource
|
|
708
|
+
// release is best-effort cleanup, so a throw there must not pre-empt a
|
|
709
|
+
// turn's real outcome.
|
|
710
|
+
//
|
|
711
|
+
// Settle the turn that was in flight so its prompt() doesn't hang:
|
|
712
|
+
// cancelled if a cancel is pending, otherwise the accumulated outcome.
|
|
713
|
+
settleActive(session.cancelled
|
|
714
|
+
? { stopReason: "cancelled" }
|
|
715
|
+
: { stopReason, usage: sessionUsage(session) });
|
|
716
|
+
// Queued turns the SDK never started never ran, so reject them rather
|
|
717
|
+
// than reporting a success (end_turn) — or a misleading "cancelled" —
|
|
718
|
+
// for a prompt that produced no output. (A cancel already settled the
|
|
719
|
+
// turns that were queued at cancel time and removed them, so anything
|
|
720
|
+
// still here was enqueued afterward and was not part of the cancel.)
|
|
721
|
+
for (const queued of [...(session.turnQueue ?? [])]) {
|
|
722
|
+
if (!queued.settled) {
|
|
723
|
+
queued.settled = true;
|
|
724
|
+
queued.reject(RequestError.internalError(undefined, SESSION_ENDED_MESSAGE));
|
|
725
|
+
}
|
|
567
726
|
}
|
|
568
|
-
|
|
727
|
+
session.turnQueue = [];
|
|
728
|
+
// The query iterator can't be revived, so close the session's stream
|
|
729
|
+
// (marks queryClosed, drops the consumer handle, releases the dead
|
|
730
|
+
// subprocess/settings resources) — a later prompt() then rejects up
|
|
731
|
+
// front rather than restarting a consumer on the exhausted stream.
|
|
732
|
+
this.closeQueryStream(session);
|
|
733
|
+
return;
|
|
569
734
|
}
|
|
570
735
|
if (session.emitRawSDKMessages &&
|
|
571
736
|
shouldEmitRawMessage(session.emitRawSDKMessages, message)) {
|
|
@@ -663,10 +828,20 @@ export class ClaudeAcpAgent {
|
|
|
663
828
|
}
|
|
664
829
|
case "session_state_changed": {
|
|
665
830
|
if (message.state === "idle") {
|
|
831
|
+
// A non-cancelled turn already settled at its terminal
|
|
832
|
+
// `result` (issue #773), so this trailing `idle` is just
|
|
833
|
+
// absorbed. We must NOT settle `activeTurn` here in that case:
|
|
834
|
+
// `idle` carries no turn identity, and it can lag (the SDK
|
|
835
|
+
// flushes held-back results / drains background agents first),
|
|
836
|
+
// so by the time it arrives the SDK may have echoed the NEXT
|
|
837
|
+
// turn and activated it — settling now would resolve that new
|
|
838
|
+
// turn prematurely with end_turn and ~zero usage, dropping its
|
|
839
|
+
// real result. Only a cancelled turn relies on `idle`: its
|
|
840
|
+
// `result` is dropped at the `session.cancelled` guard, so it
|
|
841
|
+
// never settles at a result and must settle here.
|
|
666
842
|
if (session.cancelled) {
|
|
667
|
-
stopReason
|
|
843
|
+
settleActive({ stopReason: "cancelled" });
|
|
668
844
|
}
|
|
669
|
-
return { stopReason, usage: sessionUsage(session) };
|
|
670
845
|
}
|
|
671
846
|
break;
|
|
672
847
|
}
|
|
@@ -764,6 +939,24 @@ export class ClaudeAcpAgent {
|
|
|
764
939
|
});
|
|
765
940
|
break;
|
|
766
941
|
}
|
|
942
|
+
case "informational": {
|
|
943
|
+
// Free-form notice from the SDK (e.g. why a UserPromptSubmit/Stop
|
|
944
|
+
// hook blocked continuation). Surface the text so the user sees it
|
|
945
|
+
// instead of a silent stop. ACP's agent_message_chunk has no
|
|
946
|
+
// severity field, so fold the level into the text for the more
|
|
947
|
+
// prominent levels ('info' is transcript-only noise — leave plain).
|
|
948
|
+
const text = message.level === "info"
|
|
949
|
+
? message.content
|
|
950
|
+
: `**${message.level[0].toUpperCase()}${message.level.slice(1)}:** ${message.content}`;
|
|
951
|
+
await this.client.sessionUpdate({
|
|
952
|
+
sessionId: message.session_id,
|
|
953
|
+
update: {
|
|
954
|
+
sessionUpdate: "agent_message_chunk",
|
|
955
|
+
content: { type: "text", text },
|
|
956
|
+
},
|
|
957
|
+
});
|
|
958
|
+
break;
|
|
959
|
+
}
|
|
767
960
|
case "hook_started":
|
|
768
961
|
case "hook_progress":
|
|
769
962
|
case "hook_response":
|
|
@@ -773,6 +966,11 @@ export class ClaudeAcpAgent {
|
|
|
773
966
|
case "task_progress":
|
|
774
967
|
case "task_updated":
|
|
775
968
|
break;
|
|
969
|
+
case "worker_shutting_down":
|
|
970
|
+
// A Remote Control worker announced a graceful teardown. This is a
|
|
971
|
+
// live-tail signal for remote clients to explain why a session went
|
|
972
|
+
// away; it's not meaningful for a local stdio ACP session.
|
|
973
|
+
break;
|
|
776
974
|
case "elicitation_complete": {
|
|
777
975
|
// A url-mode MCP elicitation finished server-side. Let the client
|
|
778
976
|
// dismiss any UI it opened for it. Only meaningful when the
|
|
@@ -802,11 +1000,32 @@ export class ClaudeAcpAgent {
|
|
|
802
1000
|
}
|
|
803
1001
|
break;
|
|
804
1002
|
case "result": {
|
|
805
|
-
//
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
1003
|
+
// Task-notification followups are autonomous work triggered by a
|
|
1004
|
+
// task-notification system message, not by the user's prompt.
|
|
1005
|
+
// They should not influence the user-turn lifecycle (stop reason,
|
|
1006
|
+
// slash-command output forwarding) but their cost is real.
|
|
1007
|
+
const isTaskNotification = message.origin?.kind === "task-notification";
|
|
1008
|
+
// A user-turn result needs an active turn so its stop reason is
|
|
1009
|
+
// attributed and the turn settles at idle. Local-only commands carry
|
|
1010
|
+
// no user-message echo to promote them, so do it here from the head.
|
|
1011
|
+
// Promote BEFORE accumulating usage, since activation resets the
|
|
1012
|
+
// accumulator — promoting after would discard this result's tokens.
|
|
1013
|
+
if (!isTaskNotification) {
|
|
1014
|
+
ensureActiveTurn();
|
|
1015
|
+
}
|
|
1016
|
+
// Accumulate usage into the user turn's tally. Skip task-notification
|
|
1017
|
+
// followups: their cost is real but is reported separately via the
|
|
1018
|
+
// usage_update below, and `session.accumulatedUsage` is only reset on
|
|
1019
|
+
// turn activation — so folding a task-notification result that lands
|
|
1020
|
+
// after the next turn is active (but before it settles) would leak
|
|
1021
|
+
// those tokens into that turn's PromptResponse.usage.
|
|
1022
|
+
if (!isTaskNotification) {
|
|
1023
|
+
session.accumulatedUsage.inputTokens += message.usage.input_tokens;
|
|
1024
|
+
session.accumulatedUsage.outputTokens += message.usage.output_tokens;
|
|
1025
|
+
session.accumulatedUsage.cachedReadTokens += message.usage.cache_read_input_tokens;
|
|
1026
|
+
session.accumulatedUsage.cachedWriteTokens +=
|
|
1027
|
+
message.usage.cache_creation_input_tokens;
|
|
1028
|
+
}
|
|
810
1029
|
const matchingModelUsage = lastAssistantModel
|
|
811
1030
|
? getMatchingModelUsage(message.modelUsage, lastAssistantModel)
|
|
812
1031
|
: null;
|
|
@@ -817,11 +1036,6 @@ export class ClaudeAcpAgent {
|
|
|
817
1036
|
if (matchingModelUsage) {
|
|
818
1037
|
session.contextWindowSize = matchingModelUsage.contextWindow;
|
|
819
1038
|
}
|
|
820
|
-
// Task-notification followups are autonomous work triggered by a
|
|
821
|
-
// task-notification system message, not by the user's prompt.
|
|
822
|
-
// They should not influence the user-turn lifecycle (stop reason,
|
|
823
|
-
// slash-command output forwarding) but their cost is real.
|
|
824
|
-
const isTaskNotification = message.origin?.kind === "task-notification";
|
|
825
1039
|
// Send usage_update notification
|
|
826
1040
|
if (lastAssistantTotalUsage !== null) {
|
|
827
1041
|
await this.client.sessionUpdate({
|
|
@@ -863,12 +1077,14 @@ export class ClaudeAcpAgent {
|
|
|
863
1077
|
});
|
|
864
1078
|
}
|
|
865
1079
|
stopReason = "refusal";
|
|
1080
|
+
settleActive({ stopReason: "refusal", usage: sessionUsage(session) });
|
|
866
1081
|
break;
|
|
867
1082
|
}
|
|
868
1083
|
switch (message.subtype) {
|
|
869
1084
|
case "success": {
|
|
870
1085
|
if (message.result.includes("Please run /login")) {
|
|
871
|
-
|
|
1086
|
+
failActive(RequestError.authRequired());
|
|
1087
|
+
break;
|
|
872
1088
|
}
|
|
873
1089
|
if (message.stop_reason === "max_tokens") {
|
|
874
1090
|
if (!isTaskNotification) {
|
|
@@ -877,13 +1093,14 @@ export class ClaudeAcpAgent {
|
|
|
877
1093
|
break;
|
|
878
1094
|
}
|
|
879
1095
|
if (message.is_error) {
|
|
880
|
-
|
|
1096
|
+
failActive(RequestError.internalError(errorKindData(lastAssistantError), message.result));
|
|
1097
|
+
break;
|
|
881
1098
|
}
|
|
882
1099
|
// For local-only commands (no model invocation), the result
|
|
883
1100
|
// text is the command output — forward it to the client.
|
|
884
1101
|
// Task-notification followups never originate from a user
|
|
885
1102
|
// slash command, so skip the forwarding for them.
|
|
886
|
-
if (isLocalOnlyCommand && !isTaskNotification) {
|
|
1103
|
+
if (session.activeTurn?.isLocalOnlyCommand && !isTaskNotification) {
|
|
887
1104
|
for (const notification of toAcpNotifications(message.result, "assistant", params.sessionId, session.toolUseCache, this.client, this.logger)) {
|
|
888
1105
|
await this.client.sessionUpdate(notification);
|
|
889
1106
|
}
|
|
@@ -898,7 +1115,8 @@ export class ClaudeAcpAgent {
|
|
|
898
1115
|
break;
|
|
899
1116
|
}
|
|
900
1117
|
if (message.is_error) {
|
|
901
|
-
|
|
1118
|
+
failActive(RequestError.internalError(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype));
|
|
1119
|
+
break;
|
|
902
1120
|
}
|
|
903
1121
|
if (!isTaskNotification) {
|
|
904
1122
|
stopReason = "end_turn";
|
|
@@ -909,7 +1127,8 @@ export class ClaudeAcpAgent {
|
|
|
909
1127
|
case "error_max_turns":
|
|
910
1128
|
case "error_max_structured_output_retries":
|
|
911
1129
|
if (message.is_error) {
|
|
912
|
-
|
|
1130
|
+
failActive(RequestError.internalError(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype));
|
|
1131
|
+
break;
|
|
913
1132
|
}
|
|
914
1133
|
if (!isTaskNotification) {
|
|
915
1134
|
stopReason = "max_turn_requests";
|
|
@@ -919,6 +1138,16 @@ export class ClaudeAcpAgent {
|
|
|
919
1138
|
unreachable(message, this.logger);
|
|
920
1139
|
break;
|
|
921
1140
|
}
|
|
1141
|
+
// Settle the user turn at its terminal result so the client unlocks
|
|
1142
|
+
// as soon as the answer is done, rather than waiting for the SDK's
|
|
1143
|
+
// trailing `idle` (which can lag while background work runs — issue
|
|
1144
|
+
// #773). The consumer keeps draining afterward (absorbing idle and
|
|
1145
|
+
// forwarding any background output). is_error/auth already settled
|
|
1146
|
+
// via failActive; cancellation is left to the idle/abort path.
|
|
1147
|
+
// settleActive is idempotent, so a duplicate idle is a no-op.
|
|
1148
|
+
if (!isTaskNotification && !session.cancelled) {
|
|
1149
|
+
settleActive({ stopReason, usage: sessionUsage(session) });
|
|
1150
|
+
}
|
|
922
1151
|
break;
|
|
923
1152
|
}
|
|
924
1153
|
case "stream_event": {
|
|
@@ -1002,36 +1231,49 @@ export class ClaudeAcpAgent {
|
|
|
1002
1231
|
}
|
|
1003
1232
|
case "user":
|
|
1004
1233
|
case "assistant": {
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
//
|
|
1009
|
-
// consolidated message carries both ids, so this is where we learn
|
|
1010
|
-
// the uuid that the SDK's rewind/resume APIs key on for the id we
|
|
1011
|
-
// hand clients. Not read yet (see Session.messageIdToUuid).
|
|
1234
|
+
// Record the ACP messageId -> SDK uuid mapping for this message
|
|
1235
|
+
// (including replays). The consolidated message carries both ids, so
|
|
1236
|
+
// this is where we learn the uuid the SDK's rewind/resume APIs key on
|
|
1237
|
+
// for the id we hand clients. Not read yet (see messageIdToUuid).
|
|
1012
1238
|
const mappedMessageId = messageIdForGrouping(message);
|
|
1013
1239
|
if (mappedMessageId && typeof message.uuid === "string" && message.uuid.length > 0) {
|
|
1014
1240
|
session.messageIdToUuid.set(mappedMessageId, message.uuid);
|
|
1015
1241
|
}
|
|
1016
|
-
//
|
|
1242
|
+
// A replayed user message echoes a queued turn back in submission
|
|
1243
|
+
// order. The first echo promotes that turn to active; if a different
|
|
1244
|
+
// turn is still active, it is handed off (settled end_turn) first.
|
|
1245
|
+
// Done before the `cancelled` guard so a turn enqueued after a cancel
|
|
1246
|
+
// is still promoted — activateTurn() clears the flag. The turn's own
|
|
1247
|
+
// echo is then dropped from the feed (the client already shows it).
|
|
1017
1248
|
if (message.type === "user" && "uuid" in message && message.uuid) {
|
|
1018
|
-
|
|
1249
|
+
const queued = (session.turnQueue ?? []).find((t) => t.promptUuid === message.uuid && !t.settled);
|
|
1250
|
+
if (queued) {
|
|
1251
|
+
// Only (re)activate if this isn't already the active turn — a
|
|
1252
|
+
// turn promoted early (e.g. by a result that preceded its echo)
|
|
1253
|
+
// must not have its accumulated usage reset by its own echo.
|
|
1254
|
+
if (session.activeTurn !== queued) {
|
|
1255
|
+
if (session.activeTurn) {
|
|
1256
|
+
// Hand off the previous turn. If a cancel is pending for it
|
|
1257
|
+
// (its trailing idle hasn't arrived yet), settle it
|
|
1258
|
+
// "cancelled" per the ACP contract rather than "end_turn" —
|
|
1259
|
+
// otherwise a cancel followed quickly by the next prompt
|
|
1260
|
+
// would report the cancelled turn as a normal completion.
|
|
1261
|
+
settleActive(session.cancelled
|
|
1262
|
+
? { stopReason: "cancelled" }
|
|
1263
|
+
: { stopReason: "end_turn", usage: sessionUsage(session) });
|
|
1264
|
+
}
|
|
1265
|
+
activateTurn(queued);
|
|
1266
|
+
}
|
|
1019
1267
|
break;
|
|
1020
1268
|
}
|
|
1021
|
-
const pending = session.pendingMessages.get(message.uuid);
|
|
1022
|
-
if (pending) {
|
|
1023
|
-
pending.resolve(false);
|
|
1024
|
-
session.pendingMessages.delete(message.uuid);
|
|
1025
|
-
handedOff = true;
|
|
1026
|
-
// the current loop stops with end_turn,
|
|
1027
|
-
// the loop of the next prompt continues running
|
|
1028
|
-
return { stopReason: "end_turn", usage: sessionUsage(session) };
|
|
1029
|
-
}
|
|
1030
1269
|
if ("isReplay" in message && message.isReplay) {
|
|
1031
|
-
//
|
|
1270
|
+
// Unrelated replay (e.g. the echo of an already-settled turn).
|
|
1032
1271
|
break;
|
|
1033
1272
|
}
|
|
1034
1273
|
}
|
|
1274
|
+
if (session.cancelled) {
|
|
1275
|
+
break;
|
|
1276
|
+
}
|
|
1035
1277
|
// Snapshot the latest top-level assistant usage and model so the
|
|
1036
1278
|
// next `result` can emit a usage_update tied to the right context
|
|
1037
1279
|
// window. Subagent messages are excluded to keep the snapshot
|
|
@@ -1096,7 +1338,8 @@ export class ClaudeAcpAgent {
|
|
|
1096
1338
|
message.message.content.length === 1 &&
|
|
1097
1339
|
message.message.content[0].type === "text" &&
|
|
1098
1340
|
message.message.content[0].text.includes("Please run /login")) {
|
|
1099
|
-
|
|
1341
|
+
failActive(RequestError.authRequired());
|
|
1342
|
+
break;
|
|
1100
1343
|
}
|
|
1101
1344
|
let content;
|
|
1102
1345
|
if (message.type === "assistant" && message.parent_tool_use_id === null) {
|
|
@@ -1189,83 +1432,36 @@ export class ClaudeAcpAgent {
|
|
|
1189
1432
|
break;
|
|
1190
1433
|
}
|
|
1191
1434
|
}
|
|
1192
|
-
|
|
1435
|
+
// `while (true)` only exits via the `done` return above or the catch
|
|
1436
|
+
// below, so there is no normal fall-through here.
|
|
1193
1437
|
}
|
|
1194
1438
|
catch (error) {
|
|
1195
|
-
|
|
1196
|
-
//
|
|
1197
|
-
//
|
|
1198
|
-
// the
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
this.logger.error(`Session ${params.sessionId}: drained ${MAX_DRAIN} messages after error without observing idle`);
|
|
1213
|
-
}
|
|
1214
|
-
}
|
|
1215
|
-
}
|
|
1216
|
-
catch (drainErr) {
|
|
1217
|
-
this.logger.error(`Session ${params.sessionId}: failed to drain query after prompt error:`, drainErr);
|
|
1218
|
-
}
|
|
1219
|
-
if (error instanceof RequestError || !(error instanceof Error)) {
|
|
1220
|
-
throw error;
|
|
1221
|
-
}
|
|
1222
|
-
const message = error.message;
|
|
1223
|
-
if (message.includes("ProcessTransport") ||
|
|
1224
|
-
message.includes("terminated process") ||
|
|
1225
|
-
message.includes("process exited with") ||
|
|
1226
|
-
message.includes("process terminated by signal") ||
|
|
1227
|
-
message.includes("Failed to write to process stdin")) {
|
|
1439
|
+
// The query stream itself died (a transport/process error surfaced from
|
|
1440
|
+
// query.next()). Turn-level failures (auth, error results) are handled
|
|
1441
|
+
// inline via failActive and never reach here. Reject every in-flight turn;
|
|
1442
|
+
// if the process is gone, tear the session down so the client starts fresh.
|
|
1443
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1444
|
+
const processDied = error instanceof Error &&
|
|
1445
|
+
(message.includes("ProcessTransport") ||
|
|
1446
|
+
message.includes("terminated process") ||
|
|
1447
|
+
message.includes("process exited with") ||
|
|
1448
|
+
message.includes("process terminated by signal") ||
|
|
1449
|
+
message.includes("Failed to write to process stdin"));
|
|
1450
|
+
// Either way the query iterator is finished and the consumer is exiting,
|
|
1451
|
+
// so release its resources via closeQueryStream (idempotent). A process
|
|
1452
|
+
// death is unrecoverable, so additionally evict the session so the client
|
|
1453
|
+
// starts fresh; other stream errors keep the session so prompt()/cancel()
|
|
1454
|
+
// can answer with a clear "session ended" error.
|
|
1455
|
+
if (processDied) {
|
|
1228
1456
|
this.logger.error(`Session ${params.sessionId}: Claude Agent process died: ${message}`);
|
|
1229
|
-
session.
|
|
1230
|
-
|
|
1457
|
+
failAllTurns(RequestError.internalError(undefined, "The Claude Agent process exited unexpectedly. Please start a new session."));
|
|
1458
|
+
this.closeQueryStream(session);
|
|
1231
1459
|
delete this.sessions[params.sessionId];
|
|
1232
|
-
throw RequestError.internalError(undefined, "The Claude Agent process exited unexpectedly. Please start a new session.");
|
|
1233
1460
|
}
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
// — so disarm the force-cancel backstop and release the wake-up channel
|
|
1239
|
-
// (only if we still own it; a handoff installs the next prompt's).
|
|
1240
|
-
if (session.forceCancelTimer) {
|
|
1241
|
-
clearTimeout(session.forceCancelTimer);
|
|
1242
|
-
session.forceCancelTimer = undefined;
|
|
1243
|
-
}
|
|
1244
|
-
if (session.cancelController === cancelController) {
|
|
1245
|
-
session.cancelController = undefined;
|
|
1246
|
-
}
|
|
1247
|
-
if (!handedOff) {
|
|
1248
|
-
session.promptRunning = false;
|
|
1249
|
-
if (errored) {
|
|
1250
|
-
// The query stream was just drained — handing pending prompts off
|
|
1251
|
-
// onto it would let them race with the recovery. Cancel them so
|
|
1252
|
-
// each waiting prompt() returns stopReason: "cancelled" and the
|
|
1253
|
-
// client can decide whether to retry.
|
|
1254
|
-
for (const pending of session.pendingMessages.values()) {
|
|
1255
|
-
pending.resolve(true);
|
|
1256
|
-
}
|
|
1257
|
-
session.pendingMessages.clear();
|
|
1258
|
-
}
|
|
1259
|
-
else if (session.pendingMessages.size > 0) {
|
|
1260
|
-
// This usually should not happen, but in case the loop finishes
|
|
1261
|
-
// without claude sending all message replays, we resolve the
|
|
1262
|
-
// next pending prompt call to ensure no prompts get stuck.
|
|
1263
|
-
const next = [...session.pendingMessages.entries()].sort((a, b) => a[1].order - b[1].order)[0];
|
|
1264
|
-
if (next) {
|
|
1265
|
-
next[1].resolve(false);
|
|
1266
|
-
session.pendingMessages.delete(next[0]);
|
|
1267
|
-
}
|
|
1268
|
-
}
|
|
1461
|
+
else {
|
|
1462
|
+
this.logger.error(`Session ${params.sessionId}: query stream error: ${message}`);
|
|
1463
|
+
failAllTurns(error);
|
|
1464
|
+
this.closeQueryStream(session);
|
|
1269
1465
|
}
|
|
1270
1466
|
}
|
|
1271
1467
|
}
|
|
@@ -1274,23 +1470,46 @@ export class ClaudeAcpAgent {
|
|
|
1274
1470
|
if (!session) {
|
|
1275
1471
|
return;
|
|
1276
1472
|
}
|
|
1473
|
+
// The stream already ended (see closeQueryStream): every in-flight turn was
|
|
1474
|
+
// settled when it closed, and there is no live query to interrupt. Calling
|
|
1475
|
+
// query.interrupt() on a finished iterator could reject and surface from
|
|
1476
|
+
// this fire-and-forget notification, so there is nothing to do here.
|
|
1477
|
+
if (session.queryClosed) {
|
|
1478
|
+
return;
|
|
1479
|
+
}
|
|
1277
1480
|
session.cancelled = true;
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1481
|
+
// Settle queued turns that haven't started yet (no echo seen) right away —
|
|
1482
|
+
// they have no in-flight SDK work to interrupt. The active turn is settled
|
|
1483
|
+
// by the consumer when it observes the interrupt's trailing idle (or via the
|
|
1484
|
+
// backstop below). Mirrors the old pendingMessages cancellation.
|
|
1485
|
+
if (session.turnQueue) {
|
|
1486
|
+
let orphaned = 0;
|
|
1487
|
+
for (const turn of session.turnQueue) {
|
|
1488
|
+
if (turn !== session.activeTurn && !turn.settled) {
|
|
1489
|
+
turn.settled = true;
|
|
1490
|
+
turn.resolve({ stopReason: "cancelled" });
|
|
1491
|
+
orphaned++;
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
// Each removed queued turn's user message was already pushed to the SDK,
|
|
1495
|
+
// which processes input FIFO and will still emit a result for it with no
|
|
1496
|
+
// uuid to match. Count those so the consumer skips them (see
|
|
1497
|
+
// ensureActiveTurn) rather than misattributing them to the head.
|
|
1498
|
+
session.pendingOrphanResults = (session.pendingOrphanResults ?? 0) + orphaned;
|
|
1499
|
+
session.turnQueue = session.turnQueue.filter((turn) => turn === session.activeTurn && !turn.settled);
|
|
1500
|
+
}
|
|
1501
|
+
// Arm a backstop before interrupting: if a turn is actively consuming the
|
|
1502
|
+
// query and interrupt() doesn't make the SDK yield (e.g. a wedged TaskOutput
|
|
1503
|
+
// block — issue #680), force the consumer to settle the active turn
|
|
1504
|
+
// "cancelled" after the floor elapses so the pending session/prompt still
|
|
1505
|
+
// resolves per the ACP cancellation contract instead of hanging forever. The
|
|
1506
|
+
// consumer clears this timer when interrupt() works and it settles through
|
|
1288
1507
|
// the normal idle path, so on healthy cancels it is armed but never fires.
|
|
1289
1508
|
//
|
|
1290
|
-
// Arm at most once per turn: the floor is an absolute ceiling from the
|
|
1291
|
-
//
|
|
1509
|
+
// Arm at most once per turn: the floor is an absolute ceiling from the first
|
|
1510
|
+
// cancel, so a client that re-sends cancel (each call still retries
|
|
1292
1511
|
// interrupt() below) can't keep pushing the deadline out.
|
|
1293
|
-
if (session.
|
|
1512
|
+
if (session.activeTurn &&
|
|
1294
1513
|
session.cancelController &&
|
|
1295
1514
|
!session.cancelController.signal.aborted &&
|
|
1296
1515
|
!session.forceCancelTimer) {
|
|
@@ -1302,8 +1521,37 @@ export class ClaudeAcpAgent {
|
|
|
1302
1521
|
}
|
|
1303
1522
|
await session.query.interrupt();
|
|
1304
1523
|
}
|
|
1305
|
-
/**
|
|
1306
|
-
*
|
|
1524
|
+
/** Mark a session's SDK query stream as permanently ended and release the
|
|
1525
|
+
* resources tied to it: drop the consumer handle, dispose the settings
|
|
1526
|
+
* watchers, end the input stream, and close the query (which terminates the
|
|
1527
|
+
* subprocess). The query iterator is not revivable, so `prompt()`/`cancel()`
|
|
1528
|
+
* consult `queryClosed` and fail/short-circuit instead of acting on a dead
|
|
1529
|
+
* stream. Idempotent (guarded by `queryClosed`), so the consumer's done/error
|
|
1530
|
+
* paths and a later `teardownSession` can all call it without double-releasing.
|
|
1531
|
+
*
|
|
1532
|
+
* Deliberately does NOT abort `session.abortController`: that controller may be
|
|
1533
|
+
* CLIENT-supplied (`_meta.claudeCode.options.abortController`) and reused, so
|
|
1534
|
+
* aborting it on a spontaneous stream end would cancel the client's own work
|
|
1535
|
+
* or make a sibling session born aborted. `query.close()` already terminates
|
|
1536
|
+
* the subprocess; aborting the signal belongs in `teardownSession` (explicit
|
|
1537
|
+
* destroy), not here. Also does NOT remove the session from the map — that is
|
|
1538
|
+
* `teardownSession`'s job — so prompt() can still answer with a clear "session
|
|
1539
|
+
* ended" error after an unexpected stream close. The leftover session object
|
|
1540
|
+
* is a lightweight husk (its heavy resources are released here) and is evicted
|
|
1541
|
+
* on the next closeSession/deleteSession or when the connection's `dispose()`
|
|
1542
|
+
* runs. */
|
|
1543
|
+
closeQueryStream(session) {
|
|
1544
|
+
if (session.queryClosed) {
|
|
1545
|
+
return;
|
|
1546
|
+
}
|
|
1547
|
+
session.queryClosed = true;
|
|
1548
|
+
session.consumer = undefined;
|
|
1549
|
+
session.settingsManager.dispose();
|
|
1550
|
+
session.input.end();
|
|
1551
|
+
session.query.close();
|
|
1552
|
+
}
|
|
1553
|
+
/** Cleanly tear down a session: cancel in-flight work, release stream
|
|
1554
|
+
* resources, and remove it from the session map. */
|
|
1307
1555
|
async teardownSession(sessionId) {
|
|
1308
1556
|
const session = this.sessions[sessionId];
|
|
1309
1557
|
if (!session) {
|
|
@@ -1311,20 +1559,23 @@ export class ClaudeAcpAgent {
|
|
|
1311
1559
|
}
|
|
1312
1560
|
await this.cancel({ sessionId });
|
|
1313
1561
|
// cancel() arms the force-cancel floor and interrupts gracefully, but a
|
|
1314
|
-
// wedged
|
|
1315
|
-
//
|
|
1316
|
-
//
|
|
1317
|
-
//
|
|
1318
|
-
//
|
|
1319
|
-
//
|
|
1562
|
+
// wedged consumer only wakes when `cancelController` aborts — closeQueryStream
|
|
1563
|
+
// below doesn't touch it. Since we're tearing the session down anyway, wake
|
|
1564
|
+
// the consumer now so the in-flight prompt() resolves immediately instead of
|
|
1565
|
+
// after the floor, and clear the timer so it can't outlive the deleted
|
|
1566
|
+
// session (it isn't unref'd and would otherwise keep the event loop alive
|
|
1567
|
+
// until it fires).
|
|
1320
1568
|
if (session.forceCancelTimer) {
|
|
1321
1569
|
clearTimeout(session.forceCancelTimer);
|
|
1322
1570
|
session.forceCancelTimer = undefined;
|
|
1323
1571
|
}
|
|
1324
1572
|
session.cancelController?.abort();
|
|
1325
|
-
|
|
1573
|
+
this.closeQueryStream(session);
|
|
1574
|
+
// Abort the SDK abort signal only on explicit destroy. closeQueryStream
|
|
1575
|
+
// leaves it alone (it may be a client-owned controller — see its doc), but
|
|
1576
|
+
// here the client has asked us to close the session, so signalling abort is
|
|
1577
|
+
// appropriate; query.close() above has already torn the subprocess down.
|
|
1326
1578
|
session.abortController.abort();
|
|
1327
|
-
session.query.close();
|
|
1328
1579
|
delete this.sessions[sessionId];
|
|
1329
1580
|
}
|
|
1330
1581
|
/** Tear down all active sessions. Called when the ACP connection closes. */
|
|
@@ -1348,9 +1599,16 @@ export class ClaudeAcpAgent {
|
|
|
1348
1599
|
return {};
|
|
1349
1600
|
}
|
|
1350
1601
|
async setSessionMode(params) {
|
|
1351
|
-
|
|
1602
|
+
const session = this.sessions[params.sessionId];
|
|
1603
|
+
if (!session) {
|
|
1352
1604
|
throw new Error("Session not found");
|
|
1353
1605
|
}
|
|
1606
|
+
// The SDK query stream already ended (see closeQueryStream); the session is
|
|
1607
|
+
// a husk and `query.setPermissionMode` below would act on a closed query.
|
|
1608
|
+
// Fail with the same clear message prompt()/cancel() give for a dead stream.
|
|
1609
|
+
if (session.queryClosed) {
|
|
1610
|
+
throw RequestError.internalError(undefined, SESSION_ENDED_MESSAGE);
|
|
1611
|
+
}
|
|
1354
1612
|
await this.applySessionMode(params.sessionId, params.modeId);
|
|
1355
1613
|
await this.updateConfigOption(params.sessionId, "mode", params.modeId);
|
|
1356
1614
|
return {};
|
|
@@ -1360,6 +1618,13 @@ export class ClaudeAcpAgent {
|
|
|
1360
1618
|
if (!session) {
|
|
1361
1619
|
throw new Error("Session not found");
|
|
1362
1620
|
}
|
|
1621
|
+
// The SDK query stream already ended (see closeQueryStream); the session is
|
|
1622
|
+
// a husk and the `query.setModel`/`setPermissionMode`/`applyFlagSettings`
|
|
1623
|
+
// calls this triggers would act on a closed query. Fail with the same clear
|
|
1624
|
+
// message prompt()/cancel() give for a dead stream.
|
|
1625
|
+
if (session.queryClosed) {
|
|
1626
|
+
throw RequestError.internalError(undefined, SESSION_ENDED_MESSAGE);
|
|
1627
|
+
}
|
|
1363
1628
|
if (typeof params.value !== "string") {
|
|
1364
1629
|
throw new Error(`Invalid value for config option ${params.configId}: ${params.value}`);
|
|
1365
1630
|
}
|
|
@@ -2163,9 +2428,6 @@ export class ClaudeAcpAgent {
|
|
|
2163
2428
|
models,
|
|
2164
2429
|
modelInfos: allowedModels,
|
|
2165
2430
|
configOptions,
|
|
2166
|
-
promptRunning: false,
|
|
2167
|
-
pendingMessages: new Map(),
|
|
2168
|
-
nextPendingOrder: 0,
|
|
2169
2431
|
abortController,
|
|
2170
2432
|
emitRawSDKMessages: sessionMeta?.claudeCode?.emitRawSDKMessages ?? false,
|
|
2171
2433
|
contextWindowSize: inferContextWindowFromModel(models.currentModelId) ?? DEFAULT_CONTEXT_WINDOW,
|