-
Notifications
You must be signed in to change notification settings - Fork 16k
Expand file tree
/
Copy pathmain.tsx
More file actions
7049 lines (6632 loc) · 232 KB
/
main.tsx
File metadata and controls
7049 lines (6632 loc) · 232 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
// These side-effects must run before all other imports:
// 1. profileCheckpoint marks entry before heavy module evaluation begins
// 2. startMdmRawRead fires MDM subprocesses (plutil/reg query) so they run in
// parallel with the remaining ~135ms of imports below
// 3. startKeychainPrefetch fires both macOS keychain reads (OAuth + legacy API
// key) in parallel — isRemoteManagedSettingsEligible() otherwise reads them
// sequentially via sync spawn inside applySafeConfigEnvironmentVariables()
// (~65ms on every macOS startup)
import { profileCheckpoint, profileReport } from "./utils/startupProfiler.js";
// eslint-disable-next-line custom-rules/no-top-level-side-effects
profileCheckpoint("main_tsx_entry");
import { startMdmRawRead } from "./utils/settings/mdm/rawRead.js";
// eslint-disable-next-line custom-rules/no-top-level-side-effects
startMdmRawRead();
import {
ensureKeychainPrefetchCompleted,
startKeychainPrefetch,
} from "./utils/secureStorage/keychainPrefetch.js";
// eslint-disable-next-line custom-rules/no-top-level-side-effects
startKeychainPrefetch();
import { feature } from "bun:bundle";
import {
Command as CommanderCommand,
InvalidArgumentError,
Option,
} from '@commander-js/extra-typings'
import chalk from 'chalk'
import { readFileSync } from 'fs'
import mapValues from 'lodash-es/mapValues.js'
import pickBy from 'lodash-es/pickBy.js'
import uniqBy from 'lodash-es/uniqBy.js'
import React from 'react'
import { getOauthConfig } from './constants/oauth.js'
import { getRemoteSessionUrl } from './constants/product.js'
import { getSystemContext, getUserContext } from './context.js'
import { init, initializeTelemetryAfterTrust } from './entrypoints/init.js'
import { addToHistory } from './history.js'
import type { Root } from '@anthropic/ink'
import { launchRepl } from './replLauncher.js'
import {
hasGrowthBookEnvOverride,
initializeGrowthBook,
refreshGrowthBookAfterAuthChange,
} from "./services/analytics/growthbook.js";
import { fetchBootstrapData } from "./services/api/bootstrap.js";
import {
type DownloadResult,
downloadSessionFiles,
type FilesApiConfig,
parseFileSpecs,
} from "./services/api/filesApi.js";
import { prefetchPassesEligibility } from "./services/api/referral.js";
import type {
McpSdkServerConfig,
McpServerConfig,
ScopedMcpServerConfig,
} from "./services/mcp/types.js";
import {
isPolicyAllowed,
loadPolicyLimits,
refreshPolicyLimits,
waitForPolicyLimitsToLoad,
} from "./services/policyLimits/index.js";
import {
loadRemoteManagedSettings,
refreshRemoteManagedSettings,
} from "./services/remoteManagedSettings/index.js";
import type { ToolInputJSONSchema } from "./Tool.js";
import {
createSyntheticOutputTool,
isSyntheticOutputToolEnabled,
} from "@claude-code-best/builtin-tools/tools/SyntheticOutputTool/SyntheticOutputTool.js";
import { getTools } from "./tools.js";
import {
canUserConfigureAdvisor,
getInitialAdvisorSetting,
isAdvisorEnabled,
isValidAdvisorModel,
modelSupportsAdvisor,
} from "./utils/advisor.js";
import { isAgentSwarmsEnabled } from "./utils/agentSwarmsEnabled.js";
import { count, uniq } from "./utils/array.js";
import { installAsciicastRecorder } from "./utils/asciicast.js";
import {
getSubscriptionType,
isClaudeAISubscriber,
prefetchAwsCredentialsAndBedRockInfoIfSafe,
prefetchGcpCredentialsIfSafe,
validateForceLoginOrg,
} from "./utils/auth.js";
import {
checkHasTrustDialogAccepted,
getGlobalConfig,
getRemoteControlAtStartup,
isAutoUpdaterDisabled,
saveGlobalConfig,
} from "./utils/config.js";
import { seedEarlyInput, stopCapturingEarlyInput } from "./utils/earlyInput.js";
import { getInitialEffortSetting, parseEffortValue } from "./utils/effort.js";
import {
getInitialFastModeSetting,
isFastModeEnabled,
prefetchFastModeStatus,
resolveFastModeStatusFromCache,
} from "./utils/fastMode.js";
import { applyConfigEnvironmentVariables } from "./utils/managedEnv.js";
import { createSystemMessage, createUserMessage } from "./utils/messages.js";
import { getPlatform } from "./utils/platform.js";
import { getBaseRenderOptions } from "./utils/renderOptions.js";
import { getSessionIngressAuthToken } from "./utils/sessionIngressAuth.js";
import { settingsChangeDetector } from "./utils/settings/changeDetector.js";
import { skillChangeDetector } from "./utils/skills/skillChangeDetector.js";
import { jsonParse, writeFileSync_DEPRECATED } from "./utils/slowOperations.js";
import { computeInitialTeamContext } from "./utils/swarm/reconnection.js";
import { initializeWarningHandler } from "./utils/warningHandler.js";
import { isWorktreeModeEnabled } from "./utils/worktreeModeEnabled.js";
// Lazy require to avoid circular dependency: teammate.ts -> AppState.tsx -> ... -> main.tsx
/* eslint-disable @typescript-eslint/no-require-imports */
const getTeammateUtils = () =>
require("./utils/teammate.js") as typeof import("./utils/teammate.js");
const getTeammatePromptAddendum = () =>
require("./utils/swarm/teammatePromptAddendum.js") as typeof import("./utils/swarm/teammatePromptAddendum.js");
const getTeammateModeSnapshot = () =>
require("./utils/swarm/backends/teammateModeSnapshot.js") as typeof import("./utils/swarm/backends/teammateModeSnapshot.js");
/* eslint-enable @typescript-eslint/no-require-imports */
// Dead code elimination: conditional import for COORDINATOR_MODE
/* eslint-disable @typescript-eslint/no-require-imports */
const coordinatorModeModule = feature("COORDINATOR_MODE")
? (require("./coordinator/coordinatorMode.js") as typeof import("./coordinator/coordinatorMode.js"))
: null;
/* eslint-enable @typescript-eslint/no-require-imports */
// Dead code elimination: conditional import for KAIROS (assistant mode)
/* eslint-disable @typescript-eslint/no-require-imports */
const assistantModule = feature("KAIROS")
? (require("./assistant/index.js") as typeof import("./assistant/index.js"))
: null;
const kairosGate = feature("KAIROS")
? (require("./assistant/gate.js") as typeof import("./assistant/gate.js"))
: null;
import { relative, resolve } from "path";
import { isAnalyticsDisabled } from "src/services/analytics/config.js";
import { getFeatureValue_CACHED_MAY_BE_STALE } from "src/services/analytics/growthbook.js";
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from 'src/services/analytics/index.js'
import { initializeAnalyticsGates } from 'src/services/analytics/sink.js'
import {
getOriginalCwd,
setAdditionalDirectoriesForClaudeMd,
setIsRemoteMode,
setMainLoopModelOverride,
setMainThreadAgentType,
setTeleportedSessionInfo,
} from "./bootstrap/state.js";
import { filterCommandsForRemoteMode, getCommands } from "./commands.js";
import type { StatsStore } from "./context/stats.js";
import {
launchAssistantInstallWizard,
launchAssistantSessionChooser,
launchInvalidSettingsDialog,
launchResumeChooser,
launchSnapshotUpdateDialog,
launchTeleportRepoMismatchDialog,
launchTeleportResumeWrapper,
} from './dialogLaunchers.js'
import { SHOW_CURSOR } from '@anthropic/ink'
import {
exitWithError,
exitWithMessage,
getRenderContext,
renderAndRun,
showSetupScreens,
} from "./interactiveHelpers.js";
import { initBuiltinPlugins } from "./plugins/bundled/index.js";
/* eslint-enable @typescript-eslint/no-require-imports */
import { checkQuotaStatus } from "./services/claudeAiLimits.js";
import {
getMcpToolsCommandsAndResources,
prefetchAllMcpResources,
} from "./services/mcp/client.js";
import {
VALID_INSTALLABLE_SCOPES,
VALID_UPDATE_SCOPES,
} from "./services/plugins/pluginCliCommands.js";
import { initBundledSkills } from "./skills/bundled/index.js";
import type { AgentColorName } from "@claude-code-best/builtin-tools/tools/AgentTool/agentColorManager.js";
import {
getActiveAgentsFromList,
getAgentDefinitionsWithOverrides,
isBuiltInAgent,
isCustomAgent,
parseAgentsFromJson,
} from "@claude-code-best/builtin-tools/tools/AgentTool/loadAgentsDir.js";
import type { LogOption } from "./types/logs.js";
import type { Message as MessageType } from "./types/message.js";
import {
CLAUDE_IN_CHROME_SKILL_HINT,
CLAUDE_IN_CHROME_SKILL_HINT_WITH_WEBBROWSER,
} from "./utils/claudeInChrome/prompt.js";
import {
setupClaudeInChrome,
shouldAutoEnableClaudeInChrome,
shouldEnableClaudeInChrome,
} from "./utils/claudeInChrome/setup.js";
import { getContextWindowForModel } from "./utils/context.js";
import { loadConversationForResume } from "./utils/conversationRecovery.js";
import { buildDeepLinkBanner } from "./utils/deepLink/banner.js";
import {
hasNodeOption,
isBareMode,
isEnvTruthy,
isInProtectedNamespace,
} from "./utils/envUtils.js";
import { refreshExampleCommands } from "./utils/exampleCommands.js";
import type { FpsMetrics } from "./utils/fpsTracker.js";
import { getWorktreePaths } from "./utils/getWorktreePaths.js";
import {
findGitRoot,
getBranch,
getIsGit,
getWorktreeCount,
} from "./utils/git.js";
import { getGhAuthStatus } from "./utils/github/ghAuthStatus.js";
import { safeParseJSON } from "./utils/json.js";
import { logError } from "./utils/log.js";
import { getModelDeprecationWarning } from "./utils/model/deprecation.js";
import {
getDefaultMainLoopModel,
getUserSpecifiedModelSetting,
normalizeModelStringForAPI,
parseUserSpecifiedModel,
} from "./utils/model/model.js";
import { ensureModelStringsInitialized } from "./utils/model/modelStrings.js";
import { PERMISSION_MODES } from "./utils/permissions/PermissionMode.js";
import {
getAutoModeEnabledStateIfCached,
initializeToolPermissionContext,
initialPermissionModeFromCLI,
isDefaultPermissionModeAuto,
parseToolListFromCLI,
removeDangerousPermissions,
stripDangerousPermissionsForAutoMode,
verifyAutoModeGateAccess,
} from "./utils/permissions/permissionSetup.js";
import { cleanupOrphanedPluginVersionsInBackground } from "./utils/plugins/cacheUtils.js";
import { initializeVersionedPlugins } from "./utils/plugins/installedPluginsManager.js";
import { getManagedPluginNames } from "./utils/plugins/managedPlugins.js";
import { getGlobExclusionsForPluginCache } from "./utils/plugins/orphanedPluginFilter.js";
import { getPluginSeedDirs } from "./utils/plugins/pluginDirectories.js";
import { countFilesRoundedRg } from "./utils/ripgrep.js";
import {
processSessionStartHooks,
processSetupHooks,
} from "./utils/sessionStart.js";
import {
cacheSessionTitle,
getSessionIdFromLog,
loadTranscriptFromFile,
saveAgentSetting,
saveMode,
searchSessionsByCustomTitle,
sessionIdExists,
} from "./utils/sessionStorage.js";
import { ensureMdmSettingsLoaded } from "./utils/settings/mdm/settings.js";
import {
getInitialSettings,
getManagedSettingsKeysForLogging,
getSettingsForSource,
getSettingsWithErrors,
} from "./utils/settings/settings.js";
import { resetSettingsCache } from "./utils/settings/settingsCache.js";
import type { ValidationError } from "./utils/settings/validation.js";
import {
DEFAULT_TASKS_MODE_TASK_LIST_ID,
TASK_STATUSES,
} from "./utils/tasks.js";
import {
logPluginLoadErrors,
logPluginsEnabledForSession,
} from "./utils/telemetry/pluginTelemetry.js";
import { logSkillsLoaded } from "./utils/telemetry/skillLoadedEvent.js";
import { generateTempFilePath } from "./utils/tempfile.js";
import { validateUuid } from "./utils/uuid.js";
// Plugin startup checks are now handled non-blockingly in REPL.tsx
import { registerMcpAddCommand } from "src/commands/mcp/addCommand.js";
import { registerMcpXaaIdpCommand } from "src/commands/mcp/xaaIdpCommand.js";
import { logPermissionContextForAnts } from "src/services/internalLogging.js";
import { fetchClaudeAIMcpConfigsIfEligible } from "src/services/mcp/claudeai.js";
import { clearServerCache } from "src/services/mcp/client.js";
import {
areMcpConfigsAllowedWithEnterpriseMcpConfig,
dedupClaudeAiMcpServers,
doesEnterpriseMcpConfigExist,
filterMcpServersByPolicy,
getClaudeCodeMcpConfigs,
getMcpServerSignature,
parseMcpConfig,
parseMcpConfigFromFilePath,
} from "src/services/mcp/config.js";
import {
excludeCommandsByServer,
excludeResourcesByServer,
} from "src/services/mcp/utils.js";
import { isXaaEnabled } from "src/services/mcp/xaaIdpLogin.js";
import { getRelevantTips } from "src/services/tips/tipRegistry.js";
import { logContextMetrics } from "src/utils/api.js";
import {
CLAUDE_IN_CHROME_MCP_SERVER_NAME,
isClaudeInChromeMCPServer,
} from "src/utils/claudeInChrome/common.js";
import { registerCleanup } from "src/utils/cleanupRegistry.js";
import { eagerParseCliFlag } from "src/utils/cliArgs.js";
import { createEmptyAttributionState } from "src/utils/commitAttribution.js";
import {
countConcurrentSessions,
registerSession,
updateSessionName,
} from "src/utils/concurrentSessions.js";
import { getCwd } from "src/utils/cwd.js";
import { logForDebugging, setHasFormattedOutput } from "src/utils/debug.js";
import {
errorMessage,
getErrnoCode,
isENOENT,
TeleportOperationError,
toError,
} from "src/utils/errors.js";
import {
getFsImplementation,
safeResolvePath,
} from "src/utils/fsOperations.js";
import {
gracefulShutdown,
gracefulShutdownSync,
} from "src/utils/gracefulShutdown.js";
import { setAllHookEventsEnabled } from "src/utils/hooks/hookEvents.js";
import { refreshModelCapabilities } from "src/utils/model/modelCapabilities.js";
import { peekForStdinData, writeToStderr } from "src/utils/process.js";
import { setCwd } from "src/utils/Shell.js";
import {
type ProcessedResume,
processResumedConversation,
} from "src/utils/sessionRestore.js";
import { parseSettingSourcesFlag } from "src/utils/settings/constants.js";
import { plural } from "src/utils/stringUtils.js";
import {
type ChannelEntry,
getInitialMainLoopModel,
getIsNonInteractiveSession,
getSdkBetas,
getSessionId,
getUserMsgOptIn,
setAllowedChannels,
setAllowedSettingSources,
setChromeFlagOverride,
setClientType,
setCwdState,
setDirectConnectServerUrl,
setFlagSettingsPath,
setInitialMainLoopModel,
setInlinePlugins,
setIsInteractive,
setKairosActive,
setOriginalCwd,
setQuestionPreviewFormat,
setSdkBetas,
setSessionBypassPermissionsMode,
setSessionPersistenceDisabled,
setSessionSource,
setUserMsgOptIn,
switchSession,
} from "./bootstrap/state.js";
/* eslint-disable @typescript-eslint/no-require-imports */
const autoModeStateModule = feature("TRANSCRIPT_CLASSIFIER")
? (require("./utils/permissions/autoModeState.js") as typeof import("./utils/permissions/autoModeState.js"))
: null;
// TeleportRepoMismatchDialog, TeleportResumeWrapper dynamically imported at call sites
import { migrateBypassPermissionsAcceptedToSettings } from "./migrations/migrateBypassPermissionsAcceptedToSettings.js";
import { migrateEnableAllProjectMcpServersToSettings } from "./migrations/migrateEnableAllProjectMcpServersToSettings.js";
import { migrateFennecToOpus } from "./migrations/migrateFennecToOpus.js";
import { migrateLegacyOpusToCurrent } from "./migrations/migrateLegacyOpusToCurrent.js";
import { migrateOpusToOpus1m } from "./migrations/migrateOpusToOpus1m.js";
import { migrateReplBridgeEnabledToRemoteControlAtStartup } from "./migrations/migrateReplBridgeEnabledToRemoteControlAtStartup.js";
import { migrateSonnet1mToSonnet45 } from "./migrations/migrateSonnet1mToSonnet45.js";
import { migrateSonnet45ToSonnet46 } from "./migrations/migrateSonnet45ToSonnet46.js";
import { resetAutoModeOptInForDefaultOffer } from "./migrations/resetAutoModeOptInForDefaultOffer.js";
import { resetProToOpusDefault } from "./migrations/resetProToOpusDefault.js";
import { createRemoteSessionConfig } from "./remote/RemoteSessionManager.js";
/* eslint-enable @typescript-eslint/no-require-imports */
// teleportWithProgress dynamically imported at call site
import {
createDirectConnectSession,
DirectConnectError,
} from "./server/createDirectConnectSession.js";
import { initializeLspServerManager } from "./services/lsp/manager.js";
import { shouldEnablePromptSuggestion } from "./services/PromptSuggestion/promptSuggestion.js";
import {
type AppState,
getDefaultAppState,
IDLE_SPECULATION_STATE,
} from "./state/AppStateStore.js";
import { onChangeAppState } from "./state/onChangeAppState.js";
import { createStore } from "./state/store.js";
import { asSessionId } from "./types/ids.js";
import { filterAllowedSdkBetas } from "./utils/betas.js";
import { isInBundledMode, isRunningWithBun } from "./utils/bundledMode.js";
import { logForDiagnosticsNoPII } from "./utils/diagLogs.js";
import {
filterExistingPaths,
getKnownPathsForRepo,
} from "./utils/githubRepoPathMapping.js";
import {
clearPluginCache,
loadAllPluginsCacheOnly,
} from "./utils/plugins/pluginLoader.js";
import { migrateChangelogFromConfig } from "./utils/releaseNotes.js";
import { SandboxManager } from "./utils/sandbox/sandbox-adapter.js";
import { fetchSession, prepareApiRequest } from "./utils/teleport/api.js";
import {
checkOutTeleportedSessionBranch,
processMessagesForTeleportResume,
teleportToRemoteWithErrorHandling,
validateGitState,
validateSessionRepository,
} from "./utils/teleport.js";
import {
shouldEnableThinkingByDefault,
type ThinkingConfig,
} from './utils/thinking.js'
import { initUser, resetUserCache } from './utils/user.js'
import {
getTmuxInstallInstructions,
isTmuxAvailable,
parsePRReference,
} from "./utils/worktree.js";
// eslint-disable-next-line custom-rules/no-top-level-side-effects
profileCheckpoint("main_tsx_imports_loaded");
/**
* Log managed settings keys to Statsig for analytics.
* This is called after init() completes to ensure settings are loaded
* and environment variables are applied before model resolution.
*/
function logManagedSettings(): void {
try {
const policySettings = getSettingsForSource("policySettings");
if (policySettings) {
const allKeys = getManagedSettingsKeysForLogging(policySettings);
logEvent("tengu_managed_settings_loaded", {
keyCount: allKeys.length,
keys: allKeys.join(
",",
) as unknown as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
});
}
} catch {
// Silently ignore errors - this is just for analytics
}
}
// Check if running in debug/inspection mode
function isBeingDebugged() {
const isBun = isRunningWithBun();
// Check for inspect flags in process arguments (including all variants)
const hasInspectArg = process.execArgv.some((arg) => {
if (isBun) {
// Note: Bun has an issue with single-file executables where application arguments
// from process.argv leak into process.execArgv (similar to https://github.com/oven-sh/bun/issues/11673)
// This breaks use of --debug mode if we omit this branch
// We're fine to skip that check, because Bun doesn't support Node.js legacy --debug or --debug-brk flags
return /--inspect(-brk)?/.test(arg);
} else {
// In Node.js, check for both --inspect and legacy --debug flags
return /--inspect(-brk)?|--debug(-brk)?/.test(arg);
}
});
// Check if NODE_OPTIONS contains inspect flags
const hasInspectEnv =
process.env.NODE_OPTIONS &&
/--inspect(-brk)?|--debug(-brk)?/.test(process.env.NODE_OPTIONS);
// Check if inspector is available and active (indicates debugging)
try {
// Dynamic import would be better but is async - use global object instead
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const inspector = (global as any).require("inspector");
const hasInspectorUrl = !!inspector.url();
return hasInspectorUrl || hasInspectArg || hasInspectEnv;
} catch {
// Ignore error and fall back to argument detection
return hasInspectArg || hasInspectEnv;
}
}
/**
* Per-session skill/plugin telemetry. Called from both the interactive path
* and the headless -p path (before runHeadless) — both go through
* main.tsx but branch before the interactive startup path, so it needs two
* call sites here rather than one here + one in QueryEngine.
*/
function logSessionTelemetry(): void {
const model = parseUserSpecifiedModel(
getInitialMainLoopModel() ?? getDefaultMainLoopModel(),
);
void logSkillsLoaded(
getCwd(),
getContextWindowForModel(model, getSdkBetas()),
);
void loadAllPluginsCacheOnly()
.then(({ enabled, errors }) => {
const managedNames = getManagedPluginNames();
logPluginsEnabledForSession(
enabled,
managedNames,
getPluginSeedDirs(),
);
logPluginLoadErrors(errors, managedNames);
})
.catch((err) => logError(err));
}
function getCertEnvVarTelemetry(): Record<string, boolean> {
const result: Record<string, boolean> = {};
if (process.env.NODE_EXTRA_CA_CERTS) {
result.has_node_extra_ca_certs = true;
}
if (process.env.CLAUDE_CODE_CLIENT_CERT) {
result.has_client_cert = true;
}
if (hasNodeOption("--use-system-ca")) {
result.has_use_system_ca = true;
}
if (hasNodeOption("--use-openssl-ca")) {
result.has_use_openssl_ca = true;
}
return result;
}
async function logStartupTelemetry(): Promise<void> {
if (isAnalyticsDisabled()) return;
const [isGit, worktreeCount, ghAuthStatus] = await Promise.all([
getIsGit(),
getWorktreeCount(),
getGhAuthStatus(),
]);
logEvent("tengu_startup_telemetry", {
is_git: isGit,
worktree_count: worktreeCount,
gh_auth_status:
ghAuthStatus as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
sandbox_enabled: SandboxManager.isSandboxingEnabled(),
are_unsandboxed_commands_allowed:
SandboxManager.areUnsandboxedCommandsAllowed(),
is_auto_bash_allowed_if_sandbox_enabled:
SandboxManager.isAutoAllowBashIfSandboxedEnabled(),
auto_updater_disabled: isAutoUpdaterDisabled(),
prefers_reduced_motion:
getInitialSettings().prefersReducedMotion ?? false,
...getCertEnvVarTelemetry(),
});
}
// @[MODEL LAUNCH]: Consider any migrations you may need for model strings. See migrateSonnet1mToSonnet45.ts for an example.
// Bump this when adding a new sync migration so existing users re-run the set.
const CURRENT_MIGRATION_VERSION = 11;
function runMigrations(): void {
if (getGlobalConfig().migrationVersion !== CURRENT_MIGRATION_VERSION) {
migrateBypassPermissionsAcceptedToSettings();
migrateEnableAllProjectMcpServersToSettings();
resetProToOpusDefault();
migrateSonnet1mToSonnet45();
migrateLegacyOpusToCurrent();
migrateSonnet45ToSonnet46();
migrateOpusToOpus1m();
migrateReplBridgeEnabledToRemoteControlAtStartup();
if (feature("TRANSCRIPT_CLASSIFIER")) {
resetAutoModeOptInForDefaultOffer();
}
if (process.env.USER_TYPE === "ant") {
migrateFennecToOpus();
}
saveGlobalConfig((prev) =>
prev.migrationVersion === CURRENT_MIGRATION_VERSION
? prev
: { ...prev, migrationVersion: CURRENT_MIGRATION_VERSION },
);
}
// Async migration - fire and forget since it's non-blocking
migrateChangelogFromConfig().catch(() => {
// Silently ignore migration errors - will retry on next startup
});
}
/**
* Prefetch system context (including git status) only when it's safe to do so.
* Git commands can execute arbitrary code via hooks and config (e.g., core.fsmonitor,
* diff.external), so we must only run them after trust is established or in
* non-interactive mode where trust is implicit.
*/
function prefetchSystemContextIfSafe(): void {
const isNonInteractiveSession = getIsNonInteractiveSession();
// In non-interactive mode (--print), trust dialog is skipped and
// execution is considered trusted (as documented in help text)
if (isNonInteractiveSession) {
logForDiagnosticsNoPII(
"info",
"prefetch_system_context_non_interactive",
);
void getSystemContext();
return;
}
// In interactive mode, only prefetch if trust has already been established
const hasTrust = checkHasTrustDialogAccepted();
if (hasTrust) {
logForDiagnosticsNoPII("info", "prefetch_system_context_has_trust");
void getSystemContext();
} else {
logForDiagnosticsNoPII(
"info",
"prefetch_system_context_skipped_no_trust",
);
}
// Otherwise, don't prefetch - wait for trust to be established first
}
/**
* Start background prefetches and housekeeping that are NOT needed before first render.
* These are deferred from setup() to reduce event loop contention and child process
* spawning during the critical startup path.
* Call this after the REPL has been rendered.
*/
export function startDeferredPrefetches(): void {
// This function runs after first render, so it doesn't block the initial paint.
// However, the spawned processes and async work still contend for CPU and event
// loop time, which skews startup benchmarks (CPU profiles, time-to-first-render
// measurements). Skip all of it when we're only measuring startup performance.
if (
isEnvTruthy(process.env.CLAUDE_CODE_EXIT_AFTER_FIRST_RENDER) ||
// --bare: skip ALL prefetches. These are cache-warms for the REPL's
// first-turn responsiveness (initUser, getUserContext, tips, countFiles,
// modelCapabilities, change detectors). Scripted -p calls don't have a
// "user is typing" window to hide this work in — it's pure overhead on
// the critical path.
isBareMode()
) {
return;
}
// Process-spawning prefetches (consumed at first API call, user is still typing)
void initUser();
void getUserContext();
prefetchSystemContextIfSafe();
void getRelevantTips();
if (
isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) &&
!isEnvTruthy(process.env.CLAUDE_CODE_SKIP_BEDROCK_AUTH)
) {
void prefetchAwsCredentialsAndBedRockInfoIfSafe();
}
if (
isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) &&
!isEnvTruthy(process.env.CLAUDE_CODE_SKIP_VERTEX_AUTH)
) {
void prefetchGcpCredentialsIfSafe();
}
void countFilesRoundedRg(getCwd(), AbortSignal.timeout(3000), []);
// Analytics and feature flag initialization
void initializeAnalyticsGates();
void refreshModelCapabilities();
// File change detectors deferred from init() to unblock first render
void settingsChangeDetector.initialize();
if (!isBareMode()) {
void skillChangeDetector.initialize();
}
// Event loop stall detector — logs when the main thread is blocked >500ms
if (process.env.USER_TYPE === "ant") {
void import("./utils/eventLoopStallDetector.js").then((m) =>
m.startEventLoopStallDetector(),
);
}
}
function loadSettingsFromFlag(settingsFile: string): void {
try {
const trimmedSettings = settingsFile.trim();
const looksLikeJson =
trimmedSettings.startsWith("{") && trimmedSettings.endsWith("}");
let settingsPath: string;
if (looksLikeJson) {
// It's a JSON string - validate and create temp file
const parsedJson = safeParseJSON(trimmedSettings);
if (!parsedJson) {
process.stderr.write(
chalk.red("Error: Invalid JSON provided to --settings\n"),
);
process.exit(1);
}
// Create a temporary file and write the JSON to it.
// Use a content-hash-based path instead of random UUID to avoid
// busting the Anthropic API prompt cache. The settings path ends up
// in the Bash tool's sandbox denyWithinAllow list, which is part of
// the tool description sent to the API. A random UUID per subprocess
// changes the tool description on every query() call, invalidating
// the cache prefix and causing a 12x input token cost penalty.
// The content hash ensures identical settings produce the same path
// across process boundaries (each SDK query() spawns a new process).
settingsPath = generateTempFilePath("claude-settings", ".json", {
contentHash: trimmedSettings,
});
writeFileSync_DEPRECATED(settingsPath, trimmedSettings, "utf8");
} else {
// It's a file path - resolve and validate by attempting to read
const { resolvedPath: resolvedSettingsPath } = safeResolvePath(
getFsImplementation(),
settingsFile,
);
try {
readFileSync(resolvedSettingsPath, "utf8");
} catch (e) {
if (isENOENT(e)) {
process.stderr.write(
chalk.red(
`Error: Settings file not found: ${resolvedSettingsPath}\n`,
),
);
process.exit(1);
}
throw e;
}
settingsPath = resolvedSettingsPath;
}
setFlagSettingsPath(settingsPath);
resetSettingsCache();
} catch (error) {
if (error instanceof Error) {
logError(error);
}
process.stderr.write(
chalk.red(`Error processing settings: ${errorMessage(error)}\n`),
);
process.exit(1);
}
}
function loadSettingSourcesFromFlag(settingSourcesArg: string): void {
try {
const sources = parseSettingSourcesFlag(settingSourcesArg);
setAllowedSettingSources(sources);
resetSettingsCache();
} catch (error) {
if (error instanceof Error) {
logError(error);
}
process.stderr.write(
chalk.red(
`Error processing --setting-sources: ${errorMessage(error)}\n`,
),
);
process.exit(1);
}
}
/**
* Parse and load settings flags early, before init()
* This ensures settings are filtered from the start of initialization
*/
function eagerLoadSettings(): void {
profileCheckpoint("eagerLoadSettings_start");
// Parse --settings flag early to ensure settings are loaded before init()
const settingsFile = eagerParseCliFlag("--settings");
if (settingsFile) {
loadSettingsFromFlag(settingsFile);
}
// Parse --setting-sources flag early to control which sources are loaded
const settingSourcesArg = eagerParseCliFlag("--setting-sources");
if (settingSourcesArg !== undefined) {
loadSettingSourcesFromFlag(settingSourcesArg);
}
profileCheckpoint("eagerLoadSettings_end");
}
function initializeEntrypoint(isNonInteractive: boolean): void {
// Skip if already set (e.g., by SDK or other entrypoints)
if (process.env.CLAUDE_CODE_ENTRYPOINT) {
return;
}
const cliArgs = process.argv.slice(2);
// Check for MCP serve command (handle flags before mcp serve, e.g., --debug mcp serve)
const mcpIndex = cliArgs.indexOf("mcp");
if (mcpIndex !== -1 && cliArgs[mcpIndex + 1] === "serve") {
process.env.CLAUDE_CODE_ENTRYPOINT = "mcp";
return;
}
if (isEnvTruthy(process.env.CLAUDE_CODE_ACTION)) {
process.env.CLAUDE_CODE_ENTRYPOINT = "claude-code-github-action";
return;
}
// Note: 'local-agent' entrypoint is set by the local agent mode launcher
// via CLAUDE_CODE_ENTRYPOINT env var (handled by early return above)
// Set based on interactive status
process.env.CLAUDE_CODE_ENTRYPOINT = isNonInteractive ? "sdk-cli" : "cli";
}
// Set by early argv processing when `claude open <url>` is detected (interactive mode only)
type PendingConnect = {
url: string | undefined;
authToken: string | undefined;
dangerouslySkipPermissions: boolean;
};
const _pendingConnect: PendingConnect | undefined = feature("DIRECT_CONNECT")
? {
url: undefined,
authToken: undefined,
dangerouslySkipPermissions: false,
}
: undefined;
// Set by early argv processing when `claude assistant [sessionId]` is detected
type PendingAssistantChat = { sessionId?: string; discover: boolean };
const _pendingAssistantChat: PendingAssistantChat | undefined = feature(
"KAIROS",
)
? { sessionId: undefined, discover: false }
: undefined;
// `claude ssh <host> [dir]` — parsed from argv early (same pattern as
// DIRECT_CONNECT above) so the main command path can pick it up and hand
// the REPL an SSH-backed session instead of a local one.
type PendingSSH = {
host: string | undefined;
cwd: string | undefined;
permissionMode: string | undefined;
dangerouslySkipPermissions: boolean;
/** --local: spawn the child CLI directly, skip ssh/probe/deploy. e2e test mode. */
local: boolean;
/** Extra CLI args to forward to the remote CLI on initial spawn (--resume, -c). */
extraCliArgs: string[];
remoteBin: string | undefined;
};
const _pendingSSH: PendingSSH | undefined = feature("SSH_REMOTE")
? {
host: undefined,
cwd: undefined,
permissionMode: undefined,
dangerouslySkipPermissions: false,
local: false,
extraCliArgs: [],
remoteBin: undefined,
}
: undefined;
export async function main() {
profileCheckpoint("main_function_start");
// SECURITY: Prevent Windows from executing commands from current directory
// This must be set before ANY command execution to prevent PATH hijacking attacks
// See: https://docs.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-searchpathw
process.env.NoDefaultCurrentDirectoryInExePath = "1";
// Initialize warning handler early to catch warnings
initializeWarningHandler();
process.on("exit", () => {
resetCursor();
});
process.on("SIGINT", () => {
// In print mode, print.ts registers its own SIGINT handler that aborts
// the in-flight query and calls gracefulShutdown; skip here to avoid
// preempting it with a synchronous process.exit().
if (process.argv.includes("-p") || process.argv.includes("--print")) {
return;
}
process.exit(0);
});
profileCheckpoint("main_warning_handler_initialized");
// Check for cc:// or cc+unix:// URL in argv — rewrite so the main command
// handles it, giving the full interactive TUI instead of a stripped-down subcommand.
// For headless (-p), we rewrite to the internal `open` subcommand.
if (feature("DIRECT_CONNECT")) {
const rawCliArgs = process.argv.slice(2);
const ccIdx = rawCliArgs.findIndex(
(a) => a.startsWith("cc://") || a.startsWith("cc+unix://"),
);
if (ccIdx !== -1 && _pendingConnect) {
const ccUrl = rawCliArgs[ccIdx]!;
const { parseConnectUrl } =
await import("./server/parseConnectUrl.js");
const parsed = parseConnectUrl(ccUrl);
_pendingConnect.dangerouslySkipPermissions = rawCliArgs.includes(
"--dangerously-skip-permissions",
);
if (rawCliArgs.includes("-p") || rawCliArgs.includes("--print")) {
// Headless: rewrite to internal `open` subcommand
const stripped = rawCliArgs.filter((_, i) => i !== ccIdx);
const dspIdx = stripped.indexOf(
"--dangerously-skip-permissions",
);
if (dspIdx !== -1) {
stripped.splice(dspIdx, 1);
}
process.argv = [
process.argv[0]!,
process.argv[1]!,
"open",
ccUrl,
...stripped,
];
} else {
// Interactive: strip cc:// URL and flags, run main command
_pendingConnect.url = parsed.serverUrl;
_pendingConnect.authToken = parsed.authToken;
const stripped = rawCliArgs.filter((_, i) => i !== ccIdx);
const dspIdx = stripped.indexOf(
"--dangerously-skip-permissions",
);
if (dspIdx !== -1) {
stripped.splice(dspIdx, 1);
}
process.argv = [
process.argv[0]!,
process.argv[1]!,
...stripped,
];
}
}
}
// Handle deep link URIs early — this is invoked by the OS protocol handler
// and should bail out before full init since it only needs to parse the URI
// and open a terminal.
if (feature("LODESTONE")) {
const handleUriIdx = process.argv.indexOf("--handle-uri");
if (handleUriIdx !== -1 && process.argv[handleUriIdx + 1]) {
const { enableConfigs } = await import("./utils/config.js");
enableConfigs();
const uri = process.argv[handleUriIdx + 1]!;
const { handleDeepLinkUri } =
await import("./utils/deepLink/protocolHandler.js");
const exitCode = await handleDeepLinkUri(uri);
process.exit(exitCode);
}
// macOS URL handler: when LaunchServices launches our .app bundle, the
// URL arrives via Apple Event (not argv). LaunchServices overwrites
// __CFBundleIdentifier to the launching bundle's ID, which is a precise
// positive signal — cheaper than importing and guessing with heuristics.
if (
process.platform === "darwin" &&
process.env.__CFBundleIdentifier ===
"com.anthropic.claude-code-url-handler"
) {
const { enableConfigs } = await import("./utils/config.js");
enableConfigs();
const { handleUrlSchemeLaunch } =
await import("./utils/deepLink/protocolHandler.js");
const urlSchemeResult = await handleUrlSchemeLaunch();
process.exit(urlSchemeResult ?? 1);
}
}
// `claude assistant [sessionId]` — stash and strip so the main
// command handles it, giving the full interactive TUI. Position-0 only
// (matching the ssh pattern below) — indexOf would false-positive on
// `claude -p "explain assistant"`. Root-flag-before-subcommand