-
-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathsession-manager.ts
More file actions
1406 lines (1336 loc) · 46.4 KB
/
Copy pathsession-manager.ts
File metadata and controls
1406 lines (1336 loc) · 46.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* `SessionManager` implementation backed by the Claude Agent SDK.
*/
import { randomUUID } from "node:crypto";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { basename, dirname, extname, join } from "node:path";
import {
type ElicitationResult,
type PermissionUpdate,
type Query,
query,
type SDKMessage,
type SDKUserMessage,
} from "@anthropic-ai/claude-agent-sdk";
import { isAbortError, isQueryClosedTransient } from "../abort.js";
import { ActiveTurnRegistry } from "../active-turn-registry.js";
import {
applyWindowsPathFromRegistry,
type WindowsPathEnvOptions,
} from "../agent-path-env.js";
import { buildAgentProxyEnv } from "../agent-proxy.js";
import {
buildClaudeRichMeta,
buildClaudeStoredMeta,
} from "../context-usage.js";
import type { SidecarEmitter, UserInputPayload } from "../emitter.js";
import { readImageWithResize } from "../image-resize.js";
import { parseImageRefs } from "../images.js";
import { prependLinkedDirectoriesContext } from "../linked-directories-context.js";
import { errorDetails, logger } from "../logger.js";
import { listProviderModels, modelSupportsFastMode } from "../model-catalog.js";
import { createPushable, type Pushable } from "../pushable-iterable.js";
import type {
GenerateTitleOptions,
GetContextUsageParams,
ListSlashCommandsParams,
ProviderModelInfo,
SendMessageParams,
SessionManager,
SlashCommandInfo,
UserInputResolution,
} from "../session-manager.js";
import {
buildTitlePrompt,
parseTitleAndBranchWithDiagnostics,
TITLE_GENERATION_TIMEOUT_MS,
} from "../title.js";
import { shouldSuppressCompactContextUsageMessage } from "./compact-filter.js";
import { loadProjectMcpServers } from "./project-mcp.js";
/**
* Hard upper bound on how long `listSlashCommands` will wait for the SDK's
* control-protocol response. The slash-command popup is interactive (the user
* just opened a dropdown), so anything longer than a few seconds is worse
* than just showing an empty list. Without this bound, a missing or
* unresponsive `claude-code` binary parks the request forever and the popup
* spinner never resolves.
*/
const SLASH_COMMANDS_TIMEOUT_MS = 20_000;
/**
* Hover popover fires this as an ad-hoc RPC. 30s is generous — the
* control-protocol call usually returns in <300ms, but the slow-path
* spawns a transient CLI child whose init can take seconds on a cold
* workspace. Aborting returns an error the UI surfaces as "no data yet".
*/
const CONTEXT_USAGE_TIMEOUT_MS = 30_000;
/**
* Helmor wraps every user prompt as `{helmor preamble}\n\nUser request:\n{prompt}`
* (and may also prepend a `[Linked directories …]` block). The Claude Agent SDK
* only recognises a root slash command when the prompt it receives starts with
* `/<name>`, so a wrapped `/compact` or `/context` is treated as literal text
* and silently does nothing. Strip the wrapping and return the bare command the
* SDK needs; return `null` for any non-command prompt so the normal path runs.
*/
export function normalizeRootSlashCommand(prompt: string): string | null {
const marker = "\n\nUser request:\n";
const markerIndex = prompt.lastIndexOf(marker);
const text = (
markerIndex === -1 ? prompt : prompt.slice(markerIndex + marker.length)
).trim();
if (text === "/context" || text.startsWith("/context ")) {
return "/context all";
}
if (text === "/compact" || text.startsWith("/compact ")) {
return "/compact";
}
return null;
}
/**
* Resolve the Claude Code native binary for `pathToClaudeCodeExecutable`.
* Prefers `HELMOR_CLAUDE_CODE_BIN_PATH` (release), then the platform
* sub-package (dev/test); falls back to the wrapper bin for `--omit=optional`.
* Mirrors the codex resolver in `codex/app-server-manager.ts`.
*
* MUST NOT throw: this runs at module load (before the ready signal), and
* inside a `bun build --compile` binary `require.resolve` always fails —
* if the host didn't pass the env override, an exception here kills the
* whole sidecar with "Invalid sidecar ready signal". Returning `undefined`
* lets the SDK attempt its own resolution lazily, scoping any failure to
* the individual Claude session instead of the entire process.
*/
function resolveClaudeBinPath(): string | undefined {
const override = process.env.HELMOR_CLAUDE_CODE_BIN_PATH;
if (override) {
return override;
}
const require = createRequire(import.meta.url);
const binName = process.platform === "win32" ? "claude.exe" : "claude";
const platformPkg = `@anthropic-ai/claude-code-${claudePlatformShort()}`;
try {
const pkgJson = require.resolve(`${platformPkg}/package.json`);
return join(dirname(pkgJson), binName);
} catch {
// Platform sub-package missing — try the wrapper package below.
}
try {
const pkgJson = require.resolve("@anthropic-ai/claude-code/package.json");
return join(dirname(pkgJson), "bin", "claude.exe");
} catch {
logger.info(
"Claude Code binary not resolved (no HELMOR_CLAUDE_CODE_BIN_PATH and no resolvable package); deferring to SDK default resolution",
);
return undefined;
}
}
function claudePlatformShort(): string {
const arch = process.arch === "x64" ? "x64" : "arm64";
if (process.platform === "darwin") return `darwin-${arch}`;
if (process.platform === "win32") return `win32-${arch}`;
if (process.platform === "linux") {
// claude-code ships separate -musl variants; glibcVersionRuntime is absent on musl.
const report =
typeof process.report?.getReport === "function"
? (process.report.getReport() as {
header?: { glibcVersionRuntime?: string };
})
: null;
const musl = !!report && report.header?.glibcVersionRuntime === undefined;
return `linux-${arch}${musl ? "-musl" : ""}`;
}
return `${process.platform}-${arch}`;
}
const CLAUDE_BIN_PATH = resolveClaudeBinPath();
// SDK's `env` option REPLACES process.env when set (per its docstring:
// "Defaults to process.env"). Without spreading process.env back in, the
// spawned claude-code child loses HOME / PATH / cached OAuth creds and
// reports "Not logged in". Returns undefined when no overrides are
// supplied so the SDK keeps its default-process.env path.
export function buildClaudeBaseEnv(
baseEnv: NodeJS.ProcessEnv = process.env,
options: WindowsPathEnvOptions = {},
): { [key: string]: string | undefined } {
return applyWindowsPathFromRegistry({ ...baseEnv }, options);
}
export function mergeQueryEnv(
...overrides: (Record<string, string> | undefined)[]
): { [key: string]: string | undefined } | undefined {
const present = overrides.filter(
(o): o is Record<string, string> => o !== undefined,
);
if (present.length === 0 && process.platform !== "win32") return undefined;
return Object.assign(buildClaudeBaseEnv(), ...present);
}
// claude-agent-sdk v0.3.142 changed MCP servers to connect in the
// BACKGROUND by default: the session starts immediately and a slow server
// reports `status: "pending"` in the `init` event, so a turn-1 tool call can
// race a not-yet-connected MCP. Helmor doesn't surface a "MCP loading" state,
// and the pre-0.3 behavior was to block until MCP servers were ready — so we
// pin the env flag back to blocking to keep behavior identical across the
// upgrade. Revisit if/when the UI renders pending-MCP status.
const MCP_BLOCKING_ENV: Record<string, string> = {
MCP_CONNECTION_NONBLOCKING: "0",
};
interface LiveSession {
readonly query: Query;
readonly abortController: AbortController;
/**
* Streaming-input source. The initial prompt is pushed up front in
* `sendMessage`; each `steer()` call pushes one more user message.
* The SDK folds every pushed message into ONE extended turn and
* emits a SINGLE *terminal* `result` when the whole trajectory is
* done. Backgrounded tasks add intermediate `background_requested`
* results mid-turn (filtered out, see `isBackgroundPauseResult`), so
* the for-await loop bails on the first *genuinely terminal* result.
*/
readonly promptSource: Pushable<SDKUserMessage>;
/** Request id owning this session; needed by `steer()` to synthesize
* a user passthrough event for the active stream. */
readonly requestId: string;
/** Emitter bound to the active stream — used by `steer()` to fan a
* synthetic user event to the pipeline so the UI renders the mid-turn
* bubble at the correct position instead of tacking it onto the end. */
readonly emitter: SidecarEmitter;
}
// Helmor models permission as a binary: `plan` (read-only) or full access.
const VALID_PERMISSION_MODES = ["plan", "bypassPermissions"] as const;
type ClaudePermissionMode = (typeof VALID_PERMISSION_MODES)[number];
const VALID_EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"] as const;
type ClaudeEffort = (typeof VALID_EFFORT_LEVELS)[number];
/**
* Tools that require interactive user input mid-execution. They go
* through the unified `userInputRequest` UI flow instead of being
* auto-approved by `canUseTool`.
*/
const USER_INPUT_TOOL_NAMES = new Set(["AskUserQuestion"]);
/**
* MCP elicitation `content` must be a flat object whose values are
* `string | number | boolean | string[]` (per the MCP 2025-11 spec).
* Returns the input unchanged if valid, `null` otherwise.
*/
function validateMcpElicitationContent(
content: Record<string, unknown> | undefined,
): Record<string, unknown> | null {
if (!content) return {};
for (const value of Object.values(content)) {
if (
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean"
) {
continue;
}
if (Array.isArray(value) && value.every((v) => typeof v === "string")) {
continue;
}
return null;
}
return content;
}
interface PermissionResolution {
readonly behavior: "allow" | "deny";
readonly updatedPermissions?: PermissionUpdate[];
readonly message?: string;
}
function parsePermissionMode(value: string | undefined): ClaudePermissionMode {
return value === "plan" ? "plan" : "bypassPermissions";
}
function extractSessionPermissionMode(
updates: readonly PermissionUpdate[] | undefined,
): ClaudePermissionMode | undefined {
if (!updates) {
return undefined;
}
for (const update of updates) {
if (typeof update !== "object" || update === null) {
continue;
}
const candidate = update as {
type?: unknown;
destination?: unknown;
mode?: unknown;
};
if (
candidate.type === "setMode" &&
candidate.destination === "session" &&
typeof candidate.mode === "string" &&
(VALID_PERMISSION_MODES as readonly string[]).includes(candidate.mode)
) {
return candidate.mode as ClaudePermissionMode;
}
}
return undefined;
}
function parseEffort(value: string | undefined): ClaudeEffort | undefined {
if (value && (VALID_EFFORT_LEVELS as readonly string[]).includes(value)) {
return value as ClaudeEffort;
}
return undefined;
}
type ImageMediaType = "image/jpeg" | "image/png" | "image/gif" | "image/webp";
function extToMediaType(filePath: string): ImageMediaType {
const ext = extname(filePath).toLowerCase();
switch (ext) {
case ".jpg":
case ".jpeg":
return "image/jpeg";
case ".png":
return "image/png";
case ".gif":
return "image/gif";
case ".webp":
return "image/webp";
default:
return "image/png";
}
}
type ContentBlock =
| { type: "text"; text: string }
| {
type: "image";
source: { type: "base64"; media_type: ImageMediaType; data: string };
};
async function buildUserMessageWithImages(
text: string,
imagePaths: readonly string[],
): Promise<SDKUserMessage> {
const content: ContentBlock[] = [];
if (text) {
content.push({ type: "text", text });
}
for (const imgPath of imagePaths) {
try {
const { buffer } = await readImageWithResize(imgPath);
content.push({
type: "image",
source: {
type: "base64",
media_type: extToMediaType(imgPath),
data: buffer.toString("base64"),
},
});
} catch (err) {
logger.error("Failed to read image attachment", {
imageName: basename(imgPath),
...errorDetails(err),
});
content.push({ type: "text", text: `[Image not found: ${imgPath}]` });
}
}
return {
type: "user",
message: { role: "user", content },
parent_tool_use_id: null,
} as SDKUserMessage;
}
export class ClaudeSessionManager implements SessionManager {
private readonly sessions = new Map<string, LiveSession>();
/** Shared Stop handling: instant `aborted` emit at any point (see
* ActiveTurnRegistry). Identical across all four providers. */
private readonly turns = new ActiveTurnRegistry();
private readonly pendingPermissions = new Map<
string,
(resolution: PermissionResolution) => void
>();
/**
* In-flight callbacks waiting on the user's answer to a unified
* `userInputRequest` (covers both AskUserQuestion via `canUseTool`
* and MCP `onElicitation`). Resolving runs the closure stored at
* emit-time, which encapsulates the SDK-specific conversion from
* the generic `UserInputResolution` shape back into either an AUQ
* `updatedInput` or an `ElicitationResult`. Keyed by
* `userInputId` (the wire-level round-trip key — same as the
* tool_use_id for AUQ and the elicitationId for MCP).
*/
private readonly pendingUserInputs = new Map<
string,
{ sessionId: string; resolve: (resolution: UserInputResolution) => void }
>();
resolvePermission(
permissionId: string,
behavior: "allow" | "deny",
updatedPermissions?: PermissionUpdate[],
message?: string,
): void {
const resolve = this.pendingPermissions.get(permissionId);
if (resolve) {
this.pendingPermissions.delete(permissionId);
resolve({ behavior, updatedPermissions, message });
}
}
resolveUserInput(
userInputId: string,
resolution: UserInputResolution,
): boolean {
const entry = this.pendingUserInputs.get(userInputId);
if (!entry) return false;
this.pendingUserInputs.delete(userInputId);
entry.resolve(resolution);
return true;
}
async sendMessage(
requestId: string,
params: SendMessageParams,
emitter: SidecarEmitter,
): Promise<void> {
const {
sessionId,
prompt,
model,
cwd,
resume,
permissionMode,
effortLevel,
fastMode,
claudeThinkingDisplay,
claudeEnvironment,
agentProxy,
images,
sourceRepoPath,
} = params;
const abortController = new AbortController();
// Register the turn before any await so a Stop during SDK startup
// emits `aborted` instantly + aborts the query.
this.turns.begin(sessionId, requestId, emitter, () =>
abortController.abort(),
);
const additionalDirectories = [...(params.additionalDirectories ?? [])];
logger.info(`[${requestId}] claude additionalDirectories resolved`, {
directories: additionalDirectories,
cwd: cwd ?? "(none)",
});
// Root slash commands (/compact, /context) must reach the SDK bare — any
// prepended context breaks the SDK's root-command detection. Strip the
// Helmor wrapping; for normal prompts keep the linked-dirs hint.
const rootSlashCommand = normalizeRootSlashCommand(prompt);
const promptForSdk = rootSlashCommand ?? prompt;
const promptWithContext = rootSlashCommand
? promptForSdk
: prependLinkedDirectoriesContext(promptForSdk, additionalDirectories);
const { text, imagePaths } = parseImageRefs(promptWithContext, images);
const promptSource = createPushable<SDKUserMessage>();
const initialMessage =
imagePaths.length === 0
? ({
type: "user",
message: { role: "user", content: text },
parent_tool_use_id: null,
} as SDKUserMessage)
: await buildUserMessageWithImages(text, imagePaths);
promptSource.push(initialMessage);
const effectiveFastMode =
fastMode === true && modelSupportsFastMode("claude", model);
if (fastMode === true) {
logger.info(`[${requestId}] fast-mode requested`, {
model: model ?? "(none)",
supportsFastMode: modelSupportsFastMode("claude", model),
effectiveFastMode,
});
}
const claudeEnv =
claudeEnvironment && Object.keys(claudeEnvironment).length > 0
? claudeEnvironment
: undefined;
const additionalDirectoryEnv =
additionalDirectories.length > 0
? { CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD: "1" }
: undefined;
const proxyEnv = buildAgentProxyEnv(agentProxy);
const queryEnv = mergeQueryEnv(
proxyEnv,
claudeEnv,
additionalDirectoryEnv,
MCP_BLOCKING_ENV,
);
const projectMcpServers = loadProjectMcpServers(sourceRepoPath);
if (projectMcpServers) {
logger.info(`[${requestId}] claude project MCPs injected`, {
sourceRepoPath,
servers: Object.keys(projectMcpServers),
});
}
const q = query({
prompt: promptSource,
options: {
abortController,
pathToClaudeCodeExecutable: CLAUDE_BIN_PATH,
cwd: cwd || undefined,
...(additionalDirectories.length > 0 ? { additionalDirectories } : {}),
...(queryEnv ? { env: queryEnv } : {}),
model: model || undefined,
...(resume ? { resume } : {}),
permissionMode: parsePermissionMode(permissionMode),
allowDangerouslySkipPermissions: true,
effort: parseEffort(effortLevel),
thinking: {
type: "adaptive",
display: claudeThinkingDisplay ?? "summarized",
},
...(effectiveFastMode ? { settings: { fastMode: true } } : {}),
...(projectMcpServers ? { mcpServers: projectMcpServers } : {}),
onElicitation: async (request, options) => {
// MCP elicitation: surface as a unified userInputRequest
// with `kind: "form"` (schema-driven) or `kind: "url"`
// (URL launcher). The frontend's existing form / URL
// renderers handle both shapes verbatim. The generic
// `UserInputResolution` we get back maps 1:1 onto the
// SDK's `ElicitationResult` shape.
const elicitationId = request.elicitationId ?? randomUUID();
const isUrl = request.mode === "url";
const payload: UserInputPayload = isUrl
? { kind: "url", url: request.url ?? "" }
: {
kind: "form",
schema:
(request.requestedSchema as
| Record<string, unknown>
| undefined) ?? {},
};
emitter.userInputRequest(
requestId,
elicitationId,
request.serverName,
request.message,
payload,
);
const resolution = await new Promise<UserInputResolution>(
(resolve) => {
this.pendingUserInputs.set(elicitationId, {
sessionId,
resolve,
});
options.signal.addEventListener(
"abort",
() => {
this.pendingUserInputs.delete(elicitationId);
resolve({ action: "cancel" });
},
{ once: true },
);
},
);
if (resolution.action === "submit") {
// MCP elicitation requires field values be primitives
// (`string | number | boolean | string[]`). Validate
// before handing off — a non-primitive would otherwise
// surface as an opaque SDK error far from the cause.
const validated = validateMcpElicitationContent(resolution.content);
if (validated === null) {
logger.error(
`[${requestId}] MCP elicitation content rejected (non-primitive)`,
{ elicitationId },
);
return { action: "cancel" };
}
return {
action: "accept",
content: validated as unknown as ElicitationResult extends {
content?: infer C;
}
? C
: never,
};
}
if (resolution.action === "decline") {
return { action: "decline" };
}
return { action: "cancel" };
},
includePartialMessages: true,
settingSources: ["user", "project", "local"],
canUseTool: async (_toolName, input, options) => {
// AskUserQuestion: pause this `canUseTool` callback on the
// same live `query()`, surface the question through the
// unified `userInputRequest` flow, then return the user's
// answer via `updatedInput` so the SDK executes the tool
// normally. No `--resume`, no extra process (issue #397 / #402).
if (USER_INPUT_TOOL_NAMES.has(_toolName)) {
const toolUseId = options.toolUseID;
const auqInput = input as Record<string, unknown>;
const rawQuestions = Array.isArray(auqInput.questions)
? (auqInput.questions as Array<Record<string, unknown>>)
: [];
const metadata =
typeof auqInput.metadata === "object" &&
auqInput.metadata !== null &&
!Array.isArray(auqInput.metadata)
? (auqInput.metadata as Record<string, unknown>)
: undefined;
logger.info(`[${requestId}] AUQ canUseTool fired`, {
toolUseId,
questionCount: rawQuestions.length,
hasMetadata: metadata !== undefined,
});
emitter.userInputRequest(
requestId,
toolUseId,
"Claude",
"Claude is asking for your input.",
{
kind: "ask-user-question",
questions: rawQuestions,
...(metadata ? { metadata } : {}),
},
);
logger.info(`[${requestId}] AUQ userInputRequest emitted`, {
toolUseId,
});
const resolution = await new Promise<UserInputResolution>(
(resolve) => {
this.pendingUserInputs.set(toolUseId, {
sessionId,
resolve,
});
options.signal.addEventListener(
"abort",
() => {
this.pendingUserInputs.delete(toolUseId);
resolve({ action: "cancel" });
},
{ once: true },
);
},
);
logger.info(`[${requestId}] AUQ resolved`, {
toolUseId,
action: resolution.action,
});
if (resolution.action === "submit") {
// The unified AUQ renderer submits only the answer
// payload (`{ answers, annotations? }` keyed by
// question text); merge it over the original tool
// input to build the `updatedInput` the SDK expects.
return {
behavior: "allow" as const,
updatedInput: { ...auqInput, ...resolution.content },
};
}
return {
behavior: "deny" as const,
message: "User declined",
};
}
// Intercept ExitPlanMode: capture plan content and deny to
// end the turn cleanly. The user starts a new turn to act.
if (_toolName === "ExitPlanMode") {
const plan = extractExitPlanContent(input);
if (plan) {
emitter.planCaptured(requestId, options.toolUseID, plan);
}
return {
behavior: "deny" as const,
message:
"Plan captured by the client. " +
"Do NOT continue generating text or call any tools. " +
"The turn is over. The user will respond in a new turn.",
};
}
const permissionId = options.toolUseID;
emitter.permissionRequest(
requestId,
permissionId,
_toolName,
input,
options.title,
options.description,
);
const resolution = await new Promise<PermissionResolution>(
(resolve) => {
this.pendingPermissions.set(permissionId, resolve);
options.signal.addEventListener(
"abort",
() => {
this.pendingPermissions.delete(permissionId);
resolve({ behavior: "deny" });
},
{ once: true },
);
},
);
if (resolution.behavior === "allow") {
const updatedPermissions =
resolution.updatedPermissions ?? options.suggestions;
const nextPermissionMode =
extractSessionPermissionMode(updatedPermissions);
if (nextPermissionMode) {
emitter.permissionModeChanged(requestId, nextPermissionMode);
}
return {
behavior: "allow" as const,
updatedInput: input,
updatedPermissions,
};
}
return {
behavior: "deny" as const,
message: resolution.message ?? "User denied",
};
},
},
});
const live: LiveSession = {
query: q,
abortController,
promptSource,
requestId,
emitter,
};
this.sessions.set(sessionId, live);
try {
let lastRateLimitInfo: RateLimitOverageInfo | undefined;
let fastModeNoticeEmitted = false;
for await (const message of q) {
// stopSession already emitted the terminal `aborted` and tore the
// session down. The new SDK keeps the child alive ~2s after abort,
// so the iterator can still drain buffered events — even a natural
// `result`. Drop them and return: passing them through or emitting
// `end` here would violate the "exactly one terminal event" contract.
if (this.turns.isAbortRequested(sessionId)) return;
logger.sdkEvent(requestId, message);
// /compact: drop the redundant synthetic `## Context Usage` reply —
// `compact_boundary` already confirms the compact.
if (
shouldSuppressCompactContextUsageMessage(message, rootSlashCommand)
) {
continue;
}
if (message.type === "rate_limit_event") {
lastRateLimitInfo = (
message as { rate_limit_info?: RateLimitOverageInfo }
).rate_limit_info;
}
// Surface fast-mode-not-active off the init event (carries
// `fast_mode_state` right after send), once — not the terminal
// result, which never arrives on an aborted turn.
const fms = (message as { fast_mode_state?: FastModeState })
.fast_mode_state;
if (
effectiveFastMode &&
!fastModeNoticeEmitted &&
fms &&
fms !== "on"
) {
fastModeNoticeEmitted = true;
logger.info(`[${requestId}] fast-mode unavailable`, {
fastModeState: fms,
overageDisabledReason: lastRateLimitInfo?.overageDisabledReason,
});
emitter.passthrough(requestId, {
type: "system",
subtype: "fast_mode_unavailable",
reason: describeFastModeUnavailable(fms, lastRateLimitInfo),
fastModeState: fms,
session_id: sessionId,
uuid: randomUUID(),
});
}
// Backgrounded task pause: SDK keeps the SAME query() alive and
// resumes later via task_notification. Record usage, but keep the
// pause result OUT of the pipeline (accumulator assumes one result
// per turn) and do NOT end the turn — must intercept before the
// unconditional passthrough below.
if (isBackgroundPauseResult(message)) {
const meta = buildClaudeStoredMeta(message, model ?? "");
if (meta) {
emitter.contextUsageUpdated(
requestId,
sessionId,
JSON.stringify(meta),
);
}
continue;
}
// AskUserQuestion tool_use blocks pass through INTACT — the Rust
// adapter renders them as the persistent Q&A card (and merges
// the tool_result answers into it), so stripping them here
// would lose the card on finalize/persist/reload.
emitter.passthrough(requestId, message);
if (isTerminalResult(message)) {
// Terminal result (success OR error) — both shapes carry
// `usage`/`modelUsage`, so both should update the ring.
// Bail on the first one we see; any steer() still in its
// image-load await will find `promptSource.closed` via
// the finally block below and return false.
const meta = buildClaudeStoredMeta(message, model ?? "");
if (meta) {
emitter.contextUsageUpdated(
requestId,
sessionId,
JSON.stringify(meta),
);
}
emitter.end(requestId);
return;
}
}
if (!this.turns.isAbortRequested(sessionId)) emitter.end(requestId);
} catch (err) {
if (isAbortError(err)) {
// stopSession already emitted `aborted` up front (see below) —
// don't double-emit when the iterator finally unwinds.
if (!this.turns.isAbortRequested(sessionId))
emitter.aborted(requestId, "user_requested");
return;
}
throw err;
} finally {
// `abortController.abort()` alone leaves Node-level exit listeners,
// pending control/MCP promises, and the SDK's internal child handle
// dangling. `Query.close()` is the documented hard cleanup —
// always call it, including on the natural-completion path so the
// per-request `process.on("exit", ...)` listener gets removed.
try {
q.close();
} catch (closeErr) {
logger.error("Claude session cleanup failed during q.close()", {
requestId,
sessionId,
...errorDetails(closeErr),
});
}
promptSource.close();
// Guard by `requestId`: a Stop drains the queue, so a same-session
// follow-up may have already re-registered here. A bare-sessionId
// delete would wipe the new turn's live session + Stop handle.
if (this.sessions.get(sessionId)?.requestId === requestId) {
this.sessions.delete(sessionId);
}
this.turns.end(sessionId, requestId);
// Only cancel waiters belonging to THIS session — `pendingUserInputs`
// is manager-wide and other sessions may have parked AUQs / MCP
// elicitations on it.
for (const [userInputId, entry] of this.pendingUserInputs) {
if (entry.sessionId !== sessionId) continue;
this.pendingUserInputs.delete(userInputId);
entry.resolve({ action: "cancel" });
}
}
}
/**
* Real mid-turn steer: push a `SDKUserMessage` into the active turn's
* streaming-input queue so the SDK folds it into the current extended
* turn, and emit a `user_prompt` passthrough event so the accumulator
* renders the user bubble at the correct position AND streaming.rs
* persists it exactly once (no extra DB path).
*
* Event shape matches `persist_user_message`'s DB row exactly:
* `{ type: "user_prompt", text: <raw prompt>, steer: true, files }`.
* We emit the RAW prompt (not the image-stripped version), keeping
* every `@/image.png` / `@src/foo.ts` / custom-tag sigil intact —
* that's what the adapter's `split_user_text_with_files` relies on
* to produce FileMention badges, and matches what a non-steer
* initial prompt stores. The image stripping is ONLY used to build
* the `SDKUserMessage` base64 image blocks we hand to the SDK.
*
* Two correctness properties this method enforces:
*
* 1. **Ghost-steer rejection.** The SDK emits ONE terminal `result`
* for the whole streaming session; once the for-await loop sees
* it, the finally block closes `promptSource`. If our image-
* loading await straddles that boundary, a naive post-await
* emit would plant a synthetic event into the pipeline with no
* assistant response behind it. Re-check `promptSource.closed`
* after the await to refuse the steer in that window.
*
* 2. **Strict ordering with post-steer deltas.** Emit the synthetic
* event BEFORE `promptSource.push()`. Both are synchronous so
* no other JS code can interleave, and the accumulator observes
* `user_prompt` strictly before any deltas the SDK generates
* in response.
*
* Returns `true` on success, `false` when no active session or when
* the turn finished while we were preparing the message.
*/
async steer(
sessionId: string,
prompt: string,
files: readonly string[],
images: readonly string[],
): Promise<boolean> {
const session = this.sessions.get(sessionId);
if (!session || session.promptSource.closed) {
return false;
}
// Strip image refs to build the SDK's base64 image content. Keep
// the raw prompt separately — that's what the synthetic event +
// DB row need so `@-refs` survive the round-trip.
const { text: stripped, imagePaths } = parseImageRefs(prompt, images);
const sdkMessage =
imagePaths.length === 0
? ({
type: "user",
message: { role: "user", content: prompt },
parent_tool_use_id: null,
} as SDKUserMessage)
: await buildUserMessageWithImages(stripped, imagePaths);
// Re-check after the image-loading await — during those awaits
// the for-await loop may have hit the extended turn's single
// terminal result and closed our queue. Without this guard a
// late image-steer call would plant a ghost bubble.
if (session.promptSource.closed) {
return false;
}
// Both `files` AND `images` must travel on the synthetic event so
// the persisted DB row matches what `createLiveThreadMessage`
// optimistically rendered. Without `images`, image badges in the
// steer bubble would vanish on reload because the adapter has no
// needle pool to find the `@<path>` substring with.
const event: {
type: "user_prompt";
text: string;
steer: true;
files?: string[];
images?: string[];
} = { type: "user_prompt", text: prompt, steer: true };
if (files.length > 0) event.files = [...files];
if (imagePaths.length > 0) event.images = [...imagePaths];
session.emitter.passthrough(session.requestId, event);
session.promptSource.push(sdkMessage);
logger.info(`steer ${sessionId}`, {
preview: prompt.slice(0, 60),
fileCount: files.length,
imageCount: imagePaths.length,
});
return true;
}
async generateTitle(
requestId: string,
userMessage: string,
branchRenamePrompt: string | null,
emitter: SidecarEmitter,
timeoutMs = TITLE_GENERATION_TIMEOUT_MS,
options?: GenerateTitleOptions,
): Promise<void> {
const abortController = new AbortController();
let timedOut = false;
const timeout = setTimeout(() => {
timedOut = true;
abortController.abort();
}, timeoutMs);
const model = options?.model?.trim() || "haiku";
logger.debug(`[${requestId}] claude title generation using model ${model}`);
const claudeEnv =
options?.claudeEnvironment &&
Object.keys(options.claudeEnvironment).length > 0
? options.claudeEnvironment
: undefined;
const proxyEnv = buildAgentProxyEnv(options?.agentProxy);
const queryEnv = mergeQueryEnv(proxyEnv, claudeEnv);
const generateBranch = options?.generateBranch ?? true;
const q = query({
prompt: buildTitlePrompt(userMessage, branchRenamePrompt, generateBranch),
options: {
abortController,
pathToClaudeCodeExecutable: CLAUDE_BIN_PATH,
...(queryEnv ? { env: queryEnv } : {}),
model,
permissionMode: "bypassPermissions",
allowDangerouslySkipPermissions: true,
thinking: { type: "disabled" },
settingSources: [],
tools: [],
},
});
try {
let raw = "";
for await (const message of q) {
if (isResultMessage(message)) {
raw = message.result;
}
}
const { title, branchName } = parseTitleAndBranchWithDiagnostics(
requestId,
raw,
{
generateBranch,
logError: (message, meta) => logger.error(message, meta),
},
);
emitter.titleGenerated(requestId, title, branchName);
} catch (err) {
// A timeout aborts via `abortController`, which the SDK surfaces as
// "process aborted by user" — relabel it so logs don't read like a
// manual cancel.
if (timedOut) {