dal-code 1.0.37 → 1.0.38

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 (83) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/dist/core/agent-session.js +1 -1
  3. package/dist/core/auth-storage.js +1 -1
  4. package/dist/core/package-manager.d.ts +4 -0
  5. package/dist/core/package-manager.js +2 -2
  6. package/dist/core/session-manager.d.ts +3 -0
  7. package/dist/core/session-manager.js +12 -12
  8. package/dist/core/settings-diagnostics.js +1 -1
  9. package/dist/core/settings-manager.d.ts +3 -0
  10. package/dist/core/settings-manager.js +1 -1
  11. package/dist/core/shared-data.js +1 -0
  12. package/dist/core/system-prompt.js +10 -10
  13. package/dist/core/trust-manager.js +2 -2
  14. package/dist/dal/reviewed/endorsed-cli.js +1 -0
  15. package/dist/dal/reviewed/endorsed-plan.js +1 -0
  16. package/dist/dal/reviewed/endorsed.js +1 -0
  17. package/dist/dal/reviewed/version.js +1 -0
  18. package/dist/extensions/mcp/config.js +2 -2
  19. package/dist/modes/print-mode.js +5 -5
  20. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  21. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  22. package/dist/node_modules/@dalcode/dal-goal/package.json +2 -2
  23. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  24. package/dist/node_modules/@dalcode/dal-guard/src/mode.js +2 -2
  25. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  26. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  27. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  28. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  29. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  30. package/dist/node_modules/@dalcode/dal-mcp/src/config-edit.js +2 -2
  31. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  32. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
  33. package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
  34. package/dist/node_modules/@dalcode/dal-pi-kit/dist/shared-data.js +1 -0
  35. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  36. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
  37. package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
  38. package/dist/node_modules/@dalcode/dal-pi-kit/src/shared-data.js +1 -0
  39. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  40. package/dist/node_modules/@dalcode/dal-plugins/src/state.js +2 -2
  41. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  42. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  43. package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
  44. package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +1 -1
  45. package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
  46. package/dist/node_modules/@dalcode/dal-router/src/runtime.js +1 -1
  47. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  48. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  49. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  50. package/dist/node_modules/@dalcode/dal-telemetry/src/config.js +2 -2
  51. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  52. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  53. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  54. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  55. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  56. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  57. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  58. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  59. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  60. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  61. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  62. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  63. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts +1 -1
  64. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +1 -1
  65. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  66. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  67. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  68. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  69. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  70. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  71. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  72. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  73. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  74. package/dist/package-manager-cli.js +72 -72
  75. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  76. package/examples/extensions/gondolin/package-lock.json +2 -2
  77. package/examples/extensions/gondolin/package.json +1 -1
  78. package/examples/extensions/sandbox/package-lock.json +2 -2
  79. package/examples/extensions/sandbox/package.json +1 -1
  80. package/examples/extensions/with-deps/package-lock.json +2 -2
  81. package/examples/extensions/with-deps/package.json +1 -1
  82. package/npm-shrinkwrap.json +2 -2
  83. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -8,6 +8,11 @@ DAL Code 的发布说明。这里只写用户看得见的变化。
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ - 同时使用 DAL Code 和独立的 `dal` 命令行(哪怕版本不同、同时在运行)时,设置、登录信息、会话和 MCP 配置不会再互相覆盖或丢失改动;程序意外退出也不会留下写了一半的文件。遇到更新版本写入的数据时,旧版本只读取、不改动,并提示你升级。
12
+ - 修复:上游服务的输出上限低于模型标称值时,被截断的回答不再被丢弃、导致 `dal -p` 什么都不输出却返回成功;现在会照常输出已有内容,提示被截断,并以非零状态退出。
13
+ - `dal update` 不再在没有安装第三方扩展时提示“已跳过扩展”;装了第三方扩展时,会告诉你装了几个、有几个有新版本,以及单独更新它们的命令。
14
+ - 任务描述与代码实际情况不符时(例如说某处翻译错了,但其实是对的),助手会拿出依据说明,而不是为了照办去改本来正确的内容。
15
+
11
16
  ## [1.0.37] - 2026-10-16
12
17
 
13
18
  - 修复:模型输出的工具参数不完整或格式错误时,不再按残缺的参数执行(例如写出半截文件),而是让模型重新给出完整参数。
