dal-code 1.0.36 → 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.
- package/CHANGELOG.md +20 -0
- package/dist/core/agent-session.d.ts +4 -1
- package/dist/core/agent-session.js +8 -8
- package/dist/core/auth-storage.js +1 -1
- package/dist/core/compaction/utils.js +5 -6
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/runner.d.ts +3 -2
- package/dist/core/extensions/runner.js +1 -1
- package/dist/core/extensions/types.d.ts +11 -3
- package/dist/core/model-runtime.js +2 -2
- package/dist/core/package-manager.d.ts +4 -0
- package/dist/core/package-manager.js +2 -2
- package/dist/core/session-manager.d.ts +3 -0
- package/dist/core/session-manager.js +12 -12
- package/dist/core/settings-diagnostics.js +1 -1
- package/dist/core/settings-manager.d.ts +3 -0
- package/dist/core/settings-manager.js +1 -1
- package/dist/core/shared-data.js +1 -0
- package/dist/core/system-prompt.js +10 -10
- package/dist/core/trust-manager.js +2 -2
- package/dist/dal/reviewed/endorsed-cli.js +1 -0
- package/dist/dal/reviewed/endorsed-plan.js +1 -0
- package/dist/dal/reviewed/endorsed.js +1 -0
- package/dist/dal/reviewed/version.js +1 -0
- package/dist/extensions/mcp/config.js +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/modes/print-mode.js +5 -5
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-goal/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-guard/src/mode.js +2 -2
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-mcp/src/config-edit.js +2 -2
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/shared-data.js +1 -0
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/shared-data.js +1 -0
- package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-plugins/src/state.js +2 -2
- package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-rewind/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +1 -1
- package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
- package/dist/node_modules/@dalcode/dal-router/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-router/src/runtime.js +1 -1
- package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-subagent/src/index.js +14 -12
- package/dist/node_modules/@dalcode/dal-subagent/src/process-runner.js +2 -2
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-telemetry/src/config.js +2 -2
- package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-workflow/src/plan-mode.js +14 -14
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/chord/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +5 -5
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js +4 -4
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +5 -5
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +4 -4
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/transform-messages.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/types.d.ts +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/json-parse.d.ts +2 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/json-parse.js +5 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/validation.js +2 -2
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -6
- package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/dist/package-manager-cli.js +72 -72
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/plan-mode/index.ts +6 -2
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic.js +0 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot.js +0 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/auth/oauth/openai-codex.js +0 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/bun-oauth.js +0 -1
- package/examples/extensions/custom-provider-anthropic/index.ts +0 -617
- package/examples/extensions/custom-provider-anthropic/package-lock.json +0 -24
- package/examples/extensions/custom-provider-anthropic/package.json +0 -19
|
@@ -1 +1 @@
|
|
|
1
|
-
var v=Object.defineProperty;var a=(h,e)=>v(h,"name",{value:e,configurable:!0});import{getCurrentSystemMessage as P}from"@earendil-works/pi-ai";import{theme as w}from"../../modes/interactive/theme/theme.js";import{buildSystemPrompt as E,normalizeBuildSystemPromptOptions as p}from"../system-prompt.js";const S=["app.interrupt","app.clear","app.exit","app.suspend","app.thinking.cycle","app.model.cycleForward","app.model.cycleBackward","app.model.select","app.tools.expand","app.thinking.toggle","app.editor.external","app.message.copy","app.message.followUp","tui.input.submit","tui.select.confirm","tui.select.cancel","tui.input.copy","tui.editor.deleteToLineEnd"],C=a(h=>{const e={};for(const[s,t]of Object.entries(h)){if(t===void 0)continue;const i=Array.isArray(t)?t:[t],n=S.includes(s);for(const o of i){const r=o.toLowerCase();e[r]?.restrictOverride&&!n||(e[r]={keybinding:s,restrictOverride:n})}}return e},"buildBuiltinKeybindings");function k(h){if(typeof h!="object"||h===null)return!1;const e=h,s=e.operations!==void 0,t=e.result!==void 0;if(s===t)return!1;if(s){const o=e.operations;return typeof o!="object"||o===null?!1:typeof o.exec=="function"}const i=e.result;if(typeof i!="object"||i===null)return!1;const n=i;return typeof n.output=="string"&&"exitCode"in n&&(n.exitCode===void 0||typeof n.exitCode=="number")&&typeof n.cancelled=="boolean"&&typeof n.truncated=="boolean"&&(n.fullOutputPath===void 0||typeof n.fullOutputPath=="string")}a(k,"isUserBashEventResult");async function R(h,e){return h.hasHandlers("session_shutdown")?(await h.emit(e),!0):!1}a(R,"emitSessionShutdownEvent");function g(h,e){return h.map(s=>({ext:s,handlers:s.handlers.get(e)?.slice()??[]}))}a(g,"snapshotEventHandlers");function y(h,e){return h.length===e.length&&h.every((s,t)=>s===e[t])}a(y,"sameMessages");function M(h,e,s){if(y(s,e))return h;const t=P(h);return t?[t,...s]:s}a(M,"restoreSystemMessages");async function I(h,e,s){const t=[];for(const{ext:i,handlers:n}of g(h.extensions,"project_trust"))for(const o of n)try{const r=await o(e,s);if(r.trusted==="undecided")continue;return{result:r,errors:t}}catch(r){t.push({extensionPath:i.path,event:e.type,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}return{errors:t}}a(I,"emitProjectTrustEvent");const x={select:a(async()=>{},"select"),confirm:a(async()=>!1,"confirm"),input:a(async()=>{},"input"),notify:a(()=>{},"notify"),setPanel:a(()=>{},"setPanel"),requestInput:a(async()=>{},"requestInput"),requestChoice:a(async()=>{},"requestChoice"),onTerminalInput:a(()=>()=>{},"onTerminalInput"),setStatus:a(()=>{},"setStatus"),setWorkingMessage:a(()=>{},"setWorkingMessage"),setWorkingVisible:a(()=>{},"setWorkingVisible"),setWorkingIndicator:a(()=>{},"setWorkingIndicator"),setHiddenThinkingLabel:a(()=>{},"setHiddenThinkingLabel"),setWidget:a(()=>{},"setWidget"),setFooter:a(()=>{},"setFooter"),setHeader:a(()=>{},"setHeader"),setTitle:a(()=>{},"setTitle"),custom:a(async()=>{},"custom"),pasteToEditor:a(()=>{},"pasteToEditor"),setEditorText:a(()=>{},"setEditorText"),getEditorText:a(()=>"","getEditorText"),editor:a(async()=>{},"editor"),addAutocompleteProvider:a(()=>{},"addAutocompleteProvider"),setEditorComponent:a(()=>{},"setEditorComponent"),getEditorComponent:a(()=>{},"getEditorComponent"),get theme(){return w},getAllThemes:a(()=>[],"getAllThemes"),getTheme:a(()=>{},"getTheme"),setTheme:a(h=>({success:!1,error:"UI not available"}),"setTheme"),getToolsExpanded:a(()=>!1,"getToolsExpanded"),setToolsExpanded:a(()=>{},"setToolsExpanded")};class U{static{a(this,"ExtensionRunner")}extensions;runtime;uiContext;mode="print";cwd;sessionManager;modelRegistry;errorListeners=new Set;getModel=a(()=>{},"getModel");getScopedModels=a(()=>[],"getScopedModels");isIdleFn=a(()=>!0,"isIdleFn");isProjectTrustedFn=a(()=>!0,"isProjectTrustedFn");getSignalFn=a(()=>{},"getSignalFn");waitForIdleFn=a(async()=>{},"waitForIdleFn");abortFn=a(()=>{},"abortFn");hasPendingMessagesFn=a(()=>!1,"hasPendingMessagesFn");getContextUsageFn=a(()=>{},"getContextUsageFn");compactFn=a(()=>{},"compactFn");getSystemPromptFn=a(()=>"","getSystemPromptFn");getSystemPromptOptionsFn=a(()=>p({cwd:this.cwd}),"getSystemPromptOptionsFn");executeToolFn;getCallableToolsFn=a(()=>[],"getCallableToolsFn");reportedMcpServers=new Set;newSessionHandler=a(async()=>({cancelled:!1}),"newSessionHandler");forkHandler=a(async()=>({cancelled:!1}),"forkHandler");navigateTreeHandler=a(async()=>({cancelled:!1}),"navigateTreeHandler");switchSessionHandler=a(async()=>({cancelled:!1}),"switchSessionHandler");reloadHandler=a(async()=>{},"reloadHandler");shutdownHandler=a(()=>{},"shutdownHandler");shortcutDiagnostics=[];commandDiagnostics=[];staleMessage;uiPromptDepth=0;activeUIPrompt;constructor(e,s,t,i,n){this.extensions=e,this.runtime=s,this.uiContext=x,this.cwd=t,this.sessionManager=i,this.modelRegistry=n}bindCore(e,s,t){this.runtime.sendMessage=e.sendMessage,this.runtime.sendUserMessage=e.sendUserMessage,this.runtime.appendEntry=e.appendEntry,this.runtime.emitHostEvent=e.emitHostEvent??(()=>{}),this.runtime.setSessionName=e.setSessionName,this.runtime.getSessionName=e.getSessionName,this.runtime.setLabel=e.setLabel,this.runtime.getActiveTools=e.getActiveTools,this.runtime.getAllTools=e.getAllTools,this.runtime.getSettings=e.getSettings,this.runtime.setActiveTools=e.setActiveTools,this.runtime.isToolAllowed=e.isToolAllowed,this.runtime.getToolAllowlist=e.getToolAllowlist,this.runtime.getToolDenylist=e.getToolDenylist,this.runtime.refreshTools=e.refreshTools,this.runtime.getCommands=e.getCommands,this.runtime.setModel=e.setModel,this.runtime.getThinkingLevel=e.getThinkingLevel,this.runtime.setThinkingLevel=e.setThinkingLevel,this.runtime.createContext=()=>this.createContext(),this.getModel=s.getModel,this.getScopedModels=s.getScopedModels,this.isIdleFn=s.isIdle,this.isProjectTrustedFn=s.isProjectTrusted,this.getSignalFn=s.getSignal,this.abortFn=s.abort,this.hasPendingMessagesFn=s.hasPendingMessages,this.shutdownHandler=s.shutdown,this.getContextUsageFn=s.getContextUsage,this.compactFn=s.compact,this.getSystemPromptFn=s.getSystemPrompt,this.getSystemPromptOptionsFn=s.getSystemPromptOptions??(()=>p({cwd:this.cwd})),this.executeToolFn=s.executeTool,this.getCallableToolsFn=s.getCallableTools??(()=>[]),this.runtime.mcpServers.setChangeListener(()=>{this.emit({type:"mcp_servers_change",servers:this.runtime.mcpServers.list()}),this.reportUnhandledMcpServers()});for(const{name:n,config:o,extensionPath:r}of this.runtime.pendingProviderRegistrations)try{t?.registerProvider?t.registerProvider(n,o):this.modelRegistry.registerProvider(n,o)}catch(c){this.emitError({extensionPath:r,event:"register_provider",error:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0})}this.runtime.pendingProviderRegistrations=[];for(const{provider:n,extensionPath:o}of this.runtime.pendingNativeProviderRegistrations)try{t?.registerNativeProvider?t.registerNativeProvider(n):this.modelRegistry.registerProvider(n)}catch(r){this.emitError({extensionPath:o,event:"register_provider",error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}this.runtime.pendingNativeProviderRegistrations=[];const i=a(n=>{t?.registerVirtualModel?t.registerVirtualModel(n):this.modelRegistry.registerVirtualModel(n)},"registerVirtualModel");for(const{definition:n,extensionPath:o}of this.runtime.pendingVirtualModelRegistrations)try{i(n)}catch(r){this.emitError({extensionPath:o,event:"register_virtual_model",error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}this.runtime.pendingVirtualModelRegistrations=[],this.runtime.registerProvider=(n,o)=>{if(t?.registerProvider){t.registerProvider(n,o);return}this.modelRegistry.registerProvider(n,o)},this.runtime.registerNativeProvider=n=>{if(t?.registerNativeProvider){t.registerNativeProvider(n);return}this.modelRegistry.registerProvider(n)},this.runtime.unregisterProvider=n=>{if(t?.unregisterProvider){t.unregisterProvider(n);return}this.modelRegistry.unregisterProvider(n)},this.runtime.registerVirtualModel=i,this.runtime.unregisterVirtualModel=(n,o)=>{t?.unregisterVirtualModel?t.unregisterVirtualModel(n,o):this.modelRegistry.unregisterVirtualModel(n,o)}}bindCommandContext(e){if(e){this.waitForIdleFn=e.waitForIdle,this.newSessionHandler=e.newSession,this.forkHandler=e.fork,this.navigateTreeHandler=e.navigateTree,this.switchSessionHandler=e.switchSession,this.reloadHandler=e.reload;return}this.waitForIdleFn=async()=>{},this.newSessionHandler=async()=>({cancelled:!1}),this.forkHandler=async()=>({cancelled:!1}),this.navigateTreeHandler=async()=>({cancelled:!1}),this.switchSessionHandler=async()=>({cancelled:!1}),this.reloadHandler=async()=>{}}setUIContext(e,s="print"){this.uiContext=e?this.wrapUIPromptContext(e):x,this.mode=s}wrapUIPromptContext(e){return{...e,select:a((s,t,i)=>this.withUIPrompt("select",s,()=>e.select(s,t,i)),"select"),confirm:a((s,t,i)=>this.withUIPrompt("confirm",s,()=>e.confirm(s,t,i)),"confirm"),input:a((s,t,i)=>this.withUIPrompt("input",s,()=>e.input(s,t,i)),"input"),editor:a((s,t)=>this.withUIPrompt("editor",s,()=>e.editor(s,t)),"editor"),custom:a((s,t)=>this.withUIPrompt("custom",void 0,()=>e.custom(s,t)),"custom")}}withUIPrompt(e,s,t){this.uiPromptDepth++===0&&(this.activeUIPrompt={kind:e,title:s},this.emitUIPromptEvent({type:"ui_prompt_start",reason:"ui_prompt",kind:e,...s?{title:s}:{}}));const n=a(()=>{if(--this.uiPromptDepth>0)return;this.uiPromptDepth=0;const o=this.activeUIPrompt??{kind:e,title:s};this.activeUIPrompt=void 0,this.emitUIPromptEvent({type:"ui_prompt_end",reason:"ui_prompt",kind:o.kind,...o.title?{title:o.title}:{}})},"finish");try{return t().finally(n)}catch(o){throw n(),o}}emitUIPromptEvent(e){queueMicrotask(()=>{this.emit(e)})}getUIContext(){return this.uiContext}hasUI(){return this.uiContext!==x}getExtensionPaths(){return this.extensions.map(e=>e.path)}getAllRegisteredTools(){const e=new Map;for(const s of this.extensions)for(const t of s.tools.values())e.has(t.definition.name)||e.set(t.definition.name,t);return Array.from(e.values())}getToolDefinition(e){for(const s of this.extensions){const t=s.tools.get(e);if(t)return t.definition}}getFlags(){const e=new Map;for(const s of this.extensions)for(const[t,i]of s.flags)e.has(t)||e.set(t,i);return e}setFlagValue(e,s){this.runtime.flagValues.set(e,s)}getFlagValues(){return new Map(this.runtime.flagValues)}getShortcuts(e){this.shortcutDiagnostics=[];const s=C(e),t=new Map,i=a((n,o)=>{this.shortcutDiagnostics.push({type:"warning",message:n,path:o}),this.hasUI()||console.warn(n)},"addDiagnostic");for(const n of this.extensions)for(const[o,r]of n.shortcuts){const c=o.toLowerCase(),l=s[c];if(l?.restrictOverride===!0){i(`Extension shortcut '${o}' from ${r.extensionPath} conflicts with built-in shortcut. Skipping.`,r.extensionPath);continue}l?.restrictOverride===!1&&i(`Extension shortcut conflict: '${o}' is built-in shortcut for ${l.keybinding} and ${r.extensionPath}. Using ${r.extensionPath}.`,r.extensionPath);const f=t.get(c);f&&i(`Extension shortcut conflict: '${o}' registered by both ${f.extensionPath} and ${r.extensionPath}. Using ${r.extensionPath}.`,r.extensionPath),t.set(c,r)}return t}getShortcutDiagnostics(){return this.shortcutDiagnostics}invalidate(e="This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload()."){this.staleMessage||(this.staleMessage=e,this.runtime.invalidate(e))}assertActive(){if(this.staleMessage)throw new Error(this.staleMessage)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}emitError(e){for(const s of this.errorListeners)s(e)}reportUnhandledMcpServers(){if(!this.hasHandlers("mcp_servers_change"))for(const e of this.runtime.mcpServers.list())this.reportedMcpServers.has(e.name)||(this.reportedMcpServers.add(e.name),this.emitError({extensionPath:e.extensionPath,event:"register_mcp_server",error:`MCP server "${e.name}" is registered, but no loaded extension connects MCP servers; another extension may have replaced the built-in MCP support`}))}hasHandlers(e){for(const s of this.extensions){const t=s.handlers.get(e);if(t&&t.length>0)return!0}return!1}getMessageRenderer(e){for(const s of this.extensions){const t=s.messageRenderers.get(e);if(t)return t}}getMarkdownTransformers(){return this.extensions.flatMap(e=>e.markdownTransformer?[e.markdownTransformer]:[])}getModelPickerEntries(){return this.extensions.flatMap(e=>[...e.modelPickerEntries?.values()??[]])}resolveToolRenderers(e,s){const t=this.extensions.flatMap(n=>n.toolRenderers??[]),i=a(n=>n<t.length?t[n](e,()=>i(n+1)):s(),"resolve");return i(0)}getEntryRenderer(e){for(const s of this.extensions){const t=s.entryRenderers?.get(e);if(t)return t}}resolveRegisteredCommands(){const e=[],s=new Map;for(const n of this.extensions)for(const o of n.commands.values())e.push(o),s.set(o.name,(s.get(o.name)??0)+1);const t=new Map,i=new Set;return e.map(n=>{const o=(t.get(n.name)??0)+1;t.set(n.name,o);let r=(s.get(n.name)??0)>1?`${n.name}:${o}`:n.name;if(i.has(r)){let c=o;do c++,r=`${n.name}:${c}`;while(i.has(r))}return i.add(r),{...n,invocationName:r}})}getModelRegistry(){return this.modelRegistry}getRegisteredCommands(){return this.commandDiagnostics=[],this.resolveRegisteredCommands()}getCommandDiagnostics(){return this.commandDiagnostics}getCommand(e){return this.resolveRegisteredCommands().find(s=>s.invocationName===e)}shutdown(){this.shutdownHandler()}getActiveTools(){return this.assertActive(),this.runtime.getActiveTools()}createContext(){const e=this,s=this.getModel,t=this.getScopedModels;return{get ui(){return e.assertActive(),e.uiContext},get mode(){return e.assertActive(),e.mode},get hasUI(){return e.assertActive(),e.hasUI()},get cwd(){return e.assertActive(),e.cwd},get sessionManager(){return e.assertActive(),e.sessionManager},get modelRegistry(){return e.assertActive(),e.modelRegistry},get model(){return e.assertActive(),s()},get scopedModels(){return e.assertActive(),t()},get thinkingLevel(){return e.assertActive(),e.runtime.getThinkingLevel()},isIdle:a(()=>(e.assertActive(),e.isIdleFn()),"isIdle"),isProjectTrusted:a(()=>(e.assertActive(),e.isProjectTrustedFn()),"isProjectTrusted"),get signal(){return e.assertActive(),e.getSignalFn()},abort:a(()=>{e.assertActive(),e.abortFn()},"abort"),hasPendingMessages:a(()=>(e.assertActive(),e.hasPendingMessagesFn()),"hasPendingMessages"),shutdown:a(()=>{e.assertActive(),e.shutdownHandler()},"shutdown"),getContextUsage:a(()=>(e.assertActive(),e.getContextUsageFn()),"getContextUsage"),compact:a(i=>{e.assertActive(),e.compactFn(i)},"compact"),getSystemPrompt:a(()=>(e.assertActive(),e.getSystemPromptFn()),"getSystemPrompt")}}createToolContext(e,s){const t=this;return Object.defineProperties(this.createContext(),{tools:{get(){return t.assertActive(),t.getCallableToolsFn()}},executeTool:{value:a(async(i,n,o={})=>(t.assertActive(),t.executeToolFn?t.executeToolFn(e,i,n,{...o,signal:o.signal??s}):{toolCall:{type:"toolCall",id:`${e}/0`,name:i,arguments:{}},result:{content:[{type:"text",text:"Nested tool calls are not available in this context"}],details:{}},isError:!0}),"value")}})}createCommandContext(){const e=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext()));return e.getSystemPromptOptions=()=>(this.assertActive(),this.getSystemPromptOptionsFn()),e.waitForIdle=()=>(this.assertActive(),this.waitForIdleFn()),e.newSession=s=>(this.assertActive(),this.newSessionHandler(s)),e.fork=(s,t)=>(this.assertActive(),this.forkHandler(s,t)),e.navigateTree=(s,t)=>(this.assertActive(),this.navigateTreeHandler(s,t)),e.switchSession=(s,t)=>(this.assertActive(),this.switchSessionHandler(s,t)),e.reload=()=>(this.assertActive(),this.reloadHandler()),e}async emitBoundary(e,s){const t=this.createContext();let i=[],n=!1,o=await s(i),r=!0;for(const{ext:c,handlers:l}of g(this.extensions,e.type))for(const f of l){const u={...e,entries:i,continue:n,context:o};try{const d=await f(u,t);d?.entries!==void 0&&(i=d.entries),d?.continue!==void 0&&(n=d.continue)}catch(d){this.emitError({extensionPath:c.path,event:e.type,error:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0})}try{o=await s(i),r=!0}catch(d){r=!1,this.emitError({extensionPath:c.path,event:e.type,error:`Invalid boundary entries: ${d instanceof Error?d.message:String(d)}`,stack:d instanceof Error?d.stack:void 0})}}return r?{entries:i,continue:n,context:o,valid:!0}:{entries:[],continue:!1,context:o,valid:!1}}isSessionBeforeEvent(e){return e.type==="session_before_switch"||e.type==="session_before_fork"||e.type==="session_before_compact"||e.type==="session_before_tree"}async emit(e){const s=this.createContext();let t;for(const{ext:i,handlers:n}of g(this.extensions,e.type))for(const o of n)try{const r=await o(e,s);if(this.isSessionBeforeEvent(e)&&r&&(t=r,t.cancel))return t}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:e.type,error:c,stack:l})}return t}async emitCacheWarmingDecision(e){const s=this.createContext();let t=e.action;for(const{ext:i,handlers:n}of g(this.extensions,e.type))for(const o of n)try{const r=await o(e,s);r?.action!==void 0&&(t=r.action)}catch(r){this.emitError({extensionPath:i.path,event:e.type,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}return t}async emitMessageEnd(e){const s=this.createContext();let t=e.message,i=!1;for(const{ext:n,handlers:o}of g(this.extensions,"message_end"))for(const r of o)try{const c={...e,message:t},l=await r(c,s);if(!l?.message)continue;if(l.message.role!==t.role){this.emitError({extensionPath:n.path,event:"message_end",error:"message_end handlers must return a message with the same role"});continue}t=l.message,i=!0}catch(c){const l=c instanceof Error?c.message:String(c),f=c instanceof Error?c.stack:void 0;this.emitError({extensionPath:n.path,event:"message_end",error:l,stack:f})}return i?t:void 0}async emitToolResult(e){const s=this.createContext(),t={...e};let i=!1;for(const{ext:n,handlers:o}of g(this.extensions,"tool_result"))for(const r of o)try{const c=await r(t,s);if(!c)continue;c.content!==void 0&&(t.content=c.content,c.structuredContent===void 0&&delete t.structuredContent,i=!0),c.details!==void 0&&(t.details=c.details,i=!0),c.structuredContent!==void 0&&(t.structuredContent=c.structuredContent,i=!0),c.isError!==void 0&&(t.isError=c.isError,i=!0),c.usage!==void 0&&(t.usage=c.usage,i=!0)}catch(c){const l=c instanceof Error?c.message:String(c),f=c instanceof Error?c.stack:void 0;this.emitError({extensionPath:n.path,event:"tool_result",error:l,stack:f})}if(i)return{content:t.content,details:t.details,structuredContent:t.structuredContent,isError:t.isError,usage:t.usage}}async emitToolCall(e){const s=this.createContext();let t;for(const{handlers:i}of g(this.extensions,"tool_call"))for(const n of i){const o=await n(e,s);if(o&&(t=o,t.block))return t}return t}async emitUserBash(e){const s=this.createContext();for(const{ext:t,handlers:i}of g(this.extensions,"user_bash"))for(const n of i)try{const o=await n(e,s);if(o===void 0)continue;if(!k(o))throw new Error("Invalid user_bash handler result: return undefined for local execution or exactly one valid { operations } or { result } object");return o}catch(o){const r=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0;throw this.emitError({extensionPath:t.path,event:"user_bash",error:r,stack:c}),o}}async emitContext(e){const s=this.createContext();let t=structuredClone(e);for(const{ext:i,handlers:n}of g(this.extensions,"context"))for(const o of n)try{const r=t.filter(d=>d.role!=="system"),c=r.slice(),u=(await o({type:"context",messages:r},s))?.messages??(y(r,c)?void 0:r);if(!u)continue;t=M(t,c,u)}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:"context",error:c,stack:l})}for(const{ext:i,handlers:n}of g(this.extensions,"context_with_system"))for(const o of n)try{const r=t[0]?.role==="system";t=(await o({type:"context_with_system",messages:t},s))?.messages??t,r&&t[0]?.role!=="system"&&this.emitError({extensionPath:i.path,event:"context_with_system",error:"Handler removed the leading system message; the request has no prompt or initial tool declarations. Keep it at index 0 or replace a dropped prefix with getCurrentSystemMessage()."})}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:"context_with_system",error:c,stack:l})}return t}async emitBeforeProviderRequest(e){const s=this.createContext();let t=e;for(const{ext:i,handlers:n}of g(this.extensions,"before_provider_request"))for(const o of n)try{const c=await o({type:"before_provider_request",payload:t},s);c!==void 0&&(t=c)}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:"before_provider_request",error:c,stack:l})}return t}async emitBeforeProviderHeaders(e){const s=this.createContext();for(const{ext:t,handlers:i}of g(this.extensions,"before_provider_headers"))for(const n of i)try{await n({type:"before_provider_headers",headers:e},s)}catch(o){const r=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0;this.emitError({extensionPath:t.path,event:"before_provider_headers",error:r,stack:c})}return e}async emitBeforeAgentStart(e,s,t){const i=p(t),n=a(()=>E(i),"renderCurrentSystemPrompt"),o=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext()));o.getSystemPrompt=()=>(this.assertActive(),n());const r=[];for(const{ext:c,handlers:l}of g(this.extensions,"before_agent_start"))for(const f of l)try{const d=await f({type:"before_agent_start",prompt:e,images:s,get systemPrompt(){return n()},systemPromptOptions:i},o);if(d){const m=d;m.message&&r.push(m.message),m.systemPrompt!==void 0&&(i.forceSystemPrompt=m.systemPrompt)}}catch(u){const d=u instanceof Error?u.message:String(u),m=u instanceof Error?u.stack:void 0;this.emitError({extensionPath:c.path,event:"before_agent_start",error:d,stack:m})}return{messages:r,systemPromptOptions:i}}async emitResourcesDiscover(e,s){const t=this.createContext(),i=[],n=[],o=[];for(const{ext:r,handlers:c}of g(this.extensions,"resources_discover"))for(const l of c)try{const d=await l({type:"resources_discover",cwd:e,reason:s},t);d?.skillPaths?.length&&i.push(...d.skillPaths.map(m=>({path:m,extensionPath:r.path}))),d?.promptPaths?.length&&n.push(...d.promptPaths.map(m=>({path:m,extensionPath:r.path}))),d?.themePaths?.length&&o.push(...d.themePaths.map(m=>({path:m,extensionPath:r.path})))}catch(f){const u=f instanceof Error?f.message:String(f),d=f instanceof Error?f.stack:void 0;this.emitError({extensionPath:r.path,event:"resources_discover",error:u,stack:d})}return{skillPaths:i,promptPaths:n,themePaths:o}}async emitInput(e,s,t,i){const n=this.createContext();let o=e,r=s;for(const{ext:c,handlers:l}of g(this.extensions,"input"))for(const f of l)try{const d=await f({type:"input",text:o,images:r,source:t,streamingBehavior:i},n);if(d?.action==="handled")return d;d?.action==="transform"&&(o=d.text,r=d.images??r)}catch(u){this.emitError({extensionPath:c.path,event:"input",error:u instanceof Error?u.message:String(u),stack:u instanceof Error?u.stack:void 0})}return o!==e||r!==s?{action:"transform",text:o,images:r}:{action:"continue"}}}export{U as ExtensionRunner,I as emitProjectTrustEvent,R as emitSessionShutdownEvent};
|
|
1
|
+
var v=Object.defineProperty;var a=(u,e)=>v(u,"name",{value:e,configurable:!0});import{getCurrentSystemMessage as P}from"@earendil-works/pi-ai";import{theme as w}from"../../modes/interactive/theme/theme.js";import{buildSystemPrompt as E,normalizeBuildSystemPromptOptions as p}from"../system-prompt.js";const S=["app.interrupt","app.clear","app.exit","app.suspend","app.thinking.cycle","app.model.cycleForward","app.model.cycleBackward","app.model.select","app.tools.expand","app.thinking.toggle","app.editor.external","app.message.copy","app.message.followUp","tui.input.submit","tui.select.confirm","tui.select.cancel","tui.input.copy","tui.editor.deleteToLineEnd"],C=a(u=>{const e={};for(const[s,t]of Object.entries(u)){if(t===void 0)continue;const i=Array.isArray(t)?t:[t],n=S.includes(s);for(const o of i){const r=o.toLowerCase();e[r]?.restrictOverride&&!n||(e[r]={keybinding:s,restrictOverride:n})}}return e},"buildBuiltinKeybindings");function k(u){if(typeof u!="object"||u===null)return!1;const e=u,s=e.operations!==void 0,t=e.result!==void 0;if(s===t)return!1;if(s){const o=e.operations;return typeof o!="object"||o===null?!1:typeof o.exec=="function"}const i=e.result;if(typeof i!="object"||i===null)return!1;const n=i;return typeof n.output=="string"&&"exitCode"in n&&(n.exitCode===void 0||typeof n.exitCode=="number")&&typeof n.cancelled=="boolean"&&typeof n.truncated=="boolean"&&(n.fullOutputPath===void 0||typeof n.fullOutputPath=="string")}a(k,"isUserBashEventResult");async function R(u,e){return u.hasHandlers("session_shutdown")?(await u.emit(e),!0):!1}a(R,"emitSessionShutdownEvent");function g(u,e){return u.map(s=>({ext:s,handlers:s.handlers.get(e)?.slice()??[]}))}a(g,"snapshotEventHandlers");function y(u,e){return u.length===e.length&&u.every((s,t)=>s===e[t])}a(y,"sameMessages");function M(u,e,s){if(y(s,e))return u;const t=P(u);return t?[t,...s]:s}a(M,"restoreSystemMessages");async function I(u,e,s){const t=[];for(const{ext:i,handlers:n}of g(u.extensions,"project_trust"))for(const o of n)try{const r=await o(e,s);if(r.trusted==="undecided")continue;return{result:r,errors:t}}catch(r){t.push({extensionPath:i.path,event:e.type,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}return{errors:t}}a(I,"emitProjectTrustEvent");const x={select:a(async()=>{},"select"),confirm:a(async()=>!1,"confirm"),input:a(async()=>{},"input"),notify:a(()=>{},"notify"),setPanel:a(()=>{},"setPanel"),requestInput:a(async()=>{},"requestInput"),requestChoice:a(async()=>{},"requestChoice"),onTerminalInput:a(()=>()=>{},"onTerminalInput"),setStatus:a(()=>{},"setStatus"),setWorkingMessage:a(()=>{},"setWorkingMessage"),setWorkingVisible:a(()=>{},"setWorkingVisible"),setWorkingIndicator:a(()=>{},"setWorkingIndicator"),setHiddenThinkingLabel:a(()=>{},"setHiddenThinkingLabel"),setWidget:a(()=>{},"setWidget"),setFooter:a(()=>{},"setFooter"),setHeader:a(()=>{},"setHeader"),setTitle:a(()=>{},"setTitle"),custom:a(async()=>{},"custom"),pasteToEditor:a(()=>{},"pasteToEditor"),setEditorText:a(()=>{},"setEditorText"),getEditorText:a(()=>"","getEditorText"),editor:a(async()=>{},"editor"),addAutocompleteProvider:a(()=>{},"addAutocompleteProvider"),setEditorComponent:a(()=>{},"setEditorComponent"),getEditorComponent:a(()=>{},"getEditorComponent"),get theme(){return w},getAllThemes:a(()=>[],"getAllThemes"),getTheme:a(()=>{},"getTheme"),setTheme:a(u=>({success:!1,error:"UI not available"}),"setTheme"),getToolsExpanded:a(()=>!1,"getToolsExpanded"),setToolsExpanded:a(()=>{},"setToolsExpanded")};class U{static{a(this,"ExtensionRunner")}extensions;runtime;uiContext;mode="print";cwd;sessionManager;modelRegistry;errorListeners=new Set;getModel=a(()=>{},"getModel");getScopedModels=a(()=>[],"getScopedModels");isIdleFn=a(()=>!0,"isIdleFn");isProjectTrustedFn=a(()=>!0,"isProjectTrustedFn");getSignalFn=a(()=>{},"getSignalFn");waitForIdleFn=a(async()=>{},"waitForIdleFn");abortFn=a(()=>{},"abortFn");hasPendingMessagesFn=a(()=>!1,"hasPendingMessagesFn");getContextUsageFn=a(()=>{},"getContextUsageFn");compactFn=a(()=>{},"compactFn");getSystemPromptFn=a(()=>"","getSystemPromptFn");getSystemPromptOptionsFn=a(()=>p({cwd:this.cwd}),"getSystemPromptOptionsFn");executeToolFn;getCallableToolsFn=a(()=>[],"getCallableToolsFn");reportedMcpServers=new Set;newSessionHandler=a(async()=>({cancelled:!1}),"newSessionHandler");forkHandler=a(async()=>({cancelled:!1}),"forkHandler");navigateTreeHandler=a(async()=>({cancelled:!1}),"navigateTreeHandler");switchSessionHandler=a(async()=>({cancelled:!1}),"switchSessionHandler");reloadHandler=a(async()=>{},"reloadHandler");shutdownHandler=a(()=>{},"shutdownHandler");shortcutDiagnostics=[];commandDiagnostics=[];staleMessage;uiPromptDepth=0;activeUIPrompt;constructor(e,s,t,i,n){this.extensions=e,this.runtime=s,this.uiContext=x,this.cwd=t,this.sessionManager=i,this.modelRegistry=n}bindCore(e,s,t){this.runtime.sendMessage=e.sendMessage,this.runtime.sendUserMessage=e.sendUserMessage,this.runtime.appendEntry=e.appendEntry,this.runtime.emitHostEvent=e.emitHostEvent??(()=>{}),this.runtime.setSessionName=e.setSessionName,this.runtime.getSessionName=e.getSessionName,this.runtime.setLabel=e.setLabel,this.runtime.getActiveTools=e.getActiveTools,this.runtime.getAllTools=e.getAllTools,this.runtime.getSettings=e.getSettings,this.runtime.setActiveTools=e.setActiveTools,this.runtime.isToolAllowed=e.isToolAllowed,this.runtime.getToolAllowlist=e.getToolAllowlist,this.runtime.getToolDenylist=e.getToolDenylist,this.runtime.refreshTools=e.refreshTools,this.runtime.getCommands=e.getCommands,this.runtime.setModel=e.setModel,this.runtime.getThinkingLevel=e.getThinkingLevel,this.runtime.setThinkingLevel=e.setThinkingLevel,this.runtime.createContext=()=>this.createContext(),this.getModel=s.getModel,this.getScopedModels=s.getScopedModels,this.isIdleFn=s.isIdle,this.isProjectTrustedFn=s.isProjectTrusted,this.getSignalFn=s.getSignal,this.abortFn=s.abort,this.hasPendingMessagesFn=s.hasPendingMessages,this.shutdownHandler=s.shutdown,this.getContextUsageFn=s.getContextUsage,this.compactFn=s.compact,this.getSystemPromptFn=s.getSystemPrompt,this.getSystemPromptOptionsFn=s.getSystemPromptOptions??(()=>p({cwd:this.cwd})),this.executeToolFn=s.executeTool,this.getCallableToolsFn=s.getCallableTools??(()=>[]),this.runtime.mcpServers.setChangeListener(()=>{this.emit({type:"mcp_servers_change",servers:this.runtime.mcpServers.list()}),this.reportUnhandledMcpServers()});for(const{name:n,config:o,extensionPath:r}of this.runtime.pendingProviderRegistrations)try{t?.registerProvider?t.registerProvider(n,o):this.modelRegistry.registerProvider(n,o)}catch(c){this.emitError({extensionPath:r,event:"register_provider",error:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0})}this.runtime.pendingProviderRegistrations=[];for(const{provider:n,extensionPath:o}of this.runtime.pendingNativeProviderRegistrations)try{t?.registerNativeProvider?t.registerNativeProvider(n):this.modelRegistry.registerProvider(n)}catch(r){this.emitError({extensionPath:o,event:"register_provider",error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}this.runtime.pendingNativeProviderRegistrations=[];const i=a(n=>{t?.registerVirtualModel?t.registerVirtualModel(n):this.modelRegistry.registerVirtualModel(n)},"registerVirtualModel");for(const{definition:n,extensionPath:o}of this.runtime.pendingVirtualModelRegistrations)try{i(n)}catch(r){this.emitError({extensionPath:o,event:"register_virtual_model",error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}this.runtime.pendingVirtualModelRegistrations=[],this.runtime.registerProvider=(n,o)=>{if(t?.registerProvider){t.registerProvider(n,o);return}this.modelRegistry.registerProvider(n,o)},this.runtime.registerNativeProvider=n=>{if(t?.registerNativeProvider){t.registerNativeProvider(n);return}this.modelRegistry.registerProvider(n)},this.runtime.unregisterProvider=n=>{if(t?.unregisterProvider){t.unregisterProvider(n);return}this.modelRegistry.unregisterProvider(n)},this.runtime.registerVirtualModel=i,this.runtime.unregisterVirtualModel=(n,o)=>{t?.unregisterVirtualModel?t.unregisterVirtualModel(n,o):this.modelRegistry.unregisterVirtualModel(n,o)}}bindCommandContext(e){if(e){this.waitForIdleFn=e.waitForIdle,this.newSessionHandler=e.newSession,this.forkHandler=e.fork,this.navigateTreeHandler=e.navigateTree,this.switchSessionHandler=e.switchSession,this.reloadHandler=e.reload;return}this.waitForIdleFn=async()=>{},this.newSessionHandler=async()=>({cancelled:!1}),this.forkHandler=async()=>({cancelled:!1}),this.navigateTreeHandler=async()=>({cancelled:!1}),this.switchSessionHandler=async()=>({cancelled:!1}),this.reloadHandler=async()=>{}}setUIContext(e,s="print"){this.uiContext=e?this.wrapUIPromptContext(e):x,this.mode=s}wrapUIPromptContext(e){return{...e,select:a((s,t,i)=>this.withUIPrompt("select",s,()=>e.select(s,t,i)),"select"),confirm:a((s,t,i)=>this.withUIPrompt("confirm",s,()=>e.confirm(s,t,i)),"confirm"),input:a((s,t,i)=>this.withUIPrompt("input",s,()=>e.input(s,t,i)),"input"),editor:a((s,t)=>this.withUIPrompt("editor",s,()=>e.editor(s,t)),"editor"),custom:a((s,t)=>this.withUIPrompt("custom",void 0,()=>e.custom(s,t)),"custom")}}withUIPrompt(e,s,t){this.uiPromptDepth++===0&&(this.activeUIPrompt={kind:e,title:s},this.emitUIPromptEvent({type:"ui_prompt_start",reason:"ui_prompt",kind:e,...s?{title:s}:{}}));const n=a(()=>{if(--this.uiPromptDepth>0)return;this.uiPromptDepth=0;const o=this.activeUIPrompt??{kind:e,title:s};this.activeUIPrompt=void 0,this.emitUIPromptEvent({type:"ui_prompt_end",reason:"ui_prompt",kind:o.kind,...o.title?{title:o.title}:{}})},"finish");try{return t().finally(n)}catch(o){throw n(),o}}emitUIPromptEvent(e){queueMicrotask(()=>{this.emit(e)})}getUIContext(){return this.uiContext}hasUI(){return this.uiContext!==x}getExtensionPaths(){return this.extensions.map(e=>e.path)}getAllRegisteredTools(){const e=new Map;for(const s of this.extensions)for(const t of s.tools.values())e.has(t.definition.name)||e.set(t.definition.name,t);return Array.from(e.values())}getToolDefinition(e){for(const s of this.extensions){const t=s.tools.get(e);if(t)return t.definition}}getFlags(){const e=new Map;for(const s of this.extensions)for(const[t,i]of s.flags)e.has(t)||e.set(t,i);return e}setFlagValue(e,s){this.runtime.flagValues.set(e,s)}getFlagValues(){return new Map(this.runtime.flagValues)}getShortcuts(e){this.shortcutDiagnostics=[];const s=C(e),t=new Map,i=a((n,o)=>{this.shortcutDiagnostics.push({type:"warning",message:n,path:o}),this.hasUI()||console.warn(n)},"addDiagnostic");for(const n of this.extensions)for(const[o,r]of n.shortcuts){const c=o.toLowerCase(),l=s[c];if(l?.restrictOverride===!0){i(`Extension shortcut '${o}' from ${r.extensionPath} conflicts with built-in shortcut. Skipping.`,r.extensionPath);continue}l?.restrictOverride===!1&&i(`Extension shortcut conflict: '${o}' is built-in shortcut for ${l.keybinding} and ${r.extensionPath}. Using ${r.extensionPath}.`,r.extensionPath);const h=t.get(c);h&&i(`Extension shortcut conflict: '${o}' registered by both ${h.extensionPath} and ${r.extensionPath}. Using ${r.extensionPath}.`,r.extensionPath),t.set(c,r)}return t}getShortcutDiagnostics(){return this.shortcutDiagnostics}invalidate(e="This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload()."){this.staleMessage||(this.staleMessage=e,this.runtime.invalidate(e))}assertActive(){if(this.staleMessage)throw new Error(this.staleMessage)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}emitError(e){for(const s of this.errorListeners)s(e)}reportUnhandledMcpServers(){if(!this.hasHandlers("mcp_servers_change"))for(const e of this.runtime.mcpServers.list())this.reportedMcpServers.has(e.name)||(this.reportedMcpServers.add(e.name),this.emitError({extensionPath:e.extensionPath,event:"register_mcp_server",error:`MCP server "${e.name}" is registered, but no loaded extension connects MCP servers; another extension may have replaced the built-in MCP support`}))}hasHandlers(e){for(const s of this.extensions){const t=s.handlers.get(e);if(t&&t.length>0)return!0}return!1}getMessageRenderer(e){for(const s of this.extensions){const t=s.messageRenderers.get(e);if(t)return t}}getMarkdownTransformers(){return this.extensions.flatMap(e=>e.markdownTransformer?[e.markdownTransformer]:[])}getModelPickerEntries(){return this.extensions.flatMap(e=>[...e.modelPickerEntries?.values()??[]])}resolveToolRenderers(e,s){const t=this.extensions.flatMap(n=>n.toolRenderers??[]),i=a(n=>n<t.length?t[n](e,()=>i(n+1)):s(),"resolve");return i(0)}getEntryRenderer(e){for(const s of this.extensions){const t=s.entryRenderers?.get(e);if(t)return t}}resolveRegisteredCommands(){const e=[],s=new Map;for(const n of this.extensions)for(const o of n.commands.values())e.push(o),s.set(o.name,(s.get(o.name)??0)+1);const t=new Map,i=new Set;return e.map(n=>{const o=(t.get(n.name)??0)+1;t.set(n.name,o);let r=(s.get(n.name)??0)>1?`${n.name}:${o}`:n.name;if(i.has(r)){let c=o;do c++,r=`${n.name}:${c}`;while(i.has(r))}return i.add(r),{...n,invocationName:r}})}getModelRegistry(){return this.modelRegistry}getRegisteredCommands(){return this.commandDiagnostics=[],this.resolveRegisteredCommands()}getCommandDiagnostics(){return this.commandDiagnostics}getCommand(e){return this.resolveRegisteredCommands().find(s=>s.invocationName===e)}shutdown(){this.shutdownHandler()}getActiveTools(){return this.assertActive(),this.runtime.getActiveTools()}createContext(){const e=this,s=this.getModel,t=this.getScopedModels;return{get ui(){return e.assertActive(),e.uiContext},get mode(){return e.assertActive(),e.mode},get hasUI(){return e.assertActive(),e.hasUI()},get cwd(){return e.assertActive(),e.cwd},get sessionManager(){return e.assertActive(),e.sessionManager},get modelRegistry(){return e.assertActive(),e.modelRegistry},get model(){return e.assertActive(),s()},get scopedModels(){return e.assertActive(),t()},get thinkingLevel(){return e.assertActive(),e.runtime.getThinkingLevel()},isIdle:a(()=>(e.assertActive(),e.isIdleFn()),"isIdle"),isProjectTrusted:a(()=>(e.assertActive(),e.isProjectTrustedFn()),"isProjectTrusted"),get signal(){return e.assertActive(),e.getSignalFn()},abort:a(()=>{e.assertActive(),e.abortFn()},"abort"),hasPendingMessages:a(()=>(e.assertActive(),e.hasPendingMessagesFn()),"hasPendingMessages"),shutdown:a(()=>{e.assertActive(),e.shutdownHandler()},"shutdown"),getContextUsage:a(()=>(e.assertActive(),e.getContextUsageFn()),"getContextUsage"),compact:a(i=>{e.assertActive(),e.compactFn(i)},"compact"),getSystemPrompt:a(()=>(e.assertActive(),e.getSystemPromptFn()),"getSystemPrompt")}}createToolContext(e,s){const t=this;return Object.defineProperties(this.createContext(),{tools:{get(){return t.assertActive(),t.getCallableToolsFn()}},executeTool:{value:a(async(i,n,o={})=>(t.assertActive(),t.executeToolFn?t.executeToolFn(e,i,n,{...o,signal:o.signal??s}):{toolCall:{type:"toolCall",id:`${e}/0`,name:i,arguments:{}},result:{content:[{type:"text",text:"Nested tool calls are not available in this context"}],details:{}},isError:!0}),"value")}})}createCommandContext(){const e=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext()));return e.getSystemPromptOptions=()=>(this.assertActive(),this.getSystemPromptOptionsFn()),e.waitForIdle=()=>(this.assertActive(),this.waitForIdleFn()),e.newSession=s=>(this.assertActive(),this.newSessionHandler(s)),e.fork=(s,t)=>(this.assertActive(),this.forkHandler(s,t)),e.navigateTree=(s,t)=>(this.assertActive(),this.navigateTreeHandler(s,t)),e.switchSession=(s,t)=>(this.assertActive(),this.switchSessionHandler(s,t)),e.reload=()=>(this.assertActive(),this.reloadHandler()),e}async emitBoundary(e,s){const t=this.createContext();let i=[],n=!1,o=await s(i),r=!0;for(const{ext:c,handlers:l}of g(this.extensions,e.type))for(const h of l){const f={...e,entries:i,continue:n,context:o};try{const d=await h(f,t);d?.entries!==void 0&&(i=d.entries),d?.continue!==void 0&&(n=d.continue)}catch(d){this.emitError({extensionPath:c.path,event:e.type,error:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0})}try{o=await s(i),r=!0}catch(d){r=!1,this.emitError({extensionPath:c.path,event:e.type,error:`Invalid boundary entries: ${d instanceof Error?d.message:String(d)}`,stack:d instanceof Error?d.stack:void 0})}}return r?{entries:i,continue:n,context:o,valid:!0}:{entries:[],continue:!1,context:o,valid:!1}}isSessionBeforeEvent(e){return e.type==="session_before_switch"||e.type==="session_before_fork"||e.type==="session_before_compact"||e.type==="session_before_tree"}async emit(e){const s=this.createContext();let t;for(const{ext:i,handlers:n}of g(this.extensions,e.type))for(const o of n)try{const r=await o(e,s);if(this.isSessionBeforeEvent(e)&&r&&(t=r,t.cancel))return t}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:e.type,error:c,stack:l})}return t}async emitCacheWarmingDecision(e){const s=this.createContext();let t=e.action;for(const{ext:i,handlers:n}of g(this.extensions,e.type))for(const o of n)try{const r=await o(e,s);r?.action!==void 0&&(t=r.action)}catch(r){this.emitError({extensionPath:i.path,event:e.type,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}return t}async emitMessageEnd(e){const s=this.createContext();let t=e.message,i=!1;for(const{ext:n,handlers:o}of g(this.extensions,"message_end"))for(const r of o)try{const c={...e,message:t},l=await r(c,s);if(!l?.message)continue;if(l.message.role!==t.role){this.emitError({extensionPath:n.path,event:"message_end",error:"message_end handlers must return a message with the same role"});continue}t=l.message,i=!0}catch(c){const l=c instanceof Error?c.message:String(c),h=c instanceof Error?c.stack:void 0;this.emitError({extensionPath:n.path,event:"message_end",error:l,stack:h})}return i?t:void 0}async emitToolResult(e){const s=this.createContext(),t={...e};let i=!1;for(const{ext:n,handlers:o}of g(this.extensions,"tool_result"))for(const r of o)try{const c=await r(t,s);if(!c)continue;c.content!==void 0&&(t.content=c.content,c.structuredContent===void 0&&delete t.structuredContent,i=!0),c.details!==void 0&&(t.details=c.details,i=!0),c.structuredContent!==void 0&&(t.structuredContent=c.structuredContent,i=!0),c.isError!==void 0&&(t.isError=c.isError,i=!0),c.usage!==void 0&&(t.usage=c.usage,i=!0)}catch(c){const l=c instanceof Error?c.message:String(c),h=c instanceof Error?c.stack:void 0;this.emitError({extensionPath:n.path,event:"tool_result",error:l,stack:h})}if(i)return{content:t.content,details:t.details,structuredContent:t.structuredContent,isError:t.isError,usage:t.usage}}async emitToolCall(e){const s=this.createContext();let t;for(const{handlers:i}of g(this.extensions,"tool_call"))for(const n of i){const o=await n(e,s);if(o&&(t=o,t.block))return t}return t}async emitUserBash(e){const s=this.createContext();for(const{ext:t,handlers:i}of g(this.extensions,"user_bash"))for(const n of i)try{const o=await n(e,s);if(o===void 0)continue;if(!k(o))throw new Error("Invalid user_bash handler result: return undefined for local execution or exactly one valid { operations } or { result } object");return o}catch(o){const r=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0;throw this.emitError({extensionPath:t.path,event:"user_bash",error:r,stack:c}),o}}async emitContext(e){const s=this.createContext();let t=structuredClone(e);for(const{ext:i,handlers:n}of g(this.extensions,"context"))for(const o of n)try{const r=t.filter(d=>d.role!=="system"),c=r.slice(),f=(await o({type:"context",messages:r},s))?.messages??(y(r,c)?void 0:r);if(!f)continue;t=M(t,c,f)}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:"context",error:c,stack:l})}for(const{ext:i,handlers:n}of g(this.extensions,"context_with_system"))for(const o of n)try{const r=t[0]?.role==="system";t=(await o({type:"context_with_system",messages:t},s))?.messages??t,r&&t[0]?.role!=="system"&&this.emitError({extensionPath:i.path,event:"context_with_system",error:"Handler removed the leading system message; the request has no prompt or initial tool declarations. Keep it at index 0 or replace a dropped prefix with getCurrentSystemMessage()."})}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:"context_with_system",error:c,stack:l})}return t}async emitBeforeProviderRequest(e){const s=this.createContext();let t=e;for(const{ext:i,handlers:n}of g(this.extensions,"before_provider_request"))for(const o of n)try{const c=await o({type:"before_provider_request",payload:t},s);c!==void 0&&(t=c)}catch(r){const c=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:i.path,event:"before_provider_request",error:c,stack:l})}return t}async emitBeforeProviderHeaders(e){const s=this.createContext();for(const{ext:t,handlers:i}of g(this.extensions,"before_provider_headers"))for(const n of i)try{await n({type:"before_provider_headers",headers:e},s)}catch(o){const r=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0;this.emitError({extensionPath:t.path,event:"before_provider_headers",error:r,stack:c})}return e}async emitBeforeAgentStart(e,s){const t=p(s),i=a(()=>E(t),"renderCurrentSystemPrompt"),n=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext()));n.getSystemPrompt=()=>(this.assertActive(),i());const o=[];for(const{ext:r,handlers:c}of g(this.extensions,"before_agent_start"))for(const l of c)try{const h={...e,type:"before_agent_start",get systemPrompt(){return i()},systemPromptOptions:t},f=await l(h,n);if(f){const d=f;d.message&&o.push(d.message),d.systemPrompt!==void 0&&(t.forceSystemPrompt=d.systemPrompt)}}catch(h){const f=h instanceof Error?h.message:String(h),d=h instanceof Error?h.stack:void 0;this.emitError({extensionPath:r.path,event:"before_agent_start",error:f,stack:d})}return{messages:o,systemPromptOptions:t}}async emitResourcesDiscover(e,s){const t=this.createContext(),i=[],n=[],o=[];for(const{ext:r,handlers:c}of g(this.extensions,"resources_discover"))for(const l of c)try{const d=await l({type:"resources_discover",cwd:e,reason:s},t);d?.skillPaths?.length&&i.push(...d.skillPaths.map(m=>({path:m,extensionPath:r.path}))),d?.promptPaths?.length&&n.push(...d.promptPaths.map(m=>({path:m,extensionPath:r.path}))),d?.themePaths?.length&&o.push(...d.themePaths.map(m=>({path:m,extensionPath:r.path})))}catch(h){const f=h instanceof Error?h.message:String(h),d=h instanceof Error?h.stack:void 0;this.emitError({extensionPath:r.path,event:"resources_discover",error:f,stack:d})}return{skillPaths:i,promptPaths:n,themePaths:o}}async emitInput(e,s,t,i){const n=this.createContext();let o=e,r=s;for(const{ext:c,handlers:l}of g(this.extensions,"input"))for(const h of l)try{const d=await h({type:"input",text:o,images:r,source:t,streamingBehavior:i},n);if(d?.action==="handled")return d;d?.action==="transform"&&(o=d.text,r=d.images??r)}catch(f){this.emitError({extensionPath:c.path,event:"input",error:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0})}return o!==e||r!==s?{action:"transform",text:o,images:r}:{action:"continue"}}}export{U as ExtensionRunner,I as emitProjectTrustEvent,R as emitSessionShutdownEvent};
|
|
@@ -412,13 +412,21 @@ export interface ProviderStreamEvent {
|
|
|
412
412
|
model: string;
|
|
413
413
|
data: unknown;
|
|
414
414
|
}
|
|
415
|
-
|
|
415
|
+
interface BeforeAgentStartEventBase {
|
|
416
416
|
type: "before_agent_start";
|
|
417
|
-
prompt: string;
|
|
418
|
-
images?: ImageContent[];
|
|
419
417
|
readonly systemPrompt: string;
|
|
420
418
|
systemPromptOptions: NormalizedBuildSystemPromptOptions;
|
|
421
419
|
}
|
|
420
|
+
export interface BeforeAgentStartUserEvent extends BeforeAgentStartEventBase {
|
|
421
|
+
messageType: "user";
|
|
422
|
+
prompt: string;
|
|
423
|
+
images?: ImageContent[];
|
|
424
|
+
}
|
|
425
|
+
export interface BeforeAgentStartCustomEvent extends BeforeAgentStartEventBase {
|
|
426
|
+
messageType: "custom";
|
|
427
|
+
message: CustomMessage;
|
|
428
|
+
}
|
|
429
|
+
export type BeforeAgentStartEvent = BeforeAgentStartUserEvent | BeforeAgentStartCustomEvent;
|
|
422
430
|
export interface AgentStartEvent {
|
|
423
431
|
type: "agent_start";
|
|
424
432
|
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var R=Object.defineProperty;var g=(f,e)=>R(f,"name",{value:e,configurable:!0});import{dirname as x,join as M}from"node:path";import{clampThinkingLevel as $,createModels as N,lazyStream as w,ModelsError as v,normalizeContext as E}from"@earendil-works/pi-ai";import*as P from"@earendil-works/pi-ai/providers/all";import{assertChatModel as y,assertClassifierInputSupported as O,assertClassifierModel as T,assertImageModel as K,classifierErrorResult as L,imageErrorResult as D}from"@earendil-works/pi-ai/utils/model-operations";import{APP_NAME as A,getAgentDir as U}from"../config.js";import{operationSignal as m,raceWithAbortSignal as z}from"../utils/abort.js";import{isOfflineModeEnabled as B}from"../utils/offline.js";import{AuthStorage as j}from"./auth-storage.js";import{houseProvidersEnforced as V,isLoginProviderOffered as F,protectedHouseFieldsTouched as H}from"./house-providers.js";import{ModelConfig as k}from"./model-config.js";import{FileModelsStore as _,InMemoryCodingAgentModelsStore as G}from"./models-store.js";import{composeModelProvider as W,configuredRequestAuthStatus as b,resolveCompatibilityRequestConfig as J,resolveConfiguredModelHeaders as Q,validateExtensionProvider as X}from"./provider-composer.js";import{getDefaultCatalogBaseUrl as Y,withRemoteCatalog as Z}from"./remote-catalog-provider.js";import{RuntimeCredentials as I}from"./runtime-credentials.js";import{createVirtualModel as ee,findLatestResponse as te,isVirtualModel as S,withVirtualModels as re}from"./virtual-models.js";class ie extends Error{static{g(this,"CredentialSynchronizationError")}providerId;operation;credential;constructor(e,t,r,i){super(`Credential ${t} committed for ${e}, but local synchronization failed`,i),this.name="CredentialSynchronizationError",this.providerId=e,this.operation=t,this.credential=r}}function q(f,e){if(!f&&!e)return;const t={...f};for(const[r,i]of Object.entries(e??{})){const s=r.toLowerCase();for(const o of Object.keys(t))o.toLowerCase()===s&&delete t[o];t[r]=i}return t}g(q,"mergeHeaders");function se(f,e=A){return e==="pi"||f!=="radius"}g(se,"isBuiltinProviderEnabled");class C{static{g(this,"ModelRuntime")}models;credentials;defaultBuiltins;builtins=new Map;nativeExtensionProviders=new Map;extensionProviders=new Map;virtualModels=new Map;compositionErrors=new Map;modelsPath;modelsStore;refreshesInFlight=new Set;compositionTail=Promise.resolve();modelNetworkEnabled;config;snapshot={all:[],available:[],configuredProviders:new Set,storedProviders:new Set,auth:new Map};availabilityRefreshSeq=0;availabilityErrorSeq=0;providerAvailabilitySeq=new Map;availabilityError;credentialOperations=new Map;constructor(e,t,r,i,s,o){this.credentials=e,this.config=t,this.modelsPath=r,this.modelsStore=i,this.modelNetworkEnabled=o,this.defaultBuiltins=new Map(s.map(a=>[a.id,a]));for(const[a,l]of this.defaultBuiltins)this.builtins.set(a,l);this.models=N({credentials:e,modelsStore:i}),this.rebuildProviders()}static async create(e={}){const t=new I(e.credentials??j.create(e.authPath)),r=e.modelsPath===null?void 0:e.modelsPath??M(U(),"models.json"),i=await k.load(r),s=e.modelsStore??(r?new _(e.modelsStorePath??M(x(r),"models-store.json")):new G),o=P.getBuiltinModelDataGeneratedAt(),a=e.catalogBaseUrl??Y(),l=P.builtinProviders().filter(p=>se(p.id)).map(p=>p.id==="radius"||a===void 0?p:Z(p,a,o)),h=new C(t,i,r,s,l,!B());h.configureRadiusProviders(),h.rebuildProviders();const n=h.modelNetworkEnabled&&e.allowModelNetwork===!0,d=n&&e.modelRefreshTimeoutMs!==void 0?new AbortController:void 0,c=d?setTimeout(()=>d.abort(),e.modelRefreshTimeoutMs):void 0,u=d?e.signal?AbortSignal.any([e.signal,d.signal]):d.signal:e.signal;try{e.refreshOnCreate!==!1&&await h.refresh({allowNetwork:n,signal:u})}finally{c&&clearTimeout(c)}return h}configureRadiusProviders(){this.builtins.clear();for(const[e,t]of this.defaultBuiltins)this.builtins.set(e,t);for(const e of this.config.getProviderIds()){const t=this.config.getProvider(e);t?.oauth!=="radius"||!t.baseUrl||this.builtins.set(e,P.radiusProvider({id:e,name:t.name??e,gateway:t.baseUrl.replace(/\/v1\/?$/u,"")}))}}providerIds(){return new Set([...this.builtins.keys(),...this.nativeExtensionProviders.keys(),...this.config.getProviderIds(),...this.extensionProviders.keys(),...this.virtualModels.keys()])}recomposeProvider(e){const t=this.composeProvider(e),r=[...this.virtualModels.get(e)?.values()??[]].map(i=>i.model);return r.length>0?this.models.setProvider(re(e,t,r)):t?this.models.setProvider(t):this.models.deleteProvider(e),t}composeProvider(e){const t=this.nativeExtensionProviders.get(e)??this.builtins.get(e),r=this.extensionProviders.get(e);if(!this.config.getProvider(e)&&!r)return this.compositionErrors.delete(e),t;const i=H(e,t,this.config.getProvider(e)??r);if(i.length>0)return this.compositionErrors.set(e,`\u5DF2\u5FFD\u7565\u5BF9 ${e} \u7684 ${i.join(" / ")} \u8986\u76D6\uFF1A\u81EA\u5BB6\u7F51\u5173\u7684\u5730\u5740\u548C\u51ED\u636E\u4E0D\u53EF\u6539\u5199\u3002`),t;try{const s=W(e,t,this.config,r,o=>{const a=this.extensionProviders.get(e);a&&this.extensionProviders.set(e,{...a,models:o})});return this.compositionErrors.delete(e),s}catch(s){return this.compositionErrors.set(e,s instanceof Error?s.message:String(s)),t}}rebuildProviders(){this.models.clearProviders(),this.compositionErrors.clear();for(const e of this.providerIds())this.recomposeProvider(e);this.updateModelSnapshot()}updateModelSnapshot(){const e=[...this.models.getModels()];this.snapshot={...this.snapshot,all:e,available:e.filter(t=>this.snapshot.configuredProviders.has(t.provider))}}async runAvailabilityRefresh(e,t,r){const i=this.models.getProviders(),[s,o,a]=await Promise.all([this.models.getAvailable(void 0,{signal:r}),Promise.all(i.map(async n=>[n.id,await this.models.checkAuth(n.id,{signal:r})])),this.credentials.list({signal:r})]);if(e!==this.availabilityRefreshSeq)return;const l=new Map(o),h=new Set(o.filter(n=>n[1]!==void 0).map(([n])=>n));this.snapshot={all:[...this.models.getModels()],available:[...s],configuredProviders:h,storedProviders:new Set(a.map(n=>n.providerId)),auth:l},t===this.availabilityErrorSeq&&(this.availabilityError=void 0)}queueAvailabilityRefresh(e){const t=++this.availabilityRefreshSeq;for(const[s,o]of this.providerAvailabilitySeq)this.providerAvailabilitySeq.set(s,o+1);const r=++this.availabilityErrorSeq,i=m(e);return this.runAvailabilityRefresh(t,r,i).catch(s=>{throw r===this.availabilityErrorSeq&&!i.aborted&&(this.availabilityError=s instanceof Error?s.message:String(s)),s})}async refreshProviderAvailability(e,t){++this.availabilityRefreshSeq;const r=(this.providerAvailabilitySeq.get(e)??0)+1;this.providerAvailabilitySeq.set(e,r);const i=++this.availabilityErrorSeq;try{const[s,o,a]=await Promise.all([this.models.getAvailable(e,{signal:t}),this.models.checkAuth(e,{signal:t}),this.credentials.read(e,{signal:t})]);if(t.throwIfAborted(),this.providerAvailabilitySeq.get(e)!==r)return;const l=new Set(this.snapshot.configuredProviders),h=new Set(this.snapshot.storedProviders),n=new Map(this.snapshot.auth);o?(l.add(e),n.set(e,o)):(l.delete(e),n.delete(e)),a?h.add(e):h.delete(e);const d=[...this.models.getModels()],c=new Map([...this.snapshot.available.filter(u=>u.provider!==e),...s].map(u=>[`${u.provider}\0${u.id}`,u]));this.snapshot={all:d,available:d.flatMap(u=>c.get(`${u.provider}\0${u.id}`)??[]),configuredProviders:l,storedProviders:h,auth:n},i===this.availabilityErrorSeq&&(this.availabilityError=void 0)}catch(s){throw this.providerAvailabilitySeq.get(e)===r&&i===this.availabilityErrorSeq&&!t.aborted&&(this.availabilityError=s instanceof Error?s.message:String(s)),s}}getProviders(){return this.models.getProviders()}getProvider(e){return this.models.getProvider(e)}getModels(e){return this.models.getModels(e)}getModel(e,t){return this.models.getModel(e,t)}async getPersistedCatalogCheckedAt(e,t){const r=await this.modelsStore.read(e,{signal:t});if(!(!r||r.models.length===0))return r.checkedAt??0}getModelsOfType(e,t){return this.models.getModelsOfType(e,t)}getModelOfType(e,t,r){return this.models.getModelOfType(e,t,r)}getAllModels(e){return this.models.getAllModels(e)}getAvailableOfType(e,t,r){return this.models.getAvailableOfType(e,t,r)}getAllAvailable(e,t){return this.models.getAllAvailable(e,t)}async checkAuth(e,t){return this.models.checkAuth(e,t)}async getAvailable(e,t){if(e){const r=++this.availabilityErrorSeq;try{const i=await this.models.getAvailable(e,t);return r===this.availabilityErrorSeq&&(this.availabilityError=void 0),i}catch(i){throw r===this.availabilityErrorSeq&&!t?.signal?.aborted&&(this.availabilityError=i instanceof Error?i.message:String(i)),i}}return await this.queueAvailabilityRefresh(t?.signal),this.snapshot.available}getAvailableSnapshot(){return this.snapshot.available}getError(){const e=[],t=this.config.getError();t&&e.push(t);for(const[r,i]of this.compositionErrors)e.push(`Provider "${r}": ${i}`);return this.availabilityError&&e.push(`Availability refresh: ${this.availabilityError}`),e.length>0?e.join(`
|
|
2
2
|
|
|
3
|
-
`):void 0}getRegisteredProviderConfig(e){return this.extensionProviders.get(e)}getRegisteredProviderIds(){return[...new Set([...this.extensionProviders.keys(),...this.nativeExtensionProviders.keys()])]}getRegisteredNativeProvider(e){return this.nativeExtensionProviders.get(e)}getCompatibilityRequestConfig(e){return G(e,this.config.getProvider(e.provider),this.extensionProviders.get(e.provider))}isUsingOAuth(e){return this.snapshot.auth.get(e)?.type==="oauth"}isUsingSubscription(e){return this.isUsingOAuth(e)&&this.models.getProvider(e)?.auth.oauth?.isSubscription===!0}hasConfiguredAuth(e){return this.snapshot.configuredProviders.has(e)}async getAuth(e,t={}){if(typeof e=="string")return this.models.getAuth(e,t);const r=await this.models.getAuth(e,t);if(!r)return;const i=W(e,this.config.getProvider(e.provider),this.extensionProviders.get(e.provider),{...r.env??{},...t.env??{}});return{...r,auth:{...r.auth,headers:k(r.auth.headers,i)}}}enqueueCredentialOperation(e,t,r){const i=this.credentialOperations.get(e)??Promise.resolve();let s;const o=new Promise(h=>{s=h}),a=(async()=>(await i.catch(()=>{}),t.throwIfAborted(),s?.(),r()))(),l=a.catch(()=>{});return this.credentialOperations.set(e,l),l.then(()=>{this.credentialOperations.get(e)===l&&this.credentialOperations.delete(e)}),z(o,t).then(()=>a)}async synchronizeCredentialState(e,t,r,i){try{i.throwIfAborted(),this.recomposeProvider(e);const s=this.compositionErrors.get(e);if(s)throw new Error(s);const o=await this.models.refresh({allowNetwork:!1,providers:[e],signal:i});o.aborted&&i.throwIfAborted();const a=o.errors.get(e);if(a)throw a;this.updateModelSnapshot(),await this.refreshProviderAvailability(e,i)}catch(s){throw new te(e,t,r,{cause:s})}}setRuntimeApiKey(e,t,r={}){const i=m(r.signal);return this.enqueueCredentialOperation(e,i,async()=>{this.credentials.setRuntimeApiKey(e,t),await this.synchronizeCredentialState(e,"setRuntimeApiKey",{type:"api_key",key:t},i)})}removeRuntimeApiKey(e,t={}){const r=m(t.signal);return this.enqueueCredentialOperation(e,r,async()=>{this.credentials.removeRuntimeApiKey(e),await this.synchronizeCredentialState(e,"removeRuntimeApiKey",void 0,r)})}listCredentials(e){return this.credentials.list(e)}getProviderAuthStatus(e){if(this.credentials.hasRuntimeApiKey(e))return{configured:!0,source:"runtime"};if(this.snapshot.storedProviders.has(e))return{configured:!0,source:"stored"};const t=b(this.config.getProvider(e),this.extensionProviders.get(e));if(t)return t;const r=this.snapshot.auth.get(e);return r?{configured:!0,source:"environment",label:r.source}:{configured:!1}}async prepareRequest(e,t){const r=this.models.getProvider(e.provider);if(!r)throw new v("provider",`Unknown provider: ${e.provider}`);const i=await this.getAuth(e,{apiKey:t?.apiKey,env:t?.env,signal:t?.signal});if(!i)throw new v("auth",`Provider is not configured: ${e.provider}`);const{transformHeaders:s,...o}=t??{},a=o;let l=k(i.auth.headers,a.headers);s&&(l=await s(l??{}));const h=i.env||a.env?{...i.env??{},...a.env??{}}:void 0,n=i.auth.baseUrl?{...e,baseUrl:i.auth.baseUrl}:e;return{provider:r,model:n,options:{...a,apiKey:a.apiKey??i.auth.apiKey,headers:l,env:h}}}stream(e,t,r){const i=E(t);return w(e,async()=>{y(e);const s=await this.prepareRequest(e,r);return s.provider.stream(s.model,i,s.options)})}complete(e,t,r){return this.stream(e,t,r).result()}streamSimple(e,t,r){const i=E(t);return S(e)?w(e,async()=>{const s=await this.resolveModel(e,i.messages,{reason:"direct",thinkingLevel:r?.reasoning??"off",signal:r?.signal}),{maxTokens:o}=s.model,a=r?.maxTokens&&o>0?Math.min(r.maxTokens,o):r?.maxTokens,l=s.thinkingLevel==="off"?void 0:s.thinkingLevel,{apiKey:h,headers:n,env:d,...u}=r??{},c=s.model.provider===e.provider?{apiKey:h,headers:n,env:d}:{};return this.streamSimple(s.model,t,{...u,...c,maxTokens:a,reasoning:l})}):w(e,async()=>{y(e);const s=await this.prepareRequest(e,r);return s.provider.streamSimple(s.model,i,s.options)})}completeSimple(e,t,r){return this.streamSimple(e,t,r).result()}streamDeferred(e,t,r){return w(e,async()=>{y(e);const i=await this.prepareRequest(e,r);if(!i.provider.fetchDeferred)throw new v("provider",`Provider ${e.provider} does not support deferred responses`);return i.provider.fetchDeferred(i.model,t,i.options)})}async fetchDeferred(e,t,r){return this.streamDeferred(e,t,r).result()}async cancelDeferred(e,t,r){y(e);const i=await this.prepareRequest(e,r);if(!i.provider.cancelDeferred)throw new v("provider",`Provider ${e.provider} does not support deferred responses`);await i.provider.cancelDeferred(i.model,t,i.options)}async generateImages(e,t,r){try{T(e);const i=await this.prepareRequest(e,r);if(!i.provider.generateImages)throw new v("provider",`Provider ${e.provider} does not support image generation`);return await i.provider.generateImages(i.model,t,i.options)}catch(i){return D(e,i,r?.signal?.aborted)}}async classify(e,t,r){try{O(e),N(e,t);const i=await this.prepareRequest(e,r);if(!i.provider.classify)throw new v("provider",`Provider ${e.provider} does not support classification`);return await i.provider.classify(i.model,t,i.options)}catch(i){return K(e,i,r?.signal?.aborted)}}login(e,t,r,i){const s=m(r.signal);return this.enqueueCredentialOperation(e,s,async()=>{const o=await this.models.login(e,t,{...r,signal:s},i);return await this.synchronizeCredentialState(e,"login",o,s),o})}logout(e,t={}){const r=m(t.signal);return this.enqueueCredentialOperation(e,r,async()=>{await this.models.logout(e,{signal:r}),await this.synchronizeCredentialState(e,"logout",void 0,r)})}async refresh(e={}){const t=this.refreshNow(e);this.refreshesInFlight.add(t);try{return await t}finally{this.refreshesInFlight.delete(t)}}async refreshNow(e){const t={...e,allowNetwork:e.allowNetwork??this.modelNetworkEnabled},r=A.load(this.modelsPath),i=this.compositionTail;let s;const o=new Promise(n=>{s=n});this.compositionTail=Promise.all([i,o]).then(()=>{});let a;try{const n=await r;if(await i,this.config=n,this.configureRadiusProviders(),e.providers){for(const d of new Set(e.providers))this.recomposeProvider(d);this.updateModelSnapshot()}else this.rebuildProviders();a=this.models.refresh(t)}finally{s()}const l=await a??{aborted:t.signal?.aborted??!1,errors:new Map},h=new Map(l.errors);if(this.updateModelSnapshot(),e.providers)await Promise.all([...new Set(e.providers)].map(async n=>{try{await this.refreshProviderAvailability(n,m(e.signal))}catch(d){e.signal?.aborted||h.set(n,d instanceof Error?d:new Error(String(d)))}}));else try{await this.queueAvailabilityRefresh(e.signal)}catch{}return{aborted:l.aborted||(e.signal?.aborted??!1),errors:h}}async refreshCatalogsInPlace(e){await Promise.allSettled([...this.refreshesInFlight]);const t=await this.models.refresh({providers:e.providers,signal:e.signal,allowNetwork:this.modelNetworkEnabled});return this.updateModelSnapshot(),t}registerNativeProvider(e){if(!e.id.trim())throw new Error("Provider id must not be empty.");this.extensionProviders.delete(e.id),this.nativeExtensionProviders.set(e.id,e),this.recomposeProvider(e.id),this.updateModelSnapshot(),this.markProvisionallyConfigured(e.id,b(this.config.getProvider(e.id),void 0),e.auth.oauth&&!e.auth.apiKey?"oauth":"api_key"),this.refresh({allowNetwork:!1})}markProvisionallyConfigured(e,t,r){if(!this.snapshot.storedProviders.has(e)&&!t?.configured)return;const i=new Set(this.snapshot.configuredProviders).add(e),s=new Map(this.snapshot.auth);s.get(e)||s.set(e,{type:r,source:"configured provider"}),this.snapshot={...this.snapshot,auth:s,configuredProviders:i,available:this.snapshot.all.filter(o=>i.has(o.provider))}}registerProvider(e,t){J(e,this.builtins.get(e),this.config.getProvider(e),t),this.nativeExtensionProviders.delete(e);const i={...this.extensionProviders.get(e)};for(const[s,o]of Object.entries(t))o!==void 0&&(i[s]=o);this.extensionProviders.set(e,i),this.recomposeProvider(e),this.updateModelSnapshot(),this.markProvisionallyConfigured(e,b(this.config.getProvider(e),i),i.oauth&&!i.apiKey?"oauth":"api_key"),this.refresh({allowNetwork:!1})}unregisterProvider(e){this.extensionProviders.delete(e),this.nativeExtensionProviders.delete(e),this.recomposeProvider(e),this.updateModelSnapshot(),this.refresh({allowNetwork:!1})}registerVirtualModel(e){const{provider:t,id:r}=e;if(!t.trim()||!r.trim())throw new Error("Virtual model provider and id must not be empty.");const i=this.models.getModel(t,r);if(i&&!S(i))throw new Error(`Virtual model ${t}/${r} conflicts with a physical model.`);const s=this.virtualModels.get(t)??new Map;if(s.set(r,{model:Z(e),route:g(o=>e.route(o),"route")}),this.virtualModels.set(t,s),!this.recomposeProvider(t)&&!this.snapshot.configuredProviders.has(t)){const o=new Map(this.snapshot.auth).set(t,{type:"api_key",source:"virtual"}),a=new Set(this.snapshot.configuredProviders).add(t);this.snapshot={...this.snapshot,auth:o,configuredProviders:a}}this.updateModelSnapshot(),this.refresh({allowNetwork:!1})}unregisterVirtualModel(e,t){const r=this.virtualModels.get(e);r?.delete(t)&&(r.size===0&&this.virtualModels.delete(e),this.recomposeProvider(e),this.updateModelSnapshot(),this.refresh({allowNetwork:!1}))}async resolveModel(e,t,r){const i=`Virtual model ${e.provider}/${e.id}`,s=this.virtualModels.get(e.provider)?.get(e.id);if(!s)throw new Error(`${i} is not registered.`);const{failed:o,...a}=r,l=I(t),h=l&&this.getPhysicalModel(l.provider,l.model),n=o&&this.getPhysicalModel(o.provider,o.model),d=await s.route({...a,model:e,previous:h&&{model:h,thinkingLevel:l?.thinkingLevel},failed:n&&o&&{model:n,thinkingLevel:o.thinkingLevel,message:o},messages:t}),u=this.getPhysicalModel(d.model.provider,d.model.id),c=`${i} routed to ${d.model.provider}/${d.model.id}`;if(!u)throw new Error(`${c}, which is not a physical model.`);if(!this.hasConfiguredAuth(u.provider))throw new Error(`${c}, which has no credentials.`);return{model:u,thinkingLevel:x(u,d.thinkingLevel),state:d.state}}getPhysicalModel(e,t){const r=this.models.getModel(e,t);return r&&!S(r)?r:void 0}}export{te as CredentialSynchronizationError,q as ModelRuntime,re as isBuiltinProviderEnabled};
|
|
3
|
+
`):void 0}getRegisteredProviderConfig(e){return this.extensionProviders.get(e)}getRegisteredProviderIds(){return[...new Set([...this.extensionProviders.keys(),...this.nativeExtensionProviders.keys()])]}getRegisteredNativeProvider(e){return this.nativeExtensionProviders.get(e)}getCompatibilityRequestConfig(e){return J(e,this.config.getProvider(e.provider),this.extensionProviders.get(e.provider))}isUsingOAuth(e){return this.snapshot.auth.get(e)?.type==="oauth"}isUsingSubscription(e){return this.isUsingOAuth(e)&&this.models.getProvider(e)?.auth.oauth?.isSubscription===!0}hasConfiguredAuth(e){return this.snapshot.configuredProviders.has(e)}async getAuth(e,t={}){if(typeof e=="string")return this.models.getAuth(e,t);const r=await this.models.getAuth(e,t);if(!r)return;const i=Q(e,this.config.getProvider(e.provider),this.extensionProviders.get(e.provider),{...r.env??{},...t.env??{}});return{...r,auth:{...r.auth,headers:q(r.auth.headers,i)}}}enqueueCredentialOperation(e,t,r){const i=this.credentialOperations.get(e)??Promise.resolve();let s;const o=new Promise(h=>{s=h}),a=(async()=>(await i.catch(()=>{}),t.throwIfAborted(),s?.(),r()))(),l=a.catch(()=>{});return this.credentialOperations.set(e,l),l.then(()=>{this.credentialOperations.get(e)===l&&this.credentialOperations.delete(e)}),z(o,t).then(()=>a)}async synchronizeCredentialState(e,t,r,i){try{i.throwIfAborted(),this.recomposeProvider(e);const s=this.compositionErrors.get(e);if(s)throw new Error(s);const o=await this.models.refresh({allowNetwork:!1,providers:[e],signal:i});o.aborted&&i.throwIfAborted();const a=o.errors.get(e);if(a)throw a;this.updateModelSnapshot(),await this.refreshProviderAvailability(e,i)}catch(s){throw new ie(e,t,r,{cause:s})}}setRuntimeApiKey(e,t,r={}){const i=m(r.signal);return this.enqueueCredentialOperation(e,i,async()=>{this.credentials.setRuntimeApiKey(e,t),await this.synchronizeCredentialState(e,"setRuntimeApiKey",{type:"api_key",key:t},i)})}removeRuntimeApiKey(e,t={}){const r=m(t.signal);return this.enqueueCredentialOperation(e,r,async()=>{this.credentials.removeRuntimeApiKey(e),await this.synchronizeCredentialState(e,"removeRuntimeApiKey",void 0,r)})}listCredentials(e){return this.credentials.list(e)}getProviderAuthStatus(e){if(this.credentials.hasRuntimeApiKey(e))return{configured:!0,source:"runtime"};if(this.snapshot.storedProviders.has(e))return{configured:!0,source:"stored"};const t=b(this.config.getProvider(e),this.extensionProviders.get(e));if(t)return t;const r=this.snapshot.auth.get(e);return r?{configured:!0,source:"environment",label:r.source}:{configured:!1}}async prepareRequest(e,t){const r=this.models.getProvider(e.provider);if(!r)throw new v("provider",`Unknown provider: ${e.provider}`);const i=await this.getAuth(e,{apiKey:t?.apiKey,env:t?.env,signal:t?.signal});if(!i)throw new v("auth",`Provider is not configured: ${e.provider}`);const{transformHeaders:s,...o}=t??{},a=o;let l=q(i.auth.headers,a.headers);s&&(l=await s(l??{}));const h=i.env||a.env?{...i.env??{},...a.env??{}}:void 0,n=i.auth.baseUrl?{...e,baseUrl:i.auth.baseUrl}:e;return{provider:r,model:n,options:{...a,apiKey:a.apiKey??i.auth.apiKey,headers:l,env:h}}}stream(e,t,r){const i=E(t);return w(e,async()=>{y(e);const s=await this.prepareRequest(e,r);return s.provider.stream(s.model,i,s.options)})}complete(e,t,r){return this.stream(e,t,r).result()}streamSimple(e,t,r){const i=E(t);return S(e)?w(e,async()=>{const s=await this.resolveModel(e,i.messages,{reason:"direct",thinkingLevel:r?.reasoning??"off",signal:r?.signal}),{maxTokens:o}=s.model,a=r?.maxTokens&&o>0?Math.min(r.maxTokens,o):r?.maxTokens,l=s.thinkingLevel==="off"?void 0:s.thinkingLevel,{apiKey:h,headers:n,env:d,...c}=r??{},u=s.model.provider===e.provider?{apiKey:h,headers:n,env:d}:{};return this.streamSimple(s.model,t,{...c,...u,maxTokens:a,reasoning:l})}):w(e,async()=>{y(e);const s=await this.prepareRequest(e,r);return s.provider.streamSimple(s.model,i,s.options)})}completeSimple(e,t,r){return this.streamSimple(e,t,r).result()}streamDeferred(e,t,r){return w(e,async()=>{y(e);const i=await this.prepareRequest(e,r);if(!i.provider.fetchDeferred)throw new v("provider",`Provider ${e.provider} does not support deferred responses`);return i.provider.fetchDeferred(i.model,t,i.options)})}async fetchDeferred(e,t,r){return this.streamDeferred(e,t,r).result()}async cancelDeferred(e,t,r){y(e);const i=await this.prepareRequest(e,r);if(!i.provider.cancelDeferred)throw new v("provider",`Provider ${e.provider} does not support deferred responses`);await i.provider.cancelDeferred(i.model,t,i.options)}async generateImages(e,t,r){try{K(e);const i=await this.prepareRequest(e,r);if(!i.provider.generateImages)throw new v("provider",`Provider ${e.provider} does not support image generation`);return await i.provider.generateImages(i.model,t,i.options)}catch(i){return D(e,i,r?.signal?.aborted)}}async classify(e,t,r){try{T(e),O(e,t);const i=await this.prepareRequest(e,r);if(!i.provider.classify)throw new v("provider",`Provider ${e.provider} does not support classification`);return await i.provider.classify(i.model,t,i.options)}catch(i){return L(e,i,r?.signal?.aborted)}}login(e,t,r,i){if(V()&&t==="oauth"&&!F(e))return Promise.reject(new Error(`OAuth sign-in for "${e}" is not available in ${A}.`));const s=m(r.signal);return this.enqueueCredentialOperation(e,s,async()=>{const o=await this.models.login(e,t,{...r,signal:s},i);return await this.synchronizeCredentialState(e,"login",o,s),o})}logout(e,t={}){const r=m(t.signal);return this.enqueueCredentialOperation(e,r,async()=>{await this.models.logout(e,{signal:r}),await this.synchronizeCredentialState(e,"logout",void 0,r)})}async refresh(e={}){const t=this.refreshNow(e);this.refreshesInFlight.add(t);try{return await t}finally{this.refreshesInFlight.delete(t)}}async refreshNow(e){const t={...e,allowNetwork:e.allowNetwork??this.modelNetworkEnabled},r=k.load(this.modelsPath),i=this.compositionTail;let s;const o=new Promise(n=>{s=n});this.compositionTail=Promise.all([i,o]).then(()=>{});let a;try{const n=await r;if(await i,this.config=n,this.configureRadiusProviders(),e.providers){for(const d of new Set(e.providers))this.recomposeProvider(d);this.updateModelSnapshot()}else this.rebuildProviders();a=this.models.refresh(t)}finally{s()}const l=await a??{aborted:t.signal?.aborted??!1,errors:new Map},h=new Map(l.errors);if(this.updateModelSnapshot(),e.providers)await Promise.all([...new Set(e.providers)].map(async n=>{try{await this.refreshProviderAvailability(n,m(e.signal))}catch(d){e.signal?.aborted||h.set(n,d instanceof Error?d:new Error(String(d)))}}));else try{await this.queueAvailabilityRefresh(e.signal)}catch{}return{aborted:l.aborted||(e.signal?.aborted??!1),errors:h}}async refreshCatalogsInPlace(e){await Promise.allSettled([...this.refreshesInFlight]);const t=await this.models.refresh({providers:e.providers,signal:e.signal,allowNetwork:this.modelNetworkEnabled});return this.updateModelSnapshot(),t}registerNativeProvider(e){if(!e.id.trim())throw new Error("Provider id must not be empty.");this.extensionProviders.delete(e.id),this.nativeExtensionProviders.set(e.id,e),this.recomposeProvider(e.id),this.updateModelSnapshot(),this.markProvisionallyConfigured(e.id,b(this.config.getProvider(e.id),void 0),e.auth.oauth&&!e.auth.apiKey?"oauth":"api_key"),this.refresh({allowNetwork:!1})}markProvisionallyConfigured(e,t,r){if(!this.snapshot.storedProviders.has(e)&&!t?.configured)return;const i=new Set(this.snapshot.configuredProviders).add(e),s=new Map(this.snapshot.auth);s.get(e)||s.set(e,{type:r,source:"configured provider"}),this.snapshot={...this.snapshot,auth:s,configuredProviders:i,available:this.snapshot.all.filter(o=>i.has(o.provider))}}registerProvider(e,t){X(e,this.builtins.get(e),this.config.getProvider(e),t),this.nativeExtensionProviders.delete(e);const i={...this.extensionProviders.get(e)};for(const[s,o]of Object.entries(t))o!==void 0&&(i[s]=o);this.extensionProviders.set(e,i),this.recomposeProvider(e),this.updateModelSnapshot(),this.markProvisionallyConfigured(e,b(this.config.getProvider(e),i),i.oauth&&!i.apiKey?"oauth":"api_key"),this.refresh({allowNetwork:!1})}unregisterProvider(e){this.extensionProviders.delete(e),this.nativeExtensionProviders.delete(e),this.recomposeProvider(e),this.updateModelSnapshot(),this.refresh({allowNetwork:!1})}registerVirtualModel(e){const{provider:t,id:r}=e;if(!t.trim()||!r.trim())throw new Error("Virtual model provider and id must not be empty.");const i=this.models.getModel(t,r);if(i&&!S(i))throw new Error(`Virtual model ${t}/${r} conflicts with a physical model.`);const s=this.virtualModels.get(t)??new Map;if(s.set(r,{model:ee(e),route:g(o=>e.route(o),"route")}),this.virtualModels.set(t,s),!this.recomposeProvider(t)&&!this.snapshot.configuredProviders.has(t)){const o=new Map(this.snapshot.auth).set(t,{type:"api_key",source:"virtual"}),a=new Set(this.snapshot.configuredProviders).add(t);this.snapshot={...this.snapshot,auth:o,configuredProviders:a}}this.updateModelSnapshot(),this.refresh({allowNetwork:!1})}unregisterVirtualModel(e,t){const r=this.virtualModels.get(e);r?.delete(t)&&(r.size===0&&this.virtualModels.delete(e),this.recomposeProvider(e),this.updateModelSnapshot(),this.refresh({allowNetwork:!1}))}async resolveModel(e,t,r){const i=`Virtual model ${e.provider}/${e.id}`,s=this.virtualModels.get(e.provider)?.get(e.id);if(!s)throw new Error(`${i} is not registered.`);const{failed:o,...a}=r,l=te(t),h=l&&this.getPhysicalModel(l.provider,l.model),n=o&&this.getPhysicalModel(o.provider,o.model),d=await s.route({...a,model:e,previous:h&&{model:h,thinkingLevel:l?.thinkingLevel},failed:n&&o&&{model:n,thinkingLevel:o.thinkingLevel,message:o},messages:t}),c=this.getPhysicalModel(d.model.provider,d.model.id),u=`${i} routed to ${d.model.provider}/${d.model.id}`;if(!c)throw new Error(`${u}, which is not a physical model.`);if(!this.hasConfiguredAuth(c.provider))throw new Error(`${u}, which has no credentials.`);return{model:c,thinkingLevel:$(c,d.thinkingLevel),state:d.state}}getPhysicalModel(e,t){const r=this.models.getModel(e,t);return r&&!S(r)?r:void 0}}export{ie as CredentialSynchronizationError,C as ModelRuntime,se as isBuiltinProviderEnabled};
|
|
@@ -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,
|
|
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;
|