Repository navigation
Expand file tree
/
Copy pathClaudeAdapterV2.ts
More file actions
11765 lines (11346 loc) · 474 KB
/
Copy pathClaudeAdapterV2.ts
File metadata and controls
11765 lines (11346 loc) · 474 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
import * as DocumentText from "../../provider/DocumentText.ts";
import { makeProviderTextDeltaCoalescer } from "./ProviderTextDeltaCoalescer.ts";
import { claudeTaskOutputRoot, tailClaudeTaskOutput } from "./ClaudeTaskOutputTail.ts";
import {
dynamicToolTitle,
formatReadToolLabel,
formatSearchToolLabel,
} from "@t3tools/shared/toolActivity";
import { field, text } from "../unknownField.ts";
import { mergeWorkflowAgentMetadata, type WorkflowAgentMetadata } from "../workflowAgentAnswers.ts";
import {
initialWorkflowAgentTranscriptCursor,
readWorkflowAgentTranscript,
type WorkflowAgentTranscriptCursor,
} from "../workflowAgentTranscript.ts";
import {
CLAUDE_WORKFLOW_TASK_TYPE,
hasClaudeWorkflowSnapshot,
mergeClaudeWorkflowProgress,
parseClaudeWorkflowRunHandles,
} from "./claudeWorkflowProgress.ts";
import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
import {
addClaudeLedgerUsage,
claudeLedgerDelta,
claudeModelLedger,
normalizeClaudeTurnTokenUsage,
type ClaudeLedgerUsage,
type ClaudeModelLedger,
} from "../../provider/ClaudeTurnTokenUsage.ts";
import { toMcpElicitationResponse } from "../../provider/CodexMcpElicitation.ts";
import {
type CanUseTool,
type ElicitationRequest,
type ElicitationResult,
forkSession as forkClaudeSession,
type EffortLevel,
type ForkSessionOptions,
type ForkSessionResult,
getSessionMessages,
getSubagentMessages,
type HookCallback,
query,
resolveSettings as resolveClaudeSettings,
type Options as ClaudeQueryOptions,
type PermissionMode,
type PermissionResult,
type PermissionUpdate,
type Query as ClaudeQuery,
type Settings as ClaudeSdkSettings,
type SpawnOptions as ClaudeSpawnOptions,
type SpawnedProcess as ClaudeSpawnedProcess,
type SDKAssistantMessage,
type SDKAPIRetryMessage,
type SDKMessage,
type SDKRateLimitInfo,
type SDKResultMessage,
type SDKUserMessage,
} from "@anthropic-ai/claude-agent-sdk";
import type {
AskUserQuestionInput,
WebSearchOutput,
} from "@anthropic-ai/claude-agent-sdk/sdk-tools";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- the SDK takes a Node ChildProcess for the CLI.
import * as NodeChildProcess from "node:child_process";
import * as NodeUtil from "node:util";
import { parseCliArgs } from "@t3tools/shared/cliArgs";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { AgentScope } from "@t3tools/shared/AgentScope";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
import {
CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER,
CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
formatClaudeResumeCompactionQuestion,
} from "@t3tools/shared/claudeCompaction";
import {
type ChatAttachment,
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
ClaudeSettings,
TrimmedNonEmptyString,
defaultInstanceIdForDriver,
isCompactionCommandMessage,
type ModelSelection,
type OrchestrationV2ConversationMessage,
type OrchestrationV2ExecutionNode,
type OrchestrationV2ProviderCapabilities,
type OrchestrationV2ProviderFailure,
OrchestrationV2ProviderGoal,
type OrchestrationV2PlanArtifact,
type OrchestrationV2PlanStep,
type OrchestrationV2PendingBackgroundTask,
type OrchestrationV2ProviderRetry,
type OrchestrationV2ProviderSession,
type OrchestrationV2ProviderThread,
type OrchestrationV2ProviderTurn,
type OrchestrationV2RuntimeRequest,
type OrchestrationV2UserInputQuestion,
type OrchestrationV2Subagent,
type OrchestrationV2AppThread,
type OrchestrationV2SubagentWorkflow,
type OrchestrationV2WorkflowRunHandles,
type OrchestrationV2TurnItem,
type OrchestrationV2WebSearchResult,
type ProviderApprovalDecision,
type ProviderApprovalFullAccessOverride,
type ProviderApprovalOption,
ProviderDriverKind,
type ProviderInstanceId,
type ProviderRequestKind,
type ProviderUserInputAnswers,
type ProviderThreadId,
type RunId,
type ThreadId,
resolveIdleCompaction,
} from "@t3tools/contracts";
import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts";
import {
planClaudeSkillDispatch,
type ClaudeSkillTarget,
} from "../../provider/Drivers/ClaudeSkillDispatch.ts";
import {
claudeLaunchArgDirectories,
discoverClaudeSkills,
} from "../../provider/Drivers/ClaudeSkills.ts";
import {
compileClaudeModelSelection,
type CompiledClaudeModelSelection,
} from "../../claudeModelOptions.ts";
import * as ServerConfig from "../../config.ts";
import * as PortScanner from "../../preview/PortScanner.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
import {
claudeSignedOutMessage,
makeClaudeEnvironment,
mergeClaudeProcessEnvironment,
resolveClaudeHomePath,
} from "../../provider/Drivers/ClaudeHome.ts";
import {
BUNDLED_CLAUDE_MODEL_CATALOG,
resolveClaudeCatalogContextWindowTokens,
type ClaudeModelCatalog,
getClaudeCatalogModelCapabilities,
resolveClaudeModelSlug,
scopeClaudeModelCatalog,
} from "../../provider/ClaudeModelCatalog.ts";
import {
boundProviderEventForLogging,
shouldPersistProviderEvent,
} from "../../provider/EventNdjsonLogger.ts";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import {
claudeRateLimitEventToUpdate,
type ClaudeScopedLimitNames,
} from "../../provider/claudeUsageLimits.ts";
import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot";
import {
T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH,
T3_CODE_ORCHESTRATION_INSTRUCTIONS,
} from "@t3tools/provider-core/server/orchestrationInstructions";
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
import {
mcpToolPresentation,
normalizeMcpText,
} from "@t3tools/provider-core/server/mcpToolPresentation";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import {
makeProviderFailure,
makeProviderRetryTurnItem,
} from "@t3tools/provider-core/server/failure";
import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
import { providerMessageTextWithAttachmentPaths } from "@t3tools/provider-core/server/attachmentPrompt";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import {
ProviderAdapterDriverCreateError,
type ProviderAdapterDriverCreateInput,
} from "@t3tools/provider-core/server/adapterDriver";
import {
type BackgroundWorkReport,
backgroundWorkNotification,
} from "@t3tools/provider-core/server/notification";
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import {
makeSubagentChildThread,
makeSubagentConversationArtifacts,
subagentThreadTitle,
} from "@t3tools/provider-core/server/subagentProjection";
export const CLAUDE_PROVIDER = ProviderDriverKind.make("claudeAgent");
const CLAUDE_AGENT_SDK_QUERY_PROTOCOL = "claude-agent-sdk.query" as const;
function claudeContextWindow(modelSelection: ModelSelection): number | null {
return (
resolveClaudeCatalogContextWindowTokens(BUNDLED_CLAUDE_MODEL_CATALOG, modelSelection) ?? null
);
}
interface ClaudeCacheCreation {
readonly ephemeral_1h_input_tokens: number;
readonly ephemeral_5m_input_tokens: number;
}
function claudePromptCacheTtlMs(
cacheCreation: ClaudeCacheCreation | null | undefined,
): number | undefined {
if (!cacheCreation) return undefined;
if (cacheCreation.ephemeral_1h_input_tokens > 0) return 60 * 60_000;
if (cacheCreation.ephemeral_5m_input_tokens > 0) return 5 * 60_000;
return undefined;
}
// Claude caps the window at the model's context, so a setting at or above it never applies.
// Below that, Claude compacts 33,000 tokens short of the window: Claude Code 2.1.305's
// getContextUsage reports a 150,000 window as a 117,000 threshold, for every catalog model.
const CLAUDE_AUTO_COMPACT_RESERVE_TOKENS = 33_000;
function claudeAutoCompactThreshold(autoCompactWindow: string, maxTokens: number | null) {
const windowTokens = Number(autoCompactWindow);
return windowTokens > 0 && (maxTokens === null || windowTokens < maxTokens)
? { autoCompactThreshold: windowTokens - CLAUDE_AUTO_COMPACT_RESERVE_TOKENS }
: {};
}
function claudeMessageInputTokens(usage: {
readonly input_tokens: number;
readonly cache_creation_input_tokens?: number | null;
readonly cache_read_input_tokens?: number | null;
}): number {
return (
usage.input_tokens +
(usage.cache_creation_input_tokens ?? 0) +
(usage.cache_read_input_tokens ?? 0)
);
}
export function claudeProviderTurnTokenUsage(
usage: {
readonly input_tokens: number;
readonly cache_creation_input_tokens?: number | null;
readonly cache_read_input_tokens?: number | null;
readonly cache_creation?: ClaudeCacheCreation | null;
readonly output_tokens: number;
},
modelSelection: ModelSelection,
updatedAt: string,
autoCompactWindow = "",
requestedAt?: DateTime.Utc,
) {
const inputTokens = claudeMessageInputTokens(usage);
const outputTokens = usage.output_tokens;
const promptCacheTtlMs = claudePromptCacheTtlMs(usage.cache_creation);
const maxTokens = claudeContextWindow(modelSelection);
// The cache lifetime starts with the request, not when its response ends.
const promptCacheExpiresAt =
promptCacheTtlMs === undefined || requestedAt === undefined
? undefined
: DateTime.formatIso(DateTime.add(requestedAt, { milliseconds: promptCacheTtlMs }));
return {
usedTokens: inputTokens + outputTokens,
maxTokens,
inputTokens,
cachedInputTokens: usage.cache_read_input_tokens ?? 0,
outputTokens,
reasoningOutputTokens: 0,
...(promptCacheTtlMs === undefined ? {} : { promptCacheTtlMs }),
...claudeAutoCompactThreshold(autoCompactWindow, maxTokens),
...(promptCacheExpiresAt === undefined ? {} : { promptCacheExpiresAt }),
updatedAt,
};
}
type ClaudeMessageUsage = Parameters<typeof claudeProviderTurnTokenUsage>[0];
// message_delta usage is per-message cumulative; null or absent fields retain message_start values and zeros replace them.
function mergeClaudeStreamUsage(
current: ClaudeMessageUsage,
delta: {
readonly input_tokens?: number | null;
readonly cache_creation_input_tokens?: number | null;
readonly cache_read_input_tokens?: number | null;
readonly output_tokens: number;
},
): ClaudeMessageUsage {
return {
...current,
input_tokens: delta.input_tokens ?? current.input_tokens,
cache_creation_input_tokens:
delta.cache_creation_input_tokens ?? current.cache_creation_input_tokens ?? null,
cache_read_input_tokens:
delta.cache_read_input_tokens ?? current.cache_read_input_tokens ?? null,
output_tokens: delta.output_tokens,
};
}
export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_PROVIDER);
const CLAUDE_SCRIPT_EXTENSIONS = [".js", ".mjs", ".tsx", ".ts", ".jsx"];
// The SDK has no control-request deadline; the CLI waits up to 30 s per MCP server.
const CLAUDE_MCP_REGISTRATION_TIMEOUT = "90 seconds";
// Claude can consume a subagent result before the launching turn ends, leaving
// its notification with no native wake turn to answer the continuation.
const CLAUDE_WAKE_TURN_START_DEADLINE = "2 minutes";
// Claude Code flushes transcript writes every 100 ms, so a workflow member's
// reply can land after the progress frame that settles it. Its transcript
// stays the source of its answer this long after it settles.
const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500;
// A steer waits at most this long, from its request, for its foreground
// subagents to move to the background before it is sent.
const BACKGROUND_MOVE_TIMEOUT_MS = 5_000;
// How long a Stop waits for the CLI to exit before the user is offered Force stop.
const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000;
const CLAUDE_GROUP_WATCH_SCRIPT = [
"{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } </dev/null >/dev/null 2>&1 &",
'exec "$@" 3<&-',
].join("\n");
/**
* Kill the CLI's group on exit to stop MCP grandchildren; `onExit` stops its agent scope for
* setsid daemons. The CLI keeps working after its pipes close, so a watcher stops the group on
* EOF from a pipe only this server holds, including when the server crashes.
*/
export function spawnClaudeProcessGroup(
options: ClaudeSpawnOptions,
onExit?: () => void,
): ClaudeSpawnedProcess {
const child = NodeChildProcess.spawn(
"/bin/sh",
["-c", CLAUDE_GROUP_WATCH_SCRIPT, "t3-claude", options.command, ...options.args],
{
cwd: options.cwd,
env: options.env,
signal: options.signal,
stdio: ["pipe", "pipe", "ignore", "pipe"],
detached: true,
},
);
child.once("exit", () => {
try {
signalProcessGroup(child.pid ?? 0, "SIGKILL");
} catch {}
onExit?.();
});
// Node's typings make stdin and stdout nullable once stdio has a fourth entry; both are pipes.
return child as ClaudeSpawnedProcess;
}
export const ClaudeProviderCapabilitiesV2 = {
sessions: {
supportsMultipleProviderThreadsPerSession: false,
supportsModelSwitchInSession: true,
supportsProviderSwitchingViaHandoff: true,
supportsRuntimeModeSwitchInSession: false,
pendingRequestsSurviveRestart: false,
},
threads: {
canCreateEmptyThread: true,
canReadThreadSnapshot: false,
canRollbackThread: true,
canForkThread: true,
canForkFromTurn: true,
canForkFromSubagentThread: false,
exposesNativeThreadId: true,
},
turns: {
exposesNativeTurnId: false,
emitsTurnStarted: true,
emitsTurnCompleted: true,
supportsInterrupt: true,
supportsActiveSteering: true,
activeSteeringInterruptsTools: true,
supportsSteeringByInterruptRestart: false,
supportsQueuedMessages: true,
terminalStatusQuality: "strong",
},
streaming: {
streamsAssistantText: true,
streamsReasoning: true,
streamsToolOutput: false,
streamsPlanText: false,
emitsMessageCompleted: true,
},
tools: {
exposesToolItemIds: true,
emitsToolStarted: true,
emitsToolCompleted: true,
emitsToolOutput: true,
supportsMcpTools: true,
supportsDynamicToolCallbacks: true,
},
approvals: {
supportsCommandApproval: true,
supportsFileReadApproval: true,
supportsFileChangeApproval: true,
supportsApplyPatchApproval: false,
approvalsHaveNativeRequestIds: true,
approvalCallbacksAreLiveOnly: true,
approvalsCanOriginateFromSubagents: false,
},
planning: {
emitsPlanUpdated: true,
emitsTodoList: true,
emitsProposedPlan: true,
supportsStructuredQuestions: true,
planDeltasHaveItemIds: false,
},
subagents: {
supportsSubagents: true,
exposesSubagentThreadIds: false,
emitsSubagentLifecycle: true,
canWaitForSubagents: false,
canCloseSubagents: false,
canForkSubagentThread: false,
},
context: {
acceptsSystemContext: true,
acceptsDeveloperContext: true,
acceptsSyntheticUserContext: true,
canGenerateSummaries: true,
canConsumeHandoffSummaries: true,
supportsDeltaHandoff: true,
supportsFullThreadHandoff: true,
maxRecommendedHandoffChars: null,
},
checkpointing: {
appCanCheckpointFilesystem: true,
supportsNestedCheckpointScopes: true,
providerCanRollbackConversation: true,
providerRollbackReturnsSnapshot: true,
providerCanReadConversationSnapshot: false,
},
identity: {
nativeThreadIds: "strong",
nativeTurnIds: "weak",
nativeItemIds: "strong",
nativeRequestIds: "strong",
},
runtimePolicy: {
enforcement: "native",
},
} satisfies OrchestrationV2ProviderCapabilities;
const CLAUDE_CODE_PRESET_TOOLS = {
type: "preset",
preset: "claude_code",
} satisfies NonNullable<ClaudeQueryOptions["tools"]>;
export type ClaudeAgentSdkQueryToolList = ReadonlyArray<string>;
export interface ClaudeAgentSdkQueryPresetTools {
readonly type: "preset";
readonly preset: "claude_code";
}
export type ClaudeAgentSdkQueryTools = ClaudeAgentSdkQueryToolList | ClaudeAgentSdkQueryPresetTools;
export const CLAUDE_READ_ONLY_ALLOWED_TOOLS = ["Read", "Glob", "Grep"] as const;
function claudeAgentSdkQueryToolsForSdk(
tools: ClaudeAgentSdkQueryTools,
): NonNullable<ClaudeQueryOptions["tools"]> {
if (isClaudeAgentSdkQueryToolList(tools)) {
return [...tools];
}
return { type: tools.type, preset: tools.preset };
}
function isClaudeAgentSdkQueryToolList(
tools: ClaudeAgentSdkQueryTools,
): tools is ClaudeAgentSdkQueryToolList {
return Array.isArray(tools);
}
type ClaudeAgentSdkThreadIdentity =
| {
readonly sessionId: string;
readonly resume?: never;
}
| {
readonly sessionId?: never;
readonly resume: string;
};
export type ClaudeAgentSdkQueryOptions = Omit<
ClaudeQueryOptions,
"maxTurns" | "model" | "permissionMode" | "resume" | "sessionId" | "tools"
> & {
readonly model: string;
readonly tools: NonNullable<ClaudeQueryOptions["tools"]>;
readonly permissionMode: NonNullable<ClaudeQueryOptions["permissionMode"]>;
} & ClaudeAgentSdkThreadIdentity;
export interface ClaudeAgentSdkQueryOpenInput {
readonly options: ClaudeAgentSdkQueryOptions;
readonly threadId: ThreadId;
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
}
export interface ClaudeAgentSdkQuerySession {
readonly messages: Stream.Stream<SDKMessage, ClaudeAgentSdkQueryRunnerError>;
readonly offer: (
message: SDKUserMessage,
onQueued?: () => void,
) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly setModel: (model: string) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly applyFlagSettings: (
settings: ClaudeFlagSettings,
) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly setPermissionMode: (
mode: PermissionMode,
) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly stopTask: (taskId: string) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly backgroundTasks: (
toolUseId: string,
) => Effect.Effect<boolean, ClaudeAgentSdkQueryRunnerError>;
readonly interrupt: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly close: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
}
type ClaudeQueryStreamExit = Exit.Exit<void, ClaudeAgentSdkQueryRunnerError>;
export class ClaudeAgentSdkQueryRunnerError extends Schema.TaggedError<ClaudeAgentSdkQueryRunnerError>()(
"ClaudeAgentSdkQueryRunnerError",
{
method: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Claude Agent SDK query failed.";
}
}
class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError<ClaudeMcpRegistrationTimeoutError>()(
"ClaudeMcpRegistrationTimeoutError",
{},
) {
override get message(): string {
return "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.";
}
}
export class ClaudeBackgroundWorkBlocksQueryReplacementError extends Schema.TaggedError<ClaudeBackgroundWorkBlocksQueryReplacementError>()(
"ClaudeBackgroundWorkBlocksQueryReplacementError",
{},
) {
override get message(): string {
return "Claude is still running background agents or commands, and this model or setting change would end them. Wait for them to finish, or press Stop, then send the message again.";
}
}
export class ClaudeAppendSystemPromptFileError extends Schema.TaggedError<ClaudeAppendSystemPromptFileError>()(
"ClaudeAppendSystemPromptFileError",
{
path: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Claude could not read the --append-system-prompt-file launch argument at ${this.path}. Fix the path in the Claude launch arguments, then send the message again.`;
}
}
export class ClaudeAppendSystemPromptMissingValueError extends Schema.TaggedError<ClaudeAppendSystemPromptMissingValueError>()(
"ClaudeAppendSystemPromptMissingValueError",
{ flag: Schema.Literals(["--append-system-prompt", "--append-system-prompt-file"]) },
) {
override get message(): string {
return `The ${this.flag} launch argument has no ${this.flag === "--append-system-prompt" ? "text" : "file path"}. Add it after the flag in the Claude launch arguments, then send the message again.`;
}
}
export class ClaudeSettingsLaunchArgError extends Schema.TaggedError<ClaudeSettingsLaunchArgError>()(
"ClaudeSettingsLaunchArgError",
{
path: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Claude could not read the --settings launch argument${this.path === undefined ? "" : ` at ${this.path}`} as a JSON object. Fix it in the Claude launch arguments, then send the message again.`;
}
}
export interface ClaudeAgentSdkQueryRunnerShape {
readonly allocateSessionId: Effect.Effect<string, ClaudeAgentSdkQueryRunnerError>;
readonly open: (
input: ClaudeAgentSdkQueryOpenInput,
) => Effect.Effect<ClaudeAgentSdkQuerySession, ClaudeAgentSdkQueryRunnerError>;
readonly forkSession: (
input: ClaudeAgentSdkSessionForkInput,
) => Effect.Effect<
ForkSessionResult & { readonly headMessageId?: string },
ClaudeAgentSdkQueryRunnerError
>;
readonly subagentLaunchToolUseId: (
input: ClaudeAgentSdkSubagentLookupInput,
) => Effect.Effect<string | null, ClaudeAgentSdkQueryRunnerError>;
readonly assertComplete: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
}
export class ClaudeAgentSdkQueryRunner extends Context.Service<
ClaudeAgentSdkQueryRunner,
ClaudeAgentSdkQueryRunnerShape
>()("t3/orchestration-v2/Adapters/ClaudeAdapterV2/ClaudeAgentSdkQueryRunner") {}
export interface ClaudeAgentSdkSessionForkInput {
readonly sessionId: string;
readonly options: ForkSessionOptions;
readonly environment: NodeJS.ProcessEnv;
readonly threadId: ThreadId;
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
}
export interface ClaudeAgentSdkSubagentLookupInput {
readonly sessionId: string;
readonly agentId: string;
readonly dir: string | null;
readonly threadId: ThreadId;
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
}
const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAgentSdkQueryRunnerError);
const isClaudeMcpRegistrationTimeoutError = Schema.is(ClaudeMcpRegistrationTimeoutError);
const isProviderAdapterRuntimeRequestResponseError = Schema.is(
ProviderAdapter.ProviderAdapterRuntimeRequestResponseError,
);
const isProviderAdapterRollbackThreadError = Schema.is(
ProviderAdapter.ProviderAdapterRollbackThreadError,
);
function queryRunnerError(cause: unknown, method: string): ClaudeAgentSdkQueryRunnerError {
return isClaudeAgentSdkQueryRunnerError(cause)
? cause
: new ClaudeAgentSdkQueryRunnerError({ cause, method });
}
function closeClaudeQuery(queryRuntime: ClaudeQuery) {
return Effect.try({
try: () => queryRuntime.close(),
catch: (cause) => queryRunnerError(cause, "close"),
});
}
// Iterate Query itself: the raw generator's return() queues behind a pending CLI read and deadlocks interruption.
export function claudeQueryMessages(queryRuntime: ClaudeQuery): AsyncIterable<SDKMessage, void> {
return { [Symbol.asyncIterator]: () => queryRuntime };
}
export interface ClaudeAgentSdkLoggedQueryOptions {
readonly model: ClaudeAgentSdkQueryOptions["model"];
readonly tools: ClaudeAgentSdkQueryOptions["tools"];
readonly permissionMode: ClaudeAgentSdkQueryOptions["permissionMode"];
readonly sessionId?: string;
readonly resume?: string;
readonly resumeSessionAt?: ClaudeAgentSdkQueryOptions["resumeSessionAt"];
readonly cwd?: ClaudeAgentSdkQueryOptions["cwd"];
readonly allowedTools?: ClaudeAgentSdkQueryOptions["allowedTools"];
readonly disallowedTools?: ClaudeAgentSdkQueryOptions["disallowedTools"];
readonly settingKeys?: ReadonlyArray<string>;
readonly effort?: ClaudeAgentSdkQueryOptions["effort"];
readonly includePartialMessages?: true;
readonly pathToClaudeCodeExecutable?: ClaudeAgentSdkQueryOptions["pathToClaudeCodeExecutable"];
readonly hasExtraArgs?: true;
readonly allowDangerouslySkipPermissions?: true;
readonly hasCanUseTool?: true;
readonly hasEnvironment?: true;
readonly hasMcpServers?: true;
}
export type ClaudeAgentSdkProtocolLogEvent =
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.open";
readonly options: ClaudeAgentSdkLoggedQueryOptions;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "prompt.offer";
readonly message: SDKUserMessage;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.set_model";
readonly model: string;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.apply_flag_settings";
readonly settings: ClaudeFlagSettings;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.set_permission_mode";
readonly mode: PermissionMode;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.stop_task";
readonly taskId: string;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.background_tasks";
readonly toolUseId: string;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.interrupt";
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.close";
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "session.fork";
readonly sessionId: string;
readonly options: ForkSessionOptions;
};
}
| {
readonly direction: "incoming";
readonly stage: "decoded";
readonly payload: {
readonly type: "session.forked";
readonly sessionId: string;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "subagent.lookup";
readonly sessionId: string;
readonly agentId: string;
};
}
| {
readonly direction: "incoming";
readonly stage: "decoded";
readonly payload: {
readonly type: "subagent.found";
readonly toolUseId: string | null;
};
}
| {
readonly direction: "incoming";
readonly stage: "decoded";
readonly payload: SDKMessage;
};
export type ClaudeAgentSdkProtocolLogger = (
event: ClaudeAgentSdkProtocolLogEvent,
) => Effect.Effect<void>;
export function loggedClaudeQueryOptions(
options: ClaudeAgentSdkQueryOptions,
): ClaudeAgentSdkLoggedQueryOptions {
return {
model: options.model,
tools: options.tools,
permissionMode: options.permissionMode,
...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }),
...(options.resume === undefined ? {} : { resume: options.resume }),
...(options.resumeSessionAt === undefined ? {} : { resumeSessionAt: options.resumeSessionAt }),
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }),
...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }),
// Settings can carry the user's --settings values, such as an env block with credentials.
...(typeof options.settings === "object" && options.settings !== null
? { settingKeys: Object.keys(options.settings) }
: {}),
...(options.effort === undefined ? {} : { effort: options.effort }),
...(options.includePartialMessages === true ? { includePartialMessages: true } : {}),
...(options.pathToClaudeCodeExecutable === undefined
? {}
: { pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable }),
...(options.extraArgs === undefined ? {} : { hasExtraArgs: true }),
...(options.allowDangerouslySkipPermissions === true
? { allowDangerouslySkipPermissions: true }
: {}),
...(options.canUseTool === undefined ? {} : { hasCanUseTool: true }),
...(options.env === undefined ? {} : { hasEnvironment: true }),
...(options.mcpServers === undefined ? {} : { hasMcpServers: true }),
};
}
function makeClaudeAgentSdkProtocolLogger(input: {
readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;
readonly threadId: ThreadId;
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
}): ClaudeAgentSdkProtocolLogger | undefined {
const { nativeEventLogger } = input;
if (nativeEventLogger === undefined) {
return undefined;
}
return (event) => {
if (!shouldPersistProviderEvent("native", event)) return Effect.void;
return nativeEventLogger
.write(
{
provider: CLAUDE_PROVIDER,
protocol: CLAUDE_AGENT_SDK_QUERY_PROTOCOL,
kind: "protocol",
providerSessionId: input.providerSessionId,
event: boundProviderEventForLogging(event),
},
input.threadId,
)
.pipe(Effect.ignore);
};
}
const encodeClaudeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
const decodeClaudeHistoryFork = Schema.decodeUnknownEffect(
Schema.fromJsonString(
Schema.Struct({ sessionId: Schema.String, headMessageId: Schema.optionalKey(Schema.String) }),
),
);
const claudeConfigDirOf = (
path: Path.Path,
environment: NodeJS.ProcessEnv,
homeDirectory: string,
) => path.resolve(environment.CLAUDE_CONFIG_DIR ?? path.join(homeDirectory, ".claude"));
// The SDK reads CLAUDE_CONFIG_DIR from process.env. Isolate custom homes in a
// worker so concurrent providers keep the server's environment.
const runClaudeWorker = Effect.fn("runClaudeWorker")(function* (input: {
readonly method: "forkSession";
readonly sessionId: string;
readonly options?: ForkSessionOptions;
readonly environment: NodeJS.ProcessEnv;
}) {
const path = yield* Path.Path;
const fromSource = import.meta.url.endsWith(".ts");
// A single executable hosts the worker itself; it has no sibling script.
const workerArguments = (yield* HostProcess.IsExecutable)
? ["__claude-history"]
: [
...(fromSource ? ["--experimental-strip-types"] : []),
yield* path.fromFileUrl(
new URL(
fromSource ? "../../claude-history-worker.ts" : "./claude-history-worker.mjs",
import.meta.url,
),
),
];
const executablePath = yield* HostProcess.ExecutablePath;
const result = yield* spawnAndCollect(
executablePath,
ChildProcess.make(
executablePath,
[...workerArguments, input.method, input.sessionId, encodeClaudeJson(input.options ?? {})],
{
env: {
...input.environment,
ELECTRON_RUN_AS_NODE: "1",
},
},
),
).pipe(Effect.timeout("30 seconds"));
if (result.code !== 0) {
return yield* new ClaudeAgentSdkQueryRunnerError({
method: input.method,
cause: result.stderr.trim() || `Claude history worker exited with code ${result.code}.`,
});
}
return result.stdout;
});
const forkClaudeSessionInWorker = Effect.fn("forkClaudeSessionInWorker")(function* (
input: ClaudeAgentSdkSessionForkInput,
) {
return yield* runClaudeWorker({ ...input, method: "forkSession" }).pipe(
Effect.flatMap(decodeClaudeHistoryFork),
);
});
export const layerQueryRunner: Layer.Layer<
ClaudeAgentSdkQueryRunner,
never,
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| Path.Path
| PortScanner.PortDiscovery
| ProviderEventLoggers.ProviderEventLoggers
> = Layer.effect(
ClaudeAgentSdkQueryRunner,
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
const agentScope = yield* AgentScope;
const platform = yield* HostProcess.Platform;
const runFork = Effect.runForkWith(yield* Effect.context<never>());
const hostEnvironment = yield* HostProcess.Environment;
const portDiscovery = yield* PortScanner.PortDiscovery;
return ClaudeAgentSdkQueryRunner.of({
allocateSessionId: crypto
.randomUUIDv4()
.pipe(Effect.mapError((cause) => queryRunnerError(cause, "allocateSessionId"))),
open: Effect.fn("ClaudeAgentSdkQueryRunner.open")(
function* (input: ClaudeAgentSdkQueryOpenInput) {
const protocolLogger = makeClaudeAgentSdkProtocolLogger({
nativeEventLogger,
threadId: input.threadId,
providerSessionId: input.providerSessionId,
});
const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
protocolLogger === undefined ? Effect.void : protocolLogger(event);
// A failed open shuts down its queue before retrying, so the old CLI cannot take the prompt.
const promptQueue = yield* Queue.unbounded<SDKUserMessage>();
const prompt = Stream.fromQueue(promptQueue).pipe(
Stream.catchCause((cause) =>
Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
),
Stream.toAsyncIterable,
);
// Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments.
const { mcpServers, ...sdkOptions } = input.options;
// Jobs the agent starts inherit the thread, so port discovery can attribute their servers.
const queryOptions = {
...sdkOptions,
env: {
...(sdkOptions.env ?? hostEnvironment),
[PortScanner.AGENT_THREAD_ENV]: input.threadId,
},
};
// The SDK can prepend a scope wrapper to native binaries; script entries run through node.
const binaryPath = queryOptions.pathToClaudeCodeExecutable;
const launch =
binaryPath === undefined ||
CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext))
? undefined
: yield* agentScope.wrap({
command: binaryPath,
args: [],
name: "claude",
threadId: input.threadId,