@thothdev/pink 1.0.27 → 1.0.30
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
CHANGED
|
@@ -3,10 +3,19 @@
|
|
|
3
3
|
O Pink é um fork do Pi (MIT, veja `LICENSE-PI.txt` e `NOTICE.md`). Aqui só entra o que mudou no Pink; a base de cada
|
|
4
4
|
versão está no campo `upstream` do `rebrand.json` do repositório.
|
|
5
5
|
|
|
6
|
-
## [1.0.
|
|
7
|
-
|
|
8
|
-
-
|
|
9
|
-
|
|
6
|
+
## [1.0.29] - 2026-11-28
|
|
7
|
+
|
|
8
|
+
- Nos modelos logados no Pink e no `/agente`: ao lançar subagentes, o chat mostra o bloco "N subagentes lançados" com o nome e a tarefa de cada um, sem ficar escondido no resumo.
|
|
9
|
+
|
|
10
|
+
## [1.0.28] - 2026-11-28
|
|
11
|
+
|
|
12
|
+
- `/agente opencode`: subagente que o OpenCode lança sozinho, depois da resposta, volta a aparecer na lista, e o que está trabalhando não aparece mais como pausado.
|
|
13
|
+
- `/agente`: o trabalho que o agente faz depois do fim do turno sai num bloco só; antes cada passo virava um bloco repetindo o nome do agente e o modelo.
|
|
14
|
+
|
|
15
|
+
## [1.0.27] - 2026-11-28
|
|
16
|
+
|
|
17
|
+
- `/agente` (OpenCode e outros ACP): a resposta que o agente manda depois do fim do turno (subagente ou comando em segundo plano que terminou) agora aparece no chat; antes era descartada e o agente parecia ter parado. Pedidos de permissão nesse intervalo continuam sendo perguntados.
|
|
18
|
+
|
|
10
19
|
## [1.0.26] - 2026-11-28
|
|
11
20
|
|
|
12
21
|
- `web_search` usa o servidor wigolo local (`127.0.0.1:3333`) quando ele está no ar; sem ele, ou se a resposta não for dele, segue no DuckDuckGo como antes. Nada novo para configurar.
|
|
@@ -993,7 +993,7 @@ ${message}`,[globalThis.__pinkT?.("Sim","Sí","Yes")??"Sim",globalThis.__pinkT?.
|
|
|
993
993
|
`)[cursor.line]??"":"",characterBeforeCursor=cursor&&cursor.col>0?currentLine[cursor.col-1]:"",characterAfterCursor=cursor?currentLine[cursor.col]:"",leadingSpace=characterBeforeCursor&&!/\s/.test(characterBeforeCursor)?" ":"",trailingSpace=characterAfterCursor&&!/\s/.test(characterAfterCursor)?" ":"";this.editor.insertTextAtCursor?.(`${leadingSpace}${paths}${trailingSpace}`),this.ui.requestRender();return}let image=await readClipboardImage();if(image){let tmpDir=os4.tmpdir(),ext2=extensionForImageMimeType(image.mimeType)??"png",fileName=`pi-clipboard-${crypto2.randomUUID()}.${ext2}`,filePath=path9.join(tmpDir,fileName);fs5.writeFileSync(filePath,Buffer.from(image.bytes)),this.editor.insertTextAtCursor?.(filePath),this.ui.requestRender();return}let text=await readClipboardText();text&&(this.editor.insertTextAtCursor?.(text),this.ui.requestRender())}catch(error){this.showError(`Failed to paste from clipboard: ${error instanceof Error?error.message:String(error)}`)}}handleStartupSubmit(text){this.editor.setText(text),this.showStatus("Startup is still in progress")}setupEditorSubmitHandler(){this.defaultEditor.onSubmit=async text=>{if(text=text.trim(),!!text){if(text==="/settings"){this.showSettingsSelector(),this.editor.setText("");return}if(text==="/scoped-models"){this.editor.setText(""),await this.showModelsSelector();return}if(text==="/model"||text.startsWith("/model ")){let searchTerm=text.startsWith("/model ")?text.slice(7).trim():void 0;this.editor.setText(""),await this.handleModelCommand(searchTerm);return}if(text==="/thinking"||text.startsWith("/thinking ")){let searchTerm=text.startsWith("/thinking ")?text.slice(10).trim():void 0;this.editor.setText(""),this.handleThinkingCommand(searchTerm);return}if(text==="/export"||text.startsWith("/export ")){await this.handleExportCommand(text),this.editor.setText("");return}if(text==="/import"||text.startsWith("/import ")){await this.handleImportCommand(text),this.editor.setText("");return}if(text==="/share"){await this.handleShareCommand(),this.editor.setText("");return}if(text==="/copy"){await this.handleCopyCommand(),this.editor.setText("");return}if(text==="/name"||text.startsWith("/name ")){this.handleNameCommand(text),this.editor.setText("");return}if(text==="/session"){this.handleSessionCommand(),this.editor.setText("");return}if(text==="/hotkeys"){this.handleHotkeysCommand(),this.editor.setText("");return}if(text==="/fork"){this.showUserMessageSelector(),this.editor.setText("");return}if(text==="/clone"){this.editor.setText(""),await this.handleCloneCommand();return}if(text==="/tree"){this.showTreeSelector(),this.editor.setText("");return}if(text==="/trust"){this.showTrustSelector(),this.editor.setText("");return}if(text==="/login"||text.startsWith("/login ")){let providerRef=text.startsWith("/login ")?text.slice(7).trim():void 0;this.editor.setText(""),await this.handleLoginCommand(providerRef);return}if(text==="/logout"){this.showOAuthSelector("logout"),this.editor.setText("");return}if(text==="/new"){this.editor.setText(""),await this.handleClearCommand();return}if(text==="/compact"||text.startsWith("/compact ")){let customInstructions=text.startsWith("/compact ")?text.slice(9).trim():void 0;this.editor.setText(""),await this.handleCompactCommand(customInstructions);return}if(text==="/reload"){this.editor.setText(""),await this.handleReloadCommand();return}if(text==="/debug"){this.handleDebugCommand(),this.editor.setText("");return}if(text==="/arminsayshi"){this.handleArminSaysHi(),this.editor.setText("");return}if(text==="/dementedelves"){this.handleDementedDelves(),this.editor.setText("");return}if(text==="/resume"){this.showSessionSelector(),this.editor.setText("");return}if(text==="/quit"){this.editor.setText(""),await this.shutdown();return}if(text.startsWith("!")){let isExcluded=text.startsWith("!!"),command=isExcluded?text.slice(2).trim():text.slice(1).trim();if(command){if(this.session.isBashRunning){this.showWarning("A bash command is already running. Press Esc to cancel it first."),this.editor.setText(text);return}this.editor.addToHistory?.(text),await this.handleBashCommand(command,isExcluded),this.isBashMode=!1,this.updateEditorBorderColor();return}}if(this.session.isCompacting){this.isExtensionCommand(text)?(this.editor.addToHistory?.(text),this.editor.setText(""),await this.session.prompt(text)):this.queueCompactionMessage(text,"steer");return}if(this.session.isStreaming){this.editor.addToHistory?.(text),this.editor.setText(""),await this.session.prompt(text,{streamingBehavior:"steer"}),this.updatePendingMessagesDisplay(),this.ui.requestRender();return}this.flushPendingBashComponents(),this.onInputCallback?this.onInputCallback(text):this.pendingUserInputs.push(text),this.editor.addToHistory?.(text)}}}subscribeToAgent(){this.unsubscribe=this.session.subscribe(async event=>{await this.handleEvent(event)})}async handleEvent(event){switch(this.isInitialized||await this.init(),this.footer.invalidate(),this.programStatus.handleEvent(event),event.type){case"agent_start":this.pendingTools.clear(),this.retryEscapeHandler&&(this.defaultEditor.onEscape=this.retryEscapeHandler,this.retryEscapeHandler=void 0);break;case"turn_start":this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!0),this.workingVisible?this.activeStatusIndicator?.kind!=="working"&&this.showWorkingStatusIndicator():this.clearStatusIndicator(),this.ui.requestRender();break;case"queue_update":this.updatePendingMessagesDisplay(),this.ui.requestRender();break;case"entry_appended":if(this.entriesRenderedByBoundaryCompaction.delete(event.entry.id))break;if(event.entry.type==="custom")this.addCustomEntryToChat(event.entry),this.ui.requestRender();else if(event.entry.type==="usage"&&event.entry.kind==="cache_warm")this.addCacheWarmingUsage(event.entry),this.ui.requestRender();else if(event.entry.type==="custom_message"&&event.entry.display)this.addMessageToChat(createCustomMessage(event.entry.customType,event.entry.content,event.entry.display,event.entry.details,event.entry.timestamp)),this.ui.requestRender();else if(event.entry.type==="compaction"){let entries=this.sessionManager.buildContextEntries();if(entries[0]?.id!==event.entry.id)break;this.chatContainer.clear();let branch=this.sessionManager.getBranch(),compactionIndex=branch.findIndex(entry=>entry.id===event.entry.id),entriesAfterCompaction=new Set(branch.slice(compactionIndex+1).map(entry=>entry.id)),retainedEntries=entries.slice(1);this.renderSessionEntries(retainedEntries.filter(entry=>!entriesAfterCompaction.has(entry.id))),this.addMessageToChat(createCompactionSummaryMessage(event.entry.summary,event.entry.tokensBefore,event.entry.timestamp)),event.entry.usage&&this.addCompactionCostNotice({type:"compaction_cost",kind:"compaction",usage:event.entry.usage}),this.renderSessionEntries(retainedEntries.filter(entry=>entriesAfterCompaction.has(entry.id)));for(let entryId of entriesAfterCompaction)this.entriesRenderedByBoundaryCompaction.add(entryId);this.footer.invalidate(),this.ui.requestRender()}break;case"session_info_changed":this.updateTerminalTitle(),this.footer.invalidate(),this.ui.requestRender();break;case"thinking_level_changed":this.footer.invalidate(),this.updateEditorBorderColor();break;case"message_start":event.message.role==="custom"?(this.addMessageToChat(event.message),this.ui.requestRender()):event.message.role==="user"?(this.addMessageToChat(event.message),this.updatePendingMessagesDisplay(),this.ui.requestRender()):event.message.role==="assistant"&&(this.streamingComponent=new AssistantMessageComponent(void 0,this.hideThinkingBlock,this.getMarkdownThemeWithSettings(),this.hiddenThinkingLabel,this.outputPad,this.getMarkdownTransformers()),this.streamingMessage=event.message,this.chatContainer.addChild(this.streamingComponent),this.streamingComponent.updateContent(this.streamingMessage,!0),this.ui.requestRender());break;case"message_update":if(this.streamingComponent&&event.message.role==="assistant"){this.streamingMessage=event.message,this.streamingComponent.updateContent(this.streamingMessage,!0);for(let content of this.streamingMessage.content)if(content.type==="toolCall")if(this.pendingTools.has(content.id)){let component=this.pendingTools.get(content.id);component&&component.updateArgs(content.arguments)}else{let component=new ToolExecutionComponent(content.name,content.id,content.arguments,{showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells(),outputPad:this.outputPad},this.getRegisteredToolDefinition(content.name),this.ui,this.sessionManager.getCwd());component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component),this.pendingTools.set(content.id,component)}this.ui.requestRender()}break;case"message_end":if(event.message.role==="user")break;if(this.streamingComponent&&event.message.role==="assistant"){this.streamingMessage=event.message;let errorMessage5;if(this.streamingMessage.stopReason==="aborted"){let retryAttempt=this.session.retryAttempt;errorMessage5=retryAttempt>0?`Aborted after ${retryAttempt} retry attempt${retryAttempt>1?"s":""}`:"Operation aborted",this.streamingMessage.errorMessage=errorMessage5}if(this.streamingComponent.updateContent(this.streamingMessage,!1),this.streamingMessage.stopReason==="aborted"||this.streamingMessage.stopReason==="error"){errorMessage5||(errorMessage5=this.streamingMessage.errorMessage||"Error");for(let[,component]of this.pendingTools.entries())component.updateResult({content:[{type:"text",text:errorMessage5}],isError:!0});this.pendingTools.clear(),this.maybeSuggestBugReport(this.streamingMessage)}else{for(let[,component]of this.pendingTools.entries())component.setArgsComplete();this.maybeShowThinkingDropNotice(this.streamingMessage),this.maybeShowCacheMissNotice(this.streamingMessage)}this.streamingComponent=void 0,this.streamingMessage=void 0,this.footer.invalidate()}this.ui.requestRender();break;case"bash_execution_update":break;case"tool_execution_start":{if(event.parentToolCallId)break;let component=this.pendingTools.get(event.toolCallId);component||(component=new ToolExecutionComponent(event.toolName,event.toolCallId,event.args,{showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells(),outputPad:this.outputPad},this.getRegisteredToolDefinition(event.toolName),this.ui,this.sessionManager.getCwd()),component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component),this.pendingTools.set(event.toolCallId,component)),component.markExecutionStarted(),this.ui.requestRender();break}case"tool_execution_update":{let component=this.pendingTools.get(event.toolCallId);component&&(component.updateResult({...event.partialResult,isError:!1},!0),this.ui.requestRender());break}case"tool_execution_end":{event.isError&&this.maybeShowInstallChangeWarning();let component=this.pendingTools.get(event.toolCallId);component&&(component.updateResult({...event.result,isError:event.isError,durationMs:event.durationMs}),this.pendingTools.delete(event.toolCallId),this.ui.requestRender());break}case"agent_end":this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!1),this.clearStatusIndicator("working"),this.streamingComponent&&(this.chatContainer.removeChild(this.streamingComponent),this.streamingComponent=void 0,this.streamingMessage=void 0),this.pendingTools.clear(),this.ui.requestRender();break;case"agent_settled":await this.checkShutdownRequested();break;case"compaction_start":{this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!0),this.autoCompactionEscapeHandler=this.defaultEditor.onEscape,this.defaultEditor.onEscape=()=>{this.session.abortCompaction()};let colorFn=isEmbeddedStatus(this.editor)?text=>(this.editor.borderColor??theme.getThinkingBorderColor(this.session.thinkingLevel||"off"))(text):void 0;this.showStatusIndicator(new CompactionStatusIndicator(this.ui,event.reason,colorFn)),this.ui.requestRender();break}case"compaction_end":{if(this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!1),this.autoCompactionEscapeHandler&&(this.defaultEditor.onEscape=this.autoCompactionEscapeHandler,this.autoCompactionEscapeHandler=void 0),this.clearStatusIndicator("compaction"),event.aborted)event.reason==="manual"?this.showError("Compaction cancelled"):this.showStatus("Auto-compaction cancelled");else if(event.result){let entries=this.sessionManager.buildContextEntries();if(entries[0]?.type!=="compaction")throw new Error("Completed compaction is missing from the session context");this.chatContainer.clear(),this.renderSessionEntries(entries.slice(1)),this.addMessageToChat(createCompactionSummaryMessage(event.result.summary,event.result.tokensBefore,new Date().toISOString())),event.result.usage&&this.addCompactionCostNotice({type:"compaction_cost",kind:"compaction",usage:event.result.usage}),this.footer.invalidate()}else if(event.errorMessage)if(event.reason==="manual")this.showError(event.errorMessage);else{this.chatContainer.addChild(new Spacer(1));let errorMessage5=event.errorMessage;this.chatContainer.addChild(new ThemedText(()=>theme.fg("error",errorMessage5),1,0))}this.flushCompactionQueue({willRetry:event.willRetry}),this.ui.requestRender();break}case"auto_retry_start":{this.retryEscapeHandler=this.defaultEditor.onEscape,this.defaultEditor.onEscape=()=>{this.session.abortRetry()},this.showStatusIndicator(new RetryStatusIndicator(this.ui,event.attempt,event.maxAttempts,event.delayMs)),this.ui.requestRender();break}case"auto_retry_end":{this.retryEscapeHandler&&(this.defaultEditor.onEscape=this.retryEscapeHandler,this.retryEscapeHandler=void 0),this.clearStatusIndicator("retry"),event.success||this.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError||"Unknown error"}`),this.ui.requestRender();break}case"summarization_retry_scheduled":{this.showError(event.errorMessage),this.showStatusIndicator(new RetryStatusIndicator(this.ui,event.attempt,event.maxAttempts,event.delayMs)),this.ui.requestRender();break}case"summarization_retry_attempt_start":{if(this.clearStatusIndicator("retry"),event.source==="branchSummary")this.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui));else{let colorFn=isEmbeddedStatus(this.editor)?text=>(this.editor.borderColor??theme.getThinkingBorderColor(this.session.thinkingLevel||"off"))(text):void 0;this.showStatusIndicator(new CompactionStatusIndicator(this.ui,event.reason,colorFn))}this.ui.requestRender();break}case"summarization_retry_finished":{this.clearStatusIndicator("retry"),this.ui.requestRender();break}}}getUserMessageText(message){return message.role!=="user"?"":(typeof message.content=="string"?[{type:"text",text:message.content}]:message.content.filter(c=>c.type==="text")).map(c=>c.text).join("")}showManagedToolStatus(status){this.managedToolStatusStarted||(this.chatContainer.addChild(new Spacer(1)),this.managedToolStatusStarted=!0);let message=status.type==="warning"?`Warning: ${status.message}`:status.message,color=status.type==="warning"?"warning":"dim";this.chatContainer.addChild(new ThemedText(()=>theme.fg(color,message),1,0)),this.lastStatusSpacer=void 0,this.lastStatusText=void 0,this.ui.requestRender()}showStatus(message){let children=this.chatContainer.children,last=children.length>0?children[children.length-1]:void 0,secondLast=children.length>1?children[children.length-2]:void 0;if(last&&secondLast&&last===this.lastStatusText&&secondLast===this.lastStatusSpacer){this.lastStatusMessage=message,this.lastStatusText.invalidate(),this.ui.requestRender();return}let spacer=new Spacer(1);this.lastStatusMessage=message;let text=new ThemedText(()=>theme.fg("dim",this.lastStatusMessage),1,0);this.chatContainer.addChild(spacer),this.chatContainer.addChild(text),this.lastStatusSpacer=spacer,this.lastStatusText=text,this.ui.requestRender()}addCustomEntryToChat(entry){let renderer=this.session.extensionRunner.getEntryRenderer(entry.customType);if(!renderer)return;let component=new CustomEntryComponent(entry,renderer,this.outputPad);if(component.setExpanded(this.toolOutputExpanded),!!component.hasContent()){if(this.streamingComponent){let streamingIndex=this.chatContainer.children.indexOf(this.streamingComponent);if(streamingIndex>=0){this.chatContainer.children.splice(streamingIndex,0,component);return}}this.chatContainer.addChild(component)}}addMessageToChat(message,options){switch(message.role){case"bashExecution":{let component=new BashExecutionComponent(message.command,this.ui,message.excludeFromContext,this.outputPad);message.output&&component.appendOutput(message.output),component.setComplete(message.exitCode,message.cancelled,message.truncated?{truncated:!0}:void 0,message.fullOutputPath),this.chatContainer.addChild(component);break}case"custom":{if(message.display){let renderer=this.session.extensionRunner.getMessageRenderer(message.customType),component=new CustomMessageComponent(message,renderer,this.getMarkdownThemeWithSettings(),this.outputPad);component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component)}break}case"compactionSummary":{this.chatContainer.addChild(new Spacer(1));let component=new CompactionSummaryMessageComponent(message,this.getMarkdownThemeWithSettings(),this.outputPad);component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component);break}case"branchSummary":{this.chatContainer.addChild(new Spacer(1));let component=new BranchSummaryMessageComponent(message,this.getMarkdownThemeWithSettings(),this.outputPad);component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component);break}case"system":break;case"user":{let textContent=this.getUserMessageText(message);if(textContent){this.chatContainer.children.length>0&&this.chatContainer.addChild(new Spacer(1));let skillBlock=parseSkillBlock(textContent);if(skillBlock){let component=new SkillInvocationMessageComponent(skillBlock,this.getMarkdownThemeWithSettings(),this.outputPad);if(component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component),skillBlock.userMessage){this.chatContainer.addChild(new Spacer(1));let userComponent=new UserMessageComponent(skillBlock.userMessage,this.getMarkdownThemeWithSettings(),this.outputPad,this.getMarkdownTransformers());this.chatContainer.addChild(userComponent)}}else{let userComponent=new UserMessageComponent(textContent,this.getMarkdownThemeWithSettings(),this.outputPad,this.getMarkdownTransformers());this.chatContainer.addChild(userComponent)}options?.populateHistory&&this.editor.addToHistory?.(textContent)}break}case"assistant":{let assistantComponent=new AssistantMessageComponent(message,this.hideThinkingBlock,this.getMarkdownThemeWithSettings(),this.hiddenThinkingLabel,this.outputPad,this.getMarkdownTransformers());this.chatContainer.addChild(assistantComponent);break}case"toolResult":break;default:{let _exhaustive=message}}}renderSessionItems(items,options={}){this.pendingTools.clear();let renderedPendingTools=new Map,cacheMisses=this.settingsManager.getShowCacheMissNotices()?collectCacheMisses(this.sessionManager.getEntries(),this.session.modelRuntime):new Map;options.updateFooter&&(this.footer.invalidate(),this.updateEditorBorderColor());for(let item of items){if(isCustomSessionEntry(item)){this.addCustomEntryToChat(item);continue}if(isUsageSessionEntry(item)){this.addCacheWarmingUsage(item);continue}if(isCompactionCostNotice(item)){this.addCompactionCostNotice(item);continue}let message=item;if(message.role==="assistant"){this.addMessageToChat(message);for(let content of message.content)if(content.type==="toolCall"){let component=new ToolExecutionComponent(content.name,content.id,content.arguments,{showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells(),outputPad:this.outputPad},this.getRegisteredToolDefinition(content.name),this.ui,this.sessionManager.getCwd());if(component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component),message.stopReason==="aborted"||message.stopReason==="error"){let errorMessage5;if(message.stopReason==="aborted"){let retryAttempt=this.session.retryAttempt;errorMessage5=retryAttempt>0?`Aborted after ${retryAttempt} retry attempt${retryAttempt>1?"s":""}`:"Operation aborted"}else errorMessage5=message.errorMessage||"Error";component.updateResult({content:[{type:"text",text:errorMessage5}],isError:!0})}else renderedPendingTools.set(content.id,component)}if(message.stopReason!=="aborted"&&message.stopReason!=="error"){let miss=cacheMisses.get(message);miss&&this.addCacheMissNotice(miss)}}else if(message.role==="toolResult"){let component=renderedPendingTools.get(message.toolCallId);component&&(component.updateResult(message),renderedPendingTools.delete(message.toolCallId))}else this.addMessageToChat(message,options)}for(let[toolCallId,component]of renderedPendingTools)this.pendingTools.set(toolCallId,component);this.ui.requestRender()}renderSessionEntries(entries,options={}){this.renderer instanceof TuiAltScreen&&this.renderer.resetTextSelection();let items=entries.flatMap(entry=>{if(entry.type==="custom"||entry.type==="usage"&&entry.kind==="cache_warm")return[entry];let messages=sessionEntryToContextMessages(entry);return(entry.type==="compaction"||entry.type==="branch_summary")&&entry.usage&&messages.length>0?[...messages,{type:"compaction_cost",kind:entry.type,usage:entry.usage}]:messages});this.renderSessionItems(items,options)}addCacheWarmingUsage(entry){if(!this.settingsManager.getShowCacheMissNotices())return;this.chatContainer.addChild(new Spacer(1));let usage=formatCacheWarmingUsage(entry);this.chatContainer.addChild(new ThemedText(()=>theme.fg("dim",usage),1,0))}addCompactionCostNotice(notice){if(!this.settingsManager.getShowCacheMissNotices())return;let{usage}=notice,tokens=usage.input+usage.output+usage.cacheRead+usage.cacheWrite,cost=usage.cost.total>=.01?` (~$${usage.cost.total.toFixed(2)})`:"",label=notice.kind==="compaction"?"Compaction":"Branch summary";this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",`${label}: ${formatTokens(tokens)} tokens billed${cost}`),1,0))}static countDroppedThinkingBlocks(message){let count=0;for(let diagnostic of message.diagnostics??[]){if(diagnostic.type!=="anthropic_input_transformations")continue;let transformations=diagnostic.details?.transformations;Array.isArray(transformations)&&(count+=transformations.filter(transformation=>typeof transformation=="object"&&transformation!==null&&transformation.type==="thinking_dropped").length)}return count}maybeShowThinkingDropNotice(message){if(!this.settingsManager.getShowCacheMissNotices())return;let droppedCount=_InteractiveMode.countDroppedThinkingBlocks(message);if(droppedCount===0)return;let previousDroppedCount=0,branch=this.sessionManager.getBranch();for(let i=branch.length-1;i>=0;i--){let entry=branch[i];if(entry.type==="message"&&entry.message.role==="assistant"){previousDroppedCount=_InteractiveMode.countDroppedThinkingBlocks(entry.message);break}}if(droppedCount<=previousDroppedCount)return;let noun=droppedCount===1?"thinking block":"thinking blocks";this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",`Anthropic dropped ${droppedCount} ${noun} (details in session)`),1,0))}maybeShowCacheMissNotice(message){if(!this.settingsManager.getShowCacheMissNotices())return;let miss=detectCacheMiss(this.sessionManager.getEntries(),message,this.session.modelRuntime);miss&&this.addCacheMissNotice(miss)}addCacheMissNotice(miss){if(miss.missedTokens<2e4&&miss.missedCost<.1)return;let cost=miss.missedCost>=.01?` (~$${miss.missedCost.toFixed(2)})`:"",reBilled=`${formatTokens(miss.missedTokens)} tokens re-billed${cost}`,label="Cache miss";miss.modelChanged?label="Cache miss after model switch":miss.idleMs>=3e5&&(label=`Cache miss after ${Math.round(miss.idleMs/6e4)}m idle`),this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",`${label}: ${reBilled}`),1,0))}renderInitialMessages(){let entries=this.sessionManager.buildContextEntries();this.renderSessionEntries(entries,{updateFooter:!0,populateHistory:!0}),this.renderProjectTrustWarningIfNeeded();let compactionCount=this.sessionManager.getEntries().filter(e=>e.type==="compaction").length;if(compactionCount>0){let times=compactionCount===1?"1 time":`${compactionCount} times`;this.showStatus(`Session compacted ${times}`)}}renderProjectTrustWarningIfNeeded(){this.settingsManager.isProjectTrusted()||!hasTrustRequiringProjectResources(this.sessionManager.getCwd())||(this.chatContainer.children.length>0&&this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",`This project is not trusted. Project ${CONFIG_DIR_NAME} resources and packages are ignored. Use /trust to save a trust decision, then restart pink.`),1,0)))}async getUserInput(){let queuedInput=this.pendingUserInputs.shift();return queuedInput!==void 0?queuedInput:new Promise(resolve16=>{this.onInputCallback=text=>{this.onInputCallback=void 0,resolve16(text)}})}rebuildChatFromMessages(){this.chatContainer.clear(),this.renderSessionEntries(this.sessionManager.buildContextEntries())}handleCtrlC(){let now=Date.now();now-this.lastSigintTime<500?this.shutdown():(this.clearEditor(),this.lastSigintTime=now)}handleCtrlD(){this.shutdown()}isShuttingDown=!1;async shutdown(options){if(this.isShuttingDown)return;this.isShuttingDown=!0,options?.fromSignal&&(await this.runtimeHost.dispose(),this.themeController.disableAutoSync(),await this.ui.terminal.drainInput(1e3),this.stop(),process.exit(0)),this.themeController.disableAutoSync(),await this.ui.terminal.drainInput(1e3),this.stop(),await this.runtimeHost.dispose();let resumeCommand=formatResumeCommand(this.sessionManager);globalThis.__pinkExitBanner&&resumeCommand&&process.stdout.write(globalThis.__pinkExitBanner(resumeCommand)),!globalThis.__pinkExitBanner&&resumeCommand&&process.stdout.write(`${source_default.dim("To resume this session:")} ${resumeCommand}
|
|
994
994
|
`),process.exit(0)}emergencyTerminalExit(){this.isShuttingDown=!0,this.unregisterSignalHandlers(),killTrackedDetachedChildren(),process.exit(129)}uncaughtCrash(error){isDeadTerminalError(error)&&this.emergencyTerminalExit(),this.isShuttingDown&&process.exit(1),this.isShuttingDown=!0;try{this.unregisterSignalHandlers()}catch{}try{killTrackedDetachedChildren()}catch{}try{this.ui.stop()}catch{}console.error(`${APP_NAME} exiting due to uncaughtException:`),console.error(error);let extensionHint=this.getCrashExtensionHint(error);extensionHint&&console.error(`
|
|
995
995
|
${extensionHint}`),this.recordCrash("uncaught_exception",error)&&console.error(`
|
|
996
|
-
${this.crashReportInstructions()}`),process.exit(1)}async checkShutdownRequested(){this.shutdownRequested&&await this.shutdown()}registerSignalHandlers(){this.unregisterSignalHandlers();let signals=["SIGTERM"];process.platform!=="win32"&&signals.push("SIGHUP");for(let signal of signals){let handler=()=>{killTrackedDetachedChildren(),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 stream2 of[process.stdin,process.stdout,process.stderr])stream2.on("error",terminalErrorHandler),this.signalCleanupHandlers.push(()=>stream2.off("error",terminalErrorHandler));let uncaughtExceptionHandler=error=>this.uncaughtCrash(error);process.prependListener("uncaughtException",uncaughtExceptionHandler),this.signalCleanupHandlers.push(()=>process.off("uncaughtException",uncaughtExceptionHandler))}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(()=>{},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(this.session.isCompacting){this.isExtensionCommand(text)?(this.editor.addToHistory?.(text),this.editor.setText(""),await this.session.prompt(text)):this.queueCompactionMessage(text,"followUp");return}this.session.isStreaming?(this.editor.addToHistory?.(text),this.editor.setText(""),await this.session.prompt(text,{streamingBehavior:"followUp"}),this.updatePendingMessagesDisplay(),this.ui.requestRender()):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(){if(this.isBashMode)this.editor.borderColor=theme.getBashModeBorderColor();else{let level=this.session.thinkingLevel||"off";this.editor.borderColor=theme.getThinkingBorderColor(level)}this.activeStatusIndicator?.invalidate(),this.ui.requestRender()}cycleThinkingLevel(){let newLevel=this.session.cycleThinkingLevel();newLevel===void 0?this.showStatus("Current model does not support thinking"):(this.footer.invalidate(),this.updateEditorBorderColor(),this.showStatus(`Thinking level: ${newLevel}`))}async cycleModel(direction){try{let result=await this.session.cycleModel(direction);if(result===void 0){let msg=this.session.scopedModels.length>0?"Only one model in scope":"Only one model available";this.showStatus(msg)}else{this.footer.invalidate(),this.updateEditorBorderColor();let thinkingStr=result.model.reasoning&&result.thinkingLevel!=="off"?` (thinking: ${result.thinkingLevel})`:"";this.showStatus(`Switched to ${result.model.name||result.model.id}${thinkingStr}`),this.maybeWarnAboutAnthropicSubscriptionAuth(result.model)}}catch(error){this.showError(error instanceof Error?error.message:String(error))}}toggleToolOutputExpansion(){this.setToolsExpanded(!this.toolOutputExpanded)}setToolsExpanded(expanded){if(expanded===this.toolOutputExpanded)return;this.toolOutputExpanded=expanded;let activeHeader=this.customHeader??this.builtInHeader;isExpandable(activeHeader)&&activeHeader.setExpanded(expanded);for(let container of[this.loadedResourcesContainer,this.chatContainer])for(let child of container.children)isExpandable(child)&&child.setExpanded(expanded);this.showStatus(`Tool output: ${expanded?"expanded":"collapsed"}`)}updateThinkingBlockVisibility(){for(let child of this.chatContainer.children)child instanceof AssistantMessageComponent&&child.setHideThinkingBlock(this.hideThinkingBlock);this.ui.requestRender()}toggleThinkingBlockVisibility(){this.hideThinkingBlock=!this.hideThinkingBlock,globalThis.__pinkThinkingShown=!this.hideThinkingBlock,this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock),this.updateThinkingBlockVisibility(),this.showStatus(`Thinking blocks: ${this.hideThinkingBlock?"hidden":"visible"}`)}async handleOpenExternalEditor(){let editorCmd=this.settingsManager.getExternalEditorCommand(),content=this.editor.getExpandedText?.()??this.editor.getText();this.ui.stop();try{let result=await editInExternalEditor({command:editorCmd,content});result.status==="complete"&&this.editor.setText(result.content)}finally{this.ui.start(),this.ui.requestRender(!0)}}clearEditor(){this.editor.setText(""),this.ui.requestRender()}showError(errorMessage5){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("error",`Error: ${errorMessage5}`),this.outputPad,0)),this.ui.requestRender()}showWarning(warningMessage){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",`Warning: ${warningMessage}`),1,0)),this.ui.requestRender()}showNewVersionNotification(release2){let updateInstruction=()=>theme.fg("muted",`New version ${release2.version} is available. Run `)+theme.fg("accent",`${APP_NAME} update`),changelogUrl="https://github.com/ricardopiresqa/pink/blob/main/CHANGELOG.md",changelogLine=()=>{let changelogLink=getCapabilities().hyperlinks?hyperlink(theme.fg("accent",changelogUrl),changelogUrl):theme.fg("accent",changelogUrl);return theme.fg("muted","Changelog: ")+changelogLink},note=release2.note?.trim();this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new DynamicBorder(text=>theme.fg("warning",text))),this.chatContainer.addChild(new ThemedText(()=>`${theme.bold(theme.fg("warning","Update Available"))}
|
|
996
|
+
${this.crashReportInstructions()}`),process.exit(1)}async checkShutdownRequested(){this.shutdownRequested&&await this.shutdown()}registerSignalHandlers(){this.unregisterSignalHandlers();let signals=["SIGTERM"];process.platform!=="win32"&&signals.push("SIGHUP");for(let signal of signals){let handler=()=>{killTrackedDetachedChildren(),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 stream2 of[process.stdin,process.stdout,process.stderr])stream2.on("error",terminalErrorHandler),this.signalCleanupHandlers.push(()=>stream2.off("error",terminalErrorHandler));let uncaughtExceptionHandler=error=>this.uncaughtCrash(error);process.prependListener("uncaughtException",uncaughtExceptionHandler),this.signalCleanupHandlers.push(()=>process.off("uncaughtException",uncaughtExceptionHandler))}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(()=>{},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(this.session.isCompacting){this.isExtensionCommand(text)?(this.editor.addToHistory?.(text),this.editor.setText(""),await this.session.prompt(text)):this.queueCompactionMessage(text,"followUp");return}this.session.isStreaming?(this.editor.addToHistory?.(text),this.editor.setText(""),await this.session.prompt(text,{streamingBehavior:"followUp"}),this.updatePendingMessagesDisplay(),this.ui.requestRender()):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(){if(this.isBashMode)this.editor.borderColor=theme.getBashModeBorderColor();else{let level=this.session.thinkingLevel||"off";this.editor.borderColor=theme.getThinkingBorderColor(level)}this.activeStatusIndicator?.invalidate(),this.ui.requestRender()}cycleThinkingLevel(){let newLevel=this.session.cycleThinkingLevel();newLevel===void 0?this.showStatus("Current model does not support thinking"):(this.footer.invalidate(),this.updateEditorBorderColor(),this.showStatus(`Thinking level: ${newLevel}`))}async cycleModel(direction){try{let result=await this.session.cycleModel(direction,{persist:!!globalThis.__pinkRememberModel});if(result===void 0){let msg=this.session.scopedModels.length>0?"Only one model in scope":"Only one model available";this.showStatus(msg)}else{this.footer.invalidate(),this.updateEditorBorderColor();let thinkingStr=result.model.reasoning&&result.thinkingLevel!=="off"?` (thinking: ${result.thinkingLevel})`:"";this.showStatus(`Switched to ${result.model.name||result.model.id}${thinkingStr}`),this.maybeWarnAboutAnthropicSubscriptionAuth(result.model)}}catch(error){this.showError(error instanceof Error?error.message:String(error))}}toggleToolOutputExpansion(){this.setToolsExpanded(!this.toolOutputExpanded)}setToolsExpanded(expanded){if(expanded===this.toolOutputExpanded)return;this.toolOutputExpanded=expanded;let activeHeader=this.customHeader??this.builtInHeader;isExpandable(activeHeader)&&activeHeader.setExpanded(expanded);for(let container of[this.loadedResourcesContainer,this.chatContainer])for(let child of container.children)isExpandable(child)&&child.setExpanded(expanded);this.showStatus(`Tool output: ${expanded?"expanded":"collapsed"}`)}updateThinkingBlockVisibility(){for(let child of this.chatContainer.children)child instanceof AssistantMessageComponent&&child.setHideThinkingBlock(this.hideThinkingBlock);this.ui.requestRender()}toggleThinkingBlockVisibility(){this.hideThinkingBlock=!this.hideThinkingBlock,globalThis.__pinkThinkingShown=!this.hideThinkingBlock,this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock),this.updateThinkingBlockVisibility(),this.showStatus(`Thinking blocks: ${this.hideThinkingBlock?"hidden":"visible"}`)}async handleOpenExternalEditor(){let editorCmd=this.settingsManager.getExternalEditorCommand(),content=this.editor.getExpandedText?.()??this.editor.getText();this.ui.stop();try{let result=await editInExternalEditor({command:editorCmd,content});result.status==="complete"&&this.editor.setText(result.content)}finally{this.ui.start(),this.ui.requestRender(!0)}}clearEditor(){this.editor.setText(""),this.ui.requestRender()}showError(errorMessage5){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("error",`Error: ${errorMessage5}`),this.outputPad,0)),this.ui.requestRender()}showWarning(warningMessage){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",`Warning: ${warningMessage}`),1,0)),this.ui.requestRender()}showNewVersionNotification(release2){let updateInstruction=()=>theme.fg("muted",`New version ${release2.version} is available. Run `)+theme.fg("accent",`${APP_NAME} update`),changelogUrl="https://github.com/ricardopiresqa/pink/blob/main/CHANGELOG.md",changelogLine=()=>{let changelogLink=getCapabilities().hyperlinks?hyperlink(theme.fg("accent",changelogUrl),changelogUrl):theme.fg("accent",changelogUrl);return theme.fg("muted","Changelog: ")+changelogLink},note=release2.note?.trim();this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new DynamicBorder(text=>theme.fg("warning",text))),this.chatContainer.addChild(new ThemedText(()=>`${theme.bold(theme.fg("warning","Update Available"))}
|
|
997
997
|
${updateInstruction()}`,1,0)),note&&(this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new Markdown(note,1,0,this.getMarkdownThemeWithSettings(),{color:text=>theme.fg("muted",text)})),this.chatContainer.addChild(new Spacer(1))),this.chatContainer.addChild(new ThemedText(changelogLine,1,0)),this.chatContainer.addChild(new DynamicBorder(text=>theme.fg("warning",text))),this.ui.requestRender()}showPackageUpdateNotification(packages){let updateInstruction=()=>theme.fg("muted","Package updates are available. Run ")+theme.fg("accent",`${APP_NAME} update --extensions`),packageLines=packages.map(pkg=>`- ${pkg}`).join(`
|
|
998
998
|
`);this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new DynamicBorder(text=>theme.fg("warning",text))),this.chatContainer.addChild(new ThemedText(()=>`${theme.bold(theme.fg("warning","Package Updates Available"))}
|
|
999
999
|
${updateInstruction()}
|
|
@@ -1002,7 +1002,7 @@ ${packageLines}`,1,0)),this.chatContainer.addChild(new DynamicBorder(text=>theme
|
|
|
1002
1002
|
|
|
1003
1003
|
`),currentText=options?.currentText??this.editor.getText(),combinedText=[queuedText,currentText].filter(t=>t.trim()).join(`
|
|
1004
1004
|
|
|
1005
|
-
`);return this.editor.setText(combinedText),this.updatePendingMessagesDisplay(),options?.abort&&this.session.abort(),allQueued.length}queueCompactionMessage(text,mode){this.compactionQueuedMessages.push({text,mode}),this.editor.addToHistory?.(text),this.editor.setText(""),this.updatePendingMessagesDisplay(),this.showStatus("Queued message for after compaction")}isExtensionCommand(text){if(!text.startsWith("/"))return!1;let extensionRunner=this.session.extensionRunner,spaceIndex=text.indexOf(" "),commandName=spaceIndex===-1?text.slice(1):text.slice(1,spaceIndex);return!!extensionRunner.getCommand(commandName)}async flushCompactionQueue(options){if(this.compactionQueuedMessages.length===0)return;let queuedMessages=[...this.compactionQueuedMessages];this.compactionQueuedMessages=[],this.updatePendingMessagesDisplay();let restoreQueue=error=>{this.session.clearQueue(),this.compactionQueuedMessages=queuedMessages,this.updatePendingMessagesDisplay(),this.showError(`Failed to send queued message${queuedMessages.length>1?"s":""}: ${error instanceof Error?error.message:String(error)}`)};try{if(options?.willRetry){for(let message of queuedMessages)this.isExtensionCommand(message.text)?await this.session.prompt(message.text):message.mode==="followUp"?await this.session.followUp(message.text):await this.session.steer(message.text);this.updatePendingMessagesDisplay();return}let firstPromptIndex=queuedMessages.findIndex(message=>!this.isExtensionCommand(message.text));if(firstPromptIndex===-1){for(let message of queuedMessages)await this.session.prompt(message.text);return}let preCommands=queuedMessages.slice(0,firstPromptIndex),firstPrompt=queuedMessages[firstPromptIndex],rest=queuedMessages.slice(firstPromptIndex+1);for(let message of preCommands)await this.session.prompt(message.text);let promptPromise=this.session.prompt(firstPrompt.text,{streamingBehavior:firstPrompt.mode}).catch(error=>{restoreQueue(error)});for(let message of rest)this.isExtensionCommand(message.text)?await this.session.prompt(message.text):message.mode==="followUp"?await this.session.followUp(message.text):await this.session.steer(message.text);this.updatePendingMessagesDisplay()}catch(error){restoreQueue(error)}}flushPendingBashComponents(){for(let component of this.pendingBashComponents)this.pendingMessagesContainer.removeChild(component),this.chatContainer.addChild(component);this.pendingBashComponents=[]}disposeActiveSelector(){let dispose=this.activeSelectorDispose;this.activeSelectorToken=void 0,this.activeSelectorDispose=void 0,dispose?.()}showSelector(create){let token={},dispose,created=create(()=>{dispose?.(),this.activeSelectorToken===token&&(this.activeSelectorToken=void 0,this.activeSelectorDispose=void 0,this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor))});dispose=created.dispose,this.disposeActiveSelector(),this.activeSelectorToken=token,this.activeSelectorDispose=dispose,this.editorContainer.clear(),this.editorContainer.addChild(created.component),this.ui.setFocus(created.focus),this.ui.requestRender()}showSettingsSelector(){this.showSelector(done=>{let selector,defaultProvider=this.settingsManager.getDefaultProvider(),defaultModelId=this.settingsManager.getDefaultModel(),defaultModel=defaultProvider&&defaultModelId?`${defaultProvider}/${defaultModelId}`:"not set";return selector=new SettingsSelectorComponent({autoCompact:this.session.autoCompactionEnabled,defaultModel,currentModel:this.session.model,availableDefaultModels:this.session.modelRuntime.getAvailableSnapshot(),showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells(),autoResizeImages:this.settingsManager.getImageAutoResize(),blockImages:this.settingsManager.getBlockImages(),enableSkillCommands:this.settingsManager.getEnableSkillCommands(),steeringMode:this.session.steeringMode,followUpMode:this.session.followUpMode,transport:this.settingsManager.getTransport(),sessionShareDestination:this.settingsManager.getSessionShareDestination(),httpIdleTimeoutMs:this.settingsManager.getHttpIdleTimeoutMs(),cacheWarmingMode:this.settingsManager.getCacheWarmingMode(),thinkingLevel:this.settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL,availableThinkingLevels:[...THINKING_LEVEL_OPTIONS],modelThinkingLevels:this.settingsManager.getAllModelThinkingLevels(),currentTheme:this.themeController.getThemeSelection()||SYSTEM_THEME_NAME,terminalTheme:this.themeController.getTerminalTheme(),availableThemes:getAvailableThemes(),hideThinkingBlock:this.hideThinkingBlock,mermaidRenderingMode:this.settingsManager.getMermaidRenderingMode(),collapseChangelog:this.settingsManager.getCollapseChangelog(),enableInstallTelemetry:this.settingsManager.getEnableInstallTelemetry(),doubleEscapeAction:this.settingsManager.getDoubleEscapeAction(),treeFilterMode:this.settingsManager.getTreeFilterMode(),showHardwareCursor:this.settingsManager.getShowHardwareCursor(),showCacheMissNotices:this.settingsManager.getShowCacheMissNotices(),defaultProjectTrust:this.settingsManager.getDefaultProjectTrust(),editorPaddingX:this.settingsManager.getEditorPaddingX(),outputPad:this.settingsManager.getOutputPad(),autocompleteMaxVisible:this.settingsManager.getAutocompleteMaxVisible(),quietStartup:this.settingsManager.getQuietStartup(),clearOnShrink:this.settingsManager.getClearOnShrink(),showTerminalProgress:this.settingsManager.getShowTerminalProgress(),tuiMode:this.ui.mode,fullscreenExitOutput:this.settingsManager.getFullscreenExitOutput(),fullscreenScrollbar:this.settingsManager.getFullscreenScrollbar(),fullscreenCopyOnSelect:this.settingsManager.getFullscreenCopyOnSelect(),fullscreenWheelScrollLines:this.settingsManager.getFullscreenWheelScrollLines(),warnings:this.settingsManager.getWarnings()},{onAutoCompactChange:enabled=>{this.session.setAutoCompactionEnabled(enabled),this.footer.setAutoCompactEnabled(enabled)},onShowImagesChange:enabled=>{this.settingsManager.setShowImages(enabled);for(let child of this.chatContainer.children)child instanceof ToolExecutionComponent&&child.setShowImages(enabled)},onImageWidthCellsChange:width=>{this.settingsManager.setImageWidthCells(width);for(let child of this.chatContainer.children)child instanceof ToolExecutionComponent&&child.setImageWidthCells(width)},onAutoResizeImagesChange:enabled=>{this.settingsManager.setImageAutoResize(enabled)},onBlockImagesChange:blocked=>{this.settingsManager.setBlockImages(blocked)},onEnableSkillCommandsChange:enabled=>{this.settingsManager.setEnableSkillCommands(enabled),this.setupAutocompleteProvider()},onSteeringModeChange:mode=>{this.session.setSteeringMode(mode)},onFollowUpModeChange:mode=>{this.session.setFollowUpMode(mode)},onTransportChange:transport=>{this.settingsManager.setTransport(transport),this.session.agent.transport=transport},onSessionShareDestinationChange:destination=>{this.settingsManager.setSessionShareDestination(destination)},onHttpIdleTimeoutMsChange:timeoutMs=>{this.settingsManager.setHttpIdleTimeoutMs(timeoutMs),configureHttpDispatcher(timeoutMs),this.showStatus(`HTTP idle timeout: ${formatHttpIdleTimeoutMs(timeoutMs)}`)},onCacheWarmingModeChange:mode=>{this.session.setCacheWarmingMode(mode),this.showStatus(`Cache warming: ${mode}`)},onModelThinkingLevelChange:(provider,modelId,level)=>{this.settingsManager.setModelThinkingLevel(provider,modelId,level);let current=this.session.model;current&¤t.provider===provider&¤t.id===modelId&&(this.session.setThinkingLevel(level),this.footer.invalidate(),this.updateEditorBorderColor())},onModelThinkingLevelRemove:(provider,modelId)=>{this.settingsManager.removeModelThinkingLevel(provider,modelId);let current=this.session.model;if(current&¤t.provider===provider&¤t.id===modelId){let globalDefault=this.settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL;this.session.setThinkingLevel(globalDefault),this.footer.invalidate(),this.updateEditorBorderColor()}},onThemeChange:themeSetting=>{this.settingsManager.setTheme(themeSetting),this.themeController.setThemeSetting(themeSetting)},onThemePreview:themeName=>this.themeController.preview(themeName),onHideThinkingBlockChange:hidden=>{this.hideThinkingBlock=hidden,this.settingsManager.setHideThinkingBlock(hidden),this.updateThinkingBlockVisibility()},onMermaidRenderingModeChange:mode=>{this.settingsManager.setMermaidRenderingMode(mode),this.chatContainer.invalidate(),this.ui.requestRender()},onShowCacheMissNoticesChange:shown=>{this.settingsManager.setShowCacheMissNotices(shown),this.rebuildChatFromMessages()},onCollapseChangelogChange:collapsed=>{this.settingsManager.setCollapseChangelog(collapsed)},onEnableInstallTelemetryChange:enabled=>{this.settingsManager.setEnableInstallTelemetry(enabled)},onQuietStartupChange:quiet=>{this.settingsManager.setQuietStartup(quiet)},onDefaultProjectTrustChange:defaultProjectTrust=>{this.settingsManager.setDefaultProjectTrust(defaultProjectTrust)},onDoubleEscapeActionChange:action=>{this.settingsManager.setDoubleEscapeAction(action)},onTreeFilterModeChange:mode=>{this.settingsManager.setTreeFilterMode(mode)},onShowHardwareCursorChange:enabled=>{this.settingsManager.setShowHardwareCursor(enabled),this.ui.setShowHardwareCursor(enabled)},onEditorPaddingXChange:padding=>{this.settingsManager.setEditorPaddingX(padding),this.defaultEditor.setPaddingX(padding),this.editor!==this.defaultEditor&&this.editor.setPaddingX!==void 0&&this.editor.setPaddingX(padding)},onOutputPadChange:padding=>{this.settingsManager.setOutputPad(padding),this.outputPad=padding;for(let container of[this.chatContainer,this.pendingMessagesContainer])for(let child of container.children)"setOutputPad"in child&&typeof child.setOutputPad=="function"&&child.setOutputPad(padding);this.ui.requestRender()},onAutocompleteMaxVisibleChange:maxVisible=>{this.settingsManager.setAutocompleteMaxVisible(maxVisible),this.defaultEditor.setAutocompleteMaxVisible(maxVisible),this.editor!==this.defaultEditor&&this.editor.setAutocompleteMaxVisible!==void 0&&this.editor.setAutocompleteMaxVisible(maxVisible)},onClearOnShrinkChange:enabled=>{this.settingsManager.setClearOnShrink(enabled),this.ui.setClearOnShrink(enabled),!enabled&&!this.activeStatusIndicator&&this.statusContainer.clear()},onShowTerminalProgressChange:enabled=>{this.settingsManager.setShowTerminalProgress(enabled)},onTuiModeChange:mode=>{if(!this.switchTuiMode(mode)){selector?.getSettingsList().updateValue("tui-mode",this.ui.mode),this.showStatus("Close active overlays before changing TUI mode");return}this.settingsManager.setTuiMode(mode),this.activeStatusIndicator||this.statusContainer.clear(),this.showStatus(`TUI mode: ${mode}`)},onFullscreenExitOutputChange:output=>{this.settingsManager.setFullscreenExitOutput(output)},onFullscreenScrollbarChange:mode=>{this.settingsManager.setFullscreenScrollbar(mode),this.applyFullscreenScrollbarSetting()},onFullscreenCopyOnSelectChange:enabled=>{this.settingsManager.setFullscreenCopyOnSelect(enabled),this.renderer instanceof TuiAltScreen&&this.renderer.setCopyOnSelect(enabled)},onFullscreenWheelScrollLinesChange:lines=>{this.settingsManager.setFullscreenWheelScrollLines(lines),this.renderer instanceof TuiAltScreen&&this.renderer.setWheelScrollLines(lines)},onWarningsChange:warnings=>{this.settingsManager.setWarnings(warnings)},onCancel:()=>{done(),this.ui.requestRender()}}),{component:selector,focus:selector.getSettingsList()}})}handleThinkingCommand(searchTerm){let availableLevels=this.session.getAvailableThinkingLevels();if(!searchTerm){this.showThinkingSelector();return}let normalized=searchTerm.trim().toLowerCase(),level=availableLevels.find(candidate=>candidate.toLowerCase()===normalized);if(!level){this.showError(`Unknown thinking level "${searchTerm}". Available levels: ${availableLevels.join(", ")}.`);return}this.selectThinkingLevel(level,!1)}selectThinkingLevel(level,persist){try{this.session.setThinkingLevel(level,{persist}),this.footer.invalidate(),this.updateEditorBorderColor(),this.showStatus(persist?`Default thinking level: ${level}`:`Thinking level: ${level}`)}catch(error){this.showError(error instanceof Error?error.message:String(error))}}showThinkingSelector(){this.showSelector(done=>{let selectLevel=(level,persist)=>{this.selectThinkingLevel(level,persist),done()},selector=new ThinkingSelectorComponent(this.session.thinkingLevel??DEFAULT_THINKING_LEVEL,this.session.getAvailableThinkingLevels(),level=>selectLevel(level,!1),()=>{done(),this.ui.requestRender()},level=>selectLevel(level,!0),this.settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL);return{component:selector,focus:selector}})}async handleModelCommand(searchTerm){if(!searchTerm){this.showModelSelector();return}let model=await this.findExactModelMatch(searchTerm);if(model){try{await this.session.setModel(model,{persist:!1}),this.footer.invalidate(),this.updateEditorBorderColor(),this.showStatus(`Model: ${model.id}`),this.maybeWarnAboutAnthropicSubscriptionAuth(model)}catch(error){this.showError(error instanceof Error?error.message:String(error))}return}this.showModelSelector(searchTerm)}async findExactModelMatch(searchTerm){let cachedModels=this.session.scopedModels.length>0?this.session.scopedModels.map(scoped=>scoped.model):[...this.session.modelRuntime.getAvailableSnapshot()],cachedMatch=findExactModelReferenceMatch(searchTerm,cachedModels);if(cachedMatch||this.session.scopedModels.length>0)return cachedMatch;this.showStatus("Refreshing model catalogs\u2026");let controller=new AbortController,timedOut=!1,timeout=setTimeout(()=>{timedOut=!0,controller.abort()},15e3);try{let result=await refreshModelCatalogs(this.session.modelRuntime,controller.signal);result.aborted&&timedOut?this.showWarning("Model refresh timed out; searching cached models."):result.errors.size>0&&this.showWarning(`Could not refresh ${[...result.errors.keys()].join(", ")}; searching cached models.`)}catch(error){this.showWarning(timedOut?"Model refresh timed out; searching cached models.":`Could not refresh model catalogs: ${error instanceof Error?error.message:String(error)}`)}finally{clearTimeout(timeout)}return findExactModelReferenceMatch(searchTerm,[...this.session.modelRuntime.getAvailableSnapshot()])}updateAvailableProviderCount(){let models=this.session.scopedModels.length>0?this.session.scopedModels.map(scoped=>scoped.model):this.session.modelRuntime.getAvailableSnapshot(),uniqueProviders=new Set(models.map(model=>model.provider));this.footerDataProvider.setAvailableProviderCount(uniqueProviders.size)}async maybeWarnAboutAnthropicSubscriptionAuth(model=this.session.model){if(this.settingsManager.getWarnings().anthropicExtraUsage!==!1&&!this.anthropicSubscriptionWarningShown&&!(!model||model.provider!=="anthropic"))try{if((await this.session.modelRuntime.checkAuth("anthropic"))?.type==="oauth"){this.anthropicSubscriptionWarningShown=!0,this.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);return}let apiKey=(await this.session.modelRuntime.getAuth(model.provider))?.auth.apiKey;if(!isAnthropicSubscriptionAuthKey(apiKey))return;this.anthropicSubscriptionWarningShown=!0,this.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING)}catch{}}maybeSaveImplicitProjectTrustAfterReload(){let cwd=this.sessionManager.getCwd();if(this.autoTrustOnReloadCwd!==cwd||!this.settingsManager.isProjectTrusted()||!hasTrustRequiringProjectResources(cwd))return!1;let trustStore=new ProjectTrustStore(this.runtimeHost.services.agentDir);try{return trustStore.get(cwd)!==null?(this.autoTrustOnReloadCwd=void 0,!1):(trustStore.set(cwd,!0),this.autoTrustOnReloadCwd=void 0,!0)}catch(error){return this.showWarning(`Could not save project trust after reload: ${error instanceof Error?error.message:String(error)}`),!1}}showTrustSelector(){let cwd=this.sessionManager.getCwd(),trustStore=new ProjectTrustStore(this.runtimeHost.services.agentDir),savedDecision=trustStore.getEntry(cwd);this.showSelector(done=>{let selector=new TrustSelectorComponent({cwd,savedDecision,projectTrusted:this.settingsManager.isProjectTrusted(),onSelect:selection=>{trustStore.setMany(selection.updates),done(),this.showStatus(`Saved trust decision: ${selection.trusted?"trusted":"untrusted"}. Restart ${APP_NAME} for this to take effect.`)},onCancel:()=>{done(),this.ui.requestRender()}});return{component:selector,focus:selector}})}showModelSelector(initialSearchInput){this.showSelector(done=>{let selectModel=async(model,persist)=>{try{await this.session.setModel(model,{persist}),this.updateAvailableProviderCount(),this.footer.invalidate(),this.updateEditorBorderColor(),done(),this.showStatus(persist?`Default model: ${model.provider}/${model.id}`:`Model: ${model.id}`),this.maybeWarnAboutAnthropicSubscriptionAuth(model)}catch(error){done(),this.showError(error instanceof Error?error.message:String(error))}},defaultProvider=this.settingsManager.getDefaultProvider(),defaultModel=this.settingsManager.getDefaultModel(),selector=new ModelSelectorComponent(this.ui,this.session.model,this.session.modelRuntime,this.session.scopedModels,model=>selectModel(model,!1),()=>{done(),this.ui.requestRender()},initialSearchInput,model=>selectModel(model,!0),defaultProvider&&defaultModel?{provider:defaultProvider,id:defaultModel}:void 0);return{component:selector,focus:selector,dispose:()=>selector.dispose()}})}showModelsSelector(){let availableModels=[...this.session.modelRuntime.getAvailableSnapshot()],availableModelIds=new Set(availableModels.map(model=>`${model.provider}/${model.id}`)),configuredPatterns=this.settingsManager.getEnabledModels(),sessionScopedModels=this.session.scopedModels,configuredEnabledIds=models=>{if(!configuredPatterns?.length)return null;let resolved=resolveModelScopeFromModels(configuredPatterns,models),ids=resolved.scopedModels.map(scoped=>`${scoped.model.provider}/${scoped.model.id}`);for(let diagnostic of resolved.diagnostics)diagnostic.code==="no-match"&&!ids.includes(diagnostic.pattern)&&ids.push(diagnostic.pattern);return ids},currentEnabledIds=sessionScopedModels.length>0?sessionScopedModels.map(scoped=>`${scoped.model.provider}/${scoped.model.id}`):configuredEnabledIds(availableModels),selectionChanged=!1,updateSessionModels=enabledIds=>{currentEnabledIds=enabledIds===null?null:[...enabledIds];let hasEnabledAvailableModel=enabledIds?.some(id=>availableModelIds.has(id))??!1,allAvailableModelsEnabled=enabledIds!==null&&[...availableModelIds].every(id=>enabledIds.includes(id));if(enabledIds&&hasEnabledAvailableModel&&!allAvailableModelsEnabled){let newScopedModels=resolveModelScopeFromModels(enabledIds,availableModels).scopedModels;this.session.setScopedModels(newScopedModels.map(scoped=>({model:scoped.model,thinkingLevel:scoped.thinkingLevel})))}else this.session.setScopedModels([]);this.updateAvailableProviderCount(),this.ui.requestRender()};this.showSelector(done=>{let disposed=!1,timedOut=!1,controller=new AbortController,timeout=setTimeout(()=>{timedOut=!0,controller.abort()},15e3),selector=new ScopedModelsSelectorComponent({allModels:availableModels,enabledModelIds:currentEnabledIds,refreshStatus:"Refreshing model catalogs\u2026"},{onChange:enabledIds=>{selectionChanged=!0,updateSessionModels(enabledIds)},onPersist:enabledIds=>{let allEnabled=enabledIds!==null&&enabledIds.length===availableModels.length&&enabledIds.every(id=>availableModelIds.has(id)),newPatterns=enabledIds===null||allEnabled?void 0:enabledIds;this.settingsManager.setEnabledModels(newPatterns?[...newPatterns]:void 0),this.showStatus("Model selection saved to settings")},onCancel:()=>{done(),this.ui.requestRender()}});return refreshModelCatalogs(this.session.modelRuntime,controller.signal).then(result=>{disposed||(availableModels=[...this.session.modelRuntime.getAvailableSnapshot()],availableModelIds=new Set(availableModels.map(model=>`${model.provider}/${model.id}`)),!selectionChanged&&sessionScopedModels.length===0?(currentEnabledIds=configuredEnabledIds(availableModels),selector.updateModels(availableModels,currentEnabledIds)):selector.updateModels(availableModels),currentEnabledIds!==null&&updateSessionModels(currentEnabledIds),result.aborted&&timedOut?selector.setRefreshStatus("Model refresh timed out; showing cached models.","warning"):result.errors.size>0?selector.setRefreshStatus(`Could not refresh ${[...result.errors.keys()].join(", ")}; showing cached models.`,"warning"):selector.setRefreshStatus("Model catalogs refreshed.","success"),this.ui.requestRender())}).catch(error=>{disposed||(selector.setRefreshStatus(timedOut?"Model refresh timed out; showing cached models.":`Could not refresh model catalogs: ${error instanceof Error?error.message:String(error)}`,"warning"),this.ui.requestRender())}).finally(()=>clearTimeout(timeout)),{component:selector,focus:selector,dispose:()=>{disposed=!0,clearTimeout(timeout),controller.abort()}}})}showUserMessageSelector(){let userMessages=this.session.getUserMessagesForForking();if(userMessages.length===0){this.showStatus("No messages to fork from");return}let initialSelectedId=userMessages[userMessages.length-1]?.entryId;this.showSelector(done=>{let selector=new UserMessageSelectorComponent(userMessages.map(m=>({id:m.entryId,text:m.text})),async entryId=>{done();try{let result=await this.runtimeHost.fork(entryId);if(result.cancelled){this.ui.requestRender();return}this.editor.setText(result.selectedText??""),this.showStatus("Forked to new session")}catch(error){this.showError(error instanceof Error?error.message:String(error))}},()=>{done(),this.ui.requestRender()},initialSelectedId);return{component:selector,focus:selector.getMessageList()}})}async handleCloneCommand(){let leafId=this.sessionManager.getLeafId();if(!leafId){this.showStatus("Nothing to clone yet");return}try{if((await this.runtimeHost.fork(leafId,{position:"at"})).cancelled){this.ui.requestRender();return}this.editor.setText(""),this.showStatus("Cloned to new session")}catch(error){this.showError(error instanceof Error?error.message:String(error))}}showTreeSelector(initialSelectedId){let tree=this.sessionManager.getTree(),realLeafId=this.sessionManager.getLeafId(),initialFilterMode=this.settingsManager.getTreeFilterMode();if(tree.length===0){this.showStatus("No entries in session");return}this.showSelector(done=>{let selector=new TreeSelectorComponent(tree,realLeafId,this.ui.terminal.rows,async entryId=>{if(entryId===this.sessionManager.getLeafId()){done(),this.showStatus("Already at this point");return}done();let wantsSummary=!1,customInstructions;if(!this.settingsManager.getBranchSummarySkipPrompt())for(;;){let summaryChoice=await this.showExtensionSelector("Summarize branch?",["No summary","Summarize","Summarize with custom prompt"]);if(summaryChoice===void 0){this.showTreeSelector(entryId);return}if(wantsSummary=summaryChoice!=="No summary",!(summaryChoice==="Summarize with custom prompt"&&(customInstructions=await this.showExtensionEditor("Custom summarization instructions"),customInstructions===void 0)))break}if(this.session.isStreaming&&(this.restoreQueuedMessagesToEditor(),await this.session.abort()),this.session.isCompacting){this.showError("Wait for the current compaction or tree navigation to finish before navigating the session tree.");return}let showingSummaryIndicator=!1,originalOnEscape=this.defaultEditor.onEscape;wantsSummary&&(this.defaultEditor.onEscape=()=>{this.session.abortBranchSummary()},this.chatContainer.addChild(new Spacer(1)),this.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui)),showingSummaryIndicator=!0,this.ui.requestRender());try{let result=await this.session.navigateTree(entryId,{summarize:wantsSummary,customInstructions});if(result.aborted){this.showStatus("Branch summarization cancelled"),this.showTreeSelector(entryId);return}if(result.cancelled){this.showStatus("Navigation cancelled");return}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})}catch(error){this.showError(error instanceof Error?error.message:String(error))}finally{showingSummaryIndicator&&this.clearStatusIndicator("branchSummary"),this.defaultEditor.onEscape=originalOnEscape}},()=>{done(),this.ui.requestRender()},(entryId,label)=>{this.sessionManager.appendLabelChange(entryId,label),this.ui.requestRender()},initialSelectedId,initialFilterMode);return selector.onCopy=async text=>{if(!text){this.showError("Selected entry has no text to copy");return}try{await copyToClipboard(text),this.showStatus("Copied selected message to clipboard")}catch(error){this.showError(error instanceof Error?error.message:String(error))}},{component:selector,focus:selector}})}showSessionSelector(){this.showSelector(done=>{let selector=new SessionSelectorComponent((onProgress,signal)=>SessionManager.list(this.sessionManager.getCwd(),this.sessionManager.getSessionDir(),onProgress,signal),(onProgress,signal)=>this.sessionManager.usesDefaultSessionDir()?SessionManager.listAll(onProgress,signal):SessionManager.listAll(this.sessionManager.getSessionDir(),onProgress,signal),async sessionPath=>{done(),await this.handleResumeSession(sessionPath)},()=>{done(),this.ui.requestRender()},()=>{this.shutdown()},()=>this.ui.requestRender(),{renameSession:async(sessionFilePath,nextName)=>{let next=(nextName??"").trim();if(!next)return;SessionManager.open(sessionFilePath).appendSessionInfo(next)},showRenameHint:!0,keybindings:this.keybindings},this.sessionManager.getSessionFile());return{component:selector,focus:selector}})}async handleResumeSession(sessionPath,options){this.clearStatusIndicator();try{let result=await this.runtimeHost.switchSession(sessionPath,{withSession:options?.withSession,projectTrustContextFactory:cwd=>this.createProjectTrustContext(cwd)});return result.cancelled||this.showStatus("Resumed session"),result}catch(error){if(error instanceof MissingSessionCwdError){let selectedCwd=await this.promptForMissingSessionCwd(error);if(!selectedCwd)return this.showStatus("Resume cancelled"),{cancelled:!0};let result=await this.runtimeHost.switchSession(sessionPath,{cwdOverride:selectedCwd,withSession:options?.withSession,projectTrustContextFactory:cwd=>this.createProjectTrustContext(cwd)});return result.cancelled||this.showStatus("Resumed session in current cwd"),result}return this.handleFatalRuntimeError("Failed to resume session",error)}}getLoginProviderOptions(authType){let options=[];for(let provider of this.session.modelRuntime.getProviders()){let authStatus=this.session.modelRuntime.getProviderAuthStatus(provider.id),status=authStatus.configured?{type:this.session.modelRuntime.isUsingOAuth(provider.id)?"oauth":"api_key",source:authStatus.label??authStatus.source}:void 0,subscription=provider.auth.oauth?.isSubscription===!0;(!authType||authType==="oauth")&&provider.auth.oauth&&options.push({id:provider.id,name:provider.name,authType:"oauth",method:provider.auth.oauth,status,subscription}),(!authType||authType==="api_key")&&provider.auth.apiKey&&options.push({id:provider.id,name:provider.name,authType:"api_key",method:provider.auth.apiKey,status,subscription})}return options.sort((a,b)=>a.name.localeCompare(b.name))}async getLogoutProviderOptions(){return(await this.session.modelRuntime.listCredentials({signal:AbortSignal.timeout(15e3)})).map(({providerId,type})=>{let provider=this.session.modelRuntime.getProvider(providerId);return{id:providerId,name:provider?.name??providerId,authType:type,status:{type,source:"stored credential"},subscription:provider?.auth.oauth?.isSubscription===!0}}).sort((a,b)=>a.name.localeCompare(b.name))}findLoginProviderOptions(providerRef){let normalizedProviderRef=providerRef.trim().toLowerCase();return normalizedProviderRef?this.getLoginProviderOptions().filter(provider=>provider.id.toLowerCase()===normalizedProviderRef||provider.name.toLowerCase()===normalizedProviderRef):[]}async handleLoginCommand(providerRef){if(!providerRef){this.showLoginAuthTypeSelector();return}let providerOptions=this.findLoginProviderOptions(providerRef);if(providerOptions.length===1){await this.startProviderLogin(providerOptions[0]);return}if(providerOptions.length>1&&new Set(providerOptions.map(provider=>provider.id)).size===1){this.showLoginAuthTypeSelector(providerOptions);return}this.showLoginProviderSelector(void 0,providerRef)}async startProviderLogin(providerOption,onBack){providerOption.authType==="oauth"?await this.showLoginDialog(providerOption.id,providerOption.name,onBack):providerOption.method?.login?await this.showApiKeyLoginDialog(providerOption.id,providerOption.name,onBack):this.showAmbientAuthDialog(providerOption,onBack)}showLoginAuthTypeSelector(providerOptions){let radiusOption=providerOptions?void 0:this.getLoginProviderOptions("oauth").find(provider=>provider.id===RADIUS_PROVIDER_ID),radiusText=radiusOption?`Sign in with ${radiusOption.name}`:void 0,radiusLabel=radiusOption?`${radiusText}${formatAuthSelectorProviderStatus(radiusOption)}`:void 0,oauthProvider=providerOptions?.find(provider=>provider.authType==="oauth"),subscriptionLabel=(oauthProvider?.method&&"loginLabel"in oauthProvider.method?oauthProvider.method.loginLabel:void 0)??"Sign in with an account",apiKeyLabel="Sign in with an API key",availableAuthTypes=providerOptions?new Set(providerOptions.map(provider=>provider.authType)):new Set(["oauth","api_key"]),options=[];if(availableAuthTypes.has("oauth")&&options.push(subscriptionLabel),availableAuthTypes.has("api_key")&&options.push(apiKeyLabel),radiusLabel&&options.push(radiusLabel),options.length===0){this.showStatus("No login methods available.");return}if(providerOptions&&options.length===1){let providerOption=providerOptions[0];providerOption&&this.startProviderLogin(providerOption);return}let title=providerOptions?.[0]?`Select authentication method for ${providerOptions[0].name}:`:"Select authentication method:";this.showSelector(done=>{let onSelect=option=>{if(done(),radiusOption&&option===radiusLabel){this.startProviderLogin(radiusOption,()=>this.showLoginAuthTypeSelector());return}let authType=option===subscriptionLabel?"oauth":"api_key";if(providerOptions){let providerOption=providerOptions.find(provider=>provider.authType===authType);providerOption&&this.startProviderLogin(providerOption,()=>this.showLoginAuthTypeSelector(providerOptions));return}this.showLoginProviderSelector(authType)},onCancel=()=>{done(),this.ui.requestRender()},selector=radiusLabel&&radiusText?createLoginMenuSelector(this.ui,title,options,{label:radiusLabel,text:radiusText},onSelect,onCancel):new ExtensionSelectorComponent(title,options,onSelect,onCancel);return{component:selector,focus:selector,dispose:()=>selector.dispose()}})}showLoginProviderSelector(authType,initialSearchInput){let providerOptions=this.getLoginProviderOptions(authType);if(providerOptions.length===0){let message=authType==="oauth"?"No account providers available.":authType==="api_key"?"No API key providers available.":"No login providers available.";this.showStatus(message);return}this.showSelector(done=>{let selector=new OAuthSelectorComponent("login",providerOptions,async(providerId,selectedAuthType)=>{done();let providerOption=providerOptions.find(provider=>provider.id===providerId&&provider.authType===selectedAuthType);providerOption&&await this.startProviderLogin(providerOption,()=>this.showLoginProviderSelector(authType,initialSearchInput))},()=>{done(),authType?this.showLoginAuthTypeSelector():this.ui.requestRender()},initialSearchInput);return{component:selector,focus:selector}})}async showOAuthSelector(mode){if(mode==="login"){this.showLoginAuthTypeSelector();return}let providerOptions;try{providerOptions=await this.getLogoutProviderOptions()}catch(error){this.showError(`Could not read stored credentials: ${error instanceof Error?error.message:String(error)}`);return}if(providerOptions.length===0){this.showStatus("No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.");return}this.showSelector(done=>{let selector=new OAuthSelectorComponent(mode,providerOptions,async providerId=>{done();let providerOption=providerOptions.find(provider=>provider.id===providerId);if(providerOption)try{await this.session.modelRuntime.logout(providerOption.id,{signal:AbortSignal.timeout(15e3)}),await this.updateAvailableProviderCount();let message=providerOption.authType==="oauth"?`Logged out of ${providerOption.name}`:`Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;this.showStatus(message)}catch(error){let message=error instanceof Error?error.message:String(error);this.showError(error instanceof CredentialSynchronizationError?`Credentials removed for ${providerOption.name}, but local model state could not be synchronized: ${message}`:`Logout failed: ${message}`)}},()=>{done(),this.ui.requestRender()});return{component:selector,focus:selector}})}async completeProviderAuthentication(providerId,providerName,authType,previousModel){let actionLabel=authType==="oauth"?`Logged in to ${providerName}`:`Saved API key for ${providerName}`,session=this.session,deferSelection=isUnknownModel(previousModel)&&hasDefaultModelProvider(providerId)&&!session.modelRuntime.getAvailableSnapshot().some(model=>model.provider===providerId&&model.id===defaultModelPerProvider[providerId]),finishAuthentication=async()=>{let selectedModel,selectionError;if(isUnknownModel(previousModel)){let providerModels=this.session.modelRuntime.getAvailableSnapshot().filter(model=>model.provider===providerId);if(providerId==="llama.cpp")selectionError=llamaCppPostLoginGuidance(actionLabel,providerModels.length);else if(!hasDefaultModelProvider(providerId))selectionError=`${actionLabel}, but no default model is configured for provider "${providerId}". Use /model to select a model.`;else if(providerModels.length===0)selectionError=`${actionLabel}, but no models are available for that provider. Use /model to select a model.`;else{let defaultModelId=defaultModelPerProvider[providerId];if(selectedModel=providerModels.find(model=>model.id===defaultModelId)??(providerId==="radius"?providerModels[0]:void 0),!selectedModel)selectionError=`${actionLabel}, but its default model "${defaultModelId}" is not available. Use /model to select a model.`;else try{await this.session.setModel(selectedModel,{persist:!0})}catch(error){selectedModel=void 0;let errorMessage5=error instanceof Error?error.message:String(error);selectionError=`${actionLabel}, but selecting its default model failed: ${errorMessage5}. Use /model to select a model.`}}}await this.updateAvailableProviderCount(),this.footer.invalidate(),this.updateEditorBorderColor(),selectedModel?(this.showStatus(`${actionLabel}. Selected ${selectedModel.id}. Credentials saved to ${getAuthPath()}`),this.maybeWarnAboutAnthropicSubscriptionAuth(selectedModel)):(this.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`),selectionError?this.showError(selectionError):this.maybeWarnAboutAnthropicSubscriptionAuth())};deferSelection?this.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}. Refreshing model catalog\u2026`):await finishAuthentication();let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),15e3);session.modelRuntime.refresh({providers:[providerId],signal:controller.signal}).then(async result=>{result.aborted?this.showWarning(`${actionLabel}, but its model catalog refresh timed out; using cached models.`):result.errors.size>0&&this.showWarning(`${actionLabel}, but its model catalog could not be refreshed; using cached models.`),deferSelection&&this.session===session&&session.model===previousModel&&await finishAuthentication(),this.updateAvailableProviderCount(),this.footer.invalidate(),this.ui.requestRender()}).catch(error=>{this.showWarning(`${actionLabel}, but its model catalog could not be refreshed: ${error instanceof Error?error.message:String(error)}`)}).finally(()=>clearTimeout(timeout))}showAmbientAuthDialog(providerOption,onBack){let restoreEditor3=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor),this.ui.requestRender()},dialog=new LoginDialogComponent(this.ui,providerOption.id,()=>{restoreEditor3(),onBack?.()},providerOption.name,`${providerOption.name} setup`);dialog.showInfo(`${providerOption.method?.name??"Authentication"} is configured outside ${APP_NAME}.`,[],!0),this.editorContainer.clear(),this.editorContainer.addChild(dialog),this.ui.setFocus(dialog),this.ui.requestRender()}async showApiKeyLoginDialog(providerId,providerName,onBack){let previousModel=this.session.model,dialog=new LoginDialogComponent(this.ui,providerId,(_success,_message)=>{},providerName);providerId==="amazon-bedrock"&&dialog.showDetails([theme.fg("text","You can also use an AWS profile, IAM keys, or role-based credentials."),theme.fg("muted","See:"),theme.fg("accent",` ${path9.join(getDocsPath(),"providers.md")}`)]),this.editorContainer.clear(),this.editorContainer.addChild(dialog),this.ui.setFocus(dialog),this.ui.requestRender();let restoreEditor3=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor),this.ui.requestRender()};try{await this.loginProvider(dialog,providerId,providerName,"api_key"),restoreEditor3(),await this.completeProviderAuthentication(providerId,providerName,"api_key",previousModel)}catch(error){restoreEditor3();let errorMsg=error instanceof Error?error.message:String(error);error instanceof CredentialSynchronizationError?this.showError(`Saved API key for ${providerName}, but local model state could not be synchronized: ${errorMsg}`):errorMsg==="Login cancelled"?onBack?.():this.showError(`Failed to save API key for ${providerName}: ${errorMsg}`)}}showAuthSelect(dialog,prompt,providerId){return new Promise((resolve16,reject)=>{let restoreDialog=()=>{this.editorContainer.clear(),this.editorContainer.addChild(dialog),this.ui.setFocus(dialog),this.ui.requestRender()},labels=prompt.options.map(option=>option.label),selector=new ExtensionSelectorComponent(prompt.message,labels,optionLabel=>{restoreDialog();let id=prompt.options.find(option=>option.label===optionLabel)?.id;id?resolve16(id):reject(new Error("Login cancelled"))},()=>{restoreDialog(),reject(new Error("Login cancelled"))},{description:providerId===RADIUS_PROVIDER_ID?RADIUS_LOGIN_INTRO:void 0});this.editorContainer.clear(),this.editorContainer.addChild(selector),this.ui.setFocus(selector),this.ui.requestRender()})}async showAuthPrompt(dialog,prompt,providerId){let response;if(prompt.type==="select"?response=this.showAuthSelect(dialog,prompt,providerId):prompt.type==="manual_code"?response=dialog.showManualInput(prompt.message):response=dialog.showPrompt(prompt.message,prompt.placeholder),!prompt.signal)return response;if(prompt.signal.aborted)throw new Error("Login cancelled");let signal=prompt.signal,onAbort,aborted=new Promise((_resolve,reject)=>{onAbort=()=>reject(new Error("Login cancelled")),signal.addEventListener("abort",onAbort,{once:!0})});try{return await Promise.race([response,aborted])}finally{onAbort&&signal.removeEventListener("abort",onAbort)}}notifyAuthDialog(dialog,event){event.type==="auth_url"?dialog.showAuth(event.url,event.instructions):event.type==="device_code"?(dialog.showDeviceCode(event),dialog.showWaiting("Waiting for authentication...")):event.type==="info"?dialog.showInfo(event.message,event.links):dialog.showProgress(event.message)}async loginProvider(dialog,providerId,providerName,method){this.programStatus.setBlocked("login",{kind:"auth",message:`Log in to ${providerName}`});try{await this.session.modelRuntime.login(providerId,method,{signal:dialog.signal,prompt:prompt=>this.showAuthPrompt(dialog,prompt,providerId),notify:event=>this.notifyAuthDialog(dialog,event)},{getDeviceId:()=>this.settingsManager.getOrCreateDeviceId()})}finally{this.programStatus.setBlocked("login",void 0)}}async showLoginDialog(providerId,providerName,onBack){let previousModel=this.session.model,dialog=new LoginDialogComponent(this.ui,providerId,(_success,_message)=>{},providerName);this.editorContainer.clear(),this.editorContainer.addChild(dialog),this.ui.setFocus(dialog),this.ui.requestRender();let restoreEditor3=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor),this.ui.requestRender()};try{await this.loginProvider(dialog,providerId,providerName,"oauth"),restoreEditor3(),await this.completeProviderAuthentication(providerId,providerName,"oauth",previousModel),providerId===RADIUS_PROVIDER_ID&&this.offerRadiusMcpServer(providerId,providerName)}catch(error){restoreEditor3();let errorMsg=error instanceof Error?error.message:String(error);error instanceof CredentialSynchronizationError?this.showError(`Logged in to ${providerName}, but local model state could not be synchronized: ${errorMsg}`):errorMsg==="Login cancelled"?onBack?.():this.showError(`Failed to login to ${providerName}: ${errorMsg}`)}}offerRadiusMcpServer(providerId,providerName){let mcpPath=path9.join(getAgentDir(),"mcp.json"),normalizeUrl=url=>url.replace(/\/+$/u,""),{servers}=loadMcpConfig({agentDir:getAgentDir(),cwd:this.sessionManager.getCwd(),projectTrusted:!1}),existing=servers.find(server=>"url"in server.config&&normalizeUrl(server.config.url)===normalizeUrl(RADIUS_MCP_URL));if(existing&&"url"in existing.config&&existing.config.auth?.provider===providerId)return;let name=existing?.name??"radius";!existing&&servers.some(server=>server.name===name)&&(name="radius-mcp");let config=existing&&"url"in existing.config?{...existing.config,auth:{provider:providerId}}:{url:RADIUS_MCP_URL,auth:{provider:providerId}};delete config.oauth,this.showSelector(done=>{let selector=new ExtensionSelectorComponent(`Configure ${providerName} MCP in ${mcpPath}?`,["Yes","No"],option=>{if(done(),option==="Yes"){try{addMcpServerConfig(mcpPath,name,config)}catch(error){this.showError(`Could not update ${mcpPath}: ${error instanceof Error?error.message:String(error)}`);return}this.handleReloadCommand()}},()=>{done(),this.ui.requestRender()});return{component:selector,focus:selector}})}async handleReloadCommand(){if(this.session.isStreaming){this.showWarning("Wait for the current response to finish before reloading.");return}if(this.session.isCompacting){this.showWarning("Wait for compaction to finish before reloading.");return}this.resetExtensionUI();let reloadBox=new Container,borderColor=s=>theme.fg("border",s);reloadBox.addChild(new DynamicBorder(borderColor)),reloadBox.addChild(new Spacer(1)),reloadBox.addChild(new ThemedText(()=>theme.fg("muted","Reloading keybindings, extensions, skills, prompts, themes, and context files..."),1,0)),reloadBox.addChild(new Spacer(1)),reloadBox.addChild(new DynamicBorder(borderColor));let previousEditor=this.editor;this.editorContainer.clear(),this.editorContainer.addChild(reloadBox),this.ui.setFocus(reloadBox),this.ui.requestRender(!0),await new Promise(resolve16=>process.nextTick(resolve16));let dismissReloadBox=editor=>{this.editorContainer.clear(),this.editorContainer.addChild(editor),this.ui.setFocus(editor),this.ui.requestRender()},chatRestoredBeforeSessionStart=!1,reloadBoxDismissed=!1,restoreChatBeforeSessionStart=()=>{chatRestoredBeforeSessionStart||(this.hideThinkingBlock=this.settingsManager.getHideThinkingBlock(),this.outputPad=this.settingsManager.getOutputPad(),this.rebuildChatFromMessages(),chatRestoredBeforeSessionStart=!0)};try{await this.session.reload({beforeSessionStart:restoreChatBeforeSessionStart}),restoreChatBeforeSessionStart(),this.keybindings.reload();let activeHeader=this.customHeader??this.builtInHeader;isExpandable(activeHeader)&&activeHeader.setExpanded(this.toolOutputExpanded),setRegisteredThemes(this.session.resourceLoader.getThemes().themes),this.applyRuntimeSettings(),this.themeController.applyFromSettings(),this.setupAutocompleteProvider();let runner=this.session.extensionRunner;this.setupExtensionShortcuts(runner),this.showLoadedResources({force:!1,showDiagnosticsWhenQuiet:!0});let savedImplicitProjectTrust=this.maybeSaveImplicitProjectTrustAfterReload(),modelsJsonError=this.session.modelRuntime.getError();modelsJsonError&&this.showError(`models.json error: ${modelsJsonError}`),this.showStatus(savedImplicitProjectTrust?"Reloaded keybindings, extensions, skills, prompts, themes, and context files; saved project trust":"Reloaded keybindings, extensions, skills, prompts, themes, and context files"),dismissReloadBox(this.editor),reloadBoxDismissed=!0}catch(error){reloadBoxDismissed||dismissReloadBox(previousEditor),this.showError(`Reload failed: ${error instanceof Error?error.message:String(error)}`)}}async handleExportCommand(text){let outputPath=this.getPathCommandArgument(text,"/export");try{if(outputPath?.endsWith(".jsonl")){let filePath=this.session.exportToJsonl(outputPath);this.showStatus(`Session exported to: ${filePath}`)}else{let filePath=await this.session.exportToHtml(outputPath,{themeName:theme.name});this.showStatus(`Session exported to: ${filePath}`)}}catch(error){this.showError(`Failed to export session: ${error instanceof Error?error.message:"Unknown error"}`)}}getPathCommandArgument(text,command){if(text===command||!text.startsWith(`${command} `))return;let argsString=text.slice(command.length+1).trimStart();if(!argsString)return;let firstChar=argsString[0];if(firstChar==='"'||firstChar==="'"){let closingQuoteIndex=argsString.indexOf(firstChar,1);return closingQuoteIndex<0?void 0:argsString.slice(1,closingQuoteIndex)}let firstWhitespaceIndex=argsString.search(/\s/);return firstWhitespaceIndex<0?argsString:argsString.slice(0,firstWhitespaceIndex)}async handleImportCommand(text){let inputPath=this.getPathCommandArgument(text,"/import");if(!inputPath){this.showError("Usage: /import <path.jsonl>");return}if(!await this.showExtensionConfirm("Import session",`Replace current session with ${inputPath}?`)){this.showStatus("Import cancelled");return}try{if(this.clearStatusIndicator(),(await this.runtimeHost.importFromJsonl(inputPath)).cancelled){this.showStatus("Import cancelled");return}this.showStatus(`Session imported from: ${inputPath}`)}catch(error){if(error instanceof MissingSessionCwdError){let selectedCwd=await this.promptForMissingSessionCwd(error);if(!selectedCwd){this.showStatus("Import cancelled");return}if((await this.runtimeHost.importFromJsonl(inputPath,selectedCwd)).cancelled){this.showStatus("Import cancelled");return}this.showStatus(`Session imported from: ${inputPath}`);return}if(error instanceof SessionImportFileNotFoundError){this.showError(`Failed to import session: ${error.message}`);return}await this.handleFatalRuntimeError("Failed to import session",error)}}async handleShareCommand(){await shareSession({session:this.session,ui:this.ui,editorContainer:this.editorContainer,editor:this.editor,showStatus:message=>this.showStatus(message),showError:message=>this.showError(message)})}async handleBugCommand(hint){await reportBug({session:this.session,ui:this.ui,editorContainer:this.editorContainer,editor:this.editor,keybindings:this.keybindings,showStatus:message=>this.showStatus(message),showError:message=>this.showError(message)},hint)}async handleCopyCommand(options={}){if(options.preferSelection&&this.ui instanceof TuiAltScreen&&!this.ui.getCopyOnSelect()&&this.ui.hasActiveSelection()){await this.ui.copyActiveSelectionToClipboard();return}let text=this.session.getLastAssistantText();if(!text){this.showError("No agent messages to copy yet.");return}try{await copyToClipboard(text),options.flashConfirmation&&this.ui instanceof TuiAltScreen?this.ui.flash("Copied!"):this.showStatus("Copied last agent message to clipboard")}catch(error){this.showError(error instanceof Error?error.message:String(error))}}handleNameCommand(text){let name=text.replace(/^\/name\s*/,"").trim();if(!name){let currentName=this.sessionManager.getSessionName();currentName?(this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("dim",`Session name: ${currentName}`),1,0))):this.showWarning("Usage: /name <name>"),this.ui.requestRender();return}this.session.setSessionName(name);let sessionName=this.sessionManager.getSessionName();sessionName!==name&&this.showWarning(`Session name was normalized from ${JSON.stringify(name)} to ${JSON.stringify(sessionName)}`),this.chatContainer.addChild(new Spacer(1));let displayName=sessionName??name;this.chatContainer.addChild(new ThemedText(()=>theme.fg("dim",`Session name set: ${displayName}`),1,0)),this.ui.requestRender()}handleSessionCommand(){let stats=this.session.getSessionStats(),sessionName=this.sessionManager.getSessionName(),entries=this.sessionManager.getEntries(),cacheWaste=computeCacheWaste(entries,this.session.modelRuntime),usageBreakdown=getUsageCostBreakdown(entries),cacheWarmingStatus=this.session.cacheWarmingStatus,cacheWarmingMode=this.settingsManager.getCacheWarmingMode(),model=this.session.model,selectedModelKey=`${model?.provider}/${model?.id}`,renderInfo=()=>{let info=`${theme.bold("Session Info")}
|
|
1005
|
+
`);return this.editor.setText(combinedText),this.updatePendingMessagesDisplay(),options?.abort&&this.session.abort(),allQueued.length}queueCompactionMessage(text,mode){this.compactionQueuedMessages.push({text,mode}),this.editor.addToHistory?.(text),this.editor.setText(""),this.updatePendingMessagesDisplay(),this.showStatus("Queued message for after compaction")}isExtensionCommand(text){if(!text.startsWith("/"))return!1;let extensionRunner=this.session.extensionRunner,spaceIndex=text.indexOf(" "),commandName=spaceIndex===-1?text.slice(1):text.slice(1,spaceIndex);return!!extensionRunner.getCommand(commandName)}async flushCompactionQueue(options){if(this.compactionQueuedMessages.length===0)return;let queuedMessages=[...this.compactionQueuedMessages];this.compactionQueuedMessages=[],this.updatePendingMessagesDisplay();let restoreQueue=error=>{this.session.clearQueue(),this.compactionQueuedMessages=queuedMessages,this.updatePendingMessagesDisplay(),this.showError(`Failed to send queued message${queuedMessages.length>1?"s":""}: ${error instanceof Error?error.message:String(error)}`)};try{if(options?.willRetry){for(let message of queuedMessages)this.isExtensionCommand(message.text)?await this.session.prompt(message.text):message.mode==="followUp"?await this.session.followUp(message.text):await this.session.steer(message.text);this.updatePendingMessagesDisplay();return}let firstPromptIndex=queuedMessages.findIndex(message=>!this.isExtensionCommand(message.text));if(firstPromptIndex===-1){for(let message of queuedMessages)await this.session.prompt(message.text);return}let preCommands=queuedMessages.slice(0,firstPromptIndex),firstPrompt=queuedMessages[firstPromptIndex],rest=queuedMessages.slice(firstPromptIndex+1);for(let message of preCommands)await this.session.prompt(message.text);let promptPromise=this.session.prompt(firstPrompt.text,{streamingBehavior:firstPrompt.mode}).catch(error=>{restoreQueue(error)});for(let message of rest)this.isExtensionCommand(message.text)?await this.session.prompt(message.text):message.mode==="followUp"?await this.session.followUp(message.text):await this.session.steer(message.text);this.updatePendingMessagesDisplay()}catch(error){restoreQueue(error)}}flushPendingBashComponents(){for(let component of this.pendingBashComponents)this.pendingMessagesContainer.removeChild(component),this.chatContainer.addChild(component);this.pendingBashComponents=[]}disposeActiveSelector(){let dispose=this.activeSelectorDispose;this.activeSelectorToken=void 0,this.activeSelectorDispose=void 0,dispose?.()}showSelector(create){let token={},dispose,created=create(()=>{dispose?.(),this.activeSelectorToken===token&&(this.activeSelectorToken=void 0,this.activeSelectorDispose=void 0,this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor))});dispose=created.dispose,this.disposeActiveSelector(),this.activeSelectorToken=token,this.activeSelectorDispose=dispose,this.editorContainer.clear(),this.editorContainer.addChild(created.component),this.ui.setFocus(created.focus),this.ui.requestRender()}showSettingsSelector(){this.showSelector(done=>{let selector,defaultProvider=this.settingsManager.getDefaultProvider(),defaultModelId=this.settingsManager.getDefaultModel(),defaultModel=defaultProvider&&defaultModelId?`${defaultProvider}/${defaultModelId}`:"not set";return selector=new SettingsSelectorComponent({autoCompact:this.session.autoCompactionEnabled,defaultModel,currentModel:this.session.model,availableDefaultModels:this.session.modelRuntime.getAvailableSnapshot(),showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells(),autoResizeImages:this.settingsManager.getImageAutoResize(),blockImages:this.settingsManager.getBlockImages(),enableSkillCommands:this.settingsManager.getEnableSkillCommands(),steeringMode:this.session.steeringMode,followUpMode:this.session.followUpMode,transport:this.settingsManager.getTransport(),sessionShareDestination:this.settingsManager.getSessionShareDestination(),httpIdleTimeoutMs:this.settingsManager.getHttpIdleTimeoutMs(),cacheWarmingMode:this.settingsManager.getCacheWarmingMode(),thinkingLevel:this.settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL,availableThinkingLevels:[...THINKING_LEVEL_OPTIONS],modelThinkingLevels:this.settingsManager.getAllModelThinkingLevels(),currentTheme:this.themeController.getThemeSelection()||SYSTEM_THEME_NAME,terminalTheme:this.themeController.getTerminalTheme(),availableThemes:getAvailableThemes(),hideThinkingBlock:this.hideThinkingBlock,mermaidRenderingMode:this.settingsManager.getMermaidRenderingMode(),collapseChangelog:this.settingsManager.getCollapseChangelog(),enableInstallTelemetry:this.settingsManager.getEnableInstallTelemetry(),doubleEscapeAction:this.settingsManager.getDoubleEscapeAction(),treeFilterMode:this.settingsManager.getTreeFilterMode(),showHardwareCursor:this.settingsManager.getShowHardwareCursor(),showCacheMissNotices:this.settingsManager.getShowCacheMissNotices(),defaultProjectTrust:this.settingsManager.getDefaultProjectTrust(),editorPaddingX:this.settingsManager.getEditorPaddingX(),outputPad:this.settingsManager.getOutputPad(),autocompleteMaxVisible:this.settingsManager.getAutocompleteMaxVisible(),quietStartup:this.settingsManager.getQuietStartup(),clearOnShrink:this.settingsManager.getClearOnShrink(),showTerminalProgress:this.settingsManager.getShowTerminalProgress(),tuiMode:this.ui.mode,fullscreenExitOutput:this.settingsManager.getFullscreenExitOutput(),fullscreenScrollbar:this.settingsManager.getFullscreenScrollbar(),fullscreenCopyOnSelect:this.settingsManager.getFullscreenCopyOnSelect(),fullscreenWheelScrollLines:this.settingsManager.getFullscreenWheelScrollLines(),warnings:this.settingsManager.getWarnings()},{onAutoCompactChange:enabled=>{this.session.setAutoCompactionEnabled(enabled),this.footer.setAutoCompactEnabled(enabled)},onShowImagesChange:enabled=>{this.settingsManager.setShowImages(enabled);for(let child of this.chatContainer.children)child instanceof ToolExecutionComponent&&child.setShowImages(enabled)},onImageWidthCellsChange:width=>{this.settingsManager.setImageWidthCells(width);for(let child of this.chatContainer.children)child instanceof ToolExecutionComponent&&child.setImageWidthCells(width)},onAutoResizeImagesChange:enabled=>{this.settingsManager.setImageAutoResize(enabled)},onBlockImagesChange:blocked=>{this.settingsManager.setBlockImages(blocked)},onEnableSkillCommandsChange:enabled=>{this.settingsManager.setEnableSkillCommands(enabled),this.setupAutocompleteProvider()},onSteeringModeChange:mode=>{this.session.setSteeringMode(mode)},onFollowUpModeChange:mode=>{this.session.setFollowUpMode(mode)},onTransportChange:transport=>{this.settingsManager.setTransport(transport),this.session.agent.transport=transport},onSessionShareDestinationChange:destination=>{this.settingsManager.setSessionShareDestination(destination)},onHttpIdleTimeoutMsChange:timeoutMs=>{this.settingsManager.setHttpIdleTimeoutMs(timeoutMs),configureHttpDispatcher(timeoutMs),this.showStatus(`HTTP idle timeout: ${formatHttpIdleTimeoutMs(timeoutMs)}`)},onCacheWarmingModeChange:mode=>{this.session.setCacheWarmingMode(mode),this.showStatus(`Cache warming: ${mode}`)},onModelThinkingLevelChange:(provider,modelId,level)=>{this.settingsManager.setModelThinkingLevel(provider,modelId,level);let current=this.session.model;current&¤t.provider===provider&¤t.id===modelId&&(this.session.setThinkingLevel(level),this.footer.invalidate(),this.updateEditorBorderColor())},onModelThinkingLevelRemove:(provider,modelId)=>{this.settingsManager.removeModelThinkingLevel(provider,modelId);let current=this.session.model;if(current&¤t.provider===provider&¤t.id===modelId){let globalDefault=this.settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL;this.session.setThinkingLevel(globalDefault),this.footer.invalidate(),this.updateEditorBorderColor()}},onThemeChange:themeSetting=>{this.settingsManager.setTheme(themeSetting),this.themeController.setThemeSetting(themeSetting)},onThemePreview:themeName=>this.themeController.preview(themeName),onHideThinkingBlockChange:hidden=>{this.hideThinkingBlock=hidden,this.settingsManager.setHideThinkingBlock(hidden),this.updateThinkingBlockVisibility()},onMermaidRenderingModeChange:mode=>{this.settingsManager.setMermaidRenderingMode(mode),this.chatContainer.invalidate(),this.ui.requestRender()},onShowCacheMissNoticesChange:shown=>{this.settingsManager.setShowCacheMissNotices(shown),this.rebuildChatFromMessages()},onCollapseChangelogChange:collapsed=>{this.settingsManager.setCollapseChangelog(collapsed)},onEnableInstallTelemetryChange:enabled=>{this.settingsManager.setEnableInstallTelemetry(enabled)},onQuietStartupChange:quiet=>{this.settingsManager.setQuietStartup(quiet)},onDefaultProjectTrustChange:defaultProjectTrust=>{this.settingsManager.setDefaultProjectTrust(defaultProjectTrust)},onDoubleEscapeActionChange:action=>{this.settingsManager.setDoubleEscapeAction(action)},onTreeFilterModeChange:mode=>{this.settingsManager.setTreeFilterMode(mode)},onShowHardwareCursorChange:enabled=>{this.settingsManager.setShowHardwareCursor(enabled),this.ui.setShowHardwareCursor(enabled)},onEditorPaddingXChange:padding=>{this.settingsManager.setEditorPaddingX(padding),this.defaultEditor.setPaddingX(padding),this.editor!==this.defaultEditor&&this.editor.setPaddingX!==void 0&&this.editor.setPaddingX(padding)},onOutputPadChange:padding=>{this.settingsManager.setOutputPad(padding),this.outputPad=padding;for(let container of[this.chatContainer,this.pendingMessagesContainer])for(let child of container.children)"setOutputPad"in child&&typeof child.setOutputPad=="function"&&child.setOutputPad(padding);this.ui.requestRender()},onAutocompleteMaxVisibleChange:maxVisible=>{this.settingsManager.setAutocompleteMaxVisible(maxVisible),this.defaultEditor.setAutocompleteMaxVisible(maxVisible),this.editor!==this.defaultEditor&&this.editor.setAutocompleteMaxVisible!==void 0&&this.editor.setAutocompleteMaxVisible(maxVisible)},onClearOnShrinkChange:enabled=>{this.settingsManager.setClearOnShrink(enabled),this.ui.setClearOnShrink(enabled),!enabled&&!this.activeStatusIndicator&&this.statusContainer.clear()},onShowTerminalProgressChange:enabled=>{this.settingsManager.setShowTerminalProgress(enabled)},onTuiModeChange:mode=>{if(!this.switchTuiMode(mode)){selector?.getSettingsList().updateValue("tui-mode",this.ui.mode),this.showStatus("Close active overlays before changing TUI mode");return}this.settingsManager.setTuiMode(mode),this.activeStatusIndicator||this.statusContainer.clear(),this.showStatus(`TUI mode: ${mode}`)},onFullscreenExitOutputChange:output=>{this.settingsManager.setFullscreenExitOutput(output)},onFullscreenScrollbarChange:mode=>{this.settingsManager.setFullscreenScrollbar(mode),this.applyFullscreenScrollbarSetting()},onFullscreenCopyOnSelectChange:enabled=>{this.settingsManager.setFullscreenCopyOnSelect(enabled),this.renderer instanceof TuiAltScreen&&this.renderer.setCopyOnSelect(enabled)},onFullscreenWheelScrollLinesChange:lines=>{this.settingsManager.setFullscreenWheelScrollLines(lines),this.renderer instanceof TuiAltScreen&&this.renderer.setWheelScrollLines(lines)},onWarningsChange:warnings=>{this.settingsManager.setWarnings(warnings)},onCancel:()=>{done(),this.ui.requestRender()}}),{component:selector,focus:selector.getSettingsList()}})}handleThinkingCommand(searchTerm){let availableLevels=this.session.getAvailableThinkingLevels();if(!searchTerm){this.showThinkingSelector();return}let normalized=searchTerm.trim().toLowerCase(),level=availableLevels.find(candidate=>candidate.toLowerCase()===normalized);if(!level){this.showError(`Unknown thinking level "${searchTerm}". Available levels: ${availableLevels.join(", ")}.`);return}this.selectThinkingLevel(level,!1)}selectThinkingLevel(level,persist){try{this.session.setThinkingLevel(level,{persist}),this.footer.invalidate(),this.updateEditorBorderColor(),this.showStatus(persist?`Default thinking level: ${level}`:`Thinking level: ${level}`)}catch(error){this.showError(error instanceof Error?error.message:String(error))}}showThinkingSelector(){this.showSelector(done=>{let selectLevel=(level,persist)=>{this.selectThinkingLevel(level,persist),done()},selector=new ThinkingSelectorComponent(this.session.thinkingLevel??DEFAULT_THINKING_LEVEL,this.session.getAvailableThinkingLevels(),level=>selectLevel(level,!1),()=>{done(),this.ui.requestRender()},level=>selectLevel(level,!0),this.settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL);return{component:selector,focus:selector}})}async handleModelCommand(searchTerm){if(searchTerm&&globalThis.__pinkAgentModelMenu?.(searchTerm,()=>this.showModelSelector(searchTerm,!0)))return;if(!searchTerm){this.showModelSelector();return}let model=await this.findExactModelMatch(searchTerm);if(model){try{await this.session.setModel(model,{persist:!!globalThis.__pinkRememberModel}),this.footer.invalidate(),this.updateEditorBorderColor(),this.showStatus(`Model: ${model.id}`),this.maybeWarnAboutAnthropicSubscriptionAuth(model)}catch(error){this.showError(error instanceof Error?error.message:String(error))}return}this.showModelSelector(searchTerm)}async findExactModelMatch(searchTerm){let cachedModels=this.session.scopedModels.length>0?this.session.scopedModels.map(scoped=>scoped.model):[...this.session.modelRuntime.getAvailableSnapshot()],cachedMatch=findExactModelReferenceMatch(searchTerm,cachedModels);if(cachedMatch||this.session.scopedModels.length>0)return cachedMatch;this.showStatus("Refreshing model catalogs\u2026");let controller=new AbortController,timedOut=!1,timeout=setTimeout(()=>{timedOut=!0,controller.abort()},15e3);try{let result=await refreshModelCatalogs(this.session.modelRuntime,controller.signal);result.aborted&&timedOut?this.showWarning("Model refresh timed out; searching cached models."):result.errors.size>0&&this.showWarning(`Could not refresh ${[...result.errors.keys()].join(", ")}; searching cached models.`)}catch(error){this.showWarning(timedOut?"Model refresh timed out; searching cached models.":`Could not refresh model catalogs: ${error instanceof Error?error.message:String(error)}`)}finally{clearTimeout(timeout)}return findExactModelReferenceMatch(searchTerm,[...this.session.modelRuntime.getAvailableSnapshot()])}updateAvailableProviderCount(){let models=this.session.scopedModels.length>0?this.session.scopedModels.map(scoped=>scoped.model):this.session.modelRuntime.getAvailableSnapshot(),uniqueProviders=new Set(models.map(model=>model.provider));this.footerDataProvider.setAvailableProviderCount(uniqueProviders.size)}async maybeWarnAboutAnthropicSubscriptionAuth(model=this.session.model){if(this.settingsManager.getWarnings().anthropicExtraUsage!==!1&&!this.anthropicSubscriptionWarningShown&&!(!model||model.provider!=="anthropic"))try{if((await this.session.modelRuntime.checkAuth("anthropic"))?.type==="oauth"){this.anthropicSubscriptionWarningShown=!0,this.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);return}let apiKey=(await this.session.modelRuntime.getAuth(model.provider))?.auth.apiKey;if(!isAnthropicSubscriptionAuthKey(apiKey))return;this.anthropicSubscriptionWarningShown=!0,this.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING)}catch{}}maybeSaveImplicitProjectTrustAfterReload(){let cwd=this.sessionManager.getCwd();if(this.autoTrustOnReloadCwd!==cwd||!this.settingsManager.isProjectTrusted()||!hasTrustRequiringProjectResources(cwd))return!1;let trustStore=new ProjectTrustStore(this.runtimeHost.services.agentDir);try{return trustStore.get(cwd)!==null?(this.autoTrustOnReloadCwd=void 0,!1):(trustStore.set(cwd,!0),this.autoTrustOnReloadCwd=void 0,!0)}catch(error){return this.showWarning(`Could not save project trust after reload: ${error instanceof Error?error.message:String(error)}`),!1}}showTrustSelector(){let cwd=this.sessionManager.getCwd(),trustStore=new ProjectTrustStore(this.runtimeHost.services.agentDir),savedDecision=trustStore.getEntry(cwd);this.showSelector(done=>{let selector=new TrustSelectorComponent({cwd,savedDecision,projectTrusted:this.settingsManager.isProjectTrusted(),onSelect:selection=>{trustStore.setMany(selection.updates),done(),this.showStatus(`Saved trust decision: ${selection.trusted?"trusted":"untrusted"}. Restart ${APP_NAME} for this to take effect.`)},onCancel:()=>{done(),this.ui.requestRender()}});return{component:selector,focus:selector}})}showModelSelector(initialSearchInput,pinkOwn){if(!pinkOwn&&globalThis.__pinkAgentModelMenu?.(initialSearchInput,()=>this.showModelSelector(initialSearchInput,!0)))return;this.showSelector(done=>{let selectModel=async(model,persist)=>{try{await this.session.setModel(model,{persist:persist||!!globalThis.__pinkRememberModel}),this.updateAvailableProviderCount(),this.footer.invalidate(),this.updateEditorBorderColor(),done(),this.showStatus(persist?`Default model: ${model.provider}/${model.id}`:`Model: ${model.id}`),this.maybeWarnAboutAnthropicSubscriptionAuth(model)}catch(error){done(),this.showError(error instanceof Error?error.message:String(error))}},defaultProvider=this.settingsManager.getDefaultProvider(),defaultModel=this.settingsManager.getDefaultModel(),selector=new ModelSelectorComponent(this.ui,this.session.model,this.session.modelRuntime,this.session.scopedModels,model=>selectModel(model,!1),()=>{done(),this.ui.requestRender()},initialSearchInput,model=>selectModel(model,!0),defaultProvider&&defaultModel?{provider:defaultProvider,id:defaultModel}:void 0);return{component:selector,focus:selector,dispose:()=>selector.dispose()}})}showModelsSelector(){let availableModels=[...this.session.modelRuntime.getAvailableSnapshot()],availableModelIds=new Set(availableModels.map(model=>`${model.provider}/${model.id}`)),configuredPatterns=this.settingsManager.getEnabledModels(),sessionScopedModels=this.session.scopedModels,configuredEnabledIds=models=>{if(!configuredPatterns?.length)return null;let resolved=resolveModelScopeFromModels(configuredPatterns,models),ids=resolved.scopedModels.map(scoped=>`${scoped.model.provider}/${scoped.model.id}`);for(let diagnostic of resolved.diagnostics)diagnostic.code==="no-match"&&!ids.includes(diagnostic.pattern)&&ids.push(diagnostic.pattern);return ids},currentEnabledIds=sessionScopedModels.length>0?sessionScopedModels.map(scoped=>`${scoped.model.provider}/${scoped.model.id}`):configuredEnabledIds(availableModels),selectionChanged=!1,updateSessionModels=enabledIds=>{currentEnabledIds=enabledIds===null?null:[...enabledIds];let hasEnabledAvailableModel=enabledIds?.some(id=>availableModelIds.has(id))??!1,allAvailableModelsEnabled=enabledIds!==null&&[...availableModelIds].every(id=>enabledIds.includes(id));if(enabledIds&&hasEnabledAvailableModel&&!allAvailableModelsEnabled){let newScopedModels=resolveModelScopeFromModels(enabledIds,availableModels).scopedModels;this.session.setScopedModels(newScopedModels.map(scoped=>({model:scoped.model,thinkingLevel:scoped.thinkingLevel})))}else this.session.setScopedModels([]);this.updateAvailableProviderCount(),this.ui.requestRender()};this.showSelector(done=>{let disposed=!1,timedOut=!1,controller=new AbortController,timeout=setTimeout(()=>{timedOut=!0,controller.abort()},15e3),selector=new ScopedModelsSelectorComponent({allModels:availableModels,enabledModelIds:currentEnabledIds,refreshStatus:"Refreshing model catalogs\u2026"},{onChange:enabledIds=>{selectionChanged=!0,updateSessionModels(enabledIds)},onPersist:enabledIds=>{let allEnabled=enabledIds!==null&&enabledIds.length===availableModels.length&&enabledIds.every(id=>availableModelIds.has(id)),newPatterns=enabledIds===null||allEnabled?void 0:enabledIds;this.settingsManager.setEnabledModels(newPatterns?[...newPatterns]:void 0),this.showStatus("Model selection saved to settings")},onCancel:()=>{done(),this.ui.requestRender()}});return refreshModelCatalogs(this.session.modelRuntime,controller.signal).then(result=>{disposed||(availableModels=[...this.session.modelRuntime.getAvailableSnapshot()],availableModelIds=new Set(availableModels.map(model=>`${model.provider}/${model.id}`)),!selectionChanged&&sessionScopedModels.length===0?(currentEnabledIds=configuredEnabledIds(availableModels),selector.updateModels(availableModels,currentEnabledIds)):selector.updateModels(availableModels),currentEnabledIds!==null&&updateSessionModels(currentEnabledIds),result.aborted&&timedOut?selector.setRefreshStatus("Model refresh timed out; showing cached models.","warning"):result.errors.size>0?selector.setRefreshStatus(`Could not refresh ${[...result.errors.keys()].join(", ")}; showing cached models.`,"warning"):selector.setRefreshStatus("Model catalogs refreshed.","success"),this.ui.requestRender())}).catch(error=>{disposed||(selector.setRefreshStatus(timedOut?"Model refresh timed out; showing cached models.":`Could not refresh model catalogs: ${error instanceof Error?error.message:String(error)}`,"warning"),this.ui.requestRender())}).finally(()=>clearTimeout(timeout)),{component:selector,focus:selector,dispose:()=>{disposed=!0,clearTimeout(timeout),controller.abort()}}})}showUserMessageSelector(){let userMessages=this.session.getUserMessagesForForking();if(userMessages.length===0){this.showStatus("No messages to fork from");return}let initialSelectedId=userMessages[userMessages.length-1]?.entryId;this.showSelector(done=>{let selector=new UserMessageSelectorComponent(userMessages.map(m=>({id:m.entryId,text:m.text})),async entryId=>{done();try{let result=await this.runtimeHost.fork(entryId);if(result.cancelled){this.ui.requestRender();return}this.editor.setText(result.selectedText??""),this.showStatus("Forked to new session")}catch(error){this.showError(error instanceof Error?error.message:String(error))}},()=>{done(),this.ui.requestRender()},initialSelectedId);return{component:selector,focus:selector.getMessageList()}})}async handleCloneCommand(){let leafId=this.sessionManager.getLeafId();if(!leafId){this.showStatus("Nothing to clone yet");return}try{if((await this.runtimeHost.fork(leafId,{position:"at"})).cancelled){this.ui.requestRender();return}this.editor.setText(""),this.showStatus("Cloned to new session")}catch(error){this.showError(error instanceof Error?error.message:String(error))}}showTreeSelector(initialSelectedId){let tree=this.sessionManager.getTree(),realLeafId=this.sessionManager.getLeafId(),initialFilterMode=this.settingsManager.getTreeFilterMode();if(tree.length===0){this.showStatus("No entries in session");return}this.showSelector(done=>{let selector=new TreeSelectorComponent(tree,realLeafId,this.ui.terminal.rows,async entryId=>{if(entryId===this.sessionManager.getLeafId()){done(),this.showStatus("Already at this point");return}done();let wantsSummary=!1,customInstructions;if(!this.settingsManager.getBranchSummarySkipPrompt())for(;;){let summaryChoice=await this.showExtensionSelector("Summarize branch?",["No summary","Summarize","Summarize with custom prompt"]);if(summaryChoice===void 0){this.showTreeSelector(entryId);return}if(wantsSummary=summaryChoice!=="No summary",!(summaryChoice==="Summarize with custom prompt"&&(customInstructions=await this.showExtensionEditor("Custom summarization instructions"),customInstructions===void 0)))break}if(this.session.isStreaming&&(this.restoreQueuedMessagesToEditor(),await this.session.abort()),this.session.isCompacting){this.showError("Wait for the current compaction or tree navigation to finish before navigating the session tree.");return}let showingSummaryIndicator=!1,originalOnEscape=this.defaultEditor.onEscape;wantsSummary&&(this.defaultEditor.onEscape=()=>{this.session.abortBranchSummary()},this.chatContainer.addChild(new Spacer(1)),this.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui)),showingSummaryIndicator=!0,this.ui.requestRender());try{let result=await this.session.navigateTree(entryId,{summarize:wantsSummary,customInstructions});if(result.aborted){this.showStatus("Branch summarization cancelled"),this.showTreeSelector(entryId);return}if(result.cancelled){this.showStatus("Navigation cancelled");return}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})}catch(error){this.showError(error instanceof Error?error.message:String(error))}finally{showingSummaryIndicator&&this.clearStatusIndicator("branchSummary"),this.defaultEditor.onEscape=originalOnEscape}},()=>{done(),this.ui.requestRender()},(entryId,label)=>{this.sessionManager.appendLabelChange(entryId,label),this.ui.requestRender()},initialSelectedId,initialFilterMode);return selector.onCopy=async text=>{if(!text){this.showError("Selected entry has no text to copy");return}try{await copyToClipboard(text),this.showStatus("Copied selected message to clipboard")}catch(error){this.showError(error instanceof Error?error.message:String(error))}},{component:selector,focus:selector}})}showSessionSelector(){this.showSelector(done=>{let selector=new SessionSelectorComponent((onProgress,signal)=>SessionManager.list(this.sessionManager.getCwd(),this.sessionManager.getSessionDir(),onProgress,signal),(onProgress,signal)=>this.sessionManager.usesDefaultSessionDir()?SessionManager.listAll(onProgress,signal):SessionManager.listAll(this.sessionManager.getSessionDir(),onProgress,signal),async sessionPath=>{done(),await this.handleResumeSession(sessionPath)},()=>{done(),this.ui.requestRender()},()=>{this.shutdown()},()=>this.ui.requestRender(),{renameSession:async(sessionFilePath,nextName)=>{let next=(nextName??"").trim();if(!next)return;SessionManager.open(sessionFilePath).appendSessionInfo(next)},showRenameHint:!0,keybindings:this.keybindings},this.sessionManager.getSessionFile());return{component:selector,focus:selector}})}async handleResumeSession(sessionPath,options){this.clearStatusIndicator();try{let result=await this.runtimeHost.switchSession(sessionPath,{withSession:options?.withSession,projectTrustContextFactory:cwd=>this.createProjectTrustContext(cwd)});return result.cancelled||this.showStatus("Resumed session"),result}catch(error){if(error instanceof MissingSessionCwdError){let selectedCwd=await this.promptForMissingSessionCwd(error);if(!selectedCwd)return this.showStatus("Resume cancelled"),{cancelled:!0};let result=await this.runtimeHost.switchSession(sessionPath,{cwdOverride:selectedCwd,withSession:options?.withSession,projectTrustContextFactory:cwd=>this.createProjectTrustContext(cwd)});return result.cancelled||this.showStatus("Resumed session in current cwd"),result}return this.handleFatalRuntimeError("Failed to resume session",error)}}getLoginProviderOptions(authType){let options=[];for(let provider of this.session.modelRuntime.getProviders()){let authStatus=this.session.modelRuntime.getProviderAuthStatus(provider.id),status=authStatus.configured?{type:this.session.modelRuntime.isUsingOAuth(provider.id)?"oauth":"api_key",source:authStatus.label??authStatus.source}:void 0,subscription=provider.auth.oauth?.isSubscription===!0;(!authType||authType==="oauth")&&provider.auth.oauth&&options.push({id:provider.id,name:provider.name,authType:"oauth",method:provider.auth.oauth,status,subscription}),(!authType||authType==="api_key")&&provider.auth.apiKey&&options.push({id:provider.id,name:provider.name,authType:"api_key",method:provider.auth.apiKey,status,subscription})}return options.sort((a,b)=>a.name.localeCompare(b.name))}async getLogoutProviderOptions(){return(await this.session.modelRuntime.listCredentials({signal:AbortSignal.timeout(15e3)})).map(({providerId,type})=>{let provider=this.session.modelRuntime.getProvider(providerId);return{id:providerId,name:provider?.name??providerId,authType:type,status:{type,source:"stored credential"},subscription:provider?.auth.oauth?.isSubscription===!0}}).sort((a,b)=>a.name.localeCompare(b.name))}findLoginProviderOptions(providerRef){let normalizedProviderRef=providerRef.trim().toLowerCase();return normalizedProviderRef?this.getLoginProviderOptions().filter(provider=>provider.id.toLowerCase()===normalizedProviderRef||provider.name.toLowerCase()===normalizedProviderRef):[]}async handleLoginCommand(providerRef){if(!providerRef){this.showLoginAuthTypeSelector();return}let providerOptions=this.findLoginProviderOptions(providerRef);if(providerOptions.length===1){await this.startProviderLogin(providerOptions[0]);return}if(providerOptions.length>1&&new Set(providerOptions.map(provider=>provider.id)).size===1){this.showLoginAuthTypeSelector(providerOptions);return}this.showLoginProviderSelector(void 0,providerRef)}async startProviderLogin(providerOption,onBack){providerOption.authType==="oauth"?await this.showLoginDialog(providerOption.id,providerOption.name,onBack):providerOption.method?.login?await this.showApiKeyLoginDialog(providerOption.id,providerOption.name,onBack):this.showAmbientAuthDialog(providerOption,onBack)}showLoginAuthTypeSelector(providerOptions){let radiusOption=providerOptions?void 0:this.getLoginProviderOptions("oauth").find(provider=>provider.id===RADIUS_PROVIDER_ID),radiusText=radiusOption?`Sign in with ${radiusOption.name}`:void 0,radiusLabel=radiusOption?`${radiusText}${formatAuthSelectorProviderStatus(radiusOption)}`:void 0,oauthProvider=providerOptions?.find(provider=>provider.authType==="oauth"),subscriptionLabel=(oauthProvider?.method&&"loginLabel"in oauthProvider.method?oauthProvider.method.loginLabel:void 0)??"Sign in with an account",apiKeyLabel="Sign in with an API key",availableAuthTypes=providerOptions?new Set(providerOptions.map(provider=>provider.authType)):new Set(["oauth","api_key"]),options=[];if(availableAuthTypes.has("oauth")&&options.push(subscriptionLabel),availableAuthTypes.has("api_key")&&options.push(apiKeyLabel),radiusLabel&&options.push(radiusLabel),options.length===0){this.showStatus("No login methods available.");return}if(providerOptions&&options.length===1){let providerOption=providerOptions[0];providerOption&&this.startProviderLogin(providerOption);return}let title=providerOptions?.[0]?`Select authentication method for ${providerOptions[0].name}:`:"Select authentication method:";this.showSelector(done=>{let onSelect=option=>{if(done(),radiusOption&&option===radiusLabel){this.startProviderLogin(radiusOption,()=>this.showLoginAuthTypeSelector());return}let authType=option===subscriptionLabel?"oauth":"api_key";if(providerOptions){let providerOption=providerOptions.find(provider=>provider.authType===authType);providerOption&&this.startProviderLogin(providerOption,()=>this.showLoginAuthTypeSelector(providerOptions));return}this.showLoginProviderSelector(authType)},onCancel=()=>{done(),this.ui.requestRender()},selector=radiusLabel&&radiusText?createLoginMenuSelector(this.ui,title,options,{label:radiusLabel,text:radiusText},onSelect,onCancel):new ExtensionSelectorComponent(title,options,onSelect,onCancel);return{component:selector,focus:selector,dispose:()=>selector.dispose()}})}showLoginProviderSelector(authType,initialSearchInput){let providerOptions=this.getLoginProviderOptions(authType);if(providerOptions.length===0){let message=authType==="oauth"?"No account providers available.":authType==="api_key"?"No API key providers available.":"No login providers available.";this.showStatus(message);return}this.showSelector(done=>{let selector=new OAuthSelectorComponent("login",providerOptions,async(providerId,selectedAuthType)=>{done();let providerOption=providerOptions.find(provider=>provider.id===providerId&&provider.authType===selectedAuthType);providerOption&&await this.startProviderLogin(providerOption,()=>this.showLoginProviderSelector(authType,initialSearchInput))},()=>{done(),authType?this.showLoginAuthTypeSelector():this.ui.requestRender()},initialSearchInput);return{component:selector,focus:selector}})}async showOAuthSelector(mode){if(mode==="login"){this.showLoginAuthTypeSelector();return}let providerOptions;try{providerOptions=await this.getLogoutProviderOptions()}catch(error){this.showError(`Could not read stored credentials: ${error instanceof Error?error.message:String(error)}`);return}if(providerOptions.length===0){this.showStatus("No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.");return}this.showSelector(done=>{let selector=new OAuthSelectorComponent(mode,providerOptions,async providerId=>{done();let providerOption=providerOptions.find(provider=>provider.id===providerId);if(providerOption)try{await this.session.modelRuntime.logout(providerOption.id,{signal:AbortSignal.timeout(15e3)}),await this.updateAvailableProviderCount();let message=providerOption.authType==="oauth"?`Logged out of ${providerOption.name}`:`Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;this.showStatus(message)}catch(error){let message=error instanceof Error?error.message:String(error);this.showError(error instanceof CredentialSynchronizationError?`Credentials removed for ${providerOption.name}, but local model state could not be synchronized: ${message}`:`Logout failed: ${message}`)}},()=>{done(),this.ui.requestRender()});return{component:selector,focus:selector}})}async completeProviderAuthentication(providerId,providerName,authType,previousModel){let actionLabel=authType==="oauth"?`Logged in to ${providerName}`:`Saved API key for ${providerName}`,session=this.session,deferSelection=isUnknownModel(previousModel)&&hasDefaultModelProvider(providerId)&&!session.modelRuntime.getAvailableSnapshot().some(model=>model.provider===providerId&&model.id===defaultModelPerProvider[providerId]),finishAuthentication=async()=>{let selectedModel,selectionError;if(isUnknownModel(previousModel)){let providerModels=this.session.modelRuntime.getAvailableSnapshot().filter(model=>model.provider===providerId);if(providerId==="llama.cpp")selectionError=llamaCppPostLoginGuidance(actionLabel,providerModels.length);else if(!hasDefaultModelProvider(providerId))selectionError=`${actionLabel}, but no default model is configured for provider "${providerId}". Use /model to select a model.`;else if(providerModels.length===0)selectionError=`${actionLabel}, but no models are available for that provider. Use /model to select a model.`;else{let defaultModelId=defaultModelPerProvider[providerId];if(selectedModel=providerModels.find(model=>model.id===defaultModelId)??(providerId==="radius"?providerModels[0]:void 0),!selectedModel)selectionError=`${actionLabel}, but its default model "${defaultModelId}" is not available. Use /model to select a model.`;else try{await this.session.setModel(selectedModel,{persist:!0})}catch(error){selectedModel=void 0;let errorMessage5=error instanceof Error?error.message:String(error);selectionError=`${actionLabel}, but selecting its default model failed: ${errorMessage5}. Use /model to select a model.`}}}await this.updateAvailableProviderCount(),this.footer.invalidate(),this.updateEditorBorderColor(),selectedModel?(this.showStatus(`${actionLabel}. Selected ${selectedModel.id}. Credentials saved to ${getAuthPath()}`),this.maybeWarnAboutAnthropicSubscriptionAuth(selectedModel)):(this.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`),selectionError?this.showError(selectionError):this.maybeWarnAboutAnthropicSubscriptionAuth())};deferSelection?this.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}. Refreshing model catalog\u2026`):await finishAuthentication();let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),15e3);session.modelRuntime.refresh({providers:[providerId],signal:controller.signal}).then(async result=>{result.aborted?this.showWarning(`${actionLabel}, but its model catalog refresh timed out; using cached models.`):result.errors.size>0&&this.showWarning(`${actionLabel}, but its model catalog could not be refreshed; using cached models.`),deferSelection&&this.session===session&&session.model===previousModel&&await finishAuthentication(),this.updateAvailableProviderCount(),this.footer.invalidate(),this.ui.requestRender()}).catch(error=>{this.showWarning(`${actionLabel}, but its model catalog could not be refreshed: ${error instanceof Error?error.message:String(error)}`)}).finally(()=>clearTimeout(timeout))}showAmbientAuthDialog(providerOption,onBack){let restoreEditor3=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor),this.ui.requestRender()},dialog=new LoginDialogComponent(this.ui,providerOption.id,()=>{restoreEditor3(),onBack?.()},providerOption.name,`${providerOption.name} setup`);dialog.showInfo(`${providerOption.method?.name??"Authentication"} is configured outside ${APP_NAME}.`,[],!0),this.editorContainer.clear(),this.editorContainer.addChild(dialog),this.ui.setFocus(dialog),this.ui.requestRender()}async showApiKeyLoginDialog(providerId,providerName,onBack){let previousModel=this.session.model,dialog=new LoginDialogComponent(this.ui,providerId,(_success,_message)=>{},providerName);providerId==="amazon-bedrock"&&dialog.showDetails([theme.fg("text","You can also use an AWS profile, IAM keys, or role-based credentials."),theme.fg("muted","See:"),theme.fg("accent",` ${path9.join(getDocsPath(),"providers.md")}`)]),this.editorContainer.clear(),this.editorContainer.addChild(dialog),this.ui.setFocus(dialog),this.ui.requestRender();let restoreEditor3=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor),this.ui.requestRender()};try{await this.loginProvider(dialog,providerId,providerName,"api_key"),restoreEditor3(),await this.completeProviderAuthentication(providerId,providerName,"api_key",previousModel)}catch(error){restoreEditor3();let errorMsg=error instanceof Error?error.message:String(error);error instanceof CredentialSynchronizationError?this.showError(`Saved API key for ${providerName}, but local model state could not be synchronized: ${errorMsg}`):errorMsg==="Login cancelled"?onBack?.():this.showError(`Failed to save API key for ${providerName}: ${errorMsg}`)}}showAuthSelect(dialog,prompt,providerId){return new Promise((resolve16,reject)=>{let restoreDialog=()=>{this.editorContainer.clear(),this.editorContainer.addChild(dialog),this.ui.setFocus(dialog),this.ui.requestRender()},labels=prompt.options.map(option=>option.label),selector=new ExtensionSelectorComponent(prompt.message,labels,optionLabel=>{restoreDialog();let id=prompt.options.find(option=>option.label===optionLabel)?.id;id?resolve16(id):reject(new Error("Login cancelled"))},()=>{restoreDialog(),reject(new Error("Login cancelled"))},{description:providerId===RADIUS_PROVIDER_ID?RADIUS_LOGIN_INTRO:void 0});this.editorContainer.clear(),this.editorContainer.addChild(selector),this.ui.setFocus(selector),this.ui.requestRender()})}async showAuthPrompt(dialog,prompt,providerId){let response;if(prompt.type==="select"?response=this.showAuthSelect(dialog,prompt,providerId):prompt.type==="manual_code"?response=dialog.showManualInput(prompt.message):response=dialog.showPrompt(prompt.message,prompt.placeholder),!prompt.signal)return response;if(prompt.signal.aborted)throw new Error("Login cancelled");let signal=prompt.signal,onAbort,aborted=new Promise((_resolve,reject)=>{onAbort=()=>reject(new Error("Login cancelled")),signal.addEventListener("abort",onAbort,{once:!0})});try{return await Promise.race([response,aborted])}finally{onAbort&&signal.removeEventListener("abort",onAbort)}}notifyAuthDialog(dialog,event){event.type==="auth_url"?dialog.showAuth(event.url,event.instructions):event.type==="device_code"?(dialog.showDeviceCode(event),dialog.showWaiting("Waiting for authentication...")):event.type==="info"?dialog.showInfo(event.message,event.links):dialog.showProgress(event.message)}async loginProvider(dialog,providerId,providerName,method){this.programStatus.setBlocked("login",{kind:"auth",message:`Log in to ${providerName}`});try{await this.session.modelRuntime.login(providerId,method,{signal:dialog.signal,prompt:prompt=>this.showAuthPrompt(dialog,prompt,providerId),notify:event=>this.notifyAuthDialog(dialog,event)},{getDeviceId:()=>this.settingsManager.getOrCreateDeviceId()})}finally{this.programStatus.setBlocked("login",void 0)}}async showLoginDialog(providerId,providerName,onBack){let previousModel=this.session.model,dialog=new LoginDialogComponent(this.ui,providerId,(_success,_message)=>{},providerName);this.editorContainer.clear(),this.editorContainer.addChild(dialog),this.ui.setFocus(dialog),this.ui.requestRender();let restoreEditor3=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor),this.ui.requestRender()};try{await this.loginProvider(dialog,providerId,providerName,"oauth"),restoreEditor3(),await this.completeProviderAuthentication(providerId,providerName,"oauth",previousModel),providerId===RADIUS_PROVIDER_ID&&this.offerRadiusMcpServer(providerId,providerName)}catch(error){restoreEditor3();let errorMsg=error instanceof Error?error.message:String(error);error instanceof CredentialSynchronizationError?this.showError(`Logged in to ${providerName}, but local model state could not be synchronized: ${errorMsg}`):errorMsg==="Login cancelled"?onBack?.():this.showError(`Failed to login to ${providerName}: ${errorMsg}`)}}offerRadiusMcpServer(providerId,providerName){let mcpPath=path9.join(getAgentDir(),"mcp.json"),normalizeUrl=url=>url.replace(/\/+$/u,""),{servers}=loadMcpConfig({agentDir:getAgentDir(),cwd:this.sessionManager.getCwd(),projectTrusted:!1}),existing=servers.find(server=>"url"in server.config&&normalizeUrl(server.config.url)===normalizeUrl(RADIUS_MCP_URL));if(existing&&"url"in existing.config&&existing.config.auth?.provider===providerId)return;let name=existing?.name??"radius";!existing&&servers.some(server=>server.name===name)&&(name="radius-mcp");let config=existing&&"url"in existing.config?{...existing.config,auth:{provider:providerId}}:{url:RADIUS_MCP_URL,auth:{provider:providerId}};delete config.oauth,this.showSelector(done=>{let selector=new ExtensionSelectorComponent(`Configure ${providerName} MCP in ${mcpPath}?`,["Yes","No"],option=>{if(done(),option==="Yes"){try{addMcpServerConfig(mcpPath,name,config)}catch(error){this.showError(`Could not update ${mcpPath}: ${error instanceof Error?error.message:String(error)}`);return}this.handleReloadCommand()}},()=>{done(),this.ui.requestRender()});return{component:selector,focus:selector}})}async handleReloadCommand(){if(this.session.isStreaming){this.showWarning("Wait for the current response to finish before reloading.");return}if(this.session.isCompacting){this.showWarning("Wait for compaction to finish before reloading.");return}this.resetExtensionUI();let reloadBox=new Container,borderColor=s=>theme.fg("border",s);reloadBox.addChild(new DynamicBorder(borderColor)),reloadBox.addChild(new Spacer(1)),reloadBox.addChild(new ThemedText(()=>theme.fg("muted","Reloading keybindings, extensions, skills, prompts, themes, and context files..."),1,0)),reloadBox.addChild(new Spacer(1)),reloadBox.addChild(new DynamicBorder(borderColor));let previousEditor=this.editor;this.editorContainer.clear(),this.editorContainer.addChild(reloadBox),this.ui.setFocus(reloadBox),this.ui.requestRender(!0),await new Promise(resolve16=>process.nextTick(resolve16));let dismissReloadBox=editor=>{this.editorContainer.clear(),this.editorContainer.addChild(editor),this.ui.setFocus(editor),this.ui.requestRender()},chatRestoredBeforeSessionStart=!1,reloadBoxDismissed=!1,restoreChatBeforeSessionStart=()=>{chatRestoredBeforeSessionStart||(this.hideThinkingBlock=this.settingsManager.getHideThinkingBlock(),this.outputPad=this.settingsManager.getOutputPad(),this.rebuildChatFromMessages(),chatRestoredBeforeSessionStart=!0)};try{await this.session.reload({beforeSessionStart:restoreChatBeforeSessionStart}),restoreChatBeforeSessionStart(),this.keybindings.reload();let activeHeader=this.customHeader??this.builtInHeader;isExpandable(activeHeader)&&activeHeader.setExpanded(this.toolOutputExpanded),setRegisteredThemes(this.session.resourceLoader.getThemes().themes),this.applyRuntimeSettings(),this.themeController.applyFromSettings(),this.setupAutocompleteProvider();let runner=this.session.extensionRunner;this.setupExtensionShortcuts(runner),this.showLoadedResources({force:!1,showDiagnosticsWhenQuiet:!0});let savedImplicitProjectTrust=this.maybeSaveImplicitProjectTrustAfterReload(),modelsJsonError=this.session.modelRuntime.getError();modelsJsonError&&this.showError(`models.json error: ${modelsJsonError}`),this.showStatus(savedImplicitProjectTrust?"Reloaded keybindings, extensions, skills, prompts, themes, and context files; saved project trust":"Reloaded keybindings, extensions, skills, prompts, themes, and context files"),dismissReloadBox(this.editor),reloadBoxDismissed=!0}catch(error){reloadBoxDismissed||dismissReloadBox(previousEditor),this.showError(`Reload failed: ${error instanceof Error?error.message:String(error)}`)}}async handleExportCommand(text){let outputPath=this.getPathCommandArgument(text,"/export");try{if(outputPath?.endsWith(".jsonl")){let filePath=this.session.exportToJsonl(outputPath);this.showStatus(`Session exported to: ${filePath}`)}else{let filePath=await this.session.exportToHtml(outputPath,{themeName:theme.name});this.showStatus(`Session exported to: ${filePath}`)}}catch(error){this.showError(`Failed to export session: ${error instanceof Error?error.message:"Unknown error"}`)}}getPathCommandArgument(text,command){if(text===command||!text.startsWith(`${command} `))return;let argsString=text.slice(command.length+1).trimStart();if(!argsString)return;let firstChar=argsString[0];if(firstChar==='"'||firstChar==="'"){let closingQuoteIndex=argsString.indexOf(firstChar,1);return closingQuoteIndex<0?void 0:argsString.slice(1,closingQuoteIndex)}let firstWhitespaceIndex=argsString.search(/\s/);return firstWhitespaceIndex<0?argsString:argsString.slice(0,firstWhitespaceIndex)}async handleImportCommand(text){let inputPath=this.getPathCommandArgument(text,"/import");if(!inputPath){this.showError("Usage: /import <path.jsonl>");return}if(!await this.showExtensionConfirm("Import session",`Replace current session with ${inputPath}?`)){this.showStatus("Import cancelled");return}try{if(this.clearStatusIndicator(),(await this.runtimeHost.importFromJsonl(inputPath)).cancelled){this.showStatus("Import cancelled");return}this.showStatus(`Session imported from: ${inputPath}`)}catch(error){if(error instanceof MissingSessionCwdError){let selectedCwd=await this.promptForMissingSessionCwd(error);if(!selectedCwd){this.showStatus("Import cancelled");return}if((await this.runtimeHost.importFromJsonl(inputPath,selectedCwd)).cancelled){this.showStatus("Import cancelled");return}this.showStatus(`Session imported from: ${inputPath}`);return}if(error instanceof SessionImportFileNotFoundError){this.showError(`Failed to import session: ${error.message}`);return}await this.handleFatalRuntimeError("Failed to import session",error)}}async handleShareCommand(){await shareSession({session:this.session,ui:this.ui,editorContainer:this.editorContainer,editor:this.editor,showStatus:message=>this.showStatus(message),showError:message=>this.showError(message)})}async handleBugCommand(hint){await reportBug({session:this.session,ui:this.ui,editorContainer:this.editorContainer,editor:this.editor,keybindings:this.keybindings,showStatus:message=>this.showStatus(message),showError:message=>this.showError(message)},hint)}async handleCopyCommand(options={}){if(options.preferSelection&&this.ui instanceof TuiAltScreen&&!this.ui.getCopyOnSelect()&&this.ui.hasActiveSelection()){await this.ui.copyActiveSelectionToClipboard();return}let text=this.session.getLastAssistantText();if(!text){this.showError("No agent messages to copy yet.");return}try{await copyToClipboard(text),options.flashConfirmation&&this.ui instanceof TuiAltScreen?this.ui.flash("Copied!"):this.showStatus("Copied last agent message to clipboard")}catch(error){this.showError(error instanceof Error?error.message:String(error))}}handleNameCommand(text){let name=text.replace(/^\/name\s*/,"").trim();if(!name){let currentName=this.sessionManager.getSessionName();currentName?(this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("dim",`Session name: ${currentName}`),1,0))):this.showWarning("Usage: /name <name>"),this.ui.requestRender();return}this.session.setSessionName(name);let sessionName=this.sessionManager.getSessionName();sessionName!==name&&this.showWarning(`Session name was normalized from ${JSON.stringify(name)} to ${JSON.stringify(sessionName)}`),this.chatContainer.addChild(new Spacer(1));let displayName=sessionName??name;this.chatContainer.addChild(new ThemedText(()=>theme.fg("dim",`Session name set: ${displayName}`),1,0)),this.ui.requestRender()}handleSessionCommand(){let stats=this.session.getSessionStats(),sessionName=this.sessionManager.getSessionName(),entries=this.sessionManager.getEntries(),cacheWaste=computeCacheWaste(entries,this.session.modelRuntime),usageBreakdown=getUsageCostBreakdown(entries),cacheWarmingStatus=this.session.cacheWarmingStatus,cacheWarmingMode=this.settingsManager.getCacheWarmingMode(),model=this.session.model,selectedModelKey=`${model?.provider}/${model?.id}`,renderInfo=()=>{let info=`${theme.bold("Session Info")}
|
|
1006
1006
|
|
|
1007
1007
|
`;sessionName&&(info+=`${theme.fg("dim","Name:")} ${sessionName}
|
|
1008
1008
|
`),info+=`${theme.fg("dim","File:")} ${stats.sessionFile??"In-memory"}
|
|
@@ -3675,7 +3675,7 @@ export class InteractiveMode {
|
|
|
3675
3675
|
}
|
|
3676
3676
|
async cycleModel(direction) {
|
|
3677
3677
|
try {
|
|
3678
|
-
const result = await this.session.cycleModel(direction);
|
|
3678
|
+
const result = await this.session.cycleModel(direction, { persist: !!globalThis.__pinkRememberModel });
|
|
3679
3679
|
if (result === undefined) {
|
|
3680
3680
|
const msg = this.session.scopedModels.length > 0 ? "Only one model in scope" : "Only one model available";
|
|
3681
3681
|
this.showStatus(msg);
|
|
@@ -4277,6 +4277,8 @@ export class InteractiveMode {
|
|
|
4277
4277
|
});
|
|
4278
4278
|
}
|
|
4279
4279
|
async handleModelCommand(searchTerm) {
|
|
4280
|
+
if (searchTerm && globalThis.__pinkAgentModelMenu?.(searchTerm, () => this.showModelSelector(searchTerm, true)))
|
|
4281
|
+
return;
|
|
4280
4282
|
if (!searchTerm) {
|
|
4281
4283
|
this.showModelSelector();
|
|
4282
4284
|
return;
|
|
@@ -4284,7 +4286,7 @@ export class InteractiveMode {
|
|
|
4284
4286
|
const model = await this.findExactModelMatch(searchTerm);
|
|
4285
4287
|
if (model) {
|
|
4286
4288
|
try {
|
|
4287
|
-
await this.session.setModel(model, { persist:
|
|
4289
|
+
await this.session.setModel(model, { persist: !!globalThis.__pinkRememberModel });
|
|
4288
4290
|
this.footer.invalidate();
|
|
4289
4291
|
this.updateEditorBorderColor();
|
|
4290
4292
|
this.showStatus(`Model: ${model.id}`);
|
|
@@ -4410,11 +4412,14 @@ export class InteractiveMode {
|
|
|
4410
4412
|
return { component: selector, focus: selector };
|
|
4411
4413
|
});
|
|
4412
4414
|
}
|
|
4413
|
-
showModelSelector(initialSearchInput) {
|
|
4415
|
+
showModelSelector(initialSearchInput, pinkOwn) {
|
|
4416
|
+
// Pink: com o /agente ligado, o /model e o ctrl+l mostram os modelos do agente; o primeiro item abre este menu
|
|
4417
|
+
if (!pinkOwn && globalThis.__pinkAgentModelMenu?.(initialSearchInput, () => this.showModelSelector(initialSearchInput, true)))
|
|
4418
|
+
return;
|
|
4414
4419
|
this.showSelector((done) => {
|
|
4415
4420
|
const selectModel = async (model, persist) => {
|
|
4416
4421
|
try {
|
|
4417
|
-
await this.session.setModel(model, { persist });
|
|
4422
|
+
await this.session.setModel(model, { persist: persist || !!globalThis.__pinkRememberModel }); // Pink: o último modelo escolhido volta ao reabrir
|
|
4418
4423
|
this.updateAvailableProviderCount();
|
|
4419
4424
|
this.footer.invalidate();
|
|
4420
4425
|
this.updateEditorBorderColor();
|
|
@@ -468,8 +468,11 @@ export function acpModels(session: any): ModelChoice[] {
|
|
|
468
468
|
export type Resume = { id?: string; keep?: boolean; live?: AcpConn; late?: LateTurn };
|
|
469
469
|
// o que o agente manda sozinho, sem turno aberto: um subagente ou comando em segundo plano terminou e ele respondeu
|
|
470
470
|
// (owner 2026-11-28: o Pink descartava e o agente "parava"); quem abriu o agente diz como montar e mostrar
|
|
471
|
-
export type LateTurn = { fresh: () => any; deliver: (result: any) => void; ask?: () => Ask | undefined; quietMs?: number };
|
|
472
|
-
|
|
471
|
+
export type LateTurn = { fresh: () => any; deliver: (result: any) => void; ask?: () => Ask | undefined; quietMs?: number; idleMs?: number };
|
|
472
|
+
// o ACP não avisa o fim desse turno. Silêncio depois de texto fecha a resposta; depois de pensamento ou comando o agente
|
|
473
|
+
// ainda está trabalhando e espera bem mais, senão cada passo vira um bloco com o nome do agente (owner 2026-11-28)
|
|
474
|
+
export const LATE_QUIET_MS = 8000;
|
|
475
|
+
export const LATE_IDLE_MS = 180000;
|
|
473
476
|
// `force` (Esc): um agente preso (ex.: opencode esperando um subagente que não abre) ignora o fim da entrada, e no Windows
|
|
474
477
|
// o kill pega só o cmd do npm: o opencode.exe seguia vivo, segurando os pipes, e o Esc não soltava (owner 2026-11-26)
|
|
475
478
|
export function closeKept(resume?: Resume, force = false, kill: typeof spawn = spawn) {
|
|
@@ -746,12 +749,14 @@ function flushLate(conn: AcpConn, resume?: Resume) {
|
|
|
746
749
|
function lateUpdate(conn: AcpConn, update: any, resume?: Resume) {
|
|
747
750
|
if (!resume?.late) return;
|
|
748
751
|
// só começa com algo que a pessoa veria: avisos de uso e de comandos não viram resposta
|
|
749
|
-
|
|
752
|
+
const kind = update?.sessionUpdate;
|
|
753
|
+
if (!conn.lateBuffer && !["agent_message_chunk", "agent_thought_chunk", "tool_call"].includes(kind)) return;
|
|
750
754
|
conn.lateBuffer ??= { result: resume.late.fresh(), state: { text: "" } };
|
|
751
755
|
if (conn.model) conn.lateBuffer.result.model = conn.model;
|
|
752
756
|
applyAcpUpdate(update, conn.lateBuffer.result, conn.lateBuffer.state, () => {});
|
|
757
|
+
if (!["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update"].includes(kind)) return; // uso e comandos não mexem no prazo
|
|
753
758
|
clearTimeout(conn.lateTimer);
|
|
754
|
-
conn.lateTimer = setTimeout(() => flushLate(conn, resume), resume.late.quietMs ?? LATE_QUIET_MS);
|
|
759
|
+
conn.lateTimer = setTimeout(() => flushLate(conn, resume), kind === "agent_message_chunk" || update?.rawOutput?.metadata?.status === "running" ? (resume.late.quietMs ?? LATE_QUIET_MS) : (resume.late.idleMs ?? LATE_IDLE_MS));
|
|
755
760
|
conn.lateTimer.unref?.();
|
|
756
761
|
}
|
|
757
762
|
function acpOpen(child: any, name: string, exited: Promise<number>, resume?: Resume): AcpConn {
|
|
@@ -13,14 +13,36 @@ import { fileURLToPath } from "node:url";
|
|
|
13
13
|
import { closeKept, externalAgents, listModels, pinkExtras, runExternal, subagentEnd, warmKept } from "../examples/extensions/subagent/external.ts";
|
|
14
14
|
import { bulleted, elapsedLabel, fit, runLabel, shortModel, stallNote, streamedTokens, thinkingLabel, cleanLine as clean, tailLine, thinkingNow, stripThothRules, thothConfigured, toolSummary, userLines, workingLabel } from "./pink-ui.ts";
|
|
15
15
|
|
|
16
|
+
// reabrir o Pink volta ao último usado, modelo logado ou agente (owner 2026-11-28). O agente fica neste arquivo; o modelo
|
|
17
|
+
// logado o motor grava como padrão a cada troca (rebrand.json, remember-last-model-module)
|
|
18
|
+
export const lastFile = (dir = process.env.PINK_CODING_AGENT_DIR || path.join(os.homedir(), ".pink", "agent")) => path.join(dir, "agente-ultimo.json");
|
|
19
|
+
export type LastAgent = { agent: string; model?: string; effort?: string };
|
|
20
|
+
export function readLast(file = lastFile()): LastAgent | undefined {
|
|
21
|
+
const data = readJson(file);
|
|
22
|
+
const name = /^[\w./:@-]+$/; // a mesma regra do /agente: o modelo e o esforço vão para a linha de comando do agente
|
|
23
|
+
if (typeof data?.agent !== "string" || !name.test(data.agent)) return undefined;
|
|
24
|
+
if (data.model !== undefined && !(typeof data.model === "string" && name.test(data.model))) return undefined;
|
|
25
|
+
if (data.effort !== undefined && !(typeof data.effort === "string" && /^[a-z]+$/.test(data.effort))) return undefined;
|
|
26
|
+
return data;
|
|
27
|
+
}
|
|
28
|
+
export function writeLast(value: LastAgent | undefined, file = lastFile()) {
|
|
29
|
+
try {
|
|
30
|
+
if (!value) return fs.rmSync(file, { force: true });
|
|
31
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
32
|
+
fs.writeFileSync(file, JSON.stringify(value));
|
|
33
|
+
} catch {
|
|
34
|
+
/* só conveniência: sem gravar, o Pink abre no modelo logado */
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
16
38
|
// o Pink junto (card 1dfwh7kgfjx): MCPs do mcp.json, AGENTS.md e skills do Pink, mais o próprio Pink como MCP
|
|
17
|
-
|
|
39
|
+
function readJson(file: string) {
|
|
18
40
|
try {
|
|
19
41
|
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
20
42
|
} catch {
|
|
21
43
|
return undefined;
|
|
22
44
|
}
|
|
23
|
-
}
|
|
45
|
+
}
|
|
24
46
|
// pink_tela (owner 2026-11-24): o agente instalado usa a tela DESTE Pink, a que a pessoa ligou com /tela ligar, pelo MCP
|
|
25
47
|
// do Pink. Pipe local com uma chave aleatória (o nome do pipe outros usuários conseguem listar; a chave só vai nos argumentos
|
|
26
48
|
// do MCP, que só o próprio usuário lê). Cada pedido passa pelo execute da tela: desligada recusa, agir pede confirmação aqui.
|
|
@@ -130,12 +152,14 @@ export function contextFor(entries: any[] | undefined, agent: string, max = 1600
|
|
|
130
152
|
export const handoffText = (agent: string, asks: string[]) =>
|
|
131
153
|
`${t(`O ${agent} foi interrompido na troca de modelo. O que ele já fez está acima; continue este pedido:`, `${agent} fue interrumpido al cambiar de modelo. Lo que ya hizo está arriba; continúa este pedido:`, `${agent} was stopped by the model switch. What it already did is above; continue this request:`)}\n\n${asks.filter((ask) => ask.trim()).join("\n\n")}`;
|
|
132
154
|
export const CHILD_DONE_SHOWN_MS = 15000;
|
|
133
|
-
function childState(row: any): { state: "running" | "paused" | "done" | "failed" | "stopped"; end?: number } {
|
|
155
|
+
function childState(row: any, now: number): { state: "running" | "paused" | "done" | "failed" | "stopped"; end?: number } {
|
|
134
156
|
if (row.last === undefined) {
|
|
135
157
|
const busy = Number(row.busy) || 0;
|
|
136
158
|
const idle = Number(row.idle) || 0;
|
|
137
159
|
if (idle && idle >= busy) return { state: row.outcome === "failed" ? "failed" : row.outcome === "interrupted" ? "stopped" : "done", end: idle };
|
|
138
|
-
|
|
160
|
+
// o opencode grava time_suspended também na sessão que está trabalhando (owner 2026-11-28: aparecia "pausado");
|
|
161
|
+
// só vale como pausa se ela parou de gravar. shortcut: um comando mudo por mais de 5 min também aparece pausado
|
|
162
|
+
if (row.suspended && Number(row.suspended) >= busy && now - Number(row.updated) > 5 * 60000) return { state: "paused" };
|
|
139
163
|
return { state: "running" };
|
|
140
164
|
}
|
|
141
165
|
let last: any = {};
|
|
@@ -150,7 +174,7 @@ const CHILD_MARK: Record<string, string | undefined> = { running: undefined, pau
|
|
|
150
174
|
export function childAgents(rows: any[], now: number) {
|
|
151
175
|
const out: any[] = [];
|
|
152
176
|
for (const row of rows ?? []) {
|
|
153
|
-
const { state, end } = childState(row);
|
|
177
|
+
const { state, end } = childState(row, now);
|
|
154
178
|
if (end && now - end > CHILD_DONE_SHOWN_MS) continue; // terminou há tempo: sai da lista
|
|
155
179
|
if (!end && now - Number(row.updated) > 10 * 60000) continue; // parado há 10 min: o processo morreu
|
|
156
180
|
const title = String(row.title ?? "");
|
|
@@ -275,7 +299,10 @@ export function steps(result: any, cwd = "") {
|
|
|
275
299
|
if (part.type === "text" && part.text?.trim()) out.push({ kind: "text", text: part.text });
|
|
276
300
|
// o pensamento chega de uma vez: tempo quase 0 não diz nada; o texto fica para abrir com clique ou ctrl+t (owner 2026-11-25)
|
|
277
301
|
else if (part.type === "thinking") out.push({ kind: "thinking", ms: part.ms >= 100 ? part.ms : 0, text: String(part.thinking ?? "").trim().slice(0, THOUGHT_MAX) });
|
|
278
|
-
else if (part.type === "toolCall")
|
|
302
|
+
else if (part.type === "toolCall") {
|
|
303
|
+
const child = result.subagents?.[part.id]; // lançamento de subagente: bloco próprio com nome e tarefa
|
|
304
|
+
out.push(child ? { kind: "agents", list: [{ agent: child.agent, task: child.task }] } : { kind: "tool", line: pinkTool(part, cwd) });
|
|
305
|
+
}
|
|
279
306
|
}
|
|
280
307
|
}
|
|
281
308
|
return out;
|
|
@@ -283,10 +310,19 @@ export function steps(result: any, cwd = "") {
|
|
|
283
310
|
|
|
284
311
|
// como no Claude Code: ferramentas seguidas viram uma linha de resumo. A tela vira "tela · 16 ações: list_windows,
|
|
285
312
|
// get_window_state ×5, click ×4..." e linhas iguais em sequência viram "linha ×N" (antes eram dezenas de linhas iguais)
|
|
313
|
+
// como no Claude Code: "● 3 subagentes lançados" e uma linha por subagente, com a tarefa (owner 2026-11-28)
|
|
314
|
+
export function agentLines(list: { agent: string; task?: string }[]) {
|
|
315
|
+
const head = list.length === 1 ? t("1 subagente lançado", "1 subagente lanzado", "1 subagent launched") : `${list.length} ${t("subagentes lançados", "subagentes lanzados", "subagents launched")}`;
|
|
316
|
+
return { head, items: list.map((item, index) => ({ branch: index === list.length - 1 ? "└" : "├", agent: clean(item.agent), task: clean(item.task) })) };
|
|
317
|
+
}
|
|
286
318
|
export function compact(list: any[]) {
|
|
287
319
|
const out: any[] = [];
|
|
288
320
|
for (const step of list) {
|
|
289
321
|
const last = out.at(-1);
|
|
322
|
+
if (step.kind === "agents" && last?.kind === "agents") {
|
|
323
|
+
out[out.length - 1] = { kind: "agents", list: [...last.list, ...step.list] };
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
290
326
|
const screen = step.kind === "tool" && String(step.line).startsWith("tela · ");
|
|
291
327
|
if (screen && last?.screen) last.actions.push(String(step.line).split(" ")[2]);
|
|
292
328
|
else if (step.kind === "tool" && last?.kind === "tool" && !last.screen && last.base === step.line) last.count++;
|
|
@@ -306,7 +342,7 @@ export function compact(list: any[]) {
|
|
|
306
342
|
|
|
307
343
|
export function render(result: any, cwd = ""): string {
|
|
308
344
|
const all = compact(steps(result, cwd));
|
|
309
|
-
const tools = all.filter((step) => step.kind === "tool").map((step) => `→ ${step.line}`);
|
|
345
|
+
const tools = all.filter((step) => step.kind === "tool" || step.kind === "agents").map((step) => (step.kind === "tool" ? `→ ${step.line}` : step.list.map((item: any) => `→ ${t("subagente", "subagente", "subagent")} ${item.agent}: ${item.task}`).join("\n")));
|
|
310
346
|
const answer = all.filter((step) => step.kind === "text").at(-1)?.text ?? "";
|
|
311
347
|
const body = [tools.join("\n"), answer].filter(Boolean).join("\n\n");
|
|
312
348
|
if (result.stopReason === "error") return [body, `⚠ ${result.errorMessage}`].filter(Boolean).join("\n\n");
|
|
@@ -320,7 +356,13 @@ export function liveLines(result: any, width: number, cwd = ""): string[] {
|
|
|
320
356
|
const room = Math.max(10, width - 4);
|
|
321
357
|
const head = (text: unknown) => { const line = clean(text); return line.length > room ? `${line.slice(0, room - 1)}…` : line; };
|
|
322
358
|
const tail = (text: unknown) => tailLine(text, room);
|
|
323
|
-
const done = compact(steps(result, cwd)).
|
|
359
|
+
const done = compact(steps(result, cwd)).flatMap((step: any) => {
|
|
360
|
+
if (step.kind === "agents") {
|
|
361
|
+
const block = agentLines(step.list);
|
|
362
|
+
return [`● ${block.head}`, ...block.items.map((item) => ` ${item.branch} ${head(`${item.agent}${item.task ? ` (${item.task})` : ""}`)}`)];
|
|
363
|
+
}
|
|
364
|
+
return [step.kind === "tool" ? `→ ${head(step.line)}` : step.kind === "thinking" ? thinkingLabel(step.ms) : `● ${head(step.text)}`];
|
|
365
|
+
});
|
|
324
366
|
const part = result.partial;
|
|
325
367
|
const now = !part?.text ? [] : part.kind === "thinking"
|
|
326
368
|
? thinkingNow(part.text, room)
|
|
@@ -444,13 +486,17 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
444
486
|
};
|
|
445
487
|
const watchChildren = (ui: any, read = readChildren, dbFile = opencodeDb()) => {
|
|
446
488
|
if (childTimer || !ui?.setWidget) return;
|
|
489
|
+
let shown = false;
|
|
447
490
|
const tick = () => {
|
|
448
491
|
// opencode: o banco dele mostra também os de segundo plano; os outros (e o opencode sem node:sqlite): o fluxo
|
|
449
492
|
const opencode = isOpencode(active?.agent);
|
|
450
493
|
const fromDb = opencode && active?.resume?.id ? read(dbFile, active.resume.id) : [];
|
|
451
494
|
const items = fromDb.length ? fromDb : liveAgents(active?.live, Date.now());
|
|
452
495
|
(globalThis as any).__pinkAgentChildren = items; // a lateral mostra em SUBAGENTES, abaixo da SESSÃO
|
|
453
|
-
|
|
496
|
+
// segue olhando enquanto o /agente estiver ligado: o agente lança subagente sozinho, depois da resposta
|
|
497
|
+
if (!active) return stopChildren(ui);
|
|
498
|
+
if (!items.length && !shown) return;
|
|
499
|
+
shown = items.length > 0;
|
|
454
500
|
const side = (globalThis as any).__pinkRightOn === true; // lateral ligada (pink-ui): os subagentes ficam só nela, como os do Pink
|
|
455
501
|
ui.setWidget(CHILDREN, items.length && !side ? (_screen: any, theme: any) => ({
|
|
456
502
|
render: (width: number) => items.map((item: any) => {
|
|
@@ -541,11 +587,17 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
541
587
|
box.addChild(clickable(new tui.Text(theme.fg("thinkingText", head), pad, 0), () => (opened.thoughts.has(index) ? opened.thoughts.delete(index) : opened.thoughts.add(index))));
|
|
542
588
|
if (open && step.text) box.addChild(new tui.Text(theme.italic ? theme.italic(theme.fg("thinkingText", step.text)) : theme.fg("thinkingText", step.text), pad + 2, 0));
|
|
543
589
|
};
|
|
590
|
+
const drawAgents = (box: any, step: any) => {
|
|
591
|
+
const block = agentLines(step.list);
|
|
592
|
+
box.addChild(new tui.Text(`${theme.fg("success", "●")} ${theme.fg("text", block.head)}`, pad, 0));
|
|
593
|
+
for (const item of block.items) box.addChild(new tui.Text(`${theme.fg("muted", item.branch)} ${bold(theme, theme.fg("text", item.agent))}${item.task ? theme.fg("muted", ` (${item.task})`) : ""}`, pad + 2, 0));
|
|
594
|
+
};
|
|
544
595
|
const drawSteps = (box: any, steps: any[], offset: number) => {
|
|
545
596
|
for (const [index, step] of steps.entries()) {
|
|
546
597
|
// ferramentas seguidas ficam juntas (uma busca na tela são dezenas de chamadas: com linha em branco virava uma tela inteira)
|
|
547
598
|
if (index && !(step.kind === "tool" && steps[index - 1]?.kind === "tool")) box.addChild(new tui.Spacer(1));
|
|
548
599
|
if (step.kind === "thinking") thought(box, step, offset + index);
|
|
600
|
+
else if (step.kind === "agents") drawAgents(box, step);
|
|
549
601
|
else if (step.kind === "tool") box.addChild(new tui.Text(theme.fg("muted", `→ ${step.line}`), pad, 0));
|
|
550
602
|
else box.addChild(bulleted(new tui.Markdown(String(step.text).trim(), pad, 0, coding.getMarkdownTheme())));
|
|
551
603
|
}
|
|
@@ -558,6 +610,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
558
610
|
const open = opened.work || all();
|
|
559
611
|
box.addChild(clickable(new tui.Text(theme.fg("muted", `${open ? "−" : "+"} ${summary}`), pad, 0), () => (opened.work = !opened.work)));
|
|
560
612
|
if (open) box.addChild(new tui.Spacer(1)), drawSteps(box, work, 0);
|
|
613
|
+
else for (const step of work) if (step.kind === "agents") box.addChild(new tui.Spacer(1)), drawAgents(box, step); // lançamento não fica escondido no resumo
|
|
561
614
|
if (answer.length) box.addChild(new tui.Spacer(1));
|
|
562
615
|
drawSteps(box, answer, work.length);
|
|
563
616
|
} else drawSteps(box, list, 0);
|
|
@@ -678,6 +731,82 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
678
731
|
return hits.length ? hits : null;
|
|
679
732
|
};
|
|
680
733
|
|
|
734
|
+
// menu com os modelos que o agente informa; o primeiro item mantém o padrão dele. Pelo /model, um item antes volta aos
|
|
735
|
+
// modelos logados ("back"); `search` (o "/model gpt" digitado) filtra a lista
|
|
736
|
+
const chooseModel = async (agent: any, ctx: any, back?: string, search = ""): Promise<{ model: string; effort: string } | "back" | undefined> => {
|
|
737
|
+
const name = agent.name;
|
|
738
|
+
ctx.ui?.setStatus?.(STATUS, t(`${name}: buscando modelos…`, `${name}: buscando modelos…`, `${name}: fetching models…`));
|
|
739
|
+
let choices: Awaited<ReturnType<typeof listModels>> = [];
|
|
740
|
+
try {
|
|
741
|
+
choices = await models(agent, ctx.cwd);
|
|
742
|
+
} catch (error: any) {
|
|
743
|
+
ctx.ui?.notify?.(t(`Não deu para listar os modelos do ${name} (${error?.message ?? error}); fica o padrão dele.`, `No se pudieron listar los modelos de ${name} (${error?.message ?? error}); queda su predeterminado.`, `Could not list ${name}'s models (${error?.message ?? error}); keeping its default.`), "warning");
|
|
744
|
+
}
|
|
745
|
+
ctx.ui?.setStatus?.(STATUS, active ? `${t("agente", "agente", "agent")}: ${label(active.agent)}` : undefined);
|
|
746
|
+
if (!choices.length && !back) return { model: "", effort: "" };
|
|
747
|
+
const wanted = search.trim().toLowerCase();
|
|
748
|
+
const listed = choices.filter((choice) => !wanted || `${choice.id} ${choice.label}`.toLowerCase().includes(wanted));
|
|
749
|
+
const current = choices.find((choice) => choice.current);
|
|
750
|
+
const keep = t(`Padrão do ${name}${current ? ` (${current.label})` : ""}`, `Predeterminado de ${name}${current ? ` (${current.label})` : ""}`, `${name} default${current ? ` (${current.label})` : ""}`);
|
|
751
|
+
const shown = (listed.length ? listed : choices).map((choice) => (choice.label === choice.id ? choice.id : `${choice.label} — ${choice.id}`));
|
|
752
|
+
const pool = listed.length ? listed : choices;
|
|
753
|
+
const picked = await pick(ctx, t(`Modelo do ${name}`, `Modelo de ${name}`, `${name} model`), [...(back ? [back] : []), keep, ...shown], load);
|
|
754
|
+
if (picked === undefined) return undefined;
|
|
755
|
+
if (picked === back) return "back";
|
|
756
|
+
let model = "", effort = "";
|
|
757
|
+
if (picked !== keep) model = pool[shown.indexOf(picked)]?.id ?? "";
|
|
758
|
+
// esforço (claude e codex informam os níveis de cada modelo); o primeiro item mantém o padrão dele
|
|
759
|
+
const chosen = choices.find((choice) => choice.id === model) ?? current;
|
|
760
|
+
if (chosen?.efforts?.length) {
|
|
761
|
+
const standard = t(`Padrão do ${name}${chosen.effort ? ` (${chosen.effort})` : ""}`, `Predeterminado de ${name}${chosen.effort ? ` (${chosen.effort})` : ""}`, `${name} default${chosen.effort ? ` (${chosen.effort})` : ""}`);
|
|
762
|
+
const level = await pick(ctx, t(`Esforço do ${name}`, `Esfuerzo de ${name}`, `${name} effort`), [standard, ...chosen.efforts], load);
|
|
763
|
+
if (level === undefined) return undefined;
|
|
764
|
+
if (level !== standard) effort = level;
|
|
765
|
+
}
|
|
766
|
+
return { model, effort };
|
|
767
|
+
};
|
|
768
|
+
|
|
769
|
+
// liga o agente (o /agente, o /model com agente e a volta ao último usado ao abrir o Pink)
|
|
770
|
+
const activate = async (agent: any, model: string, effort: string, ctx: any, restored = false) => {
|
|
771
|
+
// o modelo do Pink estava respondendo: para agora e o agente continua o pedido (só um trabalha; owner 2026-11-26)
|
|
772
|
+
const busyAsk = ctx.isIdle?.() === false ? [...(ctx.sessionManager?.getBranch?.() ?? [])].reverse().find((entry: any) => entry?.type === "message" && entry.message?.role === "user") : undefined;
|
|
773
|
+
if (busyAsk) {
|
|
774
|
+
ctx.abort?.();
|
|
775
|
+
await ctx.waitForIdle?.();
|
|
776
|
+
}
|
|
777
|
+
stop(ctx);
|
|
778
|
+
// mesma sessão do Pink + mesmo agente: continua a conversa dele (owner 2026-11-24); sessão nova do Pink começa do zero
|
|
779
|
+
const saved = lastAgentSession(ctx.sessionManager?.getBranch?.(), agent.name);
|
|
780
|
+
active = { agent: { ...agent, ...(model ? { model } : {}), ...(effort ? { effort } : {}), extras: extras((screen ??= bridge(() => screenCtx))) }, resume: { keep: true, ...(saved ? { id: saved } : {}) } }; // keep: o processo do agente ACP fica aberto entre as mensagens; id: retoma a conversa
|
|
781
|
+
active.resume.late = lateTurn(active.agent.name, active.resume, ctx);
|
|
782
|
+
warm(active.agent, ctx.cwd, active.resume); // já liga o agente: a primeira mensagem não espera a partida a frio
|
|
783
|
+
writeLast({ agent: agent.name, ...(model ? { model } : {}), ...(effort ? { effort } : {}) });
|
|
784
|
+
(globalThis as any).__pinkExternalAgent = { name: active.agent.name, model: active.agent.model, effort: active.agent.effort }; // rótulo da caixa (pink-ui)
|
|
785
|
+
ctx.ui?.setStatus?.(STATUS, `${t("agente", "agente", "agent")}: ${label(active.agent)}`);
|
|
786
|
+
const again = saved ? t(" Continuando a conversa anterior dele.", " Continuando su conversación anterior.", " Continuing its previous conversation.") : "";
|
|
787
|
+
const lead = restored ? t("Voltou ao último usado: ", "Volviste al último usado: ", "Back to the last one used: ") : "";
|
|
788
|
+
ctx.ui?.notify?.(lead + t(`Agora suas mensagens vão para o ${label(active.agent)}, com o login e a cota dele.${again} /agente off volta ao Pink.`, `Ahora tus mensajes van a ${label(active.agent)}, con su login y su cuota.${again} /agente off vuelve a Pink.`, `Your messages now go to ${label(active.agent)}, with its own login and quota.${again} /agente off returns to Pink.`), "info");
|
|
789
|
+
if (busyAsk) void send(handoffText(t("modelo do Pink", "modelo de Pink", "Pink model"), [textOfContent(busyAsk.message.content)]), ctx);
|
|
790
|
+
};
|
|
791
|
+
|
|
792
|
+
// /model e ctrl+l com o agente ligado: os modelos DO AGENTE (owner 2026-11-28); o primeiro item abre os modelos logados.
|
|
793
|
+
// O motor chama isto antes do menu dele (rebrand.json, model-menu-agent-module); false = o motor segue com o dele
|
|
794
|
+
(globalThis as any).__pinkRememberModel = true;
|
|
795
|
+
let menuCtx: any;
|
|
796
|
+
(globalThis as any).__pinkAgentModelMenu = (search: string | undefined, pinkMenu: () => void) => {
|
|
797
|
+
const current = active;
|
|
798
|
+
const ctx = menuCtx;
|
|
799
|
+
const agent = current && list().find((item) => item.name === current.agent.name);
|
|
800
|
+
if (!agent || !ctx?.hasUI) return false;
|
|
801
|
+
void (async () => {
|
|
802
|
+
const back = t(`Modelos do Pink (desliga o ${agent.name})`, `Modelos de Pink (apaga ${agent.name})`, `Pink models (turns ${agent.name} off)`);
|
|
803
|
+
const got = await chooseModel(agent, ctx, back, search ?? "");
|
|
804
|
+
if (got === "back") return pinkMenu(); // escolher um ali dispara o model_select, que desliga o agente
|
|
805
|
+
if (got && active === current) await activate(agent, got.model, got.effort, ctx);
|
|
806
|
+
})().catch((error: any) => ctx.ui?.notify?.(t(`Não deu para trocar o modelo: ${error?.message ?? error}`, `No se pudo cambiar el modelo: ${error?.message ?? error}`, `Could not change the model: ${error?.message ?? error}`), "warning"));
|
|
807
|
+
return true;
|
|
808
|
+
};
|
|
809
|
+
|
|
681
810
|
pink.registerCommand("agente", {
|
|
682
811
|
description: t("Conversa direto com um agente instalado (claude, codex, opencode...) com o login dele; /agente off volta ao Pink", "Conversa directo con un agente instalado (claude, codex, opencode...) con su login; /agente off vuelve a Pink", "Talk straight to an installed agent (claude, codex, opencode...) with its own login; /agente off returns to Pink"),
|
|
683
812
|
getArgumentCompletions: completions,
|
|
@@ -686,9 +815,11 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
686
815
|
const wanted = first.toLowerCase();
|
|
687
816
|
let [model = "", effort = ""] = rest; // /agente codex gpt-5 high: agente, modelo e esforço
|
|
688
817
|
const agents = list();
|
|
818
|
+
menuCtx = ctx;
|
|
689
819
|
if (wanted === "off" || wanted === "parar" || wanted === "stop") {
|
|
690
820
|
const was = active?.agent.name;
|
|
691
821
|
stop(ctx);
|
|
822
|
+
writeLast(undefined); // reabrir o Pink volta ao modelo logado
|
|
692
823
|
ctx.ui?.notify?.(was ? t(`Voltou ao Pink (${was} desligado).`, `Volviste a Pink (${was} apagado).`, `Back to Pink (${was} off).`) : t("Nenhum agente ligado.", "Ningún agente encendido.", "No agent on."), "info");
|
|
693
824
|
return;
|
|
694
825
|
}
|
|
@@ -702,6 +833,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
702
833
|
if (name === back) {
|
|
703
834
|
const was = active?.agent.name;
|
|
704
835
|
stop(ctx);
|
|
836
|
+
writeLast(undefined);
|
|
705
837
|
return ctx.ui?.notify?.(t(`Voltou ao Pink (${was} desligado).`, `Volviste a Pink (${was} apagado).`, `Back to Pink (${was} off).`), "info");
|
|
706
838
|
}
|
|
707
839
|
}
|
|
@@ -710,49 +842,11 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
710
842
|
if (rest.length > 2 || (model && !/^[\w./:@-]+$/.test(model))) return ctx.ui?.notify?.(t(`Nome de modelo inválido: ${rest.join(" ")}. Use /agente ${name} <modelo> <esforço>; digite "/agente ${name} " para ver os modelos.`, `Nombre de modelo no válido: ${rest.join(" ")}. Usa /agente ${name} <modelo> <esfuerzo>; escribe "/agente ${name} " para ver los modelos.`, `Invalid model name: ${rest.join(" ")}. Use /agente ${name} <model> <effort>; type "/agente ${name} " to see the models.`), "warning");
|
|
711
843
|
if (effort && !/^[a-z]+$/.test(effort)) return ctx.ui?.notify?.(t(`Esforço inválido: ${effort}. É uma palavra como low, medium ou high; digite "/agente ${name} ${model} " para ver os do modelo.`, `Esfuerzo no válido: ${effort}. Es una palabra como low, medium o high; escribe "/agente ${name} ${model} " para ver los del modelo.`, `Invalid effort: ${effort}. It is a word like low, medium or high; type "/agente ${name} ${model} " to see the model's.`), "warning");
|
|
712
844
|
if (!model && ctx.hasUI) {
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
try {
|
|
717
|
-
choices = await models(agent, ctx.cwd);
|
|
718
|
-
} catch (error: any) {
|
|
719
|
-
ctx.ui?.notify?.(t(`Não deu para listar os modelos do ${name} (${error?.message ?? error}); fica o padrão dele.`, `No se pudieron listar los modelos de ${name} (${error?.message ?? error}); queda su predeterminado.`, `Could not list ${name}'s models (${error?.message ?? error}); keeping its default.`), "warning");
|
|
720
|
-
}
|
|
721
|
-
ctx.ui?.setStatus?.(STATUS, active ? `${t("agente", "agente", "agent")}: ${label(active.agent)}` : undefined);
|
|
722
|
-
if (choices.length) {
|
|
723
|
-
const current = choices.find((choice) => choice.current);
|
|
724
|
-
const keep = t(`Padrão do ${name}${current ? ` (${current.label})` : ""}`, `Predeterminado de ${name}${current ? ` (${current.label})` : ""}`, `${name} default${current ? ` (${current.label})` : ""}`);
|
|
725
|
-
const shown = choices.map((choice) => (choice.label === choice.id ? choice.id : `${choice.label} — ${choice.id}`));
|
|
726
|
-
const picked = await pick(ctx, t(`Modelo do ${name}`, `Modelo de ${name}`, `${name} model`), [keep, ...shown], load);
|
|
727
|
-
if (picked === undefined) return;
|
|
728
|
-
if (picked !== keep) model = choices[shown.indexOf(picked)]?.id ?? "";
|
|
729
|
-
// esforço (claude e codex informam os níveis de cada modelo); o primeiro item mantém o padrão dele
|
|
730
|
-
const chosen = choices.find((choice) => choice.id === model) ?? current;
|
|
731
|
-
if (chosen?.efforts?.length) {
|
|
732
|
-
const standard = t(`Padrão do ${name}${chosen.effort ? ` (${chosen.effort})` : ""}`, `Predeterminado de ${name}${chosen.effort ? ` (${chosen.effort})` : ""}`, `${name} default${chosen.effort ? ` (${chosen.effort})` : ""}`);
|
|
733
|
-
const level = await pick(ctx, t(`Esforço do ${name}`, `Esfuerzo de ${name}`, `${name} effort`), [standard, ...chosen.efforts], load);
|
|
734
|
-
if (level === undefined) return;
|
|
735
|
-
if (level !== standard) effort = level;
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
// o modelo do Pink estava respondendo: para agora e o agente continua o pedido (só um trabalha; owner 2026-11-26)
|
|
740
|
-
const busyAsk = ctx.isIdle?.() === false ? [...(ctx.sessionManager?.getBranch?.() ?? [])].reverse().find((entry: any) => entry?.type === "message" && entry.message?.role === "user") : undefined;
|
|
741
|
-
if (busyAsk) {
|
|
742
|
-
ctx.abort?.();
|
|
743
|
-
await ctx.waitForIdle?.();
|
|
845
|
+
const got = await chooseModel(agent, ctx);
|
|
846
|
+
if (!got || got === "back") return;
|
|
847
|
+
({ model, effort } = got);
|
|
744
848
|
}
|
|
745
|
-
|
|
746
|
-
// mesma sessão do Pink + mesmo agente: continua a conversa dele (owner 2026-11-24); sessão nova do Pink começa do zero
|
|
747
|
-
const saved = lastAgentSession(ctx.sessionManager?.getBranch?.(), agent.name);
|
|
748
|
-
active = { agent: { ...agent, ...(model ? { model } : {}), ...(effort ? { effort } : {}), extras: extras((screen ??= bridge(() => screenCtx))) }, resume: { keep: true, ...(saved ? { id: saved } : {}) } }; // keep: o processo do agente ACP fica aberto entre as mensagens; id: retoma a conversa
|
|
749
|
-
active.resume.late = lateTurn(active.agent.name, active.resume, ctx);
|
|
750
|
-
warm(active.agent, ctx.cwd, active.resume); // já liga o agente: a primeira mensagem não espera a partida a frio
|
|
751
|
-
(globalThis as any).__pinkExternalAgent = { name: active.agent.name, model: active.agent.model, effort: active.agent.effort }; // rótulo da caixa (pink-ui)
|
|
752
|
-
ctx.ui?.setStatus?.(STATUS, `${t("agente", "agente", "agent")}: ${label(active.agent)}`);
|
|
753
|
-
const again = saved ? t(" Continuando a conversa anterior dele.", " Continuando su conversación anterior.", " Continuing its previous conversation.") : "";
|
|
754
|
-
ctx.ui?.notify?.(t(`Agora suas mensagens vão para o ${label(active.agent)}, com o login e a cota dele.${again} /agente off volta ao Pink.`, `Ahora tus mensajes van a ${label(active.agent)}, con su login y su cuota.${again} /agente off vuelve a Pink.`, `Your messages now go to ${label(active.agent)}, with its own login and quota.${again} /agente off returns to Pink.`), "info");
|
|
755
|
-
if (busyAsk) void send(handoffText(t("modelo do Pink", "modelo de Pink", "Pink model"), [textOfContent(busyAsk.message.content)]), ctx);
|
|
849
|
+
await activate(agent, model, effort, ctx);
|
|
756
850
|
},
|
|
757
851
|
});
|
|
758
852
|
|
|
@@ -792,6 +886,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
792
886
|
});
|
|
793
887
|
|
|
794
888
|
pink.on("input", async (event: any, ctx: any) => {
|
|
889
|
+
menuCtx = ctx;
|
|
795
890
|
if (!active || event.source === "extension" || String(event.text ?? "").trimStart().startsWith("/")) return { action: "continue" };
|
|
796
891
|
if (active.controller) {
|
|
797
892
|
// fila (owner 2026-11-24): o que chega enquanto o agente responde vai junto, numa mensagem só, quando ele terminar
|
|
@@ -806,7 +901,9 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
806
901
|
|
|
807
902
|
// escolher um modelo do Pink com o agente ligado volta ao Pink na hora: só um trabalha (owner 2026-11-25, os dois rodavam juntos)
|
|
808
903
|
pink.on("model_select", (event: any, ctx: any) => {
|
|
809
|
-
if (
|
|
904
|
+
if (event?.source === "restore") return; // o motor de hoje não emite; se passar a emitir, restaurar não é escolha da pessoa
|
|
905
|
+
writeLast(undefined); // um modelo logado foi o último usado: o motor já o grava como padrão (rebrand.json, remember-model-*)
|
|
906
|
+
if (!active) return;
|
|
810
907
|
const current = active;
|
|
811
908
|
const was = current.agent.name;
|
|
812
909
|
if (current.controller) current.handoff = [...(current.queue ?? [])];
|
|
@@ -814,6 +911,16 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
814
911
|
ctx?.ui?.notify?.(t(`Voltou ao Pink (${was} desligado).`, `Volviste a Pink (${was} apagado).`, `Back to Pink (${was} off).`), "info");
|
|
815
912
|
});
|
|
816
913
|
|
|
914
|
+
// abrir o Pink com o agente do último uso: só ao abrir o Pink na tela (não no pink -p, no RPC, num /new ou /resume, nem
|
|
915
|
+
// com --model na linha de comando, que é uma escolha explícita)
|
|
916
|
+
pink.on("session_start", async (event: any, ctx: any) => {
|
|
917
|
+
menuCtx = ctx;
|
|
918
|
+
if (active || !ctx?.hasUI || ctx?.mode !== "tui" || !["startup", "reload"].includes(event?.reason) || process.argv.includes("--model")) return;
|
|
919
|
+
const last = readLast();
|
|
920
|
+
const agent = last && list().find((item) => item.name === last.agent);
|
|
921
|
+
if (agent) await activate(agent, last!.model ?? "", last!.effort ?? "", ctx, true);
|
|
922
|
+
});
|
|
923
|
+
|
|
817
924
|
pink.on("session_shutdown", () => {
|
|
818
925
|
stop();
|
|
819
926
|
screen?.close();
|
package/extensions/pink-ui.ts
CHANGED
|
@@ -1307,7 +1307,7 @@ export function toolSummary(name, args = {}, result) {
|
|
|
1307
1307
|
|
|
1308
1308
|
// chamadas seguidas sem texto do modelo no meio viram uma linha só, como no Claude Code ("Rodou 3 comandos, leu 2 arquivos");
|
|
1309
1309
|
// edit, write e o plano ficam de fora: cada um tem a própria linha (e o diff)
|
|
1310
|
-
const GROUP_SKIP = new Set(["edit", "write", "todowrite"]);
|
|
1310
|
+
const GROUP_SKIP = new Set(["edit", "write", "todowrite", "subagent"]);
|
|
1311
1311
|
export function toolGroups(entries) {
|
|
1312
1312
|
const groups = new Map();
|
|
1313
1313
|
let group;
|
|
@@ -1367,6 +1367,16 @@ function groupOf(id) {
|
|
|
1367
1367
|
return PINK.groups.map.get(id);
|
|
1368
1368
|
}
|
|
1369
1369
|
|
|
1370
|
+
// lançamento de subagentes nos modelos do Pink, no mesmo formato do /agente: nome e tarefa de cada um (owner 2026-11-28)
|
|
1371
|
+
export function subagentLaunch(args, theme, pad, width) {
|
|
1372
|
+
const list = (Array.isArray(args?.tasks) ? args.tasks : Array.isArray(args?.chain) ? args.chain : [args]).filter((item) => item?.agent);
|
|
1373
|
+
if (!list.length) return [];
|
|
1374
|
+
const flat = (text) => String(text ?? "").replace(/\{previous\}/g, "").replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim();
|
|
1375
|
+
const head = list.length === 1 ? t("1 subagente lançado", "1 subagente lanzado", "1 subagent launched") : `${list.length} ${t("subagentes lançados", "subagentes lanzados", "subagents launched")}`;
|
|
1376
|
+
const margin = " ".repeat(pad);
|
|
1377
|
+
return [`${margin}${theme.fg("success", "●")} ${theme.fg("text", head)}${args.background ? theme.fg("dim", t(" em segundo plano", " en segundo plano", " in the background")) : ""}`, ...list.map((item, index) => `${margin} ${theme.fg("muted", index === list.length - 1 ? "└" : "├")} ${theme.fg("text", flat(item.agent))}${flat(item.task) ? theme.fg("muted", ` (${flat(item.task)})`) : ""}`)].map((row) => fit(row, width));
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1370
1380
|
export function compactToolRenderer(toolName, next) {
|
|
1371
1381
|
const base = next?.();
|
|
1372
1382
|
const empty = { render: () => [], invalidate() {} };
|
|
@@ -1396,6 +1406,7 @@ export function compactToolRenderer(toolName, next) {
|
|
|
1396
1406
|
renderShell: "self",
|
|
1397
1407
|
renderCall(args, theme, context) {
|
|
1398
1408
|
if (context.expanded) return wrap(base?.renderCall?.(args, theme, context) ?? line(theme, 0, `${toolName} ${shorten(JSON.stringify(args ?? {}), 80)}`), context.outputPad);
|
|
1409
|
+
if (toolName === "subagent") return { render: (width) => subagentLaunch(args, theme, context.outputPad, width), invalidate() {} };
|
|
1399
1410
|
return context.isPartial ? grouped(theme, context.outputPad, context.toolCallId, line(theme, context.outputPad, toolSummary(toolName, args ?? {}), theme.fg("dim", " …"))) : empty;
|
|
1400
1411
|
},
|
|
1401
1412
|
renderResult(result, options, theme, context) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@thothdev/pink",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.30",
|
|
4
4
|
"description": "Open-source AI coding agent for the terminal that also drives Claude Code, Codex, OpenCode and other agents, with parallel sessions, visible plan and changes, and real undo.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"piConfig": {
|