dal-code 1.0.40 → 1.0.42

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.
Files changed (145) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/NOTICE +76 -1
  3. package/PRIVACY.md +68 -2
  4. package/dist/cli/startup-ui.js +1 -1
  5. package/dist/core/agent-session.d.ts +3 -0
  6. package/dist/core/agent-session.js +6 -6
  7. package/dist/core/bug-report.js +5 -5
  8. package/dist/core/settings-manager.d.ts +0 -5
  9. package/dist/core/settings-manager.js +1 -1
  10. package/dist/dal/manifest.js +1 -1
  11. package/dist/modes/interactive/components/status-indicator.d.ts +1 -1
  12. package/dist/modes/interactive/components/status-indicator.js +1 -1
  13. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  14. package/dist/modes/interactive/interactive-mode.js +2 -2
  15. package/dist/modes/print-mode.d.ts +1 -1
  16. package/dist/modes/print-mode.js +7 -6
  17. package/dist/modes/rpc/rpc-client.d.ts +5 -1
  18. package/dist/modes/rpc/rpc-client.js +3 -3
  19. package/dist/modes/rpc/rpc-mode.js +1 -1
  20. package/dist/modes/rpc/rpc-types.d.ts +25 -0
  21. package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
  22. package/dist/node_modules/@dalcode/dal-advisor/src/index.js +9 -8
  23. package/dist/node_modules/@dalcode/dal-awake/LICENSE +21 -0
  24. package/dist/node_modules/@dalcode/dal-awake/package.json +31 -0
  25. package/dist/node_modules/@dalcode/dal-awake/src/index.js +3 -0
  26. package/dist/node_modules/@dalcode/dal-awake/src/inhibitor.js +1 -0
  27. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  28. package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
  29. package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
  30. package/dist/node_modules/@dalcode/dal-compat/src/at-imports.js +3 -0
  31. package/dist/node_modules/@dalcode/dal-compat/src/index.js +7 -5
  32. package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
  33. package/dist/node_modules/@dalcode/dal-dap/src/install.js +2 -2
  34. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  35. package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
  36. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  37. package/dist/node_modules/@dalcode/dal-guard/src/edit-anchor-core.js +22 -21
  38. package/dist/node_modules/@dalcode/dal-guard/src/edit-anchor.js +4 -4
  39. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  40. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  41. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  42. package/dist/node_modules/@dalcode/dal-learn/package.json +5 -2
  43. package/dist/node_modules/@dalcode/dal-learn/src/index.js +10 -10
  44. package/dist/node_modules/@dalcode/dal-learn/src/lessons.js +3 -3
  45. package/dist/node_modules/@dalcode/dal-learn/src/patches.js +10 -0
  46. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  47. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  48. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  49. package/dist/node_modules/@dalcode/dal-office/src/index.d.ts +1 -0
  50. package/dist/node_modules/@dalcode/dal-office/src/index.js +1 -1
  51. package/dist/node_modules/@dalcode/dal-office/src/render/deck-source.d.ts +10 -0
  52. package/dist/node_modules/@dalcode/dal-office/src/render/deck-source.js +2 -0
  53. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.js +3 -3
  54. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +3 -3
  55. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  56. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +3 -3
  57. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  58. package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
  59. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  60. package/dist/node_modules/@dalcode/dal-review/src/core.d.ts +1 -0
  61. package/dist/node_modules/@dalcode/dal-review/src/core.js +1 -1
  62. package/dist/node_modules/@dalcode/dal-review/src/findings.js +2 -2
  63. package/dist/node_modules/@dalcode/dal-review/src/index.js +1 -1
  64. package/dist/node_modules/@dalcode/dal-review/src/prompt.d.ts +1 -1
  65. package/dist/node_modules/@dalcode/dal-review/src/prompt.js +3 -2
  66. package/dist/node_modules/@dalcode/dal-review/src/runner.d.ts +2 -1
  67. package/dist/node_modules/@dalcode/dal-review/src/runner.js +2 -2
  68. package/dist/node_modules/@dalcode/dal-review/src/simplify.d.ts +5 -0
  69. package/dist/node_modules/@dalcode/dal-review/src/simplify.js +30 -0
  70. package/dist/node_modules/@dalcode/dal-review/src/types.d.ts +5 -0
  71. package/dist/node_modules/@dalcode/dal-review/src/types.js +1 -1
  72. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  73. package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
  74. package/dist/node_modules/@dalcode/dal-rtk/LICENSE +21 -0
  75. package/dist/node_modules/@dalcode/dal-rtk/package.json +31 -0
  76. package/dist/node_modules/@dalcode/dal-rtk/src/index.js +2 -0
  77. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  78. package/dist/node_modules/@dalcode/dal-skills/src/bundled/bounded-code-repair/SKILL.md +45 -0
  79. package/dist/node_modules/@dalcode/dal-skills/src/bundled/evidence-first-retrieval/SKILL.md +43 -0
  80. package/dist/node_modules/@dalcode/dal-skills/src/bundled/validated-structured-output/SKILL.md +36 -0
  81. package/dist/node_modules/@dalcode/dal-skills/src/bundled.js +1 -1
  82. package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
  83. package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
  84. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  85. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +21 -21
  86. package/dist/node_modules/@dalcode/dal-telemetry/package.json +8 -2
  87. package/dist/node_modules/@dalcode/dal-telemetry/src/config.js +3 -2
  88. package/dist/node_modules/@dalcode/dal-telemetry/src/consent.js +1 -0
  89. package/dist/node_modules/@dalcode/dal-telemetry/src/failure-queue.js +4 -0
  90. package/dist/node_modules/@dalcode/dal-telemetry/src/failure-reporting.js +5 -0
  91. package/dist/node_modules/@dalcode/dal-telemetry/src/failures.js +2 -0
  92. package/dist/node_modules/@dalcode/dal-telemetry/src/index.js +4 -3
  93. package/dist/node_modules/@dalcode/dal-telemetry/src/reporter.js +1 -1
  94. package/dist/node_modules/@dalcode/dal-telemetry/src/repro.js +1 -0
  95. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  96. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  97. package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -4
  98. package/dist/node_modules/@dalcode/dal-tool-catalog/src/path-hint.js +1 -0
  99. package/dist/node_modules/@dalcode/dal-tool-catalog/src/repair-hook.js +2 -1
  100. package/dist/node_modules/@dalcode/dal-tool-catalog/src/repair.js +1 -1
  101. package/dist/node_modules/@dalcode/dal-tool-catalog/src/tool-name.js +1 -0
  102. package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
  103. package/dist/node_modules/@dalcode/dal-usage/src/index.d.ts +1 -0
  104. package/dist/node_modules/@dalcode/dal-usage/src/index.js +2 -2
  105. package/dist/node_modules/@dalcode/dal-usage/src/time-limit.d.ts +4 -0
  106. package/dist/node_modules/@dalcode/dal-usage/src/time-limit.js +2 -0
  107. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  108. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  109. package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
  110. package/dist/node_modules/@dalcode/dal-workflow/src/lean-code.js +1 -1
  111. package/dist/node_modules/@dalcode/dal-workflow/src/working-contract.js +1 -0
  112. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  113. package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
  114. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  115. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  116. package/dist/node_modules/@earendil-works/pi-ai/dist/cli.js +0 -0
  117. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  118. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
  119. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  120. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  121. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  122. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
  123. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts +1 -0
  124. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +1 -1
  125. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  126. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  127. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  128. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  129. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  130. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  131. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  132. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  133. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  134. package/dist/sdk/index.d.ts +1 -1
  135. package/dist/sdk/office.d.ts +1 -1
  136. package/dist/sdk/office.js +1 -1
  137. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  138. package/examples/extensions/gondolin/package-lock.json +2 -2
  139. package/examples/extensions/gondolin/package.json +1 -1
  140. package/examples/extensions/sandbox/package-lock.json +2 -2
  141. package/examples/extensions/sandbox/package.json +1 -1
  142. package/examples/extensions/with-deps/package-lock.json +2 -2
  143. package/examples/extensions/with-deps/package.json +1 -1
  144. package/npm-shrinkwrap.json +2 -2
  145. package/package.json +1 -1