@@ -11,5 +11,5 @@ ${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(!Ge(this.model))return;try{await this._modelRuntime.refresh({allowNetwork:!1})}catch{}const t=Qe([...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(u=>`${u.provider}\0${u.id}`)),n=this._scopedModels.filter(u=>s.has(`${u.model.provider}\0${u.model.id}`));if(n.length<=1)return;const o=this.model;let i=n.findIndex(u=>I(u.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?pe(this.model):[...Ue]}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??Fe}_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 ke(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 _=await this._extensionRunner.emit({type:"session_before_compact",preparation:r,branchEntries:i,customInstructions:e,reason:"manual",willRetry:!1,signal:this._compactionAbortController.signal});if(_?.cancel)throw s=!0,new Error("Compaction cancelled");_?.compaction&&(a=_.compaction,t=!0)}let l,c,u,m,d;if(a)l=a.summary,c=a.firstKeptEntryId,u=a.tokensBefore,m=a.usage,d=a.details;else{const _=await this._runDefaultCompaction(r,n,e,this._compactionAbortController.signal,"manual");l=_.summary,c=_.firstKeptEntryId,u=_.tokensBefore,m=_.usage,d=_.details}if(this._compactionAbortController.signal.aborted)throw new Error("Compaction cancelled");this.sessionManager.appendCompaction(l,c,u,d,t,m);const g=this.sessionManager.getEntries();this._refreshFinalizedContext();const p=ie(this.sessionManager.buildSessionProjection().messages),f=g.find(_=>_.type==="compaction"&&_.summary===l);this._extensionRunner&&f&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:f,fromExtension:t,reason:"manual",willRetry:!1});const M={summary:l,firstKeptEntryId:c,tokensBefore:u,estimatedTokensAfter:p,usage:m,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=Z(this.sessionManager.getBranch());if(a!==null&&e.timestamp<=new Date(a.timestamp).getTime())return!1;const c=this.sessionManager.buildSessionProjection(),u=this._findPersistedMessageEntryId(e),m=u===void 0||c.entries.some(x=>x.sourceEntry.id===u&&x.messages.some(T=>T.role==="assistant")),d=this.sessionManager.getBranch(),g=u?d.findIndex(x=>x.id===u):-1,p=g>=0?d.slice(g+1):[],f=p.some(x=>x.type==="context_edit"),M=p.filter(x=>x.type==="context_edit"&&x.targetId===u).at(-1),_=u===void 0||!p.some(x=>x.type==="compaction")&&M?.replacement!==null,y=m&&!f,C=e.stopReason==="error"&&B(e),b=i&&(C&&_||y&&B(e,r)),w=i&&m&&fe(e,this.settingsManager.getOutputTokenLimit(o.maxTokens));if(b||w){const x=e.stopReason!=="stop";if(!x)return await this._runAutoCompaction("overflow",!1);if(this._overflowRecoveryAttempted){const v=b?"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:v}),await this._emitSessionCompactFailed({reason:"overflow",errorMessage:v,aborted:!1,willRetry:!1,fromExtension:!1}),!1}this._overflowRecoveryAttempted=!0,this._omitRecoveryAttempt(e,s);const T=await this._runAutoCompaction("overflow",x);return T&&(this._failedResponse=e),T}let E;const U=c,re=U.entries.some(x=>x.sourceEntry.type==="context_edit"),W=e.usage?$(e.usage):0;if(re)E=S(U,d).tokens;else if(e.stopReason==="error"||W===0){const x=this.agent.state.messages,T=Le(x);if(T.lastUsageIndex!==null){const v=x[T.lastUsageIndex];if(a&&v.role==="assistant"&&v.timestamp<=new Date(a.timestamp).getTime())return!1}E=T.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(),u=Q(c,o);if(!u)return!1;i=new AbortController,this._autoCompactionAbortController=i,r=!0,this._emit({type:"compaction_start",reason:e}),i.signal.throwIfAborted();let m;if(this._extensionRunner.hasHandlers("session_before_compact")){const w=await this._extensionRunner.emit({type:"session_before_compact",preparation:u,branchEntries:c,customInstructions:void 0,reason:e,willRetry:t,signal:i.signal});if(w?.cancel)throw l=!0,new Error("Compaction cancelled");w?.compaction&&(m=w.compaction,a=!0)}i.signal.throwIfAborted();let d,g,p,f,M;if(m)d=m.summary,g=m.firstKeptEntryId,p=m.tokensBefore,f=m.usage,M=m.details;else{const w=await this._runDefaultCompaction(u,n,void 0,i.signal,e);d=w.summary,g=w.firstKeptEntryId,p=w.tokensBefore,f=w.usage,M=w.details}i.signal.throwIfAborted(),this.sessionManager.appendCompaction(d,g,p,M,a,f);const _=this.sessionManager.getEntries();this._refreshFinalizedContext();const y=ie(this.sessionManager.buildSessionProjection().messages),C=_.find(w=>w.type==="compaction"&&w.summary===d);this._extensionRunner&&C&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:C,fromExtension:a,reason:e,willRetry:t});const b={summary:d,firstKeptEntryId:g,tokensBefore:p,estimatedTokensAfter:y,usage:f,details:M};return this._emit({type:"compaction_end",reason:e,result:b,aborted:!1,willRetry:t}),t?!0:this.agent.hasQueuedMessages()}catch(c){const u=c instanceof Error?c.message:"compaction failed",m=i?.signal.aborted===!0||l;if(r){const d=m?void 0:e==="overflow"?`Context overflow recovery failed: ${u}`:`Auto-compaction failed: ${u}`;this._emit({type:"compaction_end",reason:e,result:void 0,aborted:m,willRetry:!1,errorMessage:d}),await this._emitSessionCompactFailed({reason:e,errorMessage:d,aborted:m,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:he(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:${ce(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"),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),u=new Map(c.map(d=>[d.name,d]));for(const d of l)u.set(d.name,d);this._toolRegistry=u;const m=(e?.activeToolNames?[...e.activeToolNames]:[...s]).filter(d=>this._isAllowedTool(d));if(n)for(const d of this._toolRegistry.keys())n(d)&&this._isDeclarable(d)&&m.push(d);else if(e?.includeAllExtensionTools)for(const d of l)this._isActivatedOnRegistration(d.name)&&m.push(d.name);else if(!e?.activeToolNames)for(const d of this._toolRegistry.keys())!t.has(d)&&this._isActivatedOnRegistration(d)&&m.push(d);m.push(...this._pendingToolNames),this._setActiveTools([...new Set(m)])}_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??=it(),this._sandboxScratch}_buildRuntime(e){const t=this.settingsManager.getImageAutoResize(),s=this.settingsManager.getShellCommandPrefix(),n=this.settingsManager.getShellPath();Me(this.settingsManager.getShellEnvironmentPolicy());const o=st({settings:this.settingsManager.getSandboxSettingsSources(),override:this._sandboxOptions,defaultLevel:this._sandboxOptions.defaultLevel??"off"});this._releaseOutputFileDirectory??=Ae(()=>this.getScratchDir());const i=new rt({policy:o,onEscalation:this._sandboxOptions.onEscalation,onEvent:h(m=>this._emit(m),"onEvent"),scratchDir:h(()=>this.getScratchDir(),"scratchDir")}),r=this._shellSandbox;this._shellSandbox=i,r?.dispose(),at(i),process.env[nt]=ot(o),this._permissionRules=Ke(this.settingsManager.getPermissionRuleSources()),this._readGuard=Xe({cwd:this._cwd,rules:this._permissionRules,...o.level!=="off"?{protectedReads:tt(o,this._cwd).denyRead}:{}}),et(this._readGuard);const a=this._baseToolsOverride?Object.fromEntries(Object.entries(this._baseToolsOverride).map(([m,d])=>[m,_t(d)])):pt(this._cwd,{read:{autoResizeImages:t},bash:{commandPrefix:s,shellPath:n,sandbox:i,background:this._backgroundProcesses}});this._baseToolDefinitions=new Map(Object.entries(a).map(([m,d])=>[m,d])),this._baseToolsOverride||this._baseToolDefinitions.set("process",ft(this._cwd,this._backgroundProcesses,{sandboxed:i.active}));const l=this._resourceLoader.getExtensions();if(e.flagValues)for(const[m,d]of e.flagValues)l.runtime.flagValues.set(m,d);this._extensionRunner=new qe(l.extensions,l.runtime,this._cwd,this.sessionManager,new $e(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"],u=e.activeToolNames??c;this._refreshToolRegistry({activeToolNames:u,includeAllExtensionTools:e.includeAllExtensionTools})}async reload(e){const t=this._extensionRunner,s=t.getFlagValues();await He(t,{type:"session_shutdown",reason:"reload"}),t.invalidate();const n=h(()=>this._usesDefaultTools?ee(this.settingsManager.getDefaultTools()??ct,this._defaultToolModifiers):[],"getDefaultTools"),o=new Set(n());await this.settingsManager.reload(),this.syncQueueModesFromSettings(),ye(),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:_e(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=me(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 Ce(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}
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(!Ge(this.model))return;try{await this._modelRuntime.refresh({allowNetwork:!1})}catch{}const t=Qe([...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(u=>`${u.provider}\0${u.id}`)),n=this._scopedModels.filter(u=>s.has(`${u.model.provider}\0${u.model.id}`));if(n.length<=1)return;const o=this.model;let i=n.findIndex(u=>I(u.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?pe(this.model):[...Ue]}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??Fe}_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 ke(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 _=await this._extensionRunner.emit({type:"session_before_compact",preparation:r,branchEntries:i,customInstructions:e,reason:"manual",willRetry:!1,signal:this._compactionAbortController.signal});if(_?.cancel)throw s=!0,new Error("Compaction cancelled");_?.compaction&&(a=_.compaction,t=!0)}let l,c,u,m,d;if(a)l=a.summary,c=a.firstKeptEntryId,u=a.tokensBefore,m=a.usage,d=a.details;else{const _=await this._runDefaultCompaction(r,n,e,this._compactionAbortController.signal,"manual");l=_.summary,c=_.firstKeptEntryId,u=_.tokensBefore,m=_.usage,d=_.details}if(this._compactionAbortController.signal.aborted)throw new Error("Compaction cancelled");this.sessionManager.appendCompaction(l,c,u,d,t,m);const g=this.sessionManager.getEntries();this._refreshFinalizedContext();const p=ie(this.sessionManager.buildSessionProjection().messages),f=g.find(_=>_.type==="compaction"&&_.summary===l);this._extensionRunner&&f&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:f,fromExtension:t,reason:"manual",willRetry:!1});const M={summary:l,firstKeptEntryId:c,tokensBefore:u,estimatedTokensAfter:p,usage:m,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=Z(this.sessionManager.getBranch());if(a!==null&&e.timestamp<=new Date(a.timestamp).getTime())return!1;const c=this.sessionManager.buildSessionProjection(),u=this._findPersistedMessageEntryId(e),m=u===void 0||c.entries.some(x=>x.sourceEntry.id===u&&x.messages.some(T=>T.role==="assistant")),d=this.sessionManager.getBranch(),g=u?d.findIndex(x=>x.id===u):-1,p=g>=0?d.slice(g+1):[],f=p.some(x=>x.type==="context_edit"),M=p.filter(x=>x.type==="context_edit"&&x.targetId===u).at(-1),_=u===void 0||!p.some(x=>x.type==="compaction")&&M?.replacement!==null,y=m&&!f,C=e.stopReason==="error"&&B(e),b=i&&(C&&_||y&&B(e,r)),w=i&&m&&fe(e,this.settingsManager.getOutputTokenLimit(o.maxTokens),o.contextWindow);if(b||w){const x=e.stopReason!=="stop";if(!x)return await this._runAutoCompaction("overflow",!1);if(this._overflowRecoveryAttempted){const v=b?"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:v}),await this._emitSessionCompactFailed({reason:"overflow",errorMessage:v,aborted:!1,willRetry:!1,fromExtension:!1}),!1}this._overflowRecoveryAttempted=!0,this._omitRecoveryAttempt(e,s);const T=await this._runAutoCompaction("overflow",x);return T&&(this._failedResponse=e),T}let E;const U=c,re=U.entries.some(x=>x.sourceEntry.type==="context_edit"),W=e.usage?$(e.usage):0;if(re)E=S(U,d).tokens;else if(e.stopReason==="error"||W===0){const x=this.agent.state.messages,T=Le(x);if(T.lastUsageIndex!==null){const v=x[T.lastUsageIndex];if(a&&v.role==="assistant"&&v.timestamp<=new Date(a.timestamp).getTime())return!1}E=T.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(),u=Q(c,o);if(!u)return!1;i=new AbortController,this._autoCompactionAbortController=i,r=!0,this._emit({type:"compaction_start",reason:e}),i.signal.throwIfAborted();let m;if(this._extensionRunner.hasHandlers("session_before_compact")){const w=await this._extensionRunner.emit({type:"session_before_compact",preparation:u,branchEntries:c,customInstructions:void 0,reason:e,willRetry:t,signal:i.signal});if(w?.cancel)throw l=!0,new Error("Compaction cancelled");w?.compaction&&(m=w.compaction,a=!0)}i.signal.throwIfAborted();let d,g,p,f,M;if(m)d=m.summary,g=m.firstKeptEntryId,p=m.tokensBefore,f=m.usage,M=m.details;else{const w=await this._runDefaultCompaction(u,n,void 0,i.signal,e);d=w.summary,g=w.firstKeptEntryId,p=w.tokensBefore,f=w.usage,M=w.details}i.signal.throwIfAborted(),this.sessionManager.appendCompaction(d,g,p,M,a,f);const _=this.sessionManager.getEntries();this._refreshFinalizedContext();const y=ie(this.sessionManager.buildSessionProjection().messages),C=_.find(w=>w.type==="compaction"&&w.summary===d);this._extensionRunner&&C&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:C,fromExtension:a,reason:e,willRetry:t});const b={summary:d,firstKeptEntryId:g,tokensBefore:p,estimatedTokensAfter:y,usage:f,details:M};return this._emit({type:"compaction_end",reason:e,result:b,aborted:!1,willRetry:t}),t?!0:this.agent.hasQueuedMessages()}catch(c){const u=c instanceof Error?c.message:"compaction failed",m=i?.signal.aborted===!0||l;if(r){const d=m?void 0:e==="overflow"?`Context overflow recovery failed: ${u}`:`Auto-compaction failed: ${u}`;this._emit({type:"compaction_end",reason:e,result:void 0,aborted:m,willRetry:!1,errorMessage:d}),await this._emitSessionCompactFailed({reason:e,errorMessage:d,aborted:m,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:he(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:${ce(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"),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),u=new Map(c.map(d=>[d.name,d]));for(const d of l)u.set(d.name,d);this._toolRegistry=u;const m=(e?.activeToolNames?[...e.activeToolNames]:[...s]).filter(d=>this._isAllowedTool(d));if(n)for(const d of this._toolRegistry.keys())n(d)&&this._isDeclarable(d)&&m.push(d);else if(e?.includeAllExtensionTools)for(const d of l)this._isActivatedOnRegistration(d.name)&&m.push(d.name);else if(!e?.activeToolNames)for(const d of this._toolRegistry.keys())!t.has(d)&&this._isActivatedOnRegistration(d)&&m.push(d);m.push(...this._pendingToolNames),this._setActiveTools([...new Set(m)])}_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??=it(),this._sandboxScratch}_buildRuntime(e){const t=this.settingsManager.getImageAutoResize(),s=this.settingsManager.getShellCommandPrefix(),n=this.settingsManager.getShellPath();Me(this.settingsManager.getShellEnvironmentPolicy());const o=st({settings:this.settingsManager.getSandboxSettingsSources(),override:this._sandboxOptions,defaultLevel:this._sandboxOptions.defaultLevel??"off"});this._releaseOutputFileDirectory??=Ae(()=>this.getScratchDir());const i=new rt({policy:o,onEscalation:this._sandboxOptions.onEscalation,onEvent:h(m=>this._emit(m),"onEvent"),scratchDir:h(()=>this.getScratchDir(),"scratchDir")}),r=this._shellSandbox;this._shellSandbox=i,r?.dispose(),at(i),process.env[nt]=ot(o),this._permissionRules=Ke(this.settingsManager.getPermissionRuleSources()),this._readGuard=Xe({cwd:this._cwd,rules:this._permissionRules,...o.level!=="off"?{protectedReads:tt(o,this._cwd).denyRead}:{}}),et(this._readGuard);const a=this._baseToolsOverride?Object.fromEntries(Object.entries(this._baseToolsOverride).map(([m,d])=>[m,_t(d)])):pt(this._cwd,{read:{autoResizeImages:t},bash:{commandPrefix:s,shellPath:n,sandbox:i,background:this._backgroundProcesses}});this._baseToolDefinitions=new Map(Object.entries(a).map(([m,d])=>[m,d])),this._baseToolsOverride||this._baseToolDefinitions.set("process",ft(this._cwd,this._backgroundProcesses,{sandboxed:i.active}));const l=this._resourceLoader.getExtensions();if(e.flagValues)for(const[m,d]of e.flagValues)l.runtime.flagValues.set(m,d);this._extensionRunner=new qe(l.extensions,l.runtime,this._cwd,this.sessionManager,new $e(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"],u=e.activeToolNames??c;this._refreshToolRegistry({activeToolNames:u,includeAllExtensionTools:e.includeAllExtensionTools})}async reload(e){const t=this._extensionRunner,s=t.getFlagValues();await He(t,{type:"session_shutdown",reason:"reload"}),t.invalidate();const n=h(()=>this._usesDefaultTools?ee(this.settingsManager.getDefaultTools()??ct,this._defaultToolModifiers):[],"getDefaultTools"),o=new Set(n());await this.settingsManager.reload(),this.syncQueueModesFromSettings(),ye(),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:_e(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=me(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 Ce(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
15
  ${e}`:e;try{const a=await Ee(r,this.sessionManager.getCwd(),s?.operations??gt({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}=Ie(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 u,m=!1;if(this._extensionRunner.hasHandlers("session_before_tree")){const y=await this._extensionRunner.emit({type:"session_before_tree",preparation:c,signal:this._branchSummaryAbortController.signal});if(y?.cancel)return{cancelled:!0};y?.summary&&t.summarize&&(u=y.summary,m=!0),y?.customInstructions!==void 0&&(r=y.customInstructions),y?.replaceInstructions!==void 0&&(a=y.replaceInstructions),y?.label!==void 0&&(l=y.label)}let d,g,p;if(t.summarize&&o.length>0&&!u){const y=this._branchSummaryAbortController.signal,C=this.settingsManager.getBranchSummarySettings(),b=await Be(o,{...await this._getSummarizationRequestAuth(this.model,y),signal:y,customInstructions:r,replaceInstructions:a,reserveTokens:C.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,p=b.usage,g={readFiles:b.readFiles||[],modifiedFiles:b.modifiedFiles||[]}}else u&&(d=u.summary,g=u.details,p=u.usage);let f,M;n.type==="message"&&n.message.role==="user"?(f=n.parentId,M=P(n.message.content,"")):n.type==="custom_message"?(f=n.parentId,M=P(n.content,"")):f=e;let _;if(d){const y=this.sessionManager.branchWithSummary(f,d,g,m,p);_=this.sessionManager.getEntry(y),l&&this.sessionManager.appendLabelChange(y,l)}else f===null?this.sessionManager.resetLeaf():this.sessionManager.branch(f);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:_,fromExtension:d?m:void 0}),{editorText:M,cancelled:!1,summaryEntry:_}}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=xt();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(u=>u.messages.some(m=>m.role==="assistant"&&m.stopReason!=="aborted"&&m.stopReason!=="error"&&$(m.usage)>0)?[u.sourceEntry.id]:[])),l=n.findIndex(u=>u.id===o.id);if(!n.slice(l+1).some(u=>a.has(u.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&&we(o)!==void 0),n=ze({getToolRenderers:h(o=>this._extensionRunner.resolveToolRenderers(o,()=>this.getToolDefinition(o)),"getToolRenderers"),theme:be,cwd:this.sessionManager.getCwd()});return await je(this.sessionManager,this.state,{outputPath:e,themeName:s,toolRenderer:n})}exportToJsonl(e){return lt(this.sessionManager,e)}async summarizeForBugReport(e){const t=this.model;if(!t)throw new Error("No model selected");return Pe({...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{_s as AgentSession,fs as parseSkillBlock};
@@ -1 +1 @@
1
- var j=Object.defineProperty;var c=(l,t)=>j(l,"name",{value:t,configurable:!0});import{existsSync as f,mkdirSync as L,readFileSync as y,writeFileSync as A}from"fs";import{dirname as M,join as w}from"path";import P from"proper-lockfile";import{setTimeout as D}from"timers/promises";import{getAgentDir as m}from"../config.js";import{raceWithAbortSignal as I}from"../utils/abort.js";import{getFileRevision as u,normalizePath as p}from"../utils/paths.js";import{stripBom as v}from"../utils/text.js";import{isCommandConfigValue as O,resolveConfigValue as x}from"./resolve-config-value.js";const k={encoding:"utf-8",mode:384};let S;class F{static{c(this,"FileAuthStorageBackend")}authPath;constructor(t=w(m(),"auth.json")){this.authPath=p(t)}ensureParentDir(){const t=M(this.authPath);f(t)||L(t,{recursive:!0,mode:448})}ensureFileExists(){f(this.authPath)||A(this.authPath,"{}",k)}acquireLockSyncWithRetry(t){let a;for(let n=1;n<=10;n++)try{return P.lockSync(t,{realpath:!1})}catch(i){if((typeof i=="object"&&i!==null&&"code"in i?String(i.code):void 0)!=="ELOCKED"||n===10)throw i;a=i;const s=Date.now();for(;Date.now()-s<20;);}throw a??new Error("Failed to acquire auth storage lock")}withLock(t){this.ensureParentDir(),this.ensureFileExists();let e;try{e=this.acquireLockSyncWithRetry(this.authPath);const r=f(this.authPath)?y(this.authPath,"utf-8"):void 0,{result:a,next:n}=t(r);return n!==void 0&&A(this.authPath,n,k),a}finally{e&&e()}}async acquireLockAsync(t,e){const n=Date.now()+3e4;let i=0;for(;;){t?.throwIfAborted();let o;try{o=await P.lock(this.authPath,{realpath:!1,retries:0,stale:3e4,onCompromised:e})}catch(s){t?.throwIfAborted();const d=typeof s=="object"&&s!==null&&"code"in s?String(s.code):void 0,h=n-Date.now();if(d!=="ELOCKED"||h<=0)throw s;const E=Math.min(10*2**i,2e3/2);i++;const b=Math.min(Math.round(E*(1+Math.random())),h);t?await D(b,void 0,{signal:t}):await D(b);continue}return t?.aborted&&(await o(),t.throwIfAborted()),o}}async withLockAsync(t,e){e?.signal?.throwIfAborted(),this.ensureParentDir(),this.ensureFileExists();let r,a=!1,n;const i=c(()=>{if(a)throw n??new Error("Auth storage lock was compromised")},"throwIfCompromised");try{r=await this.acquireLockAsync(e?.signal,h=>{a=!0,n=h}),i(),e?.signal?.throwIfAborted();const o=f(this.authPath)?y(this.authPath,"utf-8"):void 0,{result:s,next:d}=await t(o);return i(),e?.signal?.throwIfAborted(),d!==void 0&&A(this.authPath,d,k),i(),s}finally{if(r)try{await r()}catch{}}}}class z{static{c(this,"ReadOnlyAuthStorage")}authPath;data;constructor(t=w(m(),"auth.json")){this.authPath=p(t)}load(){if(this.data)return this.data;let t;try{t=JSON.parse(v(y(this.authPath,"utf-8")))}catch(e){if(e.code==="ENOENT")return this.data={},this.data;throw new Error(`Failed to read auth.json: ${e instanceof Error?e.message:String(e)}`)}if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Invalid auth.json: expected an object");for(const[e,r]of Object.entries(t)){if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`Invalid auth.json credential for provider "${e}"`);const a=r;if(a.type==="api_key"){const n=a.key===void 0||typeof a.key=="string",i=a.env===void 0||typeof a.env=="object"&&a.env!==null&&!Array.isArray(a.env)&&Object.values(a.env).every(o=>typeof o=="string");if(n&&i)continue}else if(a.type==="oauth"&&typeof a.access=="string"&&typeof a.refresh=="string"&&typeof a.expires=="number"&&Number.isFinite(a.expires))continue;throw new Error(`Invalid auth.json credential for provider "${e}"`)}return this.data=t,this.data}async read(t,e){e?.signal?.throwIfAborted();const r=this.load()[t];if(e?.signal?.throwIfAborted(),!!r)return r.type!=="api_key"||!r.key||O(r.key)?structuredClone(r):{...r,key:x(r.key,r.env)}}async list(t){t?.signal?.throwIfAborted();const e=Object.entries(this.load()).map(([r,a])=>({providerId:r,type:a.type}));return t?.signal?.throwIfAborted(),e}async modify(t,e,r){throw new Error("Read-only credential storage cannot modify auth.json")}async delete(t,e){throw new Error("Read-only credential storage cannot modify auth.json")}}class C{static{c(this,"InMemoryAuthStorageBackend")}value;asyncChain=Promise.resolve();withLock(t){const{result:e,next:r}=t(this.value);return r!==void 0&&(this.value=r),e}withLockAsync(t,e){const r=this.asyncChain,a=(async()=>{await r.catch(()=>{}),e?.signal?.throwIfAborted();const{result:n,next:i}=await t(this.value);return e?.signal?.throwIfAborted(),i!==void 0&&(this.value=i),n})();return this.asyncChain=a.catch(()=>{}),I(a,e?.signal)}}class g{static{c(this,"AuthStorage")}storage;authPath;readState;constructor(t,e){if(this.storage=t,this.authPath=e,this.readState=e&&S?.authPath===e?S.readState:{data:{}},e&&!S&&(S={authPath:e,readState:this.readState}),e){const r=u(e);if(r!==void 0&&r===this.readState.revision)return}this.reload()}static create(t=w(m(),"auth.json")){const e=p(t);return new g(new F(e),e)}static fromStorage(t){return new g(t)}static inMemory(t={}){const e=new C;return e.withLock(()=>({result:void 0,next:JSON.stringify(t,null,2)})),g.fromStorage(e)}parseStorageData(t){return t?JSON.parse(v(t)):{}}updateReadState(t,e){this.readState.data=t,this.readState.revision=e}reload(){let t,e;try{this.storage.withLock(r=>(t=r,e=this.authPath?u(this.authPath):void 0,{result:void 0})),this.updateReadState(this.parseStorageData(t),e)}catch{}}async reloadFromStorageAsync(t){return this.storage.withLockAsync(async e=>{const r=this.parseStorageData(e),a=this.authPath?u(this.authPath):void 0;return this.updateReadState(r,a),{result:r}},t)}async readLatestData(t){if(t?.signal?.throwIfAborted(),!this.authPath){const a=this.reloadFromStorageAsync(t);return t?.signal?a:a.catch(()=>this.readState.data)}const e=u(this.authPath);if(e!==void 0&&e===this.readState.revision)return this.readState.data;if(!this.readState.reload){const a=new AbortController,n={controller:a,promise:this.reloadFromStorageAsync({signal:a.signal}),readers:0};this.readState.reload=n,n.promise.then(()=>{this.readState.reload===n&&(this.readState.reload=void 0)},()=>{this.readState.reload===n&&(this.readState.reload=void 0)})}const r=this.readState.reload;r.readers++;try{const a=I(r.promise,t?.signal);return t?.signal?await a:await a.catch(()=>this.readState.data)}finally{r.readers--,r.readers===0&&this.readState.reload===r&&(this.readState.reload=void 0,r.controller.abort())}}async read(t,e){const r=(await this.readLatestData(e))[t];return e?.signal?.throwIfAborted(),r?.type!=="api_key"||r.key===void 0?r:{...r,key:x(r.key,r.env)}}async modify(t,e,r){let a=this.readState.data,n;const i=await this.storage.withLockAsync(async o=>{const s=this.parseStorageData(o),d=await e(s[t]);if(d===void 0)return a=s,n=this.authPath?u(this.authPath):void 0,{result:s[t]};const h={...s,[t]:d};return a=h,{result:d,next:JSON.stringify(h,null,2)}},r);return this.updateReadState(a,n),i}async delete(t,e){let r=this.readState.data;await this.storage.withLockAsync(async a=>{const n=this.parseStorageData(a);return delete n[t],r=n,{result:void 0,next:JSON.stringify(n,null,2)}},e),this.updateReadState(r)}async list(t){const e=Object.entries(await this.readLatestData(t));return t?.signal?.throwIfAborted(),e.map(([r,a])=>({providerId:r,type:a.type}))}}function V(l,t=w(m(),"auth.json")){try{return JSON.parse(v(y(p(t),"utf-8")))[l]}catch{return}}c(V,"readStoredCredential");export{g as AuthStorage,F as FileAuthStorageBackend,C as InMemoryAuthStorageBackend,z as ReadOnlyAuthStorage,V as readStoredCredential};
1
+ var j=Object.defineProperty;var c=(l,t)=>j(l,"name",{value:t,configurable:!0});import{existsSync as f,mkdirSync as L,readFileSync as y,writeFileSync as F}from"fs";import{dirname as M,join as m}from"path";import b from"proper-lockfile";import{setTimeout as P}from"timers/promises";import{getAgentDir as w}from"../config.js";import{raceWithAbortSignal as I}from"../utils/abort.js";import{getFileRevision as u,normalizePath as p}from"../utils/paths.js";import{stripBom as A}from"../utils/text.js";import{isCommandConfigValue as O,resolveConfigValue as x}from"./resolve-config-value.js";import{writeFileAtomicSync as D}from"./shared-data.js";const v={encoding:"utf-8",mode:384};let S;class C{static{c(this,"FileAuthStorageBackend")}authPath;constructor(t=m(w(),"auth.json")){this.authPath=p(t)}ensureParentDir(){const t=M(this.authPath);f(t)||L(t,{recursive:!0,mode:448})}ensureFileExists(){if(!f(this.authPath))try{F(this.authPath,"{}",{...v,flag:"wx"})}catch(t){if(t.code!=="EEXIST")throw t}}acquireLockSyncWithRetry(t){let a;for(let n=1;n<=100;n++)try{return b.lockSync(t,{realpath:!1})}catch(i){if((typeof i=="object"&&i!==null&&"code"in i?String(i.code):void 0)!=="ELOCKED"||n===100)throw i;a=i;const s=Date.now();for(;Date.now()-s<20;);}throw a??new Error("Failed to acquire auth storage lock")}withLock(t){this.ensureParentDir(),this.ensureFileExists();let e;try{e=this.acquireLockSyncWithRetry(this.authPath);const r=f(this.authPath)?y(this.authPath,"utf-8"):void 0,{result:a,next:n}=t(r);return n!==void 0&&D(this.authPath,n,{mode:v.mode}),a}finally{e&&e()}}async acquireLockAsync(t,e){const n=Date.now()+3e4;let i=0;for(;;){t?.throwIfAborted();let o;try{o=await b.lock(this.authPath,{realpath:!1,retries:0,stale:3e4,onCompromised:e})}catch(s){t?.throwIfAborted();const d=typeof s=="object"&&s!==null&&"code"in s?String(s.code):void 0,h=n-Date.now();if(d!=="ELOCKED"||h<=0)throw s;const E=Math.min(10*2**i,2e3/2);i++;const k=Math.min(Math.round(E*(1+Math.random())),h);t?await P(k,void 0,{signal:t}):await P(k);continue}return t?.aborted&&(await o(),t.throwIfAborted()),o}}async withLockAsync(t,e){e?.signal?.throwIfAborted(),this.ensureParentDir(),this.ensureFileExists();let r,a=!1,n;const i=c(()=>{if(a)throw n??new Error("Auth storage lock was compromised")},"throwIfCompromised");try{r=await this.acquireLockAsync(e?.signal,h=>{a=!0,n=h}),i(),e?.signal?.throwIfAborted();const o=f(this.authPath)?y(this.authPath,"utf-8"):void 0,{result:s,next:d}=await t(o);return i(),e?.signal?.throwIfAborted(),d!==void 0&&D(this.authPath,d,{mode:v.mode}),i(),s}finally{if(r)try{await r()}catch{}}}}class H{static{c(this,"ReadOnlyAuthStorage")}authPath;data;constructor(t=m(w(),"auth.json")){this.authPath=p(t)}load(){if(this.data)return this.data;let t;try{t=JSON.parse(A(y(this.authPath,"utf-8")))}catch(e){if(e.code==="ENOENT")return this.data={},this.data;throw new Error(`Failed to read auth.json: ${e instanceof Error?e.message:String(e)}`)}if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Invalid auth.json: expected an object");for(const[e,r]of Object.entries(t)){if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`Invalid auth.json credential for provider "${e}"`);const a=r;if(a.type==="api_key"){const n=a.key===void 0||typeof a.key=="string",i=a.env===void 0||typeof a.env=="object"&&a.env!==null&&!Array.isArray(a.env)&&Object.values(a.env).every(o=>typeof o=="string");if(n&&i)continue}else if(a.type==="oauth"&&typeof a.access=="string"&&typeof a.refresh=="string"&&typeof a.expires=="number"&&Number.isFinite(a.expires))continue;throw new Error(`Invalid auth.json credential for provider "${e}"`)}return this.data=t,this.data}async read(t,e){e?.signal?.throwIfAborted();const r=this.load()[t];if(e?.signal?.throwIfAborted(),!!r)return r.type!=="api_key"||!r.key||O(r.key)?structuredClone(r):{...r,key:x(r.key,r.env)}}async list(t){t?.signal?.throwIfAborted();const e=Object.entries(this.load()).map(([r,a])=>({providerId:r,type:a.type}));return t?.signal?.throwIfAborted(),e}async modify(t,e,r){throw new Error("Read-only credential storage cannot modify auth.json")}async delete(t,e){throw new Error("Read-only credential storage cannot modify auth.json")}}class R{static{c(this,"InMemoryAuthStorageBackend")}value;asyncChain=Promise.resolve();withLock(t){const{result:e,next:r}=t(this.value);return r!==void 0&&(this.value=r),e}withLockAsync(t,e){const r=this.asyncChain,a=(async()=>{await r.catch(()=>{}),e?.signal?.throwIfAborted();const{result:n,next:i}=await t(this.value);return e?.signal?.throwIfAborted(),i!==void 0&&(this.value=i),n})();return this.asyncChain=a.catch(()=>{}),I(a,e?.signal)}}class g{static{c(this,"AuthStorage")}storage;authPath;readState;constructor(t,e){if(this.storage=t,this.authPath=e,this.readState=e&&S?.authPath===e?S.readState:{data:{}},e&&!S&&(S={authPath:e,readState:this.readState}),e){const r=u(e);if(r!==void 0&&r===this.readState.revision)return}this.reload()}static create(t=m(w(),"auth.json")){const e=p(t);return new g(new C(e),e)}static fromStorage(t){return new g(t)}static inMemory(t={}){const e=new R;return e.withLock(()=>({result:void 0,next:JSON.stringify(t,null,2)})),g.fromStorage(e)}parseStorageData(t){return t?JSON.parse(A(t)):{}}updateReadState(t,e){this.readState.data=t,this.readState.revision=e}reload(){let t,e;try{this.storage.withLock(r=>(t=r,e=this.authPath?u(this.authPath):void 0,{result:void 0})),this.updateReadState(this.parseStorageData(t),e)}catch{}}async reloadFromStorageAsync(t){return this.storage.withLockAsync(async e=>{const r=this.parseStorageData(e),a=this.authPath?u(this.authPath):void 0;return this.updateReadState(r,a),{result:r}},t)}async readLatestData(t){if(t?.signal?.throwIfAborted(),!this.authPath){const a=this.reloadFromStorageAsync(t);return t?.signal?a:a.catch(()=>this.readState.data)}const e=u(this.authPath);if(e!==void 0&&e===this.readState.revision)return this.readState.data;if(!this.readState.reload){const a=new AbortController,n={controller:a,promise:this.reloadFromStorageAsync({signal:a.signal}),readers:0};this.readState.reload=n,n.promise.then(()=>{this.readState.reload===n&&(this.readState.reload=void 0)},()=>{this.readState.reload===n&&(this.readState.reload=void 0)})}const r=this.readState.reload;r.readers++;try{const a=I(r.promise,t?.signal);return t?.signal?await a:await a.catch(()=>this.readState.data)}finally{r.readers--,r.readers===0&&this.readState.reload===r&&(this.readState.reload=void 0,r.controller.abort())}}async read(t,e){const r=(await this.readLatestData(e))[t];return e?.signal?.throwIfAborted(),r?.type!=="api_key"||r.key===void 0?r:{...r,key:x(r.key,r.env)}}async modify(t,e,r){let a=this.readState.data,n;const i=await this.storage.withLockAsync(async o=>{const s=this.parseStorageData(o),d=await e(s[t]);if(d===void 0)return a=s,n=this.authPath?u(this.authPath):void 0,{result:s[t]};const h={...s,[t]:d};return a=h,{result:d,next:JSON.stringify(h,null,2)}},r);return this.updateReadState(a,n),i}async delete(t,e){let r=this.readState.data;await this.storage.withLockAsync(async a=>{const n=this.parseStorageData(a);return delete n[t],r=n,{result:void 0,next:JSON.stringify(n,null,2)}},e),this.updateReadState(r)}async list(t){const e=Object.entries(await this.readLatestData(t));return t?.signal?.throwIfAborted(),e.map(([r,a])=>({providerId:r,type:a.type}))}}function U(l,t=m(w(),"auth.json")){try{return JSON.parse(A(y(p(t),"utf-8")))[l]}catch{return}}c(U,"readStoredCredential");export{g as AuthStorage,C as FileAuthStorageBackend,R as InMemoryAuthStorageBackend,H as ReadOnlyAuthStorage,U as readStoredCredential};
@@ -75,6 +75,8 @@ export interface PackageManager {
75
75
  }): boolean;
76
76
  setProgressCallback(callback: ProgressCallback | undefined): void;
77
77
  getInstalledPath(source: string, scope: "user" | "project"): string | undefined;
78
+ getRegistryIntegrity(source: string): Promise<string | undefined>;
79
+ getRecordedIntegrity(name: string, scope: "user" | "project"): string | null | undefined;
78
80
  }
79
81
  interface PackageManagerOptions {
80
82
  cwd: string;
@@ -102,6 +104,8 @@ export declare class DefaultPackageManager implements PackageManager {
102
104
  local?: boolean;
103
105
  }): boolean;
104
106
  getInstalledPath(source: string, scope: "user" | "project"): string | undefined;
107
+ getRegistryIntegrity(source: string): Promise<string | undefined>;
108
+ getRecordedIntegrity(name: string, scope: "user" | "project"): string | null | undefined;
105
109
  readDeclaredPermissions(installedPath: string | undefined): string[] | undefined;
106
110
  readGitHead(installedPath: string | undefined): Promise<string | undefined>;
107
111
  private getStoredResolvedCommit;
@@ -1,3 +1,3 @@
1
- var wt=Object.defineProperty;var m=(c,t)=>wt(c,"name",{value:t,configurable:!0});import{createHash as kt}from"node:crypto";import{chmodSync as St,existsSync as f,globSync as vt,mkdirSync as W,readdirSync as x,readFileSync as H,rmSync as I,statSync as N,writeFileSync as z}from"node:fs";import{homedir as Mt}from"node:os";function Y(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{const c=H("/proc/self/environ","utf-8"),t={};for(const e of c.split("\0")){const s=e.indexOf("=");s>0&&(t[e.slice(0,s)]=e.slice(s+1))}return t}catch{return process.env}}m(Y,"getEnv");import{basename as $,dirname as w,join as h,relative as k,resolve as S,sep as U}from"node:path";import G from"ignore";import{minimatch as j}from"minimatch";import{gt as st,maxSatisfying as Ct,rcompare as Nt,satisfies as Et,valid as bt,validRange as Ft}from"semver";import{CONFIG_DIR_NAME as A,isOfficialExtensionsPackage as xt,SHARED_SKILL_CONFIG_DIRS as nt}from"../config.js";import{spawnProcess as rt,spawnProcessSync as It}from"../utils/child-process.js";import{parseGitUrl as jt}from"../utils/git.js";import{isOfflineModeEnabled as b}from"../utils/offline.js";import{canonicalizePath as Rt,isLocalPath as $t,markPathIgnoredByCloudSync as Gt,resolvePath as L}from"../utils/paths.js";import{stripBom as it}from"../utils/text.js";import{isStdoutTakenOver as At}from"./output-guard.js";import{findNearestPiManifest as Dt,readPiManifest as _}from"./pi-manifest.js";import{BUILTIN_PATH_PREFIX as X}from"./source-info.js";const C=1e4,ot=4,Tt=4,Wt=Symbol.for("dalcode.packageManager.npmArgsHook");function Ht(c){return bt(c??"")!==null}m(Ht,"isExactNpmVersion");function Ut(c){return c?Ft(c)??void 0:void 0}m(Ut,"getNpmVersionRange");function at(c){return c.source==="builtin"?5:c.origin==="package"?4:(c.scope==="project"?0:2)+(c.source==="local"?0:1)}m(at,"resourcePrecedenceRank");const O=["extensions","skills","prompts","themes"],Lt={extensions:/\.(ts|js)$/,skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/},_t=[".gitignore",".ignore",".fdignore"];function y(c){return c.split(U).join("/")}m(y,"toPosixPath");function q(){return process.env.HOME||Mt()}m(q,"getHomeDir");function Ot(c){const t=h(c,"tmp","extensions");return W(t,{recursive:!0,mode:448}),St(t,448),t}m(Ot,"getExtensionTempFolder");function Bt(c,t){const e=c.trim();if(!e||e.startsWith("#")&&!e.startsWith("\\#"))return null;let s=c,n=!1;s.startsWith("!")?(n=!0,s=s.slice(1)):s.startsWith("\\!")&&(s=s.slice(1)),s.startsWith("/")&&(s=s.slice(1));const r=t?`${t}${s}`:s;return n?`!${r}`:r}m(Bt,"prefixIgnorePattern");function D(c,t,e){const s=k(e,t),n=s?`${y(s)}/`:"";for(const r of _t){const i=h(t,r);if(f(i))try{const a=H(i,"utf-8").split(/\r?\n/).map(l=>Bt(l,n)).filter(l=>!!l);a.length>0&&c.add(a)}catch{}}}m(D,"addIgnoreRules");function Vt(c){return c.startsWith("!")||c.startsWith("+")||c.startsWith("-")||c.includes("*")||c.includes("?")}m(Vt,"isPattern");function Q(c){return c.startsWith("!")||c.startsWith("+")||c.startsWith("-")}m(Q,"isOverridePattern");function Kt(c){return c.includes("*")||c.includes("?")}m(Kt,"hasGlobPattern");function Jt(c,t){return vt(c,{cwd:t}).map(e=>S(t,e)).filter(e=>k(t,e).split(U).every(s=>s===".."||!s.startsWith("."))).sort((e,s)=>e<s?-1:e>s?1:0)}m(Jt,"expandPackageGlob");function zt(c){const t=[],e=[];for(const s of c)Vt(s)?e.push(s):t.push(s);return{plain:t,patterns:e}}m(zt,"splitPatterns");function ct(c,t,e=!0,s,n){const r=[];if(!f(c))return r;const i=n??c,o=s??G();D(o,c,i);try{const a=x(c,{withFileTypes:!0});for(const l of a){if(l.name.startsWith(".")||e&&l.name==="node_modules")continue;const p=h(c,l.name);let u=l.isDirectory(),g=l.isFile();if(l.isSymbolicLink())try{const F=N(p);u=F.isDirectory(),g=F.isFile()}catch{continue}const P=y(k(i,p)),d=u?`${P}/`:P;o.ignores(d)||(u?r.push(...ct(p,t,e,o,i)):g&&t.test(l.name)&&r.push(p))}}catch{}return r}m(ct,"collectFiles");function Z(c,t,e,s){const n=[];if(!f(c))return n;const r=s??c,i=e??G();D(i,c,r);try{const o=x(c,{withFileTypes:!0});for(const a of o){if(a.name!=="SKILL.md")continue;const l=h(c,a.name);let p=a.isFile();if(a.isSymbolicLink())try{p=N(l).isFile()}catch{continue}const u=y(k(r,l));if(p&&!i.ignores(u))return n.push(l),n}for(const a of o){if(a.name.startsWith(".")||a.name==="node_modules")continue;const l=h(c,a.name);let p=a.isDirectory(),u=a.isFile();if(a.isSymbolicLink())try{const d=N(l);p=d.isDirectory(),u=d.isFile()}catch{continue}const g=y(k(r,l));if(u&&a.name.endsWith(".md")&&!i.ignores(g)&&(t==="pi"&&c===r||t==="agents"&&c!==r)){n.push(l);continue}p&&(i.ignores(`${g}/`)||n.push(...Z(l,t,i,r)))}}catch{}return n}m(Z,"collectSkillEntries");function B(c,t){return Z(c,t)}m(B,"collectAutoSkillEntries");function Yt(c){let t=S(c);for(;;){if(f(h(t,".git")))return t;const e=w(t);if(e===t)return null;t=e}}m(Yt,"findGitRepoRoot");function Xt(c=q()){return nt.map(t=>h(c,t,"skills"))}m(Xt,"userSharedSkillDirs");function qt(c){const t=[],e=S(c),s=Yt(e);let n=e;for(;;){for(const i of nt)t.push(h(n,i,"skills"));if(s&&n===s)break;const r=w(n);if(r===n)break;n=r}return t}m(qt,"collectAncestorAgentsSkillDirs");function lt(c){const t=[];if(!f(c))return t;const e=G();D(e,c,c);try{const s=x(c,{withFileTypes:!0});for(const n of s){if(n.name.startsWith(".")||n.name==="node_modules")continue;const r=h(c,n.name);let i=n.isFile();if(n.isSymbolicLink())try{i=N(r).isFile()}catch{continue}const o=y(k(c,r));e.ignores(o)||i&&n.name.endsWith(".md")&&t.push(r)}}catch{}return t}m(lt,"collectAutoPromptEntries");function ut(c){const t=[];if(!f(c))return t;const e=G();D(e,c,c);try{const s=x(c,{withFileTypes:!0});for(const n of s){if(n.name.startsWith(".")||n.name==="node_modules")continue;const r=h(c,n.name);let i=n.isFile();if(n.isSymbolicLink())try{i=N(r).isFile()}catch{continue}const o=y(k(c,r));e.ignores(o)||i&&n.name.endsWith(".json")&&t.push(r)}}catch{}return t}m(ut,"collectAutoThemeEntries");function pt(c){const t=h(c,"package.json");if(f(t)){const n=_(t);if(n?.extensions?.length){const r=[];for(const i of n.extensions){const o=S(c,i);f(o)&&r.push(o)}if(r.length>0)return r}}const e=h(c,"index.ts"),s=h(c,"index.js");return f(e)?[e]:f(s)?[s]:null}m(pt,"resolveExtensionEntries");function tt(c){const t=[];if(!f(c))return t;const e=pt(c);if(e)return e;const s=G();D(s,c,c);try{const n=x(c,{withFileTypes:!0});for(const r of n){if(r.name.startsWith(".")||r.name==="node_modules")continue;const i=h(c,r.name);let o=r.isDirectory(),a=r.isFile();if(r.isSymbolicLink())try{const u=N(i);o=u.isDirectory(),a=u.isFile()}catch{continue}const l=y(k(c,i)),p=o?`${l}/`:l;if(!s.ignores(p)){if(a&&(r.name.endsWith(".ts")||r.name.endsWith(".js")))t.push(i);else if(o){const u=pt(i);u&&t.push(...u)}}}}catch{}return t}m(tt,"collectAutoExtensionEntries");function V(c,t){return t==="skills"?Z(c,"pi"):t==="extensions"?tt(c):ct(c,Lt[t])}m(V,"collectResourceFiles");function K(c,t,e){const s=y(k(e,c)),n=$(c),r=y(c),i=n==="SKILL.md",o=i?w(c):void 0,a=i?y(k(e,o)):void 0,l=i?$(o):void 0,p=i?y(o):void 0;return t.some(u=>{const g=y(u);return j(s,g)||j(n,g)||j(r,g)?!0:i?j(a,g)||j(l,g)||j(p,g):!1})}m(K,"matchesAnyPattern");function Qt(c){const t=c.startsWith("./")||c.startsWith(".\\")?c.slice(2):c;return y(t)}m(Qt,"normalizeExactPattern");function T(c,t,e){if(t.length===0)return!1;const s=y(k(e,c)),n=$(c),r=y(c),i=n==="SKILL.md",o=i?w(c):void 0,a=i?y(k(e,o)):void 0,l=i?y(o):void 0;return t.some(p=>{const u=Qt(p);return u===s||u===r?!0:i?u===a||u===l:!1})}m(T,"matchesAnyExactPattern");function ht(c){return c.filter(t=>t.startsWith("!")||t.startsWith("+")||t.startsWith("-"))}m(ht,"getOverridePatterns");function ft(c,t,e){const s=ht(t),n=s.filter(a=>a.startsWith("!")).map(a=>a.slice(1)),r=s.filter(a=>a.startsWith("+")).map(a=>a.slice(1)),i=s.filter(a=>a.startsWith("-")).map(a=>a.slice(1));let o=!0;return n.length>0&&K(c,n,e)&&(o=!1),r.length>0&&T(c,r,e)&&(o=!0),i.length>0&&T(c,i,e)&&(o=!1),o}m(ft,"isEnabledByOverrides");function J(c,t,e){const s=[],n=[],r=[],i=[];for(const a of t)a.startsWith("+")?r.push(a.slice(1)):a.startsWith("-")?i.push(a.slice(1)):a.startsWith("!")?n.push(a.slice(1)):s.push(a);let o;if(s.length===0?o=[...c]:o=c.filter(a=>K(a,s,e)),n.length>0&&(o=o.filter(a=>!K(a,n,e))),r.length>0)for(const a of c)!o.includes(a)&&T(a,r,e)&&o.push(a);return i.length>0&&(o=o.filter(a=>!T(a,i,e))),new Set(o)}m(J,"applyPatterns");function mt(c,t,e){const s=new Map;for(const n of t){const r=n.slice(n.startsWith("+")||n.startsWith("-")||n.startsWith("!")?1:0),i=!n.startsWith("-")&&!n.startsWith("!"),o=n.startsWith("+")||n.startsWith("-");for(const a of c)(o?T(a,[r],e):K(a,[r],e))&&s.set(a,i)}return s}m(mt,"applyAutoloadDisabledPatterns");class de{static{m(this,"DefaultPackageManager")}cwd;agentDir;settingsManager;builtinExtensions;globalNpmRoot;globalNpmRootCommandKey;progressCallback;constructor(t){this.cwd=L(t.cwd),this.agentDir=L(t.agentDir),this.settingsManager=t.settingsManager,this.builtinExtensions=t.builtinExtensions??[]}setProgressCallback(t){this.progressCallback=t}addSourceToSettings(t,e){const s=e?.local?"project":"user",r=(s==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],i=this.normalizePackageSourceForSettings(t,s),o=m(p=>{const u=e?.resolvedCommit;return!u&&!p?i:typeof p=="string"||p===void 0?u?{source:i,resolvedCommit:u}:i:u?{...p,source:i,resolvedCommit:u}:{...p,source:i}},"toEntry"),a=r.findIndex(p=>this.packageSourcesMatch(p,t,s));if(a!==-1){const p=r[a];if(this.getPackageSourceString(p)===i&&!e?.resolvedCommit)return!1;const u=[...r];return u[a]=o(p),s==="project"?this.settingsManager.setProjectPackages(u):this.settingsManager.setPackages(u),!0}const l=[...r,o()];return s==="project"?this.settingsManager.setProjectPackages(l):this.settingsManager.setPackages(l),!0}removeSourceFromSettings(t,e){const s=e?.local?"project":"user",r=(s==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],i=r.filter(a=>!this.packageSourcesMatch(a,t,s));return i.length!==r.length?(s==="project"?this.settingsManager.setProjectPackages(i):this.settingsManager.setPackages(i),!0):!1}getInstalledPath(t,e){const s=this.parseSource(t);if(s.type==="npm"){const n=this.getNpmInstallPath(s,e);return f(n)?n:void 0}if(s.type==="git"){const n=this.getGitInstallPath(s,e);return f(n)?n:void 0}if(s.type==="local"){const n=this.getBaseDirForScope(e),r=this.resolvePathFromBase(s.path,n);return f(r)?r:void 0}}readDeclaredPermissions(t){if(!t)return;const s=Dt(t)?.manifest.permissions;return s&&s.length>0?[...s]:void 0}async readGitHead(t){if(t)try{const s=(await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:C})).trim();return/^[0-9a-f]{7,40}$/i.test(s)?s:void 0}catch{return}}getStoredResolvedCommit(t,e){const s=e==="project"?this.settingsManager.getProjectSettings().packages??[]:this.settingsManager.getGlobalSettings().packages??[];for(const n of s)if(typeof n!="string"&&this.packageSourcesMatch(n,t,e))return n.resolvedCommit}emitProgress(t){this.progressCallback?.(t)}async withProgress(t,e,s,n){this.emitProgress({type:"start",action:t,source:e,message:s});try{await n(),this.emitProgress({type:"complete",action:t,source:e})}catch(r){const i=r instanceof Error?r.message:String(r);throw this.emitProgress({type:"error",action:t,source:e,message:i}),r}}async resolve(t){const e=this.createAccumulator(),s=this.settingsManager.getGlobalSettings(),n=this.settingsManager.getProjectSettings(),r=[];for(const l of n.packages??[])r.push({pkg:l,scope:"project"});for(const l of s.packages??[])r.push({pkg:l,scope:"user"});const i=this.dedupePackages(r);await this.resolvePackageSources(i,e,t);const o=this.agentDir,a=h(this.cwd,A);for(const l of O){const p=this.getTargetMap(e,l),u=s[l]??[],g=n[l]??[];this.resolveLocalEntries(g,l,p,{source:"local",scope:"project",origin:"top-level"},a),this.resolveLocalEntries(u,l,p,{source:"local",scope:"user",origin:"top-level"},o)}this.addAutoDiscoveredResources(e,s,n,o,a);for(const l of this.builtinExtensions){const p=`${X}${l}`,u=mt([p],ht(n.extensions??[]),a).get(p);this.addResource(e.extensions,p,{source:"builtin",scope:u===void 0?"user":"project",origin:"top-level"},u??ft(p,s.extensions??[],o))}return this.toResolvedPaths(e)}async resolveExtensionSources(t,e){const s=this.createAccumulator(),n=e?.temporary?"temporary":e?.local?"project":"user";for(const i of t.filter(o=>o.startsWith(X)))this.addResource(s.extensions,i,{source:"builtin",scope:n,origin:"top-level"},!0);const r=t.filter(i=>!i.startsWith(X)).map(i=>({pkg:i,scope:n}));return await this.resolvePackageSources(r,s),this.toResolvedPaths(s)}listConfiguredPackages(){const t=this.settingsManager.getGlobalSettings(),e=this.settingsManager.getProjectSettings(),s=[];for(const n of t.packages??[]){const r=typeof n=="string"?n:n.source,i=this.getInstalledPath(r,"user");s.push({source:r,scope:"user",filtered:typeof n=="object",installedPath:i,resolvedCommit:typeof n=="object"?n.resolvedCommit:void 0,permissions:this.readDeclaredPermissions(i)})}for(const n of e.packages??[]){const r=typeof n=="string"?n:n.source,i=this.getInstalledPath(r,"project");s.push({source:r,scope:"project",filtered:typeof n=="object",installedPath:i,resolvedCommit:typeof n=="object"?n.resolvedCommit:void 0,permissions:this.readDeclaredPermissions(i)})}return s}async install(t,e){const s=this.parseSource(t),n=e?.local?"project":"user";this.assertProjectTrustedForScope(n),await this.withProgress("install",t,`Installing ${t}...`,async()=>{if(s.type==="npm"){await this.installNpm(s,n,!1);return}if(s.type==="git"){await this.installGit(s,n);return}if(s.type==="local"){const r=this.resolvePath(s.path);if(!f(r))throw new Error(`Path does not exist: ${r}`);return}throw new Error(`Unsupported install source: ${t}`)})}async installAndPersist(t,e){await this.install(t,e);const s=e?.local?"project":"user",n=this.getInstalledPath(t,s),r=await this.readGitHead(n);this.addSourceToSettings(t,{...e,resolvedCommit:r})}async remove(t,e){const s=this.parseSource(t),n=e?.local?"project":"user";this.assertProjectTrustedForScope(n),await this.withProgress("remove",t,`Removing ${t}...`,async()=>{if(s.type==="npm"){await this.uninstallNpm(s,n);return}if(s.type==="git"){await this.removeGit(s,n);return}if(s.type!=="local")throw new Error(`Unsupported remove source: ${t}`)})}async removeAndPersist(t,e){return await this.remove(t,e),this.removeSourceFromSettings(t,e)}async update(t,e){const s=e?.latest===!0,n=this.settingsManager.getGlobalSettings(),r=this.settingsManager.getProjectSettings(),i=t?this.getPackageIdentity(t):void 0;let o=!1;const a=[];for(const l of n.packages??[]){const p=typeof l=="string"?l:l.source;i&&this.getPackageIdentity(p,"user")!==i||(o=!0,a.push({source:p,scope:"user"}))}for(const l of r.packages??[]){const p=typeof l=="string"?l:l.source;i&&this.getPackageIdentity(p,"project")!==i||(o=!0,a.push({source:p,scope:"project"}))}if(t&&!o)throw new Error(this.buildNoMatchingPackageMessage(t,[...n.packages??[],...r.packages??[]]));await this.updateConfiguredSources(a,s)}async updateConfiguredSources(t,e=!1){if(b()||t.length===0)return;const s=[],n=[];for(const p of t){const u=this.parseSource(p.source);if(u.type==="npm")u.pinned||s.push({...p,parsed:u});else if(u.type==="git"){const g=this.getStoredResolvedCommit(p.source,p.scope);if(!u.ref&&g&&!e)continue;n.push({...p,parsed:u})}}const r=s.map(p=>async()=>({entry:p,shouldUpdate:await this.shouldUpdateNpmSource(p.parsed,p.scope)})),i=await this.runWithConcurrency(r,ot),o=[],a=[];for(const p of i)p.shouldUpdate&&(p.entry.scope==="user"?o.push(p.entry):a.push(p.entry));const l=[];if(o.length>0&&l.push(this.updateNpmBatch(o,"user")),a.length>0&&l.push(this.updateNpmBatch(a,"project")),n.length>0){const p=n.map(u=>async()=>this.withProgress("update",u.source,`Updating ${u.source}...`,async()=>{if(await this.updateGit(u.parsed,u.scope),!this.getStoredResolvedCommit(u.source,u.scope))return;const P=this.getInstalledPath(u.source,u.scope),d=await this.readGitHead(P);d&&this.addSourceToSettings(u.source,{local:u.scope==="project",resolvedCommit:d})}));l.push(this.runWithConcurrency(p,Tt).then(()=>{}))}await Promise.all(l)}async shouldUpdateNpmSource(t,e){const s=this.getManagedNpmInstallPath(t,e),n=f(s)?this.getInstalledNpmVersion(s):void 0;if(!n)return!0;try{const r=await this.getLatestNpmVersion(t.version?t.spec:t.name,t.range);return st(r,n)}catch{return!0}}async updateNpmBatch(t,e){if(t.length===0)return;const s=t.length===1?t[0].source:`${e} npm packages`,n=t.length===1?`Updating ${t[0].source}...`:`Updating ${e} npm packages...`,r=t.map(i=>i.parsed.version?i.parsed.spec:`${i.parsed.name}@latest`);await this.withProgress("update",s,n,async()=>{await this.installNpmBatch(r,e)})}async installNpmBatch(t,e){const s=this.getNpmInstallRoot(e,!1);this.ensureNpmProject(s),await this.runNpmCommand(this.getNpmInstallArgs(t,s))}async checkForAvailableUpdates(){if(b())return[];const t=this.settingsManager.getGlobalSettings(),e=this.settingsManager.getProjectSettings(),s=[];for(const o of e.packages??[])s.push({pkg:o,scope:"project"});for(const o of t.packages??[])s.push({pkg:o,scope:"user"});const r=this.dedupePackages(s).filter(o=>o.scope!=="temporary").map(o=>async()=>{const a=typeof o.pkg=="string"?o.pkg:o.pkg.source,l=this.parseSource(a);if(l.type==="local"||l.pinned)return;if(l.type==="npm"){const g=this.getNpmInstallPath(l,o.scope);return!f(g)||!await this.npmHasAvailableUpdate(l,g)?void 0:{source:a,displayName:l.name,type:"npm",scope:o.scope}}const p=this.getGitInstallPath(l,o.scope);if(!(!f(p)||!await this.gitHasAvailableUpdate(p)))return{source:a,displayName:`${l.host}/${l.path}`,type:"git",scope:o.scope}});return(await this.runWithConcurrency(r,ot)).filter(o=>o!==void 0)}async resolvePackageSources(t,e,s){for(const{pkg:n,scope:r}of t){const i=typeof n=="string"?n:n.source,o=typeof n=="object"?n:void 0,a=this.findAutoloadDeltaBase(n,r,t),l=a?.source??i,p=a?.scope??r,u=this.parseSource(l),g={source:i,scope:r,origin:"package"};if(u.type==="local"){const d=this.getBaseDirForScope(p);this.resolveLocalExtensionSource(u,e,o,g,d);continue}const P=m(async()=>{if(b())return!1;if(!s)return await this.installParsedSource(u,p),!0;const d=await s(l);if(d==="skip")return!1;if(d==="error")throw new Error(`Missing source: ${l}`);return await this.installParsedSource(u,p),!0},"installMissing");if(u.type==="npm"){let d=this.getNpmInstallPath(u,p);if(!f(d)||!await this.installedNpmMatchesConfiguredVersion(u,d)){if(!await P())continue;d=this.getNpmInstallPath(u,p)}g.baseDir=d,g.packageRoot=d,this.collectPackageResources(d,e,o,g);continue}if(u.type==="git"){const d=this.getGitInstallPath(u,p);if(f(d))p==="temporary"&&!u.pinned&&!b()&&await this.refreshTemporaryGitSource(u,l);else if(!await P())continue;g.baseDir=d,g.packageRoot=d,this.collectPackageResources(d,e,o,g)}}}findAutoloadDeltaBase(t,e,s){if(e!=="project"||typeof t!="object"||t.autoload!==!1)return;const n=this.getPackageIdentity(t.source,e),r=s.find(i=>i.scope==="user"&&this.getPackageIdentity(this.getPackageSourceString(i.pkg),"user")===n);return r?{source:this.getPackageSourceString(r.pkg),scope:"user"}:void 0}resolveLocalExtensionSource(t,e,s,n,r){const i=this.resolvePathFromBase(t.path,r);if(f(i))try{const o=N(i);if(o.isFile()){n.baseDir=w(i),this.addResource(e.extensions,i,n,!0);return}o.isDirectory()&&(n.baseDir=i,n.packageRoot=i,this.collectPackageResources(i,e,s,n)||this.addResource(e.extensions,i,n,!0))}catch{return}}async installParsedSource(t,e){if(t.type==="npm"){await this.installNpm(t,e,e==="temporary");return}if(t.type==="git"){await this.installGit(t,e);return}}getPackageSourceString(t){return typeof t=="string"?t:t.source}getSourceMatchKeyForInput(t){const e=this.parseSource(t);return e.type==="npm"?`npm:${e.name}`:e.type==="git"?`git:${e.host}/${e.path}`:`local:${this.resolvePath(e.path)}`}getSourceMatchKeyForSettings(t,e){const s=this.parseSource(t);if(s.type==="npm")return`npm:${s.name}`;if(s.type==="git")return`git:${s.host}/${s.path}`;const n=this.getBaseDirForScope(e);return`local:${this.resolvePathFromBase(s.path,n)}`}buildNoMatchingPackageMessage(t,e){const s=this.findSuggestedConfiguredSource(t,e);return s?`No matching package found for ${t}. Did you mean ${s}?`:`No matching package found for ${t}`}findSuggestedConfiguredSource(t,e){const s=t.trim(),n=new Set;for(const r of e){const i=this.getPackageSourceString(r),o=this.parseSource(i);if(o.type==="npm"){(s===o.name||s===o.spec)&&n.add(i);continue}if(o.type==="git"){const a=`${o.host}/${o.path}`,l=o.ref?`${a}@${o.ref}`:void 0;(s===a||l&&s===l)&&n.add(i)}}return n.values().next().value}packageSourcesMatch(t,e,s){const n=this.getSourceMatchKeyForSettings(this.getPackageSourceString(t),s),r=this.getSourceMatchKeyForInput(e);return n===r}normalizePackageSourceForSettings(t,e){const s=this.parseSource(t);if(s.type!=="local")return t;const n=this.getBaseDirForScope(e),r=this.resolvePath(s.path);return k(n,r)||"."}parseSource(t){if(t.startsWith("npm:")){const s=t.slice(4).trim(),{name:n,version:r}=this.parseNpmSpec(s);return{type:"npm",spec:s,name:n,version:r,range:Ut(r),pinned:Ht(r)}}if($t(t))return{type:"local",path:t};const e=jt(t);return e||{type:"local",path:t}}async installedNpmMatchesConfiguredVersion(t,e){const s=this.getInstalledNpmVersion(e);return s?t.range?Et(s,t.range):!0:!1}async npmHasAvailableUpdate(t,e){if(b())return!1;const s=this.getInstalledNpmVersion(e);if(!s)return!1;try{const n=await this.getLatestNpmVersion(t.version?t.spec:t.name,t.range);return st(n,s)}catch{return!1}}getInstalledNpmVersion(t){const e=h(t,"package.json");if(f(e))try{const s=H(e,"utf-8");return JSON.parse(it(s)).version}catch{return}}async getLatestNpmVersion(t,e){const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(["view",t,"version","--json"],this.cwd),i=(await this.runCommandCapture(s.command,[...s.args,...n],{cwd:this.cwd,timeoutMs:C})).trim();if(!i)throw new Error("Empty response from npm view");const o=JSON.parse(i);if(typeof o=="string")return o;if(Array.isArray(o)){const a=o.filter(p=>typeof p=="string"&&p.length>0),l=e?Ct(a,e):[...a].sort(Nt)[0];if(l)return l}throw new Error("Unexpected response from npm view")}async gitHasAvailableUpdate(t){if(b())return!1;try{const e=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:C}),s=await this.getRemoteGitHead(t);return e.trim()!==s.trim()}catch{return!1}}async getRemoteGitHead(t){const e=await this.getGitUpstreamRef(t);if(e){const i=(await this.runGitRemoteCommand(t,["ls-remote","origin",e])).match(/^([0-9a-f]{40})\s+/m);if(i?.[1])return i[1]}const n=(await this.runGitRemoteCommand(t,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!n?.[1])throw new Error("Failed to determine remote HEAD");return n[1]}async getLocalGitUpdateTarget(t){try{const s=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:t,timeoutMs:C})).trim();if(!s.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${s}`);const n=s.slice(7);if(!n)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:t,timeoutMs:C}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${n}:refs/remotes/origin/${n}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:t}).catch(()=>{});const e=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:t,timeoutMs:C}),n=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:t,timeoutMs:C}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return n?{ref:"origin/HEAD",head:e,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${n}:refs/remotes/origin/${n}`]}:{ref:"origin/HEAD",head:e,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(t){try{const s=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:t,timeoutMs:C})).trim();if(!s.startsWith("origin/"))return;const n=s.slice(7);return n?`refs/heads/${n}`:void 0}catch{return}}runGitRemoteCommand(t,e){return this.runCommandCapture("git",e,{cwd:t,timeoutMs:C,env:{GIT_TERMINAL_PROMPT:"0"}})}async runWithConcurrency(t,e){if(t.length===0)return[];const s=new Array(t.length);let n=0;const r=Math.max(1,Math.min(e,t.length)),i=m(async()=>{for(;;){const o=n;if(n+=1,o>=t.length)return;s[o]=await t[o]()}},"worker");return await Promise.all(Array.from({length:r},()=>i())),s}getPackageIdentity(t,e){const s=this.parseSource(t);if(s.type==="npm")return`npm:${s.name}`;if(s.type==="git")return`git:${s.host}/${s.path}`;if(e){const n=this.getBaseDirForScope(e);return`local:${this.resolvePathFromBase(s.path,n)}`}return`local:${this.resolvePath(s.path)}`}dedupePackages(t){const e=[],s=new Map;for(const n of t){const r=this.getPackageIdentity(this.getPackageSourceString(n.pkg),n.scope),i=s.get(r);if(i===void 0){s.set(r,e.length),e.push(n);continue}const o=e[i];o?.scope==="project"&&n.scope==="user"?typeof o.pkg=="object"&&o.pkg.autoload===!1&&e.push(n):n.scope==="project"&&(e[i]=n)}return e}parseNpmSpec(t){const e=t.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!e)return{name:t};const s=e[1]??t,n=e[2];return{name:s,version:n}}assertProjectTrustedForScope(t){if(t==="project"&&!this.settingsManager.isProjectTrusted())throw new Error("Project is not trusted; refusing to access project package storage")}getNpmCommand(){const t=this.settingsManager.getNpmCommand();if(!t||t.length===0)return{command:"npm",args:[]};const[e,...s]=t;if(!e)throw new Error("Invalid npmCommand: first array entry must be a non-empty command");return{command:e,args:s}}getPackageManagerName(){const t=this.getNpmCommand(),e=m(o=>$(o).replace(/\.(cmd|exe)$/i,""),"normalizeCommandName"),s=new Set(["npm","pnpm","bun"]),n=e(t.command),r=t.args.lastIndexOf("--");if(r>=0){const o=t.args[r+1];return o?e(o):n}if(s.has(n))return n;const i=[...new Set(t.args.map(e).filter(o=>s.has(o)))];if(i.length>1)throw new Error(`Ambiguous npmCommand package managers: ${i.join(", ")}`);return i[0]??n}async runNpmCommand(t,e){const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(t,e?.cwd);await this.runCommand(s.command,[...s.args,...n],e)}async applyNpmArgsHook(t,e){const s=globalThis[Wt];return typeof s!="function"?t:s(t,{cwd:e,packageManager:this.getPackageManagerName()})}getGitDependencyInstallArgs(){switch(this.getPackageManagerName()){case"bun":return["install","--omit=dev","--omit=peer"];case"pnpm":return["install","--prod","--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"];case"npm":return["install","--omit=dev","--legacy-peer-deps"];default:return["install"]}}runNpmCommandSync(t){const e=this.getNpmCommand();return this.runCommandSync(e.command,[...e.args,...t])}getNpmInstallArgs(t,e){const s=this.getPackageManagerName();return s==="bun"?["install",...t,"--cwd",e,"--omit=peer"]:s==="pnpm"?["install",...t,"--prefix",e,"--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"]:["install",...t,"--prefix",e,"--legacy-peer-deps"]}async installNpm(t,e,s){const n=this.getNpmInstallRoot(e,s);this.ensureNpmProject(n),await this.runNpmCommand(this.getNpmInstallArgs([t.spec],n))}async uninstallNpm(t,e){const s=this.getNpmInstallRoot(e,!1);if(!f(s))return;const n=this.getPackageManagerName();if(n==="bun"){await this.runNpmCommand(["uninstall",t.name,"--cwd",s]);return}const r=["uninstall",t.name,"--prefix",s];n!=="pnpm"&&r.push("--legacy-peer-deps"),await this.runNpmCommand(r)}async installGit(t,e){const s=this.getGitInstallPath(t,e);if(f(s)){if(t.ref){await this.ensureGitRef(s,["fetch","origin",t.ref],"FETCH_HEAD");return}const r=await this.getLocalGitUpdateTarget(s);await this.ensureGitRef(s,r.fetchArgs,r.ref);return}const n=this.getGitInstallRoot(e);n&&this.ensureGitIgnore(n),W(w(s),{recursive:!0}),I(this.getGitUpdateMarkerPath(s),{force:!0});try{await this.runCommand("git",["clone",t.repo,s]),t.ref&&await this.runCommand("git",["checkout",t.ref],{cwd:s});const r=h(s,"package.json");f(r)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:s})}catch(r){throw I(s,{recursive:!0,force:!0}),this.pruneEmptyGitParents(s,n),r}}async updateGit(t,e){const s=this.getGitInstallPath(t,e);if(!f(s)){await this.installGit(t,e);return}if(t.ref){await this.ensureGitRef(s,["fetch","origin",t.ref],"FETCH_HEAD");return}const n=await this.getLocalGitUpdateTarget(s);await this.ensureGitRef(s,n.fetchArgs,n.ref)}hasMissingGitDependencies(t){const e=h(t,"package.json");if(!f(e))return!1;try{const s=JSON.parse(it(H(e,"utf-8")));if(!s.dependencies||typeof s.dependencies!="object"||Array.isArray(s.dependencies))return!1;const n=S(t,"node_modules");return Object.keys(s.dependencies).some(r=>{const i=S(n,r);return i.startsWith(`${n}${U}`)?!f(i):!1})}catch{return!1}}async repairMissingGitDependencies(t){this.hasMissingGitDependencies(t)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:t})}getGitUpdateMarkerPath(t){return h(w(t),`.${$(t)}.pi-update-incomplete`)}async cleanAndInstallGitDependencies(t,e){try{await this.runCommand("git",["clean","-fdx"],{cwd:t})}catch(n){throw await this.repairMissingGitDependencies(t).catch(()=>{}),n}const s=h(t,"package.json");f(s)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:t}),I(e,{force:!0})}async ensureGitRef(t,e,s){await this.runCommand("git",e,{cwd:t});const n=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:C}),r=`${s}^{commit}`,i=await this.runCommandCapture("git",["rev-parse",r],{cwd:t,timeoutMs:C}),o=this.getGitUpdateMarkerPath(t);if(n.trim()===i.trim()){f(o)?await this.cleanAndInstallGitDependencies(t,o):await this.repairMissingGitDependencies(t);return}z(o,"","utf-8"),await this.runCommand("git",["reset","--hard",r],{cwd:t}),await this.cleanAndInstallGitDependencies(t,o)}async refreshTemporaryGitSource(t,e){if(!b())try{await this.withProgress("pull",e,`Refreshing ${e}...`,async()=>{await this.updateGit(t,"temporary")})}catch{}}async removeGit(t,e){const s=this.getGitInstallPath(t,e);I(s,{recursive:!0,force:!0}),I(this.getGitUpdateMarkerPath(s),{force:!0}),this.pruneEmptyGitParents(s,this.getGitInstallRoot(e))}pruneEmptyGitParents(t,e){if(!e)return;const s=S(e);let n=w(t);for(;n.startsWith(s)&&n!==s;){if(!f(n)){n=w(n);continue}if(x(n).length>0)break;try{I(n,{recursive:!0,force:!0})}catch{break}n=w(n)}}ensureNpmProject(t){f(t)||W(t,{recursive:!0}),Gt(t),this.ensureGitIgnore(t);const e=h(t,"package.json");f(e)||z(e,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(t){f(t)||W(t,{recursive:!0});const e=h(t,".gitignore");f(e)||z(e,`*
1
+ var wt=Object.defineProperty;var g=(c,t)=>wt(c,"name",{value:t,configurable:!0});import{createHash as kt}from"node:crypto";import{chmodSync as St,existsSync as f,globSync as vt,mkdirSync as H,readdirSync as x,readFileSync as $,rmSync as j,statSync as N,writeFileSync as z}from"node:fs";import{homedir as Mt}from"node:os";function Y(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{const c=$("/proc/self/environ","utf-8"),t={};for(const e of c.split("\0")){const s=e.indexOf("=");s>0&&(t[e.slice(0,s)]=e.slice(s+1))}return t}catch{return process.env}}g(Y,"getEnv");import{basename as A,dirname as w,join as h,relative as k,resolve as S,sep as U}from"node:path";import G from"ignore";import{minimatch as I}from"minimatch";import{gt as nt,maxSatisfying as Ct,rcompare as Nt,satisfies as Et,valid as bt,validRange as Ft}from"semver";import{CONFIG_DIR_NAME as D,isOfficialExtensionsPackage as xt,SHARED_SKILL_CONFIG_DIRS as rt}from"../config.js";import{spawnProcess as it,spawnProcessSync as jt}from"../utils/child-process.js";import{parseGitUrl as It}from"../utils/git.js";import{isOfflineModeEnabled as b}from"../utils/offline.js";import{canonicalizePath as Rt,isLocalPath as $t,markPathIgnoredByCloudSync as At,resolvePath as _}from"../utils/paths.js";import{stripBom as X}from"../utils/text.js";import{isStdoutTakenOver as Gt}from"./output-guard.js";import{findNearestPiManifest as Dt,readPiManifest as L}from"./pi-manifest.js";import{BUILTIN_PATH_PREFIX as q}from"./source-info.js";const v=1e4,ot=4,Tt=4,Wt=Symbol.for("dalcode.packageManager.npmArgsHook");function Ht(c){return bt(c??"")!==null}g(Ht,"isExactNpmVersion");function Ut(c){return c?Ft(c)??void 0:void 0}g(Ut,"getNpmVersionRange");function at(c){return c.source==="builtin"?5:c.origin==="package"?4:(c.scope==="project"?0:2)+(c.source==="local"?0:1)}g(at,"resourcePrecedenceRank");const O=["extensions","skills","prompts","themes"],_t={extensions:/\.(ts|js)$/,skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/},Lt=[".gitignore",".ignore",".fdignore"];function y(c){return c.split(U).join("/")}g(y,"toPosixPath");function Q(){return process.env.HOME||Mt()}g(Q,"getHomeDir");function Ot(c){const t=h(c,"tmp","extensions");return H(t,{recursive:!0,mode:448}),St(t,448),t}g(Ot,"getExtensionTempFolder");function Bt(c,t){const e=c.trim();if(!e||e.startsWith("#")&&!e.startsWith("\\#"))return null;let s=c,n=!1;s.startsWith("!")?(n=!0,s=s.slice(1)):s.startsWith("\\!")&&(s=s.slice(1)),s.startsWith("/")&&(s=s.slice(1));const r=t?`${t}${s}`:s;return n?`!${r}`:r}g(Bt,"prefixIgnorePattern");function T(c,t,e){const s=k(e,t),n=s?`${y(s)}/`:"";for(const r of Lt){const i=h(t,r);if(f(i))try{const a=$(i,"utf-8").split(/\r?\n/).map(l=>Bt(l,n)).filter(l=>!!l);a.length>0&&c.add(a)}catch{}}}g(T,"addIgnoreRules");function Jt(c){return c.startsWith("!")||c.startsWith("+")||c.startsWith("-")||c.includes("*")||c.includes("?")}g(Jt,"isPattern");function Z(c){return c.startsWith("!")||c.startsWith("+")||c.startsWith("-")}g(Z,"isOverridePattern");function Vt(c){return c.includes("*")||c.includes("?")}g(Vt,"hasGlobPattern");function Kt(c,t){return vt(c,{cwd:t}).map(e=>S(t,e)).filter(e=>k(t,e).split(U).every(s=>s===".."||!s.startsWith("."))).sort((e,s)=>e<s?-1:e>s?1:0)}g(Kt,"expandPackageGlob");function zt(c){const t=[],e=[];for(const s of c)Jt(s)?e.push(s):t.push(s);return{plain:t,patterns:e}}g(zt,"splitPatterns");function ct(c,t,e=!0,s,n){const r=[];if(!f(c))return r;const i=n??c,o=s??G();T(o,c,i);try{const a=x(c,{withFileTypes:!0});for(const l of a){if(l.name.startsWith(".")||e&&l.name==="node_modules")continue;const p=h(c,l.name);let u=l.isDirectory(),m=l.isFile();if(l.isSymbolicLink())try{const F=N(p);u=F.isDirectory(),m=F.isFile()}catch{continue}const P=y(k(i,p)),d=u?`${P}/`:P;o.ignores(d)||(u?r.push(...ct(p,t,e,o,i)):m&&t.test(l.name)&&r.push(p))}}catch{}return r}g(ct,"collectFiles");function tt(c,t,e,s){const n=[];if(!f(c))return n;const r=s??c,i=e??G();T(i,c,r);try{const o=x(c,{withFileTypes:!0});for(const a of o){if(a.name!=="SKILL.md")continue;const l=h(c,a.name);let p=a.isFile();if(a.isSymbolicLink())try{p=N(l).isFile()}catch{continue}const u=y(k(r,l));if(p&&!i.ignores(u))return n.push(l),n}for(const a of o){if(a.name.startsWith(".")||a.name==="node_modules")continue;const l=h(c,a.name);let p=a.isDirectory(),u=a.isFile();if(a.isSymbolicLink())try{const d=N(l);p=d.isDirectory(),u=d.isFile()}catch{continue}const m=y(k(r,l));if(u&&a.name.endsWith(".md")&&!i.ignores(m)&&(t==="pi"&&c===r||t==="agents"&&c!==r)){n.push(l);continue}p&&(i.ignores(`${m}/`)||n.push(...tt(l,t,i,r)))}}catch{}return n}g(tt,"collectSkillEntries");function B(c,t){return tt(c,t)}g(B,"collectAutoSkillEntries");function Yt(c){let t=S(c);for(;;){if(f(h(t,".git")))return t;const e=w(t);if(e===t)return null;t=e}}g(Yt,"findGitRepoRoot");function Xt(c=Q()){return rt.map(t=>h(c,t,"skills"))}g(Xt,"userSharedSkillDirs");function qt(c){const t=[],e=S(c),s=Yt(e);let n=e;for(;;){for(const i of rt)t.push(h(n,i,"skills"));if(s&&n===s)break;const r=w(n);if(r===n)break;n=r}return t}g(qt,"collectAncestorAgentsSkillDirs");function lt(c){const t=[];if(!f(c))return t;const e=G();T(e,c,c);try{const s=x(c,{withFileTypes:!0});for(const n of s){if(n.name.startsWith(".")||n.name==="node_modules")continue;const r=h(c,n.name);let i=n.isFile();if(n.isSymbolicLink())try{i=N(r).isFile()}catch{continue}const o=y(k(c,r));e.ignores(o)||i&&n.name.endsWith(".md")&&t.push(r)}}catch{}return t}g(lt,"collectAutoPromptEntries");function ut(c){const t=[];if(!f(c))return t;const e=G();T(e,c,c);try{const s=x(c,{withFileTypes:!0});for(const n of s){if(n.name.startsWith(".")||n.name==="node_modules")continue;const r=h(c,n.name);let i=n.isFile();if(n.isSymbolicLink())try{i=N(r).isFile()}catch{continue}const o=y(k(c,r));e.ignores(o)||i&&n.name.endsWith(".json")&&t.push(r)}}catch{}return t}g(ut,"collectAutoThemeEntries");function pt(c){const t=h(c,"package.json");if(f(t)){const n=L(t);if(n?.extensions?.length){const r=[];for(const i of n.extensions){const o=S(c,i);f(o)&&r.push(o)}if(r.length>0)return r}}const e=h(c,"index.ts"),s=h(c,"index.js");return f(e)?[e]:f(s)?[s]:null}g(pt,"resolveExtensionEntries");function et(c){const t=[];if(!f(c))return t;const e=pt(c);if(e)return e;const s=G();T(s,c,c);try{const n=x(c,{withFileTypes:!0});for(const r of n){if(r.name.startsWith(".")||r.name==="node_modules")continue;const i=h(c,r.name);let o=r.isDirectory(),a=r.isFile();if(r.isSymbolicLink())try{const u=N(i);o=u.isDirectory(),a=u.isFile()}catch{continue}const l=y(k(c,i)),p=o?`${l}/`:l;if(!s.ignores(p)){if(a&&(r.name.endsWith(".ts")||r.name.endsWith(".js")))t.push(i);else if(o){const u=pt(i);u&&t.push(...u)}}}}catch{}return t}g(et,"collectAutoExtensionEntries");function J(c,t){return t==="skills"?tt(c,"pi"):t==="extensions"?et(c):ct(c,_t[t])}g(J,"collectResourceFiles");function V(c,t,e){const s=y(k(e,c)),n=A(c),r=y(c),i=n==="SKILL.md",o=i?w(c):void 0,a=i?y(k(e,o)):void 0,l=i?A(o):void 0,p=i?y(o):void 0;return t.some(u=>{const m=y(u);return I(s,m)||I(n,m)||I(r,m)?!0:i?I(a,m)||I(l,m)||I(p,m):!1})}g(V,"matchesAnyPattern");function Qt(c){const t=c.startsWith("./")||c.startsWith(".\\")?c.slice(2):c;return y(t)}g(Qt,"normalizeExactPattern");function W(c,t,e){if(t.length===0)return!1;const s=y(k(e,c)),n=A(c),r=y(c),i=n==="SKILL.md",o=i?w(c):void 0,a=i?y(k(e,o)):void 0,l=i?y(o):void 0;return t.some(p=>{const u=Qt(p);return u===s||u===r?!0:i?u===a||u===l:!1})}g(W,"matchesAnyExactPattern");function ht(c){return c.filter(t=>t.startsWith("!")||t.startsWith("+")||t.startsWith("-"))}g(ht,"getOverridePatterns");function ft(c,t,e){const s=ht(t),n=s.filter(a=>a.startsWith("!")).map(a=>a.slice(1)),r=s.filter(a=>a.startsWith("+")).map(a=>a.slice(1)),i=s.filter(a=>a.startsWith("-")).map(a=>a.slice(1));let o=!0;return n.length>0&&V(c,n,e)&&(o=!1),r.length>0&&W(c,r,e)&&(o=!0),i.length>0&&W(c,i,e)&&(o=!1),o}g(ft,"isEnabledByOverrides");function K(c,t,e){const s=[],n=[],r=[],i=[];for(const a of t)a.startsWith("+")?r.push(a.slice(1)):a.startsWith("-")?i.push(a.slice(1)):a.startsWith("!")?n.push(a.slice(1)):s.push(a);let o;if(s.length===0?o=[...c]:o=c.filter(a=>V(a,s,e)),n.length>0&&(o=o.filter(a=>!V(a,n,e))),r.length>0)for(const a of c)!o.includes(a)&&W(a,r,e)&&o.push(a);return i.length>0&&(o=o.filter(a=>!W(a,i,e))),new Set(o)}g(K,"applyPatterns");function gt(c,t,e){const s=new Map;for(const n of t){const r=n.slice(n.startsWith("+")||n.startsWith("-")||n.startsWith("!")?1:0),i=!n.startsWith("-")&&!n.startsWith("!"),o=n.startsWith("+")||n.startsWith("-");for(const a of c)(o?W(a,[r],e):V(a,[r],e))&&s.set(a,i)}return s}g(gt,"applyAutoloadDisabledPatterns");class de{static{g(this,"DefaultPackageManager")}cwd;agentDir;settingsManager;builtinExtensions;globalNpmRoot;globalNpmRootCommandKey;progressCallback;constructor(t){this.cwd=_(t.cwd),this.agentDir=_(t.agentDir),this.settingsManager=t.settingsManager,this.builtinExtensions=t.builtinExtensions??[]}setProgressCallback(t){this.progressCallback=t}addSourceToSettings(t,e){const s=e?.local?"project":"user",r=(s==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],i=this.normalizePackageSourceForSettings(t,s),o=g(p=>{const u=e?.resolvedCommit;return!u&&!p?i:typeof p=="string"||p===void 0?u?{source:i,resolvedCommit:u}:i:u?{...p,source:i,resolvedCommit:u}:{...p,source:i}},"toEntry"),a=r.findIndex(p=>this.packageSourcesMatch(p,t,s));if(a!==-1){const p=r[a];if(this.getPackageSourceString(p)===i&&!e?.resolvedCommit)return!1;const u=[...r];return u[a]=o(p),s==="project"?this.settingsManager.setProjectPackages(u):this.settingsManager.setPackages(u),!0}const l=[...r,o()];return s==="project"?this.settingsManager.setProjectPackages(l):this.settingsManager.setPackages(l),!0}removeSourceFromSettings(t,e){const s=e?.local?"project":"user",r=(s==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],i=r.filter(a=>!this.packageSourcesMatch(a,t,s));return i.length!==r.length?(s==="project"?this.settingsManager.setProjectPackages(i):this.settingsManager.setPackages(i),!0):!1}getInstalledPath(t,e){const s=this.parseSource(t);if(s.type==="npm"){const n=this.getNpmInstallPath(s,e);return f(n)?n:void 0}if(s.type==="git"){const n=this.getGitInstallPath(s,e);return f(n)?n:void 0}if(s.type==="local"){const n=this.getBaseDirForScope(e),r=this.resolvePathFromBase(s.path,n);return f(r)?r:void 0}}async getRegistryIntegrity(t){const e=this.parseSource(t);if(e.type!=="npm"||!e.pinned)return;const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(["view",e.spec,"dist.integrity","--json"],this.cwd),i=(await this.runCommandCapture(s.command,[...s.args,...n],{cwd:this.cwd,timeoutMs:v})).trim();if(!i)return;const o=JSON.parse(i);return typeof o=="string"&&o.length>0?o:void 0}getRecordedIntegrity(t,e){const s=this.getNpmInstallRoot(e,!1),n=h(s,"package-lock.json");if(!f(n))return;let r;try{r=JSON.parse(X($(n,"utf-8")))}catch{return null}if(!r||typeof r!="object")return null;const o=r.packages?.[`node_modules/${t}`];if(!o||typeof o!="object")return null;const a=o.integrity;return typeof a=="string"&&a.length>0?a:null}readDeclaredPermissions(t){if(!t)return;const s=Dt(t)?.manifest.permissions;return s&&s.length>0?[...s]:void 0}async readGitHead(t){if(t)try{const s=(await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:v})).trim();return/^[0-9a-f]{7,40}$/i.test(s)?s:void 0}catch{return}}getStoredResolvedCommit(t,e){const s=e==="project"?this.settingsManager.getProjectSettings().packages??[]:this.settingsManager.getGlobalSettings().packages??[];for(const n of s)if(typeof n!="string"&&this.packageSourcesMatch(n,t,e))return n.resolvedCommit}emitProgress(t){this.progressCallback?.(t)}async withProgress(t,e,s,n){this.emitProgress({type:"start",action:t,source:e,message:s});try{await n(),this.emitProgress({type:"complete",action:t,source:e})}catch(r){const i=r instanceof Error?r.message:String(r);throw this.emitProgress({type:"error",action:t,source:e,message:i}),r}}async resolve(t){const e=this.createAccumulator(),s=this.settingsManager.getGlobalSettings(),n=this.settingsManager.getProjectSettings(),r=[];for(const l of n.packages??[])r.push({pkg:l,scope:"project"});for(const l of s.packages??[])r.push({pkg:l,scope:"user"});const i=this.dedupePackages(r);await this.resolvePackageSources(i,e,t);const o=this.agentDir,a=h(this.cwd,D);for(const l of O){const p=this.getTargetMap(e,l),u=s[l]??[],m=n[l]??[];this.resolveLocalEntries(m,l,p,{source:"local",scope:"project",origin:"top-level"},a),this.resolveLocalEntries(u,l,p,{source:"local",scope:"user",origin:"top-level"},o)}this.addAutoDiscoveredResources(e,s,n,o,a);for(const l of this.builtinExtensions){const p=`${q}${l}`,u=gt([p],ht(n.extensions??[]),a).get(p);this.addResource(e.extensions,p,{source:"builtin",scope:u===void 0?"user":"project",origin:"top-level"},u??ft(p,s.extensions??[],o))}return this.toResolvedPaths(e)}async resolveExtensionSources(t,e){const s=this.createAccumulator(),n=e?.temporary?"temporary":e?.local?"project":"user";for(const i of t.filter(o=>o.startsWith(q)))this.addResource(s.extensions,i,{source:"builtin",scope:n,origin:"top-level"},!0);const r=t.filter(i=>!i.startsWith(q)).map(i=>({pkg:i,scope:n}));return await this.resolvePackageSources(r,s),this.toResolvedPaths(s)}listConfiguredPackages(){const t=this.settingsManager.getGlobalSettings(),e=this.settingsManager.getProjectSettings(),s=[];for(const n of t.packages??[]){const r=typeof n=="string"?n:n.source,i=this.getInstalledPath(r,"user");s.push({source:r,scope:"user",filtered:typeof n=="object",installedPath:i,resolvedCommit:typeof n=="object"?n.resolvedCommit:void 0,permissions:this.readDeclaredPermissions(i)})}for(const n of e.packages??[]){const r=typeof n=="string"?n:n.source,i=this.getInstalledPath(r,"project");s.push({source:r,scope:"project",filtered:typeof n=="object",installedPath:i,resolvedCommit:typeof n=="object"?n.resolvedCommit:void 0,permissions:this.readDeclaredPermissions(i)})}return s}async install(t,e){const s=this.parseSource(t),n=e?.local?"project":"user";this.assertProjectTrustedForScope(n),await this.withProgress("install",t,`Installing ${t}...`,async()=>{if(s.type==="npm"){await this.installNpm(s,n,!1);return}if(s.type==="git"){await this.installGit(s,n);return}if(s.type==="local"){const r=this.resolvePath(s.path);if(!f(r))throw new Error(`Path does not exist: ${r}`);return}throw new Error(`Unsupported install source: ${t}`)})}async installAndPersist(t,e){await this.install(t,e);const s=e?.local?"project":"user",n=this.getInstalledPath(t,s),r=await this.readGitHead(n);this.addSourceToSettings(t,{...e,resolvedCommit:r})}async remove(t,e){const s=this.parseSource(t),n=e?.local?"project":"user";this.assertProjectTrustedForScope(n),await this.withProgress("remove",t,`Removing ${t}...`,async()=>{if(s.type==="npm"){await this.uninstallNpm(s,n);return}if(s.type==="git"){await this.removeGit(s,n);return}if(s.type!=="local")throw new Error(`Unsupported remove source: ${t}`)})}async removeAndPersist(t,e){return await this.remove(t,e),this.removeSourceFromSettings(t,e)}async update(t,e){const s=e?.latest===!0,n=this.settingsManager.getGlobalSettings(),r=this.settingsManager.getProjectSettings(),i=t?this.getPackageIdentity(t):void 0;let o=!1;const a=[];for(const l of n.packages??[]){const p=typeof l=="string"?l:l.source;i&&this.getPackageIdentity(p,"user")!==i||(o=!0,a.push({source:p,scope:"user"}))}for(const l of r.packages??[]){const p=typeof l=="string"?l:l.source;i&&this.getPackageIdentity(p,"project")!==i||(o=!0,a.push({source:p,scope:"project"}))}if(t&&!o)throw new Error(this.buildNoMatchingPackageMessage(t,[...n.packages??[],...r.packages??[]]));await this.updateConfiguredSources(a,s)}async updateConfiguredSources(t,e=!1){if(b()||t.length===0)return;const s=[],n=[];for(const p of t){const u=this.parseSource(p.source);if(u.type==="npm")u.pinned||s.push({...p,parsed:u});else if(u.type==="git"){const m=this.getStoredResolvedCommit(p.source,p.scope);if(!u.ref&&m&&!e)continue;n.push({...p,parsed:u})}}const r=s.map(p=>async()=>({entry:p,shouldUpdate:await this.shouldUpdateNpmSource(p.parsed,p.scope)})),i=await this.runWithConcurrency(r,ot),o=[],a=[];for(const p of i)p.shouldUpdate&&(p.entry.scope==="user"?o.push(p.entry):a.push(p.entry));const l=[];if(o.length>0&&l.push(this.updateNpmBatch(o,"user")),a.length>0&&l.push(this.updateNpmBatch(a,"project")),n.length>0){const p=n.map(u=>async()=>this.withProgress("update",u.source,`Updating ${u.source}...`,async()=>{if(await this.updateGit(u.parsed,u.scope),!this.getStoredResolvedCommit(u.source,u.scope))return;const P=this.getInstalledPath(u.source,u.scope),d=await this.readGitHead(P);d&&this.addSourceToSettings(u.source,{local:u.scope==="project",resolvedCommit:d})}));l.push(this.runWithConcurrency(p,Tt).then(()=>{}))}await Promise.all(l)}async shouldUpdateNpmSource(t,e){const s=this.getManagedNpmInstallPath(t,e),n=f(s)?this.getInstalledNpmVersion(s):void 0;if(!n)return!0;try{const r=await this.getLatestNpmVersion(t.version?t.spec:t.name,t.range);return nt(r,n)}catch{return!0}}async updateNpmBatch(t,e){if(t.length===0)return;const s=t.length===1?t[0].source:`${e} npm packages`,n=t.length===1?`Updating ${t[0].source}...`:`Updating ${e} npm packages...`,r=t.map(i=>i.parsed.version?i.parsed.spec:`${i.parsed.name}@latest`);await this.withProgress("update",s,n,async()=>{await this.installNpmBatch(r,e)})}async installNpmBatch(t,e){const s=this.getNpmInstallRoot(e,!1);this.ensureNpmProject(s),await this.runNpmCommand(this.getNpmInstallArgs(t,s))}async checkForAvailableUpdates(){if(b())return[];const t=this.settingsManager.getGlobalSettings(),e=this.settingsManager.getProjectSettings(),s=[];for(const o of e.packages??[])s.push({pkg:o,scope:"project"});for(const o of t.packages??[])s.push({pkg:o,scope:"user"});const r=this.dedupePackages(s).filter(o=>o.scope!=="temporary").map(o=>async()=>{const a=typeof o.pkg=="string"?o.pkg:o.pkg.source,l=this.parseSource(a);if(l.type==="local"||l.pinned)return;if(l.type==="npm"){const m=this.getNpmInstallPath(l,o.scope);return!f(m)||!await this.npmHasAvailableUpdate(l,m)?void 0:{source:a,displayName:l.name,type:"npm",scope:o.scope}}const p=this.getGitInstallPath(l,o.scope);if(!(!f(p)||!await this.gitHasAvailableUpdate(p)))return{source:a,displayName:`${l.host}/${l.path}`,type:"git",scope:o.scope}});return(await this.runWithConcurrency(r,ot)).filter(o=>o!==void 0)}async resolvePackageSources(t,e,s){for(const{pkg:n,scope:r}of t){const i=typeof n=="string"?n:n.source,o=typeof n=="object"?n:void 0,a=this.findAutoloadDeltaBase(n,r,t),l=a?.source??i,p=a?.scope??r,u=this.parseSource(l),m={source:i,scope:r,origin:"package"};if(u.type==="local"){const d=this.getBaseDirForScope(p);this.resolveLocalExtensionSource(u,e,o,m,d);continue}const P=g(async()=>{if(b())return!1;if(!s)return await this.installParsedSource(u,p),!0;const d=await s(l);if(d==="skip")return!1;if(d==="error")throw new Error(`Missing source: ${l}`);return await this.installParsedSource(u,p),!0},"installMissing");if(u.type==="npm"){let d=this.getNpmInstallPath(u,p);if(!f(d)||!await this.installedNpmMatchesConfiguredVersion(u,d)){if(!await P())continue;d=this.getNpmInstallPath(u,p)}m.baseDir=d,m.packageRoot=d,this.collectPackageResources(d,e,o,m);continue}if(u.type==="git"){const d=this.getGitInstallPath(u,p);if(f(d))p==="temporary"&&!u.pinned&&!b()&&await this.refreshTemporaryGitSource(u,l);else if(!await P())continue;m.baseDir=d,m.packageRoot=d,this.collectPackageResources(d,e,o,m)}}}findAutoloadDeltaBase(t,e,s){if(e!=="project"||typeof t!="object"||t.autoload!==!1)return;const n=this.getPackageIdentity(t.source,e),r=s.find(i=>i.scope==="user"&&this.getPackageIdentity(this.getPackageSourceString(i.pkg),"user")===n);return r?{source:this.getPackageSourceString(r.pkg),scope:"user"}:void 0}resolveLocalExtensionSource(t,e,s,n,r){const i=this.resolvePathFromBase(t.path,r);if(f(i))try{const o=N(i);if(o.isFile()){n.baseDir=w(i),this.addResource(e.extensions,i,n,!0);return}o.isDirectory()&&(n.baseDir=i,n.packageRoot=i,this.collectPackageResources(i,e,s,n)||this.addResource(e.extensions,i,n,!0))}catch{return}}async installParsedSource(t,e){if(t.type==="npm"){await this.installNpm(t,e,e==="temporary");return}if(t.type==="git"){await this.installGit(t,e);return}}getPackageSourceString(t){return typeof t=="string"?t:t.source}getSourceMatchKeyForInput(t){const e=this.parseSource(t);return e.type==="npm"?`npm:${e.name}`:e.type==="git"?`git:${e.host}/${e.path}`:`local:${this.resolvePath(e.path)}`}getSourceMatchKeyForSettings(t,e){const s=this.parseSource(t);if(s.type==="npm")return`npm:${s.name}`;if(s.type==="git")return`git:${s.host}/${s.path}`;const n=this.getBaseDirForScope(e);return`local:${this.resolvePathFromBase(s.path,n)}`}buildNoMatchingPackageMessage(t,e){const s=this.findSuggestedConfiguredSource(t,e);return s?`No matching package found for ${t}. Did you mean ${s}?`:`No matching package found for ${t}`}findSuggestedConfiguredSource(t,e){const s=t.trim(),n=new Set;for(const r of e){const i=this.getPackageSourceString(r),o=this.parseSource(i);if(o.type==="npm"){(s===o.name||s===o.spec)&&n.add(i);continue}if(o.type==="git"){const a=`${o.host}/${o.path}`,l=o.ref?`${a}@${o.ref}`:void 0;(s===a||l&&s===l)&&n.add(i)}}return n.values().next().value}packageSourcesMatch(t,e,s){const n=this.getSourceMatchKeyForSettings(this.getPackageSourceString(t),s),r=this.getSourceMatchKeyForInput(e);return n===r}normalizePackageSourceForSettings(t,e){const s=this.parseSource(t);if(s.type!=="local")return t;const n=this.getBaseDirForScope(e),r=this.resolvePath(s.path);return k(n,r)||"."}parseSource(t){if(t.startsWith("npm:")){const s=t.slice(4).trim(),{name:n,version:r}=this.parseNpmSpec(s);return{type:"npm",spec:s,name:n,version:r,range:Ut(r),pinned:Ht(r)}}if($t(t))return{type:"local",path:t};const e=It(t);return e||{type:"local",path:t}}async installedNpmMatchesConfiguredVersion(t,e){const s=this.getInstalledNpmVersion(e);return s?t.range?Et(s,t.range):!0:!1}async npmHasAvailableUpdate(t,e){if(b())return!1;const s=this.getInstalledNpmVersion(e);if(!s)return!1;try{const n=await this.getLatestNpmVersion(t.version?t.spec:t.name,t.range);return nt(n,s)}catch{return!1}}getInstalledNpmVersion(t){const e=h(t,"package.json");if(f(e))try{const s=$(e,"utf-8");return JSON.parse(X(s)).version}catch{return}}async getLatestNpmVersion(t,e){const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(["view",t,"version","--json"],this.cwd),i=(await this.runCommandCapture(s.command,[...s.args,...n],{cwd:this.cwd,timeoutMs:v})).trim();if(!i)throw new Error("Empty response from npm view");const o=JSON.parse(i);if(typeof o=="string")return o;if(Array.isArray(o)){const a=o.filter(p=>typeof p=="string"&&p.length>0),l=e?Ct(a,e):[...a].sort(Nt)[0];if(l)return l}throw new Error("Unexpected response from npm view")}async gitHasAvailableUpdate(t){if(b())return!1;try{const e=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:v}),s=await this.getRemoteGitHead(t);return e.trim()!==s.trim()}catch{return!1}}async getRemoteGitHead(t){const e=await this.getGitUpstreamRef(t);if(e){const i=(await this.runGitRemoteCommand(t,["ls-remote","origin",e])).match(/^([0-9a-f]{40})\s+/m);if(i?.[1])return i[1]}const n=(await this.runGitRemoteCommand(t,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!n?.[1])throw new Error("Failed to determine remote HEAD");return n[1]}async getLocalGitUpdateTarget(t){try{const s=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:t,timeoutMs:v})).trim();if(!s.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${s}`);const n=s.slice(7);if(!n)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:t,timeoutMs:v}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${n}:refs/remotes/origin/${n}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:t}).catch(()=>{});const e=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:t,timeoutMs:v}),n=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:t,timeoutMs:v}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return n?{ref:"origin/HEAD",head:e,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${n}:refs/remotes/origin/${n}`]}:{ref:"origin/HEAD",head:e,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(t){try{const s=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:t,timeoutMs:v})).trim();if(!s.startsWith("origin/"))return;const n=s.slice(7);return n?`refs/heads/${n}`:void 0}catch{return}}runGitRemoteCommand(t,e){return this.runCommandCapture("git",e,{cwd:t,timeoutMs:v,env:{GIT_TERMINAL_PROMPT:"0"}})}async runWithConcurrency(t,e){if(t.length===0)return[];const s=new Array(t.length);let n=0;const r=Math.max(1,Math.min(e,t.length)),i=g(async()=>{for(;;){const o=n;if(n+=1,o>=t.length)return;s[o]=await t[o]()}},"worker");return await Promise.all(Array.from({length:r},()=>i())),s}getPackageIdentity(t,e){const s=this.parseSource(t);if(s.type==="npm")return`npm:${s.name}`;if(s.type==="git")return`git:${s.host}/${s.path}`;if(e){const n=this.getBaseDirForScope(e);return`local:${this.resolvePathFromBase(s.path,n)}`}return`local:${this.resolvePath(s.path)}`}dedupePackages(t){const e=[],s=new Map;for(const n of t){const r=this.getPackageIdentity(this.getPackageSourceString(n.pkg),n.scope),i=s.get(r);if(i===void 0){s.set(r,e.length),e.push(n);continue}const o=e[i];o?.scope==="project"&&n.scope==="user"?typeof o.pkg=="object"&&o.pkg.autoload===!1&&e.push(n):n.scope==="project"&&(e[i]=n)}return e}parseNpmSpec(t){const e=t.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!e)return{name:t};const s=e[1]??t,n=e[2];return{name:s,version:n}}assertProjectTrustedForScope(t){if(t==="project"&&!this.settingsManager.isProjectTrusted())throw new Error("Project is not trusted; refusing to access project package storage")}getNpmCommand(){const t=this.settingsManager.getNpmCommand();if(!t||t.length===0)return{command:"npm",args:[]};const[e,...s]=t;if(!e)throw new Error("Invalid npmCommand: first array entry must be a non-empty command");return{command:e,args:s}}getPackageManagerName(){const t=this.getNpmCommand(),e=g(o=>A(o).replace(/\.(cmd|exe)$/i,""),"normalizeCommandName"),s=new Set(["npm","pnpm","bun"]),n=e(t.command),r=t.args.lastIndexOf("--");if(r>=0){const o=t.args[r+1];return o?e(o):n}if(s.has(n))return n;const i=[...new Set(t.args.map(e).filter(o=>s.has(o)))];if(i.length>1)throw new Error(`Ambiguous npmCommand package managers: ${i.join(", ")}`);return i[0]??n}async runNpmCommand(t,e){const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(t,e?.cwd);await this.runCommand(s.command,[...s.args,...n],e)}async applyNpmArgsHook(t,e){const s=globalThis[Wt];return typeof s!="function"?t:s(t,{cwd:e,packageManager:this.getPackageManagerName()})}getGitDependencyInstallArgs(){switch(this.getPackageManagerName()){case"bun":return["install","--omit=dev","--omit=peer"];case"pnpm":return["install","--prod","--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"];case"npm":return["install","--omit=dev","--legacy-peer-deps"];default:return["install"]}}runNpmCommandSync(t){const e=this.getNpmCommand();return this.runCommandSync(e.command,[...e.args,...t])}getNpmInstallArgs(t,e){const s=this.getPackageManagerName();return s==="bun"?["install",...t,"--cwd",e,"--omit=peer"]:s==="pnpm"?["install",...t,"--prefix",e,"--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"]:["install",...t,"--prefix",e,"--legacy-peer-deps"]}async installNpm(t,e,s){const n=this.getNpmInstallRoot(e,s);this.ensureNpmProject(n),await this.runNpmCommand(this.getNpmInstallArgs([t.spec],n))}async uninstallNpm(t,e){const s=this.getNpmInstallRoot(e,!1);if(!f(s))return;const n=this.getPackageManagerName();if(n==="bun"){await this.runNpmCommand(["uninstall",t.name,"--cwd",s]);return}const r=["uninstall",t.name,"--prefix",s];n!=="pnpm"&&r.push("--legacy-peer-deps"),await this.runNpmCommand(r)}async installGit(t,e){const s=this.getGitInstallPath(t,e);if(f(s)){if(t.ref){await this.ensureGitRef(s,["fetch","origin",t.ref],"FETCH_HEAD");return}const r=await this.getLocalGitUpdateTarget(s);await this.ensureGitRef(s,r.fetchArgs,r.ref);return}const n=this.getGitInstallRoot(e);n&&this.ensureGitIgnore(n),H(w(s),{recursive:!0}),j(this.getGitUpdateMarkerPath(s),{force:!0});try{await this.runCommand("git",["clone",t.repo,s]),t.ref&&await this.runCommand("git",["checkout",t.ref],{cwd:s});const r=h(s,"package.json");f(r)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:s})}catch(r){throw j(s,{recursive:!0,force:!0}),this.pruneEmptyGitParents(s,n),r}}async updateGit(t,e){const s=this.getGitInstallPath(t,e);if(!f(s)){await this.installGit(t,e);return}if(t.ref){await this.ensureGitRef(s,["fetch","origin",t.ref],"FETCH_HEAD");return}const n=await this.getLocalGitUpdateTarget(s);await this.ensureGitRef(s,n.fetchArgs,n.ref)}hasMissingGitDependencies(t){const e=h(t,"package.json");if(!f(e))return!1;try{const s=JSON.parse(X($(e,"utf-8")));if(!s.dependencies||typeof s.dependencies!="object"||Array.isArray(s.dependencies))return!1;const n=S(t,"node_modules");return Object.keys(s.dependencies).some(r=>{const i=S(n,r);return i.startsWith(`${n}${U}`)?!f(i):!1})}catch{return!1}}async repairMissingGitDependencies(t){this.hasMissingGitDependencies(t)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:t})}getGitUpdateMarkerPath(t){return h(w(t),`.${A(t)}.pi-update-incomplete`)}async cleanAndInstallGitDependencies(t,e){try{await this.runCommand("git",["clean","-fdx"],{cwd:t})}catch(n){throw await this.repairMissingGitDependencies(t).catch(()=>{}),n}const s=h(t,"package.json");f(s)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:t}),j(e,{force:!0})}async ensureGitRef(t,e,s){await this.runCommand("git",e,{cwd:t});const n=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:v}),r=`${s}^{commit}`,i=await this.runCommandCapture("git",["rev-parse",r],{cwd:t,timeoutMs:v}),o=this.getGitUpdateMarkerPath(t);if(n.trim()===i.trim()){f(o)?await this.cleanAndInstallGitDependencies(t,o):await this.repairMissingGitDependencies(t);return}z(o,"","utf-8"),await this.runCommand("git",["reset","--hard",r],{cwd:t}),await this.cleanAndInstallGitDependencies(t,o)}async refreshTemporaryGitSource(t,e){if(!b())try{await this.withProgress("pull",e,`Refreshing ${e}...`,async()=>{await this.updateGit(t,"temporary")})}catch{}}async removeGit(t,e){const s=this.getGitInstallPath(t,e);j(s,{recursive:!0,force:!0}),j(this.getGitUpdateMarkerPath(s),{force:!0}),this.pruneEmptyGitParents(s,this.getGitInstallRoot(e))}pruneEmptyGitParents(t,e){if(!e)return;const s=S(e);let n=w(t);for(;n.startsWith(s)&&n!==s;){if(!f(n)){n=w(n);continue}if(x(n).length>0)break;try{j(n,{recursive:!0,force:!0})}catch{break}n=w(n)}}ensureNpmProject(t){f(t)||H(t,{recursive:!0}),At(t),this.ensureGitIgnore(t);const e=h(t,"package.json");f(e)||z(e,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(t){f(t)||H(t,{recursive:!0});const e=h(t,".gitignore");f(e)||z(e,`*
2
2
  !.gitignore
3
- `,"utf-8")}getNpmInstallRoot(t,e){return e?this.getTemporaryDir("npm"):t==="project"?(this.assertProjectTrustedForScope(t),h(this.cwd,A,"npm")):h(this.agentDir,"npm")}getGlobalNpmRoot(){const t=this.getNpmCommand(),e=[t.command,...t.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===e)return this.globalNpmRoot;if(this.getPackageManagerName()==="bun"){const s=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=h(w(s),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=e,this.globalNpmRoot}getPnpmGlobalPackagePath(t){if(this.getPackageManagerName()!=="pnpm")return;const e=this.runNpmCommandSync(["list","-g","--depth","0","--json"]),s=JSON.parse(e);for(const n of s){const r=n.dependencies?.[t]?.path;if(r)return r}}getManagedNpmInstallPath(t,e){return e==="temporary"?h(this.getTemporaryDir("npm"),"node_modules",t.name):e==="project"?(this.assertProjectTrustedForScope(e),h(this.cwd,A,"npm","node_modules",t.name)):h(this.agentDir,"npm","node_modules",t.name)}getLegacyGlobalNpmInstallPath(t){try{return this.getPnpmGlobalPackagePath(t.name)??h(this.getGlobalNpmRoot(),t.name)}catch{return}}getNpmInstallPath(t,e){const s=this.getManagedNpmInstallPath(t,e);if(e!=="user"||f(s))return s;const n=this.getLegacyGlobalNpmInstallPath(t);return n&&f(n)?n:s}getGitInstallPath(t,e){if(e==="temporary")return this.getTemporaryDir(`git-${t.host}`,t.path,t.ref);const s=this.getGitInstallRoot(e);if(!s)throw new Error("Missing git install root");return this.resolveManagedPath(s,t.host,t.path)}getGitInstallRoot(t){if(t!=="temporary")return t==="project"?(this.assertProjectTrustedForScope(t),h(this.cwd,A,"git")):h(this.agentDir,"git")}getTemporaryDir(t,e,s){const n=this.resolveManagedPath(Ot(this.agentDir),t),r=kt("sha256").update(`${t}-${e??""}${s?`@${s}`:""}`).digest("hex").slice(0,8);return this.resolveManagedPath(n,r,e??"")}resolveManagedPath(t,...e){const s=S(t),n=S(s,...e);if(n!==s&&!n.startsWith(`${s}${U}`))throw new Error(`Refusing to use path outside package install root: ${n}`);return n}getBaseDirForScope(t){return t==="project"?(this.assertProjectTrustedForScope(t),h(this.cwd,A)):t==="user"?this.agentDir:this.cwd}resolvePath(t){return L(t,this.cwd,{homeDir:q(),trim:!0})}resolvePathFromBase(t,e){return L(t,e,{homeDir:q(),trim:!0})}collectPackageResources(t,e,s,n){if(xt(t))return!0;if(s){for(const o of O){const a=s[o],l=this.getTargetMap(e,o);s.autoload===!1?this.applyPackageDeltaFilter(t,a??[],o,l,n):a!==void 0?this.applyPackageFilter(t,a,o,l,n):this.collectDefaultResources(t,o,l,n)}return!0}const r=_(h(t,"package.json"));if(r){for(const o of O){const a=r[o];this.addManifestEntries(a,t,o,this.getTargetMap(e,o),n)}return!0}let i=!1;for(const o of O){const a=h(t,o);if(f(a)){const l=V(a,o);for(const p of l)this.addResource(this.getTargetMap(e,o),p,n,!0);i=!0}}return i}collectDefaultResources(t,e,s,n){const i=_(h(t,"package.json"))?.[e];if(i){this.addManifestEntries(i,t,e,s,n);return}const o=h(t,e);if(f(o)){const a=V(o,e);for(const l of a)this.addResource(s,l,n,!0)}}applyPackageFilter(t,e,s,n,r){const{allFiles:i}=this.collectManifestFiles(t,s);if(e.length===0){for(const a of i)this.addResource(n,a,r,!1);return}const o=J(i,e,t);for(const a of i){const l=o.has(a);this.addResource(n,a,r,l)}}applyPackageDeltaFilter(t,e,s,n,r){if(e.length===0)return;const{allFiles:i}=this.collectManifestFiles(t,s),o=mt(i,e,t);for(const[a,l]of o)this.addResource(n,a,r,l)}collectManifestFiles(t,e){const n=_(h(t,"package.json"))?.[e];if(n&&n.length>0){const o=this.collectFilesFromManifestEntries(n,t,e),a=n.filter(Q),l=a.length>0?J(o,a,t):new Set(o);return{allFiles:Array.from(l),enabledByManifest:l}}const r=h(t,e);if(!f(r))return{allFiles:[],enabledByManifest:new Set};const i=V(r,e);return{allFiles:i,enabledByManifest:new Set(i)}}addManifestEntries(t,e,s,n,r){if(!t)return;const i=this.collectFilesFromManifestEntries(t,e,s),o=t.filter(Q),a=J(i,o,e);for(const l of i)a.has(l)&&this.addResource(n,l,r,!0)}collectFilesFromManifestEntries(t,e,s){const r=t.filter(i=>!Q(i)).flatMap(i=>Kt(i)?Jt(i,e):[S(e,i)]);return this.collectFilesFromPaths(r,s)}resolveLocalEntries(t,e,s,n,r){if(t.length===0)return;const{plain:i,patterns:o}=zt(t),a=i.map(u=>this.resolvePathFromBase(u,r)),l=this.collectFilesFromPaths(a,e),p=J(l,o,r);for(const u of l)this.addResource(s,u,n,p.has(u))}addAutoDiscoveredResources(t,e,s,n,r){const i={source:"auto",scope:"user",origin:"top-level",baseDir:n},o={source:"auto",scope:"project",origin:"top-level",baseDir:r},a={extensions:e.extensions??[],skills:e.skills??[],prompts:e.prompts??[],themes:e.themes??[]},l={extensions:s.extensions??[],skills:s.skills??[],prompts:s.prompts??[],themes:s.themes??[]},p={extensions:h(n,"extensions"),skills:h(n,"skills"),prompts:h(n,"prompts"),themes:h(n,"themes")},u={extensions:h(r,"extensions"),skills:h(r,"skills"),prompts:h(r,"prompts"),themes:h(r,"themes")},g=Xt(),P=new Set(g.map(M=>S(M))),d=this.settingsManager.isProjectTrusted(),F=d?qt(this.cwd).filter(M=>!P.has(S(M))):[],v=m((M,E,R,gt,dt)=>{const yt=this.getTargetMap(t,M);for(const et of E){const Pt=ft(et,gt,dt);this.addResource(yt,et,R,Pt)}},"addResources");d&&(v("extensions",tt(u.extensions),o,l.extensions,r),v("skills",B(u.skills,"pi"),o,l.skills,r));for(const M of F){const E=w(M),R={...o,baseDir:E};v("skills",B(M,"agents"),R,l.skills,E)}d&&(v("prompts",lt(u.prompts),o,l.prompts,r),v("themes",ut(u.themes),o,l.themes,r)),v("extensions",tt(p.extensions),i,a.extensions,n),v("skills",B(p.skills,"pi"),i,a.skills,n);for(const M of g){const E=w(M),R={...i,baseDir:E};v("skills",B(M,"agents"),R,a.skills,E)}v("prompts",lt(p.prompts),i,a.prompts,n),v("themes",ut(p.themes),i,a.themes,n)}collectFilesFromPaths(t,e){const s=[];for(const n of t)if(f(n))try{const r=N(n);r.isFile()?s.push(n):r.isDirectory()&&s.push(...V(n,e))}catch{}return s}getTargetMap(t,e){switch(e){case"extensions":return t.extensions;case"skills":return t.skills;case"prompts":return t.prompts;case"themes":return t.themes;default:throw new Error(`Unknown resource type: ${e}`)}}addResource(t,e,s,n){e&&(t.has(e)||t.set(e,{metadata:s,enabled:n}))}createAccumulator(){return{extensions:new Map,skills:new Map,prompts:new Map,themes:new Map}}toResolvedPaths(t){const e=m(s=>{const n=Array.from(s.entries()).map(([i,{metadata:o,enabled:a}])=>({path:i,enabled:a,metadata:o}));n.sort((i,o)=>at(i.metadata)-at(o.metadata));const r=new Set;return n.filter(i=>{const o=Rt(i.path);return r.has(o)?!1:(r.add(o),!0)})},"mapToResolved");return{extensions:e(t.extensions),skills:e(t.skills),prompts:e(t.prompts),themes:e(t.themes)}}spawnCommand(t,e,s){const n=Y();return rt(t,e,{cwd:s?.cwd,stdio:At()?["ignore",2,2]:"inherit",env:n})}spawnCaptureCommand(t,e,s){const n=Y(),r=s?.env?{...n,...s.env}:n;return rt(t,e,{cwd:s?.cwd,stdio:["ignore","pipe","pipe"],env:r})}runCommandCapture(t,e,s){return new Promise((n,r)=>{const i=this.spawnCaptureCommand(t,e,s);let o="",a="",l=!1;const p=typeof s?.timeoutMs=="number"?setTimeout(()=>{l=!0,i.kill()},s.timeoutMs):void 0;i.stdout?.on("data",u=>{o+=u.toString()}),i.stderr?.on("data",u=>{a+=u.toString()}),i.once("error",u=>{p&&clearTimeout(p),r(u)}),i.once("close",(u,g)=>{if(p&&clearTimeout(p),l){r(new Error(`${t} ${e.join(" ")} timed out after ${s?.timeoutMs}ms`));return}if(u===0){n(o.trim());return}const P=u===null?`signal ${g??"unknown"}`:`code ${u}`;r(new Error(`${t} ${e.join(" ")} failed with ${P}: ${a||o}`))})})}runCommand(t,e,s){return new Promise((n,r)=>{const i=this.spawnCommand(t,e,s);i.on("error",r),i.on("exit",o=>{o===0?n():r(new Error(`${t} ${e.join(" ")} failed with code ${o}`))})})}runCommandSync(t,e){const s=Y(),n=It(t,e,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",env:s});if(n.error||n.status!==0)throw new Error(`Failed to run ${t} ${e.join(" ")}: ${n.error?.message||n.stderr||n.stdout}`);return(n.stdout||n.stderr||"").trim()}}export{de as DefaultPackageManager,Wt as NPM_ARGS_HOOK_SLOT,Ot as getExtensionTempFolder};
3
+ `,"utf-8")}getNpmInstallRoot(t,e){return e?this.getTemporaryDir("npm"):t==="project"?(this.assertProjectTrustedForScope(t),h(this.cwd,D,"npm")):h(this.agentDir,"npm")}getGlobalNpmRoot(){const t=this.getNpmCommand(),e=[t.command,...t.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===e)return this.globalNpmRoot;if(this.getPackageManagerName()==="bun"){const s=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=h(w(s),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=e,this.globalNpmRoot}getPnpmGlobalPackagePath(t){if(this.getPackageManagerName()!=="pnpm")return;const e=this.runNpmCommandSync(["list","-g","--depth","0","--json"]),s=JSON.parse(e);for(const n of s){const r=n.dependencies?.[t]?.path;if(r)return r}}getManagedNpmInstallPath(t,e){return e==="temporary"?h(this.getTemporaryDir("npm"),"node_modules",t.name):e==="project"?(this.assertProjectTrustedForScope(e),h(this.cwd,D,"npm","node_modules",t.name)):h(this.agentDir,"npm","node_modules",t.name)}getLegacyGlobalNpmInstallPath(t){try{return this.getPnpmGlobalPackagePath(t.name)??h(this.getGlobalNpmRoot(),t.name)}catch{return}}getNpmInstallPath(t,e){const s=this.getManagedNpmInstallPath(t,e);if(e!=="user"||f(s))return s;const n=this.getLegacyGlobalNpmInstallPath(t);return n&&f(n)?n:s}getGitInstallPath(t,e){if(e==="temporary")return this.getTemporaryDir(`git-${t.host}`,t.path,t.ref);const s=this.getGitInstallRoot(e);if(!s)throw new Error("Missing git install root");return this.resolveManagedPath(s,t.host,t.path)}getGitInstallRoot(t){if(t!=="temporary")return t==="project"?(this.assertProjectTrustedForScope(t),h(this.cwd,D,"git")):h(this.agentDir,"git")}getTemporaryDir(t,e,s){const n=this.resolveManagedPath(Ot(this.agentDir),t),r=kt("sha256").update(`${t}-${e??""}${s?`@${s}`:""}`).digest("hex").slice(0,8);return this.resolveManagedPath(n,r,e??"")}resolveManagedPath(t,...e){const s=S(t),n=S(s,...e);if(n!==s&&!n.startsWith(`${s}${U}`))throw new Error(`Refusing to use path outside package install root: ${n}`);return n}getBaseDirForScope(t){return t==="project"?(this.assertProjectTrustedForScope(t),h(this.cwd,D)):t==="user"?this.agentDir:this.cwd}resolvePath(t){return _(t,this.cwd,{homeDir:Q(),trim:!0})}resolvePathFromBase(t,e){return _(t,e,{homeDir:Q(),trim:!0})}collectPackageResources(t,e,s,n){if(xt(t))return!0;if(s){for(const o of O){const a=s[o],l=this.getTargetMap(e,o);s.autoload===!1?this.applyPackageDeltaFilter(t,a??[],o,l,n):a!==void 0?this.applyPackageFilter(t,a,o,l,n):this.collectDefaultResources(t,o,l,n)}return!0}const r=L(h(t,"package.json"));if(r){for(const o of O){const a=r[o];this.addManifestEntries(a,t,o,this.getTargetMap(e,o),n)}return!0}let i=!1;for(const o of O){const a=h(t,o);if(f(a)){const l=J(a,o);for(const p of l)this.addResource(this.getTargetMap(e,o),p,n,!0);i=!0}}return i}collectDefaultResources(t,e,s,n){const i=L(h(t,"package.json"))?.[e];if(i){this.addManifestEntries(i,t,e,s,n);return}const o=h(t,e);if(f(o)){const a=J(o,e);for(const l of a)this.addResource(s,l,n,!0)}}applyPackageFilter(t,e,s,n,r){const{allFiles:i}=this.collectManifestFiles(t,s);if(e.length===0){for(const a of i)this.addResource(n,a,r,!1);return}const o=K(i,e,t);for(const a of i){const l=o.has(a);this.addResource(n,a,r,l)}}applyPackageDeltaFilter(t,e,s,n,r){if(e.length===0)return;const{allFiles:i}=this.collectManifestFiles(t,s),o=gt(i,e,t);for(const[a,l]of o)this.addResource(n,a,r,l)}collectManifestFiles(t,e){const n=L(h(t,"package.json"))?.[e];if(n&&n.length>0){const o=this.collectFilesFromManifestEntries(n,t,e),a=n.filter(Z),l=a.length>0?K(o,a,t):new Set(o);return{allFiles:Array.from(l),enabledByManifest:l}}const r=h(t,e);if(!f(r))return{allFiles:[],enabledByManifest:new Set};const i=J(r,e);return{allFiles:i,enabledByManifest:new Set(i)}}addManifestEntries(t,e,s,n,r){if(!t)return;const i=this.collectFilesFromManifestEntries(t,e,s),o=t.filter(Z),a=K(i,o,e);for(const l of i)a.has(l)&&this.addResource(n,l,r,!0)}collectFilesFromManifestEntries(t,e,s){const r=t.filter(i=>!Z(i)).flatMap(i=>Vt(i)?Kt(i,e):[S(e,i)]);return this.collectFilesFromPaths(r,s)}resolveLocalEntries(t,e,s,n,r){if(t.length===0)return;const{plain:i,patterns:o}=zt(t),a=i.map(u=>this.resolvePathFromBase(u,r)),l=this.collectFilesFromPaths(a,e),p=K(l,o,r);for(const u of l)this.addResource(s,u,n,p.has(u))}addAutoDiscoveredResources(t,e,s,n,r){const i={source:"auto",scope:"user",origin:"top-level",baseDir:n},o={source:"auto",scope:"project",origin:"top-level",baseDir:r},a={extensions:e.extensions??[],skills:e.skills??[],prompts:e.prompts??[],themes:e.themes??[]},l={extensions:s.extensions??[],skills:s.skills??[],prompts:s.prompts??[],themes:s.themes??[]},p={extensions:h(n,"extensions"),skills:h(n,"skills"),prompts:h(n,"prompts"),themes:h(n,"themes")},u={extensions:h(r,"extensions"),skills:h(r,"skills"),prompts:h(r,"prompts"),themes:h(r,"themes")},m=Xt(),P=new Set(m.map(C=>S(C))),d=this.settingsManager.isProjectTrusted(),F=d?qt(this.cwd).filter(C=>!P.has(S(C))):[],M=g((C,E,R,mt,dt)=>{const yt=this.getTargetMap(t,C);for(const st of E){const Pt=ft(st,mt,dt);this.addResource(yt,st,R,Pt)}},"addResources");d&&(M("extensions",et(u.extensions),o,l.extensions,r),M("skills",B(u.skills,"pi"),o,l.skills,r));for(const C of F){const E=w(C),R={...o,baseDir:E};M("skills",B(C,"agents"),R,l.skills,E)}d&&(M("prompts",lt(u.prompts),o,l.prompts,r),M("themes",ut(u.themes),o,l.themes,r)),M("extensions",et(p.extensions),i,a.extensions,n),M("skills",B(p.skills,"pi"),i,a.skills,n);for(const C of m){const E=w(C),R={...i,baseDir:E};M("skills",B(C,"agents"),R,a.skills,E)}M("prompts",lt(p.prompts),i,a.prompts,n),M("themes",ut(p.themes),i,a.themes,n)}collectFilesFromPaths(t,e){const s=[];for(const n of t)if(f(n))try{const r=N(n);r.isFile()?s.push(n):r.isDirectory()&&s.push(...J(n,e))}catch{}return s}getTargetMap(t,e){switch(e){case"extensions":return t.extensions;case"skills":return t.skills;case"prompts":return t.prompts;case"themes":return t.themes;default:throw new Error(`Unknown resource type: ${e}`)}}addResource(t,e,s,n){e&&(t.has(e)||t.set(e,{metadata:s,enabled:n}))}createAccumulator(){return{extensions:new Map,skills:new Map,prompts:new Map,themes:new Map}}toResolvedPaths(t){const e=g(s=>{const n=Array.from(s.entries()).map(([i,{metadata:o,enabled:a}])=>({path:i,enabled:a,metadata:o}));n.sort((i,o)=>at(i.metadata)-at(o.metadata));const r=new Set;return n.filter(i=>{const o=Rt(i.path);return r.has(o)?!1:(r.add(o),!0)})},"mapToResolved");return{extensions:e(t.extensions),skills:e(t.skills),prompts:e(t.prompts),themes:e(t.themes)}}spawnCommand(t,e,s){const n=Y();return it(t,e,{cwd:s?.cwd,stdio:Gt()?["ignore",2,2]:"inherit",env:n})}spawnCaptureCommand(t,e,s){const n=Y(),r=s?.env?{...n,...s.env}:n;return it(t,e,{cwd:s?.cwd,stdio:["ignore","pipe","pipe"],env:r})}runCommandCapture(t,e,s){return new Promise((n,r)=>{const i=this.spawnCaptureCommand(t,e,s);let o="",a="",l=!1;const p=typeof s?.timeoutMs=="number"?setTimeout(()=>{l=!0,i.kill()},s.timeoutMs):void 0;i.stdout?.on("data",u=>{o+=u.toString()}),i.stderr?.on("data",u=>{a+=u.toString()}),i.once("error",u=>{p&&clearTimeout(p),r(u)}),i.once("close",(u,m)=>{if(p&&clearTimeout(p),l){r(new Error(`${t} ${e.join(" ")} timed out after ${s?.timeoutMs}ms`));return}if(u===0){n(o.trim());return}const P=u===null?`signal ${m??"unknown"}`:`code ${u}`;r(new Error(`${t} ${e.join(" ")} failed with ${P}: ${a||o}`))})})}runCommand(t,e,s){return new Promise((n,r)=>{const i=this.spawnCommand(t,e,s);i.on("error",r),i.on("exit",o=>{o===0?n():r(new Error(`${t} ${e.join(" ")} failed with code ${o}`))})})}runCommandSync(t,e){const s=Y(),n=jt(t,e,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",env:s});if(n.error||n.status!==0)throw new Error(`Failed to run ${t} ${e.join(" ")}: ${n.error?.message||n.stderr||n.stdout}`);return(n.stdout||n.stderr||"").trim()}}export{de as DefaultPackageManager,Wt as NPM_ARGS_HOOK_SLOT,Ot as getExtensionTempFolder};
@@ -2,6 +2,7 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import { type AssistantMessage, type ImageContent, type Message, type SystemMessage, type TextContent, type ToolResultMessage, type Usage, type UserMessage } from "@earendil-works/pi-ai";
3
3
  import { type BashExecutionMessage, type CustomMessage } from "./messages.ts";
4
4
  export declare const CURRENT_SESSION_VERSION = 3;
5
+ export declare function isNewerSessionFormat(header: Pick<SessionHeader, "version"> | undefined): boolean;
5
6
  export interface SessionHeader {
6
7
  type: "session";
7
8
  version?: number;
@@ -150,6 +151,7 @@ export declare class SessionManager {
150
151
  private cwd;
151
152
  private persist;
152
153
  private flushed;
154
+ private newerFormat;
153
155
  private fileEntries;
154
156
  private byId;
155
157
  private labelsById;
@@ -163,6 +165,7 @@ export declare class SessionManager {
163
165
  private _buildIndex;
164
166
  private _rewriteFile;
165
167
  isPersisted(): boolean;
168
+ isReadOnly(): boolean;
166
169
  getCwd(): string;
167
170
  getSessionDir(): string;
168
171
  usesDefaultSessionDir(): boolean;