@thothdev/pink 1.0.10 → 1.0.11
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 +48 -27
- package/NOTICE.md +4 -0
- package/dist/bundle/chunks/chunk-MM3LKT73.js +3 -3
- package/examples/extensions/subagent/external.ts +82 -2
- package/extensions/pink-agente.ts +208 -26
- package/extensions/pink-microfone-lock.json +221 -0
- package/extensions/pink-microfone.ts +372 -0
- package/extensions/pink-ui.ts +92 -18
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,9 +3,30 @@
|
|
|
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.11] - 2026-11-25
|
|
7
|
+
|
|
8
|
+
- /agente como o OpenCode: o trabalho antes da resposta vira uma linha "+ 2 comandos, 3 pensamentos" que abre com
|
|
9
|
+
clique; cada "+ Pensou · 5.3s" abre e mostra o raciocínio. Ctrl+T abre o de todas.
|
|
10
|
+
- /agente: as mensagens na fila ficam em cima do "Trabalhando", com uma linha vazia até a caixa. Ctrl+Enter interrompe
|
|
11
|
+
o agente e manda na hora, junto com a fila. A caixa mostra "esc interromper · ctrl+enter enviar agora".
|
|
12
|
+
- Permissão pedida pelo agente (opencode e os outros ACP) diz o que ele quer fazer: tipo, comando, arquivos e motivo.
|
|
13
|
+
As opções aparecem como "Sim / Não".
|
|
14
|
+
- As personas do DAG do Thoth (`thoth-client dag run`) aparecem em SUBAGENTES enquanto ele roda: quem está rodando,
|
|
15
|
+
esperando, pronto ou falhou (o Thoth grava `.thoth/dag/live.json`).
|
|
16
|
+
- /agente: os subagentes de todos os agentes aparecem em SUBAGENTES, rodando, pausado, pronto ou falhou: Claude Code
|
|
17
|
+
(Task/Agent), Codex (spawnAgent) e os ACP (opencode, cline, gemini, qwen, goose, copilot). No opencode, o Pink lê
|
|
18
|
+
também as sessões filhas no banco dele (só leitura), e os de segundo plano seguem na lista depois da resposta. Sem a
|
|
19
|
+
lateral (terminal estreito), a lista fica acima da caixa.
|
|
20
|
+
- SUBAGENTES passou para o fim da lateral, abaixo da SESSÃO.
|
|
21
|
+
- A lista de comandos não some mais no meio da palavra (digitando /resume, ela sumia no "/resu").
|
|
22
|
+
|
|
6
23
|
## [1.0.10] - 2026-11-24
|
|
7
24
|
|
|
8
|
-
-
|
|
25
|
+
- Microfone opcional, como no Claude e no Codex desktop: `/microfone instalar` (com o seu ok, ~530 MB uma vez) põe o
|
|
26
|
+
mesmo modelo do OpenBot, NVIDIA Parakeet TDT 0.6B v3, rodando local com o sherpa-onnx. Na tela cheia, a caixa de
|
|
27
|
+
digitar ganha o botão "◉ falar": a fala aparece ao vivo na caixa, e "‖ pausar", "■ parar" (o texto fica na caixa)
|
|
28
|
+
e "➤ enviar" (manda ao agente). O áudio não sai da máquina; sem instalar, nada muda.
|
|
29
|
+
- Inclui tudo da 1.0.9 (a 1.0.9 também está no npm).
|
|
9
30
|
|
|
10
31
|
## [1.0.9] - 2026-11-24
|
|
11
32
|
|
|
@@ -27,32 +48,32 @@ versão está no campo `upstream` do `rebrand.json` do repositório.
|
|
|
27
48
|
|
|
28
49
|
- Publicada no meio do trabalho, com só parte das mudanças acima; use a 1.0.9.
|
|
29
50
|
|
|
30
|
-
## [1.0.7] - 2026-11-24
|
|
31
|
-
|
|
32
|
-
- `/agente`: os menus de agente, modelo e esforço têm busca, como o `/model` (digite para filtrar, setas, Enter, Esc).
|
|
33
|
-
- `/agente` com opencode e outros agentes ACP: o agente já liga e abre a sessão quando é escolhido; a primeira mensagem
|
|
34
|
-
não espera a partida a frio (19 s → 8 s no teste com o opencode).
|
|
35
|
-
|
|
36
|
-
## [1.0.6] - 2026-11-24
|
|
37
|
-
|
|
38
|
-
- `/agente`: ferramentas seguidas viram uma linha de resumo, como no Claude Code (`→ tela · 26 ações: click ×6, ...`,
|
|
39
|
-
`→ Leu a.ts ×2`).
|
|
40
|
-
- Pink nativo: a tela tem nome próprio no grupo de ferramentas (`Usou a tela (26 ações), leu 1 arquivo`).
|
|
41
|
-
- A 1.0.5 ficou presa no npm (staged) e não foi publicada; o que estava nela vem nesta.
|
|
42
|
-
|
|
43
|
-
## [1.0.5] - 2026-11-24
|
|
44
|
-
|
|
45
|
-
- `/agente`: escolha do esforço (`/agente codex gpt-5.5 high`, ou o menu depois do modelo) no Claude e no codex; o
|
|
46
|
-
opencode não tem esforço.
|
|
47
|
-
- `/agente`: mensagem enviada enquanto o agente trabalha entra na fila e vai quando ele terminar (`/agente off` descarta).
|
|
48
|
-
- `/agente`: as chamadas da tela dizem o que fizeram (`→ tela · click 120, 340`, `→ tela · type_text "RTX 5070 Ti"`) e
|
|
49
|
-
ferramentas seguidas ficam juntas, sem linha em branco.
|
|
50
|
-
- `/agente` com codex: a tela do Pink e o `pink_tarefa` têm até 16 min por chamada (o padrão do codex, 60 s, estourava
|
|
51
|
-
com a confirmação esperando a pessoa).
|
|
52
|
-
- Contorno da `/tela`: fica aceso enquanto o agente trabalha e apaga quando ele termina (antes apagava 4 s depois de
|
|
53
|
-
cada ação e piscava).
|
|
54
|
-
- A ferramenta de tela pede ao agente que siga até terminar o pedido, sem parar depois de uma ação.
|
|
55
|
-
|
|
51
|
+
## [1.0.7] - 2026-11-24
|
|
52
|
+
|
|
53
|
+
- `/agente`: os menus de agente, modelo e esforço têm busca, como o `/model` (digite para filtrar, setas, Enter, Esc).
|
|
54
|
+
- `/agente` com opencode e outros agentes ACP: o agente já liga e abre a sessão quando é escolhido; a primeira mensagem
|
|
55
|
+
não espera a partida a frio (19 s → 8 s no teste com o opencode).
|
|
56
|
+
|
|
57
|
+
## [1.0.6] - 2026-11-24
|
|
58
|
+
|
|
59
|
+
- `/agente`: ferramentas seguidas viram uma linha de resumo, como no Claude Code (`→ tela · 26 ações: click ×6, ...`,
|
|
60
|
+
`→ Leu a.ts ×2`).
|
|
61
|
+
- Pink nativo: a tela tem nome próprio no grupo de ferramentas (`Usou a tela (26 ações), leu 1 arquivo`).
|
|
62
|
+
- A 1.0.5 ficou presa no npm (staged) e não foi publicada; o que estava nela vem nesta.
|
|
63
|
+
|
|
64
|
+
## [1.0.5] - 2026-11-24
|
|
65
|
+
|
|
66
|
+
- `/agente`: escolha do esforço (`/agente codex gpt-5.5 high`, ou o menu depois do modelo) no Claude e no codex; o
|
|
67
|
+
opencode não tem esforço.
|
|
68
|
+
- `/agente`: mensagem enviada enquanto o agente trabalha entra na fila e vai quando ele terminar (`/agente off` descarta).
|
|
69
|
+
- `/agente`: as chamadas da tela dizem o que fizeram (`→ tela · click 120, 340`, `→ tela · type_text "RTX 5070 Ti"`) e
|
|
70
|
+
ferramentas seguidas ficam juntas, sem linha em branco.
|
|
71
|
+
- `/agente` com codex: a tela do Pink e o `pink_tarefa` têm até 16 min por chamada (o padrão do codex, 60 s, estourava
|
|
72
|
+
com a confirmação esperando a pessoa).
|
|
73
|
+
- Contorno da `/tela`: fica aceso enquanto o agente trabalha e apaga quando ele termina (antes apagava 4 s depois de
|
|
74
|
+
cada ação e piscava).
|
|
75
|
+
- A ferramenta de tela pede ao agente que siga até terminar o pedido, sem parar depois de uma ação.
|
|
76
|
+
|
|
56
77
|
## [1.0.4] - 2026-11-24
|
|
57
78
|
|
|
58
79
|
- `/tela`: no pedido de confirmação, "Sim, e não perguntar de novo para o msedge.exe" libera aquele programa até
|
package/NOTICE.md
CHANGED
|
@@ -16,6 +16,10 @@ O que o Pink muda em relação ao Pi 1.4.0 (a lista completa e verificada está
|
|
|
16
16
|
dos temas de código do Codex (2026-11-15);
|
|
17
17
|
- ferramentas opcionais, todas desligadas até a pessoa ligar no `/ferramentas` (`extensions/pink-natives.ts`, 2026-11-15): o Ponytail (`@dietrichgebert/ponytail`, MIT, copyright de Dietrich Gebert) vem como
|
|
18
18
|
dependência npm de versão fixa; RTK, Headroom e graphify **não** vêm junto (o RTK tem partes BUSL-1.1): o Pink só usa os que já estão instalados na máquina;
|
|
19
|
+
- o microfone opcional (`/microfone instalar`, `extensions/pink-microfone.ts`, 2026-11-25): **nada vem no pacote**; com o ok da pessoa, o Pink baixa para
|
|
20
|
+
`~/.pink/agent/microfone` o sherpa-onnx (`sherpa-onnx-node`, Apache-2.0, copyright do Next-gen Kaldi team) e o decibri (Apache-2.0), que traz o
|
|
21
|
+
Silero VAD (MIT, copyright da Silero Team), e o modelo **NVIDIA Parakeet TDT 0.6B v3** (CC-BY-4.0, copyright (c) NVIDIA Corporation), convertido para
|
|
22
|
+
ONNX int8 pelo projeto sherpa-onnx; a transcrição roda na máquina e o áudio não sai dela;
|
|
19
23
|
- só as próprias pastas de skills (`~/.pink/agent/skills`, `.pink/skills`, pacotes e MCP): as pastas `.agents/skills`, compartilhadas com outros agentes, ficam de fora;
|
|
20
24
|
- alguns padrões: tela cheia, pensamento recolhido, início silencioso e barra de rolagem escondida. A troca de modelo passou de `ctrl+p` para `f2`/`shift+f2`, e o `ctrl+p` agora
|
|
21
25
|
abre a paleta (2026-10-28).
|
|
@@ -986,14 +986,14 @@ ${warningLines()}`,0,0)),this.loadedResourcesContainer.addChild(new Spacer(1))}l
|
|
|
986
986
|
${warningLines()}`,0,0)),this.loadedResourcesContainer.addChild(new Spacer(1))}let extensionDiagnostics=[],extensionsResult=this.session.resourceLoader.getExtensions();for(let error of extensionsResult.errors)extensionDiagnostics.push({type:"error",message:error.error,path:error.path});for(let warning of extensionsResult.warnings??[])extensionDiagnostics.push({type:"warning",message:warning.warning,path:warning.path});let commandDiagnostics=this.session.extensionRunner.getCommandDiagnostics();extensionDiagnostics.push(...commandDiagnostics),extensionDiagnostics.push(...this.getBuiltInCommandConflictDiagnostics(this.session.extensionRunner));let shortcutDiagnostics=this.session.extensionRunner.getShortcutDiagnostics();if(extensionDiagnostics.push(...shortcutDiagnostics),extensionDiagnostics.length>0){let warningLines=()=>this.formatDiagnostics(extensionDiagnostics,sourceInfos);this.loadedResourcesContainer.addChild(new ThemedText(()=>`${theme.fg("warning","[Extension issues]")}
|
|
987
987
|
${warningLines()}`,0,0)),this.loadedResourcesContainer.addChild(new Spacer(1))}let themeDiagnostics=themesResult.diagnostics;if(themeDiagnostics.length>0){let warningLines=()=>this.formatDiagnostics(themeDiagnostics,sourceInfos);this.loadedResourcesContainer.addChild(new ThemedText(()=>`${theme.fg("warning","[Theme conflicts]")}
|
|
988
988
|
${warningLines()}`,0,0)),this.loadedResourcesContainer.addChild(new Spacer(1))}}}async bindCurrentSessionExtensions(){let uiContext=this.createExtensionUIContext();await this.session.bindExtensions({uiContext,mode:"tui",abortHandler:()=>{this.restoreQueuedMessagesToEditor({abort:!0})},commandContextActions:{waitForIdle:()=>this.session.waitForIdle(),newSession:async options=>{this.clearStatusIndicator();try{return await this.runtimeHost.newSession(options)}catch(error){return this.handleFatalRuntimeError("Failed to create session",error)}},fork:async(entryId,options)=>{try{let result=await this.runtimeHost.fork(entryId,options);return result.cancelled||(this.editor.setText(result.selectedText??""),this.showStatus("Forked to new session")),{cancelled:result.cancelled}}catch(error){return this.handleFatalRuntimeError("Failed to fork session",error)}},navigateTree:async(targetId,options)=>{let result=await this.session.navigateTree(targetId,{summarize:options?.summarize,customInstructions:options?.customInstructions,replaceInstructions:options?.replaceInstructions,label:options?.label});return result.cancelled?{cancelled:!0}:(this.chatContainer.clear(),this.renderInitialMessages(),result.editorText&&!this.editor.getText().trim()&&this.editor.setText(result.editorText),this.showStatus("Navigated to selected point"),this.flushCompactionQueue({willRetry:!1}),{cancelled:!1})},switchSession:async(sessionPath,options)=>this.handleResumeSession(sessionPath,options),reload:async()=>{await this.handleReloadCommand()}},shutdownHandler:()=>{this.shutdownRequested=!0,this.session.isIdle&&this.shutdown()},onError:error=>{this.showExtensionError(error.extensionPath,error.error,error.stack)}}),setRegisteredThemes(this.session.resourceLoader.getThemes().themes),this.setupAutocompleteProvider();let extensionRunner=this.session.extensionRunner;this.setupExtensionShortcuts(extensionRunner),this.showLoadedResources({force:!1,showDiagnosticsWhenQuiet:!0}),this.showStartupNoticesIfNeeded()}applyFullscreenScrollbarSetting(){this.transcriptScrollView?.setScrollbar(this.settingsManager.getFullscreenScrollbar())}ensurePngTranscoder(){ensurePngTranscoder(()=>{this.ui.invalidate(),this.ui.requestRender()})}applyRuntimeSettings(){setCapabilityOverrides(this.settingsManager.getTerminalCapabilityOverrides()),this.ensurePngTranscoder(),configureHttpDispatcher(this.settingsManager.getHttpIdleTimeoutMs()),this.applyFullscreenScrollbarSetting(),this.renderer instanceof TuiAltScreen&&(this.renderer.setCopyOnSelect(this.settingsManager.getFullscreenCopyOnSelect()),this.renderer.setWheelScrollLines(this.settingsManager.getFullscreenWheelScrollLines())),this.footer.setSession(this.session),this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled),this.footerDataProvider.setCwd(this.sessionManager.getCwd()),this.hideThinkingBlock=this.settingsManager.getHideThinkingBlock(),this.outputPad=this.settingsManager.getOutputPad(),this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());let clearOnShrink=this.settingsManager.getClearOnShrink();this.ui.setClearOnShrink(clearOnShrink),!clearOnShrink&&!this.activeStatusIndicator&&this.statusContainer.clear();let editorPaddingX=this.settingsManager.getEditorPaddingX(),autocompleteMaxVisible=this.settingsManager.getAutocompleteMaxVisible();this.defaultEditor.setPaddingX(editorPaddingX),this.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible),this.editor!==this.defaultEditor&&(this.editor.setPaddingX?.(editorPaddingX),this.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible))}async rebindCurrentSession(options={}){let session=this.session;this.unsubscribe?.(),this.unsubscribe=void 0,this.programStatus.reset(),this.applyRuntimeSettings(),options.renderBeforeBind&&(this.renderCurrentSessionState(),this.subscribeToAgent()),await this.bindCurrentSessionExtensions(),this.session===session&&(options.renderBeforeBind||this.subscribeToAgent(),await this.updateAvailableProviderCount(),this.updateEditorBorderColor(),this.updateTerminalTitle())}async handleFatalRuntimeError(prefix,error){let message=error instanceof Error?error.message:String(error);this.showError(`${prefix}: ${message}`);let extensionHint=this.getCrashExtensionHint(error);if(extensionHint&&this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",extensionHint),this.outputPad,0)),this.recordCrash("fatal_error",error)){let instructions=this.crashReportInstructions();this.chatContainer.addChild(new ThemedText(()=>theme.fg("muted",instructions),this.outputPad,0))}stopThemeWatcher(),this.stop("transcript"),process.exit(1)}getCrashExtensionHint(error){try{return formatCrashExtensionHint(findExtensionStackMatches(error instanceof Error?error.stack:void 0,this.session.resourceLoader.getExtensions().extensions))}catch{return}}recordCrash(kind,error){try{return recordCrash({kind,error,sessionFile:this.session.sessionFile,cwd:this.session.sessionManager.getCwd()})!==void 0}catch{return!1}}crashReportInstructions(){return`Restart pink to continue.`}suggestBugReport(){return;this.bugReportHintShown||(this.bugReportHintShown=!0,this.chatContainer.addChild(new ThemedText(()=>theme.fg("muted",``),this.outputPad,0)),this.ui.requestRender())}maybeSuggestBugReport(message){message.stopReason!=="error"||isRetryableAssistantError(message)||/\b(?:abort(?:ed)?|cancel(?:l?ed)?)\b/i.test(message.errorMessage??"")||this.maybeShowInstallChangeWarning()||this.suggestBugReport()}maybeShowInstallChangeWarning(){if(this.installChangeWarningShown)return!0;let change=detectInstallChange();if(!change)return!1;this.installChangeWarningShown=!0;let cause=change.kind==="updated"?`${APP_NAME} was updated to ${change.version} while this session was running (${VERSION})`:`The ${APP_NAME} installation this session runs from was removed or replaced`,resumeCommand=formatResumeCommand(this.sessionManager),restart=resumeCommand?`Restart with \`${resumeCommand}\` to continue this session.`:`Restart ${APP_NAME}.`;return this.showWarning(`${cause}. Features that load code on demand can fail until restart. ${restart}`),!0}renderCurrentSessionState(){this.loadedResourcesContainer.clear(),this.chatContainer.clear(),this.pendingMessagesContainer.clear(),this.compactionQueuedMessages=[],this.streamingComponent=void 0,this.streamingMessage=void 0,this.pendingTools.clear(),this.renderInitialMessages()}getRegisteredToolDefinition(toolName){return this.session.extensionRunner.resolveToolRenderers(toolName,()=>withBuiltInRenderers(toolName,this.session.getToolDefinition(toolName)))}getMarkdownTransformers(){return[this.mermaidMarkdownTransformer,...this.session.extensionRunner.getMarkdownTransformers()]}setupExtensionShortcuts(extensionRunner){let shortcuts=extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());if(shortcuts.size===0)return;let createContext=()=>({ui:this.createExtensionUIContext(),mode:"tui",hasUI:!0,cwd:this.sessionManager.getCwd(),sessionManager:this.sessionManager,modelRegistry:extensionRunner.getModelRegistry(),model:this.session.model,scopedModels:this.session.scopedModels,thinkingLevel:this.session.thinkingLevel,isIdle:()=>this.session.isIdle,isProjectTrusted:()=>this.settingsManager.isProjectTrusted(),signal:this.session.agent.signal,abort:()=>{this.restoreQueuedMessagesToEditor({abort:!0})},hasPendingMessages:()=>this.session.pendingMessageCount>0,shutdown:()=>{this.shutdownRequested=!0},getContextUsage:()=>this.session.getContextUsage(),compact:options=>{(async()=>{try{let result=await this.session.compact(options?.customInstructions);options?.onComplete?.(result)}catch(error){let err=error instanceof Error?error:new Error(String(error));options?.onError?.(err)}})()},getSystemPrompt:()=>this.session.systemPrompt});this.defaultEditor.onExtensionShortcut=data=>{for(let[shortcutStr,shortcut]of shortcuts)if(matchesKey(data,shortcutStr))return Promise.resolve(shortcut.handler(createContext())).catch(err=>{this.showError(`Shortcut handler error: ${err instanceof Error?err.message:String(err)}`)}),!0;return!1}}setExtensionStatus(key,text){this.footerDataProvider.setExtensionStatus(key,text),this.ui.requestRender()}setEditorWorkingStatusIndicator(indicator){return this.defaultEditor.setWorkingStatusIndicator(void 0),isEmbeddedStatus(this.editor)?(this.editor.setWorkingStatusIndicator(indicator),!0):!1}showStatusIndicator(indicator){if(this.activeStatusIndicator?.dispose(),this.activeStatusIndicator=indicator,this.activeWorkingIndicatorEmbedded=!1,this.statusContainer.clear(),this.setEditorWorkingStatusIndicator(void 0),this.setEditorWorkingStatusIndicator(indicator)){this.activeWorkingIndicatorEmbedded=!0;return}this.statusContainer.addChild(indicator)}clearStatusIndicator(kind){if(kind&&this.activeStatusIndicator?.kind!==kind)return;let clearedIndicator=this.activeStatusIndicator,clearedIndicatorWasEmbedded=this.activeWorkingIndicatorEmbedded;clearedIndicator?.dispose(),this.activeStatusIndicator=void 0,this.activeWorkingIndicatorEmbedded=!1,this.statusContainer.clear(),this.setEditorWorkingStatusIndicator(void 0),clearedIndicator&&!clearedIndicatorWasEmbedded&&this.options.tuiMode==="regular"&&this.ui.getClearOnShrink()&&this.statusContainer.addChild(this.idleStatus)}showWorkingStatusIndicator(){let colorFn=isEmbeddedStatus(this.editor)?text=>(this.editor.borderColor??theme.getThinkingBorderColor(this.session.thinkingLevel||"off"))(text):void 0;this.showStatusIndicator(new WorkingStatusIndicator(this.ui,this.workingMessage??this.defaultWorkingMessage,this.workingIndicatorOptions,colorFn))}setWorkingVisible(visible){if(this.workingVisible=visible,!visible){this.clearStatusIndicator("working"),this.ui.requestRender();return}this.session.isStreaming&&this.activeStatusIndicator?.kind!=="working"&&this.showWorkingStatusIndicator(),this.ui.requestRender()}setWorkingIndicator(options){this.workingIndicatorOptions=options,this.activeStatusIndicator?.kind==="working"&&this.activeStatusIndicator.setIndicator(options),this.ui.requestRender()}setHiddenThinkingLabel(label){this.hiddenThinkingLabel=label??this.defaultHiddenThinkingLabel;for(let child of this.chatContainer.children)child instanceof AssistantMessageComponent&&child.setHiddenThinkingLabel(this.hiddenThinkingLabel);this.streamingComponent&&this.streamingComponent.setHiddenThinkingLabel(this.hiddenThinkingLabel),this.ui.requestRender()}setExtensionWidget(key,content,options){let placement=options?.placement??"aboveEditor",removeExisting=map=>{let existing=map.get(key);existing?.dispose&&existing.dispose(),map.delete(key)};if(removeExisting(this.extensionWidgetsAbove),removeExisting(this.extensionWidgetsBelow),content===void 0){this.renderWidgets();return}let component;if(Array.isArray(content)){let container=new Container;for(let line of content.slice(0,_InteractiveMode.MAX_WIDGET_LINES))container.addChild(new Text(line,1,0));content.length>_InteractiveMode.MAX_WIDGET_LINES&&container.addChild(new ThemedText(()=>theme.fg("muted","... (widget truncated)"),1,0)),component=container}else component=content(this.ui,theme);(placement==="belowEditor"?this.extensionWidgetsBelow:this.extensionWidgetsAbove).set(key,component),this.renderWidgets()}clearExtensionWidgets(){for(let widget of this.extensionWidgetsAbove.values())widget.dispose?.();for(let widget of this.extensionWidgetsBelow.values())widget.dispose?.();this.extensionWidgetsAbove.clear(),this.extensionWidgetsBelow.clear(),this.renderWidgets()}resetExtensionUI(){if(this.extensionDialogs.length>0){for(let dialog of this.extensionDialogs)dialog.component.dispose?.();this.extensionDialogs=[],this.showTopExtensionDialog()}this.ui.hideOverlay(),this.clearExtensionTerminalInputListeners(),this.setExtensionFooter(void 0),this.setExtensionHeader(void 0),this.clearExtensionWidgets(),this.footerDataProvider.clearExtensionStatuses(),this.footer.invalidate(),this.autocompleteProviderWrappers=[],this.setCustomEditorComponent(void 0),this.setupAutocompleteProvider(),this.defaultEditor.onExtensionShortcut=void 0,this.updateTerminalTitle(),this.workingMessage=void 0,this.workingVisible=!0,this.setWorkingIndicator(),this.activeStatusIndicator?.kind==="working"&&this.activeStatusIndicator.setMessage(`${this.defaultWorkingMessage} (${keyText("app.interrupt")} to interrupt)`),this.setHiddenThinkingLabel()}static MAX_WIDGET_LINES=10;renderWidgets(){!this.widgetContainerAbove||!this.widgetContainerBelow||(this.renderWidgetContainer(this.widgetContainerAbove,this.extensionWidgetsAbove,!0,!0),this.renderWidgetContainer(this.widgetContainerBelow,this.extensionWidgetsBelow,!1,!1),this.ui.requestRender())}renderWidgetContainer(container,widgets,spacerWhenEmpty,leadingSpacer){if(container.clear(),widgets.size===0){spacerWhenEmpty&&container.addChild({render:()=>this.activeStatusIndicator&&!this.activeWorkingIndicatorEmbedded?[]:[""],invalidate(){}});return}leadingSpacer&&container.addChild({render:()=>this.activeStatusIndicator&&!this.activeWorkingIndicatorEmbedded?[]:[""],invalidate(){}});for(let component of widgets.values())container.addChild(component)}setExtensionFooter(factory){this.customFooter?.dispose&&this.customFooter.dispose(),this.footerContainer.clear(),factory?(this.customFooter=factory(this.ui,theme,this.footerDataProvider),this.footerContainer.addChild(this.customFooter)):(this.customFooter=void 0,this.footerContainer.addChild(this.footer)),this.ui.requestRender()}setExtensionHeader(factory){if(!this.builtInHeader)return;this.customHeader?.dispose&&this.customHeader.dispose();let currentHeader=this.customHeader||this.builtInHeader,index3=this.headerContainer.children.indexOf(currentHeader);factory?(this.customHeader=factory(this.ui,theme),isExpandable(this.customHeader)&&this.customHeader.setExpanded(this.toolOutputExpanded),index3!==-1?this.headerContainer.children[index3]=this.customHeader:this.headerContainer.children.unshift(this.customHeader)):(this.customHeader=void 0,isExpandable(this.builtInHeader)&&this.builtInHeader.setExpanded(this.toolOutputExpanded),index3!==-1&&(this.headerContainer.children[index3]=this.builtInHeader)),this.ui.requestRender()}addExtensionTerminalInputListener(handler){let subscription={handler,unsubscribe:this.ui.addInputListener(handler)};return this.extensionTerminalInputSubscriptions.add(subscription),()=>{subscription.unsubscribe(),this.extensionTerminalInputSubscriptions.delete(subscription)}}rebindExtensionTerminalInputListeners(){for(let subscription of this.extensionTerminalInputSubscriptions)subscription.unsubscribe(),subscription.unsubscribe=this.ui.addInputListener(subscription.handler)}clearExtensionTerminalInputListeners(){for(let subscription of this.extensionTerminalInputSubscriptions)subscription.unsubscribe();this.extensionTerminalInputSubscriptions.clear()}createProjectTrustContext(cwd){let ui=this.createExtensionUIContext();return{cwd,mode:"tui",hasUI:!0,ui:{select:ui.select,confirm:ui.confirm,input:ui.input,notify:ui.notify}}}createExtensionUIContext(){return{select:(title,options,opts)=>this.showExtensionSelector(title,options,opts),confirm:(title,message,opts)=>this.showExtensionConfirm(title,message,opts),input:(title,placeholder,opts)=>this.showExtensionInput(title,placeholder,opts),notify:(message,type)=>this.showExtensionNotify(message,type),onTerminalInput:handler=>this.addExtensionTerminalInputListener(handler),setStatus:(key,text)=>this.setExtensionStatus(key,text),setWorkingMessage:message=>{this.workingMessage=message,this.activeStatusIndicator?.kind==="working"&&this.activeStatusIndicator.setMessage(message??this.defaultWorkingMessage)},setWorkingVisible:visible=>this.setWorkingVisible(visible),setWorkingIndicator:options=>this.setWorkingIndicator(options),setHiddenThinkingLabel:label=>this.setHiddenThinkingLabel(label),setWidget:(key,content,options)=>this.setExtensionWidget(key,content,options),setFooter:factory=>this.setExtensionFooter(factory),setHeader:factory=>this.setExtensionHeader(factory),setTitle:title=>this.ui.terminal.setTitle(title),custom:(factory,options)=>this.showExtensionCustom(factory,options),pasteToEditor:text=>this.editor.handleInput(`\x1B[200~${text}\x1B[201~`),setEditorText:text=>this.editor.setText(text),getEditorText:()=>this.editor.getExpandedText?.()??this.editor.getText(),editor:(title,prefill)=>this.showExtensionEditor(title,prefill),addAutocompleteProvider:factory=>{this.autocompleteProviderWrappers.push(factory),this.setupAutocompleteProvider()},setEditorComponent:factory=>this.setCustomEditorComponent(factory),getEditorComponent:()=>this.editorComponentFactory,get theme(){return theme},getAllThemes:()=>getAvailableThemesWithPaths(),getTheme:name=>getThemeByName(name),setTheme:themeOrName=>{if(themeOrName instanceof Theme)return this.themeController.setThemeInstance(themeOrName);let result=this.themeController.setThemeName(themeOrName);return result.success&&this.settingsManager.getTheme()!==themeOrName&&this.settingsManager.setTheme(themeOrName),result},getToolsExpanded:()=>this.toolOutputExpanded,setToolsExpanded:expanded=>this.setToolsExpanded(expanded)}}pushExtensionDialog(component,blocked){this.disposeActiveSelector(),this.extensionDialogs.push({component,blocked}),this.showTopExtensionDialog()}removeExtensionDialog(component){let index3=this.extensionDialogs.findIndex(dialog=>dialog.component===component);index3!==-1&&(this.extensionDialogs.splice(index3,1),index3===this.extensionDialogs.length&&this.showTopExtensionDialog())}showTopExtensionDialog(){let top=this.extensionDialogs.at(-1),component=top?.component??this.editor;this.editorContainer.clear(),this.editorContainer.addChild(component),this.ui.setFocus(component),this.programStatus.setBlocked("extension-dialog",top?.blocked),this.ui.requestRender()}showExtensionSelector(title,options,opts,blocked={kind:"question",message:title}){return new Promise(resolve16=>{if(opts?.signal?.aborted){resolve16(void 0);return}let finish=option=>{opts?.signal?.removeEventListener("abort",onAbort),selector.dispose(),this.removeExtensionDialog(selector),resolve16(option)},onAbort=()=>finish(void 0);opts?.signal?.addEventListener("abort",onAbort,{once:!0});let selector=new ExtensionSelectorComponent(title,options,option=>finish(option),()=>finish(void 0),{tui:this.ui,timeout:opts?.timeout,onToggleToolsExpanded:()=>this.toggleToolOutputExpansion()});this.pushExtensionDialog(selector,blocked)})}async showExtensionConfirm(title,message,opts){return await this.showExtensionSelector(`${title}
|
|
989
|
-
${message}`,["Yes","No"],opts,{kind:"permission",message:title})==="Yes"}async promptForMissingSessionCwd(error){return await this.showExtensionConfirm("Session cwd not found",formatMissingSessionCwdPrompt(error.issue))?error.issue.fallbackCwd:void 0}showExtensionInput(title,placeholder,opts){return new Promise(resolve16=>{if(opts?.signal?.aborted){resolve16(void 0);return}let finish=value=>{opts?.signal?.removeEventListener("abort",onAbort),input2.dispose(),this.removeExtensionDialog(input2),resolve16(value)},onAbort=()=>finish(void 0);opts?.signal?.addEventListener("abort",onAbort,{once:!0});let input2=new ExtensionInputComponent(title,placeholder,value=>finish(value),()=>finish(void 0),{tui:this.ui,timeout:opts?.timeout});this.pushExtensionDialog(input2,{kind:"question",message:title})})}showExtensionEditor(title,prefill){return new Promise(resolve16=>{let finish=value=>{this.removeExtensionDialog(editor),resolve16(value)},editor=new ExtensionEditorComponent(this.ui,this.keybindings,title,prefill,value=>finish(value),()=>finish(void 0),void 0,this.settingsManager.getExternalEditorCommand());this.pushExtensionDialog(editor,{kind:"question",message:title})})}setCustomEditorComponent(factory){this.editorComponentFactory=factory;let currentText=this.editor.getText();if(this.disposeActiveSelector(),this.editorContainer.clear(),factory){let newEditor=factory(this.ui,getEditorTheme(),this.keybindings);newEditor.onSubmit=this.defaultEditor.onSubmit,newEditor.onChange=this.defaultEditor.onChange,newEditor.setText(currentText),newEditor.borderColor!==void 0&&(newEditor.borderColor=this.defaultEditor.borderColor),newEditor.setPaddingX!==void 0&&newEditor.setPaddingX(this.defaultEditor.getPaddingX()),newEditor.setAutocompleteMaxVisible!==void 0&&newEditor.setAutocompleteMaxVisible(this.defaultEditor.getAutocompleteMaxVisible()),newEditor.setAutocompleteProvider&&this.autocompleteProvider&&newEditor.setAutocompleteProvider(this.autocompleteProvider);let customEditor=newEditor;if("actionHandlers"in customEditor&&customEditor.actionHandlers instanceof Map){customEditor.onEscape||(customEditor.onEscape=()=>this.defaultEditor.onEscape?.()),customEditor.onCtrlD||(customEditor.onCtrlD=()=>this.defaultEditor.onCtrlD?.()),customEditor.onPasteImage||(customEditor.onPasteImage=()=>this.defaultEditor.onPasteImage?.()),customEditor.onExtensionShortcut||(customEditor.onExtensionShortcut=data=>this.defaultEditor.onExtensionShortcut?.(data));for(let[action,handler]of this.defaultEditor.actionHandlers)customEditor.actionHandlers.set(action,handler)}this.editor=newEditor}else this.defaultEditor.setText(currentText),this.editor=this.defaultEditor;this.editorContainer.addChild(this.editor),this.activeStatusIndicator&&(this.statusContainer.clear(),this.activeWorkingIndicatorEmbedded=this.setEditorWorkingStatusIndicator(this.activeStatusIndicator),this.activeWorkingIndicatorEmbedded||this.statusContainer.addChild(this.activeStatusIndicator)),this.ui.setFocus(this.editor),this.ui.requestRender()}showExtensionNotify(message,type){type==="error"?this.showError(message):type==="warning"?this.showWarning(message):this.showStatus(message)}async showExtensionCustom(factory,options){let savedText=this.editor.getText(),isOverlay=options?.overlay??!1;return new Promise((resolve16,reject)=>{let component,overlayHandle,closed=!1,restoreEditor3=()=>{component&&this.removeExtensionDialog(component),this.editor.setText(savedText),this.ui.requestRender()},close=result=>{if(!closed){closed=!0,isOverlay?overlayHandle?.hide():restoreEditor3(),resolve16(result);try{component?.dispose?.()}catch{}}};Promise.resolve(factory(this.ui,theme,this.keybindings,close)).then(c=>{if(!closed)if(component=c,isOverlay){let resolveOptions=()=>{if(options?.overlayOptions)return typeof options.overlayOptions=="function"?options.overlayOptions():options.overlayOptions;let w=c.width;return w?{width:w}:void 0};overlayHandle=this.ui.showOverlay(c,resolveOptions()),options?.onHandle?.(overlayHandle)}else this.pushExtensionDialog(c)}).catch(err=>{closed||(isOverlay||restoreEditor3(),reject(err))})})}showExtensionError(extensionPath,error,stack){let errorMsg=`Extension "${extensionPath}" error: ${error}`,errorText=new ThemedText(()=>theme.fg("error",errorMsg),1,0);if(this.chatContainer.addChild(errorText),stack){let stackLines=stack.split(`
|
|
989
|
+
${message}`,[globalThis.__pinkT?.("Sim","Sí","Yes")??"Sim",globalThis.__pinkT?.("Não","No","No")??"Não"],opts,{kind:"permission",message:title})===(globalThis.__pinkT?.("Sim","Sí","Yes")??"Sim")}async promptForMissingSessionCwd(error){return await this.showExtensionConfirm("Session cwd not found",formatMissingSessionCwdPrompt(error.issue))?error.issue.fallbackCwd:void 0}showExtensionInput(title,placeholder,opts){return new Promise(resolve16=>{if(opts?.signal?.aborted){resolve16(void 0);return}let finish=value=>{opts?.signal?.removeEventListener("abort",onAbort),input2.dispose(),this.removeExtensionDialog(input2),resolve16(value)},onAbort=()=>finish(void 0);opts?.signal?.addEventListener("abort",onAbort,{once:!0});let input2=new ExtensionInputComponent(title,placeholder,value=>finish(value),()=>finish(void 0),{tui:this.ui,timeout:opts?.timeout});this.pushExtensionDialog(input2,{kind:"question",message:title})})}showExtensionEditor(title,prefill){return new Promise(resolve16=>{let finish=value=>{this.removeExtensionDialog(editor),resolve16(value)},editor=new ExtensionEditorComponent(this.ui,this.keybindings,title,prefill,value=>finish(value),()=>finish(void 0),void 0,this.settingsManager.getExternalEditorCommand());this.pushExtensionDialog(editor,{kind:"question",message:title})})}setCustomEditorComponent(factory){this.editorComponentFactory=factory;let currentText=this.editor.getText();if(this.disposeActiveSelector(),this.editorContainer.clear(),factory){let newEditor=factory(this.ui,getEditorTheme(),this.keybindings);newEditor.onSubmit=this.defaultEditor.onSubmit,newEditor.onChange=this.defaultEditor.onChange,newEditor.setText(currentText),newEditor.borderColor!==void 0&&(newEditor.borderColor=this.defaultEditor.borderColor),newEditor.setPaddingX!==void 0&&newEditor.setPaddingX(this.defaultEditor.getPaddingX()),newEditor.setAutocompleteMaxVisible!==void 0&&newEditor.setAutocompleteMaxVisible(this.defaultEditor.getAutocompleteMaxVisible()),newEditor.setAutocompleteProvider&&this.autocompleteProvider&&newEditor.setAutocompleteProvider(this.autocompleteProvider);let customEditor=newEditor;if("actionHandlers"in customEditor&&customEditor.actionHandlers instanceof Map){customEditor.onEscape||(customEditor.onEscape=()=>this.defaultEditor.onEscape?.()),customEditor.onCtrlD||(customEditor.onCtrlD=()=>this.defaultEditor.onCtrlD?.()),customEditor.onPasteImage||(customEditor.onPasteImage=()=>this.defaultEditor.onPasteImage?.()),customEditor.onExtensionShortcut||(customEditor.onExtensionShortcut=data=>this.defaultEditor.onExtensionShortcut?.(data));for(let[action,handler]of this.defaultEditor.actionHandlers)customEditor.actionHandlers.set(action,handler)}this.editor=newEditor}else this.defaultEditor.setText(currentText),this.editor=this.defaultEditor;this.editorContainer.addChild(this.editor),this.activeStatusIndicator&&(this.statusContainer.clear(),this.activeWorkingIndicatorEmbedded=this.setEditorWorkingStatusIndicator(this.activeStatusIndicator),this.activeWorkingIndicatorEmbedded||this.statusContainer.addChild(this.activeStatusIndicator)),this.ui.setFocus(this.editor),this.ui.requestRender()}showExtensionNotify(message,type){type==="error"?this.showError(message):type==="warning"?this.showWarning(message):this.showStatus(message)}async showExtensionCustom(factory,options){let savedText=this.editor.getText(),isOverlay=options?.overlay??!1;return new Promise((resolve16,reject)=>{let component,overlayHandle,closed=!1,restoreEditor3=()=>{component&&this.removeExtensionDialog(component),this.editor.setText(savedText),this.ui.requestRender()},close=result=>{if(!closed){closed=!0,isOverlay?overlayHandle?.hide():restoreEditor3(),resolve16(result);try{component?.dispose?.()}catch{}}};Promise.resolve(factory(this.ui,theme,this.keybindings,close)).then(c=>{if(!closed)if(component=c,isOverlay){let resolveOptions=()=>{if(options?.overlayOptions)return typeof options.overlayOptions=="function"?options.overlayOptions():options.overlayOptions;let w=c.width;return w?{width:w}:void 0};overlayHandle=this.ui.showOverlay(c,resolveOptions()),options?.onHandle?.(overlayHandle)}else this.pushExtensionDialog(c)}).catch(err=>{closed||(isOverlay||restoreEditor3(),reject(err))})})}showExtensionError(extensionPath,error,stack){let errorMsg=`Extension "${extensionPath}" error: ${error}`,errorText=new ThemedText(()=>theme.fg("error",errorMsg),1,0);if(this.chatContainer.addChild(errorText),stack){let stackLines=stack.split(`
|
|
990
990
|
`).slice(1);if(stackLines.length>0){let renderStack=()=>stackLines.map(line=>theme.fg("dim",` ${line.trim()}`)).join(`
|
|
991
991
|
`);this.chatContainer.addChild(new ThemedText(renderStack,1,0))}}this.ui.requestRender()}setupKeyHandlers(){this.defaultEditor.onEscape=()=>{if(this.session.isStreaming)this.restoreQueuedMessagesToEditor({abort:!0});else if(this.session.isBashRunning)this.session.abortBash();else if(this.isBashMode)this.editor.setText(""),this.isBashMode=!1,this.updateEditorBorderColor();else if(!this.editor.getText().trim()){let action=this.settingsManager.getDoubleEscapeAction();if(action!=="none"){let now=Date.now();now-this.lastEscapeTime<500?(action==="tree"?this.showTreeSelector():this.showUserMessageSelector(),this.lastEscapeTime=0):this.lastEscapeTime=now}}},this.defaultEditor.onAction("app.clear",()=>this.handleCtrlC()),this.defaultEditor.onCtrlD=()=>this.handleCtrlD(),this.defaultEditor.onAction("app.suspend",()=>this.handleCtrlZ()),this.defaultEditor.onAction("app.thinking.cycle",()=>this.cycleThinkingLevel()),this.defaultEditor.onAction("app.model.cycleForward",()=>this.cycleModel("forward")),this.defaultEditor.onAction("app.model.cycleBackward",()=>this.cycleModel("backward")),this.ui.onDebug=()=>this.handleDebugCommand(),this.defaultEditor.onAction("app.model.select",()=>this.showModelSelector()),this.defaultEditor.onAction("app.tools.expand",()=>this.toggleToolOutputExpansion()),this.defaultEditor.onAction("app.thinking.toggle",()=>this.toggleThinkingBlockVisibility()),this.defaultEditor.onAction("app.editor.external",()=>{this.handleOpenExternalEditor()}),this.defaultEditor.onAction("app.message.copy",()=>{this.handleCopyCommand({flashConfirmation:!0,preferSelection:!0})}),this.defaultEditor.onAction("app.message.followUp",()=>this.handleFollowUp()),this.defaultEditor.onAction("app.message.dequeue",()=>this.handleDequeue()),this.defaultEditor.onAction("app.session.new",()=>this.handleClearCommand()),this.defaultEditor.onAction("app.session.tree",()=>this.showTreeSelector()),this.defaultEditor.onAction("app.session.fork",()=>this.showUserMessageSelector()),this.defaultEditor.onAction("app.session.resume",()=>this.showSessionSelector()),this.defaultEditor.onChange=text=>{let wasBashMode=this.isBashMode;this.isBashMode=text.trimStart().startsWith("!"),wasBashMode!==this.isBashMode&&this.updateEditorBorderColor()},this.defaultEditor.onPasteImage=()=>{this.handleClipboardPaste()}}async handleRightClickPaste(){let target=this.renderer.getFocusedComponent(),handleInput=target?.handleInput;if(!(!target||!handleInput))try{let text=await readClipboardText();if(!text||this.renderer.getFocusedComponent()!==target)return;handleInput.call(target,`\x1B[200~${text}\x1B[201~`),this.ui.requestRender()}catch{}}async handleClipboardPaste(){try{let filePaths=await readClipboardFilePaths();if(filePaths){if(filePaths.some(filePath=>new RegExp("\\p{Cc}","u").test(filePath)))throw new Error("Clipboard file path contains control characters");let paths=this.isBashMode?filePaths.map(quoteIfNeeded).join(" "):filePaths.join(`
|
|
992
992
|
`),cursor=this.editor.getCursor?.(),currentLine=cursor?this.editor.getText().split(`
|
|
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,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);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()}
|
|
@@ -1219,4 +1219,4 @@ Options:
|
|
|
1219
1219
|
`))});try{switch(options.command){case"install":return await packageManager.installAndPersist(source,{local:options.local}),console.log(source_default.green(`Installed ${source}`)),!0;case"remove":return await packageManager.removeAndPersist(source,{local:options.local})?(console.log(source_default.green(`Removed ${source}`)),!0):(console.error(source_default.red(`No matching package found for ${source}`)),process.exitCode=1,!0);case"list":{let configuredPackages=packageManager.listConfiguredPackages(),userPackages=configuredPackages.filter(pkg=>pkg.scope==="user"),projectPackages=configuredPackages.filter(pkg=>pkg.scope==="project");if(configuredPackages.length===0)return console.log(source_default.dim("No packages installed.")),!0;let formatPackage=pkg=>{let display=pkg.filtered?`${pkg.source} (filtered)`:pkg.source;console.log(` ${display}`),pkg.installedPath&&console.log(source_default.dim(` ${pkg.installedPath}`))};if(userPackages.length>0){console.log(source_default.bold("User packages:"));for(let pkg of userPackages)formatPackage(pkg)}if(projectPackages.length>0){userPackages.length>0&&console.log(),console.log(source_default.bold("Project packages:"));for(let pkg of projectPackages)formatPackage(pkg)}return!0}case"update":{let target=options.updateTarget??{type:"self"};if(options.showExtensionsSkippedNote&&console.log(source_default.dim(`Extensions are skipped. Run ${APP_NAME} update --extensions to update extensions.`)),updateTargetIncludesExtensions(target)){let updateSource=target.type==="extensions"?target.source:void 0;await packageManager.update(updateSource),console.log(updateSource?source_default.green(`Updated ${updateSource}`):source_default.green("Updated packages"))}if(updateTargetIncludesSelf(target)){let managedInstallRoot=getActiveManagedInstallRoot();if(managedInstallRoot&&options.force)return console.error(source_default.red(`Managed ${APP_NAME} installations do not support --force; rerun the installer to repair this installation.`)),process.exitCode=1,!0;let selfUpdatePlan=await getSelfUpdatePlan(options.force);if(!selfUpdatePlan.shouldRun)return!0;if(managedInstallRoot){selfUpdatePlan.note&&printSelfUpdateNote(selfUpdatePlan.note);try{console.log(source_default.dim(`Updating managed ${APP_NAME} installation...`)),await runManagedSelfUpdate(managedInstallRoot,selfUpdatePlan.version)}catch(error){let message=error instanceof Error?error.message:"Unknown managed update error";return console.error(source_default.red(`Error: ${message}`)),process.exitCode=1,!0}return console.log(source_default.green(`Updated ${APP_NAME} from ${VERSION} to ${selfUpdatePlan.version}`)),!0}let installMethod=detectInstallMethod();if(process.platform==="win32"&&installMethod!=="npm"&&installMethod!=="pnpm")return console.error(source_default.red(`${APP_NAME} self-update on Windows is only supported for npm and pnpm installs.`)),console.error(source_default.dim(`Detected install method: ${installMethod}. Update ${APP_NAME} manually.`)),process.exitCode=1,!0;let selfUpdateTarget={packageName:selfUpdatePlan.packageName,installSpec:selfUpdatePlan.installSpec},selfUpdateCommand=getSelfUpdateCommand(PACKAGE_NAME,selfUpdateNpmCommand,selfUpdateTarget);if(!selfUpdateCommand)return printSelfUpdateUnavailable(selfUpdateNpmCommand,selfUpdateTarget),process.exitCode=1,!0;selfUpdatePlan.note&&printSelfUpdateNote(selfUpdatePlan.note);try{installMethod==="npm"&&prepareWindowsNpmSelfUpdate(),await runSelfUpdate(selfUpdateCommand)}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return console.error(source_default.red(`Error: ${message}`)),installMethod==="pnpm"&&printPnpmSelfUpdateMetadataHint(),printSelfUpdateFallback(selfUpdateCommand),process.exitCode=1,!0}if(console.log(source_default.green(`Updated ${APP_NAME} from ${VERSION} to ${selfUpdatePlan.version}`)),installMethod==="npm"){let installerCommand=process.platform==="win32"?"npm install -g @thothdev/pink":"npm install -g @thothdev/pink";console.log(),console.log(source_default.yellow(`This npm installation of ${APP_NAME} does not pin its dependencies.`)),console.log(source_default.yellow("Run the installer to migrate to a managed installation that does:")),console.log(),console.log(` ${source_default.bold(installerCommand)}`)}}return!0}}}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return console.error(source_default.red(`Error: ${message}`)),process.exitCode=1,!0}}var EXTENSION_LOAD_FAILURE_HINT=`Hint: Start without extensions using "${APP_NAME} -ne".`;async function readPipedStdin(){if(!process.stdin.isTTY)return new Promise(resolve16=>{let data="";process.stdin.setEncoding("utf8"),process.stdin.on("data",chunk=>{data+=chunk}),process.stdin.on("end",()=>{resolve16(data.trim()||void 0)}),process.stdin.resume()})}function reportDiagnostics(diagnostics){for(let diagnostic of diagnostics){let color=diagnostic.type==="error"?source_default.red:diagnostic.type==="warning"?source_default.yellow:source_default.dim,prefix=diagnostic.type==="error"?"Error: ":diagnostic.type==="warning"?"Warning: ":"";console.error(color(`${prefix}${diagnostic.message}`))}}function isTruthyEnvFlag2(value){return value?value==="1"||value.toLowerCase()==="true"||value.toLowerCase()==="yes":!1}function resolveAppMode(parsed,stdinIsTTY,stdoutIsTTY){return parsed.mode==="rpc"?"rpc":parsed.mode==="json"?"json":parsed.print||!stdinIsTTY||!stdoutIsTTY?"print":"interactive"}function toPrintOutputMode(appMode){return appMode==="json"?"json":"text"}function isPlainRuntimeMetadataCommand(parsed){return!parsed.print&&parsed.mode===void 0&&(parsed.help===!0||parsed.listModels!==void 0)}async function runAuthCommand(args){if(isAuthCommandHelp(args))return printAuthCommandHelp(),!0;let command;try{command=parseAuthCommand(args)}catch(error){let message=error instanceof AuthCommandError?error.message:"Failed to parse auth command";return console.error(source_default.red(`Error: ${message}`)),process.exitCode=1,!0}if(!command)return!1;let parsed=parseArgs(command.args);if(parsed.unknownFlags.size>0){let option=parsed.unknownFlags.keys().next().value;return console.error(source_default.red(`Unknown option --${option} for "${getAuthCommandName(command.kind)}".`)),console.error(source_default.dim(`Use "${APP_NAME} --help" or "${getAuthCommandUsage(command.kind)}".`)),process.exitCode=1,!0}try{if(parsed.diagnostics.length>0)throw new AuthCommandError(parsed.diagnostics.map(diagnostic=>diagnostic.message).join(`
|
|
1220
1220
|
`));if(command.kind!=="check"){let signal=AbortSignal.timeout(15e3),modelRuntime=await ModelRuntime.create({allowModelNetwork:!1,signal}),credential2=await resolveCredentialForPrint(parsed,modelRuntime,command.kind,command.minExpiryMs,signal);return process.stdout.write(`${credential2}
|
|
1221
1221
|
`),!0}let requestedAuth=validateAuthCommandArgs(parsed,command.kind),result,credential;try{let credentials=command.noRefresh?new ReadOnlyAuthStorage:AuthStorage.create(),modelRuntime=await createAuthCheckModelRuntime(credentials);result=await checkProviderAuth(parsed,modelRuntime,{refresh:!command.noRefresh}),command.credentials&&result.status==="ready"&&(credential=await getProviderCredential(result.provider,modelRuntime,credentials,{refresh:!command.noRefresh}),credential||(result={status:"not_ready",provider:result.provider,reason:"credential_not_available"}))}catch{result={status:"invalid",provider:requestedAuth.provider??requestedAuth.model,reason:"invalid_state"}}let output=command.json?JSON.stringify({...result,...credential?{credentials:credential}:{}}):credential??result.status;process.stdout.write(`${output}
|
|
1222
|
-
`),process.exitCode=result.status==="ready"?0:result.status==="not_ready"?1:2}catch(error){let message=error instanceof AuthCommandError?error.message:"Failed to resolve credential";console.error(source_default.red(`Error: ${message}`)),process.exitCode=command.kind==="check"?2:1}return!0}async function prepareInitialMessage(parsed,stdinContent){if(parsed.fileArgs.length===0)return buildInitialMessage({parsed,stdinContent});let{text,images}=await processFileArguments(parsed.fileArgs,{autoResizeImages:!1});return buildInitialMessage({parsed,fileText:text,fileImages:images,stdinContent})}function findLocalSessionByExactId(sessionId,cwd,sessionDir){let path10=SessionManager.findById(cwd,sessionId,sessionDir);return path10?{type:"local",path:path10}:void 0}async function resolveSessionPath(sessionArg,cwd,sessionDir){if(sessionArg.includes("/")||sessionArg.includes("\\")||sessionArg.endsWith(".jsonl"))return{type:"path",path:resolvePath(sessionArg,cwd)};let exactLocalMatch=findLocalSessionByExactId(sessionArg,cwd,sessionDir);if(exactLocalMatch)return exactLocalMatch;let localMatch=(await SessionManager.list(cwd,sessionDir)).find(s=>s.id.startsWith(sessionArg));if(localMatch)return{type:"local",path:localMatch.path};let allSessions=await SessionManager.listAll(sessionDir),globalMatch=allSessions.find(s=>s.id===sessionArg)??allSessions.find(s=>s.id.startsWith(sessionArg));return globalMatch?{type:"global",path:globalMatch.path,cwd:globalMatch.cwd}:{type:"not_found",arg:sessionArg}}async function promptConfirm(message){return new Promise(resolve16=>{let rl=createInterface4({input:process.stdin,output:process.stdout});rl.question(`${message} [y/N] `,answer=>{rl.close(),resolve16(answer.toLowerCase()==="y"||answer.toLowerCase()==="yes")})})}function validateForkFlags(parsed){if(!parsed.fork)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0,parsed.noSession?"--no-session":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --fork cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1))}function validateSessionIdFlags(parsed){if(parsed.sessionId===void 0)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --session-id cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1));try{assertValidSessionId(parsed.sessionId)}catch(error){let message=error instanceof Error?error.message:String(error);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}function openSessionOrExit(path10,sessionDir){try{return SessionManager.open(path10,sessionDir)}catch(error){let message=error instanceof Error?error.message:String(error);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}function forkSessionOrExit(sourcePath,cwd,sessionDir,sessionId){try{return SessionManager.forkFrom(sourcePath,cwd,sessionDir,{id:sessionId})}catch(error){let message=error instanceof Error?error.message:String(error);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}async function createSessionManager(parsed,cwd,sessionDir,settingsManager){if(parsed.noSession||parsed.help||parsed.listModels!==void 0)return SessionManager.inMemory(cwd,parsed.sessionId!==void 0?{id:parsed.sessionId}:void 0);if(parsed.fork){parsed.sessionId&&findLocalSessionByExactId(parsed.sessionId,cwd,sessionDir)&&(console.error(source_default.red(`Session already exists with id '${parsed.sessionId}'`)),process.exit(1));let resolved=await resolveSessionPath(parsed.fork,cwd,sessionDir);switch(resolved.type){case"path":case"local":case"global":return forkSessionOrExit(resolved.path,cwd,sessionDir,parsed.sessionId);case"not_found":console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1)}}if(parsed.session){let resolved=await resolveSessionPath(parsed.session,cwd,sessionDir);switch(resolved.type){case"path":case"local":return openSessionOrExit(resolved.path,sessionDir);case"global":return console.log(source_default.yellow(`Session found in different project: ${resolved.cwd}`)),await promptConfirm("Fork this session into current directory?")||(console.log(source_default.dim("Aborted.")),process.exit(0)),forkSessionOrExit(resolved.path,cwd,sessionDir);case"not_found":console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1)}}if(parsed.resume)try{let selectedPath=await selectSession((onProgress,signal)=>SessionManager.list(cwd,sessionDir,onProgress,signal),(onProgress,signal)=>SessionManager.listAll(sessionDir,onProgress,signal),settingsManager);return selectedPath||(console.log(source_default.dim("No session selected")),process.exit(0)),SessionManager.open(selectedPath,sessionDir)}finally{stopThemeWatcher()}if(parsed.continue)return SessionManager.continueRecent(cwd,sessionDir);if(parsed.sessionId){let existingSession=findLocalSessionByExactId(parsed.sessionId,cwd,sessionDir);if(existingSession)return SessionManager.open(existingSession.path,sessionDir);console.error(source_default.yellow(`Warning: No project session found with id '${parsed.sessionId}'; creating a new session with that id.`))}return SessionManager.create(cwd,sessionDir,{id:parsed.sessionId})}function buildSessionOptions(parsed,scopedModels,hasExistingSession,modelRuntime,settingsManager){let options={},diagnostics=[],cliThinkingFromModel=!1;if(parsed.provider&&!parsed.model&&diagnostics.push({type:"error",message:`--provider requires --model (for example: --provider ${parsed.provider} --model <pattern>)`}),parsed.model){let resolved=resolveCliModel({cliProvider:parsed.provider,cliModel:parsed.model,cliThinking:parsed.thinking,inlineApiKey:!!parsed.apiKey,modelRuntime});resolved.warning&&diagnostics.push({type:"warning",message:resolved.warning}),resolved.error&&diagnostics.push({type:"error",message:resolved.error}),resolved.model&&(options.model=resolved.model,!parsed.thinking&&resolved.thinkingLevel&&(options.thinkingLevel=resolved.thinkingLevel,cliThinkingFromModel=!0))}if(!options.model&&scopedModels.length>0&&!hasExistingSession){let savedProvider=settingsManager.getDefaultProvider(),savedModelId=settingsManager.getDefaultModel(),savedModel=savedProvider&&savedModelId?modelRuntime.getModel(savedProvider,savedModelId):void 0,savedInScope=savedModel?scopedModels.find(sm=>modelsAreEqual(sm.model,savedModel)):void 0;savedInScope?(options.model=savedInScope.model,!parsed.thinking&&savedInScope.thinkingLevel&&(options.thinkingLevel=savedInScope.thinkingLevel)):(options.model=scopedModels[0].model,!parsed.thinking&&scopedModels[0].thinkingLevel&&(options.thinkingLevel=scopedModels[0].thinkingLevel))}return parsed.thinking&&(options.thinkingLevel=parsed.thinking),scopedModels.length>0&&(options.scopedModels=scopedModels.map(sm=>({model:sm.model,thinkingLevel:sm.thinkingLevel}))),parsed.noTools?options.noTools="all":parsed.noBuiltinTools&&(options.noTools="builtin"),parsed.tools&&(options.tools=[...parsed.tools]),parsed.excludeTools&&(options.excludeTools=[...parsed.excludeTools]),{options,cliThinkingFromModel,diagnostics}}function resolveCliPaths(cwd,paths){return paths?.map(value=>isLocalPath(value)?resolvePath(value,cwd):value)}async function promptForMissingSessionCwd(issue,settingsManager){return showStartupSelector(settingsManager,formatMissingSessionCwdPrompt(issue),[{label:"Continue",value:issue.fallbackCwd},{label:"Cancel",value:void 0}])}async function main(args,options){resetTimings(),setThemeJsonValidator(validateThemeJson);let extensionFactories=[...builtInExtensions,...options?.extensionFactories??[]],offlineMode=args.includes("--offline")||isTruthyEnvFlag2(process.env.PINK_OFFLINE);if(offlineMode&&(process.env.PINK_OFFLINE="1",process.env.PINK_SKIP_VERSION_CHECK="1"),await runAuthCommand(args))return;process.platform==="win32"&&cleanupWindowsSelfUpdateQuarantine(getPackageDir()),cleanupManagedInstall();let cwd=process.cwd(),agentDir=getAgentDir(),bootstrapSettingsManager=SettingsManager.create(cwd,agentDir,{projectTrusted:!1});if(applyHttpProxySettings(bootstrapSettingsManager.getGlobalSettings().httpProxy),configureHttpDispatcher(),await handlePackageCommand(args,{extensionFactories})){let exitCode=process.exitCode??0;if(process.platform==="win32"&&exitCode===0&&args[0]==="update")return;process.exit(exitCode);return}if(await handleConfigCommand(args,{extensionFactories}))return;if(args[0]==="mcp"){let{runMcpCommand}=await loadMcpCommand();process.exitCode=await runMcpCommand(args.slice(1),{cwd,agentDir});return}let parsed=parseArgs(args);if(parsed.diagnostics.length>0){for(let d of parsed.diagnostics){let color=d.type==="error"?source_default.red:source_default.yellow;console.error(color(`${d.type==="error"?"Error":"Warning"}: ${d.message}`))}parsed.diagnostics.some(d=>d.type==="error")&&process.exit(1)}if(time("parseArgs"),parsed.version&&(console.log(VERSION),process.exit(0)),parsed.export){let result;try{let outputPath=parsed.messages.length>0?parsed.messages[0]:void 0;result=await exportFromFile(parsed.export,outputPath)}catch(error){let message=error instanceof Error?error.message:"Failed to export session";console.error(source_default.red(`Error: ${message}`)),process.exit(1)}console.log(`Exported to: ${result}`),process.exit(0)}let appMode=resolveAppMode(parsed,process.stdin.isTTY,process.stdout.isTTY);appMode!=="interactive"&&!isPlainRuntimeMetadataCommand(parsed)&&takeOverStdout(),parsed.mode==="rpc"&&parsed.fileArgs.length>0&&(console.error(source_default.red("Error: @file arguments are not supported in RPC mode")),process.exit(1)),validateForkFlags(parsed),validateSessionIdFlags(parsed);let{migratedAuthProviders:migratedProviders,deprecationWarnings}=runMigrations(cwd);time("runMigrations");let startupSettingsManager=SettingsManager.create(cwd,agentDir),startupSettingsDiagnostics=collectSettingsDiagnostics(startupSettingsManager);appMode==="interactive"&&!parsed.help&&parsed.listModels===void 0&&shouldRunFirstTimeSetup()&&(await showFirstTimeSetup(startupSettingsManager),time("firstTimeSetup")),appMode==="interactive"&&parsed.useTheme!==void 0&&startupSettingsManager.applyOverrides({theme:parsed.useTheme});let envSessionDir=process.env[ENV_SESSION_DIR],sessionDir=(parsed.sessionDir?normalizePath(parsed.sessionDir):void 0)??(envSessionDir?expandTildePath(envSessionDir):void 0)??startupSettingsManager.getSessionDir(),sessionManager=await createSessionManager(parsed,cwd,sessionDir,startupSettingsManager),missingSessionCwdIssue=getMissingSessionCwdIssue(sessionManager,cwd);if(missingSessionCwdIssue)if(appMode==="interactive"){let selectedCwd=await promptForMissingSessionCwd(missingSessionCwdIssue,startupSettingsManager);selectedCwd||process.exit(0),sessionManager=SessionManager.open(missingSessionCwdIssue.sessionFile,sessionDir,selectedCwd)}else console.error(source_default.red(new MissingSessionCwdError(missingSessionCwdIssue).message)),process.exit(1);if(parsed.name!==void 0){let name=normalizeSessionName(parsed.name);name===void 0&&(console.error(source_default.red("Error: --name requires a non-empty value")),process.exit(1)),sessionManager.appendSessionInfo(name)}time("createSessionManager");let trustStore=new ProjectTrustStore(agentDir),sessionCwd=sessionManager.getCwd(),autoTrustOnReloadCwd=parsed.projectTrustOverride===void 0&&!hasTrustRequiringProjectResources(sessionCwd)?sessionCwd:void 0,trustPromptMode=parsed.help||parsed.listModels!==void 0?"print":appMode,projectTrustByCwd=new Map,resolvedExtensionPaths=[path5.join(getPackageDir(),"extensions","pink-permissions.ts"),path5.join(getPackageDir(),"extensions","pink-hooks.ts"),...process.env.PINK_NO_BUILTIN_UI?[]:[path5.join(getPackageDir(),"extensions","pink-ui.ts"),path5.join(getPackageDir(),"extensions","pink-notify.ts"),path5.join(getPackageDir(),"extensions","pink-natives.ts"),path5.join(getPackageDir(),"extensions","pink-web.ts"),path5.join(getPackageDir(),"extensions","pink-shell-bg.ts"),path5.join(getPackageDir(),"extensions","pink-agente.ts"),path5.join(getPackageDir(),"extensions","pink-memory.ts"),path5.join(getPackageDir(),"extensions","pink-sessions-bus.ts"),path5.join(getPackageDir(),"extensions","pink-loop.ts"),path5.join(getPackageDir(),"extensions","pink-skills.ts"),path5.join(getPackageDir(),"extensions","pink-context.ts"),path5.join(getPackageDir(),"extensions","pink-lsp.ts"),path5.join(getPackageDir(),"extensions","pink-rules.ts"),path5.join(getPackageDir(),"extensions","pink-review.ts"),path5.join(getPackageDir(),"extensions","pink-skill-propose.ts"),path5.join(getPackageDir(),"extensions","pink-sandbox.ts"),path5.join(getPackageDir(),"extensions","pink-tela.ts")],path5.join(getPackageDir(),"examples","extensions","subagent","index.ts"),path5.join(getPackageDir(),"examples","extensions","questionnaire.ts"),...(resolveCliPaths(cwd,parsed.extensions)??[])],resolvedSkillPaths=resolveCliPaths(cwd,parsed.skills),resolvedPromptTemplatePaths=resolveCliPaths(cwd,parsed.promptTemplates),resolvedThemePaths=resolveCliPaths(cwd,parsed.themes),createRuntime=async({cwd:cwd2,agentDir:agentDir2,sessionManager:sessionManager2,sessionStartEvent,projectTrustContext})=>{let isInitialRuntime=sessionStartEvent===void 0,projectTrustDiagnostics=[],cachedProjectTrust=projectTrustByCwd.get(cwd2),hasTrustRequiringResources=hasTrustRequiringProjectResources(cwd2),shouldResolveProjectTrust=parsed.projectTrustOverride===void 0&&cachedProjectTrust===void 0&&hasTrustRequiringResources,projectTrusted=shouldResolveProjectTrust?!1:cachedProjectTrust??parsed.projectTrustOverride??(!hasTrustRequiringResources||trustStore.get(cwd2)===!0),runtimeSettingsManager=SettingsManager.create(cwd2,agentDir2,{projectTrusted}),services2=await createAgentSessionServices({cwd:cwd2,agentDir:agentDir2,settingsManager:runtimeSettingsManager,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:parsed.unknownFlags,resourceLoaderReloadOptions:shouldResolveProjectTrust?{resolveProjectTrust:async({extensionsResult})=>{let trusted=await resolveProjectTrusted({cwd:cwd2,trustStore,trustOverride:parsed.projectTrustOverride,defaultProjectTrust:startupSettingsManager.getDefaultProjectTrust(),extensionsResult,projectTrustContext:projectTrustContext??createProjectTrustContext({cwd:cwd2,mode:isInitialRuntime?trustPromptMode:appMode,settingsManager:startupSettingsManager,hasUI:isInitialRuntime&&trustPromptMode==="interactive"}),onExtensionError:message=>projectTrustDiagnostics.push({type:"warning",message})});return projectTrustByCwd.set(cwd2,trusted),trusted}}:void 0,resourceLoaderOptions:{additionalExtensionPaths:resolvedExtensionPaths,additionalSkillPaths:resolvedSkillPaths,additionalPromptTemplatePaths:resolvedPromptTemplatePaths,additionalThemePaths:resolvedThemePaths,noExtensions:parsed.noExtensions,disabledBuiltinExtensions:parsed.noMcp?["mcp"]:void 0,noSkills:parsed.noSkills,noPromptTemplates:parsed.noPromptTemplates,noThemes:parsed.noThemes,noContextFiles:parsed.noContextFiles,systemPrompt:parsed.systemPrompt,appendSystemPrompt:parsed.appendSystemPrompt,extensionFactories}}),{settingsManager:settingsManager2,modelRuntime:modelRuntime2,resourceLoader:resourceLoader2}=services2,diagnostics=[...projectTrustDiagnostics,...services2.diagnostics,...collectSettingsDiagnostics(settingsManager2),...resourceLoader2.getExtensions().errors.map(({path:path10,error})=>({type:"error",message:`Failed to load extension "${path10}": ${error}`})),...(resourceLoader2.getExtensions().warnings??[]).map(({path:path10,warning})=>({type:"warning",message:`Extension package "${path10}": ${warning}`}))],modelPatterns=parsed.models??settingsManager2.getEnabledModels(),scopedModels=modelPatterns&&modelPatterns.length>0?await resolveModelScope(modelPatterns,modelRuntime2,{signal:AbortSignal.timeout(15e3)}):[],{options:sessionOptions,cliThinkingFromModel,diagnostics:sessionOptionDiagnostics}=buildSessionOptions(parsed,scopedModels,sessionManager2.buildSessionContext().messages.length>0,modelRuntime2,settingsManager2);diagnostics.push(...sessionOptionDiagnostics),parsed.apiKey&&(sessionOptions.model?await modelRuntime2.setRuntimeApiKey(sessionOptions.model.provider,parsed.apiKey):diagnostics.push({type:"error",message:"--api-key requires a model to be specified via --model, --provider/--model, or --models"}));let created=await createAgentSessionFromServices({services:services2,sessionManager:sessionManager2,sessionStartEvent,model:sessionOptions.model,thinkingLevel:sessionOptions.thinkingLevel,scopedModels:sessionOptions.scopedModels,tools:sessionOptions.tools,excludeTools:sessionOptions.excludeTools,noTools:sessionOptions.noTools,customTools:sessionOptions.customTools}),cliThinkingOverride=parsed.thinking!==void 0||cliThinkingFromModel;return created.session.model&&cliThinkingOverride&&created.session.setThinkingLevel(created.session.thinkingLevel),{...created,services:services2,diagnostics}};time("createRuntime");let runtime=await createAgentSessionRuntime(createRuntime,{cwd:sessionManager.getCwd(),agentDir,sessionManager});time("createAgentSessionRuntime");let{services,session,modelFallbackMessage}=runtime,{settingsManager,modelRuntime,resourceLoader}=services;if(setCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides()),applyHttpProxySettings(settingsManager.getGlobalSettings().httpProxy),configureHttpDispatcher(settingsManager.getHttpIdleTimeoutMs()),parsed.help){reportDiagnostics(startupSettingsDiagnostics);let extensionFlags=resourceLoader.getExtensions().extensions.flatMap(extension=>Array.from(extension.flags.values()));printHelp(extensionFlags),process.exit(0)}if(parsed.listModels!==void 0){reportDiagnostics(startupSettingsDiagnostics);let searchPattern=typeof parsed.listModels=="string"?parsed.listModels:void 0;await listModels(modelRuntime,searchPattern,AbortSignal.timeout(15e3)),process.exit(0)}let stdinContent;appMode!=="rpc"&&(stdinContent=await readPipedStdin(),stdinContent!==void 0&&appMode==="interactive"&&(appMode="print")),time("readPipedStdin");let{initialMessage,initialImages}=await prepareInitialMessage(parsed,stdinContent);time("prepareInitialMessage"),initTheme(settingsManager.getTheme(),appMode==="interactive"),time("initTheme"),appMode==="interactive"&&deprecationWarnings.length>0&&await showDeprecationWarnings(deprecationWarnings),time("resolveModelScope");let startupDiagnostics=deduplicateDiagnostics([...startupSettingsDiagnostics,...runtime.diagnostics]),hasRuntimeErrors=runtime.diagnostics.some(diagnostic=>diagnostic.type==="error");(appMode!=="interactive"||hasRuntimeErrors)&&reportDiagnostics(startupDiagnostics),hasRuntimeErrors&&(runtime.diagnostics.some(diagnostic=>diagnostic.message.includes("Failed to load extension"))&&console.error(source_default.yellow(EXTENSION_LOAD_FAILURE_HINT)),process.exit(1)),time("createAgentSession"),appMode!=="interactive"&&!session.model&&(console.error(source_default.red(formatNoModelsAvailableMessage())),process.exit(1));let startupBenchmark=isTruthyEnvFlag2(process.env.PINK_STARTUP_BENCHMARK);if(startupBenchmark&&appMode!=="interactive"&&(console.error(source_default.red("Error: PINK_STARTUP_BENCHMARK only supports interactive mode")),process.exit(1)),!offlineMode&&appMode==="rpc"){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),15e3);modelRuntime.refresh({signal:controller.signal}).catch(()=>{}).finally(()=>clearTimeout(timeout))}if(appMode==="rpc")printTimings(),await runRpcMode(runtime);else if(appMode==="interactive"){let interactiveMode=new InteractiveMode(runtime,{migratedProviders,startupDiagnostics,modelFallbackMessage,autoTrustOnReloadCwd,initialMessage,initialImages,initialMessages:parsed.messages,verbose:parsed.verbose,tuiMode:parsed.tuiMode,initialThemeSetting:parsed.useTheme});if(startupBenchmark){await interactiveMode.init(),time("interactiveMode.init"),await new Promise(resolve16=>setTimeout(resolve16,150)),interactiveMode.stop(),stopThemeWatcher(),printTimings(),process.stdout.writableLength>0&&await new Promise(resolve16=>process.stdout.once("drain",resolve16)),process.stderr.writableLength>0&&await new Promise(resolve16=>process.stderr.once("drain",resolve16));return}printTimings(),await interactiveMode.run()}else{printTimings();let exitCode=await runPrintMode(runtime,{mode:toPrintOutputMode(appMode),messages:parsed.messages,initialMessage,initialImages});stopThemeWatcher(),restoreStdout(),exitCode!==0&&(process.exitCode=exitCode);return}}export{configureHttpDispatcher,value_exports2 as value_exports,compile_exports,SettingsManager,parseArgs,resolveModelScopeWithDiagnostics,resolveCliModel,all_exports,compat_exports,VIRTUAL_MODEL_STATE_ENTRY,CredentialSynchronizationError,ModelRuntime,convertToPng,resizeImage,formatDimensionNote,detectSupportedImageMimeTypeFromFile,createSyntheticSourceInfo,DefaultPackageManager,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SessionSelectorComponent,parseFrontmatter,stripFrontmatter,loadSkillsFromDir,formatSkillsForPrompt,loadSkills,ExtensionRunner,convertToLlm,CURRENT_SESSION_VERSION,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,buildSessionProjection,buildSessionContext,SessionManager,createEventBus,dist_exports,serializeConversation,DEFAULT_COMPACTION_SETTINGS,calculateContextTokens,getLastAssistantUsage,shouldCompact,estimateTokens2 as estimateTokens,findTurnStartIndex,findCutPoint,generateSummary,generateSummaryWithUsage,compact,collectEntriesForBranchSummary,prepareBranchEntries,generateBranchSummary,defineTool,isBashToolResult,isPowerShellToolResult,isReadToolResult,isEditToolResult,isWriteToolResult,isGrepToolResult,isFindToolResult,isLsToolResult,isToolCallEventType,wrapRegisteredTool,wrapRegisteredTools,ModelRegistry,createLocalBashOperations,createBashToolDefinition,createBashTool,generateUnifiedPatch,generateDiffString,withFileMutationQueue,renderDiff,createEditToolDefinition,createEditTool,createFindToolDefinition,createFindTool,createGrepToolDefinition,createGrepTool,createLsToolDefinition,createLsTool,createLocalPowerShellOperations,createPowerShellToolDefinition,createPowerShellTool,createReadToolDefinition,createReadTool,createWriteToolDefinition,createWriteTool,createCodingTools,createReadOnlyTools,parseSkillBlock,AgentSession,createAgentSession,createCodemodeExtension,copyToClipboard,createMcpExtension,createToolSearchExtension,BorderedLoader,ExtensionEditorComponent,AssistantMessageComponent,BashExecutionComponent,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CustomEditor,CustomMessageComponent,FooterComponent,LoginDialogComponent,ModelSelectorComponent,OAuthSelectorComponent,SettingsSelectorComponent,SkillInvocationMessageComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,InteractiveMode,runPrintMode,RpcClient,runRpcMode,createExtensionRuntime,discoverAndLoadExtensions,loadProjectContextFiles,DefaultResourceLoader,createAgentSessionServices,createAgentSessionFromServices,AgentSessionRuntime,createAgentSessionRuntime,main};
|
|
1222
|
+
`),process.exitCode=result.status==="ready"?0:result.status==="not_ready"?1:2}catch(error){let message=error instanceof AuthCommandError?error.message:"Failed to resolve credential";console.error(source_default.red(`Error: ${message}`)),process.exitCode=command.kind==="check"?2:1}return!0}async function prepareInitialMessage(parsed,stdinContent){if(parsed.fileArgs.length===0)return buildInitialMessage({parsed,stdinContent});let{text,images}=await processFileArguments(parsed.fileArgs,{autoResizeImages:!1});return buildInitialMessage({parsed,fileText:text,fileImages:images,stdinContent})}function findLocalSessionByExactId(sessionId,cwd,sessionDir){let path10=SessionManager.findById(cwd,sessionId,sessionDir);return path10?{type:"local",path:path10}:void 0}async function resolveSessionPath(sessionArg,cwd,sessionDir){if(sessionArg.includes("/")||sessionArg.includes("\\")||sessionArg.endsWith(".jsonl"))return{type:"path",path:resolvePath(sessionArg,cwd)};let exactLocalMatch=findLocalSessionByExactId(sessionArg,cwd,sessionDir);if(exactLocalMatch)return exactLocalMatch;let localMatch=(await SessionManager.list(cwd,sessionDir)).find(s=>s.id.startsWith(sessionArg));if(localMatch)return{type:"local",path:localMatch.path};let allSessions=await SessionManager.listAll(sessionDir),globalMatch=allSessions.find(s=>s.id===sessionArg)??allSessions.find(s=>s.id.startsWith(sessionArg));return globalMatch?{type:"global",path:globalMatch.path,cwd:globalMatch.cwd}:{type:"not_found",arg:sessionArg}}async function promptConfirm(message){return new Promise(resolve16=>{let rl=createInterface4({input:process.stdin,output:process.stdout});rl.question(`${message} [y/N] `,answer=>{rl.close(),resolve16(answer.toLowerCase()==="y"||answer.toLowerCase()==="yes")})})}function validateForkFlags(parsed){if(!parsed.fork)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0,parsed.noSession?"--no-session":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --fork cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1))}function validateSessionIdFlags(parsed){if(parsed.sessionId===void 0)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --session-id cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1));try{assertValidSessionId(parsed.sessionId)}catch(error){let message=error instanceof Error?error.message:String(error);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}function openSessionOrExit(path10,sessionDir){try{return SessionManager.open(path10,sessionDir)}catch(error){let message=error instanceof Error?error.message:String(error);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}function forkSessionOrExit(sourcePath,cwd,sessionDir,sessionId){try{return SessionManager.forkFrom(sourcePath,cwd,sessionDir,{id:sessionId})}catch(error){let message=error instanceof Error?error.message:String(error);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}async function createSessionManager(parsed,cwd,sessionDir,settingsManager){if(parsed.noSession||parsed.help||parsed.listModels!==void 0)return SessionManager.inMemory(cwd,parsed.sessionId!==void 0?{id:parsed.sessionId}:void 0);if(parsed.fork){parsed.sessionId&&findLocalSessionByExactId(parsed.sessionId,cwd,sessionDir)&&(console.error(source_default.red(`Session already exists with id '${parsed.sessionId}'`)),process.exit(1));let resolved=await resolveSessionPath(parsed.fork,cwd,sessionDir);switch(resolved.type){case"path":case"local":case"global":return forkSessionOrExit(resolved.path,cwd,sessionDir,parsed.sessionId);case"not_found":console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1)}}if(parsed.session){let resolved=await resolveSessionPath(parsed.session,cwd,sessionDir);switch(resolved.type){case"path":case"local":return openSessionOrExit(resolved.path,sessionDir);case"global":return console.log(source_default.yellow(`Session found in different project: ${resolved.cwd}`)),await promptConfirm("Fork this session into current directory?")||(console.log(source_default.dim("Aborted.")),process.exit(0)),forkSessionOrExit(resolved.path,cwd,sessionDir);case"not_found":console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1)}}if(parsed.resume)try{let selectedPath=await selectSession((onProgress,signal)=>SessionManager.list(cwd,sessionDir,onProgress,signal),(onProgress,signal)=>SessionManager.listAll(sessionDir,onProgress,signal),settingsManager);return selectedPath||(console.log(source_default.dim("No session selected")),process.exit(0)),SessionManager.open(selectedPath,sessionDir)}finally{stopThemeWatcher()}if(parsed.continue)return SessionManager.continueRecent(cwd,sessionDir);if(parsed.sessionId){let existingSession=findLocalSessionByExactId(parsed.sessionId,cwd,sessionDir);if(existingSession)return SessionManager.open(existingSession.path,sessionDir);console.error(source_default.yellow(`Warning: No project session found with id '${parsed.sessionId}'; creating a new session with that id.`))}return SessionManager.create(cwd,sessionDir,{id:parsed.sessionId})}function buildSessionOptions(parsed,scopedModels,hasExistingSession,modelRuntime,settingsManager){let options={},diagnostics=[],cliThinkingFromModel=!1;if(parsed.provider&&!parsed.model&&diagnostics.push({type:"error",message:`--provider requires --model (for example: --provider ${parsed.provider} --model <pattern>)`}),parsed.model){let resolved=resolveCliModel({cliProvider:parsed.provider,cliModel:parsed.model,cliThinking:parsed.thinking,inlineApiKey:!!parsed.apiKey,modelRuntime});resolved.warning&&diagnostics.push({type:"warning",message:resolved.warning}),resolved.error&&diagnostics.push({type:"error",message:resolved.error}),resolved.model&&(options.model=resolved.model,!parsed.thinking&&resolved.thinkingLevel&&(options.thinkingLevel=resolved.thinkingLevel,cliThinkingFromModel=!0))}if(!options.model&&scopedModels.length>0&&!hasExistingSession){let savedProvider=settingsManager.getDefaultProvider(),savedModelId=settingsManager.getDefaultModel(),savedModel=savedProvider&&savedModelId?modelRuntime.getModel(savedProvider,savedModelId):void 0,savedInScope=savedModel?scopedModels.find(sm=>modelsAreEqual(sm.model,savedModel)):void 0;savedInScope?(options.model=savedInScope.model,!parsed.thinking&&savedInScope.thinkingLevel&&(options.thinkingLevel=savedInScope.thinkingLevel)):(options.model=scopedModels[0].model,!parsed.thinking&&scopedModels[0].thinkingLevel&&(options.thinkingLevel=scopedModels[0].thinkingLevel))}return parsed.thinking&&(options.thinkingLevel=parsed.thinking),scopedModels.length>0&&(options.scopedModels=scopedModels.map(sm=>({model:sm.model,thinkingLevel:sm.thinkingLevel}))),parsed.noTools?options.noTools="all":parsed.noBuiltinTools&&(options.noTools="builtin"),parsed.tools&&(options.tools=[...parsed.tools]),parsed.excludeTools&&(options.excludeTools=[...parsed.excludeTools]),{options,cliThinkingFromModel,diagnostics}}function resolveCliPaths(cwd,paths){return paths?.map(value=>isLocalPath(value)?resolvePath(value,cwd):value)}async function promptForMissingSessionCwd(issue,settingsManager){return showStartupSelector(settingsManager,formatMissingSessionCwdPrompt(issue),[{label:"Continue",value:issue.fallbackCwd},{label:"Cancel",value:void 0}])}async function main(args,options){resetTimings(),setThemeJsonValidator(validateThemeJson);let extensionFactories=[...builtInExtensions,...options?.extensionFactories??[]],offlineMode=args.includes("--offline")||isTruthyEnvFlag2(process.env.PINK_OFFLINE);if(offlineMode&&(process.env.PINK_OFFLINE="1",process.env.PINK_SKIP_VERSION_CHECK="1"),await runAuthCommand(args))return;process.platform==="win32"&&cleanupWindowsSelfUpdateQuarantine(getPackageDir()),cleanupManagedInstall();let cwd=process.cwd(),agentDir=getAgentDir(),bootstrapSettingsManager=SettingsManager.create(cwd,agentDir,{projectTrusted:!1});if(applyHttpProxySettings(bootstrapSettingsManager.getGlobalSettings().httpProxy),configureHttpDispatcher(),await handlePackageCommand(args,{extensionFactories})){let exitCode=process.exitCode??0;if(process.platform==="win32"&&exitCode===0&&args[0]==="update")return;process.exit(exitCode);return}if(await handleConfigCommand(args,{extensionFactories}))return;if(args[0]==="mcp"){let{runMcpCommand}=await loadMcpCommand();process.exitCode=await runMcpCommand(args.slice(1),{cwd,agentDir});return}let parsed=parseArgs(args);if(parsed.diagnostics.length>0){for(let d of parsed.diagnostics){let color=d.type==="error"?source_default.red:source_default.yellow;console.error(color(`${d.type==="error"?"Error":"Warning"}: ${d.message}`))}parsed.diagnostics.some(d=>d.type==="error")&&process.exit(1)}if(time("parseArgs"),parsed.version&&(console.log(VERSION),process.exit(0)),parsed.export){let result;try{let outputPath=parsed.messages.length>0?parsed.messages[0]:void 0;result=await exportFromFile(parsed.export,outputPath)}catch(error){let message=error instanceof Error?error.message:"Failed to export session";console.error(source_default.red(`Error: ${message}`)),process.exit(1)}console.log(`Exported to: ${result}`),process.exit(0)}let appMode=resolveAppMode(parsed,process.stdin.isTTY,process.stdout.isTTY);appMode!=="interactive"&&!isPlainRuntimeMetadataCommand(parsed)&&takeOverStdout(),parsed.mode==="rpc"&&parsed.fileArgs.length>0&&(console.error(source_default.red("Error: @file arguments are not supported in RPC mode")),process.exit(1)),validateForkFlags(parsed),validateSessionIdFlags(parsed);let{migratedAuthProviders:migratedProviders,deprecationWarnings}=runMigrations(cwd);time("runMigrations");let startupSettingsManager=SettingsManager.create(cwd,agentDir),startupSettingsDiagnostics=collectSettingsDiagnostics(startupSettingsManager);appMode==="interactive"&&!parsed.help&&parsed.listModels===void 0&&shouldRunFirstTimeSetup()&&(await showFirstTimeSetup(startupSettingsManager),time("firstTimeSetup")),appMode==="interactive"&&parsed.useTheme!==void 0&&startupSettingsManager.applyOverrides({theme:parsed.useTheme});let envSessionDir=process.env[ENV_SESSION_DIR],sessionDir=(parsed.sessionDir?normalizePath(parsed.sessionDir):void 0)??(envSessionDir?expandTildePath(envSessionDir):void 0)??startupSettingsManager.getSessionDir(),sessionManager=await createSessionManager(parsed,cwd,sessionDir,startupSettingsManager),missingSessionCwdIssue=getMissingSessionCwdIssue(sessionManager,cwd);if(missingSessionCwdIssue)if(appMode==="interactive"){let selectedCwd=await promptForMissingSessionCwd(missingSessionCwdIssue,startupSettingsManager);selectedCwd||process.exit(0),sessionManager=SessionManager.open(missingSessionCwdIssue.sessionFile,sessionDir,selectedCwd)}else console.error(source_default.red(new MissingSessionCwdError(missingSessionCwdIssue).message)),process.exit(1);if(parsed.name!==void 0){let name=normalizeSessionName(parsed.name);name===void 0&&(console.error(source_default.red("Error: --name requires a non-empty value")),process.exit(1)),sessionManager.appendSessionInfo(name)}time("createSessionManager");let trustStore=new ProjectTrustStore(agentDir),sessionCwd=sessionManager.getCwd(),autoTrustOnReloadCwd=parsed.projectTrustOverride===void 0&&!hasTrustRequiringProjectResources(sessionCwd)?sessionCwd:void 0,trustPromptMode=parsed.help||parsed.listModels!==void 0?"print":appMode,projectTrustByCwd=new Map,resolvedExtensionPaths=[path5.join(getPackageDir(),"extensions","pink-permissions.ts"),path5.join(getPackageDir(),"extensions","pink-hooks.ts"),...process.env.PINK_NO_BUILTIN_UI?[]:[path5.join(getPackageDir(),"extensions","pink-ui.ts"),path5.join(getPackageDir(),"extensions","pink-notify.ts"),path5.join(getPackageDir(),"extensions","pink-natives.ts"),path5.join(getPackageDir(),"extensions","pink-web.ts"),path5.join(getPackageDir(),"extensions","pink-shell-bg.ts"),path5.join(getPackageDir(),"extensions","pink-agente.ts"),path5.join(getPackageDir(),"extensions","pink-memory.ts"),path5.join(getPackageDir(),"extensions","pink-sessions-bus.ts"),path5.join(getPackageDir(),"extensions","pink-loop.ts"),path5.join(getPackageDir(),"extensions","pink-skills.ts"),path5.join(getPackageDir(),"extensions","pink-context.ts"),path5.join(getPackageDir(),"extensions","pink-lsp.ts"),path5.join(getPackageDir(),"extensions","pink-rules.ts"),path5.join(getPackageDir(),"extensions","pink-review.ts"),path5.join(getPackageDir(),"extensions","pink-skill-propose.ts"),path5.join(getPackageDir(),"extensions","pink-sandbox.ts"),path5.join(getPackageDir(),"extensions","pink-tela.ts"),path5.join(getPackageDir(),"extensions","pink-microfone.ts")],path5.join(getPackageDir(),"examples","extensions","subagent","index.ts"),path5.join(getPackageDir(),"examples","extensions","questionnaire.ts"),...(resolveCliPaths(cwd,parsed.extensions)??[])],resolvedSkillPaths=resolveCliPaths(cwd,parsed.skills),resolvedPromptTemplatePaths=resolveCliPaths(cwd,parsed.promptTemplates),resolvedThemePaths=resolveCliPaths(cwd,parsed.themes),createRuntime=async({cwd:cwd2,agentDir:agentDir2,sessionManager:sessionManager2,sessionStartEvent,projectTrustContext})=>{let isInitialRuntime=sessionStartEvent===void 0,projectTrustDiagnostics=[],cachedProjectTrust=projectTrustByCwd.get(cwd2),hasTrustRequiringResources=hasTrustRequiringProjectResources(cwd2),shouldResolveProjectTrust=parsed.projectTrustOverride===void 0&&cachedProjectTrust===void 0&&hasTrustRequiringResources,projectTrusted=shouldResolveProjectTrust?!1:cachedProjectTrust??parsed.projectTrustOverride??(!hasTrustRequiringResources||trustStore.get(cwd2)===!0),runtimeSettingsManager=SettingsManager.create(cwd2,agentDir2,{projectTrusted}),services2=await createAgentSessionServices({cwd:cwd2,agentDir:agentDir2,settingsManager:runtimeSettingsManager,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:parsed.unknownFlags,resourceLoaderReloadOptions:shouldResolveProjectTrust?{resolveProjectTrust:async({extensionsResult})=>{let trusted=await resolveProjectTrusted({cwd:cwd2,trustStore,trustOverride:parsed.projectTrustOverride,defaultProjectTrust:startupSettingsManager.getDefaultProjectTrust(),extensionsResult,projectTrustContext:projectTrustContext??createProjectTrustContext({cwd:cwd2,mode:isInitialRuntime?trustPromptMode:appMode,settingsManager:startupSettingsManager,hasUI:isInitialRuntime&&trustPromptMode==="interactive"}),onExtensionError:message=>projectTrustDiagnostics.push({type:"warning",message})});return projectTrustByCwd.set(cwd2,trusted),trusted}}:void 0,resourceLoaderOptions:{additionalExtensionPaths:resolvedExtensionPaths,additionalSkillPaths:resolvedSkillPaths,additionalPromptTemplatePaths:resolvedPromptTemplatePaths,additionalThemePaths:resolvedThemePaths,noExtensions:parsed.noExtensions,disabledBuiltinExtensions:parsed.noMcp?["mcp"]:void 0,noSkills:parsed.noSkills,noPromptTemplates:parsed.noPromptTemplates,noThemes:parsed.noThemes,noContextFiles:parsed.noContextFiles,systemPrompt:parsed.systemPrompt,appendSystemPrompt:parsed.appendSystemPrompt,extensionFactories}}),{settingsManager:settingsManager2,modelRuntime:modelRuntime2,resourceLoader:resourceLoader2}=services2,diagnostics=[...projectTrustDiagnostics,...services2.diagnostics,...collectSettingsDiagnostics(settingsManager2),...resourceLoader2.getExtensions().errors.map(({path:path10,error})=>({type:"error",message:`Failed to load extension "${path10}": ${error}`})),...(resourceLoader2.getExtensions().warnings??[]).map(({path:path10,warning})=>({type:"warning",message:`Extension package "${path10}": ${warning}`}))],modelPatterns=parsed.models??settingsManager2.getEnabledModels(),scopedModels=modelPatterns&&modelPatterns.length>0?await resolveModelScope(modelPatterns,modelRuntime2,{signal:AbortSignal.timeout(15e3)}):[],{options:sessionOptions,cliThinkingFromModel,diagnostics:sessionOptionDiagnostics}=buildSessionOptions(parsed,scopedModels,sessionManager2.buildSessionContext().messages.length>0,modelRuntime2,settingsManager2);diagnostics.push(...sessionOptionDiagnostics),parsed.apiKey&&(sessionOptions.model?await modelRuntime2.setRuntimeApiKey(sessionOptions.model.provider,parsed.apiKey):diagnostics.push({type:"error",message:"--api-key requires a model to be specified via --model, --provider/--model, or --models"}));let created=await createAgentSessionFromServices({services:services2,sessionManager:sessionManager2,sessionStartEvent,model:sessionOptions.model,thinkingLevel:sessionOptions.thinkingLevel,scopedModels:sessionOptions.scopedModels,tools:sessionOptions.tools,excludeTools:sessionOptions.excludeTools,noTools:sessionOptions.noTools,customTools:sessionOptions.customTools}),cliThinkingOverride=parsed.thinking!==void 0||cliThinkingFromModel;return created.session.model&&cliThinkingOverride&&created.session.setThinkingLevel(created.session.thinkingLevel),{...created,services:services2,diagnostics}};time("createRuntime");let runtime=await createAgentSessionRuntime(createRuntime,{cwd:sessionManager.getCwd(),agentDir,sessionManager});time("createAgentSessionRuntime");let{services,session,modelFallbackMessage}=runtime,{settingsManager,modelRuntime,resourceLoader}=services;if(setCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides()),applyHttpProxySettings(settingsManager.getGlobalSettings().httpProxy),configureHttpDispatcher(settingsManager.getHttpIdleTimeoutMs()),parsed.help){reportDiagnostics(startupSettingsDiagnostics);let extensionFlags=resourceLoader.getExtensions().extensions.flatMap(extension=>Array.from(extension.flags.values()));printHelp(extensionFlags),process.exit(0)}if(parsed.listModels!==void 0){reportDiagnostics(startupSettingsDiagnostics);let searchPattern=typeof parsed.listModels=="string"?parsed.listModels:void 0;await listModels(modelRuntime,searchPattern,AbortSignal.timeout(15e3)),process.exit(0)}let stdinContent;appMode!=="rpc"&&(stdinContent=await readPipedStdin(),stdinContent!==void 0&&appMode==="interactive"&&(appMode="print")),time("readPipedStdin");let{initialMessage,initialImages}=await prepareInitialMessage(parsed,stdinContent);time("prepareInitialMessage"),initTheme(settingsManager.getTheme(),appMode==="interactive"),time("initTheme"),appMode==="interactive"&&deprecationWarnings.length>0&&await showDeprecationWarnings(deprecationWarnings),time("resolveModelScope");let startupDiagnostics=deduplicateDiagnostics([...startupSettingsDiagnostics,...runtime.diagnostics]),hasRuntimeErrors=runtime.diagnostics.some(diagnostic=>diagnostic.type==="error");(appMode!=="interactive"||hasRuntimeErrors)&&reportDiagnostics(startupDiagnostics),hasRuntimeErrors&&(runtime.diagnostics.some(diagnostic=>diagnostic.message.includes("Failed to load extension"))&&console.error(source_default.yellow(EXTENSION_LOAD_FAILURE_HINT)),process.exit(1)),time("createAgentSession"),appMode!=="interactive"&&!session.model&&(console.error(source_default.red(formatNoModelsAvailableMessage())),process.exit(1));let startupBenchmark=isTruthyEnvFlag2(process.env.PINK_STARTUP_BENCHMARK);if(startupBenchmark&&appMode!=="interactive"&&(console.error(source_default.red("Error: PINK_STARTUP_BENCHMARK only supports interactive mode")),process.exit(1)),!offlineMode&&appMode==="rpc"){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),15e3);modelRuntime.refresh({signal:controller.signal}).catch(()=>{}).finally(()=>clearTimeout(timeout))}if(appMode==="rpc")printTimings(),await runRpcMode(runtime);else if(appMode==="interactive"){let interactiveMode=new InteractiveMode(runtime,{migratedProviders,startupDiagnostics,modelFallbackMessage,autoTrustOnReloadCwd,initialMessage,initialImages,initialMessages:parsed.messages,verbose:parsed.verbose,tuiMode:parsed.tuiMode,initialThemeSetting:parsed.useTheme});if(startupBenchmark){await interactiveMode.init(),time("interactiveMode.init"),await new Promise(resolve16=>setTimeout(resolve16,150)),interactiveMode.stop(),stopThemeWatcher(),printTimings(),process.stdout.writableLength>0&&await new Promise(resolve16=>process.stdout.once("drain",resolve16)),process.stderr.writableLength>0&&await new Promise(resolve16=>process.stderr.once("drain",resolve16));return}printTimings(),await interactiveMode.run()}else{printTimings();let exitCode=await runPrintMode(runtime,{mode:toPrintOutputMode(appMode),messages:parsed.messages,initialMessage,initialImages});stopThemeWatcher(),restoreStdout(),exitCode!==0&&(process.exitCode=exitCode);return}}export{configureHttpDispatcher,value_exports2 as value_exports,compile_exports,SettingsManager,parseArgs,resolveModelScopeWithDiagnostics,resolveCliModel,all_exports,compat_exports,VIRTUAL_MODEL_STATE_ENTRY,CredentialSynchronizationError,ModelRuntime,convertToPng,resizeImage,formatDimensionNote,detectSupportedImageMimeTypeFromFile,createSyntheticSourceInfo,DefaultPackageManager,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SessionSelectorComponent,parseFrontmatter,stripFrontmatter,loadSkillsFromDir,formatSkillsForPrompt,loadSkills,ExtensionRunner,convertToLlm,CURRENT_SESSION_VERSION,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,buildSessionProjection,buildSessionContext,SessionManager,createEventBus,dist_exports,serializeConversation,DEFAULT_COMPACTION_SETTINGS,calculateContextTokens,getLastAssistantUsage,shouldCompact,estimateTokens2 as estimateTokens,findTurnStartIndex,findCutPoint,generateSummary,generateSummaryWithUsage,compact,collectEntriesForBranchSummary,prepareBranchEntries,generateBranchSummary,defineTool,isBashToolResult,isPowerShellToolResult,isReadToolResult,isEditToolResult,isWriteToolResult,isGrepToolResult,isFindToolResult,isLsToolResult,isToolCallEventType,wrapRegisteredTool,wrapRegisteredTools,ModelRegistry,createLocalBashOperations,createBashToolDefinition,createBashTool,generateUnifiedPatch,generateDiffString,withFileMutationQueue,renderDiff,createEditToolDefinition,createEditTool,createFindToolDefinition,createFindTool,createGrepToolDefinition,createGrepTool,createLsToolDefinition,createLsTool,createLocalPowerShellOperations,createPowerShellToolDefinition,createPowerShellTool,createReadToolDefinition,createReadTool,createWriteToolDefinition,createWriteTool,createCodingTools,createReadOnlyTools,parseSkillBlock,AgentSession,createAgentSession,createCodemodeExtension,copyToClipboard,createMcpExtension,createToolSearchExtension,BorderedLoader,ExtensionEditorComponent,AssistantMessageComponent,BashExecutionComponent,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CustomEditor,CustomMessageComponent,FooterComponent,LoginDialogComponent,ModelSelectorComponent,OAuthSelectorComponent,SettingsSelectorComponent,SkillInvocationMessageComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,InteractiveMode,runPrintMode,RpcClient,runRpcMode,createExtensionRuntime,discoverAndLoadExtensions,loadProjectContextFiles,DefaultResourceLoader,createAgentSessionServices,createAgentSessionFromServices,AgentSessionRuntime,createAgentSessionRuntime,main};
|
|
@@ -131,6 +131,45 @@ function finalText(result: any, text: string) {
|
|
|
131
131
|
if (text && lastText !== text) push(result, [{ type: "text", text }], "stop");
|
|
132
132
|
}
|
|
133
133
|
|
|
134
|
+
// ---------- subagentes de todos os agentes (owner 2026-11-25: "tem que funcionar pra todos os subagents") ----------
|
|
135
|
+
// a chamada da ferramenta de subagente abre a linha e o resultado dela fecha: result.subagents[id] = { agent, task, ... }
|
|
136
|
+
export const SUBAGENT_TOOL = /^(task|agent|subagent|delegate|dispatch_agent|spawn_?agent)$/i;
|
|
137
|
+
export function subagentStart(result: any, id: string, agent: unknown, task: unknown): boolean {
|
|
138
|
+
if (!id) return false;
|
|
139
|
+
const known = result.subagents?.[id];
|
|
140
|
+
if (known) {
|
|
141
|
+
// o ACP manda a descrição só na atualização: completa o que veio vazio
|
|
142
|
+
const text = String(task ?? "").replace(/\s+/g, " ").trim().slice(0, 200);
|
|
143
|
+
const fill = (!known.task && text) || (known.agent === "subagente" && agent && agent !== "subagente");
|
|
144
|
+
if (!known.task && text) known.task = text;
|
|
145
|
+
if (known.agent === "subagente" && agent) known.agent = String(agent);
|
|
146
|
+
return Boolean(fill);
|
|
147
|
+
}
|
|
148
|
+
result.subagents ??= {};
|
|
149
|
+
result.subagents[id] = { agent: String(agent || "subagente"), task: String(task ?? "").replace(/\s+/g, " ").trim().slice(0, 200), started: Date.now(), state: "running" };
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
export function subagentEnd(result: any, id: string, failed = false): boolean {
|
|
153
|
+
const item = result.subagents?.[id];
|
|
154
|
+
if (!item || item.end) return false;
|
|
155
|
+
item.end = Date.now();
|
|
156
|
+
item.state = failed ? "failed" : "done";
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
// Codex (colaboração): spawnAgent abre um subagente por thread; agentsStates e closeAgent dizem quando acabou.
|
|
160
|
+
// shortcut: campos do app-server do Codex lidos pela documentação do protocolo, sem um Codex com colaboração para testar
|
|
161
|
+
function codexCollab(item: any, result: any): boolean {
|
|
162
|
+
let changed = false;
|
|
163
|
+
if (/spawn/i.test(String(item.tool ?? ""))) for (const thread of item.receiverThreadIds ?? []) changed = subagentStart(result, String(thread), item.agentType ?? item.model ?? "codex", item.prompt) || changed;
|
|
164
|
+
for (const [thread, value] of Object.entries(item.agentsStates ?? {})) {
|
|
165
|
+
const status = String((value as any)?.status ?? value ?? "");
|
|
166
|
+
if (/err|fail/i.test(status)) changed = subagentEnd(result, thread, true) || changed;
|
|
167
|
+
else if (/complet|done|shutdown|closed|finished/i.test(status)) changed = subagentEnd(result, thread) || changed;
|
|
168
|
+
}
|
|
169
|
+
if (/close/i.test(String(item.tool ?? ""))) for (const thread of item.receiverThreadIds ?? []) changed = subagentEnd(result, String(thread)) || changed;
|
|
170
|
+
return changed;
|
|
171
|
+
}
|
|
172
|
+
|
|
134
173
|
// ---------- Claude Code: stream-json ----------
|
|
135
174
|
export function applyClaudeEvent(event: any, result: any, emit: () => void): void {
|
|
136
175
|
if (event?.type === "system" && event.subtype === "init") {
|
|
@@ -147,11 +186,19 @@ export function applyClaudeEvent(event: any, result: any, emit: () => void): voi
|
|
|
147
186
|
: undefined,
|
|
148
187
|
)
|
|
149
188
|
.filter(Boolean);
|
|
189
|
+
for (const part of event.message.content) if (part?.type === "tool_use" && SUBAGENT_TOOL.test(String(part.name ?? ""))) subagentStart(result, String(part.id ?? ""), part.input?.subagent_type ?? "general-purpose", part.input?.description ?? part.input?.prompt);
|
|
150
190
|
if (!content.length) return;
|
|
151
191
|
push(result, content);
|
|
152
192
|
emit();
|
|
153
193
|
return;
|
|
154
194
|
}
|
|
195
|
+
// o resultado da ferramenta volta numa mensagem "user": fecha o subagente daquela chamada
|
|
196
|
+
if (event?.type === "user" && Array.isArray(event.message?.content)) {
|
|
197
|
+
let changed = false;
|
|
198
|
+
for (const part of event.message.content) if (part?.type === "tool_result") changed = subagentEnd(result, String(part.tool_use_id ?? ""), part.is_error === true) || changed;
|
|
199
|
+
if (changed) emit();
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
155
202
|
if (event?.type === "result") {
|
|
156
203
|
const usage = event.usage ?? {};
|
|
157
204
|
result.usage.input += (usage.input_tokens || 0) + (usage.cache_creation_input_tokens || 0);
|
|
@@ -178,7 +225,9 @@ export function applyCodexItem(item: any, result: any, emit: () => void): void {
|
|
|
178
225
|
else if (item.type === "fileChange") push(result, (item.changes ?? []).map((change: any) => tool(change?.kind?.type === "add" || change?.kind === "add" ? "write" : "edit", { path: String(change?.path ?? "") }, item.id)));
|
|
179
226
|
else if (item.type === "mcpToolCall") push(result, [tool(`mcp__${item.server}__${item.tool}`, item.arguments && typeof item.arguments === "object" ? item.arguments : {}, item.id)]);
|
|
180
227
|
else if (item.type === "webSearch") push(result, [tool("web_search", { query: String(item.query ?? "") }, item.id)]);
|
|
181
|
-
else
|
|
228
|
+
else if (item.type === "collabAgentToolCall") {
|
|
229
|
+
if (!codexCollab(item, result)) return;
|
|
230
|
+
} else return;
|
|
182
231
|
emit();
|
|
183
232
|
}
|
|
184
233
|
|
|
@@ -206,6 +255,16 @@ function acpArgs(update: any, before: Record<string, unknown> = {}): Record<stri
|
|
|
206
255
|
if (typeof input.code === "string") args.code = input.code; // opencode chama MCP por código: tools.pink.pink_tela({...})
|
|
207
256
|
return args;
|
|
208
257
|
}
|
|
258
|
+
// subagente no ACP: ferramenta "task"/"agent"... ou entrada com subagent_type; status completed/failed fecha a linha
|
|
259
|
+
function acpSubagent(update: any, result: any): boolean {
|
|
260
|
+
const id = String(update.toolCallId ?? "");
|
|
261
|
+
const input = update.rawInput && typeof update.rawInput === "object" ? update.rawInput : {};
|
|
262
|
+
let changed = false;
|
|
263
|
+
if (input.subagent_type || input.agent_type || SUBAGENT_TOOL.test(String(update.title ?? "")) || SUBAGENT_TOOL.test(String(input.tool ?? "")))
|
|
264
|
+
changed = subagentStart(result, id, input.subagent_type ?? input.agent_type ?? input.agent ?? "subagente", input.description ?? input.prompt ?? (SUBAGENT_TOOL.test(String(update.title ?? "")) ? "" : update.title));
|
|
265
|
+
if (update.status === "completed" || update.status === "failed") changed = subagentEnd(result, id, update.status === "failed") || changed;
|
|
266
|
+
return changed;
|
|
267
|
+
}
|
|
209
268
|
const flushThinking = (result: any, state: any) => {
|
|
210
269
|
if (state.thinking) push(result, [{ type: "thinking", thinking: state.thinking, ms: Date.now() - state.thoughtAt }]);
|
|
211
270
|
state.thinking = "";
|
|
@@ -228,11 +287,13 @@ export function applyAcpUpdate(update: any, result: any, state: { text: string;
|
|
|
228
287
|
if (state.text) push(result, [{ type: "text", text: state.text }]), (state.text = "");
|
|
229
288
|
const name = ACP_TOOLS[update.kind] ?? (typeof update.kind === "string" && update.kind !== "other" ? update.kind : "tool");
|
|
230
289
|
push(result, [tool(name, acpArgs(update), String(update.toolCallId ?? ""))]);
|
|
290
|
+
acpSubagent(update, result);
|
|
231
291
|
emit();
|
|
232
292
|
return;
|
|
233
293
|
}
|
|
234
294
|
// o opencode manda o comando e o arquivo só na atualização (o tool_call chega com título "shell" e entrada vazia)
|
|
235
295
|
if (update.sessionUpdate === "tool_call_update" && update.toolCallId) {
|
|
296
|
+
if (acpSubagent(update, result)) emit();
|
|
236
297
|
for (const message of result.messages) {
|
|
237
298
|
const part = message.content?.find((item: any) => item.type === "toolCall" && item.id === String(update.toolCallId));
|
|
238
299
|
if (!part) continue;
|
|
@@ -532,6 +593,7 @@ async function runCodex(child: any, task: string, cwd: string, result: any, emit
|
|
|
532
593
|
"codex",
|
|
533
594
|
(method, params) => {
|
|
534
595
|
if (method === "item/completed") applyCodexItem(params?.item, result, emit);
|
|
596
|
+
else if (method === "item/started" && params?.item?.type === "collabAgentToolCall") applyCodexItem(params.item, result, emit); // o subagente aparece ao nascer
|
|
535
597
|
else if (method === "thread/tokenUsage/updated") codexUsage(params?.tokenUsage, result);
|
|
536
598
|
else if (method === "error" && params?.error?.message) result.errorMessage = String(params.error.message);
|
|
537
599
|
else if (method === "turn/completed") {
|
|
@@ -583,6 +645,24 @@ async function runCodex(child: any, task: string, cwd: string, result: any, emit
|
|
|
583
645
|
// a ligação com um agente ACP: o processo, a sessão aberta e a mensagem em andamento (turn), para servir várias mensagens
|
|
584
646
|
type AcpTurn = { result: any; state: { text: string; loading: boolean }; emit: () => void; ask: () => Ask | undefined };
|
|
585
647
|
type AcpConn = { child: any; client: ReturnType<typeof rpc>; exited: Promise<number>; turn?: AcpTurn; sessionId?: string; model?: string; setup?: Promise<string | undefined>; fresh?: boolean; loading?: boolean };
|
|
648
|
+
// o que o agente quer fazer, em palavras: o título do ACP sozinho às vezes é só "bash" ou "edit" (owner 2026-11-25:
|
|
649
|
+
// "permitindo no escuro"). Junta o tipo, o comando ou os arquivos e diz que o sim vale só para esta vez.
|
|
650
|
+
const PERMISSION_KINDS: Record<string, string> = { read: "Ler arquivo", edit: "Editar arquivo", delete: "Apagar arquivo", move: "Mover arquivo", search: "Buscar nos arquivos", execute: "Rodar um comando", fetch: "Acessar a internet", think: "Pensar", other: "Outra ação" };
|
|
651
|
+
export function permissionText(call: any): string {
|
|
652
|
+
const input = call?.rawInput && typeof call.rawInput === "object" ? call.rawInput : {};
|
|
653
|
+
const title = String(call?.title ?? "").trim();
|
|
654
|
+
const kind = PERMISSION_KINDS[String(call?.kind ?? "")];
|
|
655
|
+
const command = [input.command, input.cmd].find((v) => typeof v === "string" && v.trim()) ?? (Array.isArray(input.command) ? input.command.join(" ") : "");
|
|
656
|
+
const files = [...new Set([...(Array.isArray(call?.locations) ? call.locations.map((l: any) => l?.path) : []), input.filePath, input.file_path, input.path, input.url].filter((v) => typeof v === "string" && v.trim()))];
|
|
657
|
+
const lines = [kind && kind.toLowerCase() !== title.toLowerCase() ? `${kind}: ${title || "?"}` : title || kind || "Executar uma ação."];
|
|
658
|
+
if (command && !title.includes(command)) lines.push(`Comando: ${command}`);
|
|
659
|
+
for (const file of files.slice(0, 5)) if (!title.includes(file)) lines.push(`Arquivo: ${file}`);
|
|
660
|
+
if (typeof input.description === "string" && input.description.trim()) lines.push(`Motivo: ${input.description.trim()}`);
|
|
661
|
+
if (!title && !kind && !command && !files.length) lines.push("O agente não disse mais nada sobre esta ação.");
|
|
662
|
+
lines.push("Sim vale só para esta vez.");
|
|
663
|
+
return lines.join("\n");
|
|
664
|
+
}
|
|
665
|
+
|
|
586
666
|
function acpOpen(child: any, name: string, exited: Promise<number>): AcpConn {
|
|
587
667
|
const conn = { child, exited } as AcpConn;
|
|
588
668
|
conn.client = rpc(
|
|
@@ -598,7 +678,7 @@ function acpOpen(child: any, name: string, exited: Promise<number>): AcpConn {
|
|
|
598
678
|
const allow = options.find((option) => option?.kind === "allow_once") ?? options.find((option) => String(option?.kind).startsWith("allow"));
|
|
599
679
|
const reject = options.find((option) => option?.kind === "reject_once") ?? options.find((option) => String(option?.kind).startsWith("reject"));
|
|
600
680
|
const confirm = conn.turn?.ask();
|
|
601
|
-
const ok = Boolean(allow && confirm && (await confirm(`O ${name} pede permissão`,
|
|
681
|
+
const ok = Boolean(allow && confirm && (await confirm(`O ${name} pede permissão`, permissionText(params?.toolCall))));
|
|
602
682
|
if (ok) return { outcome: { outcome: "selected", optionId: allow.optionId } };
|
|
603
683
|
return reject ? { outcome: { outcome: "selected", optionId: reject.optionId } } : { outcome: { outcome: "cancelled" } };
|
|
604
684
|
},
|