@@ -1,15 +1,15 @@
1
- var le=Object.defineProperty;var h=(T,e)=>le(T,"name",{value:e,configurable:!0});import{readFileSync as de,rmSync as ce}from"node:fs";import{basename as he,dirname as ue}from"node:path";import{runToolCall as me}from"@earendil-works/pi-agent-core";import{contentText as P,getCurrentSystemMessage as N,retryDelayMs as ge}from"@earendil-works/pi-ai";import{clampThinkingLevel as z,cleanupSessionResources as pe,getSupportedThinkingLevels as fe,isContextOverflow as B,isRecoverableLength as _e,isRetryableAssistantError as ye,modelsAreEqual as I,resetApiProviders as xe,streamSimple as Me}from"@earendil-works/pi-ai/compat";import{configureShellEnvironment as we}from"../dal/child-env.js";import{fill as q,noteUserMessageLanguage as be,t as k}from"../dal/i18n.js";import{getThemeByName as Re,theme as Te}from"../modes/interactive/theme/theme.js";import{stripFrontmatter as Ae}from"../utils/frontmatter.js";import{processImage as Ce}from"../utils/image-process.js";import{setOutputFileDirectory as ve}from"../utils/output-files.js";import{sleep as Se}from"../utils/sleep.js";import{normalizeToolResultImages as Ee}from"../utils/tool-result-images.js";import{formatNoApiKeyFoundMessage as O,formatNoModelSelectedMessage as H}from"./auth-guidance.js";import{BackgroundProcessManager as Pe}from"./background-processes.js";import{executeBashWithOperations as Ie}from"./bash-executor.js";import{generateBugReportSummary as ke}from"./bug-report.js";import{calculateContextTokens as $,collectEntriesForBranchSummary as Le,compact as Ne,compactionThreshold as G,estimateContextTokens as Be,estimateProjectedContextTokens as S,estimateTokens as Oe,generateBranchSummary as De,PRUNE_TARGET_RATIO as Fe,planToolOutputPruning as Ue,prepareCompaction as Q,shouldCompact as V}from"./compaction/index.js";import{DEFAULT_THINKING_LEVEL as We,THINKING_LEVEL_OPTIONS as je}from"./defaults.js";import{markBlankAssistantAsError as ze}from"./empty-assistant.js";import{exportSessionToHtml as qe}from"./export-html/index.js";import{createToolHtmlRenderer as He}from"./export-html/tool-renderer.js";import{ExtensionRunner as $e,wrapRegisteredTools as K}from"./extensions/index.js";import{emitSessionShutdownEvent as Ge}from"./extensions/runner.js";import{createToolNameMatcher as J,isMcpToolName as X}from"./mcp-servers.js";import{convertToLlm as D}from"./messages.js";import{ModelRegistry as Qe}from"./model-registry.js";import{isPlaceholderModel as Ve,pickHouseModel as Ke}from"./model-resolver.js";import{NestedToolCallRunner as Je}from"./nested-tool-calls.js";import{buildRuleSet as Xe,EMPTY_RULE_SET as Ye}from"./permissions/rules.js";import{buildReadGuard as Ze,evaluateToolPolicy as et,permissionAskHandlers as tt,setProcessReadGuard as st}from"./permissions/tool-policy.js";import{expandPromptTemplate as Y}from"./prompt-templates.js";import{filesystemRules as nt,resolveSandboxPolicy as ot,SANDBOX_ENV as it,sandboxEnvironmentValue as rt}from"./sandbox/policy.js";import{createScratchDir as at,ShellSandbox as lt,setProcessShellSandbox as dt}from"./sandbox/shell-sandbox.js";import{exportSessionToJsonl as ct}from"./session-export.js";import{getLatestCompactionEntry as Z,SessionManager as ht}from"./session-manager.js";import{applyToolModifiers as ee,DEFAULT_TOOL_NAMES as ut}from"./settings-manager.js";import{BUILTIN_PATH_PREFIX as te,createSyntheticSourceInfo as F,isSyntheticPath as se}from"./source-info.js";import{buildSystemPrompt as mt,buildSystemPromptSections as gt,diffSystemPromptSections as pt,normalizeBuildSystemPromptOptions as ne}from"./system-prompt.js";import{createLocalBashOperations as ft}from"./tools/bash.js";import{createAllToolDefinitions as _t}from"./tools/index.js";import{createProcessToolDefinition as yt}from"./tools/process.js";import{createToolDefinitionFromAgentTool as xt}from"./tools/tool-definition-wrapper.js";import{addUsageToTotals as L,combineUsage as Mt,createUsageTotals as wt}from"./usage-totals.js";import{findLatestResponse as bt,getBranchSelection as Rt,getVirtualModelState as Tt,isVirtualModel as C,VIRTUAL_MODEL_STATE_ENTRY as At}from"./virtual-models.js";function ys(T){const e=T.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);return e?{name:e[1],location:e[2],content:e[3],userMessage:e[4]?.trim()||void 0}:null}h(ys,"parseSkillBlock");function oe(T){return T?Object.fromEntries(Object.entries(T).filter(e=>e[1]!==null)):void 0}h(oe,"withoutDeletedHeaders");function ie(T){let e=0;for(const t of T)e+=Oe(t);return e}h(ie,"estimateMessagesTokens");class xs{static{h(this,"AgentSession")}agent;sessionManager;settingsManager;_scopedModels;_unsubscribeAgent;_eventListeners=[];_isAgentRunActive=!1;_promptAbortGeneration=0;_agentRunAbortRequested=!1;_preparingRun;_idleWaitPromise;_resolveIdleWait;_steeringMessages=[];_followUpMessages=[];_pendingNextTurnMessages=[];_pendingCustomMessages=[];_compactionAbortController=void 0;_autoCompactionAbortController=void 0;_overflowRecoveryAttempted=!1;_branchSummaryAbortController=void 0;_retryAbortController=void 0;_retryAttempt=0;_failedResponse;_bashAbortControllers=new Set;_pendingBashMessages=[];_extensionRunner;_turnIndex=0;_entryIdsByMessage=new WeakMap;_boundaryDispatchedMessages=new WeakSet;_lastAssistantMessage;_lastAssistantToolResults=[];_lastActivityOutcome="completed";_isBeforeSettle=!1;_abortDuringBeforeSettle=!1;_isEmittingAgentSettled=!1;_deferredSettledActions=[];_resourceLoader;_customTools;_baseToolDefinitions=new Map;_cwd;_extensionRunnerRef;_initialActiveToolNames;_pendingToolNames=new Set;_usesDefaultTools;_defaultToolModifiers;_allowedTools;_allowedToolEntries;_excludedToolEntries;_allowlistFiltersMcp=!1;_excludedTools;_baseToolsOverride;_sandboxOptions;_permissionRules=Ye;_readGuard;_shellSandbox;_sandboxScratch;_releaseOutputFileDirectory;_backgroundProcesses;_sessionStartEvent;_extensionUIContext;_extensionMode="print";_extensionCommandContextActions;_extensionAbortHandler;_extensionShutdownHandler;_extensionErrorListener;_extensionErrorUnsubscriber;_modelRuntime;_desiredModel;_cacheWarmer;_toolRegistry=new Map;_nestedToolCalls;_hiddenDeclarations=new Set;_toolDefinitions=new Map;_toolPromptSnippets=new Map;_toolPromptGuidelines=new Map;_baseSystemPromptOptions;_runSystemPromptOptions;constructor(e){this.agent=e.agent,this.sessionManager=e.sessionManager,this.settingsManager=e.settingsManager,this._scopedModels=e.scopedModels??[],this._resourceLoader=e.resourceLoader,this._customTools=e.customTools??[],this._cwd=e.cwd,this._modelRuntime=e.modelRuntime,this._desiredModel=e.desiredModel,this._cacheWarmer=e.cacheWarmer,this._cacheWarmer&&(this._cacheWarmer.onWarmed=t=>this._emit({type:"entry_appended",entry:t})),this._extensionRunnerRef=e.extensionRunnerRef,this._initialActiveToolNames=e.initialActiveToolNames,this._usesDefaultTools=e.usesDefaultTools??!1,this._defaultToolModifiers=e.defaultToolModifiers??[],e.allowedToolNames&&(this._allowedTools=J(e.allowedToolNames),this._allowlistFiltersMcp=e.allowedToolNames.length===0||e.allowedToolNames.some(t=>t.startsWith("mcp__"))),this._excludedTools=e.excludedToolNames?J(e.excludedToolNames):void 0,this._allowedToolEntries=e.allowedToolNames?[...e.allowedToolNames]:void 0,this._excludedToolEntries=e.excludedToolNames?[...e.excludedToolNames]:void 0,this._baseToolsOverride=e.baseToolsOverride,this._sandboxOptions=e.sandbox??{},this._backgroundProcesses=new Pe({sandbox:h(()=>this._shellSandbox,"sandbox"),shellPath:h(()=>this.settingsManager.getShellPath(),"shellPath"),onEvent:h(t=>this._emit(t),"onEvent")}),this._sessionStartEvent=e.sessionStartEvent??{type:"session_start",reason:"startup"},this._unsubscribeAgent=this.agent.subscribe(this._handleAgentEvent),this._installAgentToolHooks(),this._installAgentNextTurnRefresh(),this._installAgentRequestProjection(),this._installAgentBoundaryHooks(),this._installHiddenDeclarationsProjection(),this._installAgentForcedPromptProjection(),this._buildRuntime({activeToolNames:this._initialActiveToolNames,includeAllExtensionTools:!0}),this._usesDefaultTools&&this._restoreToolsFromTranscript(this._defaultToolModifiers)}get modelRuntime(){return this._modelRuntime}async _askPermission(e){const t=this._extensionRunner.createContext();for(const i of tt()){const r=await i(e,t);if(r)return r}if(!t.hasUI)return{approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"};const s=typeof e.input.command=="string"?e.input.command:JSON.stringify(e.input),n=k("\u4EC5\u672C\u6B21\u5141\u8BB8");return await t.ui.select([q(k("\u89C4\u5219 {rule} \u8981\u6C42\u5148\u786E\u8BA4\u518D\u8FD0\u884C\u3002"),{rule:e.rule}),q(k("\u5DE5\u5177\uFF1A{tool}"),{tool:e.toolName}),s].join(`
2
- `),[n,k("\u62D2\u7EDD")])===n?{approved:!0}:{approved:!1,message:"the user declined"}}getSandboxStatus(){return this._shellSandbox?.status()}get backgroundProcesses(){return this._backgroundProcesses}async _getRequiredRequestAuth(e,t){let s;try{s=await this._modelRuntime.getAuth(e,{signal:t})}catch(o){const i=o instanceof Error?o.cause:void 0;throw i instanceof Error&&i.message==="authHeader requires a resolved API key"?new Error(O(e.provider)):o}if(s&&(s.auth.apiKey||s.auth.headers))return{model:s.auth.baseUrl?{...e,baseUrl:s.auth.baseUrl}:e,apiKey:s.auth.apiKey,headers:oe(s.auth.headers),env:s.env};throw this._modelRuntime.isUsingOAuth(e.provider)?new Error(`Authentication failed for "${e.provider}". Credentials may have expired or network is unavailable. Run '/login ${e.provider}' to re-authenticate.`):new Error(O(e.provider))}async _getSummarizationRequestAuth(e,t){const{model:s,thinkingLevel:n}=C(e)?await this._modelRuntime.resolveModel(e,D(this.messages),{reason:"direct",thinkingLevel:this.thinkingLevel,signal:t}):{model:e,thinkingLevel:this.thinkingLevel};if(this.agent.streamFunction===Me)return{...await this._getRequiredRequestAuth(s,t),thinkingLevel:n};try{const o=await this._modelRuntime.getAuth(s,{signal:t});return o?{model:o.auth.baseUrl?{...s,baseUrl:o.auth.baseUrl}:s,apiKey:o.auth.apiKey,headers:oe(o.auth.headers),env:o.env,thinkingLevel:n}:{model:s,thinkingLevel:n}}catch(o){if(t?.aborted)throw o;return{model:s,thinkingLevel:n}}}_modelForMessage(e){const t=this.model;return t&&C(t)?this._modelRuntime.getPhysicalModel(e.provider,e.model):t?.provider===e.provider&&t.id===e.model?t:void 0}_recordSelection(){const e=this.model;if(!e)return;const t=h((o,i)=>this._modelRuntime.getModel(o,i),"getModel"),s=Rt(this.sessionManager.getBranch(),t);if(!s||s.provider===e.provider&&s.modelId===e.id)return;const n=t(s.provider,s.modelId);!C(e)&&!(n&&C(n))||this.sessionManager.appendModelChange(e.provider,e.id)}_limitsModel(){return this.routedModel?.model??this.model}_installAgentToolHooks(){this.agent.beforeToolCall=e=>this._beforeToolCall(e),this.agent.afterToolCall=e=>this._afterToolCall(e)}async _beforeToolCall({toolCall:e,args:t},s){const n=t??{},o=et({toolName:e.name,input:n,cwd:this._cwd},{rules:this._permissionRules,readGuard:this._readGuard});if(o?.behavior==="deny")return{block:!0,reason:o.reason};const i=this._extensionRunner;let r;if(i.hasHandlers("tool_call"))try{r=await i.emitToolCall({type:"tool_call",toolName:e.name,toolCallId:e.id,...s?{parentToolCallId:s}:{},input:n})}catch(a){throw a instanceof Error?a:new Error(`Extension failed, blocking execution: ${String(a)}`)}if(r?.block)return r;if(o?.behavior==="ask"){const a=await this._askPermission({toolCallId:e.id,toolName:e.name,input:n,cwd:this._cwd,rule:o.rule,source:o.source});if(!a.approved)return{block:!0,reason:`Not approved (permission rule ${o.rule} asks first)${a.message?`: ${a.message}`:"."}`}}return r}async _afterToolCall({toolCall:e,args:t,result:s,isError:n},o){const i=this._extensionRunner,r=i.hasHandlers("tool_result")?await i.emitToolResult({type:"tool_result",toolName:e.name,toolCallId:e.id,...o?{parentToolCallId:o}:{},input:t,content:s.content,details:s.details,...s.structuredContent===void 0?{}:{structuredContent:s.structuredContent},isError:n,usage:s.usage}):void 0,a=r?.content??s.content??[],l=this._limitsModel()?.inputLimits?.images?.resize,c=await Ee(a,{autoResizeImages:this.settingsManager.getImageAutoResize(),...l?{resizeOptions:l}:{}});if(!(!r&&c===a))return{content:c,details:r?.details,structuredContent:r?r.structuredContent:s.structuredContent,isError:r?.isError??n,usage:r?.usage}}async _executeNestedToolCall(e,t,s,n){return this._nestedToolCalls??=new Je({getTools:h(()=>this._getCallableTools(),"getTools"),isSequential:h(()=>this.agent.toolExecution==="sequential","isSequential"),runToolCall:h((o,i,r,a)=>{const l=this._findLastAssistantMessage();return l?me(o,{tools:this._getCallableTools(),assistantMessage:l,context:{messages:this.agent.state.messages,tools:this.agent.state.tools},beforeToolCall:h(c=>this._beforeToolCall(c,i),"beforeToolCall"),afterToolCall:h(c=>this._afterToolCall(c,i),"afterToolCall"),signal:r,onUpdate:a}):Promise.resolve({toolCall:o,result:{content:[{type:"text",text:"No assistant message issued this call"}],details:{}},isError:!0})},"runToolCall"),emit:h(async o=>{await this._extensionRunner.emit(o),this._emit(o)},"emit")}),this._nestedToolCalls.execute(e,t,s,n)}_compactionBaseTokens(){let e=this.agent.state.systemPrompt.length;for(const t of this.agent.state.tools)e+=t.name.length+(t.description?.length??0)+JSON.stringify(t.parameters??{}).length;return Math.ceil(e/4)}_exceedsCompactionThreshold(e,t){return e.contextWindow<=0?!1:V(S(t,this.sessionManager.getBranch()).tokens,e.contextWindow,this.settingsManager.getCompactionSettings(this.model),this._compactionBaseTokens())}_compactionThresholdFor(e){return G(e,this.settingsManager.getCompactionSettings(this.model),this._compactionBaseTokens())}_pruneToolOutputsInsteadOfCompacting(e){const t=this.settingsManager.getCompactionSettings(this.model);if(!t.pruneToolOutputs||!Number.isFinite(e)||e<=0)return!1;const s=this.sessionManager.buildSessionProjection(),n=S(s,this.sessionManager.getBranch()).tokens,o=Ue(s,t.keepRecentTokens);if(o.edits.length===0||n-o.tokensSaved>e*Fe)return!1;for(const i of o.edits){const r=this.sessionManager.getEntry(this.sessionManager.appendContextEdit(i.targetId,{content:i.content}));r&&this._emit({type:"entry_appended",entry:r})}return this._refreshFinalizedContext(),!0}async _compactBeforeNextAssistantResponse(e){const t=this.sessionManager.buildSessionProjection(),s=this.model;return!s||C(s)||!this._exceedsCompactionThreshold(s,t)?{...e,messages:t.messages}:(await this._runAutoCompaction("threshold",!1,this._compactionThresholdFor(s.contextWindow)),{...e,messages:this.sessionManager.buildSessionProjection().messages})}_installAgentRequestProjection(){const e=this.agent.prepareRequest;this.agent.prepareRequest=async(t,s)=>{const n=this._failedResponse;this._failedResponse=void 0;const o=h(async()=>{const f=this.sessionManager.buildSessionProjection(),p={...t.context,messages:f.messages,tools:this.agent.state.tools.slice()},M=await e?.({...t,context:p,model:this.agent.state.model,thinkingLevel:this.agent.state.thinkingLevel},s);return{previous:M,context:M?.context??p,projection:f}},"prepare");let{previous:i,context:r,projection:a}=await o();const l=i?.model??this.agent.state.model,c=i?.thinkingLevel??this.agent.state.thinkingLevel;if(!C(l))return{...i,context:r,model:l,thinkingLevel:c};const m=r.messages.findLastIndex(f=>f.role==="assistant"),u=r.messages.slice(m+1).some(f=>f.role==="user"),d=Tt(this.sessionManager.getBranch(),l.provider,l.id),g=await this._modelRuntime.resolveModel(l,D(r.messages),{reason:n?"retry":u?"user":"continuation",thinkingLevel:c,signal:s,failed:n,state:d});if(g.state!==void 0&&g.state!==d){const f={provider:l.provider,modelId:l.id,state:g.state},p=this.sessionManager.getEntry(this.sessionManager.appendCustomEntry(At,f));p&&this._emit({type:"entry_appended",entry:p})}return this._exceedsCompactionThreshold(g.model,a)&&(await this._runAutoCompaction("threshold",!1,this._compactionThresholdFor(g.model.contextWindow)),{previous:i,context:r}=await o()),{...i,context:r,model:g.model,thinkingLevel:g.thinkingLevel}}}async _dispatchTurnEndBoundary(e,t){this._lastActivityOutcome=e.stopReason==="aborted"?"aborted":e.stopReason==="error"?"error":"completed";const s=this._findPersistedMessageEntryId(e);if(!this._extensionRunner.hasHandlers("turn_end"))return!1;if(!s)return this._extensionRunner.emitError({extensionPath:"<boundary>",event:"turn_end",error:"turn_end could not resolve the persisted assistant entry ID"}),!1;const n=t.flatMap(i=>{const r=this._findPersistedMessageEntryId(i);return r?[r]:[]}),o=await this._extensionRunner.emitBoundary({type:"turn_end",turnIndex:this._turnIndex,message:e,toolResults:t,messageEntryId:s,toolResultEntryIds:n,outcome:this._lastActivityOutcome},i=>this._buildBoundaryContext(i,"turn_end"));return this._commitBoundaryDrafts(o.entries),o.continue&&!this._buildBoundaryContext([],"turn_end").canContinue?(this._reportInvalidBoundaryContinuation("turn_end"),!1):o.continue}_installAgentBoundaryHooks(){const e=this.agent.finishTurn;this.agent.finishTurn=async(t,s)=>{this._boundaryDispatchedMessages.add(t.message);const n=await this._dispatchTurnEndBoundary(t.message,t.toolResults),o=await e?.(t,s);if(o?.action==="end")return o;if(n||o?.action==="continue")return{action:"continue"}}}_installAgentNextTurnRefresh(){const e=this.agent.prepareNextTurnWithContext??(this.agent.prepareNextTurn?async(t,s)=>await this.agent.prepareNextTurn?.(s):void 0);this.agent.prepareNextTurnWithContext=async(t,s)=>{const n=await this._compactBeforeNextAssistantResponse(t.context),o=await e?.({...t,context:n},s),i=o?.context??n,r=this._runSystemPromptOptions??this._baseSystemPromptOptions,a=ne({...r,selectedTools:this.getActiveToolNames(),toolSnippets:{...this._baseSystemPromptOptions.toolSnippets,...r.toolSnippets},toolGuidelines:{...this._baseSystemPromptOptions.toolGuidelines,...r.toolGuidelines}}),l=this._preparePromptAndToolLoadout(a,i.messages);return this._runSystemPromptOptions=a,{...o,context:{...i,tools:this.agent.state.tools.slice()},messages:l?[...o?.messages??[],l]:o?.messages,model:this.agent.state.model,thinkingLevel:this.agent.state.thinkingLevel}}}_refreshFinalizedContext(){const e=this.sessionManager.buildSessionProjection();for(const t of e.entries)for(const s of t.messages)this._entryIdsByMessage.set(s,t.sourceEntry.id);this.agent.state.messages=e.messages}_applyBoundaryDrafts(e,t){const s=[];for(const n of t){let o;switch(n.type){case"custom":o=e.appendCustomEntry(n.customType,n.data);break;case"custom_message":o=e.appendCustomMessageEntry(n.customType,n.content,n.display,n.details);break;case"context_edit":o=e.appendContextEdit(n.targetId,n.replacement);break;case"compaction":{const r=S(e.buildSessionProjection(),e.getBranch()).tokens;o=e.appendCompaction(n.summary,n.firstKeptEntryId,r,n.details,!0,n.usage);break}}const i=e.getEntry(o);i&&s.push(i)}return s}_createBoundaryPreviewManager(e){const t=this.sessionManager.getHeader();if(!t)throw new Error("Session header is missing");const s=ht.inMemory(this._cwd,void 0,[t,...this.sessionManager.getBranch()]);return this._applyBoundaryDrafts(s,e),s}_getPendingBoundaryMessages(){return[...this.agent.peekQueuedMessages(),...this._pendingCustomMessages]}_buildBoundaryContext(e,t){const s=this._createBoundaryPreviewManager(e).buildSessionProjection(),n=this._getPendingBoundaryMessages(),o=D(s.messages),i=o[o.length-1]?.role,a=o.some(c=>c.role!=="system")&&i!=="assistant",l=this._pendingCustomMessages.length>0;return{contextEntries:s.entries,contextMessages:s.messages,llmMessages:o,pendingMessages:n,canContinue:a||l||(t==="turn_end"?this.agent.hasQueuedMessages():i==="assistant"&&this.agent.hasQueuedMessages())}}_commitBoundaryDrafts(e){const t=this._applyBoundaryDrafts(this.sessionManager,e);this._refreshFinalizedContext();for(const s of t)this._emit({type:"entry_appended",entry:s})}_reportInvalidBoundaryContinuation(e){this._extensionRunner.emitError({extensionPath:"<boundary>",event:e,error:`${e} requested continuation without runnable model context`})}_emit(e){for(const t of this._eventListeners)t(e)}_emitQueueUpdate(){this._emit({type:"queue_update",steering:[...this._steeringMessages],followUp:[...this._followUpMessages]})}async _emitSessionCompactFailed(e){this._extensionRunner.hasHandlers("session_compact_failed")&&await this._extensionRunner.emit({type:"session_compact_failed",...e})}_getIdleWaitPromise(){return this._idleWaitPromise||(this._idleWaitPromise=new Promise(e=>{this._resolveIdleWait=e})),this._idleWaitPromise}_resolveIdleWaitIfIdle(){if(!this.isIdle||!this._resolveIdleWait)return;const e=this._resolveIdleWait;this._idleWaitPromise=void 0,this._resolveIdleWait=void 0,e()}async _emitAgentSettled(){this._cacheWarmer?.onAgentSettled(),this._isAgentRunActive=!1,this._isEmittingAgentSettled=!0;try{const t=this._agentRunAbortRequested;await this._extensionRunner.emit({type:"agent_settled",aborted:t}),this._emit({type:"agent_settled",aborted:t})}finally{this._isEmittingAgentSettled=!1}const e=this._deferredSettledActions.splice(0);if(e.length>0){try{for(const t of e)await t()}finally{this._resolveIdleWaitIfIdle()}return}this._resolveIdleWaitIfIdle()}_handleAgentEvent=h(async e=>{if(e.type==="agent_start"&&this._agentRunAbortRequested&&this.agent.abort(),this._nestedToolCalls)if(e.type==="message_start"&&e.message.role==="toolResult"){const t=e.message,s=this._nestedToolCalls.takeRecord(t.toolCallId);s?.calls&&(t.nestedCalls=s.calls),s?.usage&&(t.usage=t.usage?Mt(t.usage,s.usage):s.usage)}else e.type==="agent_end"&&this._nestedToolCalls.clear();if(e.type==="message_start"&&e.message.role==="user"){this._overflowRecoveryAttempted=!1;const t=P(e.message.content,"");if(t){const s=this._steeringMessages.indexOf(t);if(s!==-1)this._steeringMessages.splice(s,1),this._emitQueueUpdate();else{const n=this._followUpMessages.indexOf(t);n!==-1&&(this._followUpMessages.splice(n,1),this._emitQueueUpdate())}}}if(e.type==="message_end"&&e.message.role==="assistant"){const t=e.message,s=ze(t);if(s!==t){e.message=s;const n=this.agent.state.messages;for(let o=n.length-1;o>=0;o--)if(n[o]===t){n[o]=s;break}}}if(await this._emitExtensionEvent(e),this._emit(e.type==="agent_end"?{...e,willRetry:this._willRetryAfterAgentEnd(e)}:e),e.type==="message_end"){let t;if(e.message.role==="custom"?t=this.sessionManager.appendCustomMessageEntry(e.message.customType,e.message.content,e.message.display,e.message.details):(e.message.role==="system"||e.message.role==="user"||e.message.role==="assistant"||e.message.role==="toolResult")&&(t=this.sessionManager.appendMessage(e.message)),t&&this._entryIdsByMessage.set(e.message,t),e.message.role==="assistant"){const s=e.message;this._lastAssistantMessage=s,s.stopReason!=="error"&&s.stopReason!=="length"&&(this._overflowRecoveryAttempted=!1),s.stopReason!=="error"&&this._retryAttempt>0&&(this._emit({type:"auto_retry_end",success:!0,attempt:this._retryAttempt}),this._retryAttempt=0)}}e.type==="turn_end"&&(this._lastAssistantToolResults=e.toolResults,this._flushPendingCustomMessages())},"_handleAgentEvent");_willRetryAfterAgentEnd(e){if(this._agentRunAbortRequested)return!1;const t=this.settingsManager.getRetrySettings();if(!t.enabled||this._retryAttempt>=t.maxRetries)return!1;for(let s=e.messages.length-1;s>=0;s--){const n=e.messages[s];if(n.role==="assistant")return this._isRetryableError(n)}return!1}_findPersistedMessageEntryId(e){const t=this._entryIdsByMessage.get(e);if(t)return t;for(const i of[...this.sessionManager.getBranch()].reverse())if(i.type==="message"&&i.message===e)return i.id;const s=this.agent.state.messages.indexOf(e);if(s<0)return;const n=this.sessionManager.buildSessionProjection();let o=0;for(const i of n.entries)for(let r=0;r<i.messages.length;r++){if(o===s)return this._entryIdsByMessage.set(e,i.sourceEntry.id),i.sourceEntry.id;o++}}_omitRecoveryAttempt(e,t=[]){const s=[e,...t],n=s.map(i=>this._findPersistedMessageEntryId(i));if(s.some((i,r)=>n[r]===void 0&&this.agent.state.messages.includes(i)))throw new Error("Cannot persist recovery omission because a projected message has no source entry");for(const i of n){if(!i)continue;const r=this.sessionManager.appendContextEdit(i,null),a=this.sessionManager.getEntry(r);a&&this._emit({type:"entry_appended",entry:a})}this._refreshFinalizedContext()}_findLastAssistantMessage(){const e=this.agent.state.messages;for(let t=e.length-1;t>=0;t--){const s=e[t];if(s.role==="assistant")return s}}_replaceMessageInPlace(e,t){if(e===t)return;const s=e;for(const n of Object.keys(s))delete s[n];Object.assign(s,t)}async _emitExtensionEvent(e){if(e.type==="agent_start")this._turnIndex=0,await this._extensionRunner.emit({type:"agent_start"});else if(e.type==="agent_end")await this._extensionRunner.emit({type:"agent_end",messages:e.messages});else if(e.type==="turn_start"){const t={type:"turn_start",turnIndex:this._turnIndex,timestamp:Date.now()};await this._extensionRunner.emit(t)}else if(e.type==="turn_end")e.message.role==="assistant"&&!this._boundaryDispatchedMessages.delete(e.message)&&await this._dispatchTurnEndBoundary(e.message,e.toolResults),this._turnIndex++;else if(e.type==="message_start"){const t={type:"message_start",message:e.message};await this._extensionRunner.emit(t)}else if(e.type==="message_update"){const t={type:"message_update",message:e.message,assistantMessageEvent:e.assistantMessageEvent};await this._extensionRunner.emit(t)}else if(e.type==="message_end"){const t={type:"message_end",message:e.message},s=await this._extensionRunner.emitMessageEnd(t);if(s){const n=(s.role==="user"||s.role==="assistant"||s.role==="toolResult"||s.role==="custom")&&s.content==null?{...s,content:[]}:s;this._replaceMessageInPlace(e.message,n)}}else if(e.type==="tool_execution_start"){const t={type:"tool_execution_start",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_update"){const t={type:"tool_execution_update",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args,partialResult:e.partialResult};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_end"){const t={type:"tool_execution_end",toolCallId:e.toolCallId,toolName:e.toolName,result:e.result,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs}};await this._extensionRunner.emit(t)}}subscribe(e){return this._eventListeners.push(e),()=>{const t=this._eventListeners.indexOf(e);t!==-1&&this._eventListeners.splice(t,1)}}_disconnectFromAgent(){this._unsubscribeAgent&&(this._unsubscribeAgent(),this._unsubscribeAgent=void 0)}dispose(){try{this.abortRetry(),this.abortCompaction(),this.abortBranchSummary(),this.abortBash(),this.agent.abort()}catch{}this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload()."),this._disconnectFromAgent(),this._eventListeners=[];const e=this._shellSandbox,t=this._sandboxScratch;this._sandboxScratch=void 0,this._releaseOutputFileDirectory?.(),this._releaseOutputFileDirectory=void 0,this._backgroundProcesses.stopAll().finally(()=>(t&&ce(t,{recursive:!0,force:!0}),e?.dispose())),this._cacheWarmer&&(this._cacheWarmer.onWarmed=void 0,this._cacheWarmer.cancel()),pe(this.sessionId)}refreshContext(){this._refreshFinalizedContext()}get state(){return this.agent.state}get cacheWarmingStatus(){return this._cacheWarmer?.status}setCacheWarmingMode(e){this.settingsManager.setCacheWarmingMode(e),this._cacheWarmer?.onModeChanged()}get model(){return this.agent.state.model}get thinkingLevel(){return this.agent.state.thinkingLevel}get routedModel(){if(!this.model||!C(this.model))return;const e=bt(this.agent.state.messages),t=e&&this._modelRuntime.getPhysicalModel(e.provider,e.model);return t&&{model:t,thinkingLevel:e?.thinkingLevel}}get isStreaming(){return this._isAgentRunActive}get isIdle(){return!this._isAgentRunActive&&!this.isCompacting}get systemPrompt(){return mt(this._runSystemPromptOptions??this._baseSystemPromptOptions)}get retryAttempt(){return this._retryAttempt}getActiveToolNames(){return this.agent.state.tools.map(e=>e.name)}getCallableToolNames(){return this._getCallableTools().map(e=>e.name)}isToolAllowed(e){return this._isAllowedTool(e)}getToolDenylist(){return this._excludedToolEntries&&this._excludedToolEntries.length>0?[...this._excludedToolEntries]:void 0}getToolAllowlist(){if(this._allowedToolEntries)return this._allowedToolEntries.filter(e=>!this._excludedTools?.(e))}getAllTools(){return Array.from(this._toolDefinitions.values()).map(({definition:e,sourceInfo:t})=>({name:e.name,description:e.description,parameters:e.parameters,promptGuidelines:e.promptGuidelines,exposure:this._getToolExposure(e.name),...e.namespace?{namespace:e.namespace}:{},...e.annotations?{annotations:{...e.annotations}}:{},sourceInfo:t}))}getToolDefinition(e){return this._toolDefinitions.get(e)?.definition}setActiveToolsByName(e){const t=this.getActiveToolNames();this._setActiveTools(e);const s=new Set(this.getActiveToolNames());t.some(n=>!s.has(n))&&this._pendingToolNames.clear()}_setActiveTools(e){const t=this._applyToolLoadout(e);for(const s of t)this._pendingToolNames.delete(s.name);this._rebuildSystemPrompt(t.map(s=>s.name))}_isAllowedTool(e){return this._excludedTools?.(e)?!1:!this._allowedTools||this._allowedTools(e)?!0:!this._allowlistFiltersMcp&&X(e)}_isActivatable(e){return!this._allowedTools||this._allowedTools(e)||!X(e)?!0:this._getToolExposure(e)!=="direct"&&this._toolRegistry.has("tool_search")}_getToolExposure(e){return this._toolDefinitions.get(e)?.definition.exposure??"direct"}_getCallableTools(e=new Set(this.getActiveToolNames())){return[...this._toolRegistry.values()].filter(t=>{const s=this._getToolExposure(t.name);return s==="codemode"||s==="deferred"||s==="direct"&&e.has(t.name)})}_applyToolLoadout(e){const t=[...new Set(e)].flatMap(i=>{const r=this._toolRegistry.get(i);return r&&this._getToolExposure(i)!=="hidden"&&this._isActivatable(i)?[r]:[]}),s=t.flatMap(i=>{const r=this._toolDefinitions.get(i.name);return r?.definition.prepareLoadout?[r]:[]}),n=new Set;let o=t;if(s.length>0){const i={declared:t,callable:this._getCallableTools(new Set(t.map(a=>a.name))),registered:[...this._toolRegistry.values()],getExposure:h(a=>this._getToolExposure(a),"getExposure"),getNamespace:h(a=>this._toolDefinitions.get(a)?.definition.namespace,"getNamespace"),getPromptGuidelines:h(a=>this._toolPromptGuidelines.get(a)??[],"getPromptGuidelines")},r=new Map;for(const{definition:a,sourceInfo:l}of s)try{const c=a.prepareLoadout?.(i);for(const[m,u]of Object.entries(c?.descriptions??{}))r.set(m,u);for(const m of c?.hiddenDeclarations??[])n.add(m)}catch(c){this._extensionRunner.emitError({extensionPath:l.path,event:"prepare_loadout",error:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0})}o=t.map(a=>{const l=r.get(a.name);return l===void 0?a:{...a,description:l}})}return this._hiddenDeclarations=n,this.agent.state.tools=o,o}get isCompacting(){return this._autoCompactionAbortController!==void 0||this._compactionAbortController!==void 0||this._branchSummaryAbortController!==void 0}get messages(){return this.agent.state.messages}get steeringMode(){return this.agent.steeringMode}get followUpMode(){return this.agent.followUpMode}get sessionFile(){return this.sessionManager.getSessionFile()}get sessionId(){return this.sessionManager.getSessionId()}get sessionName(){return this.sessionManager.getSessionName()}get scopedModels(){return this._scopedModels}setScopedModels(e){this._scopedModels=e}get promptTemplates(){return this._resourceLoader.getPrompts().prompts}_normalizePromptSnippet(e){if(!e)return;const t=e.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim();return t.length>0?t:void 0}_normalizePromptGuidelines(e){if(!e||e.length===0)return[];const t=new Set;for(const s of e){const n=s.trim();n.length>0&&t.add(n)}return Array.from(t)}_rebuildSystemPrompt(e){const t=e.filter(l=>this._toolRegistry.has(l)),s={};for(const l of this._toolRegistry.keys()){const c=this._toolPromptSnippets.get(l);c&&(s[l]=c)}const n=this._resourceLoader.getSystemPrompt(),o=this._resourceLoader.getAppendSystemPrompt(),i=o.length>0?o.join(`
1
+ var le=Object.defineProperty;var h=(T,e)=>le(T,"name",{value:e,configurable:!0});import{readFileSync as de,rmSync as ce}from"node:fs";import{basename as he,dirname as ue}from"node:path";import{runToolCall as me}from"@earendil-works/pi-agent-core";import{contentText as P,getCurrentSystemMessage as B,isNetworkAssistantError as ge,retryDelayMs as pe}from"@earendil-works/pi-ai";import{clampThinkingLevel as j,cleanupSessionResources as fe,getSupportedThinkingLevels as _e,isContextOverflow as N,isRecoverableLength as ye,isRetryableAssistantError as xe,modelsAreEqual as k,resetApiProviders as Me,streamSimple as we}from"@earendil-works/pi-ai/compat";import{configureShellEnvironment as be}from"../dal/child-env.js";import{fill as z,noteUserMessageLanguage as Re,t as I}from"../dal/i18n.js";import{getThemeByName as Te,theme as Ce}from"../modes/interactive/theme/theme.js";import{stripFrontmatter as Ae}from"../utils/frontmatter.js";import{processImage as ve}from"../utils/image-process.js";import{setOutputFileDirectory as Se}from"../utils/output-files.js";import{sleep as Ee}from"../utils/sleep.js";import{normalizeToolResultImages as Pe}from"../utils/tool-result-images.js";import{formatNoApiKeyFoundMessage as O,formatNoModelSelectedMessage as H}from"./auth-guidance.js";import{BackgroundProcessManager as ke}from"./background-processes.js";import{executeBashWithOperations as Ie}from"./bash-executor.js";import{generateBugReportSummary as Le}from"./bug-report.js";import{calculateContextTokens as $,collectEntriesForBranchSummary as Be,compact as Ne,compactionThreshold as G,estimateContextTokens as Oe,estimateProjectedContextTokens as S,estimateTokens as De,generateBranchSummary as Fe,PRUNE_TARGET_RATIO as Ue,planToolOutputPruning as We,prepareCompaction as Q,shouldCompact as V}from"./compaction/index.js";import{DEFAULT_THINKING_LEVEL as qe,THINKING_LEVEL_OPTIONS as je}from"./defaults.js";import{markBlankAssistantAsError as ze}from"./empty-assistant.js";import{exportSessionToHtml as He}from"./export-html/index.js";import{createToolHtmlRenderer as $e}from"./export-html/tool-renderer.js";import{ExtensionRunner as Ge,wrapRegisteredTools as K}from"./extensions/index.js";import{emitSessionShutdownEvent as Qe}from"./extensions/runner.js";import{createToolNameMatcher as J,isMcpToolName as X}from"./mcp-servers.js";import{convertToLlm as D}from"./messages.js";import{ModelRegistry as Ve}from"./model-registry.js";import{isPlaceholderModel as Ke,pickHouseModel as Je}from"./model-resolver.js";import{NestedToolCallRunner as Xe}from"./nested-tool-calls.js";import{buildRuleSet as Ye,EMPTY_RULE_SET as Ze}from"./permissions/rules.js";import{buildReadGuard as et,evaluateToolPolicy as tt,permissionAskHandlers as st,setProcessReadGuard as nt}from"./permissions/tool-policy.js";import{expandPromptTemplate as Y}from"./prompt-templates.js";import{filesystemRules as ot,resolveSandboxPolicy as it,SANDBOX_ENV as rt,sandboxEnvironmentValue as at}from"./sandbox/policy.js";import{createScratchDir as lt,ShellSandbox as dt,setProcessShellSandbox as ct}from"./sandbox/shell-sandbox.js";import{exportSessionToJsonl as ht}from"./session-export.js";import{getLatestCompactionEntry as Z,SessionManager as ut}from"./session-manager.js";import{applyToolModifiers as ee,DEFAULT_TOOL_NAMES as mt}from"./settings-manager.js";import{BUILTIN_PATH_PREFIX as te,createSyntheticSourceInfo as F,isSyntheticPath as se}from"./source-info.js";import{buildSystemPrompt as gt,buildSystemPromptSections as pt,diffSystemPromptSections as ft,normalizeBuildSystemPromptOptions as ne}from"./system-prompt.js";import{createLocalBashOperations as _t}from"./tools/bash.js";import{createAllToolDefinitions as yt}from"./tools/index.js";import{createProcessToolDefinition as xt}from"./tools/process.js";import{createToolDefinitionFromAgentTool as Mt}from"./tools/tool-definition-wrapper.js";import{addUsageToTotals as L,combineUsage as wt,createUsageTotals as bt}from"./usage-totals.js";import{findLatestResponse as Rt,getBranchSelection as Tt,getVirtualModelState as Ct,isVirtualModel as A,VIRTUAL_MODEL_STATE_ENTRY as At}from"./virtual-models.js";function xs(T){const e=T.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);return e?{name:e[1],location:e[2],content:e[3],userMessage:e[4]?.trim()||void 0}:null}h(xs,"parseSkillBlock");function oe(T){return T?Object.fromEntries(Object.entries(T).filter(e=>e[1]!==null)):void 0}h(oe,"withoutDeletedHeaders");function ie(T){let e=0;for(const t of T)e+=De(t);return e}h(ie,"estimateMessagesTokens");class Ms{static{h(this,"AgentSession")}agent;sessionManager;settingsManager;_scopedModels;_unsubscribeAgent;_eventListeners=[];_isAgentRunActive=!1;_promptAbortGeneration=0;_agentRunAbortRequested=!1;_preparingRun;_idleWaitPromise;_resolveIdleWait;_steeringMessages=[];_followUpMessages=[];_pendingNextTurnMessages=[];_pendingCustomMessages=[];_requestCompactionChecked=!1;_compactionAbortController=void 0;_autoCompactionAbortController=void 0;_overflowRecoveryAttempted=!1;_branchSummaryAbortController=void 0;_retryAbortController=void 0;_retryAttempt=0;_failedResponse;_bashAbortControllers=new Set;_pendingBashMessages=[];_extensionRunner;_turnIndex=0;_entryIdsByMessage=new WeakMap;_boundaryDispatchedMessages=new WeakSet;_lastAssistantMessage;_lastAssistantToolResults=[];_lastActivityOutcome="completed";_isBeforeSettle=!1;_abortDuringBeforeSettle=!1;_isEmittingAgentSettled=!1;_deferredSettledActions=[];_resourceLoader;_customTools;_baseToolDefinitions=new Map;_cwd;_extensionRunnerRef;_initialActiveToolNames;_pendingToolNames=new Set;_usesDefaultTools;_defaultToolModifiers;_allowedTools;_allowedToolEntries;_excludedToolEntries;_allowlistFiltersMcp=!1;_excludedTools;_baseToolsOverride;_sandboxOptions;_permissionRules=Ze;_readGuard;_shellSandbox;_sandboxScratch;_releaseOutputFileDirectory;_backgroundProcesses;_sessionStartEvent;_extensionUIContext;_extensionMode="print";_extensionCommandContextActions;_extensionAbortHandler;_extensionShutdownHandler;_extensionErrorListener;_extensionErrorUnsubscriber;_modelRuntime;_desiredModel;_cacheWarmer;_toolRegistry=new Map;_nestedToolCalls;_hiddenDeclarations=new Set;_toolDefinitions=new Map;_toolPromptSnippets=new Map;_toolPromptGuidelines=new Map;_baseSystemPromptOptions;_runSystemPromptOptions;constructor(e){this.agent=e.agent,this.sessionManager=e.sessionManager,this.settingsManager=e.settingsManager,this._scopedModels=e.scopedModels??[],this._resourceLoader=e.resourceLoader,this._customTools=e.customTools??[],this._cwd=e.cwd,this._modelRuntime=e.modelRuntime,this._desiredModel=e.desiredModel,this._cacheWarmer=e.cacheWarmer,this._cacheWarmer&&(this._cacheWarmer.onWarmed=t=>this._emit({type:"entry_appended",entry:t})),this._extensionRunnerRef=e.extensionRunnerRef,this._initialActiveToolNames=e.initialActiveToolNames,this._usesDefaultTools=e.usesDefaultTools??!1,this._defaultToolModifiers=e.defaultToolModifiers??[],e.allowedToolNames&&(this._allowedTools=J(e.allowedToolNames),this._allowlistFiltersMcp=e.allowedToolNames.length===0||e.allowedToolNames.some(t=>t.startsWith("mcp__"))),this._excludedTools=e.excludedToolNames?J(e.excludedToolNames):void 0,this._allowedToolEntries=e.allowedToolNames?[...e.allowedToolNames]:void 0,this._excludedToolEntries=e.excludedToolNames?[...e.excludedToolNames]:void 0,this._baseToolsOverride=e.baseToolsOverride,this._sandboxOptions=e.sandbox??{},this._backgroundProcesses=new ke({sandbox:h(()=>this._shellSandbox,"sandbox"),shellPath:h(()=>this.settingsManager.getShellPath(),"shellPath"),onEvent:h(t=>this._emit(t),"onEvent")}),this._sessionStartEvent=e.sessionStartEvent??{type:"session_start",reason:"startup"},this._unsubscribeAgent=this.agent.subscribe(this._handleAgentEvent),this._installAgentToolHooks(),this._installAgentNextTurnRefresh(),this._installAgentRequestProjection(),this._installAgentBoundaryHooks(),this._installHiddenDeclarationsProjection(),this._installAgentForcedPromptProjection(),this._buildRuntime({activeToolNames:this._initialActiveToolNames,includeAllExtensionTools:!0}),this._usesDefaultTools&&this._restoreToolsFromTranscript(this._defaultToolModifiers)}get modelRuntime(){return this._modelRuntime}async _askPermission(e){const t=this._extensionRunner.createContext();for(const i of st()){const r=await i(e,t);if(r)return r}if(!t.hasUI)return{approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"};const s=typeof e.input.command=="string"?e.input.command:JSON.stringify(e.input),n=I("\u4EC5\u672C\u6B21\u5141\u8BB8");return await t.ui.select([z(I("\u89C4\u5219 {rule} \u8981\u6C42\u5148\u786E\u8BA4\u518D\u8FD0\u884C\u3002"),{rule:e.rule}),z(I("\u5DE5\u5177\uFF1A{tool}"),{tool:e.toolName}),s].join(`
2
+ `),[n,I("\u62D2\u7EDD")])===n?{approved:!0}:{approved:!1,message:"the user declined"}}getSandboxStatus(){return this._shellSandbox?.status()}get backgroundProcesses(){return this._backgroundProcesses}async _getRequiredRequestAuth(e,t){let s;try{s=await this._modelRuntime.getAuth(e,{signal:t})}catch(o){const i=o instanceof Error?o.cause:void 0;throw i instanceof Error&&i.message==="authHeader requires a resolved API key"?new Error(O(e.provider)):o}if(s&&(s.auth.apiKey||s.auth.headers))return{model:s.auth.baseUrl?{...e,baseUrl:s.auth.baseUrl}:e,apiKey:s.auth.apiKey,headers:oe(s.auth.headers),env:s.env};throw this._modelRuntime.isUsingOAuth(e.provider)?new Error(`Authentication failed for "${e.provider}". Credentials may have expired or network is unavailable. Run '/login ${e.provider}' to re-authenticate.`):new Error(O(e.provider))}async _getSummarizationRequestAuth(e,t){const{model:s,thinkingLevel:n}=A(e)?await this._modelRuntime.resolveModel(e,D(this.messages),{reason:"direct",thinkingLevel:this.thinkingLevel,signal:t}):{model:e,thinkingLevel:this.thinkingLevel};if(this.agent.streamFunction===we)return{...await this._getRequiredRequestAuth(s,t),thinkingLevel:n};try{const o=await this._modelRuntime.getAuth(s,{signal:t});return o?{model:o.auth.baseUrl?{...s,baseUrl:o.auth.baseUrl}:s,apiKey:o.auth.apiKey,headers:oe(o.auth.headers),env:o.env,thinkingLevel:n}:{model:s,thinkingLevel:n}}catch(o){if(t?.aborted)throw o;return{model:s,thinkingLevel:n}}}_modelForMessage(e){const t=this.model;return t&&A(t)?this._modelRuntime.getPhysicalModel(e.provider,e.model):t?.provider===e.provider&&t.id===e.model?t:void 0}_recordSelection(){const e=this.model;if(!e)return;const t=h((o,i)=>this._modelRuntime.getModel(o,i),"getModel"),s=Tt(this.sessionManager.getBranch(),t);if(!s||s.provider===e.provider&&s.modelId===e.id)return;const n=t(s.provider,s.modelId);!A(e)&&!(n&&A(n))||this.sessionManager.appendModelChange(e.provider,e.id)}_limitsModel(){return this.routedModel?.model??this.model}_installAgentToolHooks(){this.agent.beforeToolCall=e=>this._beforeToolCall(e),this.agent.afterToolCall=e=>this._afterToolCall(e)}async _beforeToolCall({toolCall:e,args:t},s){const n=t??{},o=tt({toolName:e.name,input:n,cwd:this._cwd},{rules:this._permissionRules,readGuard:this._readGuard});if(o?.behavior==="deny")return{block:!0,reason:o.reason};const i=this._extensionRunner;let r;if(i.hasHandlers("tool_call"))try{r=await i.emitToolCall({type:"tool_call",toolName:e.name,toolCallId:e.id,...s?{parentToolCallId:s}:{},input:n})}catch(a){throw a instanceof Error?a:new Error(`Extension failed, blocking execution: ${String(a)}`)}if(r?.block)return r;if(o?.behavior==="ask"){const a=await this._askPermission({toolCallId:e.id,toolName:e.name,input:n,cwd:this._cwd,rule:o.rule,source:o.source});if(!a.approved)return{block:!0,reason:`Not approved (permission rule ${o.rule} asks first)${a.message?`: ${a.message}`:"."}`}}return r}async _afterToolCall({toolCall:e,args:t,result:s,isError:n},o){const i=this._extensionRunner,r=i.hasHandlers("tool_result")?await i.emitToolResult({type:"tool_result",toolName:e.name,toolCallId:e.id,...o?{parentToolCallId:o}:{},input:t,content:s.content,details:s.details,...s.structuredContent===void 0?{}:{structuredContent:s.structuredContent},isError:n,usage:s.usage}):void 0,a=r?.content??s.content??[],l=this._limitsModel()?.inputLimits?.images?.resize,c=await Pe(a,{autoResizeImages:this.settingsManager.getImageAutoResize(),...l?{resizeOptions:l}:{}});if(!(!r&&c===a))return{content:c,details:r?.details,structuredContent:r?r.structuredContent:s.structuredContent,isError:r?.isError??n,usage:r?.usage}}async _executeNestedToolCall(e,t,s,n){return this._nestedToolCalls??=new Xe({getTools:h(()=>this._getCallableTools(),"getTools"),isSequential:h(()=>this.agent.toolExecution==="sequential","isSequential"),runToolCall:h((o,i,r,a)=>{const l=this._findLastAssistantMessage();return l?me(o,{tools:this._getCallableTools(),assistantMessage:l,context:{messages:this.agent.state.messages,tools:this.agent.state.tools},beforeToolCall:h(c=>this._beforeToolCall(c,i),"beforeToolCall"),afterToolCall:h(c=>this._afterToolCall(c,i),"afterToolCall"),signal:r,onUpdate:a}):Promise.resolve({toolCall:o,result:{content:[{type:"text",text:"No assistant message issued this call"}],details:{}},isError:!0})},"runToolCall"),emit:h(async o=>{await this._extensionRunner.emit(o),this._emit(o)},"emit")}),this._nestedToolCalls.execute(e,t,s,n)}_compactionBaseTokens(){let e=this.agent.state.systemPrompt.length;for(const t of this.agent.state.tools)e+=t.name.length+(t.description?.length??0)+JSON.stringify(t.parameters??{}).length;return Math.ceil(e/4)}_exceedsCompactionThreshold(e,t){return e.contextWindow<=0?!1:V(S(t,this.sessionManager.getBranch()).tokens,e.contextWindow,this.settingsManager.getCompactionSettings(this.model),this._compactionBaseTokens())}_compactionThresholdFor(e){return G(e,this.settingsManager.getCompactionSettings(this.model),this._compactionBaseTokens())}_pruneToolOutputsInsteadOfCompacting(e){const t=this.settingsManager.getCompactionSettings(this.model);if(!t.pruneToolOutputs||!Number.isFinite(e)||e<=0)return!1;const s=this.sessionManager.buildSessionProjection(),n=S(s,this.sessionManager.getBranch()).tokens,o=We(s,t.keepRecentTokens);if(o.edits.length===0||n-o.tokensSaved>e*Ue)return!1;for(const i of o.edits){const r=this.sessionManager.getEntry(this.sessionManager.appendContextEdit(i.targetId,{content:i.content}));r&&this._emit({type:"entry_appended",entry:r})}return this._refreshFinalizedContext(),!0}async _compactBeforeNextAssistantResponse(e){const t=this.sessionManager.buildSessionProjection(),s=this.model;return!s||A(s)?{...e,messages:t.messages}:(this._requestCompactionChecked=!0,this._exceedsCompactionThreshold(s,t)?(await this._compactAtRequestBoundary(s.contextWindow),{...e,messages:this.sessionManager.buildSessionProjection().messages}):{...e,messages:t.messages})}async _compactAtRequestBoundary(e){await this._runAutoCompaction("threshold",!1,this._compactionThresholdFor(e)),this._flushPendingCustomMessages()}_installAgentRequestProjection(){const e=this.agent.prepareRequest;this.agent.prepareRequest=async(t,s)=>{const n=this._failedResponse;this._failedResponse=void 0;const o=h(async()=>{const g=this.sessionManager.buildSessionProjection(),x={...t.context,messages:g.messages,tools:this.agent.state.tools.slice()},f=await e?.({...t,context:x,model:this.agent.state.model,thinkingLevel:this.agent.state.thinkingLevel},s);return{previous:f,context:f?.context??x,projection:g}},"prepare");let{previous:i,context:r,projection:a}=await o();const l=i?.model??this.agent.state.model,c=i?.thinkingLevel??this.agent.state.thinkingLevel,m=this._requestCompactionChecked;if(this._requestCompactionChecked=!1,!A(l))return!m&&l&&this._exceedsCompactionThreshold(l,a)&&(await this._compactAtRequestBoundary(l.contextWindow),{previous:i,context:r}=await o()),{...i,context:r,model:l,thinkingLevel:c};const u=r.messages.findLastIndex(g=>g.role==="assistant"),d=r.messages.slice(u+1).some(g=>g.role==="user"),p=Ct(this.sessionManager.getBranch(),l.provider,l.id),y=await this._modelRuntime.resolveModel(l,D(r.messages),{reason:n?"retry":d?"user":"continuation",thinkingLevel:c,signal:s,failed:n,state:p});if(y.state!==void 0&&y.state!==p){const g={provider:l.provider,modelId:l.id,state:y.state},x=this.sessionManager.getEntry(this.sessionManager.appendCustomEntry(At,g));x&&this._emit({type:"entry_appended",entry:x})}return this._exceedsCompactionThreshold(y.model,a)&&(await this._compactAtRequestBoundary(y.model.contextWindow),{previous:i,context:r}=await o()),{...i,context:r,model:y.model,thinkingLevel:y.thinkingLevel}}}async _dispatchTurnEndBoundary(e,t){this._lastActivityOutcome=e.stopReason==="aborted"?"aborted":e.stopReason==="error"?"error":"completed";const s=this._findPersistedMessageEntryId(e);if(!this._extensionRunner.hasHandlers("turn_end"))return!1;if(!s)return this._extensionRunner.emitError({extensionPath:"<boundary>",event:"turn_end",error:"turn_end could not resolve the persisted assistant entry ID"}),!1;const n=t.flatMap(i=>{const r=this._findPersistedMessageEntryId(i);return r?[r]:[]}),o=await this._extensionRunner.emitBoundary({type:"turn_end",turnIndex:this._turnIndex,message:e,toolResults:t,messageEntryId:s,toolResultEntryIds:n,outcome:this._lastActivityOutcome},i=>this._buildBoundaryContext(i,"turn_end"));return this._commitBoundaryDrafts(o.entries),o.continue&&!this._buildBoundaryContext([],"turn_end").canContinue?(this._reportInvalidBoundaryContinuation("turn_end"),!1):o.continue}_installAgentBoundaryHooks(){const e=this.agent.finishTurn;this.agent.finishTurn=async(t,s)=>{this._boundaryDispatchedMessages.add(t.message);const n=await this._dispatchTurnEndBoundary(t.message,t.toolResults),o=await e?.(t,s);if(o?.action==="end")return o;if(n||o?.action==="continue")return{action:"continue"}}}_installAgentNextTurnRefresh(){const e=this.agent.prepareNextTurnWithContext??(this.agent.prepareNextTurn?async(t,s)=>await this.agent.prepareNextTurn?.(s):void 0);this.agent.prepareNextTurnWithContext=async(t,s)=>{const n=await this._compactBeforeNextAssistantResponse(t.context),o=await e?.({...t,context:n},s),i=o?.context??n,r=this._runSystemPromptOptions??this._baseSystemPromptOptions,a=ne({...r,selectedTools:this.getActiveToolNames(),toolSnippets:{...this._baseSystemPromptOptions.toolSnippets,...r.toolSnippets},toolGuidelines:{...this._baseSystemPromptOptions.toolGuidelines,...r.toolGuidelines}}),l=this._preparePromptAndToolLoadout(a,i.messages);return this._runSystemPromptOptions=a,{...o,context:{...i,tools:this.agent.state.tools.slice()},messages:l?[...o?.messages??[],l]:o?.messages,model:this.agent.state.model,thinkingLevel:this.agent.state.thinkingLevel}}}_refreshFinalizedContext(){const e=this.sessionManager.buildSessionProjection();for(const t of e.entries)for(const s of t.messages)this._entryIdsByMessage.set(s,t.sourceEntry.id);this.agent.state.messages=e.messages}_applyBoundaryDrafts(e,t){const s=[];for(const n of t){let o;switch(n.type){case"custom":o=e.appendCustomEntry(n.customType,n.data);break;case"custom_message":o=e.appendCustomMessageEntry(n.customType,n.content,n.display,n.details);break;case"context_edit":o=e.appendContextEdit(n.targetId,n.replacement);break;case"compaction":{const r=S(e.buildSessionProjection(),e.getBranch()).tokens;o=e.appendCompaction(n.summary,n.firstKeptEntryId,r,n.details,!0,n.usage);break}}const i=e.getEntry(o);i&&s.push(i)}return s}_createBoundaryPreviewManager(e){const t=this.sessionManager.getHeader();if(!t)throw new Error("Session header is missing");const s=ut.inMemory(this._cwd,void 0,[t,...this.sessionManager.getBranch()]);return this._applyBoundaryDrafts(s,e),s}_getPendingBoundaryMessages(){return[...this.agent.peekQueuedMessages(),...this._pendingCustomMessages]}_buildBoundaryContext(e,t){const s=this._createBoundaryPreviewManager(e).buildSessionProjection(),n=this._getPendingBoundaryMessages(),o=D(s.messages),i=o[o.length-1]?.role,a=o.some(c=>c.role!=="system")&&i!=="assistant",l=this._pendingCustomMessages.length>0;return{contextEntries:s.entries,contextMessages:s.messages,llmMessages:o,pendingMessages:n,canContinue:a||l||(t==="turn_end"?this.agent.hasQueuedMessages():i==="assistant"&&this.agent.hasQueuedMessages())}}_commitBoundaryDrafts(e){const t=this._applyBoundaryDrafts(this.sessionManager,e);this._refreshFinalizedContext();for(const s of t)this._emit({type:"entry_appended",entry:s})}_reportInvalidBoundaryContinuation(e){this._extensionRunner.emitError({extensionPath:"<boundary>",event:e,error:`${e} requested continuation without runnable model context`})}_emit(e){for(const t of this._eventListeners)t(e)}_emitQueueUpdate(){this._emit({type:"queue_update",steering:[...this._steeringMessages],followUp:[...this._followUpMessages]})}async _emitSessionCompactFailed(e){this._extensionRunner.hasHandlers("session_compact_failed")&&await this._extensionRunner.emit({type:"session_compact_failed",...e})}_getIdleWaitPromise(){return this._idleWaitPromise||(this._idleWaitPromise=new Promise(e=>{this._resolveIdleWait=e})),this._idleWaitPromise}_resolveIdleWaitIfIdle(){if(!this.isIdle||!this._resolveIdleWait)return;const e=this._resolveIdleWait;this._idleWaitPromise=void 0,this._resolveIdleWait=void 0,e()}async _emitAgentSettled(){this._cacheWarmer?.onAgentSettled(),this._isAgentRunActive=!1,this._isEmittingAgentSettled=!0;try{const t=this._agentRunAbortRequested;await this._extensionRunner.emit({type:"agent_settled",aborted:t}),this._emit({type:"agent_settled",aborted:t})}finally{this._isEmittingAgentSettled=!1}const e=this._deferredSettledActions.splice(0);if(e.length>0){try{for(const t of e)await t()}finally{this._resolveIdleWaitIfIdle()}return}this._resolveIdleWaitIfIdle()}_handleAgentEvent=h(async e=>{if(e.type==="agent_start"&&this._agentRunAbortRequested&&this.agent.abort(),this._nestedToolCalls)if(e.type==="message_start"&&e.message.role==="toolResult"){const t=e.message,s=this._nestedToolCalls.takeRecord(t.toolCallId);s?.calls&&(t.nestedCalls=s.calls),s?.usage&&(t.usage=t.usage?wt(t.usage,s.usage):s.usage)}else e.type==="agent_end"&&this._nestedToolCalls.clear();if(e.type==="message_start"&&e.message.role==="user"){this._overflowRecoveryAttempted=!1;const t=P(e.message.content,"");if(t){const s=this._steeringMessages.indexOf(t);if(s!==-1)this._steeringMessages.splice(s,1),this._emitQueueUpdate();else{const n=this._followUpMessages.indexOf(t);n!==-1&&(this._followUpMessages.splice(n,1),this._emitQueueUpdate())}}}if(e.type==="message_end"&&e.message.role==="assistant"){const t=e.message,s=ze(t);if(s!==t){e.message=s;const n=this.agent.state.messages;for(let o=n.length-1;o>=0;o--)if(n[o]===t){n[o]=s;break}}}if(await this._emitExtensionEvent(e),this._emit(e.type==="agent_end"?{...e,willRetry:this._willRetryAfterAgentEnd(e)}:e),e.type==="message_end"){let t;if(e.message.role==="custom"?t=this.sessionManager.appendCustomMessageEntry(e.message.customType,e.message.content,e.message.display,e.message.details):(e.message.role==="system"||e.message.role==="user"||e.message.role==="assistant"||e.message.role==="toolResult")&&(t=this.sessionManager.appendMessage(e.message)),t&&this._entryIdsByMessage.set(e.message,t),e.message.role==="assistant"){const s=e.message;this._lastAssistantMessage=s,s.stopReason!=="error"&&s.stopReason!=="length"&&(this._overflowRecoveryAttempted=!1),s.stopReason!=="error"&&this._retryAttempt>0&&(this._emit({type:"auto_retry_end",success:!0,attempt:this._retryAttempt}),this._retryAttempt=0)}}e.type==="turn_end"&&(this._lastAssistantToolResults=e.toolResults,this._flushPendingCustomMessages())},"_handleAgentEvent");_willRetryAfterAgentEnd(e){if(this._agentRunAbortRequested)return!1;const t=this.settingsManager.getRetrySettings();if(!t.enabled||this._retryAttempt>=t.maxRetries)return!1;for(let s=e.messages.length-1;s>=0;s--){const n=e.messages[s];if(n.role==="assistant")return this._isRetryableError(n)}return!1}_findPersistedMessageEntryId(e){const t=this._entryIdsByMessage.get(e);if(t)return t;for(const i of[...this.sessionManager.getBranch()].reverse())if(i.type==="message"&&i.message===e)return i.id;const s=this.agent.state.messages.indexOf(e);if(s<0)return;const n=this.sessionManager.buildSessionProjection();let o=0;for(const i of n.entries)for(let r=0;r<i.messages.length;r++){if(o===s)return this._entryIdsByMessage.set(e,i.sourceEntry.id),i.sourceEntry.id;o++}}_omitRecoveryAttempt(e,t=[]){const s=[e,...t],n=s.map(i=>this._findPersistedMessageEntryId(i));if(s.some((i,r)=>n[r]===void 0&&this.agent.state.messages.includes(i)))throw new Error("Cannot persist recovery omission because a projected message has no source entry");for(const i of n){if(!i)continue;const r=this.sessionManager.appendContextEdit(i,null),a=this.sessionManager.getEntry(r);a&&this._emit({type:"entry_appended",entry:a})}this._refreshFinalizedContext()}_findLastAssistantMessage(){const e=this.agent.state.messages;for(let t=e.length-1;t>=0;t--){const s=e[t];if(s.role==="assistant")return s}}_replaceMessageInPlace(e,t){if(e===t)return;const s=e;for(const n of Object.keys(s))delete s[n];Object.assign(s,t)}async _emitExtensionEvent(e){if(e.type==="agent_start")this._turnIndex=0,await this._extensionRunner.emit({type:"agent_start"});else if(e.type==="agent_end")await this._extensionRunner.emit({type:"agent_end",messages:e.messages});else if(e.type==="turn_start"){const t={type:"turn_start",turnIndex:this._turnIndex,timestamp:Date.now()};await this._extensionRunner.emit(t)}else if(e.type==="turn_end")e.message.role==="assistant"&&!this._boundaryDispatchedMessages.delete(e.message)&&await this._dispatchTurnEndBoundary(e.message,e.toolResults),this._turnIndex++;else if(e.type==="message_start"){const t={type:"message_start",message:e.message};await this._extensionRunner.emit(t)}else if(e.type==="message_update"){const t={type:"message_update",message:e.message,assistantMessageEvent:e.assistantMessageEvent};await this._extensionRunner.emit(t)}else if(e.type==="message_end"){const t={type:"message_end",message:e.message},s=await this._extensionRunner.emitMessageEnd(t);if(s){const n=(s.role==="user"||s.role==="assistant"||s.role==="toolResult"||s.role==="custom")&&s.content==null?{...s,content:[]}:s;this._replaceMessageInPlace(e.message,n)}}else if(e.type==="tool_execution_start"){const t={type:"tool_execution_start",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_update"){const t={type:"tool_execution_update",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args,partialResult:e.partialResult};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_end"){const t={type:"tool_execution_end",toolCallId:e.toolCallId,toolName:e.toolName,result:e.result,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs}};await this._extensionRunner.emit(t)}}subscribe(e){return this._eventListeners.push(e),()=>{const t=this._eventListeners.indexOf(e);t!==-1&&this._eventListeners.splice(t,1)}}_disconnectFromAgent(){this._unsubscribeAgent&&(this._unsubscribeAgent(),this._unsubscribeAgent=void 0)}dispose(){try{this.abortRetry(),this.abortCompaction(),this.abortBranchSummary(),this.abortBash(),this.agent.abort()}catch{}this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload()."),this._disconnectFromAgent(),this._eventListeners=[];const e=this._shellSandbox,t=this._sandboxScratch;this._sandboxScratch=void 0,this._releaseOutputFileDirectory?.(),this._releaseOutputFileDirectory=void 0,this._backgroundProcesses.stopAll().finally(()=>(t&&ce(t,{recursive:!0,force:!0}),e?.dispose())),this._cacheWarmer&&(this._cacheWarmer.onWarmed=void 0,this._cacheWarmer.cancel()),fe(this.sessionId)}refreshContext(){this._refreshFinalizedContext()}get state(){return this.agent.state}get cacheWarmingStatus(){return this._cacheWarmer?.status}setCacheWarmingMode(e){this.settingsManager.setCacheWarmingMode(e),this._cacheWarmer?.onModeChanged()}get model(){return this.agent.state.model}get thinkingLevel(){return this.agent.state.thinkingLevel}get routedModel(){if(!this.model||!A(this.model))return;const e=Rt(this.agent.state.messages),t=e&&this._modelRuntime.getPhysicalModel(e.provider,e.model);return t&&{model:t,thinkingLevel:e?.thinkingLevel}}get isStreaming(){return this._isAgentRunActive}get isIdle(){return!this._isAgentRunActive&&!this.isCompacting}get systemPrompt(){return gt(this._runSystemPromptOptions??this._baseSystemPromptOptions)}get retryAttempt(){return this._retryAttempt}getActiveToolNames(){return this.agent.state.tools.map(e=>e.name)}getCallableToolNames(){return this._getCallableTools().map(e=>e.name)}isToolAllowed(e){return this._isAllowedTool(e)}getToolDenylist(){return this._excludedToolEntries&&this._excludedToolEntries.length>0?[...this._excludedToolEntries]:void 0}getToolAllowlist(){if(this._allowedToolEntries)return this._allowedToolEntries.filter(e=>!this._excludedTools?.(e))}getAllTools(){return Array.from(this._toolDefinitions.values()).map(({definition:e,sourceInfo:t})=>({name:e.name,description:e.description,parameters:e.parameters,promptGuidelines:e.promptGuidelines,exposure:this._getToolExposure(e.name),...e.namespace?{namespace:e.namespace}:{},...e.annotations?{annotations:{...e.annotations}}:{},sourceInfo:t}))}getToolDefinition(e){return this._toolDefinitions.get(e)?.definition}setActiveToolsByName(e){const t=this.getActiveToolNames();this._setActiveTools(e);const s=new Set(this.getActiveToolNames());t.some(n=>!s.has(n))&&this._pendingToolNames.clear()}_setActiveTools(e){const t=this._applyToolLoadout(e);for(const s of t)this._pendingToolNames.delete(s.name);this._rebuildSystemPrompt(t.map(s=>s.name))}_isAllowedTool(e){return this._excludedTools?.(e)?!1:!this._allowedTools||this._allowedTools(e)?!0:!this._allowlistFiltersMcp&&X(e)}_isActivatable(e){return!this._allowedTools||this._allowedTools(e)||!X(e)?!0:this._getToolExposure(e)!=="direct"&&this._toolRegistry.has("tool_search")}_getToolExposure(e){return this._toolDefinitions.get(e)?.definition.exposure??"direct"}_getCallableTools(e=new Set(this.getActiveToolNames())){return[...this._toolRegistry.values()].filter(t=>{const s=this._getToolExposure(t.name);return s==="codemode"||s==="deferred"||s==="direct"&&e.has(t.name)})}_applyToolLoadout(e){const t=[...new Set(e)].flatMap(i=>{const r=this._toolRegistry.get(i);return r&&this._getToolExposure(i)!=="hidden"&&this._isActivatable(i)?[r]:[]}),s=t.flatMap(i=>{const r=this._toolDefinitions.get(i.name);return r?.definition.prepareLoadout?[r]:[]}),n=new Set;let o=t;if(s.length>0){const i={declared:t,callable:this._getCallableTools(new Set(t.map(a=>a.name))),registered:[...this._toolRegistry.values()],getExposure:h(a=>this._getToolExposure(a),"getExposure"),getNamespace:h(a=>this._toolDefinitions.get(a)?.definition.namespace,"getNamespace"),getPromptGuidelines:h(a=>this._toolPromptGuidelines.get(a)??[],"getPromptGuidelines")},r=new Map;for(const{definition:a,sourceInfo:l}of s)try{const c=a.prepareLoadout?.(i);for(const[m,u]of Object.entries(c?.descriptions??{}))r.set(m,u);for(const m of c?.hiddenDeclarations??[])n.add(m)}catch(c){this._extensionRunner.emitError({extensionPath:l.path,event:"prepare_loadout",error:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0})}o=t.map(a=>{const l=r.get(a.name);return l===void 0?a:{...a,description:l}})}return this._hiddenDeclarations=n,this.agent.state.tools=o,o}get isCompacting(){return this._autoCompactionAbortController!==void 0||this._compactionAbortController!==void 0||this._branchSummaryAbortController!==void 0}get messages(){return this.agent.state.messages}get steeringMode(){return this.agent.steeringMode}get followUpMode(){return this.agent.followUpMode}get sessionFile(){return this.sessionManager.getSessionFile()}get sessionId(){return this.sessionManager.getSessionId()}get sessionName(){return this.sessionManager.getSessionName()}get scopedModels(){return this._scopedModels}setScopedModels(e){this._scopedModels=e}get promptTemplates(){return this._resourceLoader.getPrompts().prompts}_normalizePromptSnippet(e){if(!e)return;const t=e.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim();return t.length>0?t:void 0}_normalizePromptGuidelines(e){if(!e||e.length===0)return[];const t=new Set;for(const s of e){const n=s.trim();n.length>0&&t.add(n)}return Array.from(t)}_rebuildSystemPrompt(e){const t=e.filter(l=>this._toolRegistry.has(l)),s={};for(const l of this._toolRegistry.keys()){const c=this._toolPromptSnippets.get(l);c&&(s[l]=c)}const n=this._resourceLoader.getSystemPrompt(),o=this._resourceLoader.getAppendSystemPrompt(),i=o.length>0?o.join(`
3
3
 
4
- `):"",r=this._resourceLoader.getSkills().skills,a=this._resourceLoader.getAgentsFiles().agentsFiles;this._baseSystemPromptOptions=ne({cwd:this._cwd,gitState:!0,projectFacts:!0,skills:r,contextFiles:a,customPrompt:n,appendSystemPrompt:i,selectedTools:t,hiddenTools:[...this._hiddenDeclarations],toolSnippets:s,toolGuidelines:Object.fromEntries(this._toolPromptGuidelines)})}_preparePromptAndToolLoadout(e,t=this.agent.state.messages){e.selectedTools=this._applyToolLoadout(e.selectedTools).map(n=>n.name),e.hiddenTools=[...this._hiddenDeclarations];const s=pt(N(t)?.sections??{},gt(e));return s?{role:"system",content:"",sections:s,timestamp:Date.now()}:void 0}_installHiddenDeclarationsProjection(){const e=this.agent.transformContext;this.agent.transformContext=async(t,s)=>{const n=e?await e(t,s):t,o=this._hiddenDeclarations;return o.size===0?n:n.map(i=>{if(i.role!=="system"||!i.toolsAdded&&!i.toolsRemoved)return i;const{toolsAdded:r,toolsRemoved:a,...l}=i,c=r?.filter(u=>!o.has(u.name))??[],m=a?.filter(u=>!o.has(u.name))??[];return{...l,...c.length>0?{toolsAdded:c}:{},...m.length>0?{toolsRemoved:m}:{}}})}}_installAgentForcedPromptProjection(){const e=this.agent.transformContext;this.agent.transformContext=async(t,s)=>{const n=e?await e(t,s):t,o=this._runSystemPromptOptions?.forceSystemPrompt;if(o===void 0)return n;const i=N(n);return[{role:"system",content:o,...i?.toolsAdded?{toolsAdded:i.toolsAdded}:{},timestamp:i?.timestamp??Date.now()},...n.filter(a=>a.role!=="system")]}}_restoreToolsFromTranscript(e=[]){this._pendingToolNames.clear();const t=N(this.sessionManager.buildSessionContext().messages);if(!t)return;const s=ee((t.toolsAdded??[]).map(n=>n.name),e);this._pendingToolNames=new Set(s.filter(n=>this._isAllowedTool(n))),this._setActiveTools(s)}async _startRun(e,t={}){const s={cancellable:t.cancelled!==void 0};this._preparingRun=s,this._isAgentRunActive=!0,this._agentRunAbortRequested=!1;const n=h(()=>{this._preparingRun===s&&this._releasePreparingRun()},"endWithoutRun");let o;try{const i=t.cancelled??(()=>!1);o=await this._prepareRun(e,()=>i()||this._preparingRun!==s)}catch(i){throw n(),i}if(!o){n();return}this._preparingRun=void 0,this._flushPendingBashMessages(),this._flushPendingCustomMessages(),t.onStarted?.(),this._failedResponse=void 0,this._recordSelection(),this._pendingToolNames.clear();try{for(await this.agent.prompt(o);!this._agentRunAbortRequested;){if(await this._handlePostAgentRun()){if(this._agentRunAbortRequested)break;await this.agent.continue();continue}if(this._agentRunAbortRequested||!await this._runBeforeSettleBoundary()||this._agentRunAbortRequested)break;await this.agent.continue()}}finally{this._agentRunAbortRequested&&this._finishCancelledRetry(),this._failedResponse=void 0,this._runSystemPromptOptions=void 0,this._flushPendingBashMessages(),this._flushPendingCustomMessages(),await this._emitAgentSettled()}}_releasePreparingRun(){this._preparingRun=void 0,this._isAgentRunActive=!1,this._agentRunAbortRequested=!1,this._flushPendingBashMessages(),this._flushPendingCustomMessages(),this._resolveIdleWaitIfIdle()}async _prepareRun(e,t){const s=this._findLastAssistantMessage();if(s&&(await this._checkCompaction(s,!1),t()))return;const n=this._baseSystemPromptOptions.selectedTools,o=await this._extensionRunner.emitBeforeAgentStart(e,this._baseSystemPromptOptions);if(t())return;o.systemPromptOptions.selectedTools.length!==n.length||o.systemPromptOptions.selectedTools.some((c,m)=>c!==n[m])||(o.systemPromptOptions.selectedTools=this.getActiveToolNames());let r;if(e.messageType==="custom")r=e.message;else{const c=await this._normalizePromptImages(e.images);if(t())return;r={role:"user",content:[{type:"text",text:c.hints.length>0?`${e.prompt}
4
+ `):"",r=this._resourceLoader.getSkills().skills,a=this._resourceLoader.getAgentsFiles().agentsFiles;this._baseSystemPromptOptions=ne({cwd:this._cwd,gitState:!0,projectFacts:!0,skills:r,contextFiles:a,customPrompt:n,appendSystemPrompt:i,selectedTools:t,hiddenTools:[...this._hiddenDeclarations],toolSnippets:s,toolGuidelines:Object.fromEntries(this._toolPromptGuidelines)})}_preparePromptAndToolLoadout(e,t=this.agent.state.messages){e.selectedTools=this._applyToolLoadout(e.selectedTools).map(n=>n.name),e.hiddenTools=[...this._hiddenDeclarations];const s=ft(B(t)?.sections??{},pt(e));return s?{role:"system",content:"",sections:s,timestamp:Date.now()}:void 0}_installHiddenDeclarationsProjection(){const e=this.agent.transformContext;this.agent.transformContext=async(t,s)=>{const n=e?await e(t,s):t,o=this._hiddenDeclarations;return o.size===0?n:n.map(i=>{if(i.role!=="system"||!i.toolsAdded&&!i.toolsRemoved)return i;const{toolsAdded:r,toolsRemoved:a,...l}=i,c=r?.filter(u=>!o.has(u.name))??[],m=a?.filter(u=>!o.has(u.name))??[];return{...l,...c.length>0?{toolsAdded:c}:{},...m.length>0?{toolsRemoved:m}:{}}})}}_installAgentForcedPromptProjection(){const e=this.agent.transformContext;this.agent.transformContext=async(t,s)=>{const n=e?await e(t,s):t,o=this._runSystemPromptOptions?.forceSystemPrompt;if(o===void 0)return n;const i=B(n);return[{role:"system",content:o,...i?.toolsAdded?{toolsAdded:i.toolsAdded}:{},timestamp:i?.timestamp??Date.now()},...n.filter(a=>a.role!=="system")]}}_restoreToolsFromTranscript(e=[]){this._pendingToolNames.clear();const t=B(this.sessionManager.buildSessionContext().messages);if(!t)return;const s=ee((t.toolsAdded??[]).map(n=>n.name),e);this._pendingToolNames=new Set(s.filter(n=>this._isAllowedTool(n))),this._setActiveTools(s)}async _startRun(e,t={}){const s={cancellable:t.cancelled!==void 0};this._preparingRun=s,this._isAgentRunActive=!0,this._agentRunAbortRequested=!1;const n=h(()=>{this._preparingRun===s&&this._releasePreparingRun()},"endWithoutRun");let o;try{const i=t.cancelled??(()=>!1);o=await this._prepareRun(e,()=>i()||this._preparingRun!==s)}catch(i){throw n(),i}if(!o){n();return}this._preparingRun=void 0,this._flushPendingBashMessages(),this._flushPendingCustomMessages(),t.onStarted?.(),this._failedResponse=void 0,this._recordSelection(),this._pendingToolNames.clear();try{for(await this.agent.prompt(o);!this._agentRunAbortRequested;){if(await this._handlePostAgentRun()){if(this._agentRunAbortRequested)break;await this.agent.continue();continue}if(this._agentRunAbortRequested||!await this._runBeforeSettleBoundary()||this._agentRunAbortRequested)break;await this.agent.continue()}}finally{this._agentRunAbortRequested&&this._finishCancelledRetry(),this._failedResponse=void 0,this._runSystemPromptOptions=void 0,this._flushPendingBashMessages(),this._flushPendingCustomMessages(),await this._emitAgentSettled()}}_releasePreparingRun(){this._preparingRun=void 0,this._isAgentRunActive=!1,this._agentRunAbortRequested=!1,this._flushPendingBashMessages(),this._flushPendingCustomMessages(),this._resolveIdleWaitIfIdle()}async _prepareRun(e,t){const s=this._findLastAssistantMessage();if(s&&(await this._checkCompaction(s,!1),t()))return;const n=this._baseSystemPromptOptions.selectedTools,o=await this._extensionRunner.emitBeforeAgentStart(e,this._baseSystemPromptOptions);if(t())return;o.systemPromptOptions.selectedTools.length!==n.length||o.systemPromptOptions.selectedTools.some((c,m)=>c!==n[m])||(o.systemPromptOptions.selectedTools=this.getActiveToolNames());let r;if(e.messageType==="custom")r=e.message;else{const c=await this._normalizePromptImages(e.images);if(t())return;r={role:"user",content:[{type:"text",text:c.hints.length>0?`${e.prompt}
5
5
 
6
6
  ${c.hints.join(`
7
- `)}`:e.prompt},...c.images],timestamp:Date.now()}}const a=[...this._pendingNextTurnMessages];this._pendingNextTurnMessages=[];for(const c of o.messages)a.push({role:"custom",customType:c.customType,content:c.content??[],display:c.display,details:c.details,timestamp:Date.now()});a.push(r);const l=this._preparePromptAndToolLoadout(o.systemPromptOptions);return this._runSystemPromptOptions=o.systemPromptOptions,l&&a.unshift(l),a}async _handlePostAgentRun(){const e=this._lastAssistantMessage,t=this._lastAssistantToolResults;return this._lastAssistantMessage=void 0,this._lastAssistantToolResults=[],this._agentRunAbortRequested?(this._finishCancelledRetry(),!1):e?this._isRetryableError(e)&&await this._prepareRetry(e)?(this._agentRunAbortRequested&&this._finishCancelledRetry(),this._failedResponse=e,!this._agentRunAbortRequested):this._agentRunAbortRequested?(this._finishCancelledRetry(),!1):(e.stopReason==="error"&&this._retryAttempt>0&&(this._emit({type:"auto_retry_end",success:!1,attempt:this._retryAttempt,finalError:e.errorMessage}),this._retryAttempt=0),await this._checkCompaction(e,!0,t)?!this._agentRunAbortRequested:!this._agentRunAbortRequested&&this.agent.hasQueuedMessages()):this.agent.hasQueuedMessages()}async _runBeforeSettleBoundary(){if(!this._extensionRunner.hasHandlers("agent_before_settle"))return this.agent.hasQueuedMessages();this._isBeforeSettle=!0,this._abortDuringBeforeSettle=!1;try{const e=await this._extensionRunner.emitBoundary({type:"agent_before_settle",outcome:this._lastActivityOutcome},n=>this._buildBoundaryContext(n,"agent_before_settle"));this._commitBoundaryDrafts(e.entries),this._flushPendingCustomMessages();const t=this._buildBoundaryContext([],"agent_before_settle");if(this._abortDuringBeforeSettle)return!1;const s=e.continue||this.agent.hasQueuedMessages();return s&&!t.canContinue?(e.continue&&this._reportInvalidBoundaryContinuation("agent_before_settle"),!1):s}finally{this._isBeforeSettle=!1}}async _runInputHandlers(e,t,s,n){if(!this._extensionRunner.hasHandlers("input"))return{text:e,images:t};const o=await this._extensionRunner.emitInput(e,t,s,n);if(o.action!=="handled")return o.action==="transform"?{text:o.text,images:o.images??t}:{text:e,images:t}}async _normalizePromptImages(e){if(!e)return{images:[],hints:[]};const t=[],s=[];for(const n of e){const o=await Ce(Buffer.from(n.data,"base64"),n.mimeType,{autoResizeImages:this.settingsManager.getImageAutoResize(),resizeOptions:this._limitsModel()?.inputLimits?.images?.resize});if(!o.ok){s.push(o.message);continue}t.push({type:"image",data:o.data,mimeType:o.mimeType}),s.push(...o.hints)}return{images:t,hints:s}}async prompt(e,t){await this._prompt(e,t,this._promptAbortGeneration)}async _prompt(e,t,s){if(this._isEmittingAgentSettled){this._deferredSettledActions.push(async()=>await this._prompt(e,t,s));return}const n=t?.expandPromptTemplates??!0,o=t?.preflightResult,i=h(()=>this._promptAbortGeneration===s?!1:(o?.("cancelled"),!0),"abortedBeforeRun");if(n&&e.startsWith("/")&&await this._tryExecuteExtensionCommand(e,()=>o?.("handled")))return;if(this._compactionAbortController!==void 0)throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");const r=await this._runInputHandlers(e,t?.images,t?.source??"interactive",this.isStreaming?t?.streamingBehavior:void 0);if(i())return;if(!r){o?.("handled");return}const{text:a,images:l}=r;(t?.source??"interactive")!=="extension"&&be(a);let c=a;if(n&&(c=this._expandSkillCommand(c),c=Y(c,[...this.promptTemplates])),this.isStreaming){if(!t?.streamingBehavior)throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");t.streamingBehavior==="followUp"?await this._queueFollowUp(c,l):await this._queueSteer(c,l),o?.("queued");return}if(!this.model)throw new Error(H());const m=this._modelRuntime.hasConfiguredAuth(this.model.provider)||await this._modelRuntime.checkAuth(this.model.provider)!==void 0;if(!i()){if(!m)throw this._modelRuntime.isUsingOAuth(this.model.provider)?new Error(`Authentication failed for "${this.model.provider}". Credentials may have expired or network is unavailable. Run '/login ${this.model.provider}' to re-authenticate.`):new Error(O(this.model.provider));await this._startRun({messageType:"user",prompt:c,images:l},{onStarted:h(()=>o?.("started"),"onStarted"),cancelled:i})}}async _tryExecuteExtensionCommand(e,t){const s=e.indexOf(" "),n=s===-1?e.slice(1):e.slice(1,s),o=s===-1?"":e.slice(s+1),i=this._extensionRunner.getCommand(n);if(!i)return!1;const r=this._extensionRunner.createCommandContext();t?.(),this._emit({type:"extension_command_start",command:n});try{return await i.handler(o,r),this._emit({type:"extension_command_end",command:n}),!0}catch(a){const l=a instanceof Error?a.message:String(a);return this._extensionRunner.emitError({extensionPath:`command:${n}`,event:"command",error:l}),this._emit({type:"extension_command_end",command:n,error:l}),!0}}_expandSkillCommand(e){if(!e.startsWith("/skill:"))return e;const t=e.indexOf(" "),s=t===-1?e.slice(7):e.slice(7,t),n=t===-1?"":e.slice(t+1).trim(),o=this.resourceLoader.getSkills().skills.find(i=>i.name===s);if(!o)return e;try{const i=de(o.filePath,"utf-8"),r=Ae(i).trim(),a=`<skill name="${o.name}" location="${o.filePath}">
7
+ `)}`:e.prompt},...c.images],timestamp:Date.now()}}const a=[...this._pendingNextTurnMessages];this._pendingNextTurnMessages=[];for(const c of o.messages)a.push({role:"custom",customType:c.customType,content:c.content??[],display:c.display,details:c.details,timestamp:Date.now()});a.push(r);const l=this._preparePromptAndToolLoadout(o.systemPromptOptions);return this._runSystemPromptOptions=o.systemPromptOptions,l&&a.unshift(l),a}async _handlePostAgentRun(){const e=this._lastAssistantMessage,t=this._lastAssistantToolResults;return this._lastAssistantMessage=void 0,this._lastAssistantToolResults=[],this._agentRunAbortRequested?(this._finishCancelledRetry(),!1):e?this._isRetryableError(e)&&await this._prepareRetry(e)?(this._agentRunAbortRequested&&this._finishCancelledRetry(),this._failedResponse=e,!this._agentRunAbortRequested):this._agentRunAbortRequested?(this._finishCancelledRetry(),!1):(e.stopReason==="error"&&this._retryAttempt>0&&(this._emit({type:"auto_retry_end",success:!1,attempt:this._retryAttempt,finalError:e.errorMessage}),this._retryAttempt=0),await this._checkCompaction(e,!0,t)?!this._agentRunAbortRequested:!this._agentRunAbortRequested&&this.agent.hasQueuedMessages()):this.agent.hasQueuedMessages()}async _runBeforeSettleBoundary(){if(!this._extensionRunner.hasHandlers("agent_before_settle"))return this.agent.hasQueuedMessages();this._isBeforeSettle=!0,this._abortDuringBeforeSettle=!1;try{const e=await this._extensionRunner.emitBoundary({type:"agent_before_settle",outcome:this._lastActivityOutcome},n=>this._buildBoundaryContext(n,"agent_before_settle"));this._commitBoundaryDrafts(e.entries),this._flushPendingCustomMessages();const t=this._buildBoundaryContext([],"agent_before_settle");if(this._abortDuringBeforeSettle)return!1;const s=e.continue||this.agent.hasQueuedMessages();return s&&!t.canContinue?(e.continue&&this._reportInvalidBoundaryContinuation("agent_before_settle"),!1):s}finally{this._isBeforeSettle=!1}}async _runInputHandlers(e,t,s,n){if(!this._extensionRunner.hasHandlers("input"))return{text:e,images:t};const o=await this._extensionRunner.emitInput(e,t,s,n);if(o.action!=="handled")return o.action==="transform"?{text:o.text,images:o.images??t}:{text:e,images:t}}async _normalizePromptImages(e){if(!e)return{images:[],hints:[]};const t=[],s=[];for(const n of e){const o=await ve(Buffer.from(n.data,"base64"),n.mimeType,{autoResizeImages:this.settingsManager.getImageAutoResize(),resizeOptions:this._limitsModel()?.inputLimits?.images?.resize});if(!o.ok){s.push(o.message);continue}t.push({type:"image",data:o.data,mimeType:o.mimeType}),s.push(...o.hints)}return{images:t,hints:s}}async prompt(e,t){await this._prompt(e,t,this._promptAbortGeneration)}async _prompt(e,t,s){if(this._isEmittingAgentSettled){this._deferredSettledActions.push(async()=>await this._prompt(e,t,s));return}const n=t?.expandPromptTemplates??!0,o=t?.preflightResult,i=h(()=>this._promptAbortGeneration===s?!1:(o?.("cancelled"),!0),"abortedBeforeRun");if(n&&e.startsWith("/")&&await this._tryExecuteExtensionCommand(e,()=>o?.("handled")))return;if(this._compactionAbortController!==void 0)throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");const r=await this._runInputHandlers(e,t?.images,t?.source??"interactive",this.isStreaming?t?.streamingBehavior:void 0);if(i())return;if(!r){o?.("handled");return}const{text:a,images:l}=r;(t?.source??"interactive")!=="extension"&&Re(a);let c=a;if(n&&(c=this._expandSkillCommand(c),c=Y(c,[...this.promptTemplates])),this.isStreaming){if(!t?.streamingBehavior)throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");t.streamingBehavior==="followUp"?await this._queueFollowUp(c,l):await this._queueSteer(c,l),o?.("queued");return}if(!this.model)throw new Error(H());const m=this._modelRuntime.hasConfiguredAuth(this.model.provider)||await this._modelRuntime.checkAuth(this.model.provider)!==void 0;if(!i()){if(!m)throw this._modelRuntime.isUsingOAuth(this.model.provider)?new Error(`Authentication failed for "${this.model.provider}". Credentials may have expired or network is unavailable. Run '/login ${this.model.provider}' to re-authenticate.`):new Error(O(this.model.provider));await this._startRun({messageType:"user",prompt:c,images:l},{onStarted:h(()=>o?.("started"),"onStarted"),cancelled:i})}}async _tryExecuteExtensionCommand(e,t){const s=e.indexOf(" "),n=s===-1?e.slice(1):e.slice(1,s),o=s===-1?"":e.slice(s+1),i=this._extensionRunner.getCommand(n);if(!i)return!1;const r=this._extensionRunner.createCommandContext();t?.(),this._emit({type:"extension_command_start",command:n});try{return await i.handler(o,r),this._emit({type:"extension_command_end",command:n}),!0}catch(a){const l=a instanceof Error?a.message:String(a);return this._extensionRunner.emitError({extensionPath:`command:${n}`,event:"command",error:l}),this._emit({type:"extension_command_end",command:n,error:l}),!0}}_expandSkillCommand(e){if(!e.startsWith("/skill:"))return e;const t=e.indexOf(" "),s=t===-1?e.slice(7):e.slice(7,t),n=t===-1?"":e.slice(t+1).trim(),o=this.resourceLoader.getSkills().skills.find(i=>i.name===s);if(!o)return e;try{const i=de(o.filePath,"utf-8"),r=Ae(i).trim(),a=`<skill name="${o.name}" location="${o.filePath}">
8
8
  References are relative to ${o.baseDir}.
9
9
 
10
10
  ${r}
11
11
  </skill>`;return n?`${a}
12
12
 
13
13
  ${n}`:a}catch(i){return this._extensionRunner.emitError({extensionPath:o.filePath,event:"skill_expansion",error:i instanceof Error?i.message:String(i)}),e}}async _queueUserInput(e,t,s,n){e.startsWith("/")&&this._throwIfExtensionCommand(e);const o=await this._runInputHandlers(e,t,n,this.isStreaming?s:void 0);if(!o)return"handled";let i=this._expandSkillCommand(o.text);return i=Y(i,[...this.promptTemplates]),s==="steer"?await this._queueSteer(i,o.images):await this._queueFollowUp(i,o.images),"queued"}async steer(e,t,s){return this._queueUserInput(e,t,"steer",s?.source??"interactive")}async followUp(e,t,s){return this._queueUserInput(e,t,"followUp",s?.source??"interactive")}async _queueSteer(e,t){this._steeringMessages.push(e),this._emitQueueUpdate();const s=[{type:"text",text:e}];t&&s.push(...t),this.agent.steer({role:"user",content:s,timestamp:Date.now()})}async _queueFollowUp(e,t){this._followUpMessages.push(e),this._emitQueueUpdate();const s=[{type:"text",text:e}];t&&s.push(...t),this.agent.followUp({role:"user",content:s,timestamp:Date.now()})}_throwIfExtensionCommand(e){const t=e.indexOf(" "),s=t===-1?e.slice(1):e.slice(1,t);if(this._extensionRunner.getCommand(s))throw new Error(`Extension command "/${s}" cannot be queued. Use prompt() or execute the command when not streaming.`)}async sendCustomMessage(e,t){const s={role:"custom",customType:e.customType,content:e.content??[],display:e.display,details:e.details,timestamp:Date.now()};if(t?.deliverAs==="nextTurn")this._pendingNextTurnMessages.push(s);else if(this.isStreaming&&t?.triggerTurn!==!1)t?.deliverAs==="followUp"?this.agent.followUp(s):this.agent.steer(s);else if(t?.triggerTurn){if(this._isEmittingAgentSettled){this._deferredSettledActions.push(async()=>await this.sendCustomMessage(e,t));return}await this._startRun({messageType:"custom",message:s})}else this.isStreaming?this._pendingCustomMessages.push(s):this._appendCustomMessage(s)}_appendCustomMessage(e){this.sessionManager.appendCustomMessageEntry(e.customType,e.content,e.display,e.details),this._refreshFinalizedContext(),this._emit({type:"message_start",message:e}),this._emit({type:"message_end",message:e})}_flushPendingCustomMessages(){if(this._pendingCustomMessages.length===0)return;const e=this._pendingCustomMessages;this._pendingCustomMessages=[];for(const t of e)this._appendCustomMessage(t)}async sendUserMessage(e,t){let s,n;if(typeof e=="string")s=e;else{const o=[];n=[];for(const i of e)i.type==="text"?o.push(i.text):n.push(i);s=o.join(`
14
- `),n.length===0&&(n=void 0)}await this.prompt(s,{expandPromptTemplates:t?.expandPromptTemplates??!1,streamingBehavior:t?.deliverAs,images:n,source:"extension"})}clearQueue(){const e=[...this._steeringMessages],t=[...this._followUpMessages];return this._steeringMessages=[],this._followUpMessages=[],this.agent.clearAllQueues(),this._emitQueueUpdate(),{steering:e,followUp:t}}get pendingMessageCount(){return this._steeringMessages.length+this._followUpMessages.length}getSteeringMessages(){return this._steeringMessages}getFollowUpMessages(){return this._followUpMessages}get resourceLoader(){return this._resourceLoader}async abort(){this._promptAbortGeneration++,this._preparingRun?.cancellable?this._releasePreparingRun():this._isAgentRunActive&&(this._agentRunAbortRequested=!0),this.abortRetry(),this.abortCompaction(),this.abortBranchSummary(),this._isBeforeSettle&&(this._abortDuringBeforeSettle=!0),this.agent.abort(),await this.waitForIdle()}async waitForIdle(){this.isIdle||await this._getIdleWaitPromise()}async emitProviderAuthenticated(e,t){await this._extensionRunner.emit({type:"provider_authenticated",providerId:e,authType:t})}async _emitModelSelect(e,t,s){I(t,e)||await this._extensionRunner.emit({type:"model_select",model:e,previousModel:t,source:s})}async _reconcileDesiredModel(){const e=this._desiredModel;if(this._desiredModel=void 0,e){const s=this.model;if(s&&s.provider===e.provider&&s.id===e.modelId)return;const n=this._modelRuntime.getModel(e.provider,e.modelId);if(n&&this._modelRuntime.hasConfiguredAuth(n.provider)){await this.setModel(n);return}}if(!Ve(this.model))return;try{await this._modelRuntime.refresh({allowNetwork:!1})}catch{}const t=Ke([...this._modelRuntime.getAvailableSnapshot()]);if(t)try{await this.setModel(t)}catch{}}async setModel(e,t={}){if(!await this._modelRuntime.checkAuth(e.provider))throw new Error(`No API key for ${e.provider}/${e.id}`);const s=this.model,n=this._getThinkingLevelForModelSwitch(e);this.agent.state.model=e,this.sessionManager.appendModelChange(e.provider,e.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(e.provider,e.id),this._addPersistedDefaultToNonEmptyScope(e)),this.setThinkingLevel(n),await this._emitModelSelect(e,s,"set")}_addPersistedDefaultToNonEmptyScope(e){if(this._scopedModels.length===0||this._scopedModels.some(n=>I(n.model,e)))return;this._scopedModels=[...this._scopedModels,{model:e}];const t=this.settingsManager.getEnabledModels();if(!t?.length)return;const s=`${e.provider}/${e.id}`;t.some(n=>n.toLowerCase()===s.toLowerCase())||this.settingsManager.setEnabledModels([...t,s])}async cycleModel(e="forward",t={}){return this._scopedModels.length>0?this._cycleScopedModel(e,t):this._cycleAvailableModel(e,t)}async _cycleScopedModel(e,t){const s=new Set(this._modelRuntime.getAvailableSnapshot().map(m=>`${m.provider}\0${m.id}`)),n=this._scopedModels.filter(m=>s.has(`${m.model.provider}\0${m.model.id}`));if(n.length<=1)return;const o=this.model;let i=n.findIndex(m=>I(m.model,o));i===-1&&(i=0);const r=n.length,a=e==="forward"?(i+1)%r:(i-1+r)%r,l=n[a],c=this._getThinkingLevelForModelSwitch(l.model,l.thinkingLevel);return this.agent.state.model=l.model,this.sessionManager.appendModelChange(l.model.provider,l.model.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(l.model.provider,l.model.id),this._addPersistedDefaultToNonEmptyScope(l.model)),this.setThinkingLevel(c),await this._emitModelSelect(l.model,o,"cycle"),{model:l.model,thinkingLevel:this.thinkingLevel,isScoped:!0}}async _cycleAvailableModel(e,t){const s=this._modelRuntime.getAvailableSnapshot();if(s.length<=1)return;const n=this.model;let o=s.findIndex(c=>I(c,n));o===-1&&(o=0);const i=s.length,r=e==="forward"?(o+1)%i:(o-1+i)%i,a=s[r],l=this._getThinkingLevelForModelSwitch(a);return this.agent.state.model=a,this.sessionManager.appendModelChange(a.provider,a.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(a.provider,a.id),this._addPersistedDefaultToNonEmptyScope(a)),this.setThinkingLevel(l),await this._emitModelSelect(a,n,"cycle"),{model:a,thinkingLevel:this.thinkingLevel,isScoped:!1}}setThinkingLevel(e,t={}){const s=this.getAvailableThinkingLevels(),n=s.includes(e)?e:this._clampThinkingLevel(e,s),o=this.agent.state.thinkingLevel,i=n!==o;this.agent.state.thinkingLevel=n,t.persist&&this.settingsManager.setDefaultThinkingLevel(e),i&&(this.sessionManager.appendThinkingLevelChange(n),this._emit({type:"thinking_level_changed",level:n}),this._extensionRunner.emit({type:"thinking_level_select",level:n,previousLevel:o}))}cycleThinkingLevel(e={}){if(!this.supportsThinking())return;const t=this.getAvailableThinkingLevels(),n=(t.indexOf(this.thinkingLevel)+1)%t.length,o=t[n];return this.setThinkingLevel(o,e),o}getAvailableThinkingLevels(){return this.model?fe(this.model):[...je]}supportsThinking(){return!!this.model?.reasoning}getThinkingLevelForModel(e){return z(e,this._getThinkingLevelForModelSwitch(e))}_getThinkingLevelForModelSwitch(e,t){if(t!==void 0)return t;if(e){const s=this.settingsManager.getModelThinkingLevel(e.provider,e.id);if(s!==void 0)return s}return this.settingsManager.getDefaultThinkingLevel()??this.thinkingLevel??We}_clampThinkingLevel(e,t){return this.model?z(this.model,e):"off"}syncQueueModesFromSettings(){this.agent.steeringMode=this.settingsManager.getSteeringMode(),this.agent.followUpMode=this.settingsManager.getFollowUpMode()}setSteeringMode(e){this.agent.steeringMode=e,this.settingsManager.setSteeringMode(e)}setFollowUpMode(e){this.agent.followUpMode=e,this.settingsManager.setFollowUpMode(e)}async _runDefaultCompaction(e,t,s,n,o){const i=this.settingsManager.getCompactionSummaryModel();let r=t;if(i){const l=this._modelRuntime.getModel(i.provider,i.modelId);if(!l)throw new Error(`compaction.summaryModel "${i.provider}/${i.modelId}" is not an available model`);r=l}const a=await this._getSummarizationRequestAuth(r,n);return Ne(e,a.model,a.apiKey,a.headers,s,n,a.thinkingLevel,this.agent.streamFunction,a.env,this.settingsManager.getRetrySettings(),this._summarizationRetryCallbacks({source:"compaction",reason:o}),void 0)}_clearManualCompactionState(){this._compactionAbortController=void 0,this._resolveIdleWaitIfIdle()}async compact(e){await this.abort(),this._compactionAbortController=new AbortController,this._emit({type:"compaction_start",reason:"manual"});let t=!1,s=!1;try{const n=this.model;if(!n)throw new Error(H());const o=this.settingsManager.getCompactionSettings(n),i=this.sessionManager.getBranch(),r=Q(i,o);if(!r)throw i[i.length-1]?.type==="compaction"?new Error("Already compacted"):new Error("Nothing to compact (session too small)");let a;if(this._extensionRunner.hasHandlers("session_before_compact")){const y=await this._extensionRunner.emit({type:"session_before_compact",preparation:r,branchEntries:i,customInstructions:e,reason:"manual",willRetry:!1,signal:this._compactionAbortController.signal});if(y?.cancel)throw s=!0,new Error("Compaction cancelled");y?.compaction&&(a=y.compaction,t=!0)}let l,c,m,u,d;if(a)l=a.summary,c=a.firstKeptEntryId,m=a.tokensBefore,u=a.usage,d=a.details;else{const y=await this._runDefaultCompaction(r,n,e,this._compactionAbortController.signal,"manual");l=y.summary,c=y.firstKeptEntryId,m=y.tokensBefore,u=y.usage,d=y.details}if(this._compactionAbortController.signal.aborted)throw new Error("Compaction cancelled");this.sessionManager.appendCompaction(l,c,m,d,t,u);const g=this.sessionManager.getEntries();this._refreshFinalizedContext();const f=ie(this.sessionManager.buildSessionProjection().messages),p=g.find(y=>y.type==="compaction"&&y.summary===l);this._extensionRunner&&p&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:p,fromExtension:t,reason:"manual",willRetry:!1});const M={summary:l,firstKeptEntryId:c,tokensBefore:m,estimatedTokensAfter:f,usage:u,details:d};return this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:M,aborted:!1,willRetry:!1}),M}catch(n){const o=n instanceof Error?n.message:String(n),i=this._compactionAbortController.signal.aborted||s,r=i?void 0:`Compaction failed: ${o}`;throw this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:void 0,aborted:i,willRetry:!1,errorMessage:r}),await this._emitSessionCompactFailed({reason:"manual",errorMessage:r,aborted:i,willRetry:!1,fromExtension:t}),n}finally{this._clearManualCompactionState()}}abortCompaction(){this._compactionAbortController?.abort(),this._autoCompactionAbortController?.abort()}abortBranchSummary(){this._branchSummaryAbortController?.abort()}async _checkCompaction(e,t=!0,s=[]){const n=this.settingsManager.getCompactionSettings(this.model);if(!n.enabled||t&&e.stopReason==="aborted")return!1;const o=this._modelForMessage(e),i=o!==void 0,r=(o??this.model)?.contextWindow??0,a=this.sessionManager.getBranch(),l=Z(a);let c=!1;if(l!==null){const _=this._findPersistedMessageEntryId(e),R=_?a.findIndex(A=>A.id===_):-1;c=R>=0?R<a.indexOf(l):e.timestamp<=new Date(l.timestamp).getTime()}if(c)return!1;const m=this.sessionManager.buildSessionProjection(),u=this._findPersistedMessageEntryId(e),d=u===void 0||m.entries.some(_=>_.sourceEntry.id===u&&_.messages.some(R=>R.role==="assistant")),g=this.sessionManager.getBranch(),f=u?g.findIndex(_=>_.id===u):-1,p=f>=0?g.slice(f+1):[],M=p.some(_=>_.type==="context_edit"),y=p.filter(_=>_.type==="context_edit"&&_.targetId===u).at(-1),x=u===void 0||!p.some(_=>_.type==="compaction")&&y?.replacement!==null,v=d&&!M,b=e.stopReason==="error"&&B(e),w=i&&(b&&x||v&&B(e,r)),re=i&&d&&_e(e,this.settingsManager.getOutputTokenLimit(o.maxTokens),o.contextWindow);if(w||re){const _=e.stopReason!=="stop";if(!_)return await this._runAutoCompaction("overflow",!1);if(this._overflowRecoveryAttempted){const A=w?"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.":"Truncated response recovery failed after one compact-and-retry attempt.";return this._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!1,errorMessage:A}),await this._emitSessionCompactFailed({reason:"overflow",errorMessage:A,aborted:!1,willRetry:!1,fromExtension:!1}),!1}this._overflowRecoveryAttempted=!0,this._omitRecoveryAttempt(e,s);const R=await this._runAutoCompaction("overflow",_);return R&&(this._failedResponse=e),R}let E;const U=m,ae=U.entries.some(_=>_.sourceEntry.type==="context_edit"),W=e.usage?$(e.usage):0;if(ae)E=S(U,g).tokens;else if(e.stopReason==="error"||W===0){const _=this.agent.state.messages,R=Be(_);if(R.lastUsageIndex!==null){const A=_[R.lastUsageIndex];if(l&&A.role==="assistant"&&A.timestamp<=new Date(l.timestamp).getTime())return!1}E=R.tokens}else E=W;const j=this._compactionBaseTokens();return V(E,r,n,j)?await this._runAutoCompaction("threshold",!1,G(r,n,j)):!1}async _runAutoCompaction(e,t,s){const n=this.model,o=this.settingsManager.getCompactionSettings(n);if(e==="threshold"&&s!==void 0&&this._pruneToolOutputsInsteadOfCompacting(s))return!1;let i,r=!1,a=!1,l=!1;try{if(!n)return!1;const c=this.sessionManager.getBranch(),m=Q(c,o);if(!m)return!1;i=new AbortController,this._autoCompactionAbortController=i,r=!0,this._emit({type:"compaction_start",reason:e}),i.signal.throwIfAborted();let u;if(this._extensionRunner.hasHandlers("session_before_compact")){const w=await this._extensionRunner.emit({type:"session_before_compact",preparation:m,branchEntries:c,customInstructions:void 0,reason:e,willRetry:t,signal:i.signal});if(w?.cancel)throw l=!0,new Error("Compaction cancelled");w?.compaction&&(u=w.compaction,a=!0)}i.signal.throwIfAborted();let d,g,f,p,M;if(u)d=u.summary,g=u.firstKeptEntryId,f=u.tokensBefore,p=u.usage,M=u.details;else{const w=await this._runDefaultCompaction(m,n,void 0,i.signal,e);d=w.summary,g=w.firstKeptEntryId,f=w.tokensBefore,p=w.usage,M=w.details}i.signal.throwIfAborted(),this.sessionManager.appendCompaction(d,g,f,M,a,p);const y=this.sessionManager.getEntries();this._refreshFinalizedContext();const x=ie(this.sessionManager.buildSessionProjection().messages),v=y.find(w=>w.type==="compaction"&&w.summary===d);this._extensionRunner&&v&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:v,fromExtension:a,reason:e,willRetry:t});const b={summary:d,firstKeptEntryId:g,tokensBefore:f,estimatedTokensAfter:x,usage:p,details:M};return this._emit({type:"compaction_end",reason:e,result:b,aborted:!1,willRetry:t}),t?!0:this.agent.hasQueuedMessages()}catch(c){const m=c instanceof Error?c.message:"compaction failed",u=i?.signal.aborted===!0||l;if(r){const d=u?void 0:e==="overflow"?`Context overflow recovery failed: ${m}`:`Auto-compaction failed: ${m}`;this._emit({type:"compaction_end",reason:e,result:void 0,aborted:u,willRetry:!1,errorMessage:d}),await this._emitSessionCompactFailed({reason:e,errorMessage:d,aborted:u,willRetry:!1,fromExtension:a})}return!1}finally{this._autoCompactionAbortController===i&&(this._autoCompactionAbortController=void 0),this._resolveIdleWaitIfIdle()}}setAutoCompactionEnabled(e){this.settingsManager.setCompactionEnabled(e)}get autoCompactionEnabled(){return this.settingsManager.getCompactionEnabled()}async bindExtensions(e){e.uiContext!==void 0&&(this._extensionUIContext=e.uiContext),e.mode!==void 0&&(this._extensionMode=e.mode),e.commandContextActions!==void 0&&(this._extensionCommandContextActions=e.commandContextActions),e.abortHandler!==void 0&&(this._extensionAbortHandler=e.abortHandler),e.shutdownHandler!==void 0&&(this._extensionShutdownHandler=e.shutdownHandler),e.onError!==void 0&&(this._extensionErrorListener=e.onError),this._applyExtensionBindings(this._extensionRunner),await this._extensionRunner.emit(this._sessionStartEvent),await this._reconcileDesiredModel(),this._extensionRunner.reportUnhandledMcpServers(),await this.extendResourcesFromExtensions(this._sessionStartEvent.reason==="reload"?"reload":"startup")}async extendResourcesFromExtensions(e){if(!this._extensionRunner.hasHandlers("resources_discover"))return;const{skillPaths:t,promptPaths:s,themePaths:n}=await this._extensionRunner.emitResourcesDiscover(this._cwd,e);if(t.length===0&&s.length===0&&n.length===0)return;const o={skillPaths:this.buildExtensionResourcePaths(t),promptPaths:this.buildExtensionResourcePaths(s),themePaths:this.buildExtensionResourcePaths(n)};this._resourceLoader.extendResources(o),this._rebuildSystemPrompt(this.getActiveToolNames())}buildExtensionResourcePaths(e){return e.map(t=>{const s=this.getExtensionSourceLabel(t.extensionPath),n=se(t.extensionPath)?void 0:ue(t.extensionPath);return{path:t.path,metadata:{source:s,scope:"temporary",origin:"top-level",baseDir:n}}})}getExtensionSourceLabel(e){return se(e)?`extension:${e.replace(/[<>]/g,"")}`:`extension:${he(e).replace(/\.(ts|js)$/,"")}`}_applyExtensionBindings(e){e.setUIContext(this._extensionUIContext,this._extensionMode),e.bindCommandContext(this._extensionCommandContextActions),this._extensionErrorUnsubscriber?.(),this._extensionErrorUnsubscriber=this._extensionErrorListener?e.onError(this._extensionErrorListener):void 0}_refreshCurrentModelFromRegistry(){const e=this.model;if(!e)return;const t=this._modelRuntime.getModel(e.provider,e.id);!t||t===e||(this.agent.state.model=t)}_bindExtensionCore(e){const t=h(()=>{const s=e.getRegisteredCommands().map(i=>({name:i.invocationName,description:i.description,source:"extension",sourceInfo:i.sourceInfo})),n=this.promptTemplates.map(i=>({name:i.name,description:i.description,source:"prompt",sourceInfo:i.sourceInfo})),o=this._resourceLoader.getSkills().skills.map(i=>({name:`skill:${i.name}`,description:i.description,source:"skill",sourceInfo:i.sourceInfo}));return[...s,...n,...o]},"getCommands");e.bindCore({sendMessage:h((s,n)=>{this.sendCustomMessage(s,n).catch(o=>{e.emitError({extensionPath:"<runtime>",event:"send_message",error:o instanceof Error?o.message:String(o)})})},"sendMessage"),sendUserMessage:h((s,n)=>{this.sendUserMessage(s,n).catch(o=>{e.emitError({extensionPath:"<runtime>",event:"send_user_message",error:o instanceof Error?o.message:String(o)})})},"sendUserMessage"),appendEntry:h((s,n)=>{const o=this.sessionManager.appendCustomEntry(s,n),i=this.sessionManager.getEntry(o);i&&this._emit({type:"entry_appended",entry:i})},"appendEntry"),appendUsage:h((s,n)=>{const o=this.sessionManager.appendUsage(n.kind,n.provider??"",n.model??"",s,n.note);this._emit({type:"entry_appended",entry:o})},"appendUsage"),emitHostEvent:h((s,n)=>{this._emit({type:"extension_event",name:s,data:n??null})},"emitHostEvent"),setSessionName:h(s=>{this.setSessionName(s)},"setSessionName"),getSessionName:h(()=>this.sessionManager.getSessionName(),"getSessionName"),setLabel:h((s,n)=>{this.sessionManager.appendLabelChange(s,n)},"setLabel"),getActiveTools:h(()=>this.getActiveToolNames(),"getActiveTools"),getAllTools:h(()=>this.getAllTools(),"getAllTools"),getSettings:h(()=>this.settingsManager.getSettings(),"getSettings"),setActiveTools:h(s=>this.setActiveToolsByName(s),"setActiveTools"),isToolAllowed:h(s=>this.isToolAllowed(s),"isToolAllowed"),getToolAllowlist:h(()=>this.getToolAllowlist(),"getToolAllowlist"),getToolDenylist:h(()=>this.getToolDenylist(),"getToolDenylist"),refreshTools:h(()=>this._refreshToolRegistry(),"refreshTools"),getCommands:t,setModel:h(async s=>this._modelRuntime.hasConfiguredAuth(s.provider)?(await this.setModel(s),!0):!1,"setModel"),getThinkingLevel:h(()=>this.thinkingLevel,"getThinkingLevel"),setThinkingLevel:h(s=>this.setThinkingLevel(s),"setThinkingLevel")},{getModel:h(()=>this.model,"getModel"),getScopedModels:h(()=>this._scopedModels,"getScopedModels"),isIdle:h(()=>this.isIdle,"isIdle"),isProjectTrusted:h(()=>this.settingsManager.isProjectTrusted(),"isProjectTrusted"),getSignal:h(()=>this.agent.signal,"getSignal"),abort:h(()=>{if(this._extensionAbortHandler){this._extensionAbortHandler();return}this.abort()},"abort"),hasPendingMessages:h(()=>this.pendingMessageCount>0,"hasPendingMessages"),shutdown:h(()=>{this._extensionShutdownHandler?.()},"shutdown"),getContextUsage:h(()=>this.getContextUsage(),"getContextUsage"),compact:h(s=>{(async()=>{try{const n=await this.compact(s?.customInstructions);s?.onComplete?.(n)}catch(n){const o=n instanceof Error?n:new Error(String(n));s?.onError?.(o)}})()},"compact"),getSystemPrompt:h(()=>this.systemPrompt,"getSystemPrompt"),getSystemPromptOptions:h(()=>this._baseSystemPromptOptions,"getSystemPromptOptions"),executeTool:h((s,n,o,i)=>this._executeNestedToolCall(s,n,o,i),"executeTool"),getCallableTools:h(()=>this._getCallableTools(),"getCallableTools")},{registerProvider:h((s,n)=>{this._modelRuntime.registerProvider(s,n),this._refreshCurrentModelFromRegistry()},"registerProvider"),registerNativeProvider:h(s=>{this._modelRuntime.registerNativeProvider(s),this._refreshCurrentModelFromRegistry()},"registerNativeProvider"),unregisterProvider:h(s=>{this._modelRuntime.unregisterProvider(s),this._refreshCurrentModelFromRegistry()},"unregisterProvider"),registerVirtualModel:h(s=>{this._modelRuntime.registerVirtualModel(s),this._refreshCurrentModelFromRegistry()},"registerVirtualModel"),unregisterVirtualModel:h((s,n)=>{this._modelRuntime.unregisterVirtualModel(s,n),this._refreshCurrentModelFromRegistry()},"unregisterVirtualModel")})}_refreshToolRegistry(e){const t=new Set([...this._toolRegistry.keys()].filter(d=>this._isActivatedOnRegistration(d))),s=this.getActiveToolNames(),n=this._allowedTools,i=[...this._extensionRunner.getAllRegisteredTools(),...this._customTools.map(d=>({definition:d,sourceInfo:F(`<sdk:${d.name}>`,{source:"sdk"})}))].filter(d=>this._isAllowedTool(d.definition.name)),r=new Map(Array.from(this._baseToolDefinitions.entries()).filter(([d])=>this._isAllowedTool(d)).map(([d,g])=>[d,{definition:g,sourceInfo:F(`${te}${d}`,{source:"builtin"})}]));for(const d of i)r.set(d.definition.name,{definition:d.definition,sourceInfo:d.sourceInfo});this._toolDefinitions=r,this._toolPromptSnippets=new Map(Array.from(r.values()).map(({definition:d})=>{const g=this._normalizePromptSnippet(d.promptSnippet);return g?[d.name,g]:void 0}).filter(d=>d!==void 0)),this._toolPromptGuidelines=new Map(Array.from(r.values()).map(({definition:d})=>{const g=this._normalizePromptGuidelines(d.promptGuidelines);return g.length>0?[d.name,g]:void 0}).filter(d=>d!==void 0));const a=this._extensionRunner,l=K(i,a),c=K(Array.from(this._baseToolDefinitions.values()).filter(d=>this._isAllowedTool(d.name)).map(d=>({definition:d,sourceInfo:F(`${te}${d.name}`,{source:"builtin"})})),a),m=new Map(c.map(d=>[d.name,d]));for(const d of l)m.set(d.name,d);this._toolRegistry=m;const u=(e?.activeToolNames?[...e.activeToolNames]:[...s]).filter(d=>this._isAllowedTool(d));if(n)for(const d of this._toolRegistry.keys())n(d)&&this._isDeclarable(d)&&u.push(d);else if(e?.includeAllExtensionTools)for(const d of l)this._isActivatedOnRegistration(d.name)&&u.push(d.name);else if(!e?.activeToolNames)for(const d of this._toolRegistry.keys())!t.has(d)&&this._isActivatedOnRegistration(d)&&u.push(d);u.push(...this._pendingToolNames),this._setActiveTools([...new Set(u)])}_isDeclarable(e){const t=this._getToolExposure(e);return t==="direct"||t==="model-only"}_isActivatedOnRegistration(e){return this._isDeclarable(e)&&this._toolDefinitions.get(e)?.definition.defaultActive!==!1}getScratchDir(){return this._sandboxScratch??=at(),this._sandboxScratch}_buildRuntime(e){const t=this.settingsManager.getImageAutoResize(),s=this.settingsManager.getShellCommandPrefix(),n=this.settingsManager.getShellPath();we(this.settingsManager.getShellEnvironmentPolicy());const o=ot({settings:this.settingsManager.getSandboxSettingsSources(),override:this._sandboxOptions,defaultLevel:this._sandboxOptions.defaultLevel??"off"});this._releaseOutputFileDirectory??=ve(()=>this.getScratchDir());const i=new lt({policy:o,onEscalation:this._sandboxOptions.onEscalation,onEvent:h(u=>this._emit(u),"onEvent"),scratchDir:h(()=>this.getScratchDir(),"scratchDir")}),r=this._shellSandbox;this._shellSandbox=i,r?.dispose(),dt(i),process.env[it]=rt(o),this._permissionRules=Xe(this.settingsManager.getPermissionRuleSources()),this._readGuard=Ze({cwd:this._cwd,rules:this._permissionRules,...o.level!=="off"?{protectedReads:nt(o,this._cwd).denyRead}:{}}),st(this._readGuard);const a=this._baseToolsOverride?Object.fromEntries(Object.entries(this._baseToolsOverride).map(([u,d])=>[u,xt(d)])):_t(this._cwd,{read:{autoResizeImages:t},bash:{commandPrefix:s,shellPath:n,sandbox:i,background:this._backgroundProcesses}});this._baseToolDefinitions=new Map(Object.entries(a).map(([u,d])=>[u,d])),this._baseToolsOverride||this._baseToolDefinitions.set("process",yt(this._cwd,this._backgroundProcesses,{sandboxed:i.active}));const l=this._resourceLoader.getExtensions();if(e.flagValues)for(const[u,d]of e.flagValues)l.runtime.flagValues.set(u,d);this._extensionRunner=new $e(l.extensions,l.runtime,this._cwd,this.sessionManager,new Qe(this._modelRuntime)),this._extensionRunnerRef&&(this._extensionRunnerRef.current=this._extensionRunner),this._bindExtensionCore(this._extensionRunner),this._applyExtensionBindings(this._extensionRunner);const c=this._baseToolsOverride?Object.keys(this._baseToolsOverride):["read","bash","edit","write"],m=e.activeToolNames??c;this._refreshToolRegistry({activeToolNames:m,includeAllExtensionTools:e.includeAllExtensionTools})}async reload(e){const t=this._extensionRunner,s=t.getFlagValues();await Ge(t,{type:"session_shutdown",reason:"reload"}),t.invalidate();const n=h(()=>this._usesDefaultTools?ee(this.settingsManager.getDefaultTools()??ut,this._defaultToolModifiers):[],"getDefaultTools"),o=new Set(n());await this.settingsManager.reload(),this.syncQueueModesFromSettings(),xe(),await this._resourceLoader.reload();const i=n().filter(a=>!o.has(a));for(const a of this.getActiveToolNames())this._pendingToolNames.add(a);this._buildRuntime({activeToolNames:[...this.getActiveToolNames(),...i],flagValues:s,includeAllExtensionTools:!0}),(this._extensionUIContext||this._extensionCommandContextActions||this._extensionShutdownHandler||this._extensionErrorListener)&&(await e?.beforeSessionStart?.(),await this._extensionRunner.emit({type:"session_start",reason:"reload"}),this._extensionRunner.reportUnhandledMcpServers(),await this.extendResourcesFromExtensions("reload"))}_isRetryableError(e){return B(e,(this._modelForMessage(e)??this.model)?.contextWindow??0)?!1:ye(e)}_summarizationRetryCallbacks(e){return{onRetryScheduled:h((t,s,n,o)=>{this._emit({type:"summarization_retry_scheduled",attempt:t,maxAttempts:s,delayMs:n,errorMessage:o})},"onRetryScheduled"),onRetryAttemptStart:h(()=>{this._emit({type:"summarization_retry_attempt_start",...e})},"onRetryAttemptStart"),onRetryFinished:h(()=>{this._emit({type:"summarization_retry_finished"})},"onRetryFinished")}}_finishCancelledRetry(){if(this._retryAttempt===0)return;const e=this._retryAttempt;this._retryAttempt=0,this._emit({type:"auto_retry_end",success:!1,attempt:e,finalError:"Retry cancelled"})}async _prepareRetry(e){const t=this.settingsManager.getRetrySettings();if(!t.enabled)return!1;if(this._retryAttempt++,this._retryAttempt>t.maxRetries)return this._retryAttempt--,!1;const s=ge(t,this._retryAttempt);this._emit({type:"auto_retry_start",attempt:this._retryAttempt,maxAttempts:t.maxRetries,delayMs:s,errorMessage:e.errorMessage||"Unknown error"}),this._omitRecoveryAttempt(e),this._retryAbortController=new AbortController;try{await Se(s,this._retryAbortController.signal)}catch{return this._finishCancelledRetry(),!1}finally{this._retryAbortController=void 0}return!0}abortRetry(){this._retryAbortController?.abort()}get isRetrying(){return this._retryAbortController!==void 0}get autoRetryEnabled(){return this.settingsManager.getRetryEnabled()}setAutoRetryEnabled(e){this.settingsManager.setRetryEnabled(e)}async executeBash(e,t,s){const n=new AbortController;this._bashAbortControllers.add(n);const o=this.settingsManager.getShellCommandPrefix(),i=this.settingsManager.getShellPath(),r=o?`${o}
15
- ${e}`:e;try{const a=await Ie(r,this.sessionManager.getCwd(),s?.operations??ft({shellPath:i}),{onChunk:h(l=>{t?.(l),this._emit({type:"bash_execution_update",id:s?.id,delta:l})},"onChunk"),signal:n.signal});return this.recordBashResult(e,a,s),a}finally{this._bashAbortControllers.delete(n)}}recordBashResult(e,t,s){const n={role:"bashExecution",command:e,output:t.output,exitCode:t.exitCode,cancelled:t.cancelled,truncated:t.truncated,fullOutputPath:t.fullOutputPath,timestamp:Date.now(),excludeFromContext:s?.excludeFromContext};this.isStreaming?this._pendingBashMessages.push(n):(this.sessionManager.appendMessage(n),this._refreshFinalizedContext())}abortBash(){for(const e of[...this._bashAbortControllers])e.abort()}get isBashRunning(){return this._bashAbortControllers.size>0}get hasPendingBashMessages(){return this._pendingBashMessages.length>0}_flushPendingBashMessages(){if(this._pendingBashMessages.length!==0){for(const e of this._pendingBashMessages)this.sessionManager.appendMessage(e);this._pendingBashMessages=[],this._refreshFinalizedContext()}}setSessionName(e){this.sessionManager.appendSessionInfo(e);const t={type:"session_info_changed",name:this.sessionManager.getSessionName()};this._emit(t),this._extensionRunner.emit(t)}async navigateTree(e,t={}){if(this.isStreaming)throw new Error("Wait for the current response to finish before navigating the session tree.");if(this.isCompacting)throw new Error("Wait for the current compaction or tree navigation to finish before navigating the session tree.");const s=this.sessionManager.getLeafId();if(e===s)return{cancelled:!1};if(t.summarize&&!this.model)throw new Error("No model available for summarization");const n=this.sessionManager.getEntry(e);if(!n)throw new Error(`Entry ${e} not found`);const{entries:o,commonAncestorId:i}=Le(this.sessionManager,s,e);let r=t.customInstructions,a=t.replaceInstructions,l=t.label;const c={targetId:e,oldLeafId:s,commonAncestorId:i,entriesToSummarize:o,userWantsSummary:t.summarize??!1,customInstructions:r,replaceInstructions:a,label:l};this._branchSummaryAbortController=new AbortController;try{let m,u=!1;if(this._extensionRunner.hasHandlers("session_before_tree")){const x=await this._extensionRunner.emit({type:"session_before_tree",preparation:c,signal:this._branchSummaryAbortController.signal});if(x?.cancel)return{cancelled:!0};x?.summary&&t.summarize&&(m=x.summary,u=!0),x?.customInstructions!==void 0&&(r=x.customInstructions),x?.replaceInstructions!==void 0&&(a=x.replaceInstructions),x?.label!==void 0&&(l=x.label)}let d,g,f;if(t.summarize&&o.length>0&&!m){const x=this._branchSummaryAbortController.signal,v=this.settingsManager.getBranchSummarySettings(),b=await De(o,{...await this._getSummarizationRequestAuth(this.model,x),signal:x,customInstructions:r,replaceInstructions:a,reserveTokens:v.reserveTokens,streamFn:this.agent.streamFunction,retry:this.settingsManager.getRetrySettings(),callbacks:this._summarizationRetryCallbacks({source:"branchSummary"})});if(b.aborted)return{cancelled:!0,aborted:!0};if(b.error)throw new Error(b.error);d=b.summary,f=b.usage,g={readFiles:b.readFiles||[],modifiedFiles:b.modifiedFiles||[]}}else m&&(d=m.summary,g=m.details,f=m.usage);let p,M;n.type==="message"&&n.message.role==="user"?(p=n.parentId,M=P(n.message.content,"")):n.type==="custom_message"?(p=n.parentId,M=P(n.content,"")):p=e;let y;if(d){const x=this.sessionManager.branchWithSummary(p,d,g,u,f);y=this.sessionManager.getEntry(x),l&&this.sessionManager.appendLabelChange(x,l)}else p===null?this.sessionManager.resetLeaf():this.sessionManager.branch(p);return l&&!d&&this.sessionManager.appendLabelChange(e,l),this._refreshFinalizedContext(),this._restoreToolsFromTranscript(),await this._extensionRunner.emit({type:"session_tree",newLeafId:this.sessionManager.getLeafId(),oldLeafId:s,summaryEntry:y,fromExtension:d?u:void 0}),{editorText:M,cancelled:!1,summaryEntry:y}}finally{this._branchSummaryAbortController=void 0,this._resolveIdleWaitIfIdle()}}getUserMessagesForForking(){const e=this.sessionManager.getEntries(),t=[];for(const s of e){if(s.type!=="message"||s.message.role!=="user")continue;const n=P(s.message.content,"");n&&t.push({entryId:s.id,text:n})}return t}getSessionStats(){let e=0,t=0,s=0,n=0,o=0;const i=wt();for(const r of this.sessionManager.getEntries()){if(r.type==="usage"?L(i,r.usage):(r.type==="branch_summary"||r.type==="compaction")&&r.usage&&L(i,r.usage),r.type!=="message")continue;n++;const a=r.message;if(a.role==="user")e++;else if(a.role==="toolResult")s++,a.usage&&L(i,a.usage);else if(a.role==="assistant"){t++;const l=a;Array.isArray(l.content)&&(o+=l.content.filter(c=>c.type==="toolCall").length),L(i,l.usage)}}return{sessionFile:this.sessionFile,sessionId:this.sessionId,userMessages:e,assistantMessages:t,toolCalls:o,toolResults:s,totalMessages:n,tokens:{input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,total:i.input+i.output+i.cacheRead+i.cacheWrite},cost:i.cost,contextUsage:this.getContextUsage()}}getContextUsage(){const e=this._limitsModel();if(!e)return;const t=e.contextWindow??0;if(t<=0)return;const s=this.sessionManager.buildSessionProjection(),n=this.sessionManager.getBranch(),o=Z(n);if(o){const a=new Set(s.entries.flatMap(m=>m.messages.some(u=>u.role==="assistant"&&u.stopReason!=="aborted"&&u.stopReason!=="error"&&$(u.usage)>0)?[m.sourceEntry.id]:[])),l=n.findIndex(m=>m.id===o.id);if(!n.slice(l+1).some(m=>a.has(m.id)))return{tokens:null,contextWindow:t,percent:null}}const i=S(s,n),r=i.tokens/t*100;return{tokens:i.tokens,contextWindow:t,percent:r}}async exportToHtml(e,t={}){const s=[t.themeName,this.settingsManager.getTheme()].find(o=>o!==void 0&&Re(o)!==void 0),n=He({getToolRenderers:h(o=>this._extensionRunner.resolveToolRenderers(o,()=>this.getToolDefinition(o)),"getToolRenderers"),theme:Te,cwd:this.sessionManager.getCwd()});return await qe(this.sessionManager,this.state,{outputPath:e,themeName:s,toolRenderer:n})}exportToJsonl(e){return ct(this.sessionManager,e)}async summarizeForBugReport(e){const t=this.model;if(!t)throw new Error("No model selected");return ke({...await this._getSummarizationRequestAuth(t,e.signal),messages:this.messages,hint:e.hint,signal:e.signal,streamFn:this.agent.streamFunction,retry:this.settingsManager.getRetrySettings(),sessionId:this.sessionId})}getLastAssistantText(){const e=this.messages.slice().reverse().find(s=>{if(s.role!=="assistant")return!1;const n=s;return!(n.stopReason==="aborted"&&n.content.length===0)});if(!e)return;let t="";for(const s of e.content)s.type==="text"&&(t+=s.text);return t.trim()||void 0}createReplacedSessionContext(){const e=Object.defineProperties({},Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));return e.sendMessage=(t,s)=>this.sendCustomMessage(t,s),e.sendUserMessage=(t,s)=>this.sendUserMessage(t,s),e}hasExtensionHandlers(e){return this._extensionRunner.hasHandlers(e)}get extensionRunner(){return this._extensionRunner}}export{xs as AgentSession,ys as parseSkillBlock};
14
+ `),n.length===0&&(n=void 0)}await this.prompt(s,{expandPromptTemplates:t?.expandPromptTemplates??!1,streamingBehavior:t?.deliverAs,images:n,source:"extension"})}clearQueue(){const e=[...this._steeringMessages],t=[...this._followUpMessages];return this._steeringMessages=[],this._followUpMessages=[],this.agent.clearAllQueues(),this._emitQueueUpdate(),{steering:e,followUp:t}}get pendingMessageCount(){return this._steeringMessages.length+this._followUpMessages.length}getSteeringMessages(){return this._steeringMessages}getFollowUpMessages(){return this._followUpMessages}get resourceLoader(){return this._resourceLoader}async abort(){this._promptAbortGeneration++,this._preparingRun?.cancellable?this._releasePreparingRun():this._isAgentRunActive&&(this._agentRunAbortRequested=!0),this.abortRetry(),this.abortCompaction(),this.abortBranchSummary(),this._isBeforeSettle&&(this._abortDuringBeforeSettle=!0),this.agent.abort(),await this.waitForIdle()}async waitForIdle(){this.isIdle||await this._getIdleWaitPromise()}async emitProviderAuthenticated(e,t){await this._extensionRunner.emit({type:"provider_authenticated",providerId:e,authType:t})}async _emitModelSelect(e,t,s){k(t,e)||await this._extensionRunner.emit({type:"model_select",model:e,previousModel:t,source:s})}async _reconcileDesiredModel(){const e=this._desiredModel;if(this._desiredModel=void 0,e){const s=this.model;if(s&&s.provider===e.provider&&s.id===e.modelId)return;const n=this._modelRuntime.getModel(e.provider,e.modelId);if(n&&this._modelRuntime.hasConfiguredAuth(n.provider)){await this.setModel(n);return}}if(!Ke(this.model))return;try{await this._modelRuntime.refresh({allowNetwork:!1})}catch{}const t=Je([...this._modelRuntime.getAvailableSnapshot()]);if(t)try{await this.setModel(t)}catch{}}async setModel(e,t={}){if(!await this._modelRuntime.checkAuth(e.provider))throw new Error(`No API key for ${e.provider}/${e.id}`);const s=this.model,n=this._getThinkingLevelForModelSwitch(e);this.agent.state.model=e,this.sessionManager.appendModelChange(e.provider,e.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(e.provider,e.id),this._addPersistedDefaultToNonEmptyScope(e)),this.setThinkingLevel(n),await this._emitModelSelect(e,s,"set")}_addPersistedDefaultToNonEmptyScope(e){if(this._scopedModels.length===0||this._scopedModels.some(n=>k(n.model,e)))return;this._scopedModels=[...this._scopedModels,{model:e}];const t=this.settingsManager.getEnabledModels();if(!t?.length)return;const s=`${e.provider}/${e.id}`;t.some(n=>n.toLowerCase()===s.toLowerCase())||this.settingsManager.setEnabledModels([...t,s])}async cycleModel(e="forward",t={}){return this._scopedModels.length>0?this._cycleScopedModel(e,t):this._cycleAvailableModel(e,t)}async _cycleScopedModel(e,t){const s=new Set(this._modelRuntime.getAvailableSnapshot().map(m=>`${m.provider}\0${m.id}`)),n=this._scopedModels.filter(m=>s.has(`${m.model.provider}\0${m.model.id}`));if(n.length<=1)return;const o=this.model;let i=n.findIndex(m=>k(m.model,o));i===-1&&(i=0);const r=n.length,a=e==="forward"?(i+1)%r:(i-1+r)%r,l=n[a],c=this._getThinkingLevelForModelSwitch(l.model,l.thinkingLevel);return this.agent.state.model=l.model,this.sessionManager.appendModelChange(l.model.provider,l.model.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(l.model.provider,l.model.id),this._addPersistedDefaultToNonEmptyScope(l.model)),this.setThinkingLevel(c),await this._emitModelSelect(l.model,o,"cycle"),{model:l.model,thinkingLevel:this.thinkingLevel,isScoped:!0}}async _cycleAvailableModel(e,t){const s=this._modelRuntime.getAvailableSnapshot();if(s.length<=1)return;const n=this.model;let o=s.findIndex(c=>k(c,n));o===-1&&(o=0);const i=s.length,r=e==="forward"?(o+1)%i:(o-1+i)%i,a=s[r],l=this._getThinkingLevelForModelSwitch(a);return this.agent.state.model=a,this.sessionManager.appendModelChange(a.provider,a.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(a.provider,a.id),this._addPersistedDefaultToNonEmptyScope(a)),this.setThinkingLevel(l),await this._emitModelSelect(a,n,"cycle"),{model:a,thinkingLevel:this.thinkingLevel,isScoped:!1}}setThinkingLevel(e,t={}){const s=this.getAvailableThinkingLevels(),n=s.includes(e)?e:this._clampThinkingLevel(e,s),o=this.agent.state.thinkingLevel,i=n!==o;this.agent.state.thinkingLevel=n,t.persist&&this.settingsManager.setDefaultThinkingLevel(e),i&&(this.sessionManager.appendThinkingLevelChange(n),this._emit({type:"thinking_level_changed",level:n}),this._extensionRunner.emit({type:"thinking_level_select",level:n,previousLevel:o}))}cycleThinkingLevel(e={}){if(!this.supportsThinking())return;const t=this.getAvailableThinkingLevels(),n=(t.indexOf(this.thinkingLevel)+1)%t.length,o=t[n];return this.setThinkingLevel(o,e),o}getAvailableThinkingLevels(){return this.model?_e(this.model):[...je]}supportsThinking(){return!!this.model?.reasoning}getThinkingLevelForModel(e){return j(e,this._getThinkingLevelForModelSwitch(e))}_getThinkingLevelForModelSwitch(e,t){if(t!==void 0)return t;if(e){const s=this.settingsManager.getModelThinkingLevel(e.provider,e.id);if(s!==void 0)return s}return this.settingsManager.getDefaultThinkingLevel()??this.thinkingLevel??qe}_clampThinkingLevel(e,t){return this.model?j(this.model,e):"off"}syncQueueModesFromSettings(){this.agent.steeringMode=this.settingsManager.getSteeringMode(),this.agent.followUpMode=this.settingsManager.getFollowUpMode()}setSteeringMode(e){this.agent.steeringMode=e,this.settingsManager.setSteeringMode(e)}setFollowUpMode(e){this.agent.followUpMode=e,this.settingsManager.setFollowUpMode(e)}async _runDefaultCompaction(e,t,s,n,o){const i=this.settingsManager.getCompactionSummaryModel();let r=t;if(i){const l=this._modelRuntime.getModel(i.provider,i.modelId);if(!l)throw new Error(`compaction.summaryModel "${i.provider}/${i.modelId}" is not an available model`);r=l}const a=await this._getSummarizationRequestAuth(r,n);return Ne(e,a.model,a.apiKey,a.headers,s,n,a.thinkingLevel,this.agent.streamFunction,a.env,this.settingsManager.getRetrySettings(),this._summarizationRetryCallbacks({source:"compaction",reason:o}),void 0)}_clearManualCompactionState(){this._compactionAbortController=void 0,this._resolveIdleWaitIfIdle()}async compact(e){await this.abort(),this._compactionAbortController=new AbortController,this._emit({type:"compaction_start",reason:"manual"});let t=!1,s=!1;try{const n=this.model;if(!n)throw new Error(H());const o=this.settingsManager.getCompactionSettings(n),i=this.sessionManager.getBranch(),r=Q(i,o);if(!r)throw i[i.length-1]?.type==="compaction"?new Error("Already compacted"):new Error("Nothing to compact (session too small)");let a;if(this._extensionRunner.hasHandlers("session_before_compact")){const f=await this._extensionRunner.emit({type:"session_before_compact",preparation:r,branchEntries:i,customInstructions:e,reason:"manual",willRetry:!1,signal:this._compactionAbortController.signal});if(f?.cancel)throw s=!0,new Error("Compaction cancelled");f?.compaction&&(a=f.compaction,t=!0)}let l,c,m,u,d;if(a)l=a.summary,c=a.firstKeptEntryId,m=a.tokensBefore,u=a.usage,d=a.details;else{const f=await this._runDefaultCompaction(r,n,e,this._compactionAbortController.signal,"manual");l=f.summary,c=f.firstKeptEntryId,m=f.tokensBefore,u=f.usage,d=f.details}if(this._compactionAbortController.signal.aborted)throw new Error("Compaction cancelled");this.sessionManager.appendCompaction(l,c,m,d,t,u);const p=this.sessionManager.getEntries();this._refreshFinalizedContext();const y=ie(this.sessionManager.buildSessionProjection().messages),g=p.find(f=>f.type==="compaction"&&f.summary===l);this._extensionRunner&&g&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:g,fromExtension:t,reason:"manual",willRetry:!1});const x={summary:l,firstKeptEntryId:c,tokensBefore:m,estimatedTokensAfter:y,usage:u,details:d};return this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:x,aborted:!1,willRetry:!1}),x}catch(n){const o=n instanceof Error?n.message:String(n),i=this._compactionAbortController.signal.aborted||s,r=i?void 0:`Compaction failed: ${o}`;throw this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:void 0,aborted:i,willRetry:!1,errorMessage:r}),await this._emitSessionCompactFailed({reason:"manual",errorMessage:r,aborted:i,willRetry:!1,fromExtension:t}),n}finally{this._clearManualCompactionState()}}abortCompaction(){this._compactionAbortController?.abort(),this._autoCompactionAbortController?.abort()}abortBranchSummary(){this._branchSummaryAbortController?.abort()}async _checkCompaction(e,t=!0,s=[]){const n=this.settingsManager.getCompactionSettings(this.model);if(!n.enabled||t&&e.stopReason==="aborted")return!1;const o=this._modelForMessage(e),i=o!==void 0,r=(o??this.model)?.contextWindow??0,a=this.sessionManager.getBranch(),l=Z(a);let c=!1;if(l!==null){const _=this._findPersistedMessageEntryId(e),R=_?a.findIndex(C=>C.id===_):-1;c=R>=0?R<a.indexOf(l):e.timestamp<=new Date(l.timestamp).getTime()}if(c)return!1;const m=this.sessionManager.buildSessionProjection(),u=this._findPersistedMessageEntryId(e),d=u===void 0||m.entries.some(_=>_.sourceEntry.id===u&&_.messages.some(R=>R.role==="assistant")),p=this.sessionManager.getBranch(),y=u?p.findIndex(_=>_.id===u):-1,g=y>=0?p.slice(y+1):[],x=g.some(_=>_.type==="context_edit"),f=g.filter(_=>_.type==="context_edit"&&_.targetId===u).at(-1),M=u===void 0||!g.some(_=>_.type==="compaction")&&f?.replacement!==null,v=d&&!x,b=e.stopReason==="error"&&N(e),w=i&&(b&&M||v&&N(e,r)),re=i&&d&&ye(e,this.settingsManager.getOutputTokenLimit(o.maxTokens),o.contextWindow);if(w||re){const _=e.stopReason!=="stop";if(!_)return await this._runAutoCompaction("overflow",!1);if(this._overflowRecoveryAttempted){const C=w?"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.":"Truncated response recovery failed after one compact-and-retry attempt.";return this._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!1,errorMessage:C}),await this._emitSessionCompactFailed({reason:"overflow",errorMessage:C,aborted:!1,willRetry:!1,fromExtension:!1}),!1}this._overflowRecoveryAttempted=!0,this._omitRecoveryAttempt(e,s);const R=await this._runAutoCompaction("overflow",_);return R&&(this._failedResponse=e),R}let E;const U=m,ae=U.entries.some(_=>_.sourceEntry.type==="context_edit"),W=e.usage?$(e.usage):0;if(ae)E=S(U,p).tokens;else if(e.stopReason==="error"||W===0){const _=this.agent.state.messages,R=Oe(_);if(R.lastUsageIndex!==null){const C=_[R.lastUsageIndex];if(l&&C.role==="assistant"&&C.timestamp<=new Date(l.timestamp).getTime())return!1}E=R.tokens}else E=W;const q=this._compactionBaseTokens();return V(E,r,n,q)?await this._runAutoCompaction("threshold",!1,G(r,n,q)):!1}async _runAutoCompaction(e,t,s){const n=this.model,o=this.settingsManager.getCompactionSettings(n);if(e==="threshold"&&s!==void 0&&this._pruneToolOutputsInsteadOfCompacting(s))return!1;let i,r=!1,a=!1,l=!1;try{if(!n)return!1;const c=this.sessionManager.getBranch(),m=Q(c,o);if(!m)return!1;i=new AbortController,this._autoCompactionAbortController=i,r=!0,this._emit({type:"compaction_start",reason:e}),i.signal.throwIfAborted();let u;if(this._extensionRunner.hasHandlers("session_before_compact")){const w=await this._extensionRunner.emit({type:"session_before_compact",preparation:m,branchEntries:c,customInstructions:void 0,reason:e,willRetry:t,signal:i.signal});if(w?.cancel)throw l=!0,new Error("Compaction cancelled");w?.compaction&&(u=w.compaction,a=!0)}i.signal.throwIfAborted();let d,p,y,g,x;if(u)d=u.summary,p=u.firstKeptEntryId,y=u.tokensBefore,g=u.usage,x=u.details;else{const w=await this._runDefaultCompaction(m,n,void 0,i.signal,e);d=w.summary,p=w.firstKeptEntryId,y=w.tokensBefore,g=w.usage,x=w.details}i.signal.throwIfAborted(),this.sessionManager.appendCompaction(d,p,y,x,a,g);const f=this.sessionManager.getEntries();this._refreshFinalizedContext();const M=ie(this.sessionManager.buildSessionProjection().messages),v=f.find(w=>w.type==="compaction"&&w.summary===d);this._extensionRunner&&v&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:v,fromExtension:a,reason:e,willRetry:t});const b={summary:d,firstKeptEntryId:p,tokensBefore:y,estimatedTokensAfter:M,usage:g,details:x};return this._emit({type:"compaction_end",reason:e,result:b,aborted:!1,willRetry:t}),t?!0:this.agent.hasQueuedMessages()}catch(c){const m=c instanceof Error?c.message:"compaction failed",u=i?.signal.aborted===!0||l;if(r){const d=u?void 0:e==="overflow"?`Context overflow recovery failed: ${m}`:`Auto-compaction failed: ${m}`;this._emit({type:"compaction_end",reason:e,result:void 0,aborted:u,willRetry:!1,errorMessage:d}),await this._emitSessionCompactFailed({reason:e,errorMessage:d,aborted:u,willRetry:!1,fromExtension:a})}return!1}finally{this._autoCompactionAbortController===i&&(this._autoCompactionAbortController=void 0),this._resolveIdleWaitIfIdle()}}setAutoCompactionEnabled(e){this.settingsManager.setCompactionEnabled(e)}get autoCompactionEnabled(){return this.settingsManager.getCompactionEnabled()}async bindExtensions(e){e.uiContext!==void 0&&(this._extensionUIContext=e.uiContext),e.mode!==void 0&&(this._extensionMode=e.mode),e.commandContextActions!==void 0&&(this._extensionCommandContextActions=e.commandContextActions),e.abortHandler!==void 0&&(this._extensionAbortHandler=e.abortHandler),e.shutdownHandler!==void 0&&(this._extensionShutdownHandler=e.shutdownHandler),e.onError!==void 0&&(this._extensionErrorListener=e.onError),this._applyExtensionBindings(this._extensionRunner),await this._extensionRunner.emit(this._sessionStartEvent),await this._reconcileDesiredModel(),this._extensionRunner.reportUnhandledMcpServers(),await this.extendResourcesFromExtensions(this._sessionStartEvent.reason==="reload"?"reload":"startup")}async extendResourcesFromExtensions(e){if(!this._extensionRunner.hasHandlers("resources_discover"))return;const{skillPaths:t,promptPaths:s,themePaths:n}=await this._extensionRunner.emitResourcesDiscover(this._cwd,e);if(t.length===0&&s.length===0&&n.length===0)return;const o={skillPaths:this.buildExtensionResourcePaths(t),promptPaths:this.buildExtensionResourcePaths(s),themePaths:this.buildExtensionResourcePaths(n)};this._resourceLoader.extendResources(o),this._rebuildSystemPrompt(this.getActiveToolNames())}buildExtensionResourcePaths(e){return e.map(t=>{const s=this.getExtensionSourceLabel(t.extensionPath),n=se(t.extensionPath)?void 0:ue(t.extensionPath);return{path:t.path,metadata:{source:s,scope:"temporary",origin:"top-level",baseDir:n}}})}getExtensionSourceLabel(e){return se(e)?`extension:${e.replace(/[<>]/g,"")}`:`extension:${he(e).replace(/\.(ts|js)$/,"")}`}_applyExtensionBindings(e){e.setUIContext(this._extensionUIContext,this._extensionMode),e.bindCommandContext(this._extensionCommandContextActions),this._extensionErrorUnsubscriber?.(),this._extensionErrorUnsubscriber=this._extensionErrorListener?e.onError(this._extensionErrorListener):void 0}_refreshCurrentModelFromRegistry(){const e=this.model;if(!e)return;const t=this._modelRuntime.getModel(e.provider,e.id);!t||t===e||(this.agent.state.model=t)}_bindExtensionCore(e){const t=h(()=>{const s=e.getRegisteredCommands().map(i=>({name:i.invocationName,description:i.description,source:"extension",sourceInfo:i.sourceInfo})),n=this.promptTemplates.map(i=>({name:i.name,description:i.description,source:"prompt",sourceInfo:i.sourceInfo})),o=this._resourceLoader.getSkills().skills.map(i=>({name:`skill:${i.name}`,description:i.description,source:"skill",sourceInfo:i.sourceInfo}));return[...s,...n,...o]},"getCommands");e.bindCore({sendMessage:h((s,n)=>{this.sendCustomMessage(s,n).catch(o=>{e.emitError({extensionPath:"<runtime>",event:"send_message",error:o instanceof Error?o.message:String(o)})})},"sendMessage"),sendUserMessage:h((s,n)=>{this.sendUserMessage(s,n).catch(o=>{e.emitError({extensionPath:"<runtime>",event:"send_user_message",error:o instanceof Error?o.message:String(o)})})},"sendUserMessage"),appendEntry:h((s,n)=>{const o=this.sessionManager.appendCustomEntry(s,n),i=this.sessionManager.getEntry(o);i&&this._emit({type:"entry_appended",entry:i})},"appendEntry"),appendUsage:h((s,n)=>{const o=this.sessionManager.appendUsage(n.kind,n.provider??"",n.model??"",s,n.note);this._emit({type:"entry_appended",entry:o})},"appendUsage"),emitHostEvent:h((s,n)=>{this._emit({type:"extension_event",name:s,data:n??null})},"emitHostEvent"),setSessionName:h(s=>{this.setSessionName(s)},"setSessionName"),getSessionName:h(()=>this.sessionManager.getSessionName(),"getSessionName"),setLabel:h((s,n)=>{this.sessionManager.appendLabelChange(s,n)},"setLabel"),getActiveTools:h(()=>this.getActiveToolNames(),"getActiveTools"),getAllTools:h(()=>this.getAllTools(),"getAllTools"),getSettings:h(()=>this.settingsManager.getSettings(),"getSettings"),setActiveTools:h(s=>this.setActiveToolsByName(s),"setActiveTools"),isToolAllowed:h(s=>this.isToolAllowed(s),"isToolAllowed"),getToolAllowlist:h(()=>this.getToolAllowlist(),"getToolAllowlist"),getToolDenylist:h(()=>this.getToolDenylist(),"getToolDenylist"),refreshTools:h(()=>this._refreshToolRegistry(),"refreshTools"),getCommands:t,setModel:h(async s=>this._modelRuntime.hasConfiguredAuth(s.provider)?(await this.setModel(s),!0):!1,"setModel"),getThinkingLevel:h(()=>this.thinkingLevel,"getThinkingLevel"),setThinkingLevel:h(s=>this.setThinkingLevel(s),"setThinkingLevel")},{getModel:h(()=>this.model,"getModel"),getScopedModels:h(()=>this._scopedModels,"getScopedModels"),isIdle:h(()=>this.isIdle,"isIdle"),isProjectTrusted:h(()=>this.settingsManager.isProjectTrusted(),"isProjectTrusted"),getSignal:h(()=>this.agent.signal,"getSignal"),abort:h(()=>{if(this._extensionAbortHandler){this._extensionAbortHandler();return}this.abort()},"abort"),hasPendingMessages:h(()=>this.pendingMessageCount>0,"hasPendingMessages"),shutdown:h(()=>{this._extensionShutdownHandler?.()},"shutdown"),getContextUsage:h(()=>this.getContextUsage(),"getContextUsage"),compact:h(s=>{(async()=>{try{const n=await this.compact(s?.customInstructions);s?.onComplete?.(n)}catch(n){const o=n instanceof Error?n:new Error(String(n));s?.onError?.(o)}})()},"compact"),getSystemPrompt:h(()=>this.systemPrompt,"getSystemPrompt"),getSystemPromptOptions:h(()=>this._baseSystemPromptOptions,"getSystemPromptOptions"),executeTool:h((s,n,o,i)=>this._executeNestedToolCall(s,n,o,i),"executeTool"),getCallableTools:h(()=>this._getCallableTools(),"getCallableTools")},{registerProvider:h((s,n)=>{this._modelRuntime.registerProvider(s,n),this._refreshCurrentModelFromRegistry()},"registerProvider"),registerNativeProvider:h(s=>{this._modelRuntime.registerNativeProvider(s),this._refreshCurrentModelFromRegistry()},"registerNativeProvider"),unregisterProvider:h(s=>{this._modelRuntime.unregisterProvider(s),this._refreshCurrentModelFromRegistry()},"unregisterProvider"),registerVirtualModel:h(s=>{this._modelRuntime.registerVirtualModel(s),this._refreshCurrentModelFromRegistry()},"registerVirtualModel"),unregisterVirtualModel:h((s,n)=>{this._modelRuntime.unregisterVirtualModel(s,n),this._refreshCurrentModelFromRegistry()},"unregisterVirtualModel")})}_refreshToolRegistry(e){const t=new Set([...this._toolRegistry.keys()].filter(d=>this._isActivatedOnRegistration(d))),s=this.getActiveToolNames(),n=this._allowedTools,i=[...this._extensionRunner.getAllRegisteredTools(),...this._customTools.map(d=>({definition:d,sourceInfo:F(`<sdk:${d.name}>`,{source:"sdk"})}))].filter(d=>this._isAllowedTool(d.definition.name)),r=new Map(Array.from(this._baseToolDefinitions.entries()).filter(([d])=>this._isAllowedTool(d)).map(([d,p])=>[d,{definition:p,sourceInfo:F(`${te}${d}`,{source:"builtin"})}]));for(const d of i)r.set(d.definition.name,{definition:d.definition,sourceInfo:d.sourceInfo});this._toolDefinitions=r,this._toolPromptSnippets=new Map(Array.from(r.values()).map(({definition:d})=>{const p=this._normalizePromptSnippet(d.promptSnippet);return p?[d.name,p]:void 0}).filter(d=>d!==void 0)),this._toolPromptGuidelines=new Map(Array.from(r.values()).map(({definition:d})=>{const p=this._normalizePromptGuidelines(d.promptGuidelines);return p.length>0?[d.name,p]:void 0}).filter(d=>d!==void 0));const a=this._extensionRunner,l=K(i,a),c=K(Array.from(this._baseToolDefinitions.values()).filter(d=>this._isAllowedTool(d.name)).map(d=>({definition:d,sourceInfo:F(`${te}${d.name}`,{source:"builtin"})})),a),m=new Map(c.map(d=>[d.name,d]));for(const d of l)m.set(d.name,d);this._toolRegistry=m;const u=(e?.activeToolNames?[...e.activeToolNames]:[...s]).filter(d=>this._isAllowedTool(d));if(n)for(const d of this._toolRegistry.keys())n(d)&&this._isDeclarable(d)&&u.push(d);else if(e?.includeAllExtensionTools)for(const d of l)this._isActivatedOnRegistration(d.name)&&u.push(d.name);else if(!e?.activeToolNames)for(const d of this._toolRegistry.keys())!t.has(d)&&this._isActivatedOnRegistration(d)&&u.push(d);u.push(...this._pendingToolNames),this._setActiveTools([...new Set(u)])}_isDeclarable(e){const t=this._getToolExposure(e);return t==="direct"||t==="model-only"}_isActivatedOnRegistration(e){return this._isDeclarable(e)&&this._toolDefinitions.get(e)?.definition.defaultActive!==!1}getScratchDir(){return this._sandboxScratch??=lt(),this._sandboxScratch}_buildRuntime(e){const t=this.settingsManager.getImageAutoResize(),s=this.settingsManager.getShellCommandPrefix(),n=this.settingsManager.getShellPath();be(this.settingsManager.getShellEnvironmentPolicy());const o=it({settings:this.settingsManager.getSandboxSettingsSources(),override:this._sandboxOptions,defaultLevel:this._sandboxOptions.defaultLevel??"off"});this._releaseOutputFileDirectory??=Se(()=>this.getScratchDir());const i=new dt({policy:o,onEscalation:this._sandboxOptions.onEscalation,onEvent:h(u=>this._emit(u),"onEvent"),scratchDir:h(()=>this.getScratchDir(),"scratchDir")}),r=this._shellSandbox;this._shellSandbox=i,r?.dispose(),ct(i),process.env[rt]=at(o),this._permissionRules=Ye(this.settingsManager.getPermissionRuleSources()),this._readGuard=et({cwd:this._cwd,rules:this._permissionRules,...o.level!=="off"?{protectedReads:ot(o,this._cwd).denyRead}:{}}),nt(this._readGuard);const a=this._baseToolsOverride?Object.fromEntries(Object.entries(this._baseToolsOverride).map(([u,d])=>[u,Mt(d)])):yt(this._cwd,{read:{autoResizeImages:t},bash:{commandPrefix:s,shellPath:n,sandbox:i,background:this._backgroundProcesses}});this._baseToolDefinitions=new Map(Object.entries(a).map(([u,d])=>[u,d])),this._baseToolsOverride||this._baseToolDefinitions.set("process",xt(this._cwd,this._backgroundProcesses,{sandboxed:i.active}));const l=this._resourceLoader.getExtensions();if(e.flagValues)for(const[u,d]of e.flagValues)l.runtime.flagValues.set(u,d);this._extensionRunner=new Ge(l.extensions,l.runtime,this._cwd,this.sessionManager,new Ve(this._modelRuntime)),this._extensionRunnerRef&&(this._extensionRunnerRef.current=this._extensionRunner),this._bindExtensionCore(this._extensionRunner),this._applyExtensionBindings(this._extensionRunner);const c=this._baseToolsOverride?Object.keys(this._baseToolsOverride):["read","bash","edit","write"],m=e.activeToolNames??c;this._refreshToolRegistry({activeToolNames:m,includeAllExtensionTools:e.includeAllExtensionTools})}async reload(e){const t=this._extensionRunner,s=t.getFlagValues();await Qe(t,{type:"session_shutdown",reason:"reload"}),t.invalidate();const n=h(()=>this._usesDefaultTools?ee(this.settingsManager.getDefaultTools()??mt,this._defaultToolModifiers):[],"getDefaultTools"),o=new Set(n());await this.settingsManager.reload(),this.syncQueueModesFromSettings(),Me(),await this._resourceLoader.reload();const i=n().filter(a=>!o.has(a));for(const a of this.getActiveToolNames())this._pendingToolNames.add(a);this._buildRuntime({activeToolNames:[...this.getActiveToolNames(),...i],flagValues:s,includeAllExtensionTools:!0}),(this._extensionUIContext||this._extensionCommandContextActions||this._extensionShutdownHandler||this._extensionErrorListener)&&(await e?.beforeSessionStart?.(),await this._extensionRunner.emit({type:"session_start",reason:"reload"}),this._extensionRunner.reportUnhandledMcpServers(),await this.extendResourcesFromExtensions("reload"))}_isRetryableError(e){return N(e,(this._modelForMessage(e)??this.model)?.contextWindow??0)?!1:xe(e)}_summarizationRetryCallbacks(e){return{onRetryScheduled:h((t,s,n,o)=>{this._emit({type:"summarization_retry_scheduled",attempt:t,maxAttempts:s,delayMs:n,errorMessage:o})},"onRetryScheduled"),onRetryAttemptStart:h(()=>{this._emit({type:"summarization_retry_attempt_start",...e})},"onRetryAttemptStart"),onRetryFinished:h(()=>{this._emit({type:"summarization_retry_finished"})},"onRetryFinished")}}_finishCancelledRetry(){if(this._retryAttempt===0)return;const e=this._retryAttempt;this._retryAttempt=0,this._emit({type:"auto_retry_end",success:!1,attempt:e,finalError:"Retry cancelled"})}async _prepareRetry(e){const t=this.settingsManager.getRetrySettings();if(!t.enabled)return!1;if(this._retryAttempt++,this._retryAttempt>t.maxRetries)return this._retryAttempt--,!1;const s=pe(t,this._retryAttempt);this._emit({type:"auto_retry_start",attempt:this._retryAttempt,maxAttempts:t.maxRetries,delayMs:s,errorMessage:e.errorMessage||"Unknown error",cause:ge(e)?"network":"provider"}),this._omitRecoveryAttempt(e),this._retryAbortController=new AbortController;try{await Ee(s,this._retryAbortController.signal)}catch{return this._finishCancelledRetry(),!1}finally{this._retryAbortController=void 0}return!0}abortRetry(){this._retryAbortController?.abort()}get isRetrying(){return this._retryAbortController!==void 0}get autoRetryEnabled(){return this.settingsManager.getRetryEnabled()}setAutoRetryEnabled(e){this.settingsManager.setRetryEnabled(e)}async executeBash(e,t,s){const n=new AbortController;this._bashAbortControllers.add(n);const o=this.settingsManager.getShellCommandPrefix(),i=this.settingsManager.getShellPath(),r=o?`${o}
15
+ ${e}`:e;try{const a=await Ie(r,this.sessionManager.getCwd(),s?.operations??_t({shellPath:i}),{onChunk:h(l=>{t?.(l),this._emit({type:"bash_execution_update",id:s?.id,delta:l})},"onChunk"),signal:n.signal});return this.recordBashResult(e,a,s),a}finally{this._bashAbortControllers.delete(n)}}recordBashResult(e,t,s){const n={role:"bashExecution",command:e,output:t.output,exitCode:t.exitCode,cancelled:t.cancelled,truncated:t.truncated,fullOutputPath:t.fullOutputPath,timestamp:Date.now(),excludeFromContext:s?.excludeFromContext};this.isStreaming?this._pendingBashMessages.push(n):(this.sessionManager.appendMessage(n),this._refreshFinalizedContext())}abortBash(){for(const e of[...this._bashAbortControllers])e.abort()}get isBashRunning(){return this._bashAbortControllers.size>0}get hasPendingBashMessages(){return this._pendingBashMessages.length>0}_flushPendingBashMessages(){if(this._pendingBashMessages.length!==0){for(const e of this._pendingBashMessages)this.sessionManager.appendMessage(e);this._pendingBashMessages=[],this._refreshFinalizedContext()}}setSessionName(e){this.sessionManager.appendSessionInfo(e);const t={type:"session_info_changed",name:this.sessionManager.getSessionName()};this._emit(t),this._extensionRunner.emit(t)}async navigateTree(e,t={}){if(this.isStreaming)throw new Error("Wait for the current response to finish before navigating the session tree.");if(this.isCompacting)throw new Error("Wait for the current compaction or tree navigation to finish before navigating the session tree.");const s=this.sessionManager.getLeafId();if(e===s)return{cancelled:!1};if(t.summarize&&!this.model)throw new Error("No model available for summarization");const n=this.sessionManager.getEntry(e);if(!n)throw new Error(`Entry ${e} not found`);const{entries:o,commonAncestorId:i}=Be(this.sessionManager,s,e);let r=t.customInstructions,a=t.replaceInstructions,l=t.label;const c={targetId:e,oldLeafId:s,commonAncestorId:i,entriesToSummarize:o,userWantsSummary:t.summarize??!1,customInstructions:r,replaceInstructions:a,label:l};this._branchSummaryAbortController=new AbortController;try{let m,u=!1;if(this._extensionRunner.hasHandlers("session_before_tree")){const M=await this._extensionRunner.emit({type:"session_before_tree",preparation:c,signal:this._branchSummaryAbortController.signal});if(M?.cancel)return{cancelled:!0};M?.summary&&t.summarize&&(m=M.summary,u=!0),M?.customInstructions!==void 0&&(r=M.customInstructions),M?.replaceInstructions!==void 0&&(a=M.replaceInstructions),M?.label!==void 0&&(l=M.label)}let d,p,y;if(t.summarize&&o.length>0&&!m){const M=this._branchSummaryAbortController.signal,v=this.settingsManager.getBranchSummarySettings(),b=await Fe(o,{...await this._getSummarizationRequestAuth(this.model,M),signal:M,customInstructions:r,replaceInstructions:a,reserveTokens:v.reserveTokens,streamFn:this.agent.streamFunction,retry:this.settingsManager.getRetrySettings(),callbacks:this._summarizationRetryCallbacks({source:"branchSummary"})});if(b.aborted)return{cancelled:!0,aborted:!0};if(b.error)throw new Error(b.error);d=b.summary,y=b.usage,p={readFiles:b.readFiles||[],modifiedFiles:b.modifiedFiles||[]}}else m&&(d=m.summary,p=m.details,y=m.usage);let g,x;n.type==="message"&&n.message.role==="user"?(g=n.parentId,x=P(n.message.content,"")):n.type==="custom_message"?(g=n.parentId,x=P(n.content,"")):g=e;let f;if(d){const M=this.sessionManager.branchWithSummary(g,d,p,u,y);f=this.sessionManager.getEntry(M),l&&this.sessionManager.appendLabelChange(M,l)}else g===null?this.sessionManager.resetLeaf():this.sessionManager.branch(g);return l&&!d&&this.sessionManager.appendLabelChange(e,l),this._refreshFinalizedContext(),this._restoreToolsFromTranscript(),await this._extensionRunner.emit({type:"session_tree",newLeafId:this.sessionManager.getLeafId(),oldLeafId:s,summaryEntry:f,fromExtension:d?u:void 0}),{editorText:x,cancelled:!1,summaryEntry:f}}finally{this._branchSummaryAbortController=void 0,this._resolveIdleWaitIfIdle()}}getUserMessagesForForking(){const e=this.sessionManager.getEntries(),t=[];for(const s of e){if(s.type!=="message"||s.message.role!=="user")continue;const n=P(s.message.content,"");n&&t.push({entryId:s.id,text:n})}return t}getSessionStats(){let e=0,t=0,s=0,n=0,o=0;const i=bt();for(const r of this.sessionManager.getEntries()){if(r.type==="usage"?L(i,r.usage):(r.type==="branch_summary"||r.type==="compaction")&&r.usage&&L(i,r.usage),r.type!=="message")continue;n++;const a=r.message;if(a.role==="user")e++;else if(a.role==="toolResult")s++,a.usage&&L(i,a.usage);else if(a.role==="assistant"){t++;const l=a;Array.isArray(l.content)&&(o+=l.content.filter(c=>c.type==="toolCall").length),L(i,l.usage)}}return{sessionFile:this.sessionFile,sessionId:this.sessionId,userMessages:e,assistantMessages:t,toolCalls:o,toolResults:s,totalMessages:n,tokens:{input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,total:i.input+i.output+i.cacheRead+i.cacheWrite},cost:i.cost,contextUsage:this.getContextUsage()}}getContextUsage(){const e=this._limitsModel();if(!e)return;const t=e.contextWindow??0;if(t<=0)return;const s=this.sessionManager.buildSessionProjection(),n=this.sessionManager.getBranch(),o=Z(n);if(o){const a=new Set(s.entries.flatMap(m=>m.messages.some(u=>u.role==="assistant"&&u.stopReason!=="aborted"&&u.stopReason!=="error"&&$(u.usage)>0)?[m.sourceEntry.id]:[])),l=n.findIndex(m=>m.id===o.id);if(!n.slice(l+1).some(m=>a.has(m.id)))return{tokens:null,contextWindow:t,percent:null}}const i=S(s,n),r=i.tokens/t*100;return{tokens:i.tokens,contextWindow:t,percent:r}}async exportToHtml(e,t={}){const s=[t.themeName,this.settingsManager.getTheme()].find(o=>o!==void 0&&Te(o)!==void 0),n=$e({getToolRenderers:h(o=>this._extensionRunner.resolveToolRenderers(o,()=>this.getToolDefinition(o)),"getToolRenderers"),theme:Ce,cwd:this.sessionManager.getCwd()});return await He(this.sessionManager,this.state,{outputPath:e,themeName:s,toolRenderer:n})}exportToJsonl(e){return ht(this.sessionManager,e)}async summarizeForBugReport(e){const t=this.model;if(!t)throw new Error("No model selected");return Le({...await this._getSummarizationRequestAuth(t,e.signal),messages:this.messages,hint:e.hint,signal:e.signal,streamFn:this.agent.streamFunction,retry:this.settingsManager.getRetrySettings(),sessionId:this.sessionId})}getLastAssistantText(){const e=this.messages.slice().reverse().find(s=>{if(s.role!=="assistant")return!1;const n=s;return!(n.stopReason==="aborted"&&n.content.length===0)});if(!e)return;let t="";for(const s of e.content)s.type==="text"&&(t+=s.text);return t.trim()||void 0}createReplacedSessionContext(){const e=Object.defineProperties({},Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));return e.sendMessage=(t,s)=>this.sendCustomMessage(t,s),e.sendUserMessage=(t,s)=>this.sendUserMessage(t,s),e}hasExtensionHandlers(e){return this._extensionRunner.hasHandlers(e)}get extensionRunner(){return this._extensionRunner}}export{Ms as AgentSession,xs as parseSkillBlock};
@@ -1,8 +1,8 @@
1
- var R=Object.defineProperty;var o=(e,t)=>R(e,"name",{value:t,configurable:!0});import*as g from"node:os";import{contentText as T,normalizeContext as x,uuidv7 as E}from"@earendil-works/pi-ai";import{APP_TITLE as h,VERSION as f}from"../config.js";import{getPiUserAgent as I}from"../utils/pi-user-agent.js";import{writeZipArchive as _}from"../utils/zip.js";import{completeSummarization as O,getSummarizationFailure as b}from"./compaction/compaction.js";import{estimateTokens as k,serializeConversation as M}from"./compaction/utils.js";import{convertToLlm as N}from"./messages.js";const H="pi.bug-report",y=1,v="<redacted>",P=/(?:^|[-_])(api[-_]?key|secret|token|password|passwd|credential|authorization|cookie)(?:$|[-_])/i;function w(e){return P.test(e.replace(/([a-z0-9])([A-Z])/g,"$1_$2"))}o(w,"isSensitiveKey");function u(e){const t=/^([a-z][a-z0-9+.-]*:)([a-z][a-z0-9+.-]*:\/\/.*)$/i.exec(e);if(t)return`${t[1]}${u(t[2])}`;try{const n=new URL(e);let s=!1;(n.username||n.password)&&(n.username="",n.password="",s=!0);for(const a of n.searchParams.keys())w(a)&&(n.searchParams.set(a,v),s=!0);return s?n.toString():e}catch{return e}}o(u,"redactUrl");function m(e){if(e!==void 0)return JSON.parse(JSON.stringify(e,(t,n)=>n!=null&&w(t)?v:typeof n=="string"?u(n):n))}o(m,"redactJsonValue");function S(e){const{trackingId:t,deviceId:n,...s}=e;return m(s)}o(S,"redactSettings");function U(){const e=o(t=>process.env[t]||null,"env");return{version:f,userAgent:I(f),runtime:process.versions.bun?`bun/${process.versions.bun}`:`node/${process.version}`,platform:process.platform,arch:process.arch,osRelease:g.release(),osVersion:g.version(),shell:process.env.SHELL?.split(/[\\/]/).pop()||null,terminal:{term:e("TERM"),program:e("TERM_PROGRAM"),programVersion:e("TERM_PROGRAM_VERSION"),colorterm:e("COLORTERM"),tmux:!!process.env.TMUX,ssh:!!(process.env.SSH_CONNECTION||process.env.SSH_CLIENT||process.env.SSH_TTY),ci:!!process.env.CI},piEnvironmentVariables:Object.keys(process.env).filter(t=>t.startsWith("PI_")).sort()}}o(U,"collectEnvironment");function $(e){return{provider:e.provider,id:e.id,name:e.name,api:e.api,baseUrl:u(e.baseUrl),reasoning:e.reasoning,input:e.input,contextWindow:e.contextWindow,maxTokens:e.maxTokens,samplingParams:e.samplingParams?m(e.samplingParams):null,compat:e.compat?m(e.compat):null,thinkingLevelMap:e.thinkingLevelMap??null,headerNames:Object.keys(e.headers??{}).sort()}}o($,"describeModel");function A(e,t){const n=[];return t.auth.apiKey&&n.push("api_key"),t.auth.oauth&&n.push("oauth"),{id:t.id,name:t.name,baseUrl:t.baseUrl?u(t.baseUrl):null,headerNames:Object.keys(t.headers??{}).sort(),authTypes:n,authStatus:e.getProviderAuthStatus(t.id),usingOAuth:e.isUsingOAuth(t.id),registeredByExtension:e.getRegisteredProviderIds().includes(t.id)}}o(A,"describeProvider");function C(e){return{path:e.path,source:u(e.sourceInfo.source),scope:e.sourceInfo.scope,origin:e.sourceInfo.origin,hidden:e.hidden===!0}}o(C,"describeExtension");function q(e){const t=e.hint?.trim()||null,n=e.model?e.modelRuntime.getProvider(e.model.provider):void 0;return{schemaVersion:y,id:e.id??E(),createdAt:new Date().toISOString(),hint:t,environment:U(),session:{id:e.sessionId,included:e.includeSession,summaryIncluded:e.includeSummary,messageCount:e.messageCount,...e.includeSession?{cwd:e.cwd}:{}},model:e.model?$(e.model):null,provider:n?A(e.modelRuntime,n):null,thinkingLevel:e.thinkingLevel,extensions:e.extensions.map(C),extensionErrors:e.extensionErrors.map(({path:s,error:a})=>({path:s,error:a})),settings:{global:S(e.globalSettings),project:S(e.projectSettings)}}}o(q,"collectBugReportMetadata");function Z(e,t=[]){const n=e.getEntries(),s=[];let a=0;for(const i of n){if(i.type!=="message"||i.message.role!=="assistant")continue;a++;const r=i.message,c=r.diagnostics??[];c.length===0&&r.stopReason!=="error"&&r.stopReason!=="aborted"&&!r.errorMessage||s.push({entryId:i.id,timestamp:i.timestamp,provider:r.provider,model:r.model,api:r.api,stopReason:r.stopReason,...r.rawStopReason===void 0?{}:{rawStopReason:r.rawStopReason},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},diagnostics:c})}return{schemaVersion:y,sessionId:e.getSessionId(),entryCount:n.length,assistantMessageCount:a,assistant:s,crashes:t.map(({notified:i,...r})=>r)}}o(Z,"collectBugReportDiagnostics");function B(e){const t=[{name:"report.json",contentType:"application/json",data:`${JSON.stringify(e.metadata,null,2)}
1
+ var R=Object.defineProperty;var s=(e,t)=>R(e,"name",{value:t,configurable:!0});import*as g from"node:os";import{contentText as T,normalizeContext as x,uuidv7 as E}from"@earendil-works/pi-ai";import{APP_TITLE as h,VERSION as f}from"../config.js";import{getPiUserAgent as I}from"../utils/pi-user-agent.js";import{writeZipArchive as O}from"../utils/zip.js";import{completeSummarization as _,getSummarizationFailure as b}from"./compaction/compaction.js";import{estimateTokens as k,serializeConversation as M}from"./compaction/utils.js";import{convertToLlm as N}from"./messages.js";const H="pi.bug-report",y=1,v="<redacted>",P=/(?:^|[-_])(api[-_]?key|secret|token|password|passwd|credential|authorization|cookie)(?:$|[-_])/i;function w(e){return P.test(e.replace(/([a-z0-9])([A-Z])/g,"$1_$2"))}s(w,"isSensitiveKey");function u(e){const t=/^([a-z][a-z0-9+.-]*:)([a-z][a-z0-9+.-]*:\/\/.*)$/i.exec(e);if(t)return`${t[1]}${u(t[2])}`;try{const n=new URL(e);let o=!1;(n.username||n.password)&&(n.username="",n.password="",o=!0);for(const a of n.searchParams.keys())w(a)&&(n.searchParams.set(a,v),o=!0);return o?n.toString():e}catch{return e}}s(u,"redactUrl");function m(e){if(e!==void 0)return JSON.parse(JSON.stringify(e,(t,n)=>n!=null&&w(t)?v:typeof n=="string"?u(n):n))}s(m,"redactJsonValue");function S(e){const{deviceId:t,...n}=e;return m(n)}s(S,"redactSettings");function U(){const e=s(t=>process.env[t]||null,"env");return{version:f,userAgent:I(f),runtime:process.versions.bun?`bun/${process.versions.bun}`:`node/${process.version}`,platform:process.platform,arch:process.arch,osRelease:g.release(),osVersion:g.version(),shell:process.env.SHELL?.split(/[\\/]/).pop()||null,terminal:{term:e("TERM"),program:e("TERM_PROGRAM"),programVersion:e("TERM_PROGRAM_VERSION"),colorterm:e("COLORTERM"),tmux:!!process.env.TMUX,ssh:!!(process.env.SSH_CONNECTION||process.env.SSH_CLIENT||process.env.SSH_TTY),ci:!!process.env.CI},piEnvironmentVariables:Object.keys(process.env).filter(t=>t.startsWith("PI_")).sort()}}s(U,"collectEnvironment");function $(e){return{provider:e.provider,id:e.id,name:e.name,api:e.api,baseUrl:u(e.baseUrl),reasoning:e.reasoning,input:e.input,contextWindow:e.contextWindow,maxTokens:e.maxTokens,samplingParams:e.samplingParams?m(e.samplingParams):null,compat:e.compat?m(e.compat):null,thinkingLevelMap:e.thinkingLevelMap??null,headerNames:Object.keys(e.headers??{}).sort()}}s($,"describeModel");function A(e,t){const n=[];return t.auth.apiKey&&n.push("api_key"),t.auth.oauth&&n.push("oauth"),{id:t.id,name:t.name,baseUrl:t.baseUrl?u(t.baseUrl):null,headerNames:Object.keys(t.headers??{}).sort(),authTypes:n,authStatus:e.getProviderAuthStatus(t.id),usingOAuth:e.isUsingOAuth(t.id),registeredByExtension:e.getRegisteredProviderIds().includes(t.id)}}s(A,"describeProvider");function C(e){return{path:e.path,source:u(e.sourceInfo.source),scope:e.sourceInfo.scope,origin:e.sourceInfo.origin,hidden:e.hidden===!0}}s(C,"describeExtension");function q(e){const t=e.hint?.trim()||null,n=e.model?e.modelRuntime.getProvider(e.model.provider):void 0;return{schemaVersion:y,id:e.id??E(),createdAt:new Date().toISOString(),hint:t,environment:U(),session:{id:e.sessionId,included:e.includeSession,summaryIncluded:e.includeSummary,messageCount:e.messageCount,...e.includeSession?{cwd:e.cwd}:{}},model:e.model?$(e.model):null,provider:n?A(e.modelRuntime,n):null,thinkingLevel:e.thinkingLevel,extensions:e.extensions.map(C),extensionErrors:e.extensionErrors.map(({path:o,error:a})=>({path:o,error:a})),settings:{global:S(e.globalSettings),project:S(e.projectSettings)}}}s(q,"collectBugReportMetadata");function Z(e,t=[]){const n=e.getEntries(),o=[];let a=0;for(const i of n){if(i.type!=="message"||i.message.role!=="assistant")continue;a++;const r=i.message,c=r.diagnostics??[];c.length===0&&r.stopReason!=="error"&&r.stopReason!=="aborted"&&!r.errorMessage||o.push({entryId:i.id,timestamp:i.timestamp,provider:r.provider,model:r.model,api:r.api,stopReason:r.stopReason,...r.rawStopReason===void 0?{}:{rawStopReason:r.rawStopReason},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},diagnostics:c})}return{schemaVersion:y,sessionId:e.getSessionId(),entryCount:n.length,assistantMessageCount:a,assistant:o,crashes:t.map(({notified:i,...r})=>r)}}s(Z,"collectBugReportDiagnostics");function B(e){const t=[{name:"report.json",contentType:"application/json",data:`${JSON.stringify(e.metadata,null,2)}
2
2
  `},{name:"diagnostics.json",contentType:"application/json",data:`${JSON.stringify(e.diagnostics,null,2)}
3
3
  `}];return e.sessionJsonl!==void 0&&t.push({name:"session.jsonl",contentType:"application/x-ndjson",data:e.sessionJsonl}),e.summary!==void 0&&t.push({name:"summary.md",contentType:"text/markdown",data:e.summary.endsWith(`
4
4
  `)?e.summary:`${e.summary}
5
- `}),t}o(B,"bugReportFiles");function Q(e,t){return _(t,B(e))}o(Q,"writeBugReportArchive");function X(e){return`dal-bug-report-${e}.zip`}o(X,"bugReportArchiveFileName");const L=`You are helping a user file a bug report about ${h}, the coding agent they are talking to. You will be shown the conversation transcript. Write a report for the ${h} developers describing what the user was doing and what went wrong.
5
+ `}),t}s(B,"bugReportFiles");function Q(e,t){return O(t,B(e))}s(Q,"writeBugReportArchive");function X(e){return`dal-bug-report-${e}.zip`}s(X,"bugReportArchiveFileName");const L=`You are helping a user file a bug report about ${h}, the coding agent they are talking to. You will be shown the conversation transcript. Write a report for the ${h} developers describing what the user was doing and what went wrong.
6
6
 
7
7
  Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the report.`,j=`Write the bug report in Markdown with these sections:
8
8
 
@@ -18,10 +18,10 @@ Numbered list, as specific as the transcript allows.
18
18
  ## Relevant details
19
19
  Tool calls involved, files touched, model behavior, anything else that helps a developer reproduce or locate the problem.
20
20
 
21
- Do not include file contents, secrets, or credentials from the transcript; refer to files by path only. Keep the report factual and concise.`;function z(e,t){const n=[];let s=0;for(let a=e.length-1;a>=0;a--){const i=e[a],r=k(i);if(n.length>0&&s+r>t)break;n.push(i),s+=r}return n.reverse()}o(z,"selectMessages");async function ee(e){const{model:t}=e,n=t.contextWindow>0?t.contextWindow:128e3,s=z(e.messages,Math.floor(n*.6)),a=e.hint?.trim(),i=[s.length<e.messages.length?`Note: only the last ${s.length} of ${e.messages.length} messages are shown.`:void 0,`<conversation>
22
- ${M(N(s))}
21
+ Do not include file contents, secrets, or credentials from the transcript; refer to files by path only. Keep the report factual and concise.`;function z(e,t){const n=[];let o=0;for(let a=e.length-1;a>=0;a--){const i=e[a],r=k(i);if(n.length>0&&o+r>t)break;n.push(i),o+=r}return n.reverse()}s(z,"selectMessages");async function ee(e){const{model:t}=e,n=t.contextWindow>0?t.contextWindow:128e3,o=z(e.messages,Math.floor(n*.6)),a=e.hint?.trim(),i=[o.length<e.messages.length?`Note: only the last ${o.length} of ${e.messages.length} messages are shown.`:void 0,`<conversation>
22
+ ${M(N(o))}
23
23
  </conversation>`,a?`<user-report>
24
24
  ${a}
25
25
  </user-report>`:void 0,j].filter(l=>l!==void 0).join(`
26
26
 
27
- `),r={maxTokens:Math.min(4096,t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY),signal:e.signal,apiKey:e.apiKey,headers:e.headers,env:e.env,sessionId:e.sessionId,...t.reasoning&&e.thinkingLevel&&e.thinkingLevel!=="off"?{reasoning:e.thinkingLevel}:{}},c=await O(t,x({systemPrompt:L,messages:[{role:"user",content:[{type:"text",text:i}],timestamp:Date.now()}]}),r,e.streamFn,e.retry);if(c.stopReason==="aborted")throw new Error("Bug report summary was cancelled");const p=b(c,"Bug report summary");if(p)throw new Error(p);if(c.content.some(l=>l.type==="toolCall"))throw new Error("Bug report summary attempted to call a tool");const d=T(c.content).trim();if(!d)throw new Error("Bug report summary was empty");return d}o(ee,"generateBugReportSummary");export{H as BUG_REPORT_CUSTOM_ENTRY_TYPE,X as bugReportArchiveFileName,B as bugReportFiles,Z as collectBugReportDiagnostics,q as collectBugReportMetadata,ee as generateBugReportSummary,m as redactJsonValue,u as redactUrl,Q as writeBugReportArchive};
27
+ `),r={maxTokens:Math.min(4096,t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY),signal:e.signal,apiKey:e.apiKey,headers:e.headers,env:e.env,sessionId:e.sessionId,...t.reasoning&&e.thinkingLevel&&e.thinkingLevel!=="off"?{reasoning:e.thinkingLevel}:{}},c=await _(t,x({systemPrompt:L,messages:[{role:"user",content:[{type:"text",text:i}],timestamp:Date.now()}]}),r,e.streamFn,e.retry);if(c.stopReason==="aborted")throw new Error("Bug report summary was cancelled");const p=b(c,"Bug report summary");if(p)throw new Error(p);if(c.content.some(l=>l.type==="toolCall"))throw new Error("Bug report summary attempted to call a tool");const d=T(c.content).trim();if(!d)throw new Error("Bug report summary was empty");return d}s(ee,"generateBugReportSummary");export{H as BUG_REPORT_CUSTOM_ENTRY_TYPE,X as bugReportArchiveFileName,B as bugReportFiles,Z as collectBugReportDiagnostics,q as collectBugReportMetadata,ee as generateBugReportSummary,m as redactJsonValue,u as redactUrl,Q as writeBugReportArchive};
@@ -114,8 +114,6 @@ export interface Settings {
114
114
  npmCommand?: string[];
115
115
  collapseChangelog?: boolean;
116
116
  enableInstallTelemetry?: boolean;
117
- enableAnalytics?: boolean;
118
- trackingId?: string;
119
117
  deviceId?: string;
120
118
  packages?: PackageSource[];
121
119
  extensions?: string[];
@@ -323,9 +321,6 @@ export declare class SettingsManager {
323
321
  setCollapseChangelog(collapse: boolean): void;
324
322
  getEnableInstallTelemetry(): boolean;
325
323
  setEnableInstallTelemetry(enabled: boolean): void;
326
- getEnableAnalytics(): boolean;
327
- getTrackingId(): string | undefined;
328
- setEnableAnalytics(enabled: boolean): void;
329
324
  getOrCreateDeviceId(): string;
330
325
  getPackages(): PackageSource[];
331
326
  setPackages(packages: PackageSource[]): void;