dal-code 1.0.26 → 1.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dal-docs/settings.md +18 -2
  3. package/dist/core/agent-session.d.ts +13 -0
  4. package/dist/core/agent-session.js +9 -9
  5. package/dist/core/background-processes.js +4 -4
  6. package/dist/core/extensions/loader.js +1 -1
  7. package/dist/core/extensions/permission-surface.js +1 -1
  8. package/dist/core/extensions/runner.js +1 -1
  9. package/dist/core/extensions/types.d.ts +3 -0
  10. package/dist/core/sandbox/availability.d.ts +6 -1
  11. package/dist/core/sandbox/availability.js +1 -1
  12. package/dist/core/sandbox/denial.js +3 -3
  13. package/dist/core/sandbox/runtime.d.ts +10 -0
  14. package/dist/core/sandbox/runtime.js +1 -1
  15. package/dist/core/sandbox/shell-sandbox.d.ts +6 -0
  16. package/dist/core/sandbox/shell-sandbox.js +5 -5
  17. package/dist/core/sandbox/windows.d.ts +122 -0
  18. package/dist/core/sandbox/windows.js +5 -0
  19. package/dist/core/tools/bash.d.ts +1 -0
  20. package/dist/core/tools/bash.js +6 -6
  21. package/dist/core/tools/powershell.js +2 -2
  22. package/dist/modes/rpc/environment-update.js +1 -0
  23. package/dist/modes/rpc/rpc-client.d.ts +14 -0
  24. package/dist/modes/rpc/rpc-client.js +3 -3
  25. package/dist/modes/rpc/rpc-mode.d.ts +1 -0
  26. package/dist/modes/rpc/rpc-mode.js +1 -1
  27. package/dist/modes/rpc/rpc-types.d.ts +13 -0
  28. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  29. package/dist/node_modules/@dalcode/dal-bridge/src/index.js +1 -1
  30. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  31. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  32. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  33. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  34. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  35. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  36. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  37. package/dist/node_modules/@dalcode/dal-mcp/src/add-wizard.js +1 -1
  38. package/dist/node_modules/@dalcode/dal-mcp/src/config.d.ts +1 -1
  39. package/dist/node_modules/@dalcode/dal-mcp/src/config.js +1 -1
  40. package/dist/node_modules/@dalcode/dal-mcp/src/index.js +18 -18
  41. package/dist/node_modules/@dalcode/dal-mcp/src/proxy.js +6 -6
  42. package/dist/node_modules/@dalcode/dal-mcp/src/report.js +1 -1
  43. package/dist/node_modules/@dalcode/dal-mcp/src/types.d.ts +1 -1
  44. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  45. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
  46. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  47. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
  48. package/dist/node_modules/@dalcode/dal-plugins/package.json +2 -2
  49. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  50. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  51. package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
  52. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  53. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  54. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  55. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  56. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  57. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  58. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  59. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  60. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  61. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +4 -4
  62. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  63. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  64. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/anthropic.json +1 -1
  65. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  66. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  67. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
  68. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  69. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  70. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
  71. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  72. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  73. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  74. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  75. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  76. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  77. package/dist/node_modules/@earendil-works/pi-server/package.json +5 -5
  78. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/package.json +3 -3
  79. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  80. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  81. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  82. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  83. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  84. package/examples/extensions/gondolin/package-lock.json +2 -2
  85. package/examples/extensions/gondolin/package.json +1 -1
  86. package/examples/extensions/sandbox/package-lock.json +2 -2
  87. package/examples/extensions/sandbox/package.json +1 -1
  88. package/examples/extensions/with-deps/package-lock.json +2 -2
  89. package/examples/extensions/with-deps/package.json +1 -1
  90. package/npm-shrinkwrap.json +10 -2
  91. package/package.json +9 -1
