forked from Kuberwastaken/claurst
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.tsx
More file actions
4684 lines (4446 loc) · 785 KB
/
main.tsx
File metadata and controls
4684 lines (4446 loc) · 785 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 './ink.js';
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 { prefetchOfficialMcpUrls } from './services/mcp/officialRegistry.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 './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 './ink/termio/dec.js';
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 './tools/AgentTool/agentColorManager.js';
import { getActiveAgentsFromList, getAgentDefinitionsWithOverrides, isBuiltInAgent, isCustomAgent, parseAgentsFromJson } from './tools/AgentTool/loadAgentsDir.js';
import type { LogOption } from './types/logs.js';
import type { Message as MessageType } from './types/message.js';
import { assertMinVersion } from './utils/autoUpdater.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 { checkAndDisableBypassPermissions, 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 { migrateAutoUpdatesToSettings } from './migrations/migrateAutoUpdatesToSettings.js';
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;
}
}
// Exit if we detect node debugging or inspection
if ("external" !== 'ant' && isBeingDebugged()) {
// Use process.exit directly here since we're in the top-level code before imports
// and gracefulShutdown is not yet available
// eslint-disable-next-line custom-rules/no-top-level-side-effects
process.exit(1);
}
/**
* 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) {
migrateAutoUpdatesToSettings();
migrateBypassPermissionsAcceptedToSettings();
migrateEnableAllProjectMcpServersToSettings();
resetProToOpusDefault();
migrateSonnet1mToSonnet45();
migrateLegacyOpusToCurrent();
migrateSonnet45ToSonnet46();
migrateOpusToOpus1m();
migrateReplBridgeEnabledToRemoteControlAtStartup();
if (feature('TRANSCRIPT_CLASSIFIER')) {
resetAutoModeOptInForDefaultOffer();
}
if ("external" === '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 prefetchOfficialMcpUrls();
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 ("external" === '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[];
};
const _pendingSSH: PendingSSH | undefined = feature('SSH_REMOTE') ? {
host: undefined,
cwd: undefined,
permissionMode: undefined,
dangerouslySkipPermissions: false,
local: false,
extraCliArgs: []
} : 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
// (e.g. `--debug assistant`) falls through to the stub, which
// prints usage.
if (feature('KAIROS') && _pendingAssistantChat) {
const rawArgs = process.argv.slice(2);
if (rawArgs[0] === 'assistant') {
const nextArg = rawArgs[1];
if (nextArg && !nextArg.startsWith('-')) {
_pendingAssistantChat.sessionId = nextArg;
rawArgs.splice(0, 2); // drop 'assistant' and sessionId
process.argv = [process.argv[0]!, process.argv[1]!, ...rawArgs];
} else if (!nextArg) {
_pendingAssistantChat.discover = true;
rawArgs.splice(0, 1); // drop 'assistant'
process.argv = [process.argv[0]!, process.argv[1]!, ...rawArgs];
}
// else: `claude assistant --help` → fall through to stub
}
}
// `claude ssh <host> [dir]` — strip from argv so the main command handler
// runs (full interactive TUI), stash the host/dir for the REPL branch at
// ~line 3720 to pick up. Headless (-p) mode not supported in v1: SSH
// sessions need the local REPL to drive them (interrupt, permissions).
if (feature('SSH_REMOTE') && _pendingSSH) {
const rawCliArgs = process.argv.slice(2);
// SSH-specific flags can appear before the host positional (e.g.
// `ssh --permission-mode auto host /tmp` — standard POSIX flags-before-
// positionals). Pull them all out BEFORE checking whether a host was
// given, so `claude ssh --permission-mode auto host` and `claude ssh host
// --permission-mode auto` are equivalent. The host check below only needs
// to guard against `-h`/`--help` (which commander should handle).
if (rawCliArgs[0] === 'ssh') {
const localIdx = rawCliArgs.indexOf('--local');
if (localIdx !== -1) {
_pendingSSH.local = true;
rawCliArgs.splice(localIdx, 1);
}
const dspIdx = rawCliArgs.indexOf('--dangerously-skip-permissions');
if (dspIdx !== -1) {
_pendingSSH.dangerouslySkipPermissions = true;
rawCliArgs.splice(dspIdx, 1);
}
const pmIdx = rawCliArgs.indexOf('--permission-mode');
if (pmIdx !== -1 && rawCliArgs[pmIdx + 1] && !rawCliArgs[pmIdx + 1]!.startsWith('-')) {
_pendingSSH.permissionMode = rawCliArgs[pmIdx + 1];
rawCliArgs.splice(pmIdx, 2);
}
const pmEqIdx = rawCliArgs.findIndex(a => a.startsWith('--permission-mode='));
if (pmEqIdx !== -1) {
_pendingSSH.permissionMode = rawCliArgs[pmEqIdx]!.split('=')[1];
rawCliArgs.splice(pmEqIdx, 1);
}
// Forward session-resume + model flags to the remote CLI's initial spawn.
// --continue/-c and --resume <uuid> operate on the REMOTE session history
// (which persists under the remote's ~/.claude/projects/<cwd>/).
// --model controls which model the remote uses.
const extractFlag = (flag: string, opts: {
hasValue?: boolean;
as?: string;
} = {}) => {
const i = rawCliArgs.indexOf(flag);
if (i !== -1) {
_pendingSSH.extraCliArgs.push(opts.as ?? flag);
const val = rawCliArgs[i + 1];
if (opts.hasValue && val && !val.startsWith('-')) {
_pendingSSH.extraCliArgs.push(val);
rawCliArgs.splice(i, 2);
} else {
rawCliArgs.splice(i, 1);
}
}
const eqI = rawCliArgs.findIndex(a => a.startsWith(`${flag}=`));
if (eqI !== -1) {
_pendingSSH.extraCliArgs.push(opts.as ?? flag, rawCliArgs[eqI]!.slice(flag.length + 1));
rawCliArgs.splice(eqI, 1);
}
};
extractFlag('-c', {
as: '--continue'
});
extractFlag('--continue');
extractFlag('--resume', {
hasValue: true
});
extractFlag('--model', {
hasValue: true
});
}
// After pre-extraction, any remaining dash-arg at [1] is either -h/--help
// (commander handles) or an unknown-to-ssh flag (fall through to commander
// so it surfaces a proper error). Only a non-dash arg is the host.
if (rawCliArgs[0] === 'ssh' && rawCliArgs[1] && !rawCliArgs[1].startsWith('-')) {
_pendingSSH.host = rawCliArgs[1];
// Optional positional cwd.
let consumed = 2;
if (rawCliArgs[2] && !rawCliArgs[2].startsWith('-')) {
_pendingSSH.cwd = rawCliArgs[2];
consumed = 3;
}
const rest = rawCliArgs.slice(consumed);
// Headless (-p) mode is not supported with SSH in v1 — reject early
// so the flag doesn't silently cause local execution.
if (rest.includes('-p') || rest.includes('--print')) {
process.stderr.write('Error: headless (-p/--print) mode is not supported with claude ssh\n');
gracefulShutdownSync(1);
return;
}
// Rewrite argv so the main command sees remaining flags but not `ssh`.
process.argv = [process.argv[0]!, process.argv[1]!, ...rest];
}
}
// Check for -p/--print and --init-only flags early to set isInteractiveSession before init()
// This is needed because telemetry initialization calls auth functions that need this flag
const cliArgs = process.argv.slice(2);
const hasPrintFlag = cliArgs.includes('-p') || cliArgs.includes('--print');
const hasInitOnlyFlag = cliArgs.includes('--init-only');
const hasSdkUrl = cliArgs.some(arg => arg.startsWith('--sdk-url'));
const isNonInteractive = hasPrintFlag || hasInitOnlyFlag || hasSdkUrl || !process.stdout.isTTY;
// Stop capturing early input for non-interactive modes
if (isNonInteractive) {
stopCapturingEarlyInput();
}
// Set simplified tracking fields
const isInteractive = !isNonInteractive;
setIsInteractive(isInteractive);
// Initialize entrypoint based on mode - needs to be set before any event is logged
initializeEntrypoint(isNonInteractive);
// Determine client type
const clientType = (() => {
if (isEnvTruthy(process.env.GITHUB_ACTIONS)) return 'github-action';
if (process.env.CLAUDE_CODE_ENTRYPOINT === 'sdk-ts') return 'sdk-typescript';
if (process.env.CLAUDE_CODE_ENTRYPOINT === 'sdk-py') return 'sdk-python';
if (process.env.CLAUDE_CODE_ENTRYPOINT === 'sdk-cli') return 'sdk-cli';
if (process.env.CLAUDE_CODE_ENTRYPOINT === 'claude-vscode') return 'claude-vscode';
if (process.env.CLAUDE_CODE_ENTRYPOINT === 'local-agent') return 'local-agent';
if (process.env.CLAUDE_CODE_ENTRYPOINT === 'claude-desktop') return 'claude-desktop';
// Check if session-ingress token is provided (indicates remote session)
const hasSessionIngressToken = process.env.CLAUDE_CODE_SESSION_ACCESS_TOKEN || process.env.CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR;
if (process.env.CLAUDE_CODE_ENTRYPOINT === 'remote' || hasSessionIngressToken) {
return 'remote';
}
return 'cli';
})();
setClientType(clientType);
const previewFormat = process.env.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT;
if (previewFormat === 'markdown' || previewFormat === 'html') {
setQuestionPreviewFormat(previewFormat);
} else if (!clientType.startsWith('sdk-') &&
// Desktop and CCR pass previewFormat via toolConfig; when the feature is
// gated off they pass undefined — don't override that with markdown.
clientType !== 'claude-desktop' && clientType !== 'local-agent' && clientType !== 'remote') {
setQuestionPreviewFormat('markdown');
}
// Tag sessions created via `claude remote-control` so the backend can identify them
if (process.env.CLAUDE_CODE_ENVIRONMENT_KIND === 'bridge') {
setSessionSource('remote-control');
}
profileCheckpoint('main_client_type_determined');
// Parse and load settings flags early, before init()
eagerLoadSettings();
profileCheckpoint('main_before_run');
await run();
profileCheckpoint('main_after_run');
}
async function getInputPrompt(prompt: string, inputFormat: 'text' | 'stream-json'): Promise<string | AsyncIterable<string>> {
if (!process.stdin.isTTY &&
// Input hijacking breaks MCP.
!process.argv.includes('mcp')) {
if (inputFormat === 'stream-json') {
return process.stdin;
}
process.stdin.setEncoding('utf8');
let data = '';
const onData = (chunk: string) => {
data += chunk;
};
process.stdin.on('data', onData);
// If no data arrives in 3s, stop waiting and warn. Stdin is likely an
// inherited pipe from a parent that isn't writing (subprocess spawned
// without explicit stdin handling). 3s covers slow producers like curl,
// jq on large files, python with import overhead. The warning makes
// silent data loss visible for the rare producer that's slower still.
const timedOut = await peekForStdinData(process.stdin, 3000);
process.stdin.off('data', onData);
if (timedOut) {
process.stderr.write('Warning: no stdin data received in 3s, proceeding without it. ' + 'If piping from a slow command, redirect stdin explicitly: < /dev/null to skip, or wait longer.\n');
}
return [prompt, data].filter(Boolean).join('\n');
}
return prompt;
}
async function run(): Promise<CommanderCommand> {
profileCheckpoint('run_function_start');
// Create help config that sorts options by long option name.
// Commander supports compareOptions at runtime but @commander-js/extra-typings
// doesn't include it in the type definitions, so we use Object.assign to add it.
function createSortedHelpConfig(): {
sortSubcommands: true;
sortOptions: true;
} {
const getOptionSortKey = (opt: Option): string => opt.long?.replace(/^--/, '') ?? opt.short?.replace(/^-/, '') ?? '';
return Object.assign({
sortSubcommands: true,
sortOptions: true
} as const, {
compareOptions: (a: Option, b: Option) => getOptionSortKey(a).localeCompare(getOptionSortKey(b))
});
}
const program = new CommanderCommand().configureHelp(createSortedHelpConfig()).enablePositionalOptions();
profileCheckpoint('run_commander_initialized');
// Use preAction hook to run initialization only when executing a command,
// not when displaying help. This avoids the need for env variable signaling.
program.hook('preAction', async thisCommand => {
profileCheckpoint('preAction_start');
// Await async subprocess loads started at module evaluation (lines 12-20).
// Nearly free — subprocesses complete during the ~135ms of imports above.
// Must resolve before init() which triggers the first settings read
// (applySafeConfigEnvironmentVariables → getSettingsForSource('policySettings')
// → isRemoteManagedSettingsEligible → sync keychain reads otherwise ~65ms).
await Promise.all([ensureMdmSettingsLoaded(), ensureKeychainPrefetchCompleted()]);
profileCheckpoint('preAction_after_mdm');
await init();
profileCheckpoint('preAction_after_init');
// process.title on Windows sets the console title directly; on POSIX,
// terminal shell integration may mirror the process name to the tab.
// After init() so settings.json env can also gate this (gh-4765).
if (!isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE)) {
process.title = 'claude';
}
// Attach logging sinks so subcommand handlers can use logEvent/logError.
// Before PR #11106 logEvent dispatched directly; after, events queue until
// a sink attaches. setup() attaches sinks for the default command, but
// subcommands (doctor, mcp, plugin, auth) never call setup() and would
// silently drop events on process.exit(). Both inits are idempotent.
const {
initSinks
} = await import('./utils/sinks.js');
initSinks();
profileCheckpoint('preAction_after_sinks');
// gh-33508: --plugin-dir is a top-level program option. The default
// action reads it from its own options destructure, but subcommands
// (plugin list, plugin install, mcp *) have their own actions and
// never see it. Wire it up here so getInlinePlugins() works everywhere.
// thisCommand.opts() is typed {} here because this hook is attached
// before .option('--plugin-dir', ...) in the chain — extra-typings
// builds the type as options are added. Narrow with a runtime guard;
// the collect accumulator + [] default guarantee string[] in practice.
const pluginDir = thisCommand.getOptionValue('pluginDir');
if (Array.isArray(pluginDir) && pluginDir.length > 0 && pluginDir.every(p => typeof p === 'string')) {
setInlinePlugins(pluginDir);
clearPluginCache('preAction: --plugin-dir inline plugins');
}
runMigrations();
profileCheckpoint('preAction_after_migrations');
// Load remote managed settings for enterprise customers (non-blocking)
// Fails open - if fetch fails, continues without remote settings
// Settings are applied via hot-reload when they arrive
// Must happen after init() to ensure config reading is allowed
void loadRemoteManagedSettings();
void loadPolicyLimits();
profileCheckpoint('preAction_after_remote_settings');
// Load settings sync (non-blocking, fail-open)
// CLI: uploads local settings to remote (CCR download is handled by print.ts)
if (feature('UPLOAD_USER_SETTINGS')) {
void import('./services/settingsSync/index.js').then(m => m.uploadUserSettingsInBackground());
}
profileCheckpoint('preAction_after_settings_sync');
});
program.name('claude').description(`Claude Code - starts an interactive session by default, use -p/--print for non-interactive output`).argument('[prompt]', 'Your prompt', String)
// Subcommands inherit helpOption via commander's copyInheritedSettings —
// setting it once here covers mcp, plugin, auth, and all other subcommands.
.helpOption('-h, --help', 'Display help for command').option('-d, --debug [filter]', 'Enable debug mode with optional category filtering (e.g., "api,hooks" or "!1p,!file")', (_value: string | true) => {
// If value is provided, it will be the filter string
// If not provided but flag is present, value will be true
// The actual filtering is handled in debug.ts by parsing process.argv
return true;
}).addOption(new Option('-d2e, --debug-to-stderr', 'Enable debug mode (to stderr)').argParser(Boolean).hideHelp()).option('--debug-file <path>', 'Write debug logs to a specific file path (implicitly enables debug mode)', () => true).option('--verbose', 'Override verbose mode setting from config', () => true).option('-p, --print', 'Print response and exit (useful for pipes). Note: The workspace trust dialog is skipped when Claude is run with the -p mode. Only use this flag in directories you trust.', () => true).option('--bare', 'Minimal mode: skip hooks, LSP, plugin sync, attribution, auto-memory, background prefetches, keychain reads, and CLAUDE.md auto-discovery. Sets CLAUDE_CODE_SIMPLE=1. Anthropic auth is strictly ANTHROPIC_API_KEY or apiKeyHelper via --settings (OAuth and keychain are never read). 3P providers (Bedrock/Vertex/Foundry) use their own credentials. Skills still resolve via /skill-name. Explicitly provide context via: --system-prompt[-file], --append-system-prompt[-file], --add-dir (CLAUDE.md dirs), --mcp-config, --settings, --agents, --plugin-dir.', () => true).addOption(new Option('--init', 'Run Setup hooks with init trigger, then continue').hideHelp()).addOption(new Option('--init-only', 'Run Setup and SessionStart:startup hooks, then exit').hideHelp()).addOption(new Option('--maintenance', 'Run Setup hooks with maintenance trigger, then continue').hideHelp()).addOption(new Option('--output-format <format>', 'Output format (only works with --print): "text" (default), "json" (single result), or "stream-json" (realtime streaming)').choices(['text', 'json', 'stream-json'])).addOption(new Option('--json-schema <schema>', 'JSON Schema for structured output validation. ' + 'Example: {"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}').argParser(String)).option('--include-hook-events', 'Include all hook lifecycle events in the output stream (only works with --output-format=stream-json)', () => true).option('--include-partial-messages', 'Include partial message chunks as they arrive (only works with --print and --output-format=stream-json)', () => true).addOption(new Option('--input-format <format>', 'Input format (only works with --print): "text" (default), or "stream-json" (realtime streaming input)').choices(['text', 'stream-json'])).option('--mcp-debug', '[DEPRECATED. Use --debug instead] Enable MCP debug mode (shows MCP server errors)', () => true).option('--dangerously-skip-permissions', 'Bypass all permission checks. Recommended only for sandboxes with no internet access.', () => true).option('--allow-dangerously-skip-permissions', 'Enable bypassing all permission checks as an option, without it being enabled by default. Recommended only for sandboxes with no internet access.', () => true).addOption(new Option('--thinking <mode>', 'Thinking mode: enabled (equivalent to adaptive), disabled').choices(['enabled', 'adaptive', 'disabled']).hideHelp()).addOption(new Option('--max-thinking-tokens <tokens>', '[DEPRECATED. Use --thinking instead for newer models] Maximum number of thinking tokens (only works with --print)').argParser(Number).hideHelp()).addOption(new Option('--max-turns <turns>', 'Maximum number of agentic turns in non-interactive mode. This will early exit the conversation after the specified number of turns. (only works with --print)').argParser(Number).hideHelp()).addOption(new Option('--max-budget-usd <amount>', 'Maximum dollar amount to spend on API calls (only works with --print)').argParser(value => {
const amount = Number(value);
if (isNaN(amount) || amount <= 0) {
throw new Error('--max-budget-usd must be a positive number greater than 0');
}
return amount;
})).addOption(new Option('--task-budget <tokens>', 'API-side task budget in tokens (output_config.task_budget)').argParser(value => {
const tokens = Number(value);
if (isNaN(tokens) || tokens <= 0 || !Number.isInteger(tokens)) {
throw new Error('--task-budget must be a positive integer');
}
return tokens;
}).hideHelp()).option('--replay-user-messages', 'Re-emit user messages from stdin back on stdout for acknowledgment (only works with --input-format=stream-json and --output-format=stream-json)', () => true).addOption(new Option('--enable-auth-status', 'Enable auth status messages in SDK mode').default(false).hideHelp()).option('--allowedTools, --allowed-tools <tools...>', 'Comma or space-separated list of tool names to allow (e.g. "Bash(git:*) Edit")').option('--tools <tools...>', 'Specify the list of available tools from the built-in set. Use "" to disable all tools, "default" to use all tools, or specify tool names (e.g. "Bash,Edit,Read").').option('--disallowedTools, --disallowed-tools <tools...>', 'Comma or space-separated list of tool names to deny (e.g. "Bash(git:*) Edit")').option('--mcp-config <configs...>', 'Load MCP servers from JSON files or strings (space-separated)').addOption(new Option('--permission-prompt-tool <tool>', 'MCP tool to use for permission prompts (only works with --print)').argParser(String).hideHelp()).addOption(new Option('--system-prompt <prompt>', 'System prompt to use for the session').argParser(String)).addOption(new Option('--system-prompt-file <file>', 'Read system prompt from a file').argParser(String).hideHelp()).addOption(new Option('--append-system-prompt <prompt>', 'Append a system prompt to the default system prompt').argParser(String)).addOption(new Option('--append-system-prompt-file <file>', 'Read system prompt from a file and append to the default system prompt').argParser(String).hideHelp()).addOption(new Option('--permission-mode <mode>', 'Permission mode to use for the session').argParser(String).choices(PERMISSION_MODES)).option('-c, --continue', 'Continue the most recent conversation in the current directory', () => true).option('-r, --resume [value]', 'Resume a conversation by session ID, or open interactive picker with optional search term', value => value || true).option('--fork-session', 'When resuming, create a new session ID instead of reusing the original (use with --resume or --continue)', () => true).addOption(new Option('--prefill <text>', 'Pre-fill the prompt input with text without submitting it').hideHelp()).addOption(new Option('--deep-link-origin', 'Signal that this session was launched from a deep link').hideHelp()).addOption(new Option('--deep-link-repo <slug>', 'Repo slug the deep link ?repo= parameter resolved to the current cwd').hideHelp()).addOption(new Option('--deep-link-last-fetch <ms>', 'FETCH_HEAD mtime in epoch ms, precomputed by the deep link trampoline').argParser(v => {
const n = Number(v);
return Number.isFinite(n) ? n : undefined;
}).hideHelp()).option('--from-pr [value]', 'Resume a session linked to a PR by PR number/URL, or open interactive picker with optional search term', value => value || true).option('--no-session-persistence', 'Disable session persistence - sessions will not be saved to disk and cannot be resumed (only works with --print)').addOption(new Option('--resume-session-at <message id>', 'When resuming, only messages up to and including the assistant message with <message.id> (use with --resume in print mode)').argParser(String).hideHelp()).addOption(new Option('--rewind-files <user-message-id>', 'Restore files to state at the specified user message and exit (requires --resume)').hideHelp())
// @[MODEL LAUNCH]: Update the example model ID in the --model help text.
.option('--model <model>', `Model for the current session. Provide an alias for the latest model (e.g. 'sonnet' or 'opus') or a model's full name (e.g. 'claude-sonnet-4-6').`).addOption(new Option('--effort <level>', `Effort level for the current session (low, medium, high, max)`).argParser((rawValue: string) => {
const value = rawValue.toLowerCase();
const allowed = ['low', 'medium', 'high', 'max'];
if (!allowed.includes(value)) {
throw new InvalidArgumentError(`It must be one of: ${allowed.join(', ')}`);
}
return value;
})).option('--agent <agent>', `Agent for the current session. Overrides the 'agent' setting.`).option('--betas <betas...>', 'Beta headers to include in API requests (API key users only)').option('--fallback-model <model>', 'Enable automatic fallback to specified model when default model is overloaded (only works with --print)').addOption(new Option('--workload <tag>', 'Workload tag for billing-header attribution (cc_workload). Process-scoped; set by SDK daemon callers that spawn subprocesses for cron work. (only works with --print)').hideHelp()).option('--settings <file-or-json>', 'Path to a settings JSON file or a JSON string to load additional settings from').option('--add-dir <directories...>', 'Additional directories to allow tool access to').option('--ide', 'Automatically connect to IDE on startup if exactly one valid IDE is available', () => true).option('--strict-mcp-config', 'Only use MCP servers from --mcp-config, ignoring all other MCP configurations', () => true).option('--session-id <uuid>', 'Use a specific session ID for the conversation (must be a valid UUID)').option('-n, --name <name>', 'Set a display name for this session (shown in /resume and terminal title)').option('--agents <json>', 'JSON object defining custom agents (e.g. \'{"reviewer": {"description": "Reviews code", "prompt": "You are a code reviewer"}}\')').option('--setting-sources <sources>', 'Comma-separated list of setting sources to load (user, project, local).')