-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclaude-sdk-runtime.ts
More file actions
6294 lines (5974 loc) · 203 KB
/
Copy pathclaude-sdk-runtime.ts
File metadata and controls
6294 lines (5974 loc) · 203 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 { createClaudeContextUsageTracker } from "./claude-context-usage";
import { recordClaudeRateLimitObservation } from "./rate-limits/claude-rate-limits-observation";
import { createClaudeCompactionTracker } from "./claude-compaction";
import {
CLAUDE_STAVE_LENS_INSTRUCTIONS,
CLAUDE_STAVE_NATIVE_BROWSER_INSTRUCTIONS,
} from "./claude-browser-instructions";
import { requireCompactResumeSession } from "../../src/lib/providers/native-compaction";
import type {
BridgeEvent,
ProviderResponderResult,
ProviderSteerResponder,
StreamTurnArgs,
} from "./types";
import {
buildProviderTurnPrompt,
isProviderNativeSlashCommandInput,
filterPromptRetrievedContext,
resolveProviderResumeSessionId,
} from "../../src/lib/providers/provider-request-translators";
import {
MAX_PROVIDER_APPROVAL_DESCRIPTION_CHARS,
sanitizeTextField,
} from "../../src/lib/file-context-sanitization";
import { parsePullRequestSuggestionResponse } from "../../src/lib/source-control-pr";
import { STAVE_MCP_SCOPED_RETRIEVED_CONTEXT_SOURCE_IDS } from "../../src/lib/task-context/current-task-awareness";
import { dedupeRetrievedContextForSession } from "./retrieved-context-dedup";
import {
buildIntentGuardPrompt,
buildReviewDiffPrompt,
parseReviewFindings,
type PrePrReviewFinding,
} from "../../src/lib/source-control-review";
import { isTrustedApproval } from "../../src/lib/providers/trusted-tools";
import { modelAcceptsExplicitEffort } from "../../src/lib/providers/model-effort";
import {
DEFAULT_CLAUDE_PLAN_MODE_APPROVAL_SCOPE,
type ClaudePlanModeApprovalScope,
type UserInputQuestion,
} from "../../src/types/chat";
import {
markRecommendedUserInputOptions,
optionLabelHasRecommendedSuffix,
readQuestionRecommendPointer,
readRawOptionRecommended,
recommendedOptionDefaultValue,
} from "../../src/lib/user-input-options";
import type {
ClaudeContextUsageResponse,
ClaudeFileRewindResponse,
ClaudeMcpOauthLoginResponse,
ClaudeMcpServerStatusSnapshot,
ClaudeInstalledPluginsResponse,
ClaudeMcpStatusResponse,
ClaudePluginReloadResponse,
ClaudeSessionForkResponse,
ProviderMutationResponse,
} from "../../src/lib/providers/provider.types";
import {
buildWorkerExecutionMetadata,
buildWorkerPrimaryInstructions,
resolveWorkerProfile,
toClaudeWorkerEffort,
type ResolvedWorkerProfile,
} from "../../src/lib/providers/worker-mode";
import type {
AgentDefinition,
CanUseTool,
HookCallback,
McpServerConfig,
McpServerStatus,
OnElicitation,
OnUserDialog,
Options,
Query,
SDKMessage,
SDKAssistantMessage,
SDKHookProgressMessage,
SDKHookResponseMessage,
SDKHookStartedMessage,
SDKInformationalMessage,
SDKPermissionDeniedMessage,
SDKControlGetContextUsageResponse,
SDKControlReloadPluginsResponse,
SDKSystemMessage,
SDKResultMessage,
SDKUserMessage,
SettingSource,
SlashCommand,
} from "@anthropic-ai/claude-agent-sdk";
import { toText } from "./utils";
import {
buildClaudeNativeImageBlocks,
buildClaudeNativeUserContent,
collectNativeImageInputs,
type ClaudeNativeImageBlock,
} from "./native-image-input";
import { createTurnDiffTracker } from "./turn-diff-tracker";
import { execFileSync } from "node:child_process";
import path from "node:path";
import { z } from "zod";
import {
canExecutePath,
normalizeExecutablePathValue,
} from "./executable-path";
import {
buildClaudeCliEnv,
resolveClaudeCliExecutablePath,
} from "./cli-path-env";
import {
readPrimaryStaveLocalMcpManifest,
STAVE_LOCAL_MCP_SERVER_NAME,
toClaudeSdkMcpServerConfig,
} from "../main/stave-local-mcp-manifest";
import { resolveBoundSecretEnv } from "../main/browser/secret-service";
import { stripReservedSecretEnvNames } from "../../src/lib/secrets/secrets";
import {
parseBooleanEnv,
parsePositiveIntEnv,
parseSemverVersion,
probeExecutableVersion,
summarizePathHead,
} from "./runtime-shared";
import {
createBoundedBridgeEventCollector,
measureBridgeEventBytes,
} from "./provider-buffering";
import {
getClaudeMcpConfigPaths,
McpConfigRefreshTracker,
} from "./mcp-config-refresh";
import {
resolveClaudeMcpServers,
type ClaudeMcpConfigDiagnostic,
} from "./claude-mcp-config";
import {
resolveClaudeInstalledPlugins,
resolveClaudePluginEnablement,
} from "./claude-plugin-config";
import { sanitizeMcpDiagnosticText } from "./mcp-config-management-shared";
import { isAlwaysAllowedStaveLocalMcpTool } from "./stave-local-mcp-approval";
import { DEFAULT_READ_ONLY_PROMPT_LABEL } from "./read-only-prompt-labels";
import {
isClaudeChromeToolName,
isPlainWebFetchToolName,
isProviderBrowserAuthWallOutput,
parseProviderBrowserDomains,
shouldActivateProviderBrowser,
} from "../../src/lib/provider-browser";
/**
* Cache boundary marker for the claude-agent-sdk systemPrompt string[] API.
* Matches the SDK's SYSTEM_PROMPT_DYNAMIC_BOUNDARY export — inlined here to
* avoid a flaky ESM named-value import in bun's parallel test runner.
*/
const SYSTEM_PROMPT_DYNAMIC_BOUNDARY = "__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__";
/** SDK-level permission modes accepted by the claude-agent-sdk query() API. */
type ClaudePermissionMode =
"default" | "acceptEdits" | "bypassPermissions" | "plan" | "dontAsk" | "auto";
const ClaudePermissionResultSchema = z.union([
z.object({
behavior: z.literal("allow"),
updatedInput: z.record(z.string(), z.unknown()),
}),
z.object({
behavior: z.literal("deny"),
message: z.string(),
interrupt: z.boolean().optional(),
}),
]);
type ClaudePermissionResult = z.infer<typeof ClaudePermissionResultSchema>;
const CLAUDE_MUTATING_FILE_TOOL_NAMES = [
"Edit",
"MultiEdit",
"Write",
"NotebookEdit",
] as const;
const CLAUDE_PLAN_MODE_MUTATING_TOOL_NAMES = new Set(
CLAUDE_MUTATING_FILE_TOOL_NAMES.map((toolName) => toolName.toLowerCase()),
);
const CLAUDE_AUTO_ALLOWED_TOOL_NAMES = new Set(["exitplanmode"]);
/**
* Claude Code built-in tools that cannot mutate the filesystem or task state.
* In plan mode these are safe to auto-allow — the whole point of plan mode is
* that only read-only work is permitted, so surfacing an approval prompt for
* each Read/Grep/Glob/WebFetch/WebSearch/BashOutput/NotebookRead call is pure
* noise. Bash is intentionally excluded: even "read-only" commands can have
* network side effects, so we keep prompting for it.
*
* TodoWrite is included because it only mutates the in-session todo tracker —
* no filesystem write — so blocking it in plan mode just broke the agent's
* own progress tracking and caused mid-plan stalls.
*/
const CLAUDE_READ_ONLY_BUILTIN_TOOL_NAMES = new Set([
"read",
"grep",
"glob",
"ls",
"notebookread",
"webfetch",
"websearch",
"bashoutput",
"todoread",
"todowrite",
]);
const STAVE_LOCAL_MCP_TOOL_PREFIX = "mcp__stave-local-mcp__";
/**
* Tokens that mark a (non-Stave) MCP tool as read-only vs. mutating, used to
* decide whether plan mode can auto-allow third-party / lens MCP calls when the
* approval scope is `bashTaskAndMcp`. An MCP tool is treated as read-only only
* when it contains a read verb AND no write verb — anything ambiguous keeps
* prompting, so misclassification fails safe (toward asking the user).
*/
const CLAUDE_MCP_READ_VERB_TOKENS = new Set([
"get",
"list",
"search",
"read",
"fetch",
"query",
"describe",
"inspect",
"view",
"snapshot",
"screenshot",
"measure",
"lookup",
"resolve",
"status",
"log",
"logs",
"show",
"find",
"count",
"whoami",
"info",
"summary",
"summarize",
"summarise",
"history",
]);
const CLAUDE_MCP_WRITE_VERB_TOKENS = new Set([
"create",
"update",
"delete",
"write",
"add",
"remove",
"set",
"post",
"put",
"patch",
"send",
"merge",
"upload",
"edit",
"move",
"rename",
"transition",
"comment",
"reply",
"schedule",
"run",
"execute",
"install",
"push",
"fork",
"assign",
"react",
"cancel",
"close",
"open",
"navigate",
"click",
"type",
"download",
"evaluate",
"start",
"stop",
"apply",
"submit",
"approve",
"reject",
"clear",
"replace",
"mutate",
"destroy",
"drop",
"truncate",
"revoke",
"grant",
"modify",
"disable",
"enable",
"toggle",
"trigger",
"fire",
"dispatch",
"publish",
"archive",
"restore",
"import",
"export",
"sync",
"refresh",
"invalidate",
"purge",
"flush",
"register",
"unregister",
"link",
"unlink",
"attach",
"detach",
]);
const CLAUDE_EVENT_RETAINED_BYTES_MAX = 2 * 1024 * 1024;
const CLAUDE_OVERFLOW_TAIL_EVENTS: BridgeEvent[] = [
{
type: "error",
message:
"Claude turn output was truncated in non-stream replay because the retained snapshot limit was exceeded.",
recoverable: true,
},
{ type: "done", stop_reason: "output_overflow" },
];
const CLAUDE_OVERFLOW_TAIL_BYTES = CLAUDE_OVERFLOW_TAIL_EVENTS.reduce(
(total, event) => total + measureBridgeEventBytes(event),
0,
);
const CLAUDE_MUTATING_BASH_PATTERNS = [
/(^|[;&|]\s*)(mkdir|mktemp|rm|rmdir|mv|cp|install|touch|chmod|chown|ln|truncate)\b/i,
/(^|[;&|]\s*)git\s+(add|am|apply|checkout|cherry-pick|clean|commit|merge|rebase|reset|restore|revert|rm|stash)\b/i,
/(^|[;&|]\s*)(npm|pnpm|yarn|bun)\s+(add|install|remove|rm|uninstall|update|upgrade)\b/i,
/(^|[;&|]\s*)(sed|perl)\b[^\n]*\s-i(?:\s|$)/i,
/(^|[;&|]\s*)tee\b/i,
/(^|[;&|]\s*)cat\b[^\n]*\s\d*(?:>>|>(?![&]))/i,
/\s\d*(?:>>|>(?![&]))/,
] as const;
const CLAUDE_SECONDARY_NETWORK_BASH_PATTERNS = [
/(^|[;&|]\s*)(curl|wget|ssh|scp|sftp|ftp|telnet|nc|ncat)\b/i,
/(^|[;&|]\s*)git\s+(clone|fetch|pull|push|ls-remote)\b/i,
/\bhttps?:\/\//i,
] as const;
// ---------------------------------------------------------------------------
// Prewarm: eagerly cache the SDK module import and executable path resolution
// so the first query() call doesn't pay those costs.
// ---------------------------------------------------------------------------
let prewarmSdkModulePromise: Promise<
typeof import("@anthropic-ai/claude-agent-sdk")
> | null = null;
let prewarmExecutablePath: string | null = null;
async function getPrewarmedSdkModule(): Promise<
typeof import("@anthropic-ai/claude-agent-sdk")
> {
if (!prewarmSdkModulePromise) {
prewarmSdkModulePromise = import("@anthropic-ai/claude-agent-sdk");
}
return prewarmSdkModulePromise;
}
function getPrewarmedExecutablePath(): string {
if (prewarmExecutablePath == null) {
prewarmExecutablePath = resolveClaudeExecutablePath();
}
return prewarmExecutablePath;
}
function resolveClaudeRuntimeExecutablePath(args: {
runtimeOptions?: StreamTurnArgs["runtimeOptions"];
}) {
const explicitPath = normalizeExecutablePathValue({
value: args.runtimeOptions?.claudeBinaryPath,
});
if (explicitPath) {
return explicitPath;
}
return getPrewarmedExecutablePath();
}
/**
* Trigger eager SDK module import.
* Call this early (e.g. at app startup) so the first query() is fast.
* Safe to call multiple times — subsequent calls are no-ops.
*/
export function prewarmClaudeSdk(): void {
getPrewarmedSdkModule().catch(() => {
// Reset so next attempt retries
prewarmSdkModulePromise = null;
});
// CLI discovery invokes login shells and candidate version probes. Resolve
// it when needed instead of blocking the host's ready handshake and every
// unrelated request during startup.
}
function resolveClaudePermissionMode(args: {
runtimeValue?: ClaudePermissionMode;
envValue?: string;
fallback: ClaudePermissionMode;
}): ClaudePermissionMode {
const candidate = args.runtimeValue ?? args.envValue;
if (
candidate === "default" ||
candidate === "acceptEdits" ||
candidate === "bypassPermissions" ||
candidate === "plan" ||
candidate === "dontAsk" ||
candidate === "auto"
) {
return candidate;
}
return args.fallback;
}
export function resolveClaudeExecutablePath(
args: { explicitPath?: string } = {},
) {
return resolveClaudeCliExecutablePath({
explicitPath: args.explicitPath,
});
}
export function buildClaudeEnv(args: { executablePath: string; cwd?: string }) {
return buildClaudeCliEnv({
executablePath: args.executablePath,
cwd: args.cwd,
});
}
function buildClaudeDiagnostics(args: {
executablePath: string;
taskId?: string;
cwd: string;
}) {
const env = buildClaudeEnv({ executablePath: args.executablePath });
const versionProbe = args.executablePath
? probeExecutableVersion({
executablePath: args.executablePath,
env,
})
: null;
return {
taskId: args.taskId ?? "default",
cwd: args.cwd,
executablePath: args.executablePath || "<sdk-default>",
executableExists: args.executablePath
? canExecutePath({ path: args.executablePath })
: null,
envPathHead: summarizePathHead({ value: env.PATH }),
claudeConfigDir: env.CLAUDE_CONFIG_DIR?.trim() || null,
electronEnv: {
ELECTRON_RUN_AS_NODE: process.env.ELECTRON_RUN_AS_NODE ?? "",
ELECTRON_NO_ATTACH_CONSOLE: process.env.ELECTRON_NO_ATTACH_CONSOLE ?? "",
ELECTRON_NO_ASAR: process.env.ELECTRON_NO_ASAR ?? "",
},
versionProbe: versionProbe
? {
status: versionProbe.status,
signal: versionProbe.signal,
error: versionProbe.error,
stdout: versionProbe.stdout,
stderr: versionProbe.stderr,
}
: null,
};
}
function normalizeClaudeToolInput(input: unknown): Record<string, unknown> {
if (!input || typeof input !== "object" || Array.isArray(input)) {
return {};
}
return input as Record<string, unknown>;
}
function normalizeClaudeSkillSlug(value: string) {
const trimmed = value.trim();
if (!trimmed) {
return null;
}
const firstToken = trimmed.split(/\s+/)[0] ?? "";
const withoutPrefix = firstToken.replace(/^[/$]+/, "");
const slug = withoutPrefix.match(/^[A-Za-z0-9._-]+/)?.[0]?.toLowerCase();
return slug || null;
}
function extractClaudeSkillSlugFromRecord(input: Record<string, unknown>) {
const candidateKeys = [
"skill",
"slug",
"name",
"command",
"skill_name",
"skillName",
] as const;
for (const key of candidateKeys) {
const value = input[key];
if (typeof value !== "string") {
continue;
}
const slug = normalizeClaudeSkillSlug(value);
if (slug) {
return slug;
}
}
return null;
}
export function extractClaudeRequestedSkillSlug(args: {
input: Record<string, unknown>;
}) {
const direct = extractClaudeSkillSlugFromRecord(args.input);
if (direct) {
return direct;
}
const nestedInput = args.input.input;
if (
nestedInput &&
typeof nestedInput === "object" &&
!Array.isArray(nestedInput)
) {
return extractClaudeSkillSlugFromRecord(
nestedInput as Record<string, unknown>,
);
}
return null;
}
export function shouldRedirectClaudePreloadedSkillToolUse(args: {
toolName: string;
input: Record<string, unknown>;
preloadedSkillSlugs: ReadonlySet<string>;
}) {
if (args.toolName.trim().toLowerCase() !== "skill") {
return null;
}
if (args.preloadedSkillSlugs.size === 0) {
return null;
}
const slug = extractClaudeRequestedSkillSlug({ input: args.input });
if (!slug || !args.preloadedSkillSlugs.has(slug)) {
return null;
}
return slug;
}
function collectClaudeActivatedSkillSlugs(args: {
conversation?: StreamTurnArgs["conversation"];
}) {
const activatedSkillSlugs = new Set<string>();
args.conversation?.contextParts.forEach((part) => {
if (part.type !== "skill_context") {
return;
}
part.skills.forEach((skill) => {
[skill.slug, skill.invocationToken, skill.name].forEach((value) => {
const normalized = normalizeClaudeSkillSlug(value);
if (normalized) {
activatedSkillSlugs.add(normalized);
}
});
});
});
return activatedSkillSlugs;
}
function validateClaudePermissionResult(args: {
candidate: ClaudePermissionResult;
fallbackMessage: string;
context: string;
}): ClaudePermissionResult {
const parsed = ClaudePermissionResultSchema.safeParse(args.candidate);
if (parsed.success) {
return parsed.data;
}
console.warn(
"[claude-sdk-runtime] invalid permission callback result; falling back to deny",
{
context: args.context,
error: parsed.error.flatten(),
},
);
return {
behavior: "deny",
message: args.fallbackMessage,
};
}
function buildClaudeDenyPermissionResult(args: {
message: string;
context: string;
interrupt?: boolean;
}): ClaudePermissionResult {
return validateClaudePermissionResult({
candidate: {
behavior: "deny",
message: args.message,
...(typeof args.interrupt === "boolean"
? { interrupt: args.interrupt }
: {}),
},
fallbackMessage: args.message,
context: args.context,
});
}
function extractClaudeBashCommand(input: Record<string, unknown>) {
for (const key of ["command", "cmd", "script", "bash", "input"] as const) {
const value = input[key];
if (typeof value === "string" && value.trim().length > 0) {
return value.trim();
}
}
const rendered = toText(input).trim();
return rendered.length > 0 ? rendered : undefined;
}
function isMutatingClaudeBashCommand(command: string) {
return CLAUDE_MUTATING_BASH_PATTERNS.some((pattern) => pattern.test(command));
}
export function shouldDenyClaudeToolInSecondaryReadOnly(args: {
toolName: string;
input: Record<string, unknown>;
}) {
const toolName = args.toolName.trim().toLowerCase();
if (toolName === "read" || toolName === "glob" || toolName === "grep") {
return false;
}
if (toolName !== "bash") {
return true;
}
const command = extractClaudeBashCommand(args.input);
if (!command || isMutatingClaudeBashCommand(command)) {
return true;
}
return CLAUDE_SECONDARY_NETWORK_BASH_PATTERNS.some((pattern) =>
pattern.test(command),
);
}
/**
* Tools that stay globally disallowed while plan mode is active. Unlike Write,
* Edit / MultiEdit / NotebookEdit always target existing source files and
* never a handoff plan file — so there is no reason to route them through the
* per-call gate.
*/
const CLAUDE_PLAN_MODE_DISALLOWED_TOOL_NAMES = [
"Edit",
"MultiEdit",
"NotebookEdit",
] as const;
/**
* Matches `.stave/context/plans/<file>.md` anywhere in a path, so both
* absolute workspace-rooted paths ("/workspace/.../.stave/context/plans/x.md")
* and workspace-relative paths (".stave/context/plans/x.md") resolve as
* handoff plan files.
*/
const CLAUDE_HANDOFF_PLAN_FILE_PATTERN =
/(?:^|\/)\.stave\/context\/plans\/[^\\/]+\.md$/;
function isHandoffPlanFilePath(value: unknown): value is string {
return (
typeof value === "string" &&
CLAUDE_HANDOFF_PLAN_FILE_PATTERN.test(value.trim())
);
}
export function resolveClaudeDisallowedTools(args: {
permissionMode: ClaudePermissionMode;
runtimeDisallowedTools?: readonly string[] | null;
}) {
const merged = new Set<string>();
if (Array.isArray(args.runtimeDisallowedTools)) {
args.runtimeDisallowedTools.forEach((toolName) => {
if (typeof toolName === "string" && toolName.trim().length > 0) {
merged.add(toolName.trim());
}
});
}
if (args.permissionMode === "plan") {
CLAUDE_PLAN_MODE_DISALLOWED_TOOL_NAMES.forEach((toolName) => {
merged.add(toolName);
});
}
return [...merged];
}
/**
* Builds the single named worker registered for Worker mode.
*
* Returns `undefined` whenever the intent is absent or fails semantic
* resolution, so an unsupported primary/model combination degrades to the
* normal solo path rather than silently spawning a different tier.
*
* Three guarantees are load-bearing here:
*
* - `background` is never set. Stave's turn loop cannot deliver a background
* completion notification, and the SDK strips most tools from background
* subagents anyway, so the worker must stay foreground.
* - `permissionMode` mirrors the parent turn, so a plan/read-only turn cannot
* gain write capability by delegating.
* - `effort` is omitted when the resolver reports `null`, because Haiku-class
* models reject the field outright.
*/
export function buildClaudeWorkerAgents(args: {
runtimeOptions?: StreamTurnArgs["runtimeOptions"];
permissionMode: ClaudePermissionMode;
}): Record<string, AgentDefinition> | undefined {
const intent = args.runtimeOptions?.workerIntent;
if (!intent) {
return undefined;
}
const resolution = resolveWorkerProfile({
providerId: "claude-code",
primaryModel: args.runtimeOptions?.model ?? "",
intent,
});
if (resolution.status !== "ready") {
return undefined;
}
const { profile } = resolution;
// `AgentDefinition.effort` has no `ultra` tier, so narrow before assigning.
const effort = toClaudeWorkerEffort(profile.resolvedWorkerEffort);
return {
[profile.workerName]: {
description: profile.description,
prompt: profile.instructions,
model: profile.resolvedWorkerModel,
...(effort ? { effort } : {}),
...(profile.tools && profile.tools.length > 0
? { tools: [...profile.tools] }
: {}),
...(profile.maxTurns !== null ? { maxTurns: profile.maxTurns } : {}),
// Inherit rather than widen: the worker runs under the parent's policy so
// approvals and denials keep attributing to the same turn.
permissionMode: args.permissionMode,
},
};
}
export function shouldDenyClaudeToolInPlanMode(args: {
toolName: string;
input: Record<string, unknown>;
}) {
const normalizedToolName = args.toolName.trim().toLowerCase();
if (CLAUDE_PLAN_MODE_MUTATING_TOOL_NAMES.has(normalizedToolName)) {
// Write is the one mutating tool we conditionally allow: the handoff
// convention writes plan files into `.stave/context/plans/**`, and the
// runtime already treats that directory as session metadata.
if (
normalizedToolName === "write" &&
isHandoffPlanFilePath(args.input.file_path)
) {
return false;
}
return true;
}
if (normalizedToolName !== "bash") {
return false;
}
const command = extractClaudeBashCommand(args.input);
return typeof command === "string" && isMutatingClaudeBashCommand(command);
}
export function resolveClaudePermissionModeDecision(args: {
permissionMode: ClaudePermissionMode;
toolName: string;
}) {
const normalizedToolName = args.toolName.trim().toLowerCase();
// AskUserQuestion requests information, not permission to perform an action.
// Keep it interactive even when action approvals are bypassed or denied.
if (normalizedToolName === "askuserquestion") {
return "prompt" as const;
}
if (CLAUDE_AUTO_ALLOWED_TOOL_NAMES.has(normalizedToolName)) {
return "allow" as const;
}
if (isAlwaysAllowedStaveLocalMcpTool(normalizedToolName)) {
return "allow" as const;
}
if (
(args.permissionMode === "auto" || args.permissionMode === "dontAsk") &&
normalizedToolName.startsWith(STAVE_LOCAL_MCP_TOOL_PREFIX)
) {
return "allow" as const;
}
if (args.permissionMode === "bypassPermissions") {
return "allow" as const;
}
if (
(args.permissionMode === "acceptEdits" || args.permissionMode === "auto") &&
CLAUDE_PLAN_MODE_MUTATING_TOOL_NAMES.has(normalizedToolName)
) {
return "allow" as const;
}
// Plan mode is read-only by construction: mutating tools are hard-denied in
// the canUseTool callback, so every remaining Claude Code built-in read tool
// can be auto-allowed. Prompting the user for each Read/Grep/Glob call in a
// read-only mode is redundant friction.
if (
args.permissionMode === "plan" &&
CLAUDE_READ_ONLY_BUILTIN_TOOL_NAMES.has(normalizedToolName)
) {
return "allow" as const;
}
if (args.permissionMode === "dontAsk") {
return "deny" as const;
}
return "prompt" as const;
}
export function shouldAutoAllowClaudeTool(args: {
toolName: string;
permissionMode?: ClaudePermissionMode;
}) {
return (
resolveClaudePermissionModeDecision({
permissionMode: args.permissionMode ?? "default",
toolName: args.toolName,
}) === "allow"
);
}
export function resolveClaudePlanModeApprovalScope(args: {
runtimeValue?: ClaudePlanModeApprovalScope;
envValue?: string;
}): ClaudePlanModeApprovalScope {
const candidate = args.runtimeValue ?? args.envValue;
if (
candidate === "strict" ||
candidate === "bash" ||
candidate === "bashAndTask" ||
candidate === "bashTaskAndMcp"
) {
return candidate;
}
return DEFAULT_CLAUDE_PLAN_MODE_APPROVAL_SCOPE;
}
/**
* Classifies a non-Stave MCP tool (by its leaf name, e.g. `get_file_contents`
* or `slack_search_public`) as read-only. Returns true only when the name
* carries a read verb and no write verb, so anything ambiguous (e.g.
* `lens_navigate`, `create_pull_request`) stays gated behind an approval.
*/
export function isReadOnlyMcpLeafToolName(leafToolName: string): boolean {
const tokens = leafToolName
// Split camelCase boundaries ("searchJiraIssues" → "search Jira Issues")
// before lowercasing so camelCase MCP tool names tokenize like snake_case.
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.toLowerCase()
.split(/[^a-z0-9]+/)
.filter(Boolean);
if (tokens.length === 0) {
return false;
}
if (tokens.some((token) => CLAUDE_MCP_WRITE_VERB_TOKENS.has(token))) {
return false;
}
return tokens.some((token) => CLAUDE_MCP_READ_VERB_TOKENS.has(token));
}
/**
* Plan mode is read-only by construction — mutating file tools and mutating
* Bash are hard-denied before this runs. This decides whether a *non-mutating*
* tool call should skip the approval prompt based on the user's configured
* plan-mode approval scope, so planning feels as frictionless as auto mode
* without ever letting a mutation through.
*/
export function shouldAutoAllowPlanModeScopedTool(args: {
scope: ClaudePlanModeApprovalScope;
toolName: string;
input: Record<string, unknown>;
}): boolean {
if (args.scope === "strict") {
return false;
}
const normalizedToolName = args.toolName.trim().toLowerCase();
// Bash: only non-mutating commands. Mutating Bash is hard-denied upstream,
// but re-check here so the helper is correct in isolation.
if (normalizedToolName === "bash") {
const command = extractClaudeBashCommand(args.input);
return typeof command === "string" && !isMutatingClaudeBashCommand(command);
}
// Subagents (Task). The nested subagent's own tool calls still flow through
// this same canUseTool gate, so mutations remain hard-denied even when the
// spawn itself is auto-allowed.
if (normalizedToolName === "task") {
return args.scope === "bashAndTask" || args.scope === "bashTaskAndMcp";
}
// Read-only third-party / lens MCP tools, only at the broadest scope. Stave
// workspace MCP tools are already auto-allowed earlier, so this targets
// external servers (github, slack, lens, …).
if (
args.scope === "bashTaskAndMcp" &&
normalizedToolName.startsWith("mcp__")
) {
const leafToolName =
normalizedToolName.split("__").at(-1) ?? normalizedToolName;
return isReadOnlyMcpLeafToolName(leafToolName);
}
return false;
}
/**
* Once a plan was presented via ExitPlanMode in a plan-mode turn, every later
* tool call (except re-presenting an updated plan) must be denied so the agent
* stops and the turn completes — Stave has already captured the plan for review.
*/
export function shouldDenyClaudePostPlanTool(args: {
permissionMode: ClaudePermissionMode;
planPresented: boolean;
toolName: string;
}): boolean {
return (
args.permissionMode === "plan" &&
args.planPresented &&
args.toolName.trim().toLowerCase() !== "exitplanmode"
);
}
function resolveTrustedApprovalInput(args: {
toolName: string;
input: Record<string, unknown>;
}) {
if (args.toolName.trim().toLowerCase() === "bash") {
return extractClaudeBashCommand(args.input)?.trim() || undefined;
}
return undefined;
}
async function resolveEmbeddedStaveLocalMcpServers(options?: {
collaborationGrants?: StreamTurnArgs["staveCollaborationGrants"];
unattendedAutomationAuthorizationToken?: string;
}): Promise<Record<string, McpServerConfig> | undefined> {
const manifest = await readPrimaryStaveLocalMcpManifest();
if (!manifest) {
if (options?.collaborationGrants?.consultKey) {
throw new Error(
"Advisor is armed, but Stave Local MCP is unavailable. Start it in Settings and retry the turn.",
);
}
return undefined;
}
return {
[STAVE_LOCAL_MCP_SERVER_NAME]: toClaudeSdkMcpServerConfig(manifest, {
collaborationGrants: options?.collaborationGrants ?? {},
unattendedAutomationAuthorizationToken:
options?.unattendedAutomationAuthorizationToken,
}),
};
}
function logClaudeMcpConfigDiagnostic(diagnostic: ClaudeMcpConfigDiagnostic) {
console.warn("[claude-sdk-runtime] skipped Claude MCP configuration", {
kind: diagnostic.kind,
source: diagnostic.source,
...(diagnostic.serverName ? { serverName: diagnostic.serverName } : {}),
});
}
async function resolveClaudeMcpServersForQuery(args: {
collaborationGrants?: StreamTurnArgs["staveCollaborationGrants"];
cwd: string;
claudeExecutablePath: string;
runtimeOptions?: StreamTurnArgs["runtimeOptions"];
claudeConfigDir?: string;
unattendedAutomationAuthorizationToken?: string;
}) {
const staveServers = await resolveEmbeddedStaveLocalMcpServers({
collaborationGrants: args.collaborationGrants,
unattendedAutomationAuthorizationToken:
args.unattendedAutomationAuthorizationToken,
});
const claudeConfigDir =
args.claudeConfigDir ??
buildClaudeEnv({
executablePath: args.claudeExecutablePath,
cwd: args.cwd,
}).CLAUDE_CONFIG_DIR;
const mcpServers = await resolveClaudeMcpServers({
cwd: args.cwd,
claudeConfigDir,
staveServers,
strict: args.runtimeOptions?.claudeStrictMcpConfig === true,
onDiagnostic: logClaudeMcpConfigDiagnostic,
onStaveOverride: ({ serverName, replacedSource }) => {
console.warn(