GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — claude-code-source-code/src/cli/print.ts at main · unsignedcpp/claude-code-source-code Expand file tree/ Copy pathprint.tsMore file actions 5594 lines (5263 loc) · 208 KB / Copy pathprint.tsFile metadata and controls5594 lines (5263 loc) · 208 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 // biome-ignore-all assist/source/organizeImports: ANT-ONLY import markers must not be reordered import { feature } from 'bun:bundle' import { readFile, stat } from 'fs/promises' import { dirname } from 'path' import { downloadUserSettings, redownloadUserSettings, } from 'src/services/settingsSync/index.js' import { waitForRemoteManagedSettingsToLoad } from 'src/services/remoteManagedSettings/index.js' import { StructuredIO } from 'src/cli/structuredIO.js' import { RemoteIO } from 'src/cli/remoteIO.js' import { type Command, formatDescriptionWithSource, getCommandName, } from 'src/commands.js' import { createStreamlinedTransformer } from 'src/utils/streamlinedTransform.js' import { installStreamJsonStdoutGuard } from 'src/utils/streamJsonStdoutGuard.js' import type { ToolPermissionContext } from 'src/Tool.js' import type { ThinkingConfig } from 'src/utils/thinking.js' import { assembleToolPool, filterToolsByDenyRules } from 'src/tools.js' import uniqBy from 'lodash-es/uniqBy.js' import { uniq } from 'src/utils/array.js' import { mergeAndFilterTools } from 'src/utils/toolPool.js' import { logEvent, type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, } from 'src/services/analytics/index.js' import { getFeatureValue_CACHED_MAY_BE_STALE } from 'src/services/analytics/growthbook.js' import { logForDebugging } from 'src/utils/debug.js' import { logForDiagnosticsNoPII, withDiagnosticsTiming, } from 'src/utils/diagLogs.js' import { toolMatchesName, type Tool, type Tools } from 'src/Tool.js' import { type AgentDefinition, isBuiltInAgent, parseAgentsFromJson, } from 'src/tools/AgentTool/loadAgentsDir.js' import type { Message, NormalizedUserMessage } from 'src/types/message.js' import type { QueuedCommand } from 'src/types/textInputTypes.js' import { dequeue, dequeueAllMatching, enqueue, hasCommandsInQueue, peek, subscribeToCommandQueue, getCommandsByMaxPriority, } from 'src/utils/messageQueueManager.js' import { notifyCommandLifecycle } from 'src/utils/commandLifecycle.js' import { getSessionState, notifySessionStateChanged, notifySessionMetadataChanged, setPermissionModeChangedListener, type RequiresActionDetails, type SessionExternalMetadata, } from 'src/utils/sessionState.js' import { externalMetadataToAppState } from 'src/state/onChangeAppState.js' import { getInMemoryErrors, logError, logMCPDebug } from 'src/utils/log.js' import { writeToStdout, registerProcessOutputErrorHandlers, } from 'src/utils/process.js' import type { Stream } from 'src/utils/stream.js' import { EMPTY_USAGE } from 'src/services/api/logging.js' import { loadConversationForResume, type TurnInterruptionState, } from 'src/utils/conversationRecovery.js' import type { MCPServerConnection, McpSdkServerConfig, ScopedMcpServerConfig, } from 'src/services/mcp/types.js' import { ChannelMessageNotificationSchema, gateChannelServer, wrapChannelMessage, findChannelEntry, } from 'src/services/mcp/channelNotification.js' import { isChannelAllowlisted, isChannelsEnabled, } from 'src/services/mcp/channelAllowlist.js' import { parsePluginIdentifier } from 'src/utils/plugins/pluginIdentifier.js' import { validateUuid } from 'src/utils/uuid.js' import { fromArray } from 'src/utils/generators.js' import { ask } from 'src/QueryEngine.js' import type { PermissionPromptTool } from 'src/utils/queryHelpers.js' import { createFileStateCacheWithSizeLimit, mergeFileStateCaches, READ_FILE_STATE_CACHE_SIZE, } from 'src/utils/fileStateCache.js' import { expandPath } from 'src/utils/path.js' import { extractReadFilesFromMessages } from 'src/utils/queryHelpers.js' import { registerHookEventHandler } from 'src/utils/hooks/hookEvents.js' import { executeFilePersistence } from 'src/utils/filePersistence/filePersistence.js' import { finalizePendingAsyncHooks } from 'src/utils/hooks/AsyncHookRegistry.js' import { gracefulShutdown, gracefulShutdownSync, isShuttingDown, } from 'src/utils/gracefulShutdown.js' import { registerCleanup } from 'src/utils/cleanupRegistry.js' import { createIdleTimeoutManager } from 'src/utils/idleTimeout.js' import type { SDKStatus, ModelInfo, SDKMessage, SDKUserMessage, SDKUserMessageReplay, PermissionResult, McpServerConfigForProcessTransport, McpServerStatus, RewindFilesResult, } from 'src/entrypoints/agentSdkTypes.js' import type { StdoutMessage, SDKControlInitializeRequest, SDKControlInitializeResponse, SDKControlRequest, SDKControlResponse, SDKControlMcpSetServersResponse, SDKControlReloadPluginsResponse, } from 'src/entrypoints/sdk/controlTypes.js' import type { PermissionMode } from '@anthropic-ai/claude-agent-sdk' import type { PermissionMode as InternalPermissionMode } from 'src/types/permissions.js' import { cwd } from 'process' import { getCwd } from 'src/utils/cwd.js' import omit from 'lodash-es/omit.js' import reject from 'lodash-es/reject.js' import { isPolicyAllowed } from 'src/services/policyLimits/index.js' import type { ReplBridgeHandle } from 'src/bridge/replBridge.js' import { getRemoteSessionUrl } from 'src/constants/product.js' import { buildBridgeConnectUrl } from 'src/bridge/bridgeStatusUtil.js' import { extractInboundMessageFields } from 'src/bridge/inboundMessages.js' import { resolveAndPrepend } from 'src/bridge/inboundAttachments.js' import type { CanUseToolFn } from 'src/hooks/useCanUseTool.js' import { hasPermissionsToUseTool } from 'src/utils/permissions/permissions.js' import { safeParseJSON } from 'src/utils/json.js' import { outputSchema as permissionToolOutputSchema, permissionPromptToolResultToPermissionDecision, } from 'src/utils/permissions/PermissionPromptToolResultSchema.js' import { createAbortController } from 'src/utils/abortController.js' import { createCombinedAbortSignal } from 'src/utils/combinedAbortSignal.js' import { generateSessionTitle } from 'src/utils/sessionTitle.js' import { buildSideQuestionFallbackParams } from 'src/utils/queryContext.js' import { runSideQuestion } from 'src/utils/sideQuestion.js' import { processSessionStartHooks, processSetupHooks, takeInitialUserMessage, } from 'src/utils/sessionStart.js' import { DEFAULT_OUTPUT_STYLE_NAME, getAllOutputStyles, } from 'src/constants/outputStyles.js' import { TEAMMATE_MESSAGE_TAG, TICK_TAG } from 'src/constants/xml.js' import { getSettings_DEPRECATED, getSettingsWithSources, } from 'src/utils/settings/settings.js' import { settingsChangeDetector } from 'src/utils/settings/changeDetector.js' import { applySettingsChange } from 'src/utils/settings/applySettingsChange.js' import { isFastModeAvailable, isFastModeEnabled, isFastModeSupportedByModel, getFastModeState, } from 'src/utils/fastMode.js' import { isAutoModeGateEnabled, getAutoModeUnavailableNotification, getAutoModeUnavailableReason, isBypassPermissionsModeDisabled, transitionPermissionMode, } from 'src/utils/permissions/permissionSetup.js' import { tryGenerateSuggestion, logSuggestionOutcome, logSuggestionSuppressed, type PromptVariant, } from 'src/services/PromptSuggestion/promptSuggestion.js' import { getLastCacheSafeParams } from 'src/utils/forkedAgent.js' import { getAccountInformation } from 'src/utils/auth.js' import { OAuthService } from 'src/services/oauth/index.js' import { installOAuthTokens } from 'src/cli/handlers/auth.js' import { getAPIProvider } from 'src/utils/model/providers.js' import type { HookCallbackMatcher } from 'src/types/hooks.js' import { AwsAuthStatusManager } from 'src/utils/awsAuthStatusManager.js' import type { HookEvent } from 'src/entrypoints/agentSdkTypes.js' import { registerHookCallbacks, setInitJsonSchema, getInitJsonSchema, setSdkAgentProgressSummariesEnabled, } from 'src/bootstrap/state.js' import { createSyntheticOutputTool } from 'src/tools/SyntheticOutputTool/SyntheticOutputTool.js' import { parseSessionIdentifier } from 'src/utils/sessionUrl.js' import { hydrateRemoteSession, hydrateFromCCRv2InternalEvents, resetSessionFilePointer, doesMessageExistInSession, findUnresolvedToolUse, recordAttributionSnapshot, saveAgentSetting, saveMode, saveAiGeneratedTitle, restoreSessionMetadata, } from 'src/utils/sessionStorage.js' import { incrementPromptCount } from 'src/utils/commitAttribution.js' import { setupSdkMcpClients, connectToServer, clearServerCache, fetchToolsForClient, areMcpConfigsEqual, reconnectMcpServerImpl, } from 'src/services/mcp/client.js' import { filterMcpServersByPolicy, getMcpConfigByName, isMcpServerDisabled, setMcpServerEnabled, } from 'src/services/mcp/config.js' import { performMCPOAuthFlow, revokeServerTokens, } from 'src/services/mcp/auth.js' import { runElicitationHooks, runElicitationResultHooks, } from 'src/services/mcp/elicitationHandler.js' import { executeNotificationHooks } from 'src/utils/hooks.js' import { ElicitRequestSchema, ElicitationCompleteNotificationSchema, } from '@modelcontextprotocol/sdk/types.js' import { getMcpPrefix } from 'src/services/mcp/mcpStringUtils.js' import { commandBelongsToServer, filterToolsByServer, } from 'src/services/mcp/utils.js' import { setupVscodeSdkMcp } from 'src/services/mcp/vscodeSdkMcp.js' import { getAllMcpConfigs } from 'src/services/mcp/config.js' import { isQualifiedForGrove, checkGroveForNonInteractive, } from 'src/services/api/grove.js' import { toInternalMessages, toSDKRateLimitInfo, } from 'src/utils/messages/mappers.js' import { createModelSwitchBreadcrumbs } from 'src/utils/messages.js' import { collectContextData } from 'src/commands/context/context-noninteractive.js' import { LOCAL_COMMAND_STDOUT_TAG } from 'src/constants/xml.js' import { statusListeners, type ClaudeAILimits, } from 'src/services/claudeAiLimits.js' import { getDefaultMainLoopModel, getMainLoopModel, modelDisplayString, parseUserSpecifiedModel, } from 'src/utils/model/model.js' import { getModelOptions } from 'src/utils/model/modelOptions.js' import { modelSupportsEffort, modelSupportsMaxEffort, EFFORT_LEVELS, resolveAppliedEffort, } from 'src/utils/effort.js' import { modelSupportsAdaptiveThinking } from 'src/utils/thinking.js' import { modelSupportsAutoMode } from 'src/utils/betas.js' import { ensureModelStringsInitialized } from 'src/utils/model/modelStrings.js' import { getSessionId, setMainLoopModelOverride, setMainThreadAgentType, switchSession, isSessionPersistenceDisabled, getIsRemoteMode, getFlagSettingsInline, setFlagSettingsInline, getMainThreadAgentType, getAllowedChannels, setAllowedChannels, type ChannelEntry, } from 'src/bootstrap/state.js' import { runWithWorkload, WORKLOAD_CRON } from 'src/utils/workloadContext.js' import type { UUID } from 'crypto' import { randomUUID } from 'crypto' import type { ContentBlockParam } from '@anthropic-ai/sdk/resources/messages.mjs' import type { AppState } from 'src/state/AppStateStore.js' import { fileHistoryRewind, fileHistoryCanRestore, fileHistoryEnabled, fileHistoryGetDiffStats, } from 'src/utils/fileHistory.js' import { restoreAgentFromSession, restoreSessionStateFromLog, } from 'src/utils/sessionRestore.js' import { SandboxManager } from 'src/utils/sandbox/sandbox-adapter.js' import { headlessProfilerStartTurn, headlessProfilerCheckpoint, logHeadlessProfilerTurn, } from 'src/utils/headlessProfiler.js' import { startQueryProfile, logQueryProfileReport, } from 'src/utils/queryProfiler.js' import { asSessionId } from 'src/types/ids.js' import { jsonStringify } from '../utils/slowOperations.js' import { skillChangeDetector } from '../utils/skills/skillChangeDetector.js' import { getCommands, clearCommandsCache } from '../commands.js' import { isBareMode, isEnvTruthy, isEnvDefinedFalsy, } from '../utils/envUtils.js' import { installPluginsForHeadless } from '../utils/plugins/headlessPluginInstall.js' import { refreshActivePlugins } from '../utils/plugins/refresh.js' import { loadAllPluginsCacheOnly } from '../utils/plugins/pluginLoader.js' import { isTeamLead, hasActiveInProcessTeammates, hasWorkingInProcessTeammates, waitForTeammatesToBecomeIdle, } from '../utils/teammate.js' import { readUnreadMessages, markMessagesAsRead, isShutdownApproved, } from '../utils/teammateMailbox.js' import { removeTeammateFromTeamFile } from '../utils/swarm/teamHelpers.js' import { unassignTeammateTasks } from '../utils/tasks.js' import { getRunningTasks } from '../utils/task/framework.js' import { isBackgroundTask } from '../tasks/types.js' import { stopTask } from '../tasks/stopTask.js' import { drainSdkEvents } from '../utils/sdkEventQueue.js' import { initializeGrowthBook } from '../services/analytics/growthbook.js' import { errorMessage, toError } from '../utils/errors.js' import { sleep } from '../utils/sleep.js' import { isExtractModeActive } from '../memdir/paths.js' // Dead code elimination: conditional imports /* eslint-disable @typescript-eslint/no-require-imports */ const coordinatorModeModule = feature('COORDINATOR_MODE') ? (require('../coordinator/coordinatorMode.js') as typeof import('../coordinator/coordinatorMode.js')) : null const proactiveModule = feature('PROACTIVE') || feature('KAIROS') ? (require('../proactive/index.js') as typeof import('../proactive/index.js')) : null const cronSchedulerModule = feature('AGENT_TRIGGERS') ? (require('../utils/cronScheduler.js') as typeof import('../utils/cronScheduler.js')) : null const cronJitterConfigModule = feature('AGENT_TRIGGERS') ? (require('../utils/cronJitterConfig.js') as typeof import('../utils/cronJitterConfig.js')) : null const cronGate = feature('AGENT_TRIGGERS') ? (require('../tools/ScheduleCronTool/prompt.js') as typeof import('../tools/ScheduleCronTool/prompt.js')) : null const extractMemoriesModule = feature('EXTRACT_MEMORIES') ? (require('../services/extractMemories/extractMemories.js') as typeof import('../services/extractMemories/extractMemories.js')) : null /* eslint-enable @typescript-eslint/no-require-imports */ const SHUTDOWN_TEAM_PROMPT = `<system-reminder> You are running in non-interactive mode and cannot return a response to the user until your team is shut down. You MUST shut down your team before preparing your final response: 1. Use requestShutdown to ask each team member to shut down gracefully 2. Wait for shutdown approvals 3. Use the cleanup operation to clean up the team 4. Only then provide your final response to the user The user cannot receive your response until the team is completely shut down. </system-reminder> Shut down your team and prepare your final response for the user.` // Track message UUIDs received during the current session runtime const MAX_RECEIVED_UUIDS = 10_000 const receivedMessageUuids = new Set<UUID>() const receivedMessageUuidsOrder: UUID[] = [] function trackReceivedMessageUuid(uuid: UUID): boolean { if (receivedMessageUuids.has(uuid)) { return false // duplicate } receivedMessageUuids.add(uuid) receivedMessageUuidsOrder.push(uuid) // Evict oldest entries when at capacity if (receivedMessageUuidsOrder.length > MAX_RECEIVED_UUIDS) { const toEvict = receivedMessageUuidsOrder.splice( 0, receivedMessageUuidsOrder.length - MAX_RECEIVED_UUIDS, ) for (const old of toEvict) { receivedMessageUuids.delete(old) } } return true // new UUID } type PromptValue = string | ContentBlockParam[] function toBlocks(v: PromptValue): ContentBlockParam[] { return typeof v === 'string' ? [{ type: 'text', text: v }] : v } /** * Join prompt values from multiple queued commands into one. Strings are * newline-joined; if any value is a block array, all values are normalized * to blocks and concatenated. */ export function joinPromptValues(values: PromptValue[]): PromptValue { if (values.length === 1) return values[0]! if (values.every(v => typeof v === 'string')) { return values.join('\n') } return values.flatMap(toBlocks) } /** * Whether `next` can be batched into the same ask() call as `head`. Only * prompt-mode commands batch, and only when the workload tag matches (so the * combined turn is attributed correctly) and the isMeta flag matches (so a * proactive tick can't merge into a user prompt and lose its hidden-in- * transcript marking when the head is spread over the merged command). */ export function canBatchWith( head: QueuedCommand, next: QueuedCommand | undefined, ): boolean { return ( next !== undefined && next.mode === 'prompt' && next.workload === head.workload && next.isMeta === head.isMeta ) } export async function runHeadless( inputPrompt: string | AsyncIterable<string>, getAppState: () => AppState, setAppState: (f: (prev: AppState) => AppState) => void, commands: Command[], tools: Tools, sdkMcpConfigs: Record<string, McpSdkServerConfig>, agents: AgentDefinition[], options: { continue: boolean | undefined resume: string | boolean | undefined resumeSessionAt: string | undefined verbose: boolean | undefined outputFormat: string | undefined jsonSchema: Record<string, unknown> | undefined permissionPromptToolName: string | undefined allowedTools: string[] | undefined thinkingConfig: ThinkingConfig | undefined maxTurns: number | undefined maxBudgetUsd: number | undefined taskBudget: { total: number } | undefined systemPrompt: string | undefined appendSystemPrompt: string | undefined userSpecifiedModel: string | undefined fallbackModel: string | undefined teleport: string | true | null | undefined sdkUrl: string | undefined replayUserMessages: boolean | undefined includePartialMessages: boolean | undefined forkSession: boolean | undefined rewindFiles: string | undefined enableAuthStatus: boolean | undefined agent: string | undefined workload: string | undefined setupTrigger?: 'init' | 'maintenance' | undefined sessionStartHooksPromise?: ReturnType<typeof processSessionStartHooks> setSDKStatus?: (status: SDKStatus) => void }, ): Promise<void> { if ( process.env.USER_TYPE === 'ant' && isEnvTruthy(process.env.CLAUDE_CODE_EXIT_AFTER_FIRST_RENDER) ) { process.stderr.write( `\nStartup time: ${Math.round(process.uptime() * 1000)}ms\n`, ) // eslint-disable-next-line custom-rules/no-process-exit process.exit(0) } // Fire user settings download now so it overlaps with the MCP/tool setup // below. Managed settings already started in main.tsx preAction; this gives // user settings a similar head start. The cached promise is joined in // installPluginsAndApplyMcpInBackground before plugin install reads // enabledPlugins. if ( feature('DOWNLOAD_USER_SETTINGS') && (isEnvTruthy(process.env.CLAUDE_CODE_REMOTE) || getIsRemoteMode()) ) { void downloadUserSettings() } // In headless mode there is no React tree, so the useSettingsChange hook // never runs. Subscribe directly so that settings changes (including // managed-settings / policy updates) are fully applied. settingsChangeDetector.subscribe(source => { applySettingsChange(source, setAppState) // In headless mode, also sync the denormalized fastMode field from // settings. The TUI manages fastMode via the UI so it skips this. if (isFastModeEnabled()) { setAppState(prev => { const s = prev.settings as Record<string, unknown> const fastMode = s.fastMode === true && !s.fastModePerSessionOptIn return { ...prev, fastMode } }) } }) // Proactive activation is now handled in main.tsx before getTools() so // SleepTool passes isEnabled() filtering. This fallback covers the case // where CLAUDE_CODE_PROACTIVE is set but main.tsx's check didn't fire // (e.g. env was injected by the SDK transport after argv parsing). if ( (feature('PROACTIVE') || feature('KAIROS')) && proactiveModule && !proactiveModule.isProactiveActive() && isEnvTruthy(process.env.CLAUDE_CODE_PROACTIVE) ) { proactiveModule.activateProactive('command') } // Periodically force a full GC to keep memory usage in check if (typeof Bun !== 'undefined') { const gcTimer = setInterval(Bun.gc, 1000) gcTimer.unref() } // Start headless profiler for first turn headlessProfilerStartTurn() headlessProfilerCheckpoint('runHeadless_entry') // Check Grove requirements for non-interactive consumer subscribers if (await isQualifiedForGrove()) { await checkGroveForNonInteractive() } headlessProfilerCheckpoint('after_grove_check') // Initialize GrowthBook so feature flags take effect in headless mode. // Without this, the disk cache is empty and all flags fall back to defaults. void initializeGrowthBook() if (options.resumeSessionAt && !options.resume) { process.stderr.write(`Error: --resume-session-at requires --resume\n`) gracefulShutdownSync(1) return } if (options.rewindFiles && !options.resume) { process.stderr.write(`Error: --rewind-files requires --resume\n`) gracefulShutdownSync(1) return } if (options.rewindFiles && inputPrompt) { process.stderr.write( `Error: --rewind-files is a standalone operation and cannot be used with a prompt\n`, ) gracefulShutdownSync(1) return } const structuredIO = getStructuredIO(inputPrompt, options) // When emitting NDJSON for SDK clients, any stray write to stdout (debug // prints, dependency console.log, library banners) breaks the client's // line-by-line JSON parser. Install a guard that diverts non-JSON lines to // stderr so the stream stays clean. Must run before the first // structuredIO.write below. if (options.outputFormat === 'stream-json') { installStreamJsonStdoutGuard() } // #34044: if user explicitly set sandbox.enabled=true but deps are missing, // isSandboxingEnabled() returns false silently. Surface the reason so users // know their security config isn't being enforced. const sandboxUnavailableReason = SandboxManager.getSandboxUnavailableReason() if (sandboxUnavailableReason) { if (SandboxManager.isSandboxRequired()) { process.stderr.write( `\nError: sandbox required but unavailable: ${sandboxUnavailableReason}\n` + ` sandbox.failIfUnavailable is set — refusing to start without a working sandbox.\n\n`, ) gracefulShutdownSync(1) return } process.stderr.write( `\n⚠ Sandbox disabled: ${sandboxUnavailableReason}\n` + ` Commands will run WITHOUT sandboxing. Network and filesystem restrictions will NOT be enforced.\n\n`, ) } else if (SandboxManager.isSandboxingEnabled()) { // Initialize sandbox with a callback that forwards network permission // requests to the SDK host via the can_use_tool control_request protocol. // This must happen after structuredIO is created so we can send requests. try { await SandboxManager.initialize(structuredIO.createSandboxAskCallback()) } catch (err) { process.stderr.write(`\n❌ Sandbox Error: ${errorMessage(err)}\n`) gracefulShutdownSync(1, 'other') return } } if (options.outputFormat === 'stream-json' && options.verbose) { registerHookEventHandler(event => { const message: StdoutMessage = (() => { switch (event.type) { case 'started': return { type: 'system' as const, subtype: 'hook_started' as const, hook_id: event.hookId, hook_name: event.hookName, hook_event: event.hookEvent, uuid: randomUUID(), session_id: getSessionId(), } case 'progress': return { type: 'system' as const, subtype: 'hook_progress' as const, hook_id: event.hookId, hook_name: event.hookName, hook_event: event.hookEvent, stdout: event.stdout, stderr: event.stderr, output: event.output, uuid: randomUUID(), session_id: getSessionId(), } case 'response': return { type: 'system' as const, subtype: 'hook_response' as const, hook_id: event.hookId, hook_name: event.hookName, hook_event: event.hookEvent, output: event.output, stdout: event.stdout, stderr: event.stderr, exit_code: event.exitCode, outcome: event.outcome, uuid: randomUUID(), session_id: getSessionId(), } } })() void structuredIO.write(message) }) } if (options.setupTrigger) { await processSetupHooks(options.setupTrigger) } headlessProfilerCheckpoint('before_loadInitialMessages') const appState = getAppState() const { messages: initialMessages, turnInterruptionState, agentSetting: resumedAgentSetting, } = await loadInitialMessages(setAppState, { continue: options.continue, teleport: options.teleport, resume: options.resume, resumeSessionAt: options.resumeSessionAt, forkSession: options.forkSession, outputFormat: options.outputFormat, sessionStartHooksPromise: options.sessionStartHooksPromise, restoredWorkerState: structuredIO.restoredWorkerState, }) // SessionStart hooks can emit initialUserMessage — the first user turn for // headless orchestrator sessions where stdin is empty and additionalContext // alone (an attachment, not a turn) would leave the REPL with nothing to // respond to. The hook promise is awaited inside loadInitialMessages, so the // module-level pending value is set by the time we get here. const hookInitialUserMessage = takeInitialUserMessage() if (hookInitialUserMessage) { structuredIO.prependUserMessage(hookInitialUserMessage) } // Restore agent setting from the resumed session (if not overridden by current --agent flag // or settings-based agent, which would already have set mainThreadAgentType in main.tsx) if (!options.agent && !getMainThreadAgentType() && resumedAgentSetting) { const { agentDefinition: restoredAgent } = restoreAgentFromSession( resumedAgentSetting, undefined, { activeAgents: agents, allAgents: agents }, ) if (restoredAgent) { setAppState(prev => ({ ...prev, agent: restoredAgent.agentType })) // Apply the agent's system prompt for non-built-in agents (mirrors main.tsx initial --agent path) if (!options.systemPrompt && !isBuiltInAgent(restoredAgent)) { const agentSystemPrompt = restoredAgent.getSystemPrompt() if (agentSystemPrompt) { options.systemPrompt = agentSystemPrompt } } // Re-persist agent setting so future resumes maintain the agent saveAgentSetting(restoredAgent.agentType) } } // gracefulShutdownSync schedules an async shutdown and sets process.exitCode. // If a loadInitialMessages error path triggered it, bail early to avoid // unnecessary work while the process winds down. if (initialMessages.length === 0 && process.exitCode !== undefined) { return } // Handle --rewind-files: restore filesystem and exit immediately if (options.rewindFiles) { // File history snapshots are only created for user messages, // so we require the target to be a user message const targetMessage = initialMessages.find( m => m.uuid === options.rewindFiles, ) if (!targetMessage || targetMessage.type !== 'user') { process.stderr.write( `Error: --rewind-files requires a user message UUID, but ${options.rewindFiles} is not a user message in this session\n`, ) gracefulShutdownSync(1) return } const currentAppState = getAppState() const result = await handleRewindFiles( options.rewindFiles as UUID, currentAppState, setAppState, false, ) if (!result.canRewind) { process.stderr.write(`Error: ${result.error || 'Unexpected error'}\n`) gracefulShutdownSync(1) return } // Rewind complete - exit successfully process.stdout.write( `Files rewound to state at message ${options.rewindFiles}\n`, ) gracefulShutdownSync(0) return } // Check if we need input prompt - skip if we're resuming with a valid session ID/JSONL file or using SDK URL const hasValidResumeSessionId = typeof options.resume === 'string' && (Boolean(validateUuid(options.resume)) || options.resume.endsWith('.jsonl')) const isUsingSdkUrl = Boolean(options.sdkUrl) if (!inputPrompt && !hasValidResumeSessionId && !isUsingSdkUrl) { process.stderr.write( `Error: Input must be provided either through stdin or as a prompt argument when using --print\n`, ) gracefulShutdownSync(1) return } if (options.outputFormat === 'stream-json' && !options.verbose) { process.stderr.write( 'Error: When using --print, --output-format=stream-json requires --verbose\n', ) gracefulShutdownSync(1) return } // Filter out MCP tools that are in the deny list const allowedMcpTools = filterToolsByDenyRules( appState.mcp.tools, appState.toolPermissionContext, ) let filteredTools = [...tools, ...allowedMcpTools] // When using SDK URL, always use stdio permission prompting to delegate to the SDK const effectivePermissionPromptToolName = options.sdkUrl ? 'stdio' : options.permissionPromptToolName // Callback for when a permission prompt is shown const onPermissionPrompt = (details: RequiresActionDetails) => { if (feature('COMMIT_ATTRIBUTION')) { setAppState(prev => ({ ...prev, attribution: { ...prev.attribution, permissionPromptCount: prev.attribution.permissionPromptCount + 1, }, })) } notifySessionStateChanged('requires_action', details) } const canUseTool = getCanUseToolFn( effectivePermissionPromptToolName, structuredIO, () => getAppState().mcp.tools, onPermissionPrompt, ) if (options.permissionPromptToolName) { // Remove the permission prompt tool from the list of available tools. filteredTools = filteredTools.filter( tool => !toolMatchesName(tool, options.permissionPromptToolName!), ) } // Install errors handlers to gracefully handle broken pipes (e.g., when parent process dies) registerProcessOutputErrorHandlers() headlessProfilerCheckpoint('after_loadInitialMessages') // Ensure model strings are initialized before generating model options. // For Bedrock users, this waits for the profile fetch to get correct region strings. await ensureModelStringsInitialized() headlessProfilerCheckpoint('after_modelStrings') // UDS inbox store registration is deferred until after `run` is defined // so we can pass `run` as the onEnqueue callback (see below). // Only `json` + `verbose` needs the full array (jsonStringify(messages) below). // For stream-json (SDK/CCR) and default text output, only the last message is // read for the exit code / final result. Avoid accumulating every message in // memory for the entire session. const needsFullArray = options.outputFormat === 'json' && options.verbose const messages: SDKMessage[] = [] let lastMessage: SDKMessage | undefined // Streamlined mode transforms messages when CLAUDE_CODE_STREAMLINED_OUTPUT=true and using stream-json // Build flag gates this out of external builds; env var is the runtime opt-in for ant builds const transformToStreamlined = feature('STREAMLINED_OUTPUT') && isEnvTruthy(process.env.CLAUDE_CODE_STREAMLINED_OUTPUT) && options.outputFormat === 'stream-json' ? createStreamlinedTransformer() : null headlessProfilerCheckpoint('before_runHeadlessStreaming') for await (const message of runHeadlessStreaming( structuredIO, appState.mcp.clients, [...commands, ...appState.mcp.commands], filteredTools, initialMessages, canUseTool, sdkMcpConfigs, getAppState, setAppState, agents, options, turnInterruptionState, )) { if (transformToStreamlined) { // Streamlined mode: transform messages and stream immediately const transformed = transformToStreamlined(message) if (transformed) { await structuredIO.write(transformed) } } else if (options.outputFormat === 'stream-json' && options.verbose) { await structuredIO.write(message) } // Should not be getting control messages or stream events in non-stream mode. // Also filter out streamlined types since they're only produced by the transformer. // SDK-only system events are excluded so lastMessage stays at the result // (session_state_changed(idle) and any late task_notification drain after // result in the finally block). if ( message.type !== 'control_response' && message.type !== 'control_request' && message.type !== 'control_cancel_request' && !( message.type === 'system' && (message.subtype === 'session_state_changed' || message.subtype === 'task_notification' || message.subtype === 'task_started' || message.subtype === 'task_progress' || message.subtype === 'post_turn_summary') ) && message.type !== 'stream_event' && message.type !== 'keep_alive' && message.type !== 'streamlined_text' && message.type !== 'streamlined_tool_use_summary' && message.type !== 'prompt_suggestion' ) { if (needsFullArray) { messages.push(message) } lastMessage = message } } switch (options.outputFormat) { case 'json': if (!lastMessage || lastMessage.type !== 'result') { throw new Error('No messages returned') } if (options.verbose) { writeToStdout(jsonStringify(messages) + '\n') break } writeToStdout(jsonStringify(lastMessage) + '\n') break case 'stream-json': // already logged above break default: if (!lastMessage || lastMessage.type !== 'result') { throw new Error('No messages returned') } switch (lastMessage.subtype) { case 'success': writeToStdout( lastMessage.result.endsWith('\n') ? lastMessage.result : lastMessage.result + '\n', ) break case 'error_during_execution': writeToStdout(`Execution error`) break case 'error_max_turns': writeToStdout(`Error: Reached max turns (${options.maxTurns})`) break case 'error_max_budget_usd': writeToStdout(`Error: Exceeded USD budget (${options.maxBudgetUsd})`) break case 'error_max_structured_output_retries': writeToStdout( `Error: Failed to provide valid structured output after maximum retries`, ) } } // Log headless latency metrics for the final turn logHeadlessProfilerTurn() // Drain any in-flight memory extraction before shutdown. The response is // already flushed above, so this adds no user-visible latency — it just // delays process exit so gracefulShutdownSync's 5s failsafe doesn't kill // the forked agent mid-flight. Gated by isExtractModeActive so the // tengu_slate_thimble flag controls non-interactive extraction end-to-end. if (feature('EXTRACT_MEMORIES') && isExtractModeActive()) { await extractMemoriesModule!.drainPendingExtraction() } gracefulShutdownSync( lastMessage?.type === 'result' && lastMessage?.is_error ? 1 : 0, ) } function runHeadlessStreaming( structuredIO: StructuredIO, mcpClients: MCPServerConnection[], commands: Command[], tools: Tools, initialMessages: Message[], canUseTool: CanUseToolFn, sdkMcpConfigs: Record<string, McpSdkServerConfig>, getAppState: () => AppState, setAppState: (f: (prev: AppState) => AppState) => void, agents: AgentDefinition[], options: { verbose: boolean | undefined jsonSchema: Record<string, unknown> | undefined permissionPromptToolName: string | undefined allowedTools: string[] | undefined thinkingConfig: ThinkingConfig | undefined maxTurns: number | undefined maxBudgetUsd: number | undefined taskBudget: { total: number } | undefined systemPrompt: string | undefined appendSystemPrompt: string | undefined userSpecifiedModel: string | undefined fallbackModel: string | undefined replayUserMessages?: boolean | undefined |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |