@humain/humain-code 0.8.4 → 0.8.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/bundle/chunks/{chunk-4BNDLR6C.js → chunk-2RXTZK2V.js} +1 -1
- package/dist/bundle/chunks/{chunk-CIAXW64K.js → chunk-3OOOEJV4.js} +5 -5
- package/dist/bundle/chunks/{chunk-J5YFXMTM.js → chunk-53DWQSBC.js} +1 -1
- package/dist/bundle/chunks/{chunk-73YX5XGR.js → chunk-7XRMMCKG.js} +267 -251
- package/dist/bundle/chunks/{chunk-HWXQCJDP.js → chunk-BDNX23GT.js} +76 -71
- package/dist/bundle/chunks/{chunk-52642TYH.js → chunk-COZTJAOY.js} +54 -51
- package/dist/bundle/chunks/{chunk-SOE25WIS.js → chunk-EWPEY4F4.js} +789 -790
- package/dist/bundle/chunks/{chunk-ARTF7ZMQ.js → chunk-FHP5BULR.js} +1 -1
- package/dist/bundle/chunks/{chunk-XGSJX23G.js → chunk-N3W4ALAM.js} +1 -1
- package/dist/bundle/chunks/{chunk-OTVHRZ67.js → chunk-SASR4VNV.js} +1 -1
- package/dist/bundle/chunks/{chunk-EVDQRT3I.js → chunk-VWUEKLRH.js} +8 -8
- package/dist/bundle/chunks/{compat-7UJJAO4E.js → compat-2RC4CJNV.js} +1 -1
- package/dist/bundle/chunks/{dist-7PCCEUQF.js → dist-3DAGUOYC.js} +1 -1
- package/dist/bundle/chunks/{dist-I53JI67E.js → dist-K4QIXV5O.js} +5 -5
- package/dist/bundle/chunks/{doctor-KJVAYG3F.js → doctor-EH7X36SK.js} +2 -2
- package/dist/bundle/chunks/{flow-implementer-GE2ARQKR.js → flow-implementer-J6QTLBTH.js} +2 -2
- package/dist/bundle/chunks/{inprocess-MGMVI6HN.js → inprocess-OHNEKTFB.js} +3 -3
- package/dist/bundle/chunks/{interactive-mode-HHWOE4FD.js → interactive-mode-ZREVRX7W.js} +2 -2
- package/dist/bundle/chunks/{virtual-modules-UXSSFNV5.js → virtual-modules-6FVRJTM3.js} +3 -3
- package/dist/bundle/cli-runtime.js +2 -2
- package/dist/bundle/index.js +6 -6
- package/dist/bundle/rpc-entry.js +2 -2
- package/dist/core/bug-report.d.ts +24 -1
- package/dist/core/bug-report.d.ts.map +1 -1
- package/dist/core/bug-report.js +216 -19
- package/dist/core/bug-report.js.map +1 -1
- package/dist/core/extensions/containment.d.ts +26 -0
- package/dist/core/extensions/containment.d.ts.map +1 -0
- package/dist/core/extensions/containment.js +66 -0
- package/dist/core/extensions/containment.js.map +1 -0
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +65 -7
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +2 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +55 -10
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +5 -2
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/extensions/wrapper.d.ts.map +1 -1
- package/dist/core/extensions/wrapper.js +4 -1
- package/dist/core/extensions/wrapper.js.map +1 -1
- package/dist/humain/checklist/vendor/commands.d.ts.map +1 -1
- package/dist/humain/checklist/vendor/commands.js +20 -8
- package/dist/humain/checklist/vendor/commands.js.map +1 -1
- package/dist/humain/flow-loader.d.ts.map +1 -1
- package/dist/humain/flow-loader.js +31 -5
- package/dist/humain/flow-loader.js.map +1 -1
- package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/index.js +11 -1
- package/dist/humain/web-access/vendor/index.js.map +1 -1
- package/dist/modes/interactive/bug-report.d.ts.map +1 -1
- package/dist/modes/interactive/bug-report.js +48 -12
- package/dist/modes/interactive/bug-report.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +3 -3
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +28 -46
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/docs/extensions.md +2 -0
- package/docs/flow.md +2 -0
- package/docs/humain-code.md +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/src/humain/web-access/UPSTREAM.md +8 -0
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
2
|
import{ArminComponent}from"./chunk-O44A4E4K.js";import{SessionSelectorComponent}from"./chunk-AER66CNP.js";import{CountdownTimer,ExtensionInputComponent,ExtensionSelectorComponent,InteractiveThemeController,ProgramStatusReporter,dialogBlockedStatus,renderHumainCodeIcon,renderHumainCodeIconInline}from"./chunk-UOSJTMCL.js";import{AuthUrlComponent,FULLSCREEN_OVERLAY,FooterComponent,HCODE_LOGIN_MISMATCH_DETAILS,StatusLineContainer,bindClaudeUsageReconnect,checkWatchedHcodeCatalog,copyToClipboard,
|
|
3
|
-
formatOAuthAccountOption,formatOAuthAccountResetTime,formatOAuthAccountUsage,formatTokens,fullscreenSurface,hcodeEmptyCatalogMessage,hcodeEmptyCatalogNotice,hcodeEmptyCatalogReason,hcodeLoginAvailability,hcodeSignedInElsewhereNotice,onUnhandledRejection,readClaudeUsage,readClipboardFilePaths,readClipboardText,refreshModelCatalogs,refreshStartupModelCatalogs,renderUsageBar,retryHcodeCatalog,runClipboardCommand,subscriptionAccountUsage,trackUserWait,usageDisplayText,usagePaneRow,waitForSignalShutdown}from"./chunk-
|
|
4
|
-
import{ANTHROPIC_USAGE_PROVIDER_ID,Agent,BUG_REPORT_CUSTOM_ENTRY_TYPE,CAVEMAN_LEVELS,FooterDataProvider,HUMAIN_FUSE_PROVIDER,MissingSessionCwdError,RUNTIME_MODES,SessionImportFileNotFoundError,bugReportArchiveFileName,collectBugReportDiagnostics,collectBugReportMetadata,createBugReportConversation,
|
|
5
|
-
getCavemanDefaultMode,getModelSelectionIntent,grepRenderers,isInstallTelemetryEnabled,lsRenderers,parseSkillBlock,readDefaultMode,readRenderers,renderersMayHighlight,resolveAdhdSessionMode,resolveCavemanSessionMode,resolveSessionMode,writeBugReportArchive,writeRenderers}from"./chunk-
|
|
6
|
-
import{ACCOUNT_REPORT_REQUEST_TIMEOUT_MS,ANTHROPIC_PROVIDER_ID,AccountReporter,CODEX_USAGE_PROVIDER_ID,CredentialSynchronizationError,DEFAULT_THINKING_LEVEL,HCODE_PROVIDER,HCODE_SELECTION_CHANGED_MESSAGE,HCODE_SESSION_ONLY_NOTICE,HCODE_UNSUPPORTED_THINKING_MESSAGE,HUMAIN_GATEWAY_PROVIDER,HUMAIN_NODE_BASE_URL_ENV,HUMAIN_NODE_PROVIDER,MAX_NODE_FALLBACK_KEYS,
|
|
7
|
-
createAnthropicReportCollector,createCodexUsageCollector,defaultModelPerProvider,describeHumainNodeEndpoint,detectSupportedImageMimeType,ensurePngTranscoder,ensurePngTranscoderOnFirstUse,findExactModelReferenceMatch,formatAccountUsageReport,formatHcodeMessageNotice,getBranchSelection,getCodexAvailability,getOAuthAccountRemovalSuccessor,hcodeExcludedSelection,
|
|
8
|
-
import{SessionManager,bashTruncationNote,createCompactionSummaryMessage,createCustomMessage,loadPhoton,sessionEntryToContextMessages}from"./chunk-B3FT6L6S.js";import{createTraceRedactor,getTraceEnvSecrets}from"./chunk-D4UCXXDP.js";import{DEFAULT_RADIUS_GATEWAY,normalizeRadiusGatewayUrl}from"./chunk-
|
|
9
|
-
|
|
10
|
-
import{formatKeyText,keyDisplayText,keyHint,keyText,rawKeyHint,selectNavigationHint}from"./chunk-MXF3KYLZ.js";import{DEFAULT_THEME_NAME,SYSTEM_THEME_NAME,Theme,getAvailableThemes,getAvailableThemesWithPaths,getEditorTheme,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,getThemeByName,getThemeInstance,loadAllHighlightLanguagesOnDemand,onThemeChange,parseAutoThemeSetting,
|
|
11
|
-
getSourcePackageKey,hcodeDisplayName,isSyntheticPath,isWSL,parseGitUrl,resolveHcodeEnvironment}from"./chunk-OADQOW67.js";import{CACHE_WARMING_MODES,HTTP_IDLE_TIMEOUT_CHOICES,configureHttpDispatcher,formatHttpIdleTimeoutMs}from"./chunk-4SL6URR3.js";import{SETTINGS_DEFAULTS}from"./chunk-RP6MWUAP.js";import{Box,CURSOR_MARKER,CancellableLoader,CombinedAutocompleteProvider,
|
|
12
|
-
Spacer,Text,TruncatedText,TuiAltScreen,TuiMainScreen,VStack,applyBackgroundToLine,foregroundAnsi,fuzzyFilter,getCapabilities,getKeybindings,getNativeClipboard,getSelectPageIndex,hyperlink,isViewportTUI,markLiveRender,markReportsChanges,markStableRender,matchesKey,mixColors,ne,onCapabilitiesChange,parseColor,renderChildLines,renderedMarkdownGeneration,replaceControlCharacters,
|
|
13
|
-
startsWithText,stripTerminalSequences,truncateToWidth,visibleWidth,wrapTextWithAnsi}from"./chunk-H35P7ROY.js";import{source_default}from"./chunk-XQRYOCHA.js";import{isRetryableAssistantError}from"./chunk-BIC5BSNX.js";import{clampThinkingLevel,getSupportedThinkingLevels,modelsAreEqual}from"./chunk-KJ3QRSSY.js";import{curatedModelsPolicy,isCuratedModel}from"./chunk-T7F2TEIS.js";
|
|
14
|
-
getAuthPath,getBundledInteractiveAssetPath,getChangelogPath,getChangelogUrl,getCwdRelativePath,getDebugLogPath,getDocsPath,getShareViewerUrl,resolvePath,shortenHomePath,stripBom,usesDefaultAgentDir}from"./chunk-CKFLQGJN.js";import*as fs3 from"node:fs";import*as path4 from"node:path";import{spawn as spawn3}from"child_process";function detectMiss(prev,message,models){let usage=message.usage,promptTokens=usage.input+usage.cacheRead+usage.cacheWrite;if(!prev||promptTokens<=0||usage.cacheRead+usage.cacheWrite===0&&!prev.reportedCache)return;let missedTokens=Math.min(prev.promptTokens,promptTokens)-usage.cacheRead;if(missedTokens<=1024)return;let paidTokens=usage.input+usage.cacheWrite,paidPerToken=paidTokens>0?(usage.cost.input+usage.cost.cacheWrite)/paidTokens:0,readPerToken=usage.cacheRead>0?usage.cost.cacheRead/usage.
|
|
3
|
+
formatOAuthAccountOption,formatOAuthAccountResetTime,formatOAuthAccountUsage,formatTokens,fullscreenSurface,hcodeEmptyCatalogMessage,hcodeEmptyCatalogNotice,hcodeEmptyCatalogReason,hcodeLoginAvailability,hcodeSignedInElsewhereNotice,onUnhandledRejection,readClaudeUsage,readClipboardFilePaths,readClipboardText,refreshModelCatalogs,refreshStartupModelCatalogs,renderUsageBar,retryHcodeCatalog,runClipboardCommand,subscriptionAccountUsage,trackUserWait,usageDisplayText,usagePaneRow,waitForSignalShutdown}from"./chunk-2RXTZK2V.js";
|
|
4
|
+
import{ANTHROPIC_USAGE_PROVIDER_ID,Agent,BUG_REPORT_CUSTOM_ENTRY_TYPE,CAVEMAN_LEVELS,FooterDataProvider,HUMAIN_FUSE_PROVIDER,MissingSessionCwdError,RUNTIME_MODES,SessionImportFileNotFoundError,bugReportArchiveFileName,collectBugReportDiagnostics,collectBugReportMetadata,containStaleExtension,createBugReportConversation,createBugReportExportRedactor,createShellRenderers,createSubagentToolDefinition,editRenderers,ensureTool,exportSessionToJsonl,findRenderers,formatCacheWarmingStatus,formatCacheWarmingUsage,
|
|
5
|
+
formatMissingSessionCwdPrompt,getCavemanDefaultMode,getModelSelectionIntent,grepRenderers,isInstallTelemetryEnabled,lsRenderers,parseSkillBlock,projectBugReportFields,readDefaultMode,readRenderers,renderersMayHighlight,resolveAdhdSessionMode,resolveCavemanSessionMode,resolveSessionMode,setExtensionErrorReporter,writeBugReportArchive,writeMinimalBugReportArchive,writeRenderers}from"./chunk-7XRMMCKG.js";import{formatReadLineRange,formatToolCallWithArgs,getTextOutput,getUsageCostBreakdown,stopToolTimer,
|
|
6
|
+
stripAnsi,truncateToVisualLines}from"./chunk-MLOUZAVZ.js";import{checkForNewPiVersion,getAuthCredential}from"./chunk-SASR4VNV.js";import{ACCOUNT_REPORT_REQUEST_TIMEOUT_MS,ANTHROPIC_PROVIDER_ID,AccountReporter,CODEX_USAGE_PROVIDER_ID,CredentialSynchronizationError,DEFAULT_THINKING_LEVEL,HCODE_PROVIDER,HCODE_SELECTION_CHANGED_MESSAGE,HCODE_SESSION_ONLY_NOTICE,HCODE_UNSUPPORTED_THINKING_MESSAGE,HUMAIN_GATEWAY_PROVIDER,HUMAIN_NODE_BASE_URL_ENV,HUMAIN_NODE_PROVIDER,MAX_NODE_FALLBACK_KEYS,
|
|
7
|
+
MAX_NODE_LABEL_LENGTH,SafeCredentialError,THINKING_LEVEL_OPTIONS,anthropicOrganizationTarget,assertHcodeSelection,assessNodeFallback,availableHcodeSelection,createAnthropicReportCollector,createCodexUsageCollector,defaultModelPerProvider,describeHumainNodeEndpoint,detectSupportedImageMimeType,ensurePngTranscoder,ensurePngTranscoderOnFirstUse,findExactModelReferenceMatch,formatAccountUsageReport,formatHcodeMessageNotice,getBranchSelection,getCodexAvailability,getOAuthAccountRemovalSuccessor,hcodeExcludedSelection,
|
|
8
|
+
hcodeSelectionUnavailable,isSafeNodeText,isVirtualModel,resolveModelScopeFromModels,sameReference,unavailableReport}from"./chunk-N3W4ALAM.js";import{SessionManager,bashTruncationNote,createCompactionSummaryMessage,createCustomMessage,loadPhoton,sessionEntryToContextMessages}from"./chunk-B3FT6L6S.js";import{createTraceRedactor,getTraceEnvSecrets}from"./chunk-D4UCXXDP.js";import{DEFAULT_RADIUS_GATEWAY,normalizeRadiusGatewayUrl}from"./chunk-EWPEY4F4.js";import{loadMcpConfig,
|
|
9
|
+
updateMcpConfigLocked}from"./chunk-J64VNQ6D.js";import{ProjectTrustStore,getProjectTrustOptions,hasTrustRequiringProjectResources}from"./chunk-SZZ5PNP6.js";import{openBrowser}from"./chunk-IWZQ25I3.js";import{AccountSourceReplacementError,mcpNamespace,raceWithAbortSignal,timerSignal,validateMcpServerConfig}from"./chunk-GMPJWLZS.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,truncateTail}from"./chunk-7DIRHF4H.js";import{killTrackedDetachedChildren,killTrackedDetachedChildrenAsync}from"./chunk-PYX6ZCC7.js";
|
|
10
|
+
import{KeybindingsManager,flushStdout}from"./chunk-HWFAAGYK.js";import{DynamicBorder}from"./chunk-XGOJCV6Z.js";import{formatKeyText,keyDisplayText,keyHint,keyText,rawKeyHint,selectNavigationHint}from"./chunk-MXF3KYLZ.js";import{DEFAULT_THEME_NAME,SYSTEM_THEME_NAME,Theme,getAvailableThemes,getAvailableThemesWithPaths,getEditorTheme,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,getThemeByName,getThemeInstance,loadAllHighlightLanguagesOnDemand,onThemeChange,parseAutoThemeSetting,
|
|
11
|
+
setRegisteredThemes,stopThemeWatcher,supportsLanguage,theme}from"./chunk-FLWO3H5J.js";import{DefaultPackageManager,getSourcePackageKey,hcodeDisplayName,isSyntheticPath,isWSL,parseGitUrl,resolveHcodeEnvironment}from"./chunk-OADQOW67.js";import{CACHE_WARMING_MODES,HTTP_IDLE_TIMEOUT_CHOICES,configureHttpDispatcher,formatHttpIdleTimeoutMs}from"./chunk-4SL6URR3.js";import{SETTINGS_DEFAULTS}from"./chunk-RP6MWUAP.js";import{Box,CURSOR_MARKER,CancellableLoader,CombinedAutocompleteProvider,
|
|
12
|
+
Container,Editor,Image,Input,LiveLineArray,Loader,Markdown,MouseRegion,ProcessTerminal,ScrollView,SelectList,SettingsList,Spacer,Text,TruncatedText,TuiAltScreen,TuiMainScreen,VStack,applyBackgroundToLine,foregroundAnsi,fuzzyFilter,getCapabilities,getKeybindings,getNativeClipboard,getSelectPageIndex,hyperlink,isViewportTUI,markLiveRender,markReportsChanges,markStableRender,matchesKey,mixColors,ne,onCapabilitiesChange,parseColor,renderChildLines,renderedMarkdownGeneration,replaceControlCharacters,
|
|
13
|
+
reportRenderChange,reportsChanges,sanitizeTerminalText,setCapabilityOverrides,setKeybindings,setSubtreeReportsChanges,sliceByColumn,startsWithText,stripTerminalSequences,truncateToWidth,visibleWidth,wrapTextWithAnsi}from"./chunk-H35P7ROY.js";import{source_default}from"./chunk-XQRYOCHA.js";import{isRetryableAssistantError}from"./chunk-BIC5BSNX.js";import{clampThinkingLevel,getSupportedThinkingLevels,modelsAreEqual}from"./chunk-KJ3QRSSY.js";import{curatedModelsPolicy,isCuratedModel}from"./chunk-T7F2TEIS.js";
|
|
14
|
+
import{APP_COMMAND,APP_TITLE,CONFIG_DIR_NAME,ENV_OFFLINE,VERSION,detectInstallChange,getAgentDir,getAuthPath,getBundledInteractiveAssetPath,getChangelogPath,getChangelogUrl,getCwdRelativePath,getDebugLogPath,getDocsPath,getShareViewerUrl,resolvePath,shortenHomePath,stripBom,usesDefaultAgentDir}from"./chunk-CKFLQGJN.js";import*as fs3 from"node:fs";import*as path4 from"node:path";import{spawn as spawn3}from"child_process";function detectMiss(prev,message,models){let usage=message.usage,promptTokens=usage.input+usage.cacheRead+usage.cacheWrite;if(!prev||promptTokens<=0||usage.cacheRead+usage.cacheWrite===0&&!prev.reportedCache)return;let missedTokens=Math.min(prev.promptTokens,promptTokens)-usage.cacheRead;if(missedTokens<=1024)return;let paidTokens=usage.input+usage.cacheWrite,paidPerToken=paidTokens>0?(usage.cost.input+usage.cost.cacheWrite)/paidTokens:0,readPerToken=usage.cacheRead>0?usage.cost.cacheRead/usage.
|
|
15
15
|
cacheRead:(models.getModel(message.provider,message.model)?.cost.cacheRead??0)/1e6;return{missedTokens,missedCost:missedTokens*Math.max(0,paidPerToken-readPerToken),idleMs:Math.max(0,message.timestamp-prev.timestamp),modelChanged:`${message.provider}/${message.model}`!==prev.modelKey}}function asPreviousRequest(message,reportedCache){let usage=message.usage,promptTokens=usage.input+usage.cacheRead+usage.cacheWrite;if(!(promptTokens<=0))return{promptTokens,modelKey:`${message.provider}/${message.
|
|
16
16
|
model}`,timestamp:message.timestamp,reportedCache:reportedCache||usage.cacheRead+usage.cacheWrite>0}}function scan(entries,models){let prev,totals={missedTokens:0,missedCost:0,missCount:0},misses=new Map;for(let entry of entries){if(entry.type==="compaction"||entry.type==="branch_summary"){prev=void 0;continue}if(entry.type==="usage"&&entry.kind==="cache_warm"){let promptTokens=entry.usage.input+entry.usage.cacheRead+entry.usage.cacheWrite;promptTokens>0&&(prev={promptTokens,modelKey:`${entry.provider}\
|
|
17
17
|
/${entry.model}`,timestamp:Date.parse(entry.timestamp),reportedCache:!0})}else if(entry.type==="message"&&entry.message.role==="assistant"){let miss=detectMiss(prev,entry.message,models);miss&&(totals.missedTokens+=miss.missedTokens,totals.missedCost+=miss.missedCost,totals.missCount+=1,misses.set(entry.message,miss)),prev=asPreviousRequest(entry.message,prev?.reportedCache??!1)??prev}}return{prev,totals,misses}}function computeCacheWaste(entries,models){return scan(entries,models).totals}function collectCacheMisses(entries,models){
|
|
@@ -112,12 +112,16 @@ readFileSync4(filePath,"utf-8")).replace(/\n$/,"")}}catch(error){return{status:"
|
|
|
112
112
|
env.EDITOR||(process.platform==="win32"?"notepad":"nano"),this.onSubmitCallback=onSubmit,this.onCancelCallback=onCancel;let{description,...editorOptions}=options??{};this.addChild(new DynamicBorder),this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("accent",title),1,0)),description&&(this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("text",description),1,0))),this.addChild(new Spacer(1)),this.editor=new Editor(tui,getEditorTheme(),editorOptions),prefill&&this.editor.setText(
|
|
113
113
|
prefill),this.editor.onSubmit=text=>{this.onSubmitCallback(text)},this.addChild(this.editor),this.addChild(this.externalEditorStatus),this.addChild(new Spacer(1));let hint=keyHint("tui.input.submit","submit")+" "+keyHint("tui.input.newLine","newline")+" "+keyHint("tui.select.cancel","cancel")+` ${keyHint("app.editor.external","external editor")}`;this.addChild(new Text(hint,1,0)),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder)}handleInput(keyData){if(getKeybindings().matches(keyData,
|
|
114
114
|
"tui.select.cancel")){this.onCancelCallback();return}if(this.keybindings.matches(keyData,"app.editor.external")){this.handleOpenExternalEditor();return}this.editor.handleInput(keyData)}async handleOpenExternalEditor(){let content=this.editor.getText();this.tui.stop();try{let result=await editInExternalEditor({command:this.externalEditorCommand,content});this.externalEditorStatus.setText(result.status==="failed"?theme.fg("warning",result.message):""),result.status==="complete"&&this.editor.setText(
|
|
115
|
-
result.content)}finally{this.tui.start(),this.tui.requestRender(!0)}}};var DISCLAIMER="Create a local bug report with account and installation details and diagnostics. Secrets are excluded. You'll choose whether to attach the conversation. Nothing is automatically emailed or uploaded.",TRANSCRIPT_NOTE="Conversation content can include prompts, code, tool calls, file contents, and command output. Secrets are excluded. Review the archive before sending it.";async function reportBug(context,initialHint){let redactor=
|
|
116
|
-
sessionId=manager.getSessionId(),runtime=context.session.modelRuntime,model=context.session.model,current=()=>context.session.sessionManager===manager&&manager.getSessionId()===sessionId&&context.session.modelRuntime===runtime&&context.session.model===model,options;try{let extensions=context.session.resourceLoader.getExtensions();
|
|
117
|
-
session.settingsManager.getProjectSettings(),crashes:readCrashLog()},"available"),options=await promptForOptions(context,redactor,initialHint)}catch{
|
|
118
|
-
name??"the current model"}...`);try{let summaryInput={messages:options.conversation.messages,hint:options.hint},reviewed=redactor.redactJson(summaryInput,"summary").value;if(JSON.stringify(reviewed)!==JSON.stringify(summaryInput))throw new Error("Summary input redaction changed after review.");summary=redactor.redactText(await context.session.summarizeForBugReport({hint:options.hint,signal:loader.signal,conversation:options.conversation})).text}catch{restoreEditor(context,loader),loader.signal.
|
|
119
|
-
context.showStatus("Bug report cancelled"):context
|
|
120
|
-
|
|
115
|
+
result.content)}finally{this.tui.start(),this.tui.requestRender(!0)}}};var DISCLAIMER="Create a local bug report with account and installation details and diagnostics. Secrets are excluded. You'll choose whether to attach the conversation. Nothing is automatically emailed or uploaded.",TRANSCRIPT_NOTE="Conversation content can include prompts, code, tool calls, file contents, and command output. Secrets are excluded. Review the archive before sending it.";async function reportBug(context,initialHint){let redactor=createBugReportExportRedactor(),manager=context.session.
|
|
116
|
+
sessionManager,sessionId=manager.getSessionId(),runtime=context.session.modelRuntime,model=context.session.model,current=()=>context.session.sessionManager===manager&&manager.getSessionId()===sessionId&&context.session.modelRuntime===runtime&&context.session.model===model,options;try{let extensions=context.session.resourceLoader.getExtensions();projectBugReportFields({model,extensions:extensions.extensions,extensionErrors:extensions.errors,global:context.session.settingsManager.getGlobalSettings(),
|
|
117
|
+
project:context.session.settingsManager.getProjectSettings(),crashes:readCrashLog()},redactor,"available"),options=await promptForOptions(context,redactor,initialHint)}catch{redactor.disable(),await exportMinimalReport(context,current,redactor);return}if(!current()){context.showStatus("Bug report cancelled: session changed");return}if(!options){context.showStatus("Bug report cancelled");return}let summary;if(options.includeSummary){let loader=showLoader(context,`Writing summary with ${context.session.
|
|
118
|
+
model?.name??"the current model"}...`);try{let summaryInput={messages:options.conversation.messages,hint:options.hint},reviewed=redactor.redactJson(summaryInput,"summary").value;if(JSON.stringify(reviewed)!==JSON.stringify(summaryInput))throw new Error("Summary input redaction changed after review.");summary=redactor.redactText(await context.session.summarizeForBugReport({hint:options.hint,signal:loader.signal,conversation:options.conversation})).text}catch{restoreEditor(context,loader),loader.signal.
|
|
119
|
+
aborted?context.showStatus("Bug report cancelled"):await exportConfirmedMinimalReport(context,current,redactor);return}if(restoreEditor(context,loader),loader.signal.aborted){context.showStatus("Bug report cancelled");return}}let bundle;try{if(!current())throw new Error("Session changed");if(bundle=await buildBundle(context.session,options,summary,redactor),options.conversation.omittedFields&&(options.includeSession||summary!==void 0)&&bundle.metadata.omissions.push("Over-budget conversation fie\
|
|
120
|
+
lds were omitted after secret discovery."),!current())throw new Error("Session changed")}catch{redactor.disable(),await exportMinimalReport(context,current,redactor);return}await exportZip(context,bundle,redactor,current)}async function exportMinimalReport(context,current,redactor){if(!current()){context.showStatus("Bug report cancelled: session changed");return}let confirmation=await choose(context,"Export a minimal bug report?",["Export as Zip","Cancel"],"Some fields were omitted. Safely redac\
|
|
121
|
+
ted crash details are included when secret discovery completed; otherwise only CLI/platform details and crash dates/kinds are included. Configuration, descriptions, conversation and summary are excluded. Nothing is automatically emailed or uploaded.");if(!current()||confirmation!=="Export as Zip"){context.showStatus("Bug report cancelled");return}await exportConfirmedMinimalReport(context,current,redactor)}async function exportConfirmedMinimalReport(context,current,redactor){if(!current()){context.
|
|
122
|
+
showStatus("Bug report cancelled: session changed");return}try{let{id,archivePath}=await writeMinimalBugReportArchive(readCrashLog(),process.cwd(),redactor);context.showStatus(`Bug report exported to: ${archivePath}
|
|
123
|
+
Report ID: ${id}
|
|
124
|
+
Some fields were omitted. Review the archive before manually emailing it to akarim@humain.com. Nothing was automatically emailed or uploaded.`)}catch{context.showError("Failed to write minimal bug report. No report was exported.")}}async function promptForOptions(context,redactor,initialHint){let hint=await input(context,"Report a bug",`${DISCLAIMER}
|
|
121
125
|
|
|
122
126
|
What went wrong? (optional)`,initialHint===void 0?void 0:redactor.redactText(initialHint).text);if(hint===null)return;redactor.redactText(hint.trim());let conversation=createBugReportConversation(context.session.sessionManager,redactor),description=redactor.redactText(hint.trim()).text,transcript=await choose(context,`Attach the current conversation (${conversation.bytes} bytes)?`,["Attach conversation","Don't attach"],TRANSCRIPT_NOTE);if(!transcript)return;let includeSession=transcript==="Attac\
|
|
123
127
|
h conversation",includeSummary=!1;{let model=context.session.model,summary=await choose(context,"Generate a summary with the selected model?",["Yes, generate a summary","No"],`Generate a summary with the selected model? This sends the secret-redacted conversation to your inference provider and may use your allowance or provider tokens. Selected provider: ${model?.provider??"none"}.`);if(!summary)return;includeSummary=summary!=="No"}if(await choose(context,"Bug report",["Export as Zip","Cancel"],
|
|
@@ -127,13 +131,13 @@ Summary: ${includeSummary?`written by ${context.session.model?.name??"the curren
|
|
|
127
131
|
|
|
128
132
|
The zip archive will be written to the current directory. Review the archive before manually emailing it to akarim@humain.com.`)==="Export as Zip")return{hint:description||void 0,includeSession,includeSummary,conversation}}async function buildBundle(session,options,summary,redactor){let support=await session.modelRuntime.getHcodeSupportSnapshot(AbortSignal.timeout(1e3)),extensions=session.resourceLoader.getExtensions();return{metadata:collectBugReportMetadata({redactor,support,hint:options.hint,
|
|
129
133
|
sessionId:session.sessionId,cwd:session.sessionManager.getCwd(),includeSession:options.includeSession,includeSummary:summary!==void 0,messageCount:options.includeSession?options.conversation.messages.length:0,model:session.model,modelRuntime:session.modelRuntime,thinkingLevel:session.thinkingLevel,extensions:extensions.extensions,extensionErrors:extensions.errors,globalSettings:session.settingsManager.getGlobalSettings(),projectSettings:session.settingsManager.getProjectSettings()}),diagnostics:collectBugReportDiagnostics(
|
|
130
|
-
options.includeSession?{kind:"conversation",session:session.sessionManager,crashes:readCrashLog()}:{kind:"standalone",crashes:readCrashLog()},redactor),summary,sessionJsonl:options.includeSession?options.conversation.sessionJsonl:void 0}}async function exportZip(context,bundle,redactor,current){let archivePath=path2.join(process.cwd(),bugReportArchiveFileName(bundle.metadata.id));try{await writeBugReportArchive(bundle,archivePath,redactor)}catch{
|
|
131
|
-
|
|
134
|
+
options.includeSession?{kind:"conversation",session:session.sessionManager,crashes:readCrashLog()}:{kind:"standalone",crashes:readCrashLog()},redactor),summary,sessionJsonl:options.includeSession?options.conversation.sessionJsonl:void 0}}async function exportZip(context,bundle,redactor,current){let archivePath=path2.join(process.cwd(),bugReportArchiveFileName(bundle.metadata.id)),omittedFields;try{({omittedFields}=await writeBugReportArchive(bundle,archivePath,redactor))}catch{await exportConfirmedMinimalReport(
|
|
135
|
+
context,current,redactor);return}current()&&recordInSession(context.session,bundle,archivePath,omittedFields),context.showStatus(`Bug report exported to: ${archivePath}
|
|
132
136
|
Report ID: ${bundle.metadata.id}
|
|
133
|
-
Review the archive before manually emailing it to akarim@humain.com. Nothing was automatically emailed or uploaded.`)}function recordInSession(session,bundle,archivePath){session.sessionManager.appendCustomEntry(BUG_REPORT_CUSTOM_ENTRY_TYPE,{id:bundle.metadata.id,createdAt:bundle.metadata.createdAt,hint:bundle.metadata.hint,sessionIncluded:bundle.metadata.session.included,summaryIncluded:bundle.metadata.session.summaryIncluded,delivery:"zip",path:archivePath})
|
|
134
|
-
clearCrashLog()}function input(context,title,description,initialValue){return new Promise(resolve2=>{let component,finish=value=>{restoreEditor(context,component),resolve2(value)};component=new ExtensionEditorComponent(context.ui,context.keybindings,title,initialValue,value=>finish(value),()=>finish(null),{description},context.session.settingsManager.getExternalEditorCommand()),showOverlay(
|
|
135
|
-
finish=value=>{restoreEditor(context,component),resolve2(value)};component=new ExtensionSelectorComponent(title,options,finish,()=>finish(),{tui:context.ui,description}),showOverlay(context,component)})}function showLoader(context,message){let loader=new BorderedLoader(context.ui,theme,message);return showOverlay(context,loader),loader}function showOverlay(context,component){context.
|
|
136
|
-
function restoreEditor(context,component){component.dispose?.(),context.editorContainer.clear(),context.editorContainer.addChild(context.editor),context.ui.setFocus(context.editor),context.ui.requestRender()}function createChatViewport(options){let transcript=new ScrollView(options.document,{follow:"end",primary:!0,overscroll:"chain",scrollbar:options.scrollbar??"auto",...options.scrollbarTrackStyle===void 0?{}:{scrollbarTrackStyle:options.scrollbarTrackStyle},...options.scrollbarThumbStyle===void 0?{}:{scrollbarThumbStyle:options.scrollbarThumbStyle}}),dock=new VStack([{component:options.pendingMessages,shrink:1,minSize:0},...options.widgetsAbove===void 0?[]:[{component:options.widgetsAbove,shrink:1,
|
|
137
|
+
Review the archive before manually emailing it to akarim@humain.com. Nothing was automatically emailed or uploaded.`)}function recordInSession(session,bundle,archivePath,omittedFields){session.sessionManager.appendCustomEntry(BUG_REPORT_CUSTOM_ENTRY_TYPE,{id:bundle.metadata.id,createdAt:bundle.metadata.createdAt,hint:bundle.metadata.hint,sessionIncluded:bundle.metadata.session.included,summaryIncluded:bundle.metadata.session.summaryIncluded,delivery:"zip",path:archivePath}),!omittedFields&&bundle.
|
|
138
|
+
diagnostics.crashes.length>0&&bundle.diagnostics.omissions.length===0&&bundle.metadata.omissions.length===0&&clearCrashLog()}function input(context,title,description,initialValue){return new Promise(resolve2=>{let component,finish=value=>{restoreEditor(context,component),resolve2(value)};component=new ExtensionEditorComponent(context.ui,context.keybindings,title,initialValue,value=>finish(value),()=>finish(null),{description},context.session.settingsManager.getExternalEditorCommand()),showOverlay(
|
|
139
|
+
context,component)})}function choose(context,title,options,description){return new Promise(resolve2=>{let component,finish=value=>{restoreEditor(context,component),resolve2(value)};component=new ExtensionSelectorComponent(title,options,finish,()=>finish(),{tui:context.ui,description}),showOverlay(context,component)})}function showLoader(context,message){let loader=new BorderedLoader(context.ui,theme,message);return showOverlay(context,loader),loader}function showOverlay(context,component){context.
|
|
140
|
+
editorContainer.clear(),context.editorContainer.addChild(component),context.ui.setFocus(component),context.ui.requestRender()}function restoreEditor(context,component){component.dispose?.(),context.editorContainer.clear(),context.editorContainer.addChild(context.editor),context.ui.setFocus(context.editor),context.ui.requestRender()}function createChatViewport(options){let transcript=new ScrollView(options.document,{follow:"end",primary:!0,overscroll:"chain",scrollbar:options.scrollbar??"auto",...options.scrollbarTrackStyle===void 0?{}:{scrollbarTrackStyle:options.scrollbarTrackStyle},...options.scrollbarThumbStyle===void 0?{}:{scrollbarThumbStyle:options.scrollbarThumbStyle}}),dock=new VStack([{component:options.pendingMessages,shrink:1,minSize:0},...options.widgetsAbove===void 0?[]:[{component:options.widgetsAbove,shrink:1,
|
|
137
141
|
minSize:0}],{component:options.status,shrink:0,minSize:0},{component:options.editor,shrink:1,minSize:3},...options.widgetsBelow===void 0?[]:[{component:options.widgetsBelow,shrink:1,minSize:0}],{component:options.footer,shrink:1,minSize:0}]);return{transcript,root:new VStack([{component:transcript,basis:0,grow:1,shrink:1,minSize:1},{component:dock,basis:"auto",grow:0,shrink:1,minSize:1}])}}var statusTone={"Sign-in expired":"warning",Blocked:"error",Active:"success",Ready:"accent",Saved:"muted"},AccountPickerComponent=class{selected=0;detailTop=0;detailPage=1;maxDetailTop=0;closed=!1;title;getRows;getHeight;onSelect;onCancel;constructor(title,getRows,getHeight,onSelect,onCancel){this.title=title,this.getRows=getRows,this.getHeight=getHeight,this.onSelect=onSelect,this.onCancel=onCancel}invalidate(){}handleInput(data){if(this.closed)return;let kb=getKeybindings(),rows=this.getRows();
|
|
138
142
|
if(kb.matches(data,"tui.select.cancel")||kb.matches(data,"app.clear")){this.closed=!0,this.onCancel();return}if(kb.matches(data,"tui.select.up")||kb.matches(data,"app.select.upAlternate"))this.selected=(this.selected+rows.length-1)%rows.length,this.detailTop=0;else if(kb.matches(data,"tui.select.down")||kb.matches(data,"app.select.downAlternate"))this.selected=(this.selected+1)%rows.length,this.detailTop=0;else if(kb.matches(data,"tui.select.pageUp"))this.detailTop=Math.max(0,this.detailTop-this.
|
|
139
143
|
detailPage);else if(kb.matches(data,"tui.select.pageDown"))this.detailTop=Math.min(this.maxDetailTop,this.detailTop+this.detailPage);else{let action=kb.matches(data,"tui.select.confirm")?"choose":rows[this.selected].kind!=="account"?void 0:kb.matches(data,"app.accounts.reconnect")?"reconnect":kb.matches(data,"app.accounts.remove")?"remove":kb.matches(data,"app.accounts.more")?"more":void 0;if(!action)return;this.closed=!0,this.onSelect(this.selected,action)}}render(width){if(width<1||this.closed)
|
|
@@ -757,44 +761,43 @@ ${warningLines()}`,0,0)),this.loadedResourcesContainer.addChild(new Spacer(1))}l
|
|
|
757
761
|
${warningLines()}`,0,0)),this.loadedResourcesContainer.addChild(new Spacer(1))}}}async bindCurrentSessionExtensions(){let uiContext=this.createExtensionUIContext();await this.session.bindExtensions({uiContext,mode:"tui",abortHandler:()=>{this.restoreQueuedMessagesToEditor({abort:!0})},commandContextActions:{waitForIdle:()=>this.session.waitForIdle(),newSession:async options=>{this.clearStatusIndicator();try{return await this.runtimeHost.newSession(options)}catch(error){return this.handleFatalRuntimeError(
|
|
758
762
|
"Failed to create session",error)}},fork:async(entryId,options)=>{try{let result=await this.runtimeHost.fork(entryId,options);return result.cancelled||(this.editor.setText(result.selectedText??""),this.showStatus("Forked to new session")),{cancelled:result.cancelled}}catch(error){return this.handleFatalRuntimeError("Failed to fork session",error)}},navigateTree:async(targetId,options)=>{let result=await this.session.navigateTree(targetId,{summarize:options?.summarize,customInstructions:options?.
|
|
759
763
|
customInstructions,replaceInstructions:options?.replaceInstructions,label:options?.label});return result.cancelled?{cancelled:!0}:(this.chatContainer.clear(),this.renderInitialMessages(),result.editorText&&!this.editor.getText().trim()&&this.editor.setText(result.editorText),this.showStatus("Navigated to selected point"),this.flushCompactionQueue({willRetry:!1}),{cancelled:!1})},switchSession:async(sessionPath,options)=>this.handleResumeSession(sessionPath,options),reload:async()=>{await this.handleReloadCommand()}},
|
|
760
|
-
shutdownHandler:()=>{this.shutdownRequested=!0,this.session.isIdle&&this.shutdown()},onError:error=>
|
|
761
|
-
this.
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
if(
|
|
775
|
-
|
|
776
|
-
(this.
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
this.
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
this.
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
this.
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
"abort",onAbort,{once:!0});let selector=new ExtensionSelectorComponent(title,options,option=>finish(option),()=>finish(void 0),{tui:this.ui,timeout:opts?.timeout,onToggleToolsExpanded:()=>this.toggleToolOutputExpansion()});this.pushExtensionDialog(selector,dialogBlockedStatus(opts?.blockedKind??"question",title),onAbort)})}async showExtensionConfirm(title,message,opts){return await this.showExtensionSelector(`${title}
|
|
764
|
+
shutdownHandler:()=>{this.shutdownRequested=!0,this.session.isIdle&&this.shutdown()},onError:error=>this.handleExtensionError(error)}),this.bindFlowAccountsHostToSession(),setRegisteredThemes(this.session.resourceLoader.getThemes().themes),this.setupAutocompleteProvider();let extensionRunner=this.session.extensionRunner;this.setupExtensionShortcuts(extensionRunner),this.showLoadedResources({force:!1,hideListing:!this.getStartupExpansionState(),showDiagnosticsWhenQuiet:!0}),this.showStartupNoticesIfNeeded()}applyFullscreenScrollbarSetting(){
|
|
765
|
+
this.transcriptScrollView?.setScrollbar(this.settingsManager.getFullscreenScrollbar())}ensurePngTranscoder(){ensurePngTranscoderOnFirstUse(()=>{this.ui.invalidate(),this.ui.requestRender()})}applyRuntimeSettings(){setCapabilityOverrides(this.settingsManager.getTerminalCapabilityOverrides()),this.ensurePngTranscoder(),configureHttpDispatcher(this.settingsManager.getHttpIdleTimeoutMs()),this.applyFullscreenScrollbarSetting(),this.renderer instanceof TuiAltScreen&&(this.renderer.setCopyOnSelect(this.
|
|
766
|
+
settingsManager.getFullscreenCopyOnSelect()),this.renderer.setWheelScrollLines(this.settingsManager.getFullscreenWheelScrollLines())),this.session.setAutoEffortInteractive(!0),this.footer.setSession(this.session),this.footerDataProvider.setCwd(this.sessionManager.getCwd()),this.hideThinkingBlock=this.settingsManager.getHideThinkingBlock(),this.outputPad=this.settingsManager.getOutputPad(),this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());let clearOnShrink=this.settingsManager.
|
|
767
|
+
getClearOnShrink();this.ui.setClearOnShrink(clearOnShrink),!clearOnShrink&&!this.activeStatusIndicator&&this.statusContainer.clear();let editorPaddingX=this.settingsManager.getEditorPaddingX(),autocompleteMaxVisible=this.settingsManager.getAutocompleteMaxVisible();this.defaultEditor.setPaddingX(editorPaddingX),this.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible),this.editor!==this.defaultEditor&&(this.editor.setPaddingX?.(editorPaddingX),this.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible))}showRuntimeDiagnostics(diagnostics){
|
|
768
|
+
for(let diagnostic of diagnostics)diagnostic.type==="error"?this.showError(diagnostic.message):diagnostic.type==="warning"?this.showWarning(diagnostic.message):this.showStatus(diagnostic.message)}async rebindCurrentSession(options={}){let session=this.session;this.unsubscribe?.(),this.unsubscribe=void 0,this.programStatus.reset(),this.applyRuntimeSettings(),options.renderBeforeBind&&(this.renderCurrentSessionState(),this.subscribeToAgent()),await this.bindCurrentSessionExtensions(),this.session===
|
|
769
|
+
session&&(options.renderBeforeBind||this.subscribeToAgent(),await this.updateAvailableProviderCount(),this.updateEditorBorderColor(),this.updateTerminalTitle())}async handleFatalRuntimeError(prefix,error){let message=error instanceof Error?error.message:String(error);this.showError(`${prefix}: ${message}`);let extensionHint=this.getCrashExtensionHint(error);if(extensionHint&&this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",extensionHint),this.outputPad,0)),this.recordCrash("fata\
|
|
770
|
+
l_error",error)){let instructions=this.crashReportInstructions();this.chatContainer.addChild(new ThemedText(()=>theme.fg("muted",instructions),this.outputPad,0))}stopThemeWatcher(),this.stop("transcript");try{await this.runtimeHost.dispose()}finally{await flushStdout(),process.exit(1)}}getCrashExtensionHint(error){try{return formatCrashExtensionHint(findExtensionStackMatches(error instanceof Error?error.stack:void 0,this.session.resourceLoader.getExtensions().extensions))}catch{return}}recordCrash(kind,error){
|
|
771
|
+
try{return recordCrash({kind,error,sessionFile:this.session.sessionFile,cwd:this.session.sessionManager.getCwd()})!==void 0}catch{return!1}}crashReportInstructions(){return`To export a bug report zip: ${this.session.sessionFile?`run \`${APP_COMMAND} -r\` to resume the session, then`:`start ${APP_COMMAND} and`} run /bug. The crash details are attached automatically.`}suggestBugReport(){this.bugReportHintShown||(this.bugReportHintShown=!0,this.chatContainer.addChild(new ThemedText(()=>theme.fg("mu\
|
|
772
|
+
ted",`If this looks like a ${APP_TITLE} bug, /bug exports a report zip for the HUMAIN Code CLI maintainers.`),this.outputPad,0)),this.ui.requestRender())}maybeSuggestBugReport(message){message.stopReason!=="error"||isRetryableAssistantError(message)||/\b(?:abort(?:ed)?|cancel(?:l?ed)?)\b/i.test(message.errorMessage??"")||this.maybeShowInstallChangeWarning()||this.suggestBugReport()}maybeShowInstallChangeWarning(){if(this.installChangeWarningShown)return!0;let change=detectInstallChange();if(!change)
|
|
773
|
+
return!1;this.installChangeWarningShown=!0;let cause=change.kind==="updated"?`${APP_TITLE} was updated to ${change.version} while this session was running (${VERSION})`:`The ${APP_TITLE} installation this session runs from was removed or replaced`,resumeCommand=formatResumeCommand(this.sessionManager,this.session.modelRuntime.hcode.environment.id),restart=resumeCommand?`Restart with \`${resumeCommand}\` to continue this session.`:`Restart ${APP_COMMAND}.`;return this.showWarning(`${cause}. Featu\
|
|
774
|
+
res that load code on demand can fail until restart. ${restart}`),!0}clearPendingTools(){for(let component of this.pendingTools.values())component.dispose();this.pendingTools.clear()}renderCurrentSessionState(){this.loadedResourcesContainer.clear(),this.chatContainer.clear(),this.pendingMessagesContainer.clear(),this.pendingBashComponents=[],this.compactionQueuedMessages=[],this.streamingComponent=void 0,this.streamingMessage=void 0,this.clearPendingTools(),this.renderInitialMessages()}getRegisteredToolDefinition(toolName){
|
|
775
|
+
return this.session.extensionRunner.resolveToolRenderers(toolName,()=>withBuiltInRenderers(toolName,this.session.getToolDefinition(toolName)))}getMarkdownTransformers(){return[this.mermaidMarkdownTransformer,...this.session.extensionRunner.getMarkdownTransformers()]}setupExtensionShortcuts(extensionRunner){let shortcuts=extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());shortcuts.size!==0&&(this.defaultEditor.onExtensionShortcut=data=>{for(let[shortcutStr,shortcut]of shortcuts)if(matchesKey(
|
|
776
|
+
data,shortcutStr))return(async()=>{try{await shortcut.handler(extensionRunner.createContext())}catch(error){this.handleExtensionError({extensionPath:shortcut.extensionPath,event:`shortcut:${shortcutStr}`,error:error instanceof Error?error.message:String(error),stack:error instanceof Error?error.stack:void 0})}})(),!0;return!1})}setExtensionStatus(key,text){this.footerDataProvider.setExtensionStatus(key,text),this.ui.requestRender()}setEditorWorkingStatusIndicator(indicator){return this.defaultEditor.
|
|
777
|
+
setWorkingStatusIndicator(void 0),isEmbeddedStatus(this.editor)?(this.editor.setWorkingStatusIndicator(indicator),!0):!1}showStatusIndicator(indicator){if(this.activeStatusIndicator?.dispose(),this.activeStatusIndicator=indicator,this.statusStartedAt=performance.now(),this.activeWorkingIndicatorEmbedded=!1,this.statusContainer.clear(),this.setEditorWorkingStatusIndicator(void 0),this.setEditorWorkingStatusIndicator(indicator)){this.activeWorkingIndicatorEmbedded=!0;return}this.statusContainer.addChild(
|
|
778
|
+
indicator)}clearStatusIndicator(kind){if(kind&&this.activeStatusIndicator?.kind!==kind)return;this.activeStatusIndicator&&(this.statusLastDuration=Math.max(0,Math.floor((performance.now()-this.statusStartedAt)/1e3)));let clearedIndicator=this.activeStatusIndicator,clearedIndicatorWasEmbedded=this.activeWorkingIndicatorEmbedded;clearedIndicator?.dispose(),this.activeStatusIndicator=void 0,this.activeWorkingIndicatorEmbedded=!1,this.statusContainer.clear(),this.setEditorWorkingStatusIndicator(void 0),
|
|
779
|
+
clearedIndicator&&!clearedIndicatorWasEmbedded&&this.options.tuiMode==="regular"&&this.ui.getClearOnShrink()&&this.statusContainer.addChild(this.idleStatus)}showWorkingStatusIndicator(){if(this.statusError=!1,this.settingsPreviewOpen)return;let colorFn=isEmbeddedStatus(this.editor)?text=>(this.editor.borderColor??theme.getThinkingBorderColor(this.session.thinkingLevel||"off"))(text):void 0;this.showStatusIndicator(new WorkingStatusIndicator(this.ui,this.workingMessage??this.defaultWorkingMessage,
|
|
780
|
+
this.workingIndicatorOptions,colorFn,this.resolveWorkingIndicator(this.settingsManager.getWorkingIndicator()),this.session.model?.reasoning&&this.session.getAvailableThinkingLevels().includes(this.session.thinkingLevel)?this.session.thinkingLevel:"off",this.settingsManager.getReducedMotion()))}getStatusIndicatorConfiguration(){return{indicator:this.workingIndicatorOptions,style:this.resolveWorkingIndicator(this.settingsManager.getWorkingIndicator()),level:this.session.model?.reasoning&&this.session.
|
|
781
|
+
getAvailableThinkingLevels().includes(this.session.thinkingLevel)?this.session.thinkingLevel:"off",reducedMotion:this.settingsManager.getReducedMotion()}}setWorkingVisible(visible){if(this.workingVisible=visible,!visible){this.clearStatusIndicator("working"),this.ui.requestRender();return}this.session.isStreaming&&this.activeStatusIndicator?.kind!=="working"&&this.showWorkingStatusIndicator(),this.ui.requestRender()}setWorkingIndicator(options){this.workingIndicatorOptions=options,this.activeStatusIndicator?.
|
|
782
|
+
kind==="working"&&this.showWorkingStatusIndicator(),this.ui.requestRender()}setHiddenThinkingLabel(label){this.hiddenThinkingLabel=label??this.defaultHiddenThinkingLabel;for(let child of this.chatContainer.children)child instanceof AssistantMessageComponent&&child.setHiddenThinkingLabel(this.hiddenThinkingLabel);this.streamingComponent&&this.streamingComponent.setHiddenThinkingLabel(this.hiddenThinkingLabel),this.ui.requestRender()}setExtensionWidget(key,content,options){let placement=options?.placement??
|
|
783
|
+
"aboveEditor",removeExisting=map=>{let existing=map.get(key);existing?.dispose&&existing.dispose(),map.delete(key)};if(removeExisting(this.extensionWidgetsAbove),removeExisting(this.extensionWidgetsBelow),content===void 0){this.renderWidgets();return}let component;if(Array.isArray(content)){let container=new Container;for(let line of content.slice(0,_InteractiveMode.MAX_WIDGET_LINES))container.addChild(new Text(line,1,0));content.length>_InteractiveMode.MAX_WIDGET_LINES&&container.addChild(new ThemedText(
|
|
784
|
+
()=>theme.fg("muted","... (widget truncated)"),1,0)),component=container}else component=content(this.ui,theme);(placement==="belowEditor"?this.extensionWidgetsBelow:this.extensionWidgetsAbove).set(key,component),this.renderWidgets()}clearExtensionWidgets(){for(let widget of this.extensionWidgetsAbove.values())widget.dispose?.();for(let widget of this.extensionWidgetsBelow.values())widget.dispose?.();this.extensionWidgetsAbove.clear(),this.extensionWidgetsBelow.clear(),this.renderWidgets()}resetExtensionUI(){
|
|
785
|
+
this.disposeActiveSelector(),this.releaseFlowAccountsHost(),this.extensionDialogs.length>0&&this.closeExtensionDialogs();for(let removeOverlay of[...this.extensionOverlays.values()].reverse())removeOverlay();this.clearExtensionTerminalInputListeners(),this.setExtensionFooter(void 0),this.setExtensionHeader(void 0),this.clearExtensionWidgets(),this.footerDataProvider.clearExtensionStatuses(),this.hcodeCatalogStatus&&this.footerDataProvider.setExtensionStatus(HCODE_STATUS_KEY,this.hcodeCatalogStatus),
|
|
786
|
+
this.footer.invalidate(),this.autocompleteProviderWrappers=[],this.extensionEditorAccent=void 0,this.editorChangeListeners.clear(),this.setCustomEditorComponent(void 0),this.setupAutocompleteProvider(),this.defaultEditor.onExtensionShortcut=void 0,this.updateTerminalTitle(),this.workingMessage=void 0,this.workingVisible=!0,this.setWorkingIndicator(),this.activeStatusIndicator?.kind==="working"&&this.activeStatusIndicator.setMessage(`${this.defaultWorkingMessage} (${keyText("app.interrupt")} to i\
|
|
787
|
+
nterrupt)`),this.setHiddenThinkingLabel()}static MAX_WIDGET_LINES=10;renderWidgets(){!this.widgetContainerAbove||!this.widgetContainerBelow||(this.renderWidgetContainer(this.widgetContainerAbove,this.extensionWidgetsAbove,!0,!0),this.renderWidgetContainer(this.widgetContainerBelow,this.extensionWidgetsBelow,!1,!1),this.ui.requestRender())}renderWidgetContainer(container,widgets,spacerWhenEmpty,leadingSpacer){if(container.clear(),widgets.size===0){spacerWhenEmpty&&container.addChild(new Spacer(1));
|
|
788
|
+
return}leadingSpacer&&container.addChild(new Spacer(1));for(let component of widgets.values())container.addChild(component)}setExtensionFooter(factory){this.customFooter?.dispose&&this.customFooter.dispose(),this.footerContainer.clear(),factory?(this.customFooter=factory(this.ui,theme,this.footerDataProvider),this.footerContainer.addChild(this.customFooter)):(this.customFooter=void 0,this.footerContainer.addChild(this.footer)),this.ui.requestRender()}setExtensionHeader(factory){if(!this.builtInHeader)
|
|
789
|
+
return;this.customHeader?.dispose&&this.customHeader.dispose();let currentHeader=this.customHeader||this.builtInHeader,index=this.headerContainer.children.indexOf(currentHeader);factory?(this.customHeader=factory(this.ui,theme),isExpandable(this.customHeader)&&this.customHeader.setExpanded(this.toolOutputExpanded),index!==-1?this.headerContainer.children[index]=this.customHeader:this.headerContainer.children.unshift(this.customHeader)):(this.customHeader=void 0,isExpandable(this.builtInHeader)&&
|
|
790
|
+
this.builtInHeader.setExpanded(this.toolOutputExpanded),index!==-1&&(this.headerContainer.children[index]=this.builtInHeader)),this.ui.requestRender()}addExtensionTerminalInputListener(handler){let subscription={handler,unsubscribe:this.ui.addInputListener(handler)};return this.extensionTerminalInputSubscriptions.add(subscription),()=>{subscription.unsubscribe(),this.extensionTerminalInputSubscriptions.delete(subscription)}}rebindExtensionTerminalInputListeners(){for(let subscription of this.extensionTerminalInputSubscriptions)
|
|
791
|
+
subscription.unsubscribe(),subscription.unsubscribe=this.ui.addInputListener(subscription.handler)}clearExtensionTerminalInputListeners(){for(let subscription of this.extensionTerminalInputSubscriptions)subscription.unsubscribe();this.extensionTerminalInputSubscriptions.clear()}createProjectTrustContext(cwd){let ui=this.createExtensionUIContext();return{cwd,mode:"tui",hasUI:!0,ui:{select:ui.select,confirm:ui.confirm,input:ui.input,notify:ui.notify}}}createExtensionUIContext(){return{select:(title,options,opts)=>trackUserWait(
|
|
792
|
+
title,this.showExtensionSelector(title,options,opts)),confirm:(title,message,opts)=>trackUserWait(title,this.showExtensionConfirm(title,message,opts)),input:(title,placeholder,opts)=>trackUserWait(title,this.showExtensionInput(title,placeholder,opts)),notify:(message,type)=>this.showExtensionNotify(message,type),onTerminalInput:handler=>this.addExtensionTerminalInputListener(handler),setStatus:(key,text)=>this.setExtensionStatus(key,text),setWorkingMessage:message=>{this.workingMessage=message,this.
|
|
793
|
+
activeStatusIndicator?.kind==="working"&&this.activeStatusIndicator.setMessage(message??this.defaultWorkingMessage)},setWorkingVisible:visible=>this.setWorkingVisible(visible),setWorkingIndicator:options=>this.setWorkingIndicator(options),setHiddenThinkingLabel:label=>this.setHiddenThinkingLabel(label),setWidget:(key,content,options)=>this.setExtensionWidget(key,content,options),setFooter:factory=>this.setExtensionFooter(factory),setHeader:factory=>this.setExtensionHeader(factory),setTitle:title=>this.
|
|
794
|
+
ui.terminal.setTitle(title),custom:(factory,options)=>this.showExtensionCustom(factory,options),pasteToEditor:text=>{this.editor.handleInput(`\x1B[200~${text}\x1B[201~`),this.ui.requestRender()},setEditorText:text=>{this.editor.setText(text),this.ui.requestRender()},getEditorText:()=>this.editor.getExpandedText?.()??this.editor.getText(),editor:(title,prefill)=>trackUserWait(title,this.showExtensionEditor(title,prefill)),addAutocompleteProvider:factory=>{this.autocompleteProviderWrappers.push(factory),
|
|
795
|
+
this.setupAutocompleteProvider()},setEditorComponent:factory=>this.setCustomEditorComponent(factory),getEditorComponent:()=>this.editorComponentFactory,setEditorAccent:accent=>{this.extensionEditorAccent=accent,this.updateEditorBorderColor()},onEditorChange:handler=>(this.editorChangeListeners.add(handler),()=>this.editorChangeListeners.delete(handler)),get theme(){return theme},getAllThemes:()=>getAvailableThemesWithPaths(),getTheme:name=>getThemeByName(name),setTheme:themeOrName=>{if(themeOrName instanceof
|
|
796
|
+
Theme)return this.themeController.setThemeInstance(themeOrName);let result=this.themeController.setThemeName(themeOrName);return result.success&&this.settingsManager.getTheme()!==themeOrName&&this.settingsManager.setTheme(themeOrName),result},getToolsExpanded:()=>this.toolOutputExpanded,setToolsExpanded:expanded=>this.setToolsExpanded(expanded)}}pushExtensionDialog(component,blocked,cancel,visibility){this.disposeActiveSelector();let covered=this.extensionDialogs.at(-1);this.extensionDialogs.push(
|
|
797
|
+
{component,blocked,cancel,dismissOnCover:visibility==="foreground-only"}),covered?.dismissOnCover&&covered.cancel?.(),this.showTopExtensionDialog()}closeExtensionDialogs(){let dialogs=this.extensionDialogs;this.extensionDialogs=[];for(let dialog of dialogs)dialog.component.dispose?.(),dialog.cancel?.();this.showTopExtensionDialog()}removeExtensionDialog(component){let index=this.extensionDialogs.findIndex(dialog=>dialog.component===component);index!==-1&&(this.extensionDialogs.splice(index,1),index===
|
|
798
|
+
this.extensionDialogs.length&&this.showTopExtensionDialog())}showTopExtensionDialog(){let top=this.extensionDialogs.at(-1),component=top?.component??this.editor;this.editorContainer.clear(),this.editorContainer.addChild(component),this.ui.setFocus(component),this.programStatus.setBlocked("extension-dialog",top?.blocked),this.ui.requestRender()}showExtensionSelector(title,options,opts){return new Promise(resolve2=>{if(opts?.signal?.aborted){resolve2(void 0);return}let finish=option=>{opts?.signal?.
|
|
799
|
+
removeEventListener("abort",onAbort),selector.dispose(),this.removeExtensionDialog(selector),resolve2(option)},onAbort=()=>finish(void 0);opts?.signal?.addEventListener("abort",onAbort,{once:!0});let selector=new ExtensionSelectorComponent(title,options,option=>finish(option),()=>finish(void 0),{tui:this.ui,timeout:opts?.timeout,onToggleToolsExpanded:()=>this.toggleToolOutputExpansion()});this.pushExtensionDialog(selector,dialogBlockedStatus(opts?.blockedKind??"question",title),onAbort)})}async showExtensionConfirm(title,message,opts){
|
|
800
|
+
return await this.showExtensionSelector(`${title}
|
|
798
801
|
${message}`,["Yes","No"],{...opts,blockedKind:opts?.blockedKind??"permission"})==="Yes"}async handleRemoteCommand(input2){if(this.remoteTerminalStopped)return;let label=hcodeDisplayName(this.session.modelRuntime.hcode.environment.id),owner=this.runtimeHost.sessionLifetime,flags=this.options.featureFlags,lookup=this.options.remoteFlagLookup;if(lookup){try{flags=await lookup(owner)}catch{this.showWarning(`${label}: Remote flag lookup failed; Remote stays available.`)}if(this.remoteTerminalStopped||
|
|
799
802
|
owner.aborted)return}if(!isRemoteHostEnabled(flags)){this.showWarning(`${label}: Remote is not enabled.`);return}let binding=this.options.remoteWatch;binding&&(this.remoteTerminalLifetime??=new AbortController);let terminal=this.remoteTerminalLifetime?.signal;if(owner.aborted||terminal?.aborted)return;let remote=this.remoteTerminal,lifetime=remote?.owner===owner?remote.lifetime:terminal?AbortSignal.any([owner,terminal]):owner,ui={notice:message=>{lifetime.aborted||this.showWarning(message)},confirm:(title,message,signal)=>this.
|
|
800
803
|
showRemoteConfirm(title,message,signal?AbortSignal.any([signal,lifetime]):lifetime)};binding&&remote?.owner!==owner&&(this.remoteTerminal={owner,lifetime,session:bindRemoteTerminalSession({...binding,environment:this.session.modelRuntime.hcode.environment,lifetime,source:watchCurrentBranch(this.session),ui})}),await runRemoteCommand(input2,ui,this.remoteTerminal?.session,this.session.modelRuntime.hcode.environment.id)}showRemoteConfirm(title,message,signal){return signal?.aborted||this.extensionDialogs.
|
|
@@ -809,8 +812,9 @@ onCtrlD=()=>this.defaultEditor.onCtrlD?.()),customEditor.onPasteImage||(customEd
|
|
|
809
812
|
this.editor=this.defaultEditor;dialogOpen||this.editorContainer.addChild(this.editor),this.activeStatusIndicator&&(this.statusContainer.clear(),this.activeWorkingIndicatorEmbedded=this.setEditorWorkingStatusIndicator(this.activeStatusIndicator),this.activeWorkingIndicatorEmbedded||this.statusContainer.addChild(this.activeStatusIndicator)),dialogOpen||this.ui.setFocus(this.editor),this.updateEditorBorderColor(),this.ui.requestRender()}showExtensionNotify(message,type){type==="error"?this.showError(
|
|
810
813
|
message):type==="warning"?this.showWarning(message):this.showStatus(message)}async showExtensionCustom(factory,options){let savedText=this.editor.getExpandedText?.()??this.editor.getText(),isOverlay=options?.overlay??!1;return new Promise((resolve2,reject)=>{let component,overlayHandle,closed=!1,restoreEditor3=()=>{component&&this.removeExtensionDialog(component),this.editor.setText(savedText),this.ui.requestRender()},disposeComponent=()=>{try{component?.dispose?.()}catch{}},removeOverlay=()=>{!overlayHandle||
|
|
811
814
|
!this.extensionOverlays.delete(overlayHandle)||(overlayHandle.hide(),disposeComponent())},close=result=>{closed||(closed=!0,isOverlay?(removeOverlay(),resolve2(result)):(restoreEditor3(),resolve2(result),disposeComponent()))};Promise.resolve(factory(this.ui,theme,this.keybindings,close)).then(c=>{if(!closed)if(component=c,isOverlay){let overlayOptions=(()=>{if(options?.overlayOptions)return typeof options.overlayOptions=="function"?options.overlayOptions():options.overlayOptions;let w=c.width;return w?
|
|
812
|
-
{width:w}:void 0})(),covered=this.extensionDialogs.at(-1);covered?.dismissOnCover&&covered.cancel?.(),overlayHandle=this.ui.showOverlay(c,overlayOptions),this.extensionOverlays.set(overlayHandle,removeOverlay),options?.onHandle?.(overlayHandle)}else this.pushExtensionDialog(c,options?.blocked)}).catch(err=>{closed||(isOverlay||restoreEditor3(),reject(err))})})}
|
|
813
|
-
|
|
815
|
+
{width:w}:void 0})(),covered=this.extensionDialogs.at(-1);covered?.dismissOnCover&&covered.cancel?.(),overlayHandle=this.ui.showOverlay(c,overlayOptions),this.extensionOverlays.set(overlayHandle,removeOverlay),options?.onHandle?.(overlayHandle)}else this.pushExtensionDialog(c,options?.blocked)}).catch(err=>{closed||(isOverlay||restoreEditor3(),reject(err))})})}handleExtensionError(failure){let error=new Error(`Extension "${failure.extensionPath}" (${failure.event}): ${failure.error}`);failure.stack&&
|
|
816
|
+
(error.stack=`${error.message}
|
|
817
|
+
${failure.stack}`),this.recordCrash("uncaught_exception",error),this.showExtensionError(failure.extensionPath,failure.error,failure.stack)}showExtensionError(extensionPath,error,stack){let errorMsg=`Extension "${extensionPath}" error: ${error}`,errorText=new ThemedText(()=>theme.fg("error",errorMsg),1,0);if(this.chatContainer.addChild(errorText),stack){let stackLines=stack.split(`
|
|
814
818
|
`).slice(1);if(stackLines.length>0){let renderStack=()=>stackLines.map(line=>theme.fg("dim",` ${line.trim()}`)).join(`
|
|
815
819
|
`);this.chatContainer.addChild(new ThemedText(renderStack,1,0))}}this.ui.requestRender()}setupKeyHandlers(){this.defaultEditor.onEscape=()=>{if(this.session.isStreaming)this.restoreQueuedMessagesToEditor({abort:!0});else if(this.session.isBashRunning)this.session.abortBash();else if(this.isBashMode)this.editor.setText(""),this.isBashMode=!1,this.updateEditorBorderColor();else if(!this.editor.getText().trim()){let action=this.settingsManager.getDoubleEscapeAction();if(action!=="none"){let now=Date.
|
|
816
820
|
now();now-this.lastEscapeTime<500?(action==="tree"?this.showTreeSelector():this.showUserMessageSelector(),this.lastEscapeTime=0):this.lastEscapeTime=now}}},this.defaultEditor.onAction("app.clear",()=>this.handleCtrlC()),this.defaultEditor.onCtrlD=()=>this.handleCtrlD(),this.defaultEditor.onAction("app.suspend",()=>this.handleCtrlZ()),this.defaultEditor.onAction("app.thinking.cycle",()=>this.cycleThinkingLevel()),this.defaultEditor.onAction("app.model.cycleForward",()=>this.cycleModel("forward")),
|
|
@@ -887,14 +891,15 @@ resolve2(text)}})}rebuildChatFromMessages(){this.chatContainer.clear(),this.rend
|
|
|
887
891
|
if(options?.fromSignal){try{await waitForSignalShutdown(this.runtimeHost.dispose())}finally{await termination}this.themeController.disableAutoSync(),await this.ui.terminal.drainInput(1e3),this.stop(),await flushStdout(),killTrackedDetachedChildren(),process.exit(0)}this.themeController.disableAutoSync(),await this.ui.terminal.drainInput(1e3),this.stop();try{await this.runtimeHost.dispose()}finally{await termination}let resumeCommand=formatResumeCommand(this.sessionManager,this.session.modelRuntime.
|
|
888
892
|
hcode.environment.id);resumeCommand&&process.stdout.write(`${source_default.dim("To resume this session:")}
|
|
889
893
|
${resumeCommand}
|
|
890
|
-
`),await flushStdout(),killTrackedDetachedChildren(),process.exit(0)}emergencyTerminalExit(){this.isShuttingDown=!0,this.releaseFlowAccountsHost(),this.unregisterSignalHandlers(),killTrackedDetachedChildren(),process.exit(129)}uncaughtCrash(error){isDeadTerminalError(error)&&this.emergencyTerminalExit(),this.isShuttingDown&&(killTrackedDetachedChildren(),process.exit(1)),this.isShuttingDown=!0,this.releaseFlowAccountsHost();
|
|
891
|
-
try{this.ui.stop()}catch{}console.error(`${APP_TITLE} exiting due to uncaughtException:`),console.error(error);let extensionHint=this.getCrashExtensionHint(error);extensionHint&&console.error(`
|
|
894
|
+
`),await flushStdout(),killTrackedDetachedChildren(),process.exit(0)}emergencyTerminalExit(){this.isShuttingDown=!0,this.releaseFlowAccountsHost(),this.unregisterSignalHandlers(),killTrackedDetachedChildren(),process.exit(129)}uncaughtCrash(error){if(containStaleExtension(error,failure=>this.handleExtensionError(failure)))return;isDeadTerminalError(error)&&this.emergencyTerminalExit(),this.isShuttingDown&&(killTrackedDetachedChildren(),process.exit(1)),this.isShuttingDown=!0,this.releaseFlowAccountsHost();
|
|
895
|
+
try{this.unregisterSignalHandlers()}catch{}try{killTrackedDetachedChildren()}catch{}try{this.ui.stop()}catch{}console.error(`${APP_TITLE} exiting due to uncaughtException:`),console.error(error);let extensionHint=this.getCrashExtensionHint(error);extensionHint&&console.error(`
|
|
892
896
|
${extensionHint}`),this.recordCrash("uncaught_exception",error)&&console.error(`
|
|
893
|
-
${this.crashReportInstructions()}`),process.exit(1)}async checkShutdownRequested(){this.shutdownRequested&&await this.shutdown()}registerSignalHandlers(){this.unregisterSignalHandlers();let signals=["SIGTERM","SIGHUP"];process.platform==="win32"&&signals.push("SIGBREAK");for(let signal of signals){let handler=()=>{this.isShuttingDown&&(killTrackedDetachedChildren(),process.exit(signal==="SIGHUP"?129:
|
|
894
|
-
push(()=>process.off(signal,handler))}let terminalErrorHandler=error=>{throw isDeadTerminalError(error)&&this.emergencyTerminalExit(),error};for(let stream of[process.stdin,process.stdout,process.stderr])stream.on("error",terminalErrorHandler),this.signalCleanupHandlers.push(()=>stream.off("error",terminalErrorHandler));let uncaughtExceptionHandler=error=>this.uncaughtCrash(error);process.prependListener(
|
|
895
|
-
"uncaughtException",uncaughtExceptionHandler)),this.signalCleanupHandlers.push(onUnhandledRejection(error=>this.uncaughtCrash(error)))}unregisterSignalHandlers(){for(let cleanup of this.signalCleanupHandlers)cleanup();this.signalCleanupHandlers=[]}handleCtrlZ(){if(process.platform==="win32"){this.showStatus("Suspend to background is not supported on Windows");return}let suspendKeepAlive=setInterval(()=>{},
|
|
896
|
-
suspendKeepAlive),process.removeListener("SIGINT",ignoreSigint),this.ui.start(),this.ui.requestRender(!0)});try{this.ui.stop(),process.kill(0,"SIGTSTP")}catch(error){throw clearInterval(suspendKeepAlive),process.removeListener("SIGINT",ignoreSigint),error}}async handleFollowUp(){let text=(this.editor.getExpandedText?.()??this.editor.getText()).trim();if(text){if(text.startsWith("/")||this.footer.
|
|
897
|
-
this.editor.setText(""),await this.session.prompt(text)):this.queueCompactionMessage(text,"followUp");return}if(this.session.isStreaming){this.editor.addToHistory?.(text),this.editor.setText("");try{await this.session.prompt(text,{streamingBehavior:"followUp",expandPromptTemplates:!1})}catch(error){let draft=this.editor.getText();draft!==text&&this.editor.setText([text,draft].filter(Boolean).
|
|
897
|
+
${this.crashReportInstructions()}`),process.exit(1)}async checkShutdownRequested(){this.shutdownRequested&&await this.shutdown()}registerSignalHandlers(){this.unregisterSignalHandlers(),this.signalCleanupHandlers.push(setExtensionErrorReporter(error=>this.handleExtensionError(error)));let signals=["SIGTERM","SIGHUP"];process.platform==="win32"&&signals.push("SIGBREAK");for(let signal of signals){let handler=()=>{this.isShuttingDown&&(killTrackedDetachedChildren(),process.exit(signal==="SIGHUP"?129:
|
|
898
|
+
143)),this.shutdown({fromSignal:!0})};process.prependListener(signal,handler),this.signalCleanupHandlers.push(()=>process.off(signal,handler))}let terminalErrorHandler=error=>{throw isDeadTerminalError(error)&&this.emergencyTerminalExit(),error};for(let stream of[process.stdin,process.stdout,process.stderr])stream.on("error",terminalErrorHandler),this.signalCleanupHandlers.push(()=>stream.off("error",terminalErrorHandler));let uncaughtExceptionHandler=error=>this.uncaughtCrash(error);process.prependListener(
|
|
899
|
+
"uncaughtException",uncaughtExceptionHandler),this.signalCleanupHandlers.push(()=>process.off("uncaughtException",uncaughtExceptionHandler)),this.signalCleanupHandlers.push(onUnhandledRejection(error=>this.uncaughtCrash(error)))}unregisterSignalHandlers(){for(let cleanup of this.signalCleanupHandlers)cleanup();this.signalCleanupHandlers=[]}handleCtrlZ(){if(process.platform==="win32"){this.showStatus("Suspend to background is not supported on Windows");return}let suspendKeepAlive=setInterval(()=>{},
|
|
900
|
+
2**30),ignoreSigint=()=>{};process.on("SIGINT",ignoreSigint),process.once("SIGCONT",()=>{clearInterval(suspendKeepAlive),process.removeListener("SIGINT",ignoreSigint),this.ui.start(),this.ui.requestRender(!0)});try{this.ui.stop(),process.kill(0,"SIGTSTP")}catch(error){throw clearInterval(suspendKeepAlive),process.removeListener("SIGINT",ignoreSigint),error}}async handleFollowUp(){let text=(this.editor.getExpandedText?.()??this.editor.getText()).trim();if(text){if(text.startsWith("/")||this.footer.
|
|
901
|
+
markActivity(),this.session.isCompacting){this.isExtensionCommand(text)?(this.editor.addToHistory?.(text),this.editor.setText(""),await this.session.prompt(text)):this.queueCompactionMessage(text,"followUp");return}if(this.session.isStreaming){this.editor.addToHistory?.(text),this.editor.setText("");try{await this.session.prompt(text,{streamingBehavior:"followUp",expandPromptTemplates:!1})}catch(error){let draft=this.editor.getText();draft!==text&&this.editor.setText([text,draft].filter(Boolean).
|
|
902
|
+
join(`
|
|
898
903
|
|
|
899
904
|
`)),this.showError(error instanceof Error?error.message:String(error))}this.updatePendingMessagesDisplay(),this.ui.requestRender()}else this.editor.onSubmit&&(this.editor.setText(""),this.editor.onSubmit(text))}}handleDequeue(){let restored=this.restoreQueuedMessagesToEditor();restored===0?this.showStatus("No queued messages to restore"):this.showStatus(`Restored ${restored} queued message${restored>1?"s":""} to editor`)}updateEditorBorderColor(){let level=this.session.model?.reasoning&&this.session.
|
|
900
905
|
getAvailableThinkingLevels().includes(this.session.thinkingLevel)?this.session.thinkingLevel:"off",accent=this.isBashMode?void 0:this.extensionEditorAccent;if("setAccentLabel"in this.editor&&typeof this.editor.setAccentLabel=="function"&&this.editor.setAccentLabel(accent?.label),this.isBashMode)this.editor.borderColor=theme.getBashModeBorderColor();else if(accent){let color=accent.color;this.editor.borderColor=s=>theme.fg(color,s)}else this.editor.borderColor=theme.getThinkingBorderColor(level);
|