@@ -1 +1 @@
1
- var v=Object.defineProperty;var a=(l,e)=>v(l,"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"],k=a(l=>{const e={};for(const[s,t]of Object.entries(l)){if(t===void 0)continue;const o=Array.isArray(t)?t:[t],i=S.includes(s);for(const n of o){const r=n.toLowerCase();e[r]?.restrictOverride&&!i||(e[r]={keybinding:s,restrictOverride:i})}}return e},"buildBuiltinKeybindings");function _(l){if(typeof l!="object"||l===null)return!1;const e=l,s=e.operations!==void 0,t=e.result!==void 0;if(s===t)return!1;if(s){const n=e.operations;return typeof n!="object"||n===null?!1:typeof n.exec=="function"}const o=e.result;if(typeof o!="object"||o===null)return!1;const i=o;return typeof i.output=="string"&&"exitCode"in i&&(i.exitCode===void 0||typeof i.exitCode=="number")&&typeof i.cancelled=="boolean"&&typeof i.truncated=="boolean"&&(i.fullOutputPath===void 0||typeof i.fullOutputPath=="string")}a(_,"isUserBashEventResult");async function F(l,e){return l.hasHandlers("session_shutdown")?(await l.emit(e),!0):!1}a(F,"emitSessionShutdownEvent");function m(l,e){return l.map(s=>({ext:s,handlers:s.handlers.get(e)?.slice()??[]}))}a(m,"snapshotEventHandlers");function x(l,e){return l.length===e.length&&l.every((s,t)=>s===e[t])}a(x,"sameMessages");function C(l,e,s){if(x(s,e))return l;const t=P(l);return t?[t,...s]:s}a(C,"restoreSystemMessages");async function I(l,e,s){const t=[];for(const{ext:o,handlers:i}of m(l.extensions,"project_trust"))for(const n of i)try{const r=await n(e,s);if(r.trusted==="undecided")continue;return{result:r,errors:t}}catch(r){t.push({extensionPath:o.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 y={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(l=>({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");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,o,i){this.extensions=e,this.runtime=s,this.uiContext=y,this.cwd=t,this.sessionManager=o,this.modelRegistry=i}bindCore(e,s,t){this.runtime.sendMessage=e.sendMessage,this.runtime.sendUserMessage=e.sendUserMessage,this.runtime.appendEntry=e.appendEntry,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.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.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}));for(const{name:o,config:i,extensionPath:n}of this.runtime.pendingProviderRegistrations)try{t?.registerProvider?t.registerProvider(o,i):this.modelRegistry.registerProvider(o,i)}catch(r){this.emitError({extensionPath:n,event:"register_provider",error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}this.runtime.pendingProviderRegistrations=[];for(const{provider:o,extensionPath:i}of this.runtime.pendingNativeProviderRegistrations)try{t?.registerNativeProvider?t.registerNativeProvider(o):this.modelRegistry.registerProvider(o)}catch(n){this.emitError({extensionPath:i,event:"register_provider",error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0})}this.runtime.pendingNativeProviderRegistrations=[],this.runtime.registerProvider=(o,i)=>{if(t?.registerProvider){t.registerProvider(o,i);return}this.modelRegistry.registerProvider(o,i)},this.runtime.registerNativeProvider=o=>{if(t?.registerNativeProvider){t.registerNativeProvider(o);return}this.modelRegistry.registerProvider(o)},this.runtime.unregisterProvider=o=>{if(t?.unregisterProvider){t.unregisterProvider(o);return}this.modelRegistry.unregisterProvider(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):y,this.mode=s}wrapUIPromptContext(e){return{...e,select:a((s,t,o)=>this.withUIPrompt("select",s,()=>e.select(s,t,o)),"select"),confirm:a((s,t,o)=>this.withUIPrompt("confirm",s,()=>e.confirm(s,t,o)),"confirm"),input:a((s,t,o)=>this.withUIPrompt("input",s,()=>e.input(s,t,o)),"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 i=a(()=>{if(--this.uiPromptDepth>0)return;this.uiPromptDepth=0;const n=this.activeUIPrompt??{kind:e,title:s};this.activeUIPrompt=void 0,this.emitUIPromptEvent({type:"ui_prompt_end",reason:"ui_prompt",kind:n.kind,...n.title?{title:n.title}:{}})},"finish");try{return t().finally(i)}catch(n){throw i(),n}}emitUIPromptEvent(e){queueMicrotask(()=>{this.emit(e)})}getUIContext(){return this.uiContext}hasUI(){return this.uiContext!==y}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,o]of s.flags)e.has(t)||e.set(t,o);return e}setFlagValue(e,s){this.runtime.flagValues.set(e,s)}getFlagValues(){return new Map(this.runtime.flagValues)}getShortcuts(e){this.shortcutDiagnostics=[];const s=k(e),t=new Map,o=a((i,n)=>{this.shortcutDiagnostics.push({type:"warning",message:i,path:n}),this.hasUI()||console.warn(i)},"addDiagnostic");for(const i of this.extensions)for(const[n,r]of i.shortcuts){const c=n.toLowerCase(),h=s[c];if(h?.restrictOverride===!0){o(`Extension shortcut '${n}' from ${r.extensionPath} conflicts with built-in shortcut. Skipping.`,r.extensionPath);continue}h?.restrictOverride===!1&&o(`Extension shortcut conflict: '${n}' is built-in shortcut for ${h.keybinding} and ${r.extensionPath}. Using ${r.extensionPath}.`,r.extensionPath);const f=t.get(c);f&&o(`Extension shortcut conflict: '${n}' 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)}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()??[]])}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 i of this.extensions)for(const n of i.commands.values())e.push(n),s.set(n.name,(s.get(n.name)??0)+1);const t=new Map,o=new Set;return e.map(i=>{const n=(t.get(i.name)??0)+1;t.set(i.name,n);let r=(s.get(i.name)??0)>1?`${i.name}:${n}`:i.name;if(o.has(r)){let c=n;do c++,r=`${i.name}:${c}`;while(o.has(r))}return o.add(r),{...i,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(o=>{e.assertActive(),e.compactFn(o)},"compact"),getSystemPrompt:a(()=>(e.assertActive(),e.getSystemPromptFn()),"getSystemPrompt")}}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 o=[],i=!1,n=await s(o),r=!0;for(const{ext:c,handlers:h}of m(this.extensions,e.type))for(const f of h){const u={...e,entries:o,continue:i,context:n};try{const d=await f(u,t);d?.entries!==void 0&&(o=d.entries),d?.continue!==void 0&&(i=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{n=await s(o),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:o,continue:i,context:n,valid:!0}:{entries:[],continue:!1,context:n,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:o,handlers:i}of m(this.extensions,e.type))for(const n of i)try{const r=await n(e,s);if(this.isSessionBeforeEvent(e)&&r&&(t=r,t.cancel))return t}catch(r){const c=r instanceof Error?r.message:String(r),h=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:o.path,event:e.type,error:c,stack:h})}return t}async emitCacheWarmingDecision(e){const s=this.createContext();let t=e.action;for(const{ext:o,handlers:i}of m(this.extensions,e.type))for(const n of i)try{const r=await n(e,s);r?.action!==void 0&&(t=r.action)}catch(r){this.emitError({extensionPath:o.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,o=!1;for(const{ext:i,handlers:n}of m(this.extensions,"message_end"))for(const r of n)try{const c={...e,message:t},h=await r(c,s);if(!h?.message)continue;if(h.message.role!==t.role){this.emitError({extensionPath:i.path,event:"message_end",error:"message_end handlers must return a message with the same role"});continue}t=h.message,o=!0}catch(c){const h=c instanceof Error?c.message:String(c),f=c instanceof Error?c.stack:void 0;this.emitError({extensionPath:i.path,event:"message_end",error:h,stack:f})}return o?t:void 0}async emitToolResult(e){const s=this.createContext(),t={...e};let o=!1;for(const{ext:i,handlers:n}of m(this.extensions,"tool_result"))for(const r of n)try{const c=await r(t,s);if(!c)continue;c.content!==void 0&&(t.content=c.content,o=!0),c.details!==void 0&&(t.details=c.details,o=!0),c.isError!==void 0&&(t.isError=c.isError,o=!0),c.usage!==void 0&&(t.usage=c.usage,o=!0)}catch(c){const h=c instanceof Error?c.message:String(c),f=c instanceof Error?c.stack:void 0;this.emitError({extensionPath:i.path,event:"tool_result",error:h,stack:f})}if(o)return{content:t.content,details:t.details,isError:t.isError,usage:t.usage}}async emitToolCall(e){const s=this.createContext();let t;for(const{handlers:o}of m(this.extensions,"tool_call"))for(const i of o){const n=await i(e,s);if(n&&(t=n,t.block))return t}return t}async emitUserBash(e){const s=this.createContext();for(const{ext:t,handlers:o}of m(this.extensions,"user_bash"))for(const i of o)try{const n=await i(e,s);if(n===void 0)continue;if(!_(n))throw new Error("Invalid user_bash handler result: return undefined for local execution or exactly one valid { operations } or { result } object");return n}catch(n){const r=n instanceof Error?n.message:String(n),c=n instanceof Error?n.stack:void 0;throw this.emitError({extensionPath:t.path,event:"user_bash",error:r,stack:c}),n}}async emitContext(e){const s=this.createContext();let t=structuredClone(e);for(const{ext:o,handlers:i}of m(this.extensions,"context"))for(const n of i)try{const r=t.filter(d=>d.role!=="system"),c=r.slice(),u=(await n({type:"context",messages:r},s))?.messages??(x(r,c)?void 0:r);if(!u)continue;t=C(t,c,u)}catch(r){const c=r instanceof Error?r.message:String(r),h=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:o.path,event:"context",error:c,stack:h})}for(const{ext:o,handlers:i}of m(this.extensions,"context_with_system"))for(const n of i)try{const r=t[0]?.role==="system";t=(await n({type:"context_with_system",messages:t},s))?.messages??t,r&&t[0]?.role!=="system"&&this.emitError({extensionPath:o.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),h=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:o.path,event:"context_with_system",error:c,stack:h})}return t}async emitBeforeProviderRequest(e){const s=this.createContext();let t=e;for(const{ext:o,handlers:i}of m(this.extensions,"before_provider_request"))for(const n of i)try{const c=await n({type:"before_provider_request",payload:t},s);c!==void 0&&(t=c)}catch(r){const c=r instanceof Error?r.message:String(r),h=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:o.path,event:"before_provider_request",error:c,stack:h})}return t}async emitBeforeProviderHeaders(e){const s=this.createContext();for(const{ext:t,handlers:o}of m(this.extensions,"before_provider_headers"))for(const i of o)try{await i({type:"before_provider_headers",headers:e},s)}catch(n){const r=n instanceof Error?n.message:String(n),c=n instanceof Error?n.stack:void 0;this.emitError({extensionPath:t.path,event:"before_provider_headers",error:r,stack:c})}return e}async emitBeforeAgentStart(e,s,t){const o=p(t),i=a(()=>E(o),"renderCurrentSystemPrompt"),n=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext()));n.getSystemPrompt=()=>(this.assertActive(),i());const r=[];for(const{ext:c,handlers:h}of m(this.extensions,"before_agent_start"))for(const f of h)try{const d=await f({type:"before_agent_start",prompt:e,images:s,get systemPrompt(){return i()},systemPromptOptions:o},n);if(d){const g=d;g.message&&r.push(g.message),g.systemPrompt!==void 0&&(o.forceSystemPrompt=g.systemPrompt)}}catch(u){const d=u instanceof Error?u.message:String(u),g=u instanceof Error?u.stack:void 0;this.emitError({extensionPath:c.path,event:"before_agent_start",error:d,stack:g})}return{messages:r,systemPromptOptions:o}}async emitResourcesDiscover(e,s){const t=this.createContext(),o=[],i=[],n=[];for(const{ext:r,handlers:c}of m(this.extensions,"resources_discover"))for(const h of c)try{const d=await h({type:"resources_discover",cwd:e,reason:s},t);d?.skillPaths?.length&&o.push(...d.skillPaths.map(g=>({path:g,extensionPath:r.path}))),d?.promptPaths?.length&&i.push(...d.promptPaths.map(g=>({path:g,extensionPath:r.path}))),d?.themePaths?.length&&n.push(...d.themePaths.map(g=>({path:g,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:o,promptPaths:i,themePaths:n}}async emitInput(e,s,t,o){const i=this.createContext();let n=e,r=s;for(const{ext:c,handlers:h}of m(this.extensions,"input"))for(const f of h)try{const d=await f({type:"input",text:n,images:r,source:t,streamingBehavior:o},i);if(d?.action==="handled")return d;d?.action==="transform"&&(n=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 n!==e||r!==s?{action:"transform",text:n,images:r}:{action:"continue"}}}export{U as ExtensionRunner,I as emitProjectTrustEvent,F as emitSessionShutdownEvent};
1
+ var v=Object.defineProperty;var a=(l,e)=>v(l,"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"],k=a(l=>{const e={};for(const[s,t]of Object.entries(l)){if(t===void 0)continue;const o=Array.isArray(t)?t:[t],i=S.includes(s);for(const n of o){const r=n.toLowerCase();e[r]?.restrictOverride&&!i||(e[r]={keybinding:s,restrictOverride:i})}}return e},"buildBuiltinKeybindings");function _(l){if(typeof l!="object"||l===null)return!1;const e=l,s=e.operations!==void 0,t=e.result!==void 0;if(s===t)return!1;if(s){const n=e.operations;return typeof n!="object"||n===null?!1:typeof n.exec=="function"}const o=e.result;if(typeof o!="object"||o===null)return!1;const i=o;return typeof i.output=="string"&&"exitCode"in i&&(i.exitCode===void 0||typeof i.exitCode=="number")&&typeof i.cancelled=="boolean"&&typeof i.truncated=="boolean"&&(i.fullOutputPath===void 0||typeof i.fullOutputPath=="string")}a(_,"isUserBashEventResult");async function F(l,e){return l.hasHandlers("session_shutdown")?(await l.emit(e),!0):!1}a(F,"emitSessionShutdownEvent");function m(l,e){return l.map(s=>({ext:s,handlers:s.handlers.get(e)?.slice()??[]}))}a(m,"snapshotEventHandlers");function x(l,e){return l.length===e.length&&l.every((s,t)=>s===e[t])}a(x,"sameMessages");function C(l,e,s){if(x(s,e))return l;const t=P(l);return t?[t,...s]:s}a(C,"restoreSystemMessages");async function I(l,e,s){const t=[];for(const{ext:o,handlers:i}of m(l.extensions,"project_trust"))for(const n of i)try{const r=await n(e,s);if(r.trusted==="undecided")continue;return{result:r,errors:t}}catch(r){t.push({extensionPath:o.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 y={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(l=>({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");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,o,i){this.extensions=e,this.runtime=s,this.uiContext=y,this.cwd=t,this.sessionManager=o,this.modelRegistry=i}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.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.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}));for(const{name:o,config:i,extensionPath:n}of this.runtime.pendingProviderRegistrations)try{t?.registerProvider?t.registerProvider(o,i):this.modelRegistry.registerProvider(o,i)}catch(r){this.emitError({extensionPath:n,event:"register_provider",error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0})}this.runtime.pendingProviderRegistrations=[];for(const{provider:o,extensionPath:i}of this.runtime.pendingNativeProviderRegistrations)try{t?.registerNativeProvider?t.registerNativeProvider(o):this.modelRegistry.registerProvider(o)}catch(n){this.emitError({extensionPath:i,event:"register_provider",error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0})}this.runtime.pendingNativeProviderRegistrations=[],this.runtime.registerProvider=(o,i)=>{if(t?.registerProvider){t.registerProvider(o,i);return}this.modelRegistry.registerProvider(o,i)},this.runtime.registerNativeProvider=o=>{if(t?.registerNativeProvider){t.registerNativeProvider(o);return}this.modelRegistry.registerProvider(o)},this.runtime.unregisterProvider=o=>{if(t?.unregisterProvider){t.unregisterProvider(o);return}this.modelRegistry.unregisterProvider(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):y,this.mode=s}wrapUIPromptContext(e){return{...e,select:a((s,t,o)=>this.withUIPrompt("select",s,()=>e.select(s,t,o)),"select"),confirm:a((s,t,o)=>this.withUIPrompt("confirm",s,()=>e.confirm(s,t,o)),"confirm"),input:a((s,t,o)=>this.withUIPrompt("input",s,()=>e.input(s,t,o)),"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 i=a(()=>{if(--this.uiPromptDepth>0)return;this.uiPromptDepth=0;const n=this.activeUIPrompt??{kind:e,title:s};this.activeUIPrompt=void 0,this.emitUIPromptEvent({type:"ui_prompt_end",reason:"ui_prompt",kind:n.kind,...n.title?{title:n.title}:{}})},"finish");try{return t().finally(i)}catch(n){throw i(),n}}emitUIPromptEvent(e){queueMicrotask(()=>{this.emit(e)})}getUIContext(){return this.uiContext}hasUI(){return this.uiContext!==y}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,o]of s.flags)e.has(t)||e.set(t,o);return e}setFlagValue(e,s){this.runtime.flagValues.set(e,s)}getFlagValues(){return new Map(this.runtime.flagValues)}getShortcuts(e){this.shortcutDiagnostics=[];const s=k(e),t=new Map,o=a((i,n)=>{this.shortcutDiagnostics.push({type:"warning",message:i,path:n}),this.hasUI()||console.warn(i)},"addDiagnostic");for(const i of this.extensions)for(const[n,r]of i.shortcuts){const c=n.toLowerCase(),h=s[c];if(h?.restrictOverride===!0){o(`Extension shortcut '${n}' from ${r.extensionPath} conflicts with built-in shortcut. Skipping.`,r.extensionPath);continue}h?.restrictOverride===!1&&o(`Extension shortcut conflict: '${n}' is built-in shortcut for ${h.keybinding} and ${r.extensionPath}. Using ${r.extensionPath}.`,r.extensionPath);const f=t.get(c);f&&o(`Extension shortcut conflict: '${n}' 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)}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()??[]])}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 i of this.extensions)for(const n of i.commands.values())e.push(n),s.set(n.name,(s.get(n.name)??0)+1);const t=new Map,o=new Set;return e.map(i=>{const n=(t.get(i.name)??0)+1;t.set(i.name,n);let r=(s.get(i.name)??0)>1?`${i.name}:${n}`:i.name;if(o.has(r)){let c=n;do c++,r=`${i.name}:${c}`;while(o.has(r))}return o.add(r),{...i,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(o=>{e.assertActive(),e.compactFn(o)},"compact"),getSystemPrompt:a(()=>(e.assertActive(),e.getSystemPromptFn()),"getSystemPrompt")}}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 o=[],i=!1,n=await s(o),r=!0;for(const{ext:c,handlers:h}of m(this.extensions,e.type))for(const f of h){const u={...e,entries:o,continue:i,context:n};try{const d=await f(u,t);d?.entries!==void 0&&(o=d.entries),d?.continue!==void 0&&(i=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{n=await s(o),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:o,continue:i,context:n,valid:!0}:{entries:[],continue:!1,context:n,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:o,handlers:i}of m(this.extensions,e.type))for(const n of i)try{const r=await n(e,s);if(this.isSessionBeforeEvent(e)&&r&&(t=r,t.cancel))return t}catch(r){const c=r instanceof Error?r.message:String(r),h=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:o.path,event:e.type,error:c,stack:h})}return t}async emitCacheWarmingDecision(e){const s=this.createContext();let t=e.action;for(const{ext:o,handlers:i}of m(this.extensions,e.type))for(const n of i)try{const r=await n(e,s);r?.action!==void 0&&(t=r.action)}catch(r){this.emitError({extensionPath:o.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,o=!1;for(const{ext:i,handlers:n}of m(this.extensions,"message_end"))for(const r of n)try{const c={...e,message:t},h=await r(c,s);if(!h?.message)continue;if(h.message.role!==t.role){this.emitError({extensionPath:i.path,event:"message_end",error:"message_end handlers must return a message with the same role"});continue}t=h.message,o=!0}catch(c){const h=c instanceof Error?c.message:String(c),f=c instanceof Error?c.stack:void 0;this.emitError({extensionPath:i.path,event:"message_end",error:h,stack:f})}return o?t:void 0}async emitToolResult(e){const s=this.createContext(),t={...e};let o=!1;for(const{ext:i,handlers:n}of m(this.extensions,"tool_result"))for(const r of n)try{const c=await r(t,s);if(!c)continue;c.content!==void 0&&(t.content=c.content,o=!0),c.details!==void 0&&(t.details=c.details,o=!0),c.isError!==void 0&&(t.isError=c.isError,o=!0),c.usage!==void 0&&(t.usage=c.usage,o=!0)}catch(c){const h=c instanceof Error?c.message:String(c),f=c instanceof Error?c.stack:void 0;this.emitError({extensionPath:i.path,event:"tool_result",error:h,stack:f})}if(o)return{content:t.content,details:t.details,isError:t.isError,usage:t.usage}}async emitToolCall(e){const s=this.createContext();let t;for(const{handlers:o}of m(this.extensions,"tool_call"))for(const i of o){const n=await i(e,s);if(n&&(t=n,t.block))return t}return t}async emitUserBash(e){const s=this.createContext();for(const{ext:t,handlers:o}of m(this.extensions,"user_bash"))for(const i of o)try{const n=await i(e,s);if(n===void 0)continue;if(!_(n))throw new Error("Invalid user_bash handler result: return undefined for local execution or exactly one valid { operations } or { result } object");return n}catch(n){const r=n instanceof Error?n.message:String(n),c=n instanceof Error?n.stack:void 0;throw this.emitError({extensionPath:t.path,event:"user_bash",error:r,stack:c}),n}}async emitContext(e){const s=this.createContext();let t=structuredClone(e);for(const{ext:o,handlers:i}of m(this.extensions,"context"))for(const n of i)try{const r=t.filter(d=>d.role!=="system"),c=r.slice(),u=(await n({type:"context",messages:r},s))?.messages??(x(r,c)?void 0:r);if(!u)continue;t=C(t,c,u)}catch(r){const c=r instanceof Error?r.message:String(r),h=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:o.path,event:"context",error:c,stack:h})}for(const{ext:o,handlers:i}of m(this.extensions,"context_with_system"))for(const n of i)try{const r=t[0]?.role==="system";t=(await n({type:"context_with_system",messages:t},s))?.messages??t,r&&t[0]?.role!=="system"&&this.emitError({extensionPath:o.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),h=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:o.path,event:"context_with_system",error:c,stack:h})}return t}async emitBeforeProviderRequest(e){const s=this.createContext();let t=e;for(const{ext:o,handlers:i}of m(this.extensions,"before_provider_request"))for(const n of i)try{const c=await n({type:"before_provider_request",payload:t},s);c!==void 0&&(t=c)}catch(r){const c=r instanceof Error?r.message:String(r),h=r instanceof Error?r.stack:void 0;this.emitError({extensionPath:o.path,event:"before_provider_request",error:c,stack:h})}return t}async emitBeforeProviderHeaders(e){const s=this.createContext();for(const{ext:t,handlers:o}of m(this.extensions,"before_provider_headers"))for(const i of o)try{await i({type:"before_provider_headers",headers:e},s)}catch(n){const r=n instanceof Error?n.message:String(n),c=n instanceof Error?n.stack:void 0;this.emitError({extensionPath:t.path,event:"before_provider_headers",error:r,stack:c})}return e}async emitBeforeAgentStart(e,s,t){const o=p(t),i=a(()=>E(o),"renderCurrentSystemPrompt"),n=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext()));n.getSystemPrompt=()=>(this.assertActive(),i());const r=[];for(const{ext:c,handlers:h}of m(this.extensions,"before_agent_start"))for(const f of h)try{const d=await f({type:"before_agent_start",prompt:e,images:s,get systemPrompt(){return i()},systemPromptOptions:o},n);if(d){const g=d;g.message&&r.push(g.message),g.systemPrompt!==void 0&&(o.forceSystemPrompt=g.systemPrompt)}}catch(u){const d=u instanceof Error?u.message:String(u),g=u instanceof Error?u.stack:void 0;this.emitError({extensionPath:c.path,event:"before_agent_start",error:d,stack:g})}return{messages:r,systemPromptOptions:o}}async emitResourcesDiscover(e,s){const t=this.createContext(),o=[],i=[],n=[];for(const{ext:r,handlers:c}of m(this.extensions,"resources_discover"))for(const h of c)try{const d=await h({type:"resources_discover",cwd:e,reason:s},t);d?.skillPaths?.length&&o.push(...d.skillPaths.map(g=>({path:g,extensionPath:r.path}))),d?.promptPaths?.length&&i.push(...d.promptPaths.map(g=>({path:g,extensionPath:r.path}))),d?.themePaths?.length&&n.push(...d.themePaths.map(g=>({path:g,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:o,promptPaths:i,themePaths:n}}async emitInput(e,s,t,o){const i=this.createContext();let n=e,r=s;for(const{ext:c,handlers:h}of m(this.extensions,"input"))for(const f of h)try{const d=await f({type:"input",text:n,images:r,source:t,streamingBehavior:o},i);if(d?.action==="handled")return d;d?.action==="transform"&&(n=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 n!==e||r!==s?{action:"transform",text:n,images:r}:{action:"continue"}}}export{U as ExtensionRunner,I as emitProjectTrustEvent,F as emitSessionShutdownEvent};
@@ -783,6 +783,7 @@ export interface ExtensionAPI {
783
783
  expandPromptTemplates?: boolean;
784
784
  }): Promise<void>;
785
785
  appendEntry<T = unknown>(customType: string, data?: T): void;
786
+ emitHostEvent(name: string, data?: unknown): void;
786
787
  setSessionName(name: string): void;
787
788
  getSessionName(): string | undefined;
788
789
  setLabel(entryId: string, label: string | undefined): void;
@@ -872,6 +873,7 @@ export type SendUserMessageHandler = (content: string | (TextContent | ImageCont
872
873
  expandPromptTemplates?: boolean;
873
874
  }) => void;
874
875
  export type AppendEntryHandler = <T = unknown>(customType: string, data?: T) => void;
876
+ export type EmitHostEventHandler = (name: string, data?: unknown) => void;
875
877
  export type SetSessionNameHandler = (name: string) => void;
876
878
  export type GetSessionNameHandler = () => string | undefined;
877
879
  export type GetActiveToolsHandler = () => string[];
@@ -911,6 +913,7 @@ export interface ExtensionActions {
911
913
  sendMessage: SendMessageHandler;
912
914
  sendUserMessage: SendUserMessageHandler;
913
915
  appendEntry: AppendEntryHandler;
916
+ emitHostEvent?: EmitHostEventHandler;
914
917
  setSessionName: SetSessionNameHandler;
915
918
  getSessionName: GetSessionNameHandler;
916
919
  setLabel: SetLabelHandler;
@@ -1,9 +1,14 @@
1
+ import { type MxcRuntime } from "./windows.ts";
1
2
  export interface SandboxAvailability {
2
3
  available: boolean;
3
4
  platform: NodeJS.Platform;
4
- mechanism?: "seatbelt" | "bubblewrap";
5
+ mechanism?: "seatbelt" | "bubblewrap" | "mxc";
5
6
  reason?: string;
6
7
  ripgrep?: string;
8
+ mxc?: MxcRuntime;
9
+ isolationTier?: string;
10
+ isolationWarnings?: string[];
11
+ limitations?: readonly string[];
7
12
  }
8
13
  export declare function detectSandboxAvailability(): SandboxAvailability;
9
14
  export declare function setSandboxAvailabilityForTesting(value: SandboxAvailability | undefined): void;
@@ -1 +1 @@
1
- var b=Object.defineProperty;var r=(e,t)=>b(e,"name",{value:t,configurable:!0});import{spawnSync as n}from"node:child_process";import{existsSync as c}from"node:fs";import{getToolPath as l}from"../../utils/tools-manager.js";let a,i;function p(e){const t=n("which",[e],{encoding:"utf8",timeout:2e3});return t.status===0&&t.stdout.trim()||void 0}r(p,"which");function u(e){return`${e.stderr??""}${e.stdout??""}`.trim()||(e.error?e.error.message:`exit code ${e.status}`)}r(u,"probeOutput");function f(){const e="/usr/bin/sandbox-exec";if(!c(e))return{available:!1,platform:"darwin",reason:`${e} is missing.`};const t=n(e,["-p","(version 1)(allow default)","/usr/bin/true"],{encoding:"utf8",timeout:5e3});return t.status!==0?{available:!1,platform:"darwin",mechanism:"seatbelt",reason:`sandbox-exec cannot apply a profile here (${u(t)}). This happens when dal itself runs inside another sandbox.`}:{available:!0,platform:"darwin",mechanism:"seatbelt",ripgrep:l("rg")??"rg"}}r(f,"detectDarwin");function d(){const e=[],t=p("bwrap");t||e.push("bubblewrap (bwrap)");const s=l("rg")??p("rg");if(s||e.push("ripgrep (rg)"),e.length>0)return{available:!1,platform:"linux",mechanism:"bubblewrap",reason:`missing ${e.join(", ")}. Install them (e.g. \`apt install bubblewrap socat ripgrep\`).`};const o=n(t,["--new-session","--die-with-parent","--ro-bind","/","/","--dev","/dev","--unshare-net","--unshare-pid","--proc","/proc","--","true"],{encoding:"utf8",timeout:5e3});return o.status!==0?{available:!1,platform:"linux",mechanism:"bubblewrap",reason:`bubblewrap cannot create its namespaces here (${u(o)}). Containers often forbid unprivileged user namespaces.`}:{available:!0,platform:"linux",mechanism:"bubblewrap",ripgrep:s}}r(d,"detectLinux");function g(){if(i)return i;if(a)return a;switch(process.platform){case"darwin":a=f();break;case"linux":a=d();break;case"win32":a={available:!1,platform:"win32",reason:"Windows is not supported by the OS sandbox yet."};break;default:a={available:!1,platform:process.platform,reason:`the OS sandbox does not support ${process.platform}.`}}return a}r(g,"detectSandboxAvailability");function v(e){i=e}r(v,"setSandboxAvailabilityForTesting");export{g as detectSandboxAvailability,v as setSandboxAvailabilityForTesting};
1
+ var c=Object.defineProperty;var a=(e,r)=>c(e,"name",{value:r,configurable:!0});import{spawnSync as t}from"node:child_process";import{existsSync as m}from"node:fs";import{getToolPath as l}from"../../utils/tools-manager.js";import{loadMxcRuntime as b,probeWindowsSandbox as f,WINDOWS_SANDBOX_LIMITATIONS as d}from"./windows.js";let n,i;function p(e){const r=t("which",[e],{encoding:"utf8",timeout:2e3});return r.status===0&&r.stdout.trim()||void 0}a(p,"which");function u(e){return`${e.stderr??""}${e.stdout??""}`.trim()||(e.error?e.error.message:`exit code ${e.status}`)}a(u,"probeOutput");function h(){const e="/usr/bin/sandbox-exec";if(!m(e))return{available:!1,platform:"darwin",reason:`${e} is missing.`};const r=t(e,["-p","(version 1)(allow default)","/usr/bin/true"],{encoding:"utf8",timeout:5e3});return r.status!==0?{available:!1,platform:"darwin",mechanism:"seatbelt",reason:`sandbox-exec cannot apply a profile here (${u(r)}). This happens when dal itself runs inside another sandbox.`}:{available:!0,platform:"darwin",mechanism:"seatbelt",ripgrep:l("rg")??"rg"}}a(h,"detectDarwin");function w(){const e=[],r=p("bwrap");r||e.push("bubblewrap (bwrap)");const o=l("rg")??p("rg");if(o||e.push("ripgrep (rg)"),e.length>0)return{available:!1,platform:"linux",mechanism:"bubblewrap",reason:`missing ${e.join(", ")}. Install them (e.g. \`apt install bubblewrap socat ripgrep\`).`};const s=t(r,["--new-session","--die-with-parent","--ro-bind","/","/","--dev","/dev","--unshare-net","--unshare-pid","--proc","/proc","--","true"],{encoding:"utf8",timeout:5e3});return s.status!==0?{available:!1,platform:"linux",mechanism:"bubblewrap",reason:`bubblewrap cannot create its namespaces here (${u(s)}). Containers often forbid unprivileged user namespaces.`}:{available:!0,platform:"linux",mechanism:"bubblewrap",ripgrep:o}}a(w,"detectLinux");function x(){const e=b();if("error"in e)return{available:!1,platform:"win32",mechanism:"mxc",reason:e.error};const r=f(e);return r.ok?{available:!0,platform:"win32",mechanism:"mxc",mxc:e,...r.support.isolationTier?{isolationTier:r.support.isolationTier}:{},...r.support.isolationWarnings?.length?{isolationWarnings:r.support.isolationWarnings}:{},limitations:d}:{available:!1,platform:"win32",mechanism:"mxc",reason:r.reason}}a(x,"detectWindows");function W(){if(i)return i;if(n)return n;switch(process.platform){case"darwin":n=h();break;case"linux":n=w();break;case"win32":n=x();break;default:n={available:!1,platform:process.platform,reason:`the OS sandbox does not support ${process.platform}.`}}return n}a(W,"detectSandboxAvailability");function y(e){i=e}a(y,"setSandboxAvailabilityForTesting");export{W as detectSandboxAvailability,y as setSandboxAvailabilityForTesting};
@@ -1,3 +1,3 @@
1
- var u=Object.defineProperty;var i=(r,t)=>u(r,"name",{value:t,configurable:!0});const m=20;function f(r){const t=/deny(?:\(\d+\))?\s+(?<operation>[\w-]+)\s+(?<target>.+?)\s*$/.exec(r);if(!t?.groups)return;const{operation:o,target:e}=t.groups;if(o.startsWith("file-write"))return{kind:"file-write",target:e,source:"kernel",detail:o};if(o.startsWith("file-read"))return{kind:"file-read",target:e,source:"kernel",detail:o};if(o.startsWith("network"))return{kind:"network",target:e,source:"kernel",detail:o}}i(f,"parseViolationLine");const p=[{regex:/(?<target>\/[^\s:'"`]+)['"`]?:\s*Read-only file system/,kind:"file-write"},{regex:/Read-only file system[^/\n]*(?<target>\/[^\s'"`]+)/,kind:"file-write"},{regex:/['"`]?(?<target>\/[^\s:'"`]+)['"`]?:\s*Operation not permitted/,kind:"file-write"},{regex:/EPERM: operation not permitted, \w+ ['"](?<target>\/[^'"]+)['"]/,kind:"file-write"},{regex:/EROFS: read-only file system, \w+ ['"](?<target>\/[^'"]+)['"]/,kind:"file-write"},{regex:/Could not resolve host:\s*(?<target>[\w.-]+)/,kind:"network"},{regex:/getaddrinfo (?:ENOTFOUND|EAI_AGAIN) (?<target>[\w.-]+)/,kind:"network"},{regex:/Failed to connect to (?<target>[\w.-]+) port (?<port>\d+)/,kind:"network"},{regex:/Temporary failure in name resolution.*?(?<target>[\w-]+(?:\.[\w-]+)+)?/,kind:"network"}],g=/^(?:\S*\/)?(?:cat|head|tail|less|more|grep|rg|ls|find|wc|stat|file|diff|cmp|od|xxd|strings|base64|sha\d*sum|md5|openssl)\b[^:]*:/;function k(r){const t=[];for(const o of r.split(`
2
- `)){const e=o.trim();for(const{regex:s,kind:n}of p){const a=s.exec(e);if(!a)continue;const d=a.groups?.target;if(!d){n==="network"&&t.push({kind:n,target:"(unknown host)",source:"output",detail:e});break}const l=a.groups?.port,c=n==="file-write"&&/Operation not permitted/.test(e)&&g.test(e)?"file-read":n;t.push({kind:c,target:l?`${d}:${l}`:d,source:"output",detail:e.slice(0,200)});break}}return t}i(k,"parseOutput");function w(r){const t=new Set,o=[];for(const e of r){const s=`${e.kind}\0${e.target}`;if(!t.has(s)&&(t.add(s),o.push(e),o.length>=20))break}return o}i(w,"dedupe");function x(r){const t=[...r.refusals.map(e=>({kind:"network",target:e.port!==void 0?`${e.host}:${e.port}`:e.host,source:"proxy"})),...r.violations.flatMap(e=>{const s=f(e.line);return s?[s]:[]})];(t.length===0||t.every(e=>e.kind==="network"&&e.target.startsWith("/")))&&t.push(...k(r.output));const o=w(t);return o.length>0?o:void 0}i(x,"collectBlockedAccesses");function b(r){const t=[`[sandbox] The OS sandbox (${r.level}, network off except allowlisted domains) blocked this command:`];for(const n of r.blocked){const a=n.source==="output"?" (inferred from the output)":"";t.push(` - ${n.kind}: ${n.target}${a}`)}r.networkProxyError&&t.push(` (allowlisted domains are unreachable too: the network proxy could not start: ${r.networkProxyError})`);const o=r.blocked.filter(n=>n.kind==="network"&&!n.target.startsWith("/")),e=r.blocked.filter(n=>n.kind==="file-write"),s={mode:"allow",justification:"<why this is needed>"};return o.length>0&&(s.allow_domains=o.map(n=>n.target.replace(/:\d+$/,""))),e.length>0&&(s.allow_write=e.map(n=>n.target)),t.push(`Do not try to work around the sandbox. If the task genuinely needs this access, call the tool again with the same command and sandbox_escalation: ${JSON.stringify(o.length>0||e.length>0?s:{mode:"unsandboxed",justification:"<why this is needed>"})} (or mode "unsandboxed" to run outside the sandbox). The user will be asked to approve.`),t.join(`
3
- `)}i(b,"describeDenialForModel");export{x as collectBlockedAccesses,b as describeDenialForModel,k as parseOutput,f as parseViolationLine};
1
+ var u=Object.defineProperty;var s=(o,t)=>u(o,"name",{value:t,configurable:!0});const m=20;function f(o){const t=/deny(?:\(\d+\))?\s+(?<operation>[\w-]+)\s+(?<target>.+?)\s*$/.exec(o);if(!t?.groups)return;const{operation:r,target:e}=t.groups;if(r.startsWith("file-write"))return{kind:"file-write",target:e,source:"kernel",detail:r};if(r.startsWith("file-read"))return{kind:"file-read",target:e,source:"kernel",detail:r};if(r.startsWith("network"))return{kind:"network",target:e,source:"kernel",detail:r}}s(f,"parseViolationLine");const g=[{regex:/(?<target>\/[^\s:'"`]+)['"`]?:\s*Read-only file system/,kind:"file-write"},{regex:/Read-only file system[^/\n]*(?<target>\/[^\s'"`]+)/,kind:"file-write"},{regex:/['"`]?(?<target>\/[^\s:'"`]+)['"`]?:\s*Operation not permitted/,kind:"file-write"},{regex:/EPERM: operation not permitted, \w+ ['"](?<target>(?:\/|[A-Za-z]:\\)[^'"]+)['"]/,kind:"file-write"},{regex:/EROFS: read-only file system, \w+ ['"](?<target>\/[^'"]+)['"]/,kind:"file-write"},{regex:/EACCES: permission denied, \w+ ['"](?<target>[A-Za-z]:\\[^'"]+)['"]/,kind:"file-write"},{regex:/Access to the path ['"](?<target>[A-Za-z]:\\[^'"]+)['"] is denied/,kind:"file-write"},{regex:/['"`](?<target>\/[A-Za-z]\/[^'"`]+)['"`]:\s*Permission denied/,kind:"file-write"},{regex:/Could not resolve host:\s*(?<target>[\w.-]+)/,kind:"network"},{regex:/getaddrinfo (?:ENOTFOUND|EAI_AGAIN) (?<target>[\w.-]+)/,kind:"network"},{regex:/Failed to connect to (?<target>[\w.-]+) port (?<port>\d+)/,kind:"network"},{regex:/Temporary failure in name resolution.*?(?<target>[\w-]+(?:\.[\w-]+)+)?/,kind:"network"}],p=/^(?:\S*\/)?(?:cat|head|tail|less|more|grep|rg|ls|find|wc|stat|file|diff|cmp|od|xxd|strings|base64|sha\d*sum|md5|openssl)\b[^:]*:/;function k(o){const t=[];for(const r of o.split(`
2
+ `)){const e=r.trim();for(const{regex:i,kind:n}of g){const a=i.exec(e);if(!a)continue;const d=a.groups?.target;if(!d){n==="network"&&t.push({kind:n,target:"(unknown host)",source:"output",detail:e});break}const l=a.groups?.port,c=n==="file-write"&&/Operation not permitted|Permission denied/.test(e)&&p.test(e)?"file-read":n;t.push({kind:c,target:l?`${d}:${l}`:d,source:"output",detail:e.slice(0,200)});break}}return t}s(k,"parseOutput");function w(o){const t=new Set,r=[];for(const e of o){const i=`${e.kind}\0${e.target}`;if(!t.has(i)&&(t.add(i),r.push(e),r.length>=20))break}return r}s(w,"dedupe");function x(o){const t=[...o.refusals.map(e=>({kind:"network",target:e.port!==void 0?`${e.host}:${e.port}`:e.host,source:"proxy"})),...o.violations.flatMap(e=>{const i=f(e.line);return i?[i]:[]})];(t.length===0||t.every(e=>e.kind==="network"&&e.target.startsWith("/")))&&t.push(...k(o.output));const r=w(t);return r.length>0?r:void 0}s(x,"collectBlockedAccesses");function b(o){const t=[`[sandbox] The OS sandbox (${o.level}, network off except allowlisted domains) blocked this command:`];for(const n of o.blocked){const a=n.source==="output"?" (inferred from the output)":"";t.push(` - ${n.kind}: ${n.target}${a}`)}o.networkProxyError&&t.push(` (allowlisted domains are unreachable too: the network proxy could not start: ${o.networkProxyError})`);const r=o.blocked.filter(n=>n.kind==="network"&&!n.target.startsWith("/")),e=o.blocked.filter(n=>n.kind==="file-write"),i={mode:"allow",justification:"<why this is needed>"};return r.length>0&&(i.allow_domains=r.map(n=>n.target.replace(/:\d+$/,""))),e.length>0&&(i.allow_write=e.map(n=>n.target)),t.push(`Do not try to work around the sandbox. If the task genuinely needs this access, call the tool again with the same command and sandbox_escalation: ${JSON.stringify(r.length>0||e.length>0?i:{mode:"unsandboxed",justification:"<why this is needed>"})} (or mode "unsandboxed" to run outside the sandbox). The user will be asked to approve.`),t.join(`
3
+ `)}s(b,"describeDenialForModel");export{x as collectBlockedAccesses,b as describeDenialForModel,k as parseOutput,f as parseViolationLine};
@@ -20,6 +20,16 @@ export interface WrapRequest {
20
20
  export declare function registerNetworkGrant(grant: NetworkGrant): () => void;
21
21
  export declare function decideNetworkRequest(host: string, port: number | undefined): boolean;
22
22
  export declare function proxyUnavailableReason(): string | undefined;
23
+ export declare function setFilteringProxyStarterForTesting(starter: (() => Promise<{
24
+ port: number;
25
+ } | {
26
+ error: string;
27
+ }>) | undefined): void;
28
+ export declare function ensureFilteringProxy(): Promise<{
29
+ port: number;
30
+ } | {
31
+ error: string;
32
+ }>;
23
33
  export declare function acquireSandboxRuntime(): void;
24
34
  export declare function releaseSandboxRuntime(): Promise<void>;
25
35
  export declare function wrapCommand(request: WrapRequest, grant: NetworkGrant): Promise<{
@@ -1 +1 @@
1
- var h=Object.defineProperty;var t=(e,o)=>h(e,"name",{value:o,configurable:!0});import{domainMatches as y,isAlwaysBlockedHost as b}from"./policy.js";const g="dal-sandbox.invalid",l=new Set;let d,s,u,x=Promise.resolve(),m=0;async function D(){return d??=import("@anthropic-ai/sandbox-runtime").then(e=>e.SandboxManager),d}t(D,"loadManager");function S(e){return{network:{allowedDomains:[g],deniedDomains:[],allowLocalBinding:e.allowLocalBinding},filesystem:{denyRead:[],allowWrite:[],denyWrite:[]},...e.ripgrep?{ripgrep:{command:e.ripgrep}}:{}}}t(S,"baseConfig");function I(e){return l.add(e),()=>{l.delete(e)}}t(I,"registerNetworkGrant");function T(e,o){let a=!1;if(!b(e))for(const r of l)r.deniedDomains.some(n=>y(e,n))||r.allowedDomains.some(n=>y(e,n))&&(a=!0);if(!a)for(const r of l)r.refusals.some(n=>n.host===e&&n.port===o)||r.refusals.push({host:e,...o!==void 0?{port:o}:{}});return a}t(T,"decideNetworkRequest");function R(){const e=process._getActiveHandles;return new Set(typeof e=="function"?e.call(process):[])}t(R,"activeHandles");async function v(e,o){s||(u??=(async()=>{const a={SIGINT:new Set(process.listeners("SIGINT")),SIGTERM:new Set(process.listeners("SIGTERM"))},r=R();try{await e.initialize(S(o),async({host:n,port:i})=>T(n,i),!1),s={ready:!0}}catch(n){s={ready:!1,error:n instanceof Error?n.message:String(n)}}finally{for(const n of["SIGINT","SIGTERM"])for(const i of process.listeners(n))a[n].has(i)||process.removeListener(n,i);for(const n of R())!r.has(n)&&typeof n.unref=="function"&&n.unref()}})(),await u)}t(v,"ensureProxy");function W(){return s&&!s.ready?s.error:void 0}t(W,"proxyUnavailableReason");function E(){m++}t(E,"acquireSandboxRuntime");async function L(){m=Math.max(0,m-1),m===0&&await G()}t(L,"releaseSandboxRuntime");async function N(e,o){const a=await D(),r=o.allowedDomains.length>0;r&&await v(a,e);const n=t(async()=>{const w={denyRead:e.denyRead,allowWrite:e.allowWrite,denyWrite:e.denyWrite};a.updateConfig({...S(e),filesystem:w});const p=r&&s?.ready===!0;return{wrapped:await a.wrapWithSandbox(e.command,e.shell,{network:{allowedDomains:p?[g]:[],deniedDomains:[]},filesystem:w}),proxied:p}},"run"),i=x.then(n,n);x=i.catch(()=>{});const{wrapped:f,proxied:c}=await i;return{command:f,proxied:c,release:I(o)}}t(N,"wrapCommand");async function P(e,o,a){if(!d)return[];const n=(await d).getSandboxViolationStore();if(n.getTotalCount()===0)return[];const i=Date.now()+a;for(;;){const f=n.getViolationsForCommand(e).filter(c=>c.timestamp.getTime()>=o-1e3);if(f.length>0||Date.now()>=i)return f;await new Promise(c=>setTimeout(c,50))}}t(P,"violationsForCommand");async function G(){l.clear();const e=s!==void 0;if(s=void 0,u=void 0,!e||!d)return;await(await d).reset()}t(G,"resetSandboxRuntime");export{E as acquireSandboxRuntime,T as decideNetworkRequest,W as proxyUnavailableReason,I as registerNetworkGrant,L as releaseSandboxRuntime,G as resetSandboxRuntime,P as violationsForCommand,N as wrapCommand};
1
+ var D=Object.defineProperty;var t=(e,r)=>D(e,"name",{value:r,configurable:!0});import{domainMatches as x,isAlwaysBlockedHost as T}from"./policy.js";const S="dal-sandbox.invalid",f=new Set;let d,c,w,P=Promise.resolve(),p=0;async function I(){return d??=import("@anthropic-ai/sandbox-runtime").then(e=>e.SandboxManager),d}t(I,"loadManager");function h(e){return{network:{allowedDomains:[S],deniedDomains:[],allowLocalBinding:e.allowLocalBinding},filesystem:{denyRead:[],allowWrite:[],denyWrite:[]},...e.ripgrep?{ripgrep:{command:e.ripgrep}}:{}}}t(h,"baseConfig");function G(e){return f.add(e),()=>{f.delete(e)}}t(G,"registerNetworkGrant");function v(e,r){let i=!1;if(!T(e))for(const a of f)a.deniedDomains.some(n=>x(e,n))||a.allowedDomains.some(n=>x(e,n))&&(i=!0);if(!i)for(const a of f)a.refusals.some(n=>n.host===e&&n.port===r)||a.refusals.push({host:e,...r!==void 0?{port:r}:{}});return i}t(v,"decideNetworkRequest");function R(){const e=process._getActiveHandles;return new Set(typeof e=="function"?e.call(process):[])}t(R,"activeHandles");async function k(e,r){c||(w??=(async()=>{const i={SIGINT:new Set(process.listeners("SIGINT")),SIGTERM:new Set(process.listeners("SIGTERM"))},a=R();try{await e.initialize(h(r),async({host:n,port:s})=>v(n,s),!1),c={ready:!0}}catch(n){c={ready:!1,error:n instanceof Error?n.message:String(n)}}finally{for(const n of["SIGINT","SIGTERM"])for(const s of process.listeners(n))i[n].has(s)||process.removeListener(n,s);for(const n of R())!a.has(n)&&typeof n.unref=="function"&&n.unref()}})(),await w)}t(k,"ensureProxy");function L(){return c&&!c.ready?c.error:o&&"error"in o?o.error:void 0}t(L,"proxyUnavailableReason");let o,m,b;function N(e){b=e?async()=>{const r=await e();return"error"in r?r:{port:r.port,server:{close:t(()=>{},"close")}}}:void 0,o=void 0,m=void 0}t(N,"setFilteringProxyStarterForTesting");async function C(){try{const{createHttpProxyServer:e}=await import("@anthropic-ai/sandbox-runtime/dist/sandbox/http-proxy.js"),r=e({filter:t((a,n)=>v(n,a),"filter")}),i=await new Promise((a,n)=>{r.once("error",n),r.listen(0,"127.0.0.1",()=>{const s=r.address();a(typeof s=="object"&&s?s.port:0)})});return r.unref(),{port:i,server:r}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}t(C,"startFilteringProxy");async function H(){return o?"error"in o?o:{port:o.port}:(m??=(b??C)(),o=await m,"error"in o?o:{port:o.port})}t(H,"ensureFilteringProxy");function B(){p++}t(B,"acquireSandboxRuntime");async function A(){p=Math.max(0,p-1),p===0&&await E()}t(A,"releaseSandboxRuntime");async function O(e,r){const i=await I(),a=r.allowedDomains.length>0;a&&await k(i,e);const n=t(async()=>{const y={denyRead:e.denyRead,allowWrite:e.allowWrite,denyWrite:e.denyWrite};i.updateConfig({...h(e),filesystem:y});const g=a&&c?.ready===!0;return{wrapped:await i.wrapWithSandbox(e.command,e.shell,{network:{allowedDomains:g?[S]:[],deniedDomains:[]},filesystem:y}),proxied:g}},"run"),s=P.then(n,n);P=s.catch(()=>{});const{wrapped:u,proxied:l}=await s;return{command:u,proxied:l,release:G(r)}}t(O,"wrapCommand");async function V(e,r,i){if(!d)return[];const n=(await d).getSandboxViolationStore();if(n.getTotalCount()===0)return[];const s=Date.now()+i;for(;;){const u=n.getViolationsForCommand(e).filter(l=>l.timestamp.getTime()>=r-1e3);if(u.length>0||Date.now()>=s)return u;await new Promise(l=>setTimeout(l,50))}}t(V,"violationsForCommand");async function E(){f.clear(),o&&"server"in o&&o.server.close(),o=void 0,m=void 0;const e=c!==void 0;if(c=void 0,w=void 0,!e||!d)return;await(await d).reset()}t(E,"resetSandboxRuntime");export{B as acquireSandboxRuntime,v as decideNetworkRequest,H as ensureFilteringProxy,L as proxyUnavailableReason,G as registerNetworkGrant,A as releaseSandboxRuntime,E as resetSandboxRuntime,N as setFilteringProxyStarterForTesting,V as violationsForCommand,O as wrapCommand};
@@ -2,6 +2,7 @@ import type { ExtensionContext } from "../extensions/types.ts";
2
2
  import { type SandboxAvailability } from "./availability.ts";
3
3
  import { type SandboxDenial } from "./denial.ts";
4
4
  import { type ResolvedSandboxPolicy, type SandboxLevel, type SandboxOverride } from "./policy.ts";
5
+ import { type WindowsShellKind } from "./windows.ts";
5
6
  export interface SandboxEscalationInput {
6
7
  mode: "allow" | "unsandboxed";
7
8
  justification: string;
@@ -55,6 +56,8 @@ export interface SandboxStatus {
55
56
  domains: string[];
56
57
  writablePaths: string[];
57
58
  };
59
+ isolationTier?: string;
60
+ limitations?: string[];
58
61
  }
59
62
  export interface SandboxOptions extends SandboxOverride {
60
63
  defaultLevel?: SandboxLevel;
@@ -113,7 +116,10 @@ export declare class ShellSandbox {
113
116
  escalation?: SandboxEscalationInput;
114
117
  background?: boolean;
115
118
  ctx?: ExtensionContext;
119
+ env?: NodeJS.ProcessEnv;
120
+ shellKind?: WindowsShellKind;
116
121
  }): Promise<PreparedCommand>;
122
+ private prepareWindows;
117
123
  private approveEscalation;
118
124
  }
119
125
  export declare function createScratchDir(): string;
@@ -1,5 +1,5 @@
1
- var M=Object.defineProperty;var r=(o,e)=>M(o,"name",{value:e,configurable:!0});import{spawnSync as O}from"node:child_process";import{mkdtempSync as B,rmSync as L}from"node:fs";import{tmpdir as U}from"node:os";import{isAbsolute as W,join as H,relative as F,resolve as K}from"node:path";import{fill as f,t as d}from"../../dal/i18n.js";import{detectSandboxAvailability as Q}from"./availability.js";import{collectBlockedAccesses as X}from"./denial.js";import{expandPath as Y,filesystemRules as z}from"./policy.js";import{acquireSandboxRuntime as G,proxyUnavailableReason as R,releaseSandboxRuntime as J,violationsForCommand as V,wrapCommand as Z}from"./runtime.js";const v=Symbol.for("dal.sandbox.escalationHandlers"),x=globalThis;x[v]instanceof Set||(x[v]=new Set);const g=x[v];function ue(o){return g.add(o),()=>{g.delete(o)}}r(ue,"registerSandboxEscalationHandler");let $;function pe(o){$=o}r(pe,"setProcessShellSandbox");function we(){return $}r(we,"getProcessShellSandbox");const j=new Map;function q(o){const e=j.get(o);if(e)return e;const t=O("git",["rev-parse","--absolute-git-dir","--git-common-dir"],{cwd:o,encoding:"utf8",timeout:3e3}),a=[];if(t.status===0)for(const l of t.stdout.split(`
2
- `)){const n=l.trim();if(!n)continue;const s=W(n)?n:K(o,n),c=F(o,s);(c.startsWith("..")||W(c))&&a.push(s)}const i=[...new Set(a)];return j.set(o,i),i}r(q,"gitDirsOutside");function C(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}r(C,"cleanList");let ee=0;class be{static{r(this,"ShellSandbox")}policy;onEscalation;onEvent;availabilityOverride;sessionDomains=new Set;sessionWritable=new Set;holdsRuntime=!1;sharedScratch;ownScratch;constructor(e){this.policy=e.policy,this.onEscalation=e.onEscalation,this.onEvent=e.onEvent,this.availabilityOverride=e.availability,this.sharedScratch=e.scratchDir,this.active&&(G(),this.holdsRuntime=!0)}scratchDir(){return this.sharedScratch?this.sharedScratch():(this.ownScratch??=oe(),this.ownScratch)}async dispose(){this.ownScratch&&(L(this.ownScratch,{recursive:!0,force:!0}),this.ownScratch=void 0),this.holdsRuntime&&(this.holdsRuntime=!1,await J())}get level(){return this.policy.level}get active(){return this.policy.level!=="off"}availability(){return this.availabilityOverride??Q()}status(){const e=this.availability(),t=R();return{level:this.policy.level,levelSource:this.policy.levelSource,enforced:this.active&&e.available,platform:e.platform,...e.mechanism?{mechanism:e.mechanism}:{},...this.active&&!e.available&&e.reason?{unavailableReason:e.reason}:{},network:{allowedDomains:[...this.policy.network.allowedDomains],deniedDomains:[...this.policy.network.deniedDomains],...t?{proxyError:t}:{}},sessionAllowances:{domains:[...this.sessionDomains],writablePaths:[...this.sessionWritable]}}}describeForModel(){if(!this.active)return;const e=this.policy.level==="read-only"?"nothing may be written except $TMPDIR (a scratch directory for this session)":"writes are limited to the working directory and $TMPDIR (a scratch directory for this session; agent/editor config, git hooks and .env files stay read-only)",t=this.policy.network.allowedDomains,a=t.length>0?`network is off except ${t.join(", ")}`:"network is off";return`Commands run inside an OS sandbox (${this.policy.level}): ${e}; ${a}; credential files such as ~/.ssh cannot be read. When the sandbox blocks something the result says what; only then, and only if the task needs it, retry with sandbox_escalation.`}unavailableRefusal(){if(!this.active)return;const e=this.availability();if(e.available)return;const t=e.platform==="win32";return[`Command refused: the sandbox level is "${this.policy.level}", but ${e.reason??"the OS sandbox is unavailable."}`,"Commands are not run without the sandbox unless the user says so explicitly.",t?'To run commands on Windows, the user must opt out: `dal --sandbox off`, or "sandbox": { "level": "off" } in ~/.dal/agent/settings.json.':'The user can fix the sandbox, or opt out explicitly with `dal --sandbox off` or "sandbox": { "level": "off" } in ~/.dal/agent/settings.json.','A single command can still run if the user approves it: retry with sandbox_escalation {"mode":"unsandboxed","justification":"..."}.'].join(`
3
- `)}async prepare(e){const t=this.policy.level;if(t==="off")return I(e.command,{level:t,sandboxed:!1});const a=this.unavailableRefusal();if(a&&e.escalation?.mode!=="unsandboxed")throw new Error(a);let i=[],l=[],n;if(e.escalation){const h=await this.approveEscalation(e,e.escalation);if(n=h,!h.decision.approved)throw new Error(`Sandbox escalation refused${h.decision.message?`: ${h.decision.message}`:"."} Do not retry the same escalation; continue without it or ask the user.`);if(h.request.mode==="unsandboxed")return I(e.command,{level:t,sandboxed:!1,escalation:n});i=h.request.allowDomains,l=h.request.allowWrite}const s=this.availability(),c=this.scratchDir(),m=z(this.policy,e.cwd,{gitDirs:this.policy.level==="workspace-write"?q(e.cwd):[],extraWrite:[...this.sessionWritable,...l],scratchDir:c}),S={allowedDomains:[...this.policy.network.allowedDomains,...this.sessionDomains,...i],deniedDomains:this.policy.network.deniedDomains,refusals:[]},A=`${process.pid}-${++ee}`,u=te(c),D=`export DAL_SANDBOX_RUN=${A} TMPDIR=${u} TMP=${u} TEMP=${u}
4
- ${e.command}`,_=Date.now(),p=await Z({command:D,shell:e.shell,allowWrite:m.allowWrite,denyWrite:m.denyWrite,denyRead:m.denyRead,allowLocalBinding:e.background===!0||this.policy.network.allowLocalBinding,...s.ripgrep?{ripgrep:s.ripgrep}:{}},S),w={level:t,sandboxed:!0,...n?{escalation:n}:{}};let k=!1;return{command:p.command,sandboxed:!0,details:w,finish:r(async(h,P)=>{if(k)return w.denial;if(k=!0,p.release(),h===0)return;const N=s.platform==="darwin"?await V(D,_,400):[],b=X({refusals:S.refusals,violations:N,output:P});if(!b)return;const E=p.proxied?void 0:R(),y={level:t,platform:s.platform,command:e.command,cwd:e.cwd,blocked:b,...E&&b.some(T=>T.kind==="network")?{networkProxyError:E}:{}};return w.denial=y,this.onEvent?.({type:"sandbox_denied",toolCallId:e.toolCallId,toolName:e.toolName,denial:y}),y},"finish")}}async approveEscalation(e,t){const a=t.mode==="unsandboxed"?"unsandboxed":"allow",i={toolCallId:e.toolCallId,toolName:e.toolName,command:e.command,cwd:e.cwd,level:this.policy.level,mode:a,justification:typeof t.justification=="string"?t.justification.trim():"",allowDomains:a==="allow"?C(t.allow_domains):[],allowWrite:a==="allow"?C(t.allow_write).map(n=>Y(n,e.cwd)):[],background:e.background===!0},l=r((n,s)=>{const c=n.approved&&n.scope==="session"&&a==="unsandboxed"?{...n,scope:"once"}:n;if(c.approved&&c.scope==="session"){for(const m of i.allowDomains)this.sessionDomains.add(m);for(const m of i.allowWrite)this.sessionWritable.add(m)}return this.onEvent?.({type:"sandbox_escalation",toolCallId:e.toolCallId,toolName:e.toolName,request:i,decision:c,decidedBy:s}),{request:i,decision:c}},"finish");if(!i.justification)return l({approved:!1,message:"an escalation needs a justification"},"none");if(a==="allow"&&i.allowDomains.length===0&&i.allowWrite.length===0)return l({approved:!1,message:'mode "allow" needs allow_domains or allow_write'},"none");if(this.onEscalation){const n=await this.onEscalation(i,e.ctx);if(n)return l(n,"sdk")}for(const n of g){const s=await n(i,e.ctx);if(s)return l(s,"handler")}return e.ctx?.hasUI?l(await ne(i,e.ctx),"ui"):l({approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"},"none")}}function I(o,e){return{command:o,sandboxed:!1,details:e,finish:r(async()=>{},"finish")}}r(I,"passthrough");function oe(){return B(H(U(),"dal-sandbox-"))}r(oe,"createScratchDir");function te(o){return`'${o.replace(/'/g,"'\\''")}'`}r(te,"shellQuote");async function ne(o,e){const t=d("\u4EC5\u672C\u6B21\u5141\u8BB8"),a=d("\u672C\u4F1A\u8BDD\u5185\u90FD\u5141\u8BB8"),i=d("\u62D2\u7EDD"),l=o.mode==="unsandboxed"?d("\u5728\u6C99\u7BB1\u4E4B\u5916\u8FD0\u884C\u547D\u4EE4\uFF08\u53EF\u8BBF\u95EE\u4F60\u7684\u5168\u90E8\u6587\u4EF6\u548C\u7F51\u7EDC\uFF09"):[o.allowDomains.length>0?f(d("\u8BBF\u95EE {domains}"),{domains:o.allowDomains.join(", ")}):"",o.allowWrite.length>0?f(d("\u5199\u5165 {paths}"),{paths:o.allowWrite.join(", ")}):""].filter(Boolean).join(d("\uFF0C\u5E76")),n=[f(d("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:l}),f(d("\u547D\u4EE4\uFF1A{command}"),{command:o.command}),f(d("\u76EE\u5F55\uFF1A{cwd}"),{cwd:o.cwd}),f(d("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:o.justification})].join(`
5
- `),s=o.mode==="unsandboxed"?[t,i]:[t,a,i],c=await e.ui.select(n,s);return c===t?{approved:!0,scope:"once"}:c===a?{approved:!0,scope:"session"}:{approved:!1,message:"the user declined"}}r(ne,"askThroughUi");export{be as ShellSandbox,oe as createScratchDir,we as getProcessShellSandbox,ue as registerSandboxEscalationHandler,pe as setProcessShellSandbox};
1
+ var M=Object.defineProperty;var d=(n,o)=>M(n,"name",{value:o,configurable:!0});import{spawnSync as B}from"node:child_process";import{mkdtempSync as U,rmSync as H}from"node:fs";import{tmpdir as K}from"node:os";import{isAbsolute as R,join as F,relative as G,resolve as Q}from"node:path";import{fill as b,t as c}from"../../dal/i18n.js";import{detectSandboxAvailability as X}from"./availability.js";import{collectBlockedAccesses as I}from"./denial.js";import{expandPath as Y,filesystemRules as z}from"./policy.js";import{acquireSandboxRuntime as J,ensureFilteringProxy as V,proxyUnavailableReason as j,registerNetworkGrant as Z,releaseSandboxRuntime as q,violationsForCommand as oo,wrapCommand as eo}from"./runtime.js";import{prepareWindowsCommand as no}from"./windows.js";const k=Symbol.for("dal.sandbox.escalationHandlers"),E=globalThis;E[k]instanceof Set||(E[k]=new Set);const W=E[k];function xo(n){return W.add(n),()=>{W.delete(n)}}d(xo,"registerSandboxEscalationHandler");let P;function go(n){P=n}d(go,"setProcessShellSandbox");function So(){return P}d(So,"getProcessShellSandbox");const N=new Map;function io(n){const o=N.get(n);if(o)return o;const e=B("git",["rev-parse","--absolute-git-dir","--git-common-dir"],{cwd:n,encoding:"utf8",timeout:3e3}),s=[];if(e.status===0)for(const l of e.stdout.split(`
2
+ `)){const i=l.trim();if(!i)continue;const a=R(i)?i:Q(n,i),r=G(n,a);(r.startsWith("..")||R(r))&&s.push(a)}const t=[...new Set(s)];return N.set(n,t),t}d(io,"gitDirsOutside");function _(n){return Array.isArray(n)?n.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>o.trim()):[]}d(_,"cleanList");let to=0;class Do{static{d(this,"ShellSandbox")}policy;onEscalation;onEvent;availabilityOverride;sessionDomains=new Set;sessionWritable=new Set;holdsRuntime=!1;sharedScratch;ownScratch;constructor(o){this.policy=o.policy,this.onEscalation=o.onEscalation,this.onEvent=o.onEvent,this.availabilityOverride=o.availability,this.sharedScratch=o.scratchDir,this.active&&(J(),this.holdsRuntime=!0)}scratchDir(){return this.sharedScratch?this.sharedScratch():(this.ownScratch??=ao(),this.ownScratch)}async dispose(){this.ownScratch&&(H(this.ownScratch,{recursive:!0,force:!0}),this.ownScratch=void 0),this.holdsRuntime&&(this.holdsRuntime=!1,await q())}get level(){return this.policy.level}get active(){return this.policy.level!=="off"}availability(){return this.availabilityOverride??X()}status(){const o=this.availability(),e=j();return{level:this.policy.level,levelSource:this.policy.levelSource,enforced:this.active&&o.available,platform:o.platform,...o.mechanism?{mechanism:o.mechanism}:{},...this.active&&!o.available&&o.reason?{unavailableReason:o.reason}:{},...o.isolationTier?{isolationTier:o.isolationTier}:{},...o.limitations?.length?{limitations:[...o.limitations]}:{},network:{allowedDomains:[...this.policy.network.allowedDomains],deniedDomains:[...this.policy.network.deniedDomains],...e?{proxyError:e}:{}},sessionAllowances:{domains:[...this.sessionDomains],writablePaths:[...this.sessionWritable]}}}describeForModel(){if(!this.active)return;const o=this.policy.level==="read-only"?"nothing may be written except $TMPDIR (a scratch directory for this session)":"writes are limited to the working directory and $TMPDIR (a scratch directory for this session; agent/editor config, git hooks and .env files stay read-only)",e=this.policy.network.allowedDomains,s=e.length>0?`network is off except ${e.join(", ")}`:"network is off";return`Commands run inside an OS sandbox (${this.policy.level}): ${o}; ${s}; credential files such as ~/.ssh cannot be read. When the sandbox blocks something the result says what; only then, and only if the task needs it, retry with sandbox_escalation.`}unavailableRefusal(){if(!this.active)return;const o=this.availability();if(!o.available)return[`Command refused: the sandbox level is "${this.policy.level}", but ${o.reason??"the OS sandbox is unavailable."}`,"Commands are not run without the sandbox unless the user says so explicitly.",'The user can fix the sandbox, or opt out explicitly with `dal --sandbox off` or "sandbox": { "level": "off" } in ~/.dal/agent/settings.json.','A single command can still run if the user approves it: retry with sandbox_escalation {"mode":"unsandboxed","justification":"..."}.'].join(`
3
+ `)}async prepare(o){const e=this.policy.level;if(e==="off")return A(o.command,{level:e,sandboxed:!1});const s=this.unavailableRefusal();if(s&&o.escalation?.mode!=="unsandboxed")throw new Error(s);let t=[],l=[],i;if(o.escalation){const f=await this.approveEscalation(o,o.escalation);if(i=f,!f.decision.approved)throw new Error(`Sandbox escalation refused${f.decision.message?`: ${f.decision.message}`:"."} Do not retry the same escalation; continue without it or ask the user.`);if(f.request.mode==="unsandboxed")return A(o.command,{level:e,sandboxed:!1,escalation:i});t=f.request.allowDomains,l=f.request.allowWrite}const a=this.availability(),r=o.shellKind??"bash";if(r!=="bash"&&a.mechanism!=="mxc")throw new Error(`Command refused: ${r} commands cannot run inside the ${a.mechanism??"OS"} sandbox, and the sandbox level is "${e}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);const m=this.scratchDir(),w=z(this.policy,o.cwd,{gitDirs:this.policy.level==="workspace-write"?io(o.cwd):[],extraWrite:[...this.sessionWritable,...l],scratchDir:m}),u={allowedDomains:[...this.policy.network.allowedDomains,...this.sessionDomains,...t],deniedDomains:this.policy.network.deniedDomains,refusals:[]},y=`${process.pid}-${++to}`;if(a.mechanism==="mxc"&&a.mxc)return this.prepareWindows(o,{level:e,shellKind:r,scratch:m,rules:w,grant:u,runId:y,escalation:i,availability:a});const h=so(m),g=`export DAL_SANDBOX_RUN=${y} TMPDIR=${h} TMP=${h} TEMP=${h}
4
+ ${o.command}`,v=Date.now(),p=await eo({command:g,shell:o.shell,allowWrite:w.allowWrite,denyWrite:w.denyWrite,denyRead:w.denyRead,allowLocalBinding:o.background===!0||this.policy.network.allowLocalBinding,...a.ripgrep?{ripgrep:a.ripgrep}:{}},u),x={level:e,sandboxed:!0,...i?{escalation:i}:{}};let $=!1;return{command:p.command,sandboxed:!0,details:x,finish:d(async(f,T)=>{if($)return x.denial;if($=!0,p.release(),f===0)return;const O=a.platform==="darwin"?await oo(g,v,400):[],S=I({refusals:u.refusals,violations:O,output:T});if(!S)return;const C=p.proxied?void 0:j(),D={level:e,platform:a.platform,command:o.command,cwd:o.cwd,blocked:S,...C&&S.some(L=>L.kind==="network")?{networkProxyError:C}:{}};return x.denial=D,this.onEvent?.({type:"sandbox_denied",toolCallId:o.toolCallId,toolName:o.toolName,denial:D}),D},"finish")}}async prepareWindows(o,e){const{level:s,grant:t,availability:l}=e,i=l.mxc;if(!i)throw new Error("Command refused: the Windows sandbox (mxc) is not loaded.");let a,r;if(t.allowedDomains.length>0){const h=await V();"port"in h?a=h.port:r=h.error}const m=no({runtime:i,kind:e.shellKind,shellPath:o.shell,command:o.command,cwd:o.cwd,level:s,rules:e.rules,env:o.env??process.env,scratchDir:e.scratch,runId:e.runId,...a!==void 0?{proxyPort:a}:{},allowLocalNetwork:o.background===!0||this.policy.network.allowLocalBinding}),w=Z(t),u={level:s,sandboxed:!0,...e.escalation?{escalation:e.escalation}:{}};let y=!1;return{command:m.command,sandboxed:!0,details:u,finish:d(async(h,g)=>{if(y)return u.denial;if(y=!0,w(),m.cleanup(),h===0)return;const v=I({refusals:t.refusals,violations:[],output:g});if(!v)return;const p={level:s,platform:l.platform,command:o.command,cwd:o.cwd,blocked:v,...r&&v.some(x=>x.kind==="network")?{networkProxyError:r}:{}};return u.denial=p,this.onEvent?.({type:"sandbox_denied",toolCallId:o.toolCallId,toolName:o.toolName,denial:p}),p},"finish")}}async approveEscalation(o,e){const s=e.mode==="unsandboxed"?"unsandboxed":"allow",t={toolCallId:o.toolCallId,toolName:o.toolName,command:o.command,cwd:o.cwd,level:this.policy.level,mode:s,justification:typeof e.justification=="string"?e.justification.trim():"",allowDomains:s==="allow"?_(e.allow_domains):[],allowWrite:s==="allow"?_(e.allow_write).map(i=>Y(i,o.cwd)):[],background:o.background===!0},l=d((i,a)=>{const r=i.approved&&i.scope==="session"&&s==="unsandboxed"?{...i,scope:"once"}:i;if(r.approved&&r.scope==="session"){for(const m of t.allowDomains)this.sessionDomains.add(m);for(const m of t.allowWrite)this.sessionWritable.add(m)}return this.onEvent?.({type:"sandbox_escalation",toolCallId:o.toolCallId,toolName:o.toolName,request:t,decision:r,decidedBy:a}),{request:t,decision:r}},"finish");if(!t.justification)return l({approved:!1,message:"an escalation needs a justification"},"none");if(s==="allow"&&t.allowDomains.length===0&&t.allowWrite.length===0)return l({approved:!1,message:'mode "allow" needs allow_domains or allow_write'},"none");if(this.onEscalation){const i=await this.onEscalation(t,o.ctx);if(i)return l(i,"sdk")}for(const i of W){const a=await i(t,o.ctx);if(a)return l(a,"handler")}return o.ctx?.hasUI?l(await ro(t,o.ctx),"ui"):l({approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"},"none")}}function A(n,o){return{command:n,sandboxed:!1,details:o,finish:d(async()=>{},"finish")}}d(A,"passthrough");function ao(){return U(F(K(),"dal-sandbox-"))}d(ao,"createScratchDir");function so(n){return`'${n.replace(/'/g,"'\\''")}'`}d(so,"shellQuote");async function ro(n,o){const e=c("\u4EC5\u672C\u6B21\u5141\u8BB8"),s=c("\u672C\u4F1A\u8BDD\u5185\u90FD\u5141\u8BB8"),t=c("\u62D2\u7EDD"),l=n.mode==="unsandboxed"?c("\u5728\u6C99\u7BB1\u4E4B\u5916\u8FD0\u884C\u547D\u4EE4\uFF08\u53EF\u8BBF\u95EE\u4F60\u7684\u5168\u90E8\u6587\u4EF6\u548C\u7F51\u7EDC\uFF09"):[n.allowDomains.length>0?b(c("\u8BBF\u95EE {domains}"),{domains:n.allowDomains.join(", ")}):"",n.allowWrite.length>0?b(c("\u5199\u5165 {paths}"),{paths:n.allowWrite.join(", ")}):""].filter(Boolean).join(c("\uFF0C\u5E76")),i=[b(c("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:l}),b(c("\u547D\u4EE4\uFF1A{command}"),{command:n.command}),b(c("\u76EE\u5F55\uFF1A{cwd}"),{cwd:n.cwd}),b(c("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:n.justification})].join(`
5
+ `),a=n.mode==="unsandboxed"?[e,t]:[e,s,t],r=await o.ui.select(i,a);return r===e?{approved:!0,scope:"once"}:r===s?{approved:!0,scope:"session"}:{approved:!1,message:"the user declined"}}d(ro,"askThroughUi");export{Do as ShellSandbox,ao as createScratchDir,So as getProcessShellSandbox,xo as registerSandboxEscalationHandler,go as setProcessShellSandbox};
@@ -0,0 +1,122 @@
1
+ import type { CommandFilesystemRules, SandboxLevel } from "./policy.ts";
2
+ export declare const MXC_SDK_DIR_ENV = "DAL_MXC_SDK_DIR";
3
+ export declare const MXC_POLICY_VERSION = "0.6.0-alpha";
4
+ export declare const WINDOWS_SANDBOX_LIMITATIONS: readonly string[];
5
+ export interface MxcPlatformSupport {
6
+ isSupported: boolean;
7
+ reason?: string;
8
+ availableMethods: string[];
9
+ isolationTier?: string;
10
+ isolationWarnings?: string[];
11
+ }
12
+ export interface MxcFilesystemFragment {
13
+ readonlyPaths: string[];
14
+ readwritePaths: string[];
15
+ }
16
+ export interface MxcPolicy {
17
+ version: string;
18
+ filesystem: {
19
+ readwritePaths: string[];
20
+ readonlyPaths: string[];
21
+ deniedPaths: string[];
22
+ };
23
+ network: {
24
+ allowOutbound?: boolean;
25
+ allowLocalNetwork?: boolean;
26
+ proxy?: {
27
+ localhost: number;
28
+ };
29
+ };
30
+ ui: {
31
+ allowWindows: boolean;
32
+ clipboard: "none";
33
+ allowInputInjection: boolean;
34
+ };
35
+ }
36
+ export interface MxcContainerConfig {
37
+ version: string;
38
+ process?: {
39
+ commandLine: string;
40
+ cwd?: string;
41
+ env?: string[];
42
+ timeout?: number;
43
+ };
44
+ [key: string]: unknown;
45
+ }
46
+ export interface MxcSdkApi {
47
+ getPlatformSupport(): MxcPlatformSupport;
48
+ createConfigFromPolicy(policy: MxcPolicy, containment?: string, containerName?: string): MxcContainerConfig;
49
+ getAvailableToolsPolicy(env?: Record<string, string | undefined>, options?: {
50
+ containerType?: "processcontainer";
51
+ }): MxcFilesystemFragment;
52
+ getUserProfilePolicy(): MxcFilesystemFragment;
53
+ }
54
+ export interface MxcRuntime {
55
+ sdkDir: string;
56
+ sdkVersion: string;
57
+ wxcExec: string;
58
+ api: MxcSdkApi;
59
+ }
60
+ export declare function setMxcRuntimeForTesting(value: MxcRuntime | {
61
+ error: string;
62
+ } | undefined): void;
63
+ export declare function loadMxcRuntime(options?: {
64
+ env?: NodeJS.ProcessEnv;
65
+ arch?: string;
66
+ }): MxcRuntime | {
67
+ error: string;
68
+ };
69
+ export declare function toWindowsPath(path: string): string;
70
+ export declare function quoteWindowsArgument(value: string): string;
71
+ export type WindowsShellKind = "bash" | "powershell";
72
+ export declare function shellInstallRoot(shellPath: string): string;
73
+ export declare function windowsSandboxPolicy(input: {
74
+ level: SandboxLevel;
75
+ cwd: string;
76
+ rules: CommandFilesystemRules;
77
+ tools: MxcFilesystemFragment;
78
+ shellRoot: string;
79
+ runDir: string;
80
+ proxyPort?: number;
81
+ allowLocalNetwork: boolean;
82
+ exists: (path: string) => boolean;
83
+ }): MxcPolicy;
84
+ export declare function windowsSandboxEnvironment(env: NodeJS.ProcessEnv, overrides: {
85
+ scratchDir: string;
86
+ runId: string;
87
+ proxyPort?: number;
88
+ }): string[];
89
+ export declare function windowsInnerCommand(kind: WindowsShellKind, shellPath: string, command: string, scriptPath: string): {
90
+ script: string;
91
+ commandLine: string;
92
+ };
93
+ export declare function windowsOuterCommand(kind: WindowsShellKind, wxcExec: string, configPath: string): string;
94
+ export declare function createRunDirectory(): string;
95
+ export declare function prepareWindowsCommand(input: {
96
+ runtime: MxcRuntime;
97
+ kind: WindowsShellKind;
98
+ shellPath: string;
99
+ command: string;
100
+ cwd: string;
101
+ level: SandboxLevel;
102
+ rules: CommandFilesystemRules;
103
+ env: NodeJS.ProcessEnv;
104
+ scratchDir: string;
105
+ runId: string;
106
+ proxyPort?: number;
107
+ allowLocalNetwork: boolean;
108
+ runDir?: string;
109
+ exists?: (path: string) => boolean;
110
+ }): {
111
+ command: string;
112
+ configPath: string;
113
+ config: MxcContainerConfig;
114
+ cleanup: () => void;
115
+ };
116
+ export declare function probeWindowsSandbox(runtime: MxcRuntime): {
117
+ ok: true;
118
+ support: MxcPlatformSupport;
119
+ } | {
120
+ ok: false;
121
+ reason: string;
122
+ };
@@ -0,0 +1,5 @@
1
+ var S=Object.defineProperty;var c=(e,r)=>S(e,"name",{value:r,configurable:!0});import{spawnSync as D}from"node:child_process";import{existsSync as u,mkdtempSync as I,readFileSync as v,rmSync as w,writeFileSync as p}from"node:fs";import{createRequire as y}from"node:module";import{tmpdir as L}from"node:os";import{join as d,win32 as m}from"node:path";const x="DAL_MXC_SDK_DIR",P="0.6.0-alpha",O=/^0\.6\.\d+$/,H=["Allowlisted domains are reached through dal's filtering proxy, handed to mxc as its network proxy; mxc does not enforce per-host allow or block lists on Windows.","A background process that may listen locally gets mxc's local-network access, which also reaches other machines on the private network, not only localhost.","Protected names inside a writable folder (.env, .git/hooks, .vscode, .dal, \u2026) are protected only if they already exist when the command starts; creating a missing one is not blocked.","Protected credential files (~/.ssh, cloud credentials, \u2026) are denied only if they exist when the command starts."];let h;function V(e){h=e}c(V,"setMxcRuntimeForTesting");function E(e){const r=e[x]?.trim();if(r)return u(d(r,"package.json"))?{dir:r}:{error:`${x} is set to ${r}, but there is no package there.`};try{const o=y(import.meta.url);return{dir:d(o.resolve("@microsoft/mxc-sdk/package.json"),"..")}}catch{return{error:`Microsoft eXecution Containers (mxc) is not installed. Install it with \`npm install -g @microsoft/mxc-sdk@0.6.0\`, or set ${x} to an @microsoft/mxc-sdk 0.6 package directory.`}}}c(E,"sdkDirectory");function B(e={}){if(h)return h;const r=e.env??process.env,o=E(r);if("error"in o)return o;let t;try{t=JSON.parse(v(d(o.dir,"package.json"),"utf8")).version??""}catch(n){return{error:`cannot read the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}if(!O.test(t))return{error:`dal supports @microsoft/mxc-sdk 0.6.x, but ${o.dir} is version ${t||"(unknown)"}. Install @microsoft/mxc-sdk@0.6.0.`};const a=(e.arch??process.arch)==="arm64"?"arm64":"x64",s=d(o.dir,"bin",a,"wxc-exec.exe");if(!u(s))return{error:`the mxc SDK at ${o.dir} has no ${a} wxc-exec.exe.`};let i;try{i=y(import.meta.url)(d(o.dir,"dist","index.js"))}catch(n){return{error:`cannot load the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}return{sdkDir:o.dir,sdkVersion:t,wxcExec:s,api:i}}c(B,"loadMxcRuntime");function l(e){return e.replace(/\//g,"\\")}c(l,"toWindowsPath");function f(e){return e.length>0&&!/[\s"]/.test(e)?e:`"${e.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/,"$1$1")}"`}c(f,"quoteWindowsArgument");function g(e){return`'${e.replace(/'/g,"''")}'`}c(g,"powershellQuote");function $(e){return`'${e.replace(/'/g,"'\\''")}'`}c($,"bashQuote");function T(e){const r=m.dirname(e),o=m.dirname(r);return m.basename(r).toLowerCase()==="bin"&&m.basename(o).toLowerCase()==="usr"?m.dirname(o):m.basename(r).toLowerCase()==="bin"?o:r}c(T,"shellInstallRoot");function _(e,r){const o=m.relative(r,e);return o===""||!o.startsWith("..")&&!m.isAbsolute(o)}c(_,"isWithinWindows");function C(e){const r=c(n=>[...new Set(n.map(l))],"unique"),o=r([...e.rules.allowWrite,...e.tools.readwritePaths]),t=e.rules.denyWrite.filter(n=>!/[*?]/.test(n)&&e.exists(n)&&o.some(b=>_(l(n),b))),a=r([...e.tools.readonlyPaths,e.shellRoot,e.runDir,...e.level==="read-only"?[e.cwd]:[],...t]).filter(n=>!o.includes(n)),s=r(e.rules.denyRead.filter(n=>!/[*?]/.test(n)&&e.exists(n))),i=e.proxyPort!==void 0?{proxy:{localhost:e.proxyPort}}:{allowOutbound:!1,allowLocalNetwork:e.allowLocalNetwork};return{version:P,filesystem:{readwritePaths:o,readonlyPaths:a,deniedPaths:s},network:i,ui:{allowWindows:!0,clipboard:"none",allowInputInjection:!1}}}c(C,"windowsSandboxPolicy");function R(e,r){const o={};for(const[s,i]of Object.entries(e))typeof i=="string"&&(o[s]=i);const t=c((s,i)=>{for(const n of Object.keys(o))n.toLowerCase()===s.toLowerCase()&&delete o[n];o[s]=i},"set"),a=l(r.scratchDir);if(t("TMP",a),t("TEMP",a),t("TMPDIR",a),t("DAL_SANDBOX_RUN",r.runId),r.proxyPort!==void 0){const s=`http://127.0.0.1:${r.proxyPort}`;t("HTTP_PROXY",s),t("HTTPS_PROXY",s),o.http_proxy=s,o.https_proxy=s}return Object.entries(o).map(([s,i])=>`${s}=${i}`)}c(R,"windowsSandboxEnvironment");const N="try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}";function W(e,r,o,t){return e==="powershell"?{script:`${N}
2
+ ${o}
3
+ if (-not $?) { if ($LASTEXITCODE) { exit $LASTEXITCODE } else { exit 1 } }
4
+ `,commandLine:[f(r),"-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",f(t)].join(" ")}:{script:`${o}
5
+ `,commandLine:[f(r),"--noprofile","--norc",f(t)].join(" ")}}c(W,"windowsInnerCommand");function j(e,r,o){if(e==="powershell")return`& ${g(l(r))} ${g(l(o))}; exit $LASTEXITCODE`;const t=c(a=>a.replace(/\\/g,"/"),"forward");return`${$(t(r))} ${$(t(o))}`}c(j,"windowsOuterCommand");function k(){return I(d(L(),"dal-mxc-"))}c(k,"createRunDirectory");function J(e){const r=e.runDir??k(),o=c(()=>w(r,{recursive:!0,force:!0}),"cleanup");try{const t=d(r,e.kind==="powershell"?"command.ps1":"command.sh"),a=d(r,"config.json"),s=W(e.kind,l(e.shellPath),e.command,l(t)),i=C({level:e.level,cwd:e.cwd,rules:e.rules,tools:M(e.runtime.api.getAvailableToolsPolicy(e.env,{containerType:"processcontainer"}),e.runtime.api.getUserProfilePolicy()),shellRoot:T(l(e.shellPath)),runDir:l(r),...e.proxyPort!==void 0?{proxyPort:e.proxyPort}:{},allowLocalNetwork:e.allowLocalNetwork,exists:e.exists??u}),n=e.runtime.api.createConfigFromPolicy(i,"process",`dal-${e.runId}`);return n.process={...n.process??{commandLine:""},commandLine:s.commandLine,cwd:l(e.cwd),env:R(e.env,{scratchDir:e.scratchDir,runId:e.runId,...e.proxyPort!==void 0?{proxyPort:e.proxyPort}:{}})},p(t,s.script,{mode:384}),p(a,JSON.stringify(n),{mode:384}),{command:j(e.kind,e.runtime.wxcExec,a),configPath:a,config:n,cleanup:o}}catch(t){throw o(),t}}c(J,"prepareWindowsCommand");function M(...e){return{readonlyPaths:e.flatMap(r=>r.readonlyPaths??[]),readwritePaths:e.flatMap(r=>r.readwritePaths??[])}}c(M,"mergeFragments");function Y(e){let r;try{r=e.api.getPlatformSupport()}catch(t){return{ok:!1,reason:`mxc could not check this machine: ${t instanceof Error?t.message:t}`}}if(!r.isSupported)return{ok:!1,reason:`mxc does not support this Windows installation: ${r.reason||"no reason given"}.`};if(!r.availableMethods.includes("processcontainer"))return{ok:!1,reason:`mxc's process container is not available here (available: ${r.availableMethods.join(", ")||"none"}).`};const o=k();try{const t=e.api.createConfigFromPolicy({version:P,filesystem:{readwritePaths:[],readonlyPaths:[],deniedPaths:[]},network:{allowOutbound:!1},ui:{allowWindows:!1,clipboard:"none",allowInputInjection:!1}},"process",`dal-probe-${process.pid}`);t.process={...t.process??{commandLine:""},commandLine:"cmd.exe /d /c exit 0"};const a=d(o,"config.json");p(a,JSON.stringify(t),{mode:384});const s=D(e.wxcExec,[a],{encoding:"utf8",timeout:3e4,windowsHide:!0});return s.status!==0?{ok:!1,reason:`mxc could not start a sandboxed process (${`${s.stderr??""}${s.stdout??""}`.trim()||s.error?.message||`exit code ${s.status}`}).`}:{ok:!0,support:r}}finally{w(o,{recursive:!0,force:!0})}}c(Y,"probeWindowsSandbox");export{P as MXC_POLICY_VERSION,x as MXC_SDK_DIR_ENV,H as WINDOWS_SANDBOX_LIMITATIONS,k as createRunDirectory,B as loadMxcRuntime,J as prepareWindowsCommand,Y as probeWindowsSandbox,f as quoteWindowsArgument,V as setMxcRuntimeForTesting,T as shellInstallRoot,l as toWindowsPath,W as windowsInnerCommand,j as windowsOuterCommand,R as windowsSandboxEnvironment,C as windowsSandboxPolicy};
@@ -81,6 +81,7 @@ export interface ShellToolConfig {
81
81
  tempFilePrefix: string;
82
82
  readOnlyCommand?: (command: unknown) => boolean;
83
83
  sandboxShell?: (shellPath: string | undefined) => string;
84
+ sandboxShellKind?: "bash" | "powershell";
84
85
  defaultOperations?: () => BashOperations;
85
86
  }
86
87
  export declare function createShellToolDefinition(cwd: string, config: ShellToolConfig, options?: BashToolOptions): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState>;
@@ -1,6 +1,6 @@
1
- var le=Object.defineProperty;var d=(t,e)=>le(t,"name",{value:e,configurable:!0});import{constants as ue}from"node:fs";import{access as ce}from"node:fs/promises";import{constants as me}from"node:os";import{ToolExecutionError as pe}from"@earendil-works/pi-agent-core";import{Container as fe,Text as M,truncateToWidth as he}from"@earendil-works/pi-tui";import{spawn as we}from"child_process";import{Type as f}from"typebox";import{fill as C,t as $}from"../../dal/i18n.js";import{keyHint as Se}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as xe}from"../../modes/interactive/components/visual-truncate.js";import{theme as x}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as be}from"../../utils/child-process.js";import{getShellConfig as Y,getShellEnv as q,killProcessTree as J,trackDetachedChildPid as Ee,untrackDetachedChildPid as $e}from"../../utils/shell.js";import{describeDenialForModel as Oe}from"../sandbox/denial.js";import{getProcessShellSandbox as ye}from"../sandbox/shell-sandbox.js";import{isReadOnlyBashCommand as Te}from"./bash-read-only.js";import{OutputAccumulator as Pe}from"./output-accumulator.js";import{countOutputLines as ge,formatCollapsedSummary as Le,getTextOutput as Q,invalidArgText as Ce,str as Z,truncateDisplay as _e}from"./render-utils.js";import{wrapToolDefinition as ve}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as U,DEFAULT_MAX_LINES as Ie,formatSize as A}from"./truncate.js";const ee=2147483647,De=ee/1e3,te=12e4;function Fe(t){if(t===void 0)return te;if(!Number.isFinite(t)||t<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const e=t*1e3;if(e>ee)throw new Error(`Invalid timeout: maximum is ${De} seconds`);return e}d(Fe,"resolveTimeoutMs");const ne=f.Object({command:f.String({description:"Shell command to execute"}),description:f.String({description:`One short line, in the user's language, saying what this command does and why \u2014 shown in place of the command itself. Describe the intent, not the syntax: "Find hardcoded key names", not "run grep with --exclude-dir". 3-10 words.`}),timeout:f.Optional(f.Number({description:"Timeout in seconds. Defaults to 120; raise it for genuinely long-running commands."}))}),Me=f.Optional(f.Object({mode:f.Union([f.Literal("allow"),f.Literal("unsandboxed")],{description:'"allow": run sandboxed with the extra domains / writable paths below. "unsandboxed": run outside the sandbox entirely.'}),justification:f.String({description:"One sentence for the user saying why this access is needed. The user must approve it."}),allow_domains:f.Optional(f.Array(f.String(),{description:"Domains to allow, e.g. registry.npmjs.org"})),allow_write:f.Optional(f.Array(f.String(),{description:"Paths to make writable"}))},{description:"Only after the sandbox blocked this command: ask the user for the access it needs. Never use it pre-emptively."})),ke=f.Object({...ne.properties,sandbox_escalation:Me}),ie={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect PI_* environment variables for current model and session details."]};function Ae(t,e){return{exec:d(async(i,s,{onData:c,signal:a,timeout:b,env:l})=>{const p=Fe(b);if(a?.aborted)throw new Error("aborted");const w=e();try{await ce(s,ue.F_OK)}catch{throw new Error(`Working directory does not exist: ${s}
1
+ var le=Object.defineProperty;var d=(t,e)=>le(t,"name",{value:e,configurable:!0});import{constants as ue}from"node:fs";import{access as ce}from"node:fs/promises";import{constants as me}from"node:os";import{ToolExecutionError as pe}from"@earendil-works/pi-agent-core";import{Container as fe,Text as M,truncateToWidth as he}from"@earendil-works/pi-tui";import{spawn as we}from"child_process";import{Type as f}from"typebox";import{fill as C,t as $}from"../../dal/i18n.js";import{keyHint as Se}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as xe}from"../../modes/interactive/components/visual-truncate.js";import{theme as x}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as be}from"../../utils/child-process.js";import{getShellConfig as Y,getShellEnv as q,killProcessTree as J,trackDetachedChildPid as Ee,untrackDetachedChildPid as $e}from"../../utils/shell.js";import{describeDenialForModel as Oe}from"../sandbox/denial.js";import{getProcessShellSandbox as ye}from"../sandbox/shell-sandbox.js";import{isReadOnlyBashCommand as Te}from"./bash-read-only.js";import{OutputAccumulator as Pe}from"./output-accumulator.js";import{countOutputLines as ge,formatCollapsedSummary as Le,getTextOutput as Q,invalidArgText as ve,str as Z,truncateDisplay as Ce}from"./render-utils.js";import{wrapToolDefinition as _e}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as U,DEFAULT_MAX_LINES as Ie,formatSize as A}from"./truncate.js";const ee=2147483647,De=ee/1e3,te=12e4;function Fe(t){if(t===void 0)return te;if(!Number.isFinite(t)||t<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const e=t*1e3;if(e>ee)throw new Error(`Invalid timeout: maximum is ${De} seconds`);return e}d(Fe,"resolveTimeoutMs");const ne=f.Object({command:f.String({description:"Shell command to execute"}),description:f.String({description:`One short line, in the user's language, saying what this command does and why \u2014 shown in place of the command itself. Describe the intent, not the syntax: "Find hardcoded key names", not "run grep with --exclude-dir". 3-10 words.`}),timeout:f.Optional(f.Number({description:"Timeout in seconds. Defaults to 120; raise it for genuinely long-running commands."}))}),Me=f.Optional(f.Object({mode:f.Union([f.Literal("allow"),f.Literal("unsandboxed")],{description:'"allow": run sandboxed with the extra domains / writable paths below. "unsandboxed": run outside the sandbox entirely.'}),justification:f.String({description:"One sentence for the user saying why this access is needed. The user must approve it."}),allow_domains:f.Optional(f.Array(f.String(),{description:"Domains to allow, e.g. registry.npmjs.org"})),allow_write:f.Optional(f.Array(f.String(),{description:"Paths to make writable"}))},{description:"Only after the sandbox blocked this command: ask the user for the access it needs. Never use it pre-emptively."})),ke=f.Object({...ne.properties,sandbox_escalation:Me}),ie={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect PI_* environment variables for current model and session details."]};function Ae(t,e){return{exec:d(async(i,s,{onData:c,signal:a,timeout:b,env:l})=>{const p=Fe(b);if(a?.aborted)throw new Error("aborted");const w=e();try{await ce(s,ue.F_OK)}catch{throw new Error(`Working directory does not exist: ${s}
2
2
  Cannot execute ${t} commands.`)}const h=w.commandTransport==="stdin",n=we(w.shell,h?w.args:[...w.args,i],{cwd:s,detached:process.platform!=="win32",env:l??q(),stdio:[h?"pipe":"ignore","pipe","pipe"],windowsHide:!0});h&&(n.stdin?.on("error",()=>{}),n.stdin?.end(i)),n.pid&&Ee(n.pid);let m=!1,o;const u=d(()=>{n.pid&&J(n.pid)},"onAbort");try{p!==void 0&&(o=setTimeout(()=>{m=!0,n.pid&&J(n.pid)},p)),n.stdout?.on("data",c),n.stderr?.on("data",c),a&&(a.aborted?u():a.addEventListener("abort",u,{once:!0}));const O=await be(n);if(a?.aborted)throw new Error("aborted");if(m)throw new Error(`timeout:${(p??te)/1e3}`);const P=n.signalCode;return{exitCode:O??(P?128+(me.signals[P]??0):1)}}finally{n.pid&&$e(n.pid),o&&clearTimeout(o),a&&a.removeEventListener("abort",u)}},"exec")}}d(Ae,"createLocalShellOperations");function Ne(t){return Ae("bash",()=>Y(t?.shellPath))}d(Ne,"createLocalBashOperations");const W=new Set;function ht(t){return W.add(t),()=>{W.delete(t)}}d(ht,"registerShellExecutionGuard");async function Be(t){for(const e of W){let i;try{i=await e(t)}catch(s){return`Command refused: the safety check could not run (${s instanceof Error?s.message:String(s)}).`}if(i!==void 0)return i}}d(Be,"shellExecutionRefusal");function Re(t,e,i,s,c){const a={...q()};if(delete a.PI_SESSION_ID,delete a.PI_SESSION_FILE,delete a.PI_PROVIDER,delete a.PI_MODEL,delete a.PI_REASONING_LEVEL,s&&c){const l=c.model;a.PI_SESSION_ID=c.sessionManager.getSessionId();const p=c.sessionManager.getSessionFile();p&&(a.PI_SESSION_FILE=p),l&&(a.PI_PROVIDER=l.provider,a.PI_MODEL=l.id),c.thinkingLevel&&(a.PI_REASONING_LEVEL=c.thinkingLevel)}const b={command:t,cwd:e,env:a};return i?i(b):b}d(Re,"resolveSpawnContext");const Ge=5,je=100;class Ue extends fe{static{d(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function oe(t){const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const i=Math.floor(e),s=Math.floor(i/60),c=i%60;return s<60?`${s}m ${c}s`:`${Math.floor(s/60)}h ${s%60}m ${c}s`}d(oe,"formatDuration");function We(t,e,i=!1){const s=Z(t?.command),c=Z(t?.description)?.trim(),a=t?.timeout,b=a?x.fg("muted",C($(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:a})):"";if(c){const p=x.fg("toolTitle",x.bold(c))+b;return!i||!s?p:`${p}
3
- ${x.fg("muted",` \u23BF ${e} ${s.trim()}`)}`}const l=s===null?Ce(x):s?x.fg("dim",_e(s.replace(/\s+/g," ").trim(),42)):x.fg("dim","\u2026");return`${x.fg("toolTitle",x.bold(e))} ${l}${b}`}d(We,"formatShellCall");function He(t,e,i,s,c,a,b){const l=t.state;if(t.clear(),!i.expanded&&!b){const n=Q(e,s),m=ge(n),o=[];if(m>0&&o.push(C($("{count} \u884C"),{count:m})),c!==void 0){const P=(a??Date.now())-c;if(i.isPartial||P>=100){const k=i.isPartial?$("\u5DF2\u8FD0\u884C"):$("\u8017\u65F6");o.push(`${k} ${oe(P)}`)}}const u=Le(x,o);u&&t.addChild(new M(u,0,0));return}let p=Q(e,s).trim();const w=e.details?.truncation,h=e.details?.fullOutputPath;if(!i.isPartial&&w?.truncated&&h&&p.endsWith("]")){const n=p.lastIndexOf(`
3
+ ${x.fg("muted",` \u23BF ${e} ${s.trim()}`)}`}const l=s===null?ve(x):s?x.fg("dim",Ce(s.replace(/\s+/g," ").trim(),42)):x.fg("dim","\u2026");return`${x.fg("toolTitle",x.bold(e))} ${l}${b}`}d(We,"formatShellCall");function He(t,e,i,s,c,a,b){const l=t.state;if(t.clear(),!i.expanded&&!b){const n=Q(e,s),m=ge(n),o=[];if(m>0&&o.push(C($("{count} \u884C"),{count:m})),c!==void 0){const P=(a??Date.now())-c;if(i.isPartial||P>=100){const k=i.isPartial?$("\u5DF2\u8FD0\u884C"):$("\u8017\u65F6");o.push(`${k} ${oe(P)}`)}}const u=Le(x,o);u&&t.addChild(new M(u,0,0));return}let p=Q(e,s).trim();const w=e.details?.truncation,h=e.details?.fullOutputPath;if(!i.isPartial&&w?.truncated&&h&&p.endsWith("]")){const n=p.lastIndexOf(`
4
4
 
5
5
  [`);n!==-1&&p.slice(n).includes(h)&&(p=p.slice(0,n).trimEnd())}if(p){const n=p.split(`
6
6
  `).map(m=>x.fg("toolOutput",m)).join(`
@@ -8,14 +8,14 @@ ${x.fg("muted",` \u23BF ${e} ${s.trim()}`)}`}const l=s===null?Ce(x):s?x.fg("dim
8
8
  ${n}`,0,0)):t.addChild({render:d(m=>{if(l.cachedLines===void 0||l.cachedWidth!==m){const o=xe(n,Ge,m);l.cachedLines=o.visualLines,l.cachedSkipped=o.skippedCount,l.cachedWidth=m}if(l.cachedSkipped&&l.cachedSkipped>0){const o=x.fg("muted",C($("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:l.cachedSkipped}))+` ${Se("app.tools.expand",$("\u5373\u53EF\u5C55\u5F00"))}${x.fg("muted",")")}`;return["",he(o,m,"..."),...l.cachedLines??[]]}return["",...l.cachedLines??[]]},"render"),invalidate:d(()=>{l.cachedWidth=void 0,l.cachedLines=void 0,l.cachedSkipped=void 0},"invalidate")})}if(w?.truncated||h){const n=[];h&&n.push(C($("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:h})),w?.truncated&&(w.truncatedBy==="lines"?n.push(C($("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:w.outputLines,total:w.totalLines})):n.push(C($("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:w.outputLines,limit:A(w.maxBytes??U)}))),t.addChild(new M(`
9
9
  ${x.fg("warning",`[${n.join(". ")}]`)}`,0,0))}if(c!==void 0){const m=(a??Date.now())-c;if(i.isPartial||m>=100){const o=i.isPartial?$("\u5DF2\u8FD0\u884C"):$("\u8017\u65F6");t.addChild(new M(`
10
10
  ${x.fg("muted",`${o} ${oe(m)}`)}`,0,0))}}}d(He,"rebuildBashResultRenderComponent");function Ve(t,e,i){const s=i?.operations??e.defaultOperations?.()??Ne({shellPath:i?.shellPath}),c=i?.commandPrefix,a=i?.exposeSessionEnvironment??!0,b=i?.spawnHook,l=i?.sandbox,p=i?.operations===void 0,w=l?.describeForModel();return{name:e.name,label:e.label,description:`Execute a ${e.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${Ie} lines or ${U/1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.${w?` ${w}`:""}`,promptSnippet:e.promptSnippet,promptGuidelines:a&&e.promptGuidelines?[...e.promptGuidelines]:void 0,executionMode:"sequential",executionModeFor:e.readOnlyCommand&&!c?h=>e.readOnlyCommand?.(h?.command)?"parallel":void 0:void 0,parameters:l?.active?ke:ne,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(h,n,m,o,u){const{command:O,timeout:P}=n;o&&o({content:[],details:void 0});const k=await Be({toolName:e.name,command:O,cwd:u?.cwd||t,sessionFile:u?.sessionManager?.getSessionFile()});if(k!==void 0)throw new Error(k);const se=c?`${c}
11
- ${O}`:O,_=Re(se,u?.cwd||t,b,a,u),N=l??(p?ye():void 0);let y;if(N?.active){if(!e.sandboxShell)throw new Error(`Command refused: ${e.shellName} commands cannot run inside the OS sandbox yet, and the sandbox level is "${N.level}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);y=await N.prepare({command:_.command,cwd:_.cwd,shell:e.sandboxShell(i?.shellPath),toolCallId:h,toolName:e.name,escalation:n.sandbox_escalation,ctx:u})}const g=new Pe({tempFilePrefix:e.tempFilePrefix});let H=!0,v,B=!1,V=0;const R=d(()=>{if(!o||!B)return;B=!1,V=Date.now();const r=g.snapshot({persistIfTruncated:!0});o({content:[{type:"text",text:r.content||""}],details:{truncation:r.truncation.truncated?r.truncation:void 0,fullOutputPath:r.fullOutputPath}})},"emitOutputUpdate"),G=d(()=>{v&&(clearTimeout(v),v=void 0)},"clearUpdateTimer"),ae=d(()=>{if(!o)return;B=!0;const r=je-(Date.now()-V);if(r<=0){G(),R();return}v??=setTimeout(()=>{v=void 0,R()},r)},"scheduleOutputUpdate"),re=d(r=>{H&&(g.append(r),ae())},"handleData"),X=d(async()=>{H=!1,g.finish(),G(),R();const r=g.snapshot({persistIfTruncated:!0});return await g.closeTempFile(),r},"finishOutput"),z=d((r,L="(no output)")=>{const S=r.truncation;let T=r.content||L,D;if(S.truncated){D={truncation:S,fullOutputPath:r.fullOutputPath};const F=S.totalLines-S.outputLines+1,E=S.totalLines;if(S.lastLinePartial){const j=A(g.getLastLineBytes());T+=`
11
+ ${O}`:O,g=Re(se,u?.cwd||t,b,a,u),N=l??(p?ye():void 0);let y;if(N?.active){if(!e.sandboxShell)throw new Error(`Command refused: ${e.shellName} commands cannot run inside the OS sandbox yet, and the sandbox level is "${N.level}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);y=await N.prepare({command:g.command,cwd:g.cwd,shell:e.sandboxShell(i?.shellPath),shellKind:e.sandboxShellKind??"bash",env:g.env,toolCallId:h,toolName:e.name,escalation:n.sandbox_escalation,ctx:u})}const L=new Pe({tempFilePrefix:e.tempFilePrefix});let H=!0,_,B=!1,V=0;const R=d(()=>{if(!o||!B)return;B=!1,V=Date.now();const r=L.snapshot({persistIfTruncated:!0});o({content:[{type:"text",text:r.content||""}],details:{truncation:r.truncation.truncated?r.truncation:void 0,fullOutputPath:r.fullOutputPath}})},"emitOutputUpdate"),G=d(()=>{_&&(clearTimeout(_),_=void 0)},"clearUpdateTimer"),ae=d(()=>{if(!o)return;B=!0;const r=je-(Date.now()-V);if(r<=0){G(),R();return}_??=setTimeout(()=>{_=void 0,R()},r)},"scheduleOutputUpdate"),re=d(r=>{H&&(L.append(r),ae())},"handleData"),K=d(async()=>{H=!1,L.finish(),G(),R();const r=L.snapshot({persistIfTruncated:!0});return await L.closeTempFile(),r},"finishOutput"),X=d((r,v="(no output)")=>{const S=r.truncation;let T=r.content||v,D;if(S.truncated){D={truncation:S,fullOutputPath:r.fullOutputPath};const F=S.totalLines-S.outputLines+1,E=S.totalLines;if(S.lastLinePartial){const j=A(L.getLastLineBytes());T+=`
12
12
 
13
13
  [Showing last ${A(S.outputBytes)} of line ${E} (line is ${j}). Full output: ${r.fullOutputPath}]`}else S.truncatedBy==="lines"?T+=`
14
14
 
15
15
  [Showing lines ${F}-${E} of ${S.totalLines}. Full output: ${r.fullOutputPath}]`:T+=`
16
16
 
17
- [Showing lines ${F}-${E} of ${S.totalLines} (${A(U)} limit). Full output: ${r.fullOutputPath}]`}return{text:T,details:D}},"formatOutput"),I=d((r,L)=>`${r?`${r}
17
+ [Showing lines ${F}-${E} of ${S.totalLines} (${A(U)} limit). Full output: ${r.fullOutputPath}]`}return{text:T,details:D}},"formatOutput"),I=d((r,v)=>`${r?`${r}
18
18
 
19
- `:""}${L}`,"appendStatus");try{let r;try{r=(await s.exec(y?.command??_.command,_.cwd,{onData:re,signal:m,timeout:P,env:_.env})).exitCode}catch(E){const j=await X(),{text:K}=z(j,"");if(await y?.finish(null,""),E instanceof Error&&E.message==="aborted")throw new Error(I(K,"Command aborted"));if(E instanceof Error&&E.message.startsWith("timeout:")){const de=E.message.split(":")[1];throw new Error(I(K,`Command timed out after ${de} seconds`))}throw E}const L=await X(),{text:S,details:T}=z(L),D=await y?.finish(r,L.content||"");if(D&&y)throw new pe(`${I(S,`Command exited with code ${r??"(none)"}`)}
19
+ `:""}${v}`,"appendStatus");try{let r;try{r=(await s.exec(y?.command??g.command,g.cwd,{onData:re,signal:m,timeout:P,env:g.env})).exitCode}catch(E){const j=await K(),{text:z}=X(j,"");if(await y?.finish(null,""),E instanceof Error&&E.message==="aborted")throw new Error(I(z,"Command aborted"));if(E instanceof Error&&E.message.startsWith("timeout:")){const de=E.message.split(":")[1];throw new Error(I(z,`Command timed out after ${de} seconds`))}throw E}const v=await K(),{text:S,details:T}=X(v),D=await y?.finish(r,v.content||"");if(D&&y)throw new pe(`${I(S,`Command exited with code ${r??"(none)"}`)}
20
20
 
21
- ${Oe(D)}`,{...T,sandbox:y.details});if(r===null)throw new Error(I(S,"Command terminated without an exit code"));if(r!==0)throw new Error(I(S,`Command exited with code ${r}`));const F=y?.details.escalation?y.details:void 0;return{content:[{type:"text",text:S}],details:F?{...T,sandbox:F}:T}}finally{G()}},renderCall(h,n,m){const o=m.state;m.executionStarted&&o.startedAt===void 0&&(o.startedAt=Date.now(),o.endedAt=void 0);const u=m.lastComponent??new M("",0,0);return u.setText(We(h,e.prompt,m.expanded===!0)),u},renderResult(h,n,m,o){const u=o.state;u.startedAt!==void 0&&n.isPartial&&!u.interval&&(u.interval=setInterval(()=>o.invalidate(),1e3)),(!n.isPartial||o.isError)&&(u.endedAt??=Date.now(),u.interval&&(clearInterval(u.interval),u.interval=void 0));const O=o.lastComponent??new Ue;return He(O,h,n,o.showImages,u.startedAt,u.endedAt,o.isError),O.invalidate(),O}}}d(Ve,"createShellToolDefinition");const Xe={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:ie.snippet,promptGuidelines:ie.guidelines,tempFilePrefix:"pi-bash",readOnlyCommand:Te,sandboxShell:d(t=>Y(t).shell,"sandboxShell")};function ze(t,e){return Ve(t,Xe,e)}d(ze,"createBashToolDefinition");function wt(t,e){const i=ze(t,e),s=ve(i);return Object.assign(s,{promptSnippet:i.promptSnippet,promptGuidelines:i.promptGuidelines}),s}d(wt,"createBashTool");export{ie as bashToolSystemPromptContribution,wt as createBashTool,ze as createBashToolDefinition,Ne as createLocalBashOperations,Ae as createLocalShellOperations,Ve as createShellToolDefinition,ht as registerShellExecutionGuard,Me as sandboxEscalationSchema};
21
+ ${Oe(D)}`,{...T,sandbox:y.details});if(r===null)throw new Error(I(S,"Command terminated without an exit code"));if(r!==0)throw new Error(I(S,`Command exited with code ${r}`));const F=y?.details.escalation?y.details:void 0;return{content:[{type:"text",text:S}],details:F?{...T,sandbox:F}:T}}finally{G()}},renderCall(h,n,m){const o=m.state;m.executionStarted&&o.startedAt===void 0&&(o.startedAt=Date.now(),o.endedAt=void 0);const u=m.lastComponent??new M("",0,0);return u.setText(We(h,e.prompt,m.expanded===!0)),u},renderResult(h,n,m,o){const u=o.state;u.startedAt!==void 0&&n.isPartial&&!u.interval&&(u.interval=setInterval(()=>o.invalidate(),1e3)),(!n.isPartial||o.isError)&&(u.endedAt??=Date.now(),u.interval&&(clearInterval(u.interval),u.interval=void 0));const O=o.lastComponent??new Ue;return He(O,h,n,o.showImages,u.startedAt,u.endedAt,o.isError),O.invalidate(),O}}}d(Ve,"createShellToolDefinition");const Ke={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:ie.snippet,promptGuidelines:ie.guidelines,tempFilePrefix:"pi-bash",readOnlyCommand:Te,sandboxShell:d(t=>Y(t).shell,"sandboxShell")};function Xe(t,e){return Ve(t,Ke,e)}d(Xe,"createBashToolDefinition");function wt(t,e){const i=Xe(t,e),s=_e(i);return Object.assign(s,{promptSnippet:i.promptSnippet,promptGuidelines:i.promptGuidelines}),s}d(wt,"createBashTool");export{ie as bashToolSystemPromptContribution,wt as createBashTool,Xe as createBashToolDefinition,Ne as createLocalBashOperations,Ae as createLocalShellOperations,Ve as createShellToolDefinition,ht as registerShellExecutionGuard,Me as sandboxEscalationSchema};
@@ -1,2 +1,2 @@
1
- var l=Object.defineProperty;var n=(e,o)=>l(e,"name",{value:o,configurable:!0});import{getPowerShellConfig as p}from"../../utils/shell.js";import{createLocalShellOperations as s,createShellToolDefinition as c}from"./bash.js";import{wrapToolDefinition as a}from"./tool-definition-wrapper.js";const m=`try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}
2
- `,i={snippet:"Execute PowerShell commands",guidelines:["You can inspect PI_* environment variables for current model and session details."]};function u(){const e=s("PowerShell",p);return{exec:n((o,t,r)=>e.exec(`${m}${o}`,t,r),"exec")}}n(u,"createLocalPowerShellOperations");const h={name:"powershell",label:"powershell",shellName:"PowerShell",prompt:"PS>",promptSnippet:i.snippet,promptGuidelines:i.guidelines,tempFilePrefix:"pi-powershell",defaultOperations:u};function f(e,o){return c(e,h,o)}n(f,"createPowerShellToolDefinition");function T(e,o){const t=f(e,o),r=a(t);return Object.assign(r,{promptSnippet:t.promptSnippet,promptGuidelines:t.promptGuidelines}),r}n(T,"createPowerShellTool");export{u as createLocalPowerShellOperations,T as createPowerShellTool,f as createPowerShellToolDefinition,i as powershellToolSystemPromptContribution};
1
+ var p=Object.defineProperty;var t=(e,o)=>p(e,"name",{value:o,configurable:!0});import{getPowerShellConfig as r}from"../../utils/shell.js";import{createLocalShellOperations as s,createShellToolDefinition as c}from"./bash.js";import{wrapToolDefinition as a}from"./tool-definition-wrapper.js";const m=`try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}
2
+ `,i={snippet:"Execute PowerShell commands",guidelines:["You can inspect PI_* environment variables for current model and session details."]};function h(){const e=s("PowerShell",r);return{exec:t((o,n,l)=>e.exec(`${m}${o}`,n,l),"exec")}}t(h,"createLocalPowerShellOperations");const u={name:"powershell",label:"powershell",shellName:"PowerShell",prompt:"PS>",promptSnippet:i.snippet,promptGuidelines:i.guidelines,tempFilePrefix:"pi-powershell",defaultOperations:h,sandboxShell:t(()=>process.platform==="win32"?r().shell:"pwsh","sandboxShell"),sandboxShellKind:"powershell"};function S(e,o){return c(e,u,o)}t(S,"createPowerShellToolDefinition");function x(e,o){const n=S(e,o),l=a(n);return Object.assign(l,{promptSnippet:n.promptSnippet,promptGuidelines:n.promptGuidelines}),l}t(x,"createPowerShellTool");export{h as createLocalPowerShellOperations,x as createPowerShellTool,S as createPowerShellToolDefinition,i as powershellToolSystemPromptContribution};
@@ -0,0 +1 @@
1
+ var f=Object.defineProperty;var i=(t,r)=>f(t,"name",{value:r,configurable:!0});const a=/^[A-Za-z_][A-Za-z0-9_]*$/;function v(t,r=process.env){const n=t.set??{},o=t.unset??[];if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("set_environment: `set` must be an object of name \u2192 string value");if(!Array.isArray(o))throw new Error("set_environment: `unset` must be an array of names");for(const[e,s]of Object.entries(n)){if(!a.test(e))throw new Error(`set_environment: invalid variable name ${JSON.stringify(e)}`);if(typeof s!="string")throw new Error(`set_environment: the value of ${e} must be a string`)}for(const e of o){if(typeof e!="string"||!a.test(e))throw new Error(`set_environment: invalid variable name ${JSON.stringify(e)}`);if(e in n)throw new Error(`set_environment: ${e} is both set and unset`)}for(const[e,s]of Object.entries(n))r[e]=s;for(const e of o)delete r[e];return[...Object.keys(n),...o]}i(v,"applyEnvironmentUpdate");export{v as applyEnvironmentUpdate};