dal-code 1.0.34 → 1.0.35

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 (84) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/core/agent-session.d.ts +2 -0
  3. package/dist/core/agent-session.js +5 -5
  4. package/dist/core/background-processes.d.ts +14 -1
  5. package/dist/core/background-processes.js +7 -6
  6. package/dist/core/git-state.js +1 -0
  7. package/dist/core/model-config.d.ts +30 -0
  8. package/dist/core/model-config.js +2 -2
  9. package/dist/core/sandbox/denial.d.ts +1 -0
  10. package/dist/core/sandbox/denial.js +4 -3
  11. package/dist/core/sandbox/shell-sandbox.js +5 -5
  12. package/dist/core/system-prompt.d.ts +1 -0
  13. package/dist/core/system-prompt.js +12 -12
  14. package/dist/core/tools/bash.d.ts +7 -0
  15. package/dist/core/tools/bash.js +14 -20
  16. package/dist/core/tools/output-accumulator.js +3 -3
  17. package/dist/core/tools/output-condense.js +1 -1
  18. package/dist/core/tools/process.d.ts +3 -4
  19. package/dist/core/tools/process.js +15 -15
  20. package/dist/core/tools/truncate.d.ts +12 -0
  21. package/dist/core/tools/truncate.js +12 -5
  22. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  23. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  24. package/dist/node_modules/@dalcode/dal-gateway/src/index.js +1 -1
  25. package/dist/node_modules/@dalcode/dal-goal/package.json +2 -2
  26. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  27. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  28. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  29. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  30. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  31. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  32. package/dist/node_modules/@dalcode/dal-mcp/src/index.js +18 -18
  33. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  34. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
  35. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  36. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +2 -2
  37. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  38. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  39. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  40. package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
  41. package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
  42. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  43. package/dist/node_modules/@dalcode/dal-skills/src/catalog.js +2 -2
  44. package/dist/node_modules/@dalcode/dal-skills/src/index.js +10 -10
  45. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  46. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +14 -16
  47. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  48. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  49. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  50. package/dist/node_modules/@dalcode/dal-tool-catalog/src/groups.js +1 -1
  51. package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -5
  52. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  53. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  54. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  55. package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
  56. package/dist/node_modules/@dalcode/deepailab/src/model-defaults.js +1 -1
  57. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  58. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  59. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.d.ts +2 -1
  60. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +5 -5
  61. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  62. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  63. package/dist/node_modules/@earendil-works/pi-ai/dist/types.d.ts +1 -0
  64. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  65. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  66. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  67. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  68. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  69. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  70. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  71. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  72. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  73. package/dist/utils/output-files.js +1 -1
  74. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  75. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  76. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  77. package/examples/extensions/gondolin/package-lock.json +2 -2
  78. package/examples/extensions/gondolin/package.json +1 -1
  79. package/examples/extensions/sandbox/package-lock.json +2 -2
  80. package/examples/extensions/sandbox/package.json +1 -1
  81. package/examples/extensions/with-deps/package-lock.json +2 -2
  82. package/examples/extensions/with-deps/package.json +1 -1
  83. package/npm-shrinkwrap.json +2 -2
  84. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- var v=Object.defineProperty;var O=(t,o)=>v(t,"name",{value:o,configurable:!0});import{readFile as R}from"node:fs/promises";import{Type as e}from"typebox";import{Compile as x}from"typebox/compile";import{stripJsonComments as T}from"../utils/json.js";import{normalizePath as k}from"../utils/paths.js";import{stripBom as A}from"../utils/text.js";const g=e.Object({p50:e.Optional(e.Number()),p75:e.Optional(e.Number()),p90:e.Optional(e.Number()),p99:e.Optional(e.Number())}),U=e.Object({allow_fallbacks:e.Optional(e.Boolean()),require_parameters:e.Optional(e.Boolean()),data_collection:e.Optional(e.Union([e.Literal("deny"),e.Literal("allow")])),zdr:e.Optional(e.Boolean()),enforce_distillable_text:e.Optional(e.Boolean()),order:e.Optional(e.Array(e.String())),only:e.Optional(e.Array(e.String())),ignore:e.Optional(e.Array(e.String())),quantizations:e.Optional(e.Array(e.String())),sort:e.Optional(e.Union([e.String(),e.Object({by:e.Optional(e.String()),partition:e.Optional(e.Union([e.String(),e.Null()]))})])),max_price:e.Optional(e.Object({prompt:e.Optional(e.Union([e.Number(),e.String()])),completion:e.Optional(e.Union([e.Number(),e.String()])),image:e.Optional(e.Union([e.Number(),e.String()])),audio:e.Optional(e.Union([e.Number(),e.String()])),request:e.Optional(e.Union([e.Number(),e.String()]))})),preferred_min_throughput:e.Optional(e.Union([e.Number(),g])),preferred_max_latency:e.Optional(e.Union([e.Number(),g]))}),C=e.Object({only:e.Optional(e.Array(e.String())),order:e.Optional(e.Array(e.String()))}),l=e.Union([e.String(),e.Null()]),h=e.Object({off:e.Optional(l),minimal:e.Optional(l),low:e.Optional(l),medium:e.Optional(l),high:e.Optional(l),xhigh:e.Optional(l),max:e.Optional(l)}),i=e.Record(e.String(),e.Unknown()),d=e.Object({off:e.Optional(i),minimal:e.Optional(i),low:e.Optional(i),medium:e.Optional(i),high:e.Optional(i),xhigh:e.Optional(i),max:e.Optional(i)}),M=e.Union([e.String(),e.Number(),e.Boolean(),e.Null()]),P=e.Object({$var:e.Union([e.Literal("thinking.enabled"),e.Literal("thinking.effort")]),omitWhenOff:e.Optional(e.Boolean())}),S=e.Union([M,P]),I=e.Object({supportsStore:e.Optional(e.Boolean()),supportsDeveloperRole:e.Optional(e.Boolean()),supportsReasoningEffort:e.Optional(e.Boolean()),supportsUsageInStreaming:e.Optional(e.Boolean()),supportsFinishReason:e.Optional(e.Boolean()),maxTokensField:e.Optional(e.Union([e.Literal("max_completion_tokens"),e.Literal("max_tokens")])),requiresToolResultName:e.Optional(e.Boolean()),requiresAssistantAfterToolResult:e.Optional(e.Boolean()),requiresThinkingAsText:e.Optional(e.Boolean()),requiresReasoningContentOnAssistantMessages:e.Optional(e.Boolean()),thinkingFormat:e.Optional(e.Union([e.Literal("openai"),e.Literal("openrouter"),e.Literal("together"),e.Literal("baseten"),e.Literal("deepseek"),e.Literal("zai"),e.Literal("qwen"),e.Literal("chat-template"),e.Literal("qwen-chat-template"),e.Literal("string-thinking"),e.Literal("ant-ling")])),chatTemplateKwargs:e.Optional(e.Record(e.String(),S)),chatTemplateArgs:e.Optional(e.Record(e.String(),S)),cacheControlFormat:e.Optional(e.Literal("anthropic")),openRouterRouting:e.Optional(U),vercelGatewayRouting:e.Optional(C),supportsOpenAIGrammarTools:e.Optional(e.Boolean()),supportsStrictMode:e.Optional(e.Boolean()),sendSessionAffinityHeaders:e.Optional(e.Boolean()),sessionAffinityFormat:e.Optional(e.Union([e.Literal("openai"),e.Literal("openai-nosession"),e.Literal("openrouter")])),supportsLongCacheRetention:e.Optional(e.Boolean()),vllmPriority:e.Optional(e.Number())}),q=e.Object({supportsDeveloperRole:e.Optional(e.Boolean()),sessionAffinityFormat:e.Optional(e.Union([e.Literal("openai"),e.Literal("openai-nosession"),e.Literal("openrouter")])),supportsLongCacheRetention:e.Optional(e.Boolean()),supportsStrictMode:e.Optional(e.Boolean()),supportsOpenAIGrammarTools:e.Optional(e.Boolean()),supportsMaxOutputTokens:e.Optional(e.Boolean())}),b={input:e.Number(),output:e.Number(),cacheRead:e.Number(),cacheWrite:e.Number()},L=e.Object({inputTokensAbove:e.Number(),...b}),f=e.Object({...b,tiers:e.Optional(e.Array(L))}),B=e.Object({short:e.Optional(e.Number({exclusiveMinimum:0})),long:e.Optional(e.Number({exclusiveMinimum:0}))}),F=e.Object({maxWidth:e.Optional(e.Integer({minimum:1})),maxHeight:e.Optional(e.Integer({minimum:1})),maxBytes:e.Optional(e.Integer({minimum:1})),jpegQuality:e.Optional(e.Integer({minimum:1,maximum:100}))}),y=e.Object({maxRequestBytes:e.Optional(e.Integer({minimum:1})),images:e.Optional(e.Object({resize:e.Optional(F),maxPerMessage:e.Optional(e.Integer({minimum:1})),maxPerRequest:e.Optional(e.Integer({minimum:1}))}))}),$=e.Object({supportsEagerToolInputStreaming:e.Optional(e.Boolean()),supportsLongCacheRetention:e.Optional(e.Boolean()),sendSessionAffinityHeaders:e.Optional(e.Boolean()),supportsCacheControlOnTools:e.Optional(e.Boolean()),supportsTemperature:e.Optional(e.Boolean()),forceAdaptiveThinking:e.Optional(e.Boolean()),allowEmptySignature:e.Optional(e.Boolean()),supportsStrictTools:e.Optional(e.Boolean()),supportsMidConvoEffort:e.Optional(e.Boolean()),allowedFallbackModels:e.Optional(e.Array(e.Object({provider:e.String({minLength:1}),model:e.String({minLength:1}),cost:f}),{maxItems:3}))}),c=e.Union([I,q,$]),E=e.Object({id:e.String({minLength:1}),name:e.Optional(e.String({minLength:1})),api:e.Optional(e.String({minLength:1})),baseUrl:e.Optional(e.String({minLength:1})),reasoning:e.Optional(e.Boolean()),thinkingLevelMap:e.Optional(h),input:e.Optional(e.Array(e.Union([e.Literal("text"),e.Literal("image")]))),inputLimits:e.Optional(y),cost:e.Optional(f),promptCache:e.Optional(B),contextWindow:e.Optional(e.Number()),maxTokens:e.Optional(e.Number()),samplingParams:e.Optional(i),samplingParamsByThinkingLevel:e.Optional(d),headers:e.Optional(e.Record(e.String(),e.String())),compat:e.Optional(c)}),z=e.Object({name:e.Optional(e.String({minLength:1})),reasoning:e.Optional(e.Boolean()),thinkingLevelMap:e.Optional(h),input:e.Optional(e.Array(e.Union([e.Literal("text"),e.Literal("image")]))),inputLimits:e.Optional(y),cost:e.Optional(e.Object({input:e.Optional(e.Number()),output:e.Optional(e.Number()),cacheRead:e.Optional(e.Number()),cacheWrite:e.Optional(e.Number()),tiers:e.Optional(e.Array(L))})),promptCache:e.Optional(B),contextWindow:e.Optional(e.Number()),maxTokens:e.Optional(e.Number()),samplingParams:e.Optional(i),samplingParamsByThinkingLevel:e.Optional(d),headers:e.Optional(e.Record(e.String(),e.String())),compat:e.Optional(c)}),_=e.Object({name:e.Optional(e.String({minLength:1})),baseUrl:e.Optional(e.String({minLength:1})),apiKey:e.Optional(e.String({minLength:1})),api:e.Optional(e.String({minLength:1})),oauth:e.Optional(e.Literal("radius")),headers:e.Optional(e.Record(e.String(),e.String())),compat:e.Optional(c),authHeader:e.Optional(e.Boolean()),models:e.Optional(e.Array(E)),modelOverrides:e.Optional(e.Record(e.String(),z))}),W=e.Object({providers:e.Record(e.String(),_)}),N=x(W);function K(t){if(t.keyword==="required"){const s=t.params.requiredProperties?.[0];if(s){const r=t.instancePath.replace(/^\//,"").replace(/\//g,".");return r?`${r}.${s}`:s}}return t.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}O(K,"formatValidationPath");function j(t){if(typeof t!="object"||t===null||Object.isFrozen(t))return t;for(const o of Object.values(t))j(o);return Object.freeze(t)}O(j,"deepFreeze");class p{static{O(this,"ModelConfig")}providers;error;constructor(o,a){this.providers=o,this.error=a}static async load(o){if(!o)return new p(new Map);const a=k(o);let s;try{s=await R(a,"utf-8")}catch(n){return n.code==="ENOENT"?new p(new Map):new p(new Map,`Failed to load models.json: ${n instanceof Error?n.message:n}
1
+ var w=Object.defineProperty;var c=(t,o)=>w(t,"name",{value:o,configurable:!0});import{readFile as v}from"node:fs/promises";import{Type as e}from"typebox";import{Compile as x}from"typebox/compile";import{stripJsonComments as T}from"../utils/json.js";import{normalizePath as k}from"../utils/paths.js";import{stripBom as A}from"../utils/text.js";const g=e.Object({p50:e.Optional(e.Number()),p75:e.Optional(e.Number()),p90:e.Optional(e.Number()),p99:e.Optional(e.Number())}),C=e.Object({allow_fallbacks:e.Optional(e.Boolean()),require_parameters:e.Optional(e.Boolean()),data_collection:e.Optional(e.Union([e.Literal("deny"),e.Literal("allow")])),zdr:e.Optional(e.Boolean()),enforce_distillable_text:e.Optional(e.Boolean()),order:e.Optional(e.Array(e.String())),only:e.Optional(e.Array(e.String())),ignore:e.Optional(e.Array(e.String())),quantizations:e.Optional(e.Array(e.String())),sort:e.Optional(e.Union([e.String(),e.Object({by:e.Optional(e.String()),partition:e.Optional(e.Union([e.String(),e.Null()]))})])),max_price:e.Optional(e.Object({prompt:e.Optional(e.Union([e.Number(),e.String()])),completion:e.Optional(e.Union([e.Number(),e.String()])),image:e.Optional(e.Union([e.Number(),e.String()])),audio:e.Optional(e.Union([e.Number(),e.String()])),request:e.Optional(e.Union([e.Number(),e.String()]))})),preferred_min_throughput:e.Optional(e.Union([e.Number(),g])),preferred_max_latency:e.Optional(e.Union([e.Number(),g]))}),U=e.Object({only:e.Optional(e.Array(e.String())),order:e.Optional(e.Array(e.String()))}),l=e.Union([e.String(),e.Null()]),h=e.Object({off:e.Optional(l),minimal:e.Optional(l),low:e.Optional(l),medium:e.Optional(l),high:e.Optional(l),xhigh:e.Optional(l),max:e.Optional(l)}),i=e.Record(e.String(),e.Unknown()),d=e.Object({off:e.Optional(i),minimal:e.Optional(i),low:e.Optional(i),medium:e.Optional(i),high:e.Optional(i),xhigh:e.Optional(i),max:e.Optional(i)}),M=e.Union([e.String(),e.Number(),e.Boolean(),e.Null()]),P=e.Object({$var:e.Union([e.Literal("thinking.enabled"),e.Literal("thinking.effort")]),omitWhenOff:e.Optional(e.Boolean())}),S=e.Union([M,P]),I=e.Object({supportsStore:e.Optional(e.Boolean()),supportsDeveloperRole:e.Optional(e.Boolean()),supportsReasoningEffort:e.Optional(e.Boolean()),supportsUsageInStreaming:e.Optional(e.Boolean()),supportsFinishReason:e.Optional(e.Boolean()),maxTokensField:e.Optional(e.Union([e.Literal("max_completion_tokens"),e.Literal("max_tokens")])),requiresToolResultName:e.Optional(e.Boolean()),requiresAssistantAfterToolResult:e.Optional(e.Boolean()),requiresThinkingAsText:e.Optional(e.Boolean()),requiresReasoningContentOnAssistantMessages:e.Optional(e.Boolean()),thinkingFormat:e.Optional(e.Union([e.Literal("openai"),e.Literal("openrouter"),e.Literal("together"),e.Literal("baseten"),e.Literal("deepseek"),e.Literal("zai"),e.Literal("qwen"),e.Literal("chat-template"),e.Literal("qwen-chat-template"),e.Literal("string-thinking"),e.Literal("ant-ling")])),chatTemplateKwargs:e.Optional(e.Record(e.String(),S)),chatTemplateArgs:e.Optional(e.Record(e.String(),S)),cacheControlFormat:e.Optional(e.Literal("anthropic")),openRouterRouting:e.Optional(C),vercelGatewayRouting:e.Optional(U),supportsOpenAIGrammarTools:e.Optional(e.Boolean()),supportsStrictMode:e.Optional(e.Boolean()),sendSessionAffinityHeaders:e.Optional(e.Boolean()),sessionAffinityFormat:e.Optional(e.Union([e.Literal("openai"),e.Literal("openai-nosession"),e.Literal("openrouter")])),supportsLongCacheRetention:e.Optional(e.Boolean()),vllmPriority:e.Optional(e.Number()),responseModelCosts:e.Optional(e.Record(e.String(),e.Object({input:e.Number(),output:e.Number(),cacheRead:e.Number(),cacheWrite:e.Number()})))}),q=e.Object({supportsDeveloperRole:e.Optional(e.Boolean()),sessionAffinityFormat:e.Optional(e.Union([e.Literal("openai"),e.Literal("openai-nosession"),e.Literal("openrouter")])),supportsLongCacheRetention:e.Optional(e.Boolean()),supportsStrictMode:e.Optional(e.Boolean()),supportsOpenAIGrammarTools:e.Optional(e.Boolean()),supportsMaxOutputTokens:e.Optional(e.Boolean())}),b={input:e.Number(),output:e.Number(),cacheRead:e.Number(),cacheWrite:e.Number()},L=e.Object({inputTokensAbove:e.Number(),...b}),f=e.Object({...b,tiers:e.Optional(e.Array(L))}),B=e.Object({short:e.Optional(e.Number({exclusiveMinimum:0})),long:e.Optional(e.Number({exclusiveMinimum:0}))}),F=e.Object({maxWidth:e.Optional(e.Integer({minimum:1})),maxHeight:e.Optional(e.Integer({minimum:1})),maxBytes:e.Optional(e.Integer({minimum:1})),jpegQuality:e.Optional(e.Integer({minimum:1,maximum:100}))}),y=e.Object({maxRequestBytes:e.Optional(e.Integer({minimum:1})),images:e.Optional(e.Object({resize:e.Optional(F),maxPerMessage:e.Optional(e.Integer({minimum:1})),maxPerRequest:e.Optional(e.Integer({minimum:1}))}))}),$=e.Object({supportsEagerToolInputStreaming:e.Optional(e.Boolean()),supportsLongCacheRetention:e.Optional(e.Boolean()),sendSessionAffinityHeaders:e.Optional(e.Boolean()),supportsCacheControlOnTools:e.Optional(e.Boolean()),supportsTemperature:e.Optional(e.Boolean()),forceAdaptiveThinking:e.Optional(e.Boolean()),allowEmptySignature:e.Optional(e.Boolean()),supportsStrictTools:e.Optional(e.Boolean()),supportsMidConvoEffort:e.Optional(e.Boolean()),allowedFallbackModels:e.Optional(e.Array(e.Object({provider:e.String({minLength:1}),model:e.String({minLength:1}),cost:f}),{maxItems:3}))}),O=e.Union([I,q,$]),E=e.Object({id:e.String({minLength:1}),name:e.Optional(e.String({minLength:1})),api:e.Optional(e.String({minLength:1})),baseUrl:e.Optional(e.String({minLength:1})),reasoning:e.Optional(e.Boolean()),thinkingLevelMap:e.Optional(h),input:e.Optional(e.Array(e.Union([e.Literal("text"),e.Literal("image")]))),inputLimits:e.Optional(y),cost:e.Optional(f),promptCache:e.Optional(B),contextWindow:e.Optional(e.Number()),maxTokens:e.Optional(e.Number()),samplingParams:e.Optional(i),samplingParamsByThinkingLevel:e.Optional(d),headers:e.Optional(e.Record(e.String(),e.String())),compat:e.Optional(O)}),z=e.Object({name:e.Optional(e.String({minLength:1})),reasoning:e.Optional(e.Boolean()),thinkingLevelMap:e.Optional(h),input:e.Optional(e.Array(e.Union([e.Literal("text"),e.Literal("image")]))),inputLimits:e.Optional(y),cost:e.Optional(e.Object({input:e.Optional(e.Number()),output:e.Optional(e.Number()),cacheRead:e.Optional(e.Number()),cacheWrite:e.Optional(e.Number()),tiers:e.Optional(e.Array(L))})),promptCache:e.Optional(B),contextWindow:e.Optional(e.Number()),maxTokens:e.Optional(e.Number()),samplingParams:e.Optional(i),samplingParamsByThinkingLevel:e.Optional(d),headers:e.Optional(e.Record(e.String(),e.String())),compat:e.Optional(O)}),W=e.Object({name:e.Optional(e.String({minLength:1})),baseUrl:e.Optional(e.String({minLength:1})),apiKey:e.Optional(e.String({minLength:1})),api:e.Optional(e.String({minLength:1})),oauth:e.Optional(e.Literal("radius")),headers:e.Optional(e.Record(e.String(),e.String())),compat:e.Optional(O),authHeader:e.Optional(e.Boolean()),models:e.Optional(e.Array(E)),modelOverrides:e.Optional(e.Record(e.String(),z))}),_=e.Object({providers:e.Record(e.String(),W)}),N=x(_);function K(t){if(t.keyword==="required"){const s=t.params.requiredProperties?.[0];if(s){const r=t.instancePath.replace(/^\//,"").replace(/\//g,".");return r?`${r}.${s}`:s}}return t.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}c(K,"formatValidationPath");function j(t){if(typeof t!="object"||t===null||Object.isFrozen(t))return t;for(const o of Object.values(t))j(o);return Object.freeze(t)}c(j,"deepFreeze");class p{static{c(this,"ModelConfig")}providers;error;constructor(o,a){this.providers=o,this.error=a}static async load(o){if(!o)return new p(new Map);const a=k(o);let s;try{s=await v(a,"utf-8")}catch(n){return n.code==="ENOENT"?new p(new Map):new p(new Map,`Failed to load models.json: ${n instanceof Error?n.message:n}
2
2
 
3
3
  File: ${a}`)}let r;try{r=JSON.parse(T(A(s)))}catch(n){return new p(new Map,`Failed to parse models.json: ${n instanceof Error?n.message:n}
4
4
 
@@ -6,4 +6,4 @@ File: ${a}`)}if(!N.Check(r)){const n=N.Errors(r).map(m=>` - ${K(m)}: ${m.messag
6
6
  `)||"Unknown schema error";return new p(new Map,`Invalid models.json schema:
7
7
  ${n}
8
8
 
9
- File: ${a}`)}const w=r,u=new Map;for(const[n,m]of Object.entries(w.providers))u.set(n,j(structuredClone(m)));return new p(u)}getProvider(o){return this.providers.get(o)}getProviderIds(){return[...this.providers.keys()]}getError(){return this.error}}export{p as ModelConfig};
9
+ File: ${a}`)}const R=r,u=new Map;for(const[n,m]of Object.entries(R.providers))u.set(n,j(structuredClone(m)));return new p(u)}getProvider(o){return this.providers.get(o)}getProviderIds(){return[...this.providers.keys()]}getError(){return this.error}}export{p as ModelConfig};
@@ -14,6 +14,7 @@ export interface SandboxDenial {
14
14
  cwd: string;
15
15
  blocked: SandboxBlockedAccess[];
16
16
  networkProxyError?: string;
17
+ scratchDir?: string;
17
18
  }
18
19
  export declare function parseViolationLine(line: string): SandboxBlockedAccess | undefined;
19
20
  export declare function parseOutput(output: string): SandboxBlockedAccess[];
@@ -1,3 +1,4 @@
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};
1
+ var u=Object.defineProperty;var d=(o,r)=>u(o,"name",{value:r,configurable:!0});function f(o,r){const t=o.replace(/\\/g,"/");for(const e of r){if(!e)continue;const s=e.replace(/\\/g,"/").replace(/\/$/,"");if(t===s||t.startsWith(`${s}/`))return!1}return/^\/(?:private\/)?(?:var\/)?tmp(?:\/|$)/.test(t)||/^\/(?:private\/)?var\/folders\/[^/]+\/[^/]+\/T(?:\/|$)/.test(t)||/^[A-Za-z]:\/(?:Windows\/Temp|Users\/[^/]+\/AppData\/Local\/Temp)(?:\/|$)/i.test(t)}d(f,"isSystemTempPath");const p=20;function h(o){const r=/deny(?:\(\d+\))?\s+(?<operation>[\w-]+)\s+(?<target>.+?)\s*$/.exec(o);if(!r?.groups)return;const{operation:t,target:e}=r.groups;if(t.startsWith("file-write"))return{kind:"file-write",target:e,source:"kernel",detail:t};if(t.startsWith("file-read"))return{kind:"file-read",target:e,source:"kernel",detail:t};if(t.startsWith("network"))return{kind:"network",target:e,source:"kernel",detail:t}}d(h,"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"}],w=/^(?:\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 r=[];for(const t of o.split(`
2
+ `)){const e=t.trim();for(const{regex:s,kind:i}of g){const a=s.exec(e);if(!a)continue;const n=a.groups?.target;if(!n){i==="network"&&r.push({kind:i,target:"(unknown host)",source:"output",detail:e});break}const c=a.groups?.port,l=i==="file-write"&&/Operation not permitted|Permission denied/.test(e)&&w.test(e)?"file-read":i;r.push({kind:l,target:c?`${n}:${c}`:n,source:"output",detail:e.slice(0,200)});break}}return r}d(k,"parseOutput");function m(o){const r=new Set,t=[];for(const e of o){const s=`${e.kind}\0${e.target}`;if(!r.has(s)&&(r.add(s),t.push(e),t.length>=p))break}return t}d(m,"dedupe");function y(o){const r=[...o.refusals.map(e=>({kind:"network",target:e.port!==void 0?`${e.host}:${e.port}`:e.host,source:"proxy"})),...o.violations.flatMap(e=>{const s=h(e.line);return s?[s]:[]})];(r.length===0||r.every(e=>e.kind==="network"&&e.target.startsWith("/")))&&r.push(...k(o.output));const t=m(r);return t.length>0?t:void 0}d(y,"collectBlockedAccesses");function $(o){const r=[`[sandbox] The OS sandbox (${o.level}, network off except allowlisted domains) blocked this command:`];for(const n of o.blocked){const c=n.source==="output"?" (inferred from the output)":"";r.push(` - ${n.kind}: ${n.target}${c}`)}o.networkProxyError&&r.push(` (allowlisted domains are unreachable too: the network proxy could not start: ${o.networkProxyError})`);const t=o.blocked.filter(n=>n.kind==="network"&&!n.target.startsWith("/")),e=o.blocked.filter(n=>n.kind==="file-write"),s=e.filter(n=>f(n.target,[o.scratchDir,o.cwd])),i=e.filter(n=>!s.includes(n));if(s.length>0){const n=o.scratchDir?`$TMPDIR (${o.scratchDir})`:"$TMPDIR";if(r.push(`Temporary files go in ${n}: it is the temp directory this sandbox lets commands write, the others are blocked. Rerun the command with those paths under $TMPDIR; do not ask to write the system temp directory.`),i.length===0&&t.length===0)return r.join(`
3
+ `)}const a={mode:"allow",justification:"<why this is needed>"};return t.length>0&&(a.allow_domains=t.map(n=>n.target.replace(/:\d+$/,""))),i.length>0&&(a.allow_write=i.map(n=>n.target)),r.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(t.length>0||i.length>0?a:{mode:"unsandboxed",justification:"<why this is needed>"})} (or mode "unsandboxed" to run outside the sandbox). The user will be asked to approve.`),r.join(`
4
+ `)}d($,"describeDenialForModel");export{y as collectBlockedAccesses,$ as describeDenialForModel,k as parseOutput,h as parseViolationLine};
@@ -1,5 +1,5 @@
1
- var G=Object.defineProperty;var m=(n,e)=>G(n,"name",{value:e,configurable:!0});import{spawnSync as Q}from"node:child_process";import{mkdirSync as V,mkdtempSync as z,rmSync as J}from"node:fs";import{tmpdir as Z}from"node:os";import{isAbsolute as P,join as q,relative as ee,resolve as oe}from"node:path";import{fill as y,t as h}from"../../dal/i18n.js";import{detectSandboxAvailability as ne}from"./availability.js";import{collectBlockedAccesses as O}from"./denial.js";import{detectNetworkCommand as T,FAIL_FAST_NETWORK_ENV as L,networkDomainsFor as te,packageCacheDirs as ie}from"./package-managers.js";import{domainMatches as U,expandPath as B,filesystemRules as ae}from"./policy.js";import{acquireSandboxRuntime as se,ensureFilteringProxy as re,proxyUnavailableReason as M,registerNetworkGrant as le,releaseSandboxRuntime as de,violationsForCommand as ce,wrapCommand as me}from"./runtime.js";import{prepareWindowsCommand as he}from"./windows.js";const R=Symbol.for("dal.sandbox.escalationHandlers"),k=globalThis;k[R]instanceof Set||(k[R]=new Set);const j=k[R];function je(n){return j.add(n),()=>{j.delete(n)}}m(je,"registerSandboxEscalationHandler");const F=Symbol.for("dal.sandbox.processSandbox");function Ae(n){k[F]=n}m(Ae,"setProcessShellSandbox");function Ne(){return k[F]}m(Ne,"getProcessShellSandbox");const K=new Map;function fe(n){const e=K.get(n);if(e)return e;const o=Q("git",["rev-parse","--absolute-git-dir","--git-common-dir"],{cwd:n,encoding:"utf8",timeout:3e3}),r=[];if(o.status===0)for(const s of o.stdout.split(`
2
- `)){const i=s.trim();if(!i)continue;const t=P(i)?i:oe(n,i),a=ee(n,t);(a.startsWith("..")||P(a))&&r.push(t)}const l=[...new Set(r)];return K.set(n,l),l}m(fe,"gitDirsOutside");function S(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}m(S,"cleanList");let ue=0;class Ie{static{m(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&&(se(),this.holdsRuntime=!0)}scratchDir(){return this.sharedScratch?this.sharedScratch():(this.ownScratch??=we(),this.ownScratch)}async dispose(){this.ownScratch&&(J(this.ownScratch,{recursive:!0,force:!0}),this.ownScratch=void 0),this.holdsRuntime&&(this.holdsRuntime=!1,await de())}get level(){return this.policy.level}get active(){return this.policy.level!=="off"}availability(){return this.availabilityOverride??ne()}status(){const e=this.availability(),o=M();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}:{},...e.isolationTier?{isolationTier:e.isolationTier}:{},...e.limitations?.length?{limitations:[...e.limitations]}:{},network:{allowedDomains:[...this.policy.network.allowedDomains],deniedDomains:[...this.policy.network.deniedDomains],...o?{proxyError:o}:{}},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, $TMPDIR (a scratch directory for this session) and package-manager caches (agent/editor config, git hooks and .env files stay read-only)",o=this.policy.network.allowedDomains,r=(o.length>0?`network is off except ${o.join(", ")}`:"network is off")+(this.policy.level==="workspace-write"?" (package installs such as npm/pnpm/yarn/pip/uv/cargo/go and curl/wget/git clone of a URL ask the user for their registry's hosts automatically before running; run them plainly, without sandbox_escalation)":"");return`Commands run inside an OS sandbox (${this.policy.level}): ${e}; ${r}; 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[`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.",'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
- `)}planNetworkEscalation(e){if(this.policy.level!=="workspace-write"||!this.availability().available)return;const o=T(e.command);if(!o)return;const r=[...this.policy.network.allowedDomains,...this.sessionDomains],l=this.policy.network.deniedDomains,s=te(o,e.cwd).filter(t=>!r.some(a=>U(t,a))&&!l.some(a=>U(t,a)));if(s.length===0)return;const i=o.ecosystems.length>0?"package-install":"download";return{mode:"allow",allow_domains:s,trigger:i,justification:i==="package-install"?h("\u8FD9\u6761\u547D\u4EE4\u8981\u5B89\u88C5\u4F9D\u8D56\uFF0C\u9700\u8981\u4ECE\u8F6F\u4EF6\u6E90\u4E0B\u8F7D\u3002"):h("\u8FD9\u6761\u547D\u4EE4\u8981\u4ECE\u7F51\u4E0A\u4E0B\u8F7D\u6587\u4EF6\u3002")}}async prepare(e){const o=this.policy.level;if(o==="off")return H(e.command,{level:o,sandboxed:!1});const r=this.unavailableRefusal();if(r&&e.escalation?.mode!=="unsandboxed")throw new Error(r);let l=[],s=[],i;const t=e.escalation||r?void 0:this.planNetworkEscalation(e),a=t?await this.approveEscalation(e,t,t.trigger):void 0;if(t&&a&&a.decidedBy!=="none"){const f={request:a.request,decision:a.decision};if(i=f,!f.decision.approved)throw new Error(`The user did not allow network access for this command${f.decision.message?` (${f.decision.message})`:""}: it needs ${t.allow_domains.join(", ")}. Do not retry it with sandbox_escalation; continue without it or ask the user.`);l=a.allowDomains,s=a.allowWrite}else if(e.escalation){const{decidedBy:f,allowDomains:x,allowWrite:C,...w}=await this.approveEscalation(e,e.escalation);if(i=w,!w.decision.approved)throw new Error(`Sandbox escalation refused${w.decision.message?`: ${w.decision.message}`:"."} Do not retry the same escalation; continue without it or ask the user.`);if(w.request.mode==="unsandboxed")return H(e.command,{level:o,sandboxed:!1,escalation:i});l=x,s=C}const d=this.availability(),b=e.shellKind??"bash";if(b!=="bash"&&d.mechanism!=="mxc")throw new Error(`Command refused: ${b} commands cannot run inside the ${d.mechanism??"OS"} sandbox, and the sandbox level is "${o}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);const u=this.scratchDir();o==="workspace-write"&&pe(T(e.command)?.managers);const p=ae(this.policy,e.cwd,{gitDirs:this.policy.level==="workspace-write"?fe(e.cwd):[],extraWrite:[...this.sessionWritable,...s],scratchDir:u}),c={allowedDomains:[...this.policy.network.allowedDomains,...this.sessionDomains,...l],deniedDomains:this.policy.network.deniedDomains,refusals:[]},D=`${process.pid}-${++ue}`,g=c.allowedDomains.length===0;if(d.mechanism==="mxc"&&d.mxc){const f=g?{...e.env??process.env,...L}:e.env;return this.prepareWindows({...e,...f?{env:f}:{}},{level:o,shellKind:b,scratch:u,rules:p,grant:c,runId:D,escalation:i,availability:d})}const v=be(u),E=g?Object.entries(L).map(([f,x])=>` ${f}=${x}`).join(""):"",A=`export DAL_SANDBOX_RUN=${D} TMPDIR=${v} TMP=${v} TEMP=${v}${E}
4
- ${e.command}`,X=Date.now(),W=await me({command:A,shell:e.shell,allowWrite:p.allowWrite,denyWrite:p.denyWrite,denyRead:p.denyRead,allowLocalBinding:e.background===!0||this.policy.network.allowLocalBinding,...d.ripgrep?{ripgrep:d.ripgrep}:{}},c),$={level:o,sandboxed:!0,...i?{escalation:i}:{}};let N=!1;return{command:W.command,sandboxed:!0,details:$,finish:m(async(f,x)=>{if(N)return $.denial;if(N=!0,W.release(),f===0)return;const C=d.platform==="darwin"?await ce(A,X,400):[],w=O({refusals:c.refusals,violations:C,output:x});if(!w)return;const I=W.proxied?void 0:M(),_={level:o,platform:d.platform,command:e.command,cwd:e.cwd,blocked:w,...I&&w.some(Y=>Y.kind==="network")?{networkProxyError:I}:{}};return $.denial=_,this.onEvent?.({type:"sandbox_denied",toolCallId:e.toolCallId,toolName:e.toolName,denial:_}),_},"finish")}}async prepareWindows(e,o){const{level:r,grant:l,availability:s}=o,i=s.mxc;if(!i)throw new Error("Command refused: the Windows sandbox (mxc) is not loaded.");let t,a;if(l.allowedDomains.length>0){const c=await re();"port"in c?t=c.port:a=c.error}const d=he({runtime:i,kind:o.shellKind,shellPath:e.shell,command:e.command,cwd:e.cwd,level:r,rules:o.rules,env:e.env??process.env,scratchDir:o.scratch,runId:o.runId,...t!==void 0?{proxyPort:t}:{},allowLocalNetwork:e.background===!0||this.policy.network.allowLocalBinding}),b=le(l),u={level:r,sandboxed:!0,...o.escalation?{escalation:o.escalation}:{}};let p=!1;return{command:d.command,sandboxed:!0,details:u,finish:m(async(c,D)=>{if(p)return u.denial;if(p=!0,b(),d.cleanup(),c===0)return;const g=O({refusals:l.refusals,violations:[],output:D});if(!g)return;const v={level:r,platform:s.platform,command:e.command,cwd:e.cwd,blocked:g,...a&&g.some(E=>E.kind==="network")?{networkProxyError:a}:{}};return u.denial=v,this.onEvent?.({type:"sandbox_denied",toolCallId:e.toolCallId,toolName:e.toolName,denial:v}),v},"finish")}}uiApprovals=Promise.resolve();queueUiApproval(e){const o=this.uiApprovals.then(e,e);return this.uiApprovals=o.catch(()=>{}),o}async approveEscalation(e,o,r){const l=o.mode==="unsandboxed"?"unsandboxed":"allow",s={toolCallId:e.toolCallId,toolName:e.toolName,command:e.command,cwd:e.cwd,level:this.policy.level,mode:l,justification:typeof o.justification=="string"?o.justification.trim():"",allowDomains:l==="allow"?S(o.allow_domains):[],allowWrite:l==="allow"?S(o.allow_write).map(t=>B(t,e.cwd)):[],background:e.background===!0,...r?{trigger:r}:{}},i=m((t,a)=>{const d=t.approved&&t.scope==="session"&&l==="unsandboxed"?{...t,scope:"once"}:t,b=d.approved&&l==="allow"?d.grant:void 0,u=[...new Set([...s.allowDomains,...S(b?.allowDomains)])],p=[...new Set([...s.allowWrite,...S(b?.allowWrite).map(c=>B(c,e.cwd))])];if(d.approved&&d.scope==="session"){for(const c of u)this.sessionDomains.add(c);for(const c of p)this.sessionWritable.add(c)}return r&&a==="none"||this.onEvent?.({type:"sandbox_escalation",toolCallId:e.toolCallId,toolName:e.toolName,request:s,decision:d,decidedBy:a}),{request:s,decision:d,decidedBy:a,allowDomains:u,allowWrite:p}},"finish");if(!s.justification)return i({approved:!1,message:"an escalation needs a justification"},"none");if(l==="allow"&&s.allowDomains.length===0&&s.allowWrite.length===0)return i({approved:!1,message:'mode "allow" needs allow_domains or allow_write'},"none");if(this.onEscalation){const t=await this.onEscalation(s,e.ctx);if(t)return i(t,"sdk")}for(const t of j){const a=await t(s,e.ctx);if(a)return i(a,"handler")}if(e.ctx?.hasUI){const t=e.ctx;return i(await this.queueUiApproval(()=>ve(s,t,e.signal)),"ui")}return i({approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"},"none")}}function H(n,e){return{command:n,sandboxed:!1,details:e,finish:m(async()=>{},"finish")}}m(H,"passthrough");function pe(n){if(!(!n||n.length===0))for(const e of ie(n))try{V(e,{recursive:!0,mode:448})}catch{}}m(pe,"ensurePackageCaches");function we(){return z(q(Z(),"dal-sandbox-"))}m(we,"createScratchDir");function be(n){return`'${n.replace(/'/g,"'\\''")}'`}m(be,"shellQuote");async function ve(n,e,o){if(o?.aborted)return{approved:!1,message:"the turn was interrupted before the user answered"};const r=h("\u4EC5\u672C\u6B21\u5141\u8BB8"),l=h("\u672C\u4F1A\u8BDD\u5185\u90FD\u5141\u8BB8"),s=h("\u62D2\u7EDD"),i=n.mode==="unsandboxed"?h("\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?y(h("\u8BBF\u95EE {domains}"),{domains:n.allowDomains.join(", ")}):"",n.allowWrite.length>0?y(h("\u5199\u5165 {paths}"),{paths:n.allowWrite.join(", ")}):""].filter(Boolean).join(h("\uFF0C\u5E76")),t=[y(h("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:i}),y(h("\u547D\u4EE4\uFF1A{command}"),{command:n.command}),y(h("\u76EE\u5F55\uFF1A{cwd}"),{cwd:n.cwd}),n.trigger?y(h("\u539F\u56E0\uFF1A{reason}"),{reason:n.justification}):y(h("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:n.justification})].join(`
5
- `),a=n.mode==="unsandboxed"?[r,s]:[r,l,s],d=await e.ui.select(t,a,o?{signal:o}:void 0);return o?.aborted?{approved:!1,message:"the turn was interrupted before the user answered"}:d===r?{approved:!0,scope:"once"}:d===l?{approved:!0,scope:"session"}:{approved:!1,message:"the user declined"}}m(ve,"askThroughUi");export{Ie as ShellSandbox,we as createScratchDir,Ne as getProcessShellSandbox,je as registerSandboxEscalationHandler,Ae as setProcessShellSandbox};
1
+ var G=Object.defineProperty;var m=(n,e)=>G(n,"name",{value:e,configurable:!0});import{spawnSync as Q}from"node:child_process";import{mkdirSync as V,mkdtempSync as z,rmSync as J}from"node:fs";import{tmpdir as Z}from"node:os";import{isAbsolute as P,join as q,relative as ee,resolve as oe}from"node:path";import{fill as y,t as h}from"../../dal/i18n.js";import{detectSandboxAvailability as ne}from"./availability.js";import{collectBlockedAccesses as O}from"./denial.js";import{detectNetworkCommand as T,FAIL_FAST_NETWORK_ENV as U,networkDomainsFor as te,packageCacheDirs as ie}from"./package-managers.js";import{domainMatches as B,expandPath as L,filesystemRules as ae}from"./policy.js";import{acquireSandboxRuntime as se,ensureFilteringProxy as re,proxyUnavailableReason as M,registerNetworkGrant as le,releaseSandboxRuntime as de,violationsForCommand as ce,wrapCommand as me}from"./runtime.js";import{prepareWindowsCommand as he}from"./windows.js";const j=Symbol.for("dal.sandbox.escalationHandlers"),k=globalThis;k[j]instanceof Set||(k[j]=new Set);const R=k[j];function Re(n){return R.add(n),()=>{R.delete(n)}}m(Re,"registerSandboxEscalationHandler");const F=Symbol.for("dal.sandbox.processSandbox");function Ae(n){k[F]=n}m(Ae,"setProcessShellSandbox");function Ne(){return k[F]}m(Ne,"getProcessShellSandbox");const K=new Map;function fe(n){const e=K.get(n);if(e)return e;const o=Q("git",["rev-parse","--absolute-git-dir","--git-common-dir"],{cwd:n,encoding:"utf8",timeout:3e3}),r=[];if(o.status===0)for(const s of o.stdout.split(`
2
+ `)){const i=s.trim();if(!i)continue;const t=P(i)?i:oe(n,i),a=ee(n,t);(a.startsWith("..")||P(a))&&r.push(t)}const l=[...new Set(r)];return K.set(n,l),l}m(fe,"gitDirsOutside");function S(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}m(S,"cleanList");let pe=0;class Ie{static{m(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&&(se(),this.holdsRuntime=!0)}scratchDir(){return this.sharedScratch?this.sharedScratch():(this.ownScratch??=we(),this.ownScratch)}async dispose(){this.ownScratch&&(J(this.ownScratch,{recursive:!0,force:!0}),this.ownScratch=void 0),this.holdsRuntime&&(this.holdsRuntime=!1,await de())}get level(){return this.policy.level}get active(){return this.policy.level!=="off"}availability(){return this.availabilityOverride??ne()}status(){const e=this.availability(),o=M();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}:{},...e.isolationTier?{isolationTier:e.isolationTier}:{},...e.limitations?.length?{limitations:[...e.limitations]}:{},network:{allowedDomains:[...this.policy.network.allowedDomains],deniedDomains:[...this.policy.network.deniedDomains],...o?{proxyError:o}:{}},sessionAllowances:{domains:[...this.sessionDomains],writablePaths:[...this.sessionWritable]}}}describeForModel(){if(!this.active)return;const e=this.policy.level==="read-only"?"writes only to $TMPDIR (session scratch)":"writes only to the working directory, $TMPDIR (session scratch) and package caches (agent/editor config, git hooks and .env stay read-only)",o=this.policy.network.allowedDomains,r=(o.length>0?`network off except ${o.join(", ")}`:"network off")+(this.policy.level==="workspace-write"?" (package installs via npm/pnpm/yarn/pip/uv/cargo/go and curl/wget/git clone ask the user for their hosts by themselves: run them plainly, without sandbox_escalation)":"");return`OS sandbox (${this.policy.level}): ${e}; ${r}; ~/.ssh and other credentials unreadable. Use sandbox_escalation only after the result says the sandbox blocked something the task needs.`}unavailableRefusal(){if(!this.active)return;const e=this.availability();if(!e.available)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.",'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
+ `)}planNetworkEscalation(e){if(this.policy.level!=="workspace-write"||!this.availability().available)return;const o=T(e.command);if(!o)return;const r=[...this.policy.network.allowedDomains,...this.sessionDomains],l=this.policy.network.deniedDomains,s=te(o,e.cwd).filter(t=>!r.some(a=>B(t,a))&&!l.some(a=>B(t,a)));if(s.length===0)return;const i=o.ecosystems.length>0?"package-install":"download";return{mode:"allow",allow_domains:s,trigger:i,justification:i==="package-install"?h("\u8FD9\u6761\u547D\u4EE4\u8981\u5B89\u88C5\u4F9D\u8D56\uFF0C\u9700\u8981\u4ECE\u8F6F\u4EF6\u6E90\u4E0B\u8F7D\u3002"):h("\u8FD9\u6761\u547D\u4EE4\u8981\u4ECE\u7F51\u4E0A\u4E0B\u8F7D\u6587\u4EF6\u3002")}}async prepare(e){const o=this.policy.level;if(o==="off")return H(e.command,{level:o,sandboxed:!1});const r=this.unavailableRefusal();if(r&&e.escalation?.mode!=="unsandboxed")throw new Error(r);let l=[],s=[],i;const t=e.escalation||r?void 0:this.planNetworkEscalation(e),a=t?await this.approveEscalation(e,t,t.trigger):void 0;if(t&&a&&a.decidedBy!=="none"){const f={request:a.request,decision:a.decision};if(i=f,!f.decision.approved)throw new Error(`The user did not allow network access for this command${f.decision.message?` (${f.decision.message})`:""}: it needs ${t.allow_domains.join(", ")}. Do not retry it with sandbox_escalation; continue without it or ask the user.`);l=a.allowDomains,s=a.allowWrite}else if(e.escalation){const{decidedBy:f,allowDomains:x,allowWrite:_,...w}=await this.approveEscalation(e,e.escalation);if(i=w,!w.decision.approved)throw new Error(`Sandbox escalation refused${w.decision.message?`: ${w.decision.message}`:"."} Do not retry the same escalation; continue without it or ask the user.`);if(w.request.mode==="unsandboxed")return H(e.command,{level:o,sandboxed:!1,escalation:i});l=x,s=_}const d=this.availability(),v=e.shellKind??"bash";if(v!=="bash"&&d.mechanism!=="mxc")throw new Error(`Command refused: ${v} commands cannot run inside the ${d.mechanism??"OS"} sandbox, and the sandbox level is "${o}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);const p=this.scratchDir();o==="workspace-write"&&ue(T(e.command)?.managers);const u=ae(this.policy,e.cwd,{gitDirs:this.policy.level==="workspace-write"?fe(e.cwd):[],extraWrite:[...this.sessionWritable,...s],scratchDir:p}),c={allowedDomains:[...this.policy.network.allowedDomains,...this.sessionDomains,...l],deniedDomains:this.policy.network.deniedDomains,refusals:[]},D=`${process.pid}-${++pe}`,g=c.allowedDomains.length===0;if(d.mechanism==="mxc"&&d.mxc){const f=g?{...e.env??process.env,...U}:e.env;return this.prepareWindows({...e,...f?{env:f}:{}},{level:o,shellKind:v,scratch:p,rules:u,grant:c,runId:D,escalation:i,availability:d})}const b=ve(p),E=g?Object.entries(U).map(([f,x])=>` ${f}=${x}`).join(""):"",A=`export DAL_SANDBOX_RUN=${D} TMPDIR=${b} TMP=${b} TEMP=${b}${E}
4
+ ${e.command}`,X=Date.now(),$=await me({command:A,shell:e.shell,allowWrite:u.allowWrite,denyWrite:u.denyWrite,denyRead:u.denyRead,allowLocalBinding:e.background===!0||this.policy.network.allowLocalBinding,...d.ripgrep?{ripgrep:d.ripgrep}:{}},c),W={level:o,sandboxed:!0,...i?{escalation:i}:{}};let N=!1;return{command:$.command,sandboxed:!0,details:W,finish:m(async(f,x)=>{if(N)return W.denial;if(N=!0,$.release(),f===0)return;const _=d.platform==="darwin"?await ce(A,X,400):[],w=O({refusals:c.refusals,violations:_,output:x});if(!w)return;const I=$.proxied?void 0:M(),C={level:o,platform:d.platform,command:e.command,cwd:e.cwd,blocked:w,scratchDir:p,...I&&w.some(Y=>Y.kind==="network")?{networkProxyError:I}:{}};return W.denial=C,this.onEvent?.({type:"sandbox_denied",toolCallId:e.toolCallId,toolName:e.toolName,denial:C}),C},"finish")}}async prepareWindows(e,o){const{level:r,grant:l,availability:s}=o,i=s.mxc;if(!i)throw new Error("Command refused: the Windows sandbox (mxc) is not loaded.");let t,a;if(l.allowedDomains.length>0){const c=await re();"port"in c?t=c.port:a=c.error}const d=he({runtime:i,kind:o.shellKind,shellPath:e.shell,command:e.command,cwd:e.cwd,level:r,rules:o.rules,env:e.env??process.env,scratchDir:o.scratch,runId:o.runId,...t!==void 0?{proxyPort:t}:{},allowLocalNetwork:e.background===!0||this.policy.network.allowLocalBinding}),v=le(l),p={level:r,sandboxed:!0,...o.escalation?{escalation:o.escalation}:{}};let u=!1;return{command:d.command,sandboxed:!0,details:p,finish:m(async(c,D)=>{if(u)return p.denial;if(u=!0,v(),d.cleanup(),c===0)return;const g=O({refusals:l.refusals,violations:[],output:D});if(!g)return;const b={level:r,platform:s.platform,command:e.command,cwd:e.cwd,blocked:g,scratchDir:o.scratch,...a&&g.some(E=>E.kind==="network")?{networkProxyError:a}:{}};return p.denial=b,this.onEvent?.({type:"sandbox_denied",toolCallId:e.toolCallId,toolName:e.toolName,denial:b}),b},"finish")}}uiApprovals=Promise.resolve();queueUiApproval(e){const o=this.uiApprovals.then(e,e);return this.uiApprovals=o.catch(()=>{}),o}async approveEscalation(e,o,r){const l=o.mode==="unsandboxed"?"unsandboxed":"allow",s={toolCallId:e.toolCallId,toolName:e.toolName,command:e.command,cwd:e.cwd,level:this.policy.level,mode:l,justification:typeof o.justification=="string"?o.justification.trim():"",allowDomains:l==="allow"?S(o.allow_domains):[],allowWrite:l==="allow"?S(o.allow_write).map(t=>L(t,e.cwd)):[],background:e.background===!0,...r?{trigger:r}:{}},i=m((t,a)=>{const d=t.approved&&t.scope==="session"&&l==="unsandboxed"?{...t,scope:"once"}:t,v=d.approved&&l==="allow"?d.grant:void 0,p=[...new Set([...s.allowDomains,...S(v?.allowDomains)])],u=[...new Set([...s.allowWrite,...S(v?.allowWrite).map(c=>L(c,e.cwd))])];if(d.approved&&d.scope==="session"){for(const c of p)this.sessionDomains.add(c);for(const c of u)this.sessionWritable.add(c)}return r&&a==="none"||this.onEvent?.({type:"sandbox_escalation",toolCallId:e.toolCallId,toolName:e.toolName,request:s,decision:d,decidedBy:a}),{request:s,decision:d,decidedBy:a,allowDomains:p,allowWrite:u}},"finish");if(!s.justification)return i({approved:!1,message:"an escalation needs a justification"},"none");if(l==="allow"&&s.allowDomains.length===0&&s.allowWrite.length===0)return i({approved:!1,message:'mode "allow" needs allow_domains or allow_write'},"none");if(this.onEscalation){const t=await this.onEscalation(s,e.ctx);if(t)return i(t,"sdk")}for(const t of R){const a=await t(s,e.ctx);if(a)return i(a,"handler")}if(e.ctx?.hasUI){const t=e.ctx;return i(await this.queueUiApproval(()=>be(s,t,e.signal)),"ui")}return i({approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"},"none")}}function H(n,e){return{command:n,sandboxed:!1,details:e,finish:m(async()=>{},"finish")}}m(H,"passthrough");function ue(n){if(!(!n||n.length===0))for(const e of ie(n))try{V(e,{recursive:!0,mode:448})}catch{}}m(ue,"ensurePackageCaches");function we(){return z(q(Z(),"dal-sandbox-"))}m(we,"createScratchDir");function ve(n){return`'${n.replace(/'/g,"'\\''")}'`}m(ve,"shellQuote");async function be(n,e,o){if(o?.aborted)return{approved:!1,message:"the turn was interrupted before the user answered"};const r=h("\u4EC5\u672C\u6B21\u5141\u8BB8"),l=h("\u672C\u4F1A\u8BDD\u5185\u90FD\u5141\u8BB8"),s=h("\u62D2\u7EDD"),i=n.mode==="unsandboxed"?h("\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?y(h("\u8BBF\u95EE {domains}"),{domains:n.allowDomains.join(", ")}):"",n.allowWrite.length>0?y(h("\u5199\u5165 {paths}"),{paths:n.allowWrite.join(", ")}):""].filter(Boolean).join(h("\uFF0C\u5E76")),t=[y(h("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:i}),y(h("\u547D\u4EE4\uFF1A{command}"),{command:n.command}),y(h("\u76EE\u5F55\uFF1A{cwd}"),{cwd:n.cwd}),n.trigger?y(h("\u539F\u56E0\uFF1A{reason}"),{reason:n.justification}):y(h("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:n.justification})].join(`
5
+ `),a=n.mode==="unsandboxed"?[r,s]:[r,l,s],d=await e.ui.select(t,a,o?{signal:o}:void 0);return o?.aborted?{approved:!1,message:"the turn was interrupted before the user answered"}:d===r?{approved:!0,scope:"once"}:d===l?{approved:!0,scope:"session"}:{approved:!1,message:"the user declined"}}m(be,"askThroughUi");export{Ie as ShellSandbox,we as createScratchDir,Ne as getProcessShellSandbox,Re as registerSandboxEscalationHandler,Ae as setProcessShellSandbox};
@@ -11,6 +11,7 @@ export interface BuildSystemPromptOptions {
11
11
  appendSystemPrompt?: string;
12
12
  sections?: Record<string, string>;
13
13
  cwd: string;
14
+ gitState?: boolean;
14
15
  contextFiles?: Array<{
15
16
  path: string;
16
17
  content: string;
@@ -1,28 +1,28 @@
1
- var x=Object.defineProperty;var l=(e,t)=>x(e,"name",{value:t,configurable:!0});import{join as v}from"node:path";import{getSystemMessageText as E}from"@earendil-works/pi-ai";import{APP_NAME as $,APP_TITLE as h,getDalDocsPath as j,getDocsPath as O,getExamplesPath as T,getReadmePath as _,IS_WHITE_LABEL_BUILD as I}from"../config.js";import{formatSkillsForPrompt as N}from"./skills.js";const A=/^[a-z][a-z0-9_-]*$/;function D(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],hiddenTools:[...e.hiddenTools??[]],toolSnippets:{...e.toolSnippets??{}},toolGuidelines:Object.fromEntries(Object.entries(e.toolGuidelines??{}).map(([t,o])=>[t,[...o]])),promptGuidelines:[...e.promptGuidelines??[]],appendSystemPrompt:e.appendSystemPrompt??"",sections:{...e.sections??{}},cwd:e.cwd,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}l(D,"normalizeBuildSystemPromptOptions");function M(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:o})=>`<project_instructions path="${t}">
2
- ${o}
1
+ var P=Object.defineProperty;var c=(e,t)=>P(e,"name",{value:t,configurable:!0});import{join as v}from"node:path";import{getSystemMessageText as E}from"@earendil-works/pi-ai";import{APP_NAME as $,APP_TITLE as h,getDalDocsPath as j,getDocsPath as O,getExamplesPath as _,getReadmePath as I,IS_WHITE_LABEL_BUILD as T}from"../config.js";import{describeGitState as N}from"./git-state.js";import{formatSkillsForPrompt as A}from"./skills.js";const D=/^[a-z][a-z0-9_-]*$/;function M(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],hiddenTools:[...e.hiddenTools??[]],toolSnippets:{...e.toolSnippets??{}},toolGuidelines:Object.fromEntries(Object.entries(e.toolGuidelines??{}).map(([t,n])=>[t,[...n]])),promptGuidelines:[...e.promptGuidelines??[]],appendSystemPrompt:e.appendSystemPrompt??"",sections:{...e.sections??{}},cwd:e.cwd,gitState:e.gitState,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}c(M,"normalizeBuildSystemPromptOptions");function R(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:n})=>`<project_instructions path="${t}">
2
+ ${n}
3
3
  </project_instructions>`)].join(`
4
4
 
5
- `)}l(M,"renderProjectContext");function R(e,t,o){const i=[],d=new Set,n=l(a=>{const m=a.trim();!m||d.has(m)||(d.add(m),i.push(m))},"addRule"),p=e.includes("bash"),f=e.includes("powershell"),r=e.includes("grep"),g=e.includes("find"),S=e.includes("ls");(p||f)&&!r&&!g&&!S&&n(p&&f?"Use bash or PowerShell for file operations like listing, searching, and finding files":f?"Use PowerShell for file operations like listing, searching, and finding files":"Use bash for file operations like ls, rg, find");for(const a of e)for(const m of t[a]??[])n(m);for(const a of o)n(a);return e.length>0&&(n("When several tool calls do not depend on each other's results (reading multiple files, independent searches or commands), make them all in one response; they run in parallel. Each extra round trip costs the user seconds"),n("Answer as soon as you can: once you know enough, give the answer or your best current conclusion, then offer to dig further. Do not investigate everything before saying anything"),n("During longer work, tell the user every few tool rounds, in a sentence or two, what you found and what you will check next"),n("If you cannot tell which product, project or file the user means, ask instead of searching widely on a guess. When the user writes while you are working, respond to that message first: it may change the direction")),n("Be concise in your responses"),n("Show file paths clearly when working with files"),i.map(a=>`- ${a}`).join(`
6
- `)}l(R,"buildRules");function L(e){const t=D(e),{customPrompt:o,selectedTools:i,hiddenTools:d,toolSnippets:n,toolGuidelines:p,promptGuidelines:f,appendSystemPrompt:r,sections:g,cwd:S,contextFiles:a,skills:m}=t;for(const s of Object.keys(g))if(!A.test(s)||s==="preamble")throw new Error(`Invalid system prompt section name: ${s}`);const b=i.filter(s=>!d.includes(s)),c={};if(o)c.preamble=o;else{c.preamble=`You are an expert coding assistant operating inside ${h} (${$}). You help users by reading files, executing commands, editing code, and writing new files.`;const s=b.filter(y=>!!n[y]),u=s.length>0?s.map(y=>`- ${y}: ${n[y]}`).join(`
7
- `):"(none)";c.tools=`${u}
5
+ `)}c(R,"renderProjectContext");function G(e,t,n){const i=[],d=new Set,o=c(l=>{const m=l.trim();!m||d.has(m)||(d.add(m),i.push(m))},"addRule"),p=e.includes("bash"),f=e.includes("powershell"),a=e.includes("grep"),g=e.includes("find"),y=e.includes("ls");(p||f)&&!a&&!g&&!y&&o(p&&f?"Use bash or PowerShell for file operations like listing, searching, and finding files":f?"Use PowerShell for file operations like listing, searching, and finding files":"Use bash for file operations like ls, rg, find");for(const l of e)for(const m of t[l]??[])o(m);for(const l of n)o(l);return e.length>0&&(o("When several tool calls do not depend on each other's results (reading multiple files, independent searches or commands), make them all in one response; they run in parallel. Each extra round trip costs the user seconds"),o("Answer as soon as you can: once you know enough, give the answer or your best current conclusion, then offer to dig further. Do not investigate everything before saying anything"),o("During longer work, tell the user every few tool rounds, in a sentence or two, what you found and what you will check next"),o("If you cannot tell which product, project or file the user means, ask instead of searching widely on a guess. When the user writes while you are working, respond to that message first: it may change the direction"),o("In a small project, read every source file the task touches in one response (parallel reads, or one command that prints them) instead of exploring one file per round"),o("Verify the behaviours the request names and the edge cases it implies; do not write exhaustive or randomized test sweeps unless asked"),o("Before reporting done, run every code path you added at least once, including backward-compatibility, fallback and error branches: a branch that never ran is not verified")),o("Be concise in your responses"),o("Show file paths clearly when working with files"),i.map(l=>`- ${l}`).join(`
6
+ `)}c(G,"buildRules");function L(e){const t=M(e),{customPrompt:n,selectedTools:i,hiddenTools:d,toolSnippets:o,toolGuidelines:p,promptGuidelines:f,appendSystemPrompt:a,sections:g,cwd:y,contextFiles:l,skills:m}=t;for(const s of Object.keys(g))if(!D.test(s)||s==="preamble")throw new Error(`Invalid system prompt section name: ${s}`);const S=i.filter(s=>!d.includes(s)),r={};if(n)r.preamble=n;else{r.preamble=`You are an expert coding assistant operating inside ${h} (${$}). You help users by reading files, executing commands, editing code, and writing new files.`;const s=S.filter(b=>!!o[b]),u=s.length>0?s.map(b=>`- ${b}: ${o[b]}`).join(`
7
+ `):"(none)";r.tools=`${u}
8
8
 
9
- In addition to the tools above, you may have access to other custom tools depending on the project.`,c.rules=R(b,p,f),c.docs=W()}r&&(c.addendum=r),a.length>0&&(c.project_context=M(a));const k=["read","bash"],w=k.find(s=>b.includes(s))??(k.some(s=>i.includes(s))?"indirect":void 0);if(w&&m.length>0){const s=N(m,w).trim();s&&(c.skills=s)}c.cwd=S.replace(/\\/g,"/");for(const[s,u]of Object.entries(g))u&&(c[s]=u);const P={preamble:c.preamble};for(const[s,u]of Object.entries(c))s!=="preamble"&&(P[s]=`<${s}>
9
+ In addition to the tools above, you may have access to other custom tools depending on the project.`,r.rules=G(S,p,f),r.docs=W()}a&&(r.addendum=a),l.length>0&&(r.project_context=R(l));const k=["read","bash"],w=k.find(s=>S.includes(s))??(k.some(s=>i.includes(s))?"indirect":void 0);if(w&&m.length>0){const s=A(m,w).trim();s&&(r.skills=s)}r.cwd=y.replace(/\\/g,"/"),t.gitState&&!g.git_state&&(r.git=N(y));for(const[s,u]of Object.entries(g))u&&(r[s]=u);const x={preamble:r.preamble};for(const[s,u]of Object.entries(r))s!=="preamble"&&(x[s]=`<${s}>
10
10
  ${u}
11
- </${s}>`);return P}l(L,"buildSystemPromptSections");const F="cwd",G="Environment of this session, part of the system prompt. Later updates to these sections arrive as system prompt updates.";function V(e){const t=e[0];if(!t||t.role!=="system"||!t.sections)return e;const o=Object.keys(t.sections),i=o.indexOf(F);if(i===-1)return e;const d=o.slice(i).map(r=>t.sections?.[r]).filter(r=>typeof r=="string"&&r.length>0),n=Object.fromEntries(o.slice(0,i).map(r=>[r,t.sections?.[r]??null])),p={...t,sections:n};if(d.length===0)return[p,...e.slice(1)];const f={role:"user",content:[{type:"text",text:`<session_environment>
12
- ${G}
11
+ </${s}>`);return x}c(L,"buildSystemPromptSections");const F="cwd",U="Environment of this session, part of the system prompt. Later updates to these sections arrive as system prompt updates.";function H(e){const t=e[0];if(!t||t.role!=="system"||!t.sections)return e;const n=Object.keys(t.sections),i=n.indexOf(F);if(i===-1)return e;const d=n.slice(i).map(a=>t.sections?.[a]).filter(a=>typeof a=="string"&&a.length>0),o=Object.fromEntries(n.slice(0,i).map(a=>[a,t.sections?.[a]??null])),p={...t,sections:o};if(d.length===0)return[p,...e.slice(1)];const f={role:"user",content:[{type:"text",text:`<session_environment>
12
+ ${U}
13
13
 
14
14
  ${d.join(`
15
15
 
16
16
  `)}
17
- </session_environment>`}],timestamp:t.timestamp};return[p,f,...e.slice(1)]}l(V,"moveSessionEnvironmentOutOfSystemPrompt");function U(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:L(e)}}l(U,"buildSystemPromptState");function H(e){return E({role:"system",...U(e),timestamp:0})}l(H,"buildSystemPrompt");function q(e,t){const o={};for(const[i,d]of Object.entries(t))e[i]!==d&&(o[i]=d);for(const i of Object.keys(e))t[i]===void 0&&(o[i]=null);return Object.keys(o).length>0?o:void 0}l(q,"diffSystemPromptSections");function W(){if(I){const e=j();return`${h} documentation (read only when the user asks about ${h} itself: its commands, settings, skills, prompt templates, extensions, packages, themes or keybindings):
17
+ </session_environment>`}],timestamp:t.timestamp};return[p,f,...e.slice(1)]}c(H,"moveSessionEnvironmentOutOfSystemPrompt");function B(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:L(e)}}c(B,"buildSystemPromptState");function J(e){return E({role:"system",...B(e),timestamp:0})}c(J,"buildSystemPrompt");function Q(e,t){const n={};for(const[i,d]of Object.entries(t))e[i]!==d&&(n[i]=d);for(const i of Object.keys(e))t[i]===void 0&&(n[i]=null);return Object.keys(n).length>0?n:void 0}c(Q,"diffSystemPromptSections");function W(){if(T){const e=j();return`${h} documentation (read only when the user asks about ${h} itself: its commands, settings, skills, prompt templates, extensions, packages, themes or keybindings):
18
18
  - Start with: ${v(e,"README.md")}
19
19
  - Topics, in the same folder: skills.md, prompt-templates.md, extensions.md, packages.md, themes.md, keybindings.md, settings.md
20
20
  - Resolve those file names under ${e}, not the current working directory
21
21
  - Read the relevant file completely before answering or implementing, and describe the product as ${h}`}return`${h} documentation (read only when the user asks about ${h} itself, its SDK, extensions, themes, skills, or TUI):
22
- - Main documentation: ${_()}
22
+ - Main documentation: ${I()}
23
23
  - Additional docs: ${O()}
24
- - Examples: ${T()} (extensions, custom tools, SDK)
24
+ - Examples: ${_()} (extensions, custom tools, SDK)
25
25
  - When reading these docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory
26
26
  - When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), packages (docs/packages.md), environment variables (docs/environment-variables.md), MCP servers (docs/mcp.md), codemode scripts and non-LLM models such as classifiers and image models (docs/codemode.md)
27
27
  - When working on these topics, read the docs and examples, and follow .md cross-references before implementing
28
- - Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}l(W,"buildDocumentationSection");export{F as SESSION_ENVIRONMENT_FIRST_SECTION,H as buildSystemPrompt,L as buildSystemPromptSections,U as buildSystemPromptState,q as diffSystemPromptSections,V as moveSessionEnvironmentOutOfSystemPrompt,D as normalizeBuildSystemPromptOptions};
28
+ - Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}c(W,"buildDocumentationSection");export{F as SESSION_ENVIRONMENT_FIRST_SECTION,J as buildSystemPrompt,L as buildSystemPromptSections,B as buildSystemPromptState,Q as diffSystemPromptSections,H as moveSessionEnvironmentOutOfSystemPrompt,M as normalizeBuildSystemPromptOptions};
@@ -1,6 +1,8 @@
1
1
  import { type AgentTool } from "@earendil-works/pi-agent-core";
2
+ import { type ChildProcess } from "child_process";
2
3
  import { type Static, Type } from "typebox";
3
4
  import { type ShellConfig } from "../../utils/shell.ts";
5
+ import type { BackgroundProcessInfo, BackgroundProcessManager } from "../background-processes.ts";
4
6
  import type { ToolDefinition } from "../extensions/types.ts";
5
7
  import { type SandboxRunDetails, type ShellSandbox } from "../sandbox/shell-sandbox.ts";
6
8
  import { type TruncationResult } from "./truncate.ts";
@@ -25,6 +27,7 @@ declare const bashOutputSchema: Type.TObject<{
25
27
  truncated: Type.TBoolean;
26
28
  full_output_path: Type.TOptional<Type.TString>;
27
29
  exit_code: Type.TNumber;
30
+ background_id: Type.TOptional<Type.TString>;
28
31
  wall_time_seconds: Type.TNumber;
29
32
  }>;
30
33
  export type BashToolOutput = Static<typeof bashOutputSchema>;
@@ -32,6 +35,7 @@ export interface BashToolDetails {
32
35
  truncation?: TruncationResult;
33
36
  fullOutputPath?: string;
34
37
  sandbox?: SandboxRunDetails;
38
+ background?: BackgroundProcessInfo;
35
39
  }
36
40
  export interface BashOperations {
37
41
  exec: (command: string, cwd: string, options: {
@@ -39,8 +43,10 @@ export interface BashOperations {
39
43
  signal?: AbortSignal;
40
44
  timeout?: number;
41
45
  env?: NodeJS.ProcessEnv;
46
+ yieldTo?: (child: ChildProcess) => boolean;
42
47
  }) => Promise<{
43
48
  exitCode: number | null;
49
+ yielded?: boolean;
44
50
  }>;
45
51
  }
46
52
  export declare function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations;
@@ -68,6 +74,7 @@ export interface BashToolOptions {
68
74
  exposeSessionEnvironment?: boolean;
69
75
  spawnHook?: BashSpawnHook;
70
76
  sandbox?: ShellSandbox;
77
+ background?: BackgroundProcessManager;
71
78
  }
72
79
  export type BashRenderState = {
73
80
  startedAt: number | undefined;
@@ -1,25 +1,19 @@
1
- var he=Object.defineProperty;var u=(t,e)=>he(t,"name",{value:e,configurable:!0});import{constants as Se}from"node:fs";import{access as we}from"node:fs/promises";import{constants as be}from"node:os";import{ToolExecutionError as xe}from"@earendil-works/pi-agent-core";import{Container as Oe,Text as k,truncateToWidth as Ee}from"@earendil-works/pi-tui";import{spawn as _e}from"child_process";import{Type as m}from"typebox";import{fill as I,t as $}from"../../dal/i18n.js";import{keyHint as $e}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as ye}from"../../modes/interactive/components/visual-truncate.js";import{theme as w}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as Pe}from"../../utils/child-process.js";import{writeOutputFile as Le}from"../../utils/output-files.js";import{getShellConfig as ee,getShellEnv as te,killProcessTree as ne,trackDetachedChildPid as Te,untrackDetachedChildPid as Ce}from"../../utils/shell.js";import{describeDenialForModel as ge}from"../sandbox/denial.js";import{getProcessShellSandbox as ve}from"../sandbox/shell-sandbox.js";import{isReadOnlyBashCommand as Ie}from"./bash-read-only.js";import{OutputAccumulator as De}from"./output-accumulator.js";import{condenseShellOutput as Ae,outputCondenseDisabled as Fe}from"./output-condense.js";import{countOutputLines as Me,formatCollapsedSummary as Ne,getTextOutput as oe,invalidArgText as ke,str as ie,truncateDisplay as Re}from"./render-utils.js";import{wrapToolDefinition as Be}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as V,DEFAULT_MAX_LINES as Ue,formatSize as R}from"./truncate.js";const se=2147483647,Ge=1024*1024,je=se/1e3,re=12e4;function Ve(t){if(t===void 0)return re;if(!Number.isFinite(t)||t<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const e=t*1e3;if(e>se)throw new Error(`Invalid timeout: maximum is ${je} seconds`);return e}u(Ve,"resolveTimeoutMs");const ae=m.Object({command:m.String({description:"Shell command to execute"}),description:m.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:m.Optional(m.Number({description:"Timeout in seconds. Defaults to 120; raise it for genuinely long-running commands."}))}),We=m.Optional(m.Object({mode:m.Union([m.Literal("allow"),m.Literal("unsandboxed")],{description:'"allow": run sandboxed with the extra domains / writable paths below. "unsandboxed": run outside the sandbox entirely.'}),justification:m.String({description:"One sentence for the user saying why this access is needed. The user must approve it."}),allow_domains:m.Optional(m.Array(m.String(),{description:"Domains to allow, e.g. registry.npmjs.org"})),allow_write:m.Optional(m.Array(m.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."})),He=m.Object({...ae.properties,sandbox_escalation:We}),de={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect DAL_* environment variables for current model and session details."]},Xe=m.Object({output:m.String({description:"Combined stdout and stderr, possibly truncated"}),truncated:m.Boolean(),full_output_path:m.Optional(m.String({description:"Full output, when truncated"})),exit_code:m.Number(),wall_time_seconds:m.Number()});function Ke(t,e){return{exec:u(async(o,s,{onData:c,signal:a,timeout:O,env:h})=>{const l=Ve(O);if(a?.aborted)throw new Error("aborted");const x=e();try{await we(s,Se.F_OK)}catch{throw new Error(`Working directory does not exist: ${s}
2
- Cannot execute ${t} commands.`)}const p=x.commandTransport==="stdin",r=_e(x.shell,p?x.args:[...x.args,o],{cwd:s,detached:process.platform!=="win32",env:h??te(),stdio:[p?"pipe":"ignore","pipe","pipe"],windowsHide:!0});p&&(r.stdin?.on("error",()=>{}),r.stdin?.end(o)),r.pid&&Te(r.pid);let S=!1,n;const i=u(()=>{r.pid&&ne(r.pid)},"onAbort");try{l!==void 0&&(n=setTimeout(()=>{S=!0,r.pid&&ne(r.pid)},l)),r.stdout?.on("data",c),r.stderr?.on("data",c),a&&(a.aborted?i():a.addEventListener("abort",i,{once:!0}));const f=await Pe(r);if(a?.aborted)throw new Error("aborted");if(S)throw new Error(`timeout:${(l??re)/1e3}`);const L=r.signalCode;return{exitCode:f??(L?128+(be.signals[L]??0):1)}}finally{r.pid&&Ce(r.pid),n&&clearTimeout(n),a&&a.removeEventListener("abort",i)}},"exec")}}u(Ke,"createLocalShellOperations");function Ye(t){return Ke("bash",()=>ee(t?.shellPath))}u(Ye,"createLocalBashOperations");const W=new Set;function It(t){return W.add(t),()=>{W.delete(t)}}u(It,"registerShellExecutionGuard");async function ze(t){for(const e of W){let o;try{o=await e(t)}catch(s){return`Command refused: the safety check could not run (${s instanceof Error?s.message:String(s)}).`}if(o!==void 0)return o}}u(ze,"shellExecutionRefusal");const qe=["SESSION_ID","SESSION_FILE","PROVIDER","MODEL","REASONING_LEVEL"];function Je(t,e,o,s,c){const a={...te()};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 h=c.model;a.PI_SESSION_ID=c.sessionManager.getSessionId();const l=c.sessionManager.getSessionFile();l&&(a.PI_SESSION_FILE=l),h&&(a.PI_PROVIDER=h.provider,a.PI_MODEL=h.id),c.thinkingLevel&&(a.PI_REASONING_LEVEL=c.thinkingLevel)}for(const h of qe){delete a[`DAL_${h}`];const l=a[`PI_${h}`];l!==void 0&&(a[`DAL_${h}`]=l)}const O={command:t,cwd:e,env:a};return o?o(O):O}u(Je,"resolveSpawnContext");const Qe=5,Ze=100;class et extends Oe{static{u(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function tt(t){const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const o=Math.floor(e),s=Math.floor(o/60),c=o%60;return s<60?`${s}m ${c}s`:`${Math.floor(s/60)}h ${s%60}m ${c}s`}u(tt,"formatDuration");function nt(t,e,o=!1){const s=ie(t?.command),c=ie(t?.description)?.trim(),a=t?.timeout,O=a?w.fg("muted",I($(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:a})):"";if(c){const l=w.fg("toolTitle",w.bold(c))+O;return!o||!s?l:`${l}
3
- ${w.fg("muted",` \u23BF ${e} ${s.trim()}`)}`}const h=s===null?ke(w):s?w.fg("dim",Re(s.replace(/\s+/g," ").trim(),42)):w.fg("dim","\u2026");return`${w.fg("toolTitle",w.bold(e))} ${h}${O}`}u(nt,"formatShellCall");function ot(t,e,o,s,c,a,O,h){const l=t.state;t.clear();const x=it(o,c,a,h);if(!o.expanded&&!O){const n=oe(e,s),i=Me(n),f=[];i>0&&f.push(I($("{count} \u884C"),{count:i})),x&&f.push(x);const L=Ne(w,f);L&&t.addChild(new k(L,0,0));return}let p=oe(e,s).trim();const r=e.details?.truncation,S=e.details?.fullOutputPath;if(!o.isPartial&&r?.truncated&&S&&p.endsWith("]")){const n=p.lastIndexOf(`
1
+ var _e=Object.defineProperty;var r=(t,e)=>_e(t,"name",{value:e,configurable:!0});import{constants as ye}from"node:fs";import{access as ge}from"node:fs/promises";import{constants as $e}from"node:os";import{ToolExecutionError as Le}from"@earendil-works/pi-agent-core";import{Container as Ce,Text as G,truncateToWidth as Te}from"@earendil-works/pi-tui";import{spawn as Pe}from"child_process";import{Type as d}from"typebox";import{fill as R,t as I}from"../../dal/i18n.js";import{keyHint as Ie}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as ve}from"../../modes/interactive/components/visual-truncate.js";import{theme as x}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as De}from"../../utils/child-process.js";import{writeOutputFile as Ae}from"../../utils/output-files.js";import{getShellConfig as ae,getShellEnv as de,killProcessTree as le,trackDetachedChildPid as ke,untrackDetachedChildPid as Fe}from"../../utils/shell.js";import{describeDenialForModel as Me}from"../sandbox/denial.js";import{getProcessShellSandbox as Ne}from"../sandbox/shell-sandbox.js";import{isReadOnlyBashCommand as Be}from"./bash-read-only.js";import{OutputAccumulator as Re}from"./output-accumulator.js";import{condenseShellOutput as Ue,outputCondenseDisabled as je}from"./output-condense.js";import{countOutputLines as Ge,formatCollapsedSummary as We,getTextOutput as ue,invalidArgText as He,str as ce,truncateDisplay as Ve}from"./render-utils.js";import{wrapToolDefinition as Xe}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as Ye,formatSize as Ke,SHELL_OUTPUT_MAX_CHARS as ee,truncateHeadTail as qe}from"./truncate.js";const me=2147483647,pe=1024*1024,ze=8*1024*1024,Je=me/1e3,te=12e4,ne=30;function Qe(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>me)throw new Error(`Invalid timeout: maximum is ${Je} seconds`);return e}r(Qe,"resolveTimeoutMs");const fe=d.Object({command:d.String({description:"Shell command to execute"}),description:d.String({description:`What it does and why, 3-10 words in the user's language, shown instead of the command: "Find hardcoded key names", not "run grep"`}),timeout:d.Optional(d.Number({description:"Seconds to wait for the command (default in the tool description). Raise it for long builds."}))}),Ze=d.Optional(d.Object({mode:d.Union([d.Literal("allow"),d.Literal("unsandboxed")],{description:'"allow": stay sandboxed with the domains/paths below; "unsandboxed": run outside the sandbox'}),justification:d.String({description:"Why, in one sentence for the user, who must approve it"}),allow_domains:d.Optional(d.Array(d.String(),{description:"e.g. registry.npmjs.org"})),allow_write:d.Optional(d.Array(d.String(),{description:"Paths to make writable"}))},{description:"Only after the sandbox blocked this command: the access it needs. Never pre-emptively."})),et=d.Object({...fe.properties,sandbox_escalation:Ze}),he={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect DAL_* environment variables for current model and session details."]},tt=d.Object({output:d.String({description:"Combined stdout and stderr, possibly truncated"}),truncated:d.Boolean(),full_output_path:d.Optional(d.String({description:"Full output, when truncated"})),exit_code:d.Number({description:"-1 while the command runs in the background"}),background_id:d.Optional(d.String({description:"Background process id, when it is still running"})),wall_time_seconds:d.Number()});function nt(t,e){return{exec:r(async(n,o,{onData:l,signal:i,timeout:_,env:w,yieldTo:s})=>{const y=Qe(_);if(i?.aborted)throw new Error("aborted");const S=e();try{await ge(o,ye.F_OK)}catch{throw new Error(`Working directory does not exist: ${o}
2
+ Cannot execute ${t} commands.`)}const b=S.commandTransport==="stdin",u=Pe(S.shell,b?S.args:[...S.args,n],{cwd:o,detached:process.platform!=="win32",env:w??de(),stdio:[b?"pipe":"ignore","pipe","pipe"],windowsHide:!0});b&&(u.stdin?.on("error",()=>{}),u.stdin?.end(n)),u.pid&&ke(u.pid);let a=!1,m=!1,h;const p=new Promise(A=>{h=r(()=>A("yielded"),"onYielded")});let f;const O=r(()=>{u.pid&&le(u.pid)},"onAbort");try{y!==void 0&&(f=setTimeout(()=>{if(s&&u.exitCode===null&&u.signalCode===null&&s(u)){m=!0,h?.();return}a=!0,u.pid&&le(u.pid)},y)),u.stdout?.on("data",l),u.stderr?.on("data",l),i&&(i.aborted?O():i.addEventListener("abort",O,{once:!0}));const A=De(u),U=await Promise.race([A,p]);if(U==="yielded")return A.catch(()=>{}),{exitCode:null,yielded:!0};const V=U;if(i?.aborted)throw new Error("aborted");if(a)throw new Error(`timeout:${(y??te)/1e3}`);const $=u.signalCode;return{exitCode:V??($?128+($e.signals[$]??0):1)}}finally{u.pid&&!m&&Fe(u.pid),f&&clearTimeout(f),i&&i.removeEventListener("abort",O)}},"exec")}}r(nt,"createLocalShellOperations");function ot(t){return nt("bash",()=>ae(t?.shellPath))}r(ot,"createLocalBashOperations");const oe=new Set;function Ut(t){return oe.add(t),()=>{oe.delete(t)}}r(Ut,"registerShellExecutionGuard");async function it(t){for(const e of oe){let n;try{n=await e(t)}catch(o){return`Command refused: the safety check could not run (${o instanceof Error?o.message:String(o)}).`}if(n!==void 0)return n}}r(it,"shellExecutionRefusal");const st=["SESSION_ID","SESSION_FILE","PROVIDER","MODEL","REASONING_LEVEL"];function rt(t,e,n,o,l){const i={...de()};if(delete i.PI_SESSION_ID,delete i.PI_SESSION_FILE,delete i.PI_PROVIDER,delete i.PI_MODEL,delete i.PI_REASONING_LEVEL,o&&l){const w=l.model;i.PI_SESSION_ID=l.sessionManager.getSessionId();const s=l.sessionManager.getSessionFile();s&&(i.PI_SESSION_FILE=s),w&&(i.PI_PROVIDER=w.provider,i.PI_MODEL=w.id),l.thinkingLevel&&(i.PI_REASONING_LEVEL=l.thinkingLevel)}for(const w of st){delete i[`DAL_${w}`];const s=i[`PI_${w}`];s!==void 0&&(i[`DAL_${w}`]=s)}const _={command:t,cwd:e,env:i};return n?n(_):_}r(rt,"resolveSpawnContext");const at=5,dt=100;class lt extends Ce{static{r(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function ut(t){const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const n=Math.floor(e),o=Math.floor(n/60),l=n%60;return o<60?`${o}m ${l}s`:`${Math.floor(o/60)}h ${o%60}m ${l}s`}r(ut,"formatDuration");function ct(t,e,n=!1){const o=ce(t?.command),l=ce(t?.description)?.trim(),i=t?.timeout,_=i?x.fg("muted",R(I(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:i})):"";if(l){const s=x.fg("toolTitle",x.bold(l))+_;return!n||!o?s:`${s}
3
+ ${x.fg("muted",` \u23BF ${e} ${o.trim()}`)}`}const w=o===null?He(x):o?x.fg("dim",Ve(o.replace(/\s+/g," ").trim(),42)):x.fg("dim","\u2026");return`${x.fg("toolTitle",x.bold(e))} ${w}${_}`}r(ct,"formatShellCall");function mt(t,e,n,o,l,i,_,w){const s=t.state;t.clear();const y=pt(n,l,i,w);if(!n.expanded&&!_){const a=ue(e,o),m=Ge(a),h=[];m>0&&h.push(R(I("{count} \u884C"),{count:m})),y&&h.push(y);const p=We(x,h);p&&t.addChild(new G(p,0,0));return}let S=ue(e,o).trim();const b=e.details?.truncation,u=e.details?.fullOutputPath;if(!n.isPartial&&b?.truncated&&u&&S.endsWith("]")){const a=S.lastIndexOf(`
4
4
 
5
- [`);n!==-1&&p.slice(n).includes(S)&&(p=p.slice(0,n).trimEnd())}if(p){const n=p.split(`
6
- `).map(i=>w.fg("toolOutput",i)).join(`
7
- `);o.expanded?t.addChild(new k(`
8
- ${n}`,0,0)):t.addChild({render:u(i=>{if(l.cachedLines===void 0||l.cachedWidth!==i){const f=ye(n,Qe,i);l.cachedLines=f.visualLines,l.cachedSkipped=f.skippedCount,l.cachedWidth=i}if(l.cachedSkipped&&l.cachedSkipped>0){const f=w.fg("muted",I($("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:l.cachedSkipped}))+` ${$e("app.tools.expand",$("\u5373\u53EF\u5C55\u5F00"))}${w.fg("muted",")")}`;return["",Ee(f,i,"..."),...l.cachedLines??[]]}return["",...l.cachedLines??[]]},"render"),invalidate:u(()=>{l.cachedWidth=void 0,l.cachedLines=void 0,l.cachedSkipped=void 0},"invalidate")})}if(r?.truncated||S){const n=[];S&&n.push(I($("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:S})),r?.truncated&&(r.truncatedBy==="lines"?n.push(I($("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:r.outputLines,total:r.totalLines})):n.push(I($("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:r.outputLines,limit:R(r.maxBytes??V)}))),t.addChild(new k(`
9
- ${w.fg("warning",`[${n.join(". ")}]`)}`,0,0))}x&&t.addChild(new k(`
10
- ${w.fg("muted",x)}`,0,0))}u(ot,"rebuildBashResultRenderComponent");function it(t,e,o,s){let c;if(!t.isPartial&&s!==void 0)c=s;else if(e!==void 0)c=(o??Date.now())-e;else return;if(!(!t.isPartial&&c<100))return`${t.isPartial?$("\u5DF2\u8FD0\u884C"):$("\u8017\u65F6")} ${tt(c)}`}u(it,"bashTimingLabel");function st(t,e,o){const s=o?.operations??e.defaultOperations?.()??Ye({shellPath:o?.shellPath}),c=o?.commandPrefix,a=o?.exposeSessionEnvironment??!0,O=o?.spawnHook,h=o?.sandbox,l=o?.operations===void 0,x=h?.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 ${Ue} lines or ${V/1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.${x?` ${x}`:""}`,promptSnippet:e.promptSnippet,promptGuidelines:a&&e.promptGuidelines?[...e.promptGuidelines]:void 0,executionMode:"sequential",executionModeFor:e.readOnlyCommand&&!c?p=>e.readOnlyCommand?.(p?.command)?"parallel":void 0:void 0,parameters:h?.active?He:ae,outputSchema:Xe,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(p,r,S,n,i){const{command:f,timeout:L}=r;n&&n({content:[],details:void 0});const H=await ze({toolName:e.name,command:f,cwd:i?.cwd||t,sessionFile:i?.sessionManager?.getSessionFile()});if(H!==void 0)throw new Error(H);const le=c?`${c}
11
- ${f}`:f,g=Je(le,i?.cwd||t,O,a,i),B=h??(l?ve():void 0);let y;if(B?.active){if(!e.sandboxShell)throw new Error(`Command refused: ${e.shellName} commands cannot run inside the OS sandbox yet, and the sandbox level is "${B.level}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);y=await B.prepare({command:g.command,cwd:g.cwd,shell:e.sandboxShell(o?.shellPath),shellKind:e.sandboxShellKind??"bash",env:g.env,toolCallId:p,toolName:e.name,escalation:r.sandbox_escalation,ctx:i,signal:S})}const T=new De({tempFilePrefix:e.tempFilePrefix});let X=!0,D,U=!1,K=0;const G=u(()=>{if(!n||!U)return;U=!1,K=Date.now();const d=T.snapshot({persistIfTruncated:!0});n({content:[{type:"text",text:d.content||""}],details:{truncation:d.truncation.truncated?d.truncation:void 0,fullOutputPath:d.fullOutputPath}})},"emitOutputUpdate"),j=u(()=>{D&&(clearTimeout(D),D=void 0)},"clearUpdateTimer"),ue=u(()=>{if(!n)return;U=!0;const d=Ze-(Date.now()-K);if(d<=0){j(),G();return}D??=setTimeout(()=>{D=void 0,G()},d)},"scheduleOutputUpdate"),ce=u(d=>{X&&(T.append(d),ue())},"handleData"),Y=u(async()=>{X=!1,T.finish(),j(),G();const d=T.snapshot({persistIfTruncated:!0});return await T.closeTempFile(),d},"finishOutput"),z=u((d,E="(no output)",P)=>{const b=d.truncation;let _=P?.text||d.content||E;P&&(_+=b.truncated?`
5
+ [`);a!==-1&&S.slice(a).includes(u)&&(S=S.slice(0,a).trimEnd())}if(S){const a=S.split(`
6
+ `).map(m=>x.fg("toolOutput",m)).join(`
7
+ `);n.expanded?t.addChild(new G(`
8
+ ${a}`,0,0)):t.addChild({render:r(m=>{if(s.cachedLines===void 0||s.cachedWidth!==m){const h=ve(a,at,m);s.cachedLines=h.visualLines,s.cachedSkipped=h.skippedCount,s.cachedWidth=m}if(s.cachedSkipped&&s.cachedSkipped>0){const h=x.fg("muted",R(I("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:s.cachedSkipped}))+` ${Ie("app.tools.expand",I("\u5373\u53EF\u5C55\u5F00"))}${x.fg("muted",")")}`;return["",Te(h,m,"..."),...s.cachedLines??[]]}return["",...s.cachedLines??[]]},"render"),invalidate:r(()=>{s.cachedWidth=void 0,s.cachedLines=void 0,s.cachedSkipped=void 0},"invalidate")})}if(b?.truncated||u){const a=[];u&&a.push(R(I("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:u})),b?.truncated&&(b.truncatedBy==="lines"?a.push(R(I("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:b.outputLines,total:b.totalLines})):a.push(R(I("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:b.outputLines,limit:Ke(b.maxBytes??Ye)}))),t.addChild(new G(`
9
+ ${x.fg("warning",`[${a.join(". ")}]`)}`,0,0))}y&&t.addChild(new G(`
10
+ ${x.fg("muted",y)}`,0,0))}r(mt,"rebuildBashResultRenderComponent");function pt(t,e,n,o){let l;if(!t.isPartial&&o!==void 0)l=o;else if(e!==void 0)l=(n??Date.now())-e;else return;if(!(!t.isPartial&&l<100))return`${t.isPartial?I("\u5DF2\u8FD0\u884C"):I("\u8017\u65F6")} ${ut(l)}`}r(pt,"bashTimingLabel");function ft(t,e,n){const o=n?.operations??e.defaultOperations?.()??ot({shellPath:n?.shellPath}),l=n?.commandPrefix,i=n?.exposeSessionEnvironment??!0,_=n?.spawnHook,w=n?.sandbox,s=n?.operations===void 0,y=w?.describeForModel(),S=n?.background;let b=!1;const u=r(a=>`Execute a ${e.shellName} command in the current working directory; returns stdout and stderr. Long output is cut to its start and end (error lines kept) and the full output saved to a file named in the result. ${a?`A command still running after \`timeout\` seconds (default ${ne}) keeps running in the background: you get its id and the output so far, then use the process tool to poll or kill it.`:`A command still running after \`timeout\` seconds (default ${te/1e3}) is killed.`}${y?` ${y}`:""}`,"describe");return{name:e.name,label:e.label,description:u(!1),prepareLoadout:S&&s?a=>(b=a.declared.some(m=>m.name==="process"),b?{descriptions:{[e.name]:u(!0)}}:void 0):void 0,promptSnippet:e.promptSnippet,promptGuidelines:i&&e.promptGuidelines?[...e.promptGuidelines]:void 0,executionMode:"sequential",executionModeFor:e.readOnlyCommand&&!l?a=>e.readOnlyCommand?.(a?.command)?"parallel":void 0:void 0,parameters:w?.active?et:fe,outputSchema:tt,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(a,m,h,p,f){const{command:O,timeout:A}=m;p&&p({content:[],details:void 0});const U=await it({toolName:e.name,command:O,cwd:f?.cwd||t,sessionFile:f?.sessionManager?.getSessionFile()});if(U!==void 0)throw new Error(U);const V=l?`${l}
11
+ ${O}`:O,$=rt(V,f?.cwd||t,_,i,f),X=w??(s?Ne():void 0);let L;if(X?.active){if(!e.sandboxShell)throw new Error(`Command refused: ${e.shellName} commands cannot run inside the OS sandbox yet, and the sandbox level is "${X.level}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);L=await X.prepare({command:$.command,cwd:$.cwd,shell:e.sandboxShell(n?.shellPath),shellKind:e.sandboxShellKind??"bash",env:$.env,toolCallId:a,toolName:e.name,escalation:m.sandbox_escalation,ctx:f,signal:h})}const T=new Re({tempFilePrefix:e.tempFilePrefix,maxBytes:ee});let W=!0,j,Y=!1,ie=0;const K=r(()=>{if(!p||!Y)return;Y=!1,ie=Date.now();const c=T.snapshot({persistIfTruncated:!0});p({content:[{type:"text",text:c.content||""}],details:{truncation:c.truncation.truncated?c.truncation:void 0,fullOutputPath:c.fullOutputPath}})},"emitOutputUpdate"),q=r(()=>{j&&(clearTimeout(j),j=void 0)},"clearUpdateTimer"),we=r(()=>{if(!p)return;Y=!0;const c=dt-(Date.now()-ie);if(c<=0){q(),K();return}j??=setTimeout(()=>{j=void 0,K()},c)},"scheduleOutputUpdate"),Se=r(c=>{W&&(T.append(c),we())},"handleData"),be=r(async()=>{W=!1,T.finish(),q(),K();const c=T.snapshot({persistIfTruncated:!0});return await T.closeTempFile(),c},"finishOutput"),z=r(async(c="(no output)")=>{const g=await be(),k=await T.readFullOutput(ze),C=je()?void 0:Ue(k.content),E=qe(C?.text??k.content,ee);let D=g.fullOutputPath;(E.truncated||C)&&!D&&(D=await Ae(e.tempFilePrefix,".log",k.content));let F=E.content||c,N;const B=g.truncation.totalLines;return E.truncated?(N={truncation:{content:E.content,truncated:!0,truncatedBy:"bytes",totalLines:B,totalBytes:g.truncation.totalBytes,outputLines:E.headLines+E.tailLines,outputBytes:Buffer.byteLength(E.content,"utf-8"),lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:B,maxBytes:ee},fullOutputPath:D},F+=`
12
12
 
13
- [Condensed: ${P.summary}.]`:`
13
+ [Truncated: first ${E.headLines} and last ${E.tailLines} of ${E.totalLines} lines shown${C?`, after condensing ${B} lines (${C.summary})`:""}; read more with read (offset/limit) or grep. Full output: ${D}]`):C&&(N={fullOutputPath:D},F+=`
14
14
 
15
- [Condensed: ${P.summary}. Full output: ${P.fullOutputPath}]`);let v;if(b.truncated){v={truncation:b,fullOutputPath:d.fullOutputPath};const F=b.totalLines-b.outputLines+1,M=b.totalLines;if(b.lastLinePartial){const N=R(T.getLastLineBytes());_+=`
15
+ [Condensed: ${C.summary}. Full output: ${D}]`),{text:F,details:N,snapshot:g}},"modelOutput"),M=r((c,g)=>`${c?`${c}
16
16
 
17
- [Showing last ${R(b.outputBytes)} of line ${M} (line is ${N}). Full output: ${d.fullOutputPath}]`}else b.truncatedBy==="lines"?_+=`
17
+ `:""}${g}`,"appendStatus"),se=performance.now();let v;const J=S&&s&&b?c=>{W=!1;try{return v=S.adopt({child:c,command:O,cwd:$.cwd,...L?{prepared:L}:{},...T.handOff()}),!0}catch{return W=!0,!1}}:void 0;try{let c;try{const P=await o.exec(L?.command??$.command,$.cwd,{onData:Se,signal:h,timeout:A??(J?ne:void 0),env:$.env,...J?{yieldTo:J}:{}});if(P.yielded&&v){const{text:H,details:Z}=await z(""),xe=A??ne,Ee=v.urls.length>0?` It printed ${v.urls.join(" ")}.`:"",Oe=`[Still running after ${xe}s, now in the background as ${v.id}.${Ee} For new output and the exit code call process with action "poll" and id "${v.id}"; "kill" stops it.]`,re=await T.readFullOutput(pe);return{content:[{type:"text",text:M(H,Oe)}],details:{...Z,background:v},structuredContent:{output:re.content,truncated:re.truncated,exit_code:-1,background_id:v.id,wall_time_seconds:Math.round((performance.now()-se)/100)/10}}}c=P.exitCode}catch(P){const{text:H}=await z("");if(await L?.finish(null,""),P instanceof Error&&P.message==="aborted")throw new Error(M(H,"Command aborted"));if(P instanceof Error&&P.message.startsWith("timeout:")){const Z=P.message.split(":")[1];throw new Error(M(H,`Command timed out after ${Z} seconds`))}throw P}const{text:g,details:k,snapshot:C}=await z(),E=await L?.finish(c,C.content||"");if(E&&L)throw new Le(`${M(g,`Command exited with code ${c??"(none)"}`)}
18
18
 
19
- [Showing lines ${F}-${M} of ${b.totalLines}. Full output: ${d.fullOutputPath}]`:_+=`
20
-
21
- [Showing lines ${F}-${M} of ${b.totalLines} (${R(V)} limit). Full output: ${d.fullOutputPath}]`}return{text:_,details:v}},"formatOutput"),A=u((d,E)=>`${d?`${d}
22
-
23
- `:""}${E}`,"appendStatus"),me=performance.now();try{let d;try{d=(await s.exec(y?.command??g.command,g.cwd,{onData:ce,signal:S,timeout:L,env:g.env})).exitCode}catch(C){const pe=await Y(),{text:Z}=z(pe,"");if(await y?.finish(null,""),C instanceof Error&&C.message==="aborted")throw new Error(A(Z,"Command aborted"));if(C instanceof Error&&C.message.startsWith("timeout:")){const fe=C.message.split(":")[1];throw new Error(A(Z,`Command timed out after ${fe} seconds`))}throw C}const E=await Y(),P=Fe()?void 0:Ae(E.content),b=P&&{...P,fullOutputPath:E.fullOutputPath??await Le(e.tempFilePrefix,".log",E.content)},{text:_,details:v}=z(E,void 0,b),F=await y?.finish(d,E.content||"");if(F&&y)throw new xe(`${A(_,`Command exited with code ${d??"(none)"}`)}
24
-
25
- ${ge(F)}`,{...v,sandbox:y.details});if(d===null)throw new Error(A(_,"Command terminated without an exit code"));const M=Math.round((performance.now()-me)/100)/10,N=await T.readFullOutput(Ge),q={output:N.content,truncated:N.truncated,...N.truncated&&E.fullOutputPath?{full_output_path:E.fullOutputPath}:{},exit_code:d,wall_time_seconds:M},J=y?.details.escalation?y.details:void 0,Q=J?{...v,sandbox:J}:v;return d!==0?{content:[{type:"text",text:A(_,`Command exited with code ${d}`)}],details:Q,structuredContent:q,isError:!0}:{content:[{type:"text",text:_}],details:Q,structuredContent:q}}finally{j()}},renderCall(p,r,S){const n=S.state;S.executionStarted&&n.startedAt===void 0&&(n.startedAt=Date.now(),n.endedAt=void 0);const i=S.lastComponent??new k("",0,0);return i.setText(nt(p,e.prompt,S.expanded===!0)),i},renderResult(p,r,S,n){const i=n.state;i.startedAt!==void 0&&r.isPartial&&!i.interval&&(i.interval=setInterval(()=>n.invalidate(),1e3)),(!r.isPartial||n.isError)&&(i.endedAt??=Date.now(),i.interval&&(clearInterval(i.interval),i.interval=void 0));const f=n.lastComponent??new et;return ot(f,p,r,n.showImages,i.startedAt,i.endedAt,n.isError,n.durationMs),f.invalidate(),f}}}u(st,"createShellToolDefinition");const rt={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:de.snippet,promptGuidelines:de.guidelines,tempFilePrefix:"dal-bash",readOnlyCommand:Ie,sandboxShell:u(t=>ee(t).shell,"sandboxShell")};function at(t,e){return st(t,rt,e)}u(at,"createBashToolDefinition");function Dt(t,e){const o=at(t,e),s=Be(o);return Object.assign(s,{promptSnippet:o.promptSnippet,promptGuidelines:o.promptGuidelines}),s}u(Dt,"createBashTool");export{de as bashToolSystemPromptContribution,Dt as createBashTool,at as createBashToolDefinition,Ye as createLocalBashOperations,Ke as createLocalShellOperations,st as createShellToolDefinition,It as registerShellExecutionGuard,We as sandboxEscalationSchema};
19
+ ${Me(E)}`,{...k,sandbox:L.details});if(c===null)throw new Error(M(g,"Command terminated without an exit code"));const D=Math.round((performance.now()-se)/100)/10,F=await T.readFullOutput(pe),N={output:F.content,truncated:F.truncated,...F.truncated&&C.fullOutputPath?{full_output_path:C.fullOutputPath}:{},exit_code:c,wall_time_seconds:D},B=L?.details.escalation?L.details:void 0,Q=B?{...k,sandbox:B}:k;return c!==0?{content:[{type:"text",text:M(g,`Command exited with code ${c}`)}],details:Q,structuredContent:N,isError:!0}:{content:[{type:"text",text:g}],details:Q,structuredContent:N}}finally{q()}},renderCall(a,m,h){const p=h.state;h.executionStarted&&p.startedAt===void 0&&(p.startedAt=Date.now(),p.endedAt=void 0);const f=h.lastComponent??new G("",0,0);return f.setText(ct(a,e.prompt,h.expanded===!0)),f},renderResult(a,m,h,p){const f=p.state;f.startedAt!==void 0&&m.isPartial&&!f.interval&&(f.interval=setInterval(()=>p.invalidate(),1e3)),(!m.isPartial||p.isError)&&(f.endedAt??=Date.now(),f.interval&&(clearInterval(f.interval),f.interval=void 0));const O=p.lastComponent??new lt;return mt(O,a,m,p.showImages,f.startedAt,f.endedAt,p.isError,p.durationMs),O.invalidate(),O}}}r(ft,"createShellToolDefinition");const ht={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:he.snippet,promptGuidelines:he.guidelines,tempFilePrefix:"dal-bash",readOnlyCommand:Be,sandboxShell:r(t=>ae(t).shell,"sandboxShell")};function wt(t,e){return ft(t,ht,e)}r(wt,"createBashToolDefinition");function jt(t,e){const n=wt(t,e),o=Xe(n);return Object.assign(o,{promptSnippet:n.promptSnippet,promptGuidelines:n.promptGuidelines}),o}r(jt,"createBashTool");export{he as bashToolSystemPromptContribution,jt as createBashTool,wt as createBashToolDefinition,ot as createLocalBashOperations,nt as createLocalShellOperations,ft as createShellToolDefinition,Ut as registerShellExecutionGuard,Ze as sandboxEscalationSchema};
@@ -1,8 +1,8 @@
1
- var f=Object.defineProperty;var a=(r,t)=>f(r,"name",{value:t,configurable:!0});import{open as p}from"node:fs/promises";import{createOutputFileStream as x}from"../../utils/output-files.js";import{DEFAULT_MAX_BYTES as y,DEFAULT_MAX_LINES as B,truncateTail as L}from"./truncate.js";function c(r){return Buffer.byteLength(r,"utf-8")}a(c,"byteLength");class S{static{a(this,"OutputAccumulator")}maxLines;maxBytes;maxRollingBytes;tempFilePrefix;decoder=new TextDecoder;rawChunks=[];tailText="";tailBytes=0;tailStartsAtLineBoundary=!0;totalRawBytes=0;totalDecodedBytes=0;completedLines=0;totalLines=0;currentLineBytes=0;hasOpenLine=!1;finished=!1;tempFilePath;tempFileStream;constructor(t={}){this.maxLines=t.maxLines??B,this.maxBytes=t.maxBytes??y,this.maxRollingBytes=Math.max(this.maxBytes*2,1),this.tempFilePrefix=t.tempFilePrefix??"dal-output"}append(t){if(this.finished)throw new Error("Cannot append to a finished output accumulator");this.totalRawBytes+=t.length,this.appendDecodedText(this.decoder.decode(t,{stream:!0})),this.tempFileStream||this.shouldUseTempFile()?(this.ensureTempFile(),this.tempFileStream?.write(t)):t.length>0&&this.rawChunks.push(t)}finish(){this.finished||(this.finished=!0,this.appendDecodedText(this.decoder.decode()),this.shouldUseTempFile()&&this.ensureTempFile())}snapshot(t={}){const e=L(this.getSnapshotText(),{maxLines:this.maxLines,maxBytes:this.maxBytes}),s=this.totalLines>this.maxLines||this.totalDecodedBytes>this.maxBytes,n=s?e.truncatedBy??(this.totalDecodedBytes>this.maxBytes?"bytes":"lines"):null,i={...e,truncated:s,truncatedBy:n,totalLines:this.totalLines,totalBytes:this.totalDecodedBytes,maxLines:this.maxLines,maxBytes:this.maxBytes};return t.persistIfTruncated&&i.truncated&&this.ensureTempFile(),{content:i.content,truncation:i,fullOutputPath:this.tempFilePath}}async closeTempFile(){if(!this.tempFileStream)return;const t=this.tempFileStream;this.tempFileStream=void 0,await new Promise((e,s)=>{const n=a(l=>{t.off("finish",i),s(l)},"onError"),i=a(()=>{t.off("error",n),e()},"onFinish");t.once("error",n),t.once("finish",i),t.end()})}async readFullOutput(t){if(!this.tempFilePath)return{content:new TextDecoder().decode(Buffer.concat(this.rawChunks)),truncated:!1};const e=await p(this.tempFilePath,"r");try{const s=(await e.stat()).size;if(s<=t)return{content:new TextDecoder().decode(await e.readFile()),truncated:!1};const n=Math.floor(t/2),i=t-n,l=Buffer.alloc(n),h=Buffer.alloc(i);await e.read(l,0,n,0),await e.read(h,0,i,s-i);const u=new TextDecoder().decode(l,{stream:!0});let o=0;for(;o<h.length&&(h[o]&192)===128;)o++;const d=new TextDecoder().decode(h.subarray(o)),m=s-n-i;return{content:`${u}
1
+ var f=Object.defineProperty;var a=(r,t)=>f(r,"name",{value:t,configurable:!0});import{open as p}from"node:fs/promises";import{createOutputFileStream as x}from"../../utils/output-files.js";import{DEFAULT_MAX_BYTES as y,DEFAULT_MAX_LINES as B,truncateTail as L}from"./truncate.js";function c(r){return Buffer.byteLength(r,"utf-8")}a(c,"byteLength");class S{static{a(this,"OutputAccumulator")}maxLines;maxBytes;maxRollingBytes;tempFilePrefix;decoder=new TextDecoder;rawChunks=[];tailText="";tailBytes=0;tailStartsAtLineBoundary=!0;totalRawBytes=0;totalDecodedBytes=0;completedLines=0;totalLines=0;currentLineBytes=0;hasOpenLine=!1;finished=!1;tempFilePath;tempFileStream;constructor(t={}){this.maxLines=t.maxLines??B,this.maxBytes=t.maxBytes??y,this.maxRollingBytes=Math.max(this.maxBytes*2,1),this.tempFilePrefix=t.tempFilePrefix??"dal-output"}append(t){if(this.finished)throw new Error("Cannot append to a finished output accumulator");this.totalRawBytes+=t.length,this.appendDecodedText(this.decoder.decode(t,{stream:!0})),this.tempFileStream||this.shouldUseTempFile()?(this.ensureTempFile(),this.tempFileStream?.write(t)):t.length>0&&this.rawChunks.push(t)}finish(){this.finished||(this.finished=!0,this.appendDecodedText(this.decoder.decode()),this.shouldUseTempFile()&&this.ensureTempFile())}snapshot(t={}){const e=L(this.getSnapshotText(),{maxLines:this.maxLines,maxBytes:this.maxBytes}),s=this.totalLines>this.maxLines||this.totalDecodedBytes>this.maxBytes,n=s?e.truncatedBy??(this.totalDecodedBytes>this.maxBytes?"bytes":"lines"):null,i={...e,truncated:s,truncatedBy:n,totalLines:this.totalLines,totalBytes:this.totalDecodedBytes,maxLines:this.maxLines,maxBytes:this.maxBytes};return t.persistIfTruncated&&i.truncated&&this.ensureTempFile(),{content:i.content,truncation:i,fullOutputPath:this.tempFilePath}}async closeTempFile(){if(!this.tempFileStream)return;const t=this.tempFileStream;this.tempFileStream=void 0,await new Promise((e,s)=>{const n=a(h=>{t.off("finish",i),s(h)},"onError"),i=a(()=>{t.off("error",n),e()},"onFinish");t.once("error",n),t.once("finish",i),t.end()})}async readFullOutput(t){if(!this.tempFilePath)return{content:new TextDecoder().decode(Buffer.concat(this.rawChunks)),truncated:!1};const e=await p(this.tempFilePath,"r");try{const s=(await e.stat()).size;if(s<=t)return{content:new TextDecoder().decode(await e.readFile()),truncated:!1};const n=Math.floor(t/2),i=t-n,h=Buffer.alloc(n),l=Buffer.alloc(i);await e.read(h,0,n,0),await e.read(l,0,i,s-i);const u=new TextDecoder().decode(h,{stream:!0});let o=0;for(;o<l.length&&(l[o]&192)===128;)o++;const m=new TextDecoder().decode(l.subarray(o)),d=s-n-i;return{content:`${u}
2
2
 
3
- [... ${m} bytes omitted ...]
3
+ [... ${d} bytes omitted ...]
4
4
 
5
- ${d}`,truncated:!0}}finally{await e.close()}}getLastLineBytes(){return this.currentLineBytes}appendDecodedText(t){if(t.length===0)return;const e=c(t);this.totalDecodedBytes+=e,this.tailText+=t,this.tailBytes+=e,this.tailBytes>this.maxRollingBytes*2&&this.trimTail();let s=0,n=-1;for(let i=t.indexOf(`
5
+ ${m}`,truncated:!0}}finally{await e.close()}}handOff(){return this.tempFilePath?{earlierFile:this.tempFilePath}:{earlier:Buffer.concat(this.rawChunks)}}getLastLineBytes(){return this.currentLineBytes}appendDecodedText(t){if(t.length===0)return;const e=c(t);this.totalDecodedBytes+=e,this.tailText+=t,this.tailBytes+=e,this.tailBytes>this.maxRollingBytes*2&&this.trimTail();let s=0,n=-1;for(let i=t.indexOf(`
6
6
  `);i!==-1;i=t.indexOf(`
7
7
  `,i+1))s++,n=i;if(s===0)this.currentLineBytes+=e,this.hasOpenLine=!0;else{this.completedLines+=s;const i=t.slice(n+1);this.currentLineBytes=c(i),this.hasOpenLine=i.length>0}this.totalLines=this.completedLines+(this.hasOpenLine?1:0)}trimTail(){const t=Buffer.from(this.tailText,"utf-8");if(t.length<=this.maxRollingBytes){this.tailBytes=t.length;return}let e=t.length-this.maxRollingBytes;for(;e<t.length&&(t[e]&192)===128;)e++;this.tailStartsAtLineBoundary=e===0?this.tailStartsAtLineBoundary:t[e-1]===10,this.tailText=t.subarray(e).toString("utf-8"),this.tailBytes=c(this.tailText)}getSnapshotText(){if(this.tailStartsAtLineBoundary)return this.tailText;const t=this.tailText.indexOf(`
8
8
  `);return t===-1?this.tailText:this.tailText.slice(t+1)}shouldUseTempFile(){return this.totalRawBytes>this.maxBytes||this.totalDecodedBytes>this.maxBytes||this.totalLines>this.maxLines}ensureTempFile(){if(this.tempFilePath)return;const{path:t,stream:e}=x(this.tempFilePrefix,".log");this.tempFilePath=t,this.tempFileStream=e;for(const s of this.rawChunks)this.tempFileStream.write(s);this.rawChunks=[]}}export{S as OutputAccumulator};
@@ -1,3 +1,3 @@
1
1
  var I=Object.defineProperty;var d=(o,t)=>I(o,"name",{value:t,configurable:!0});const g=/\b(?:error|errors|fail|failed|failure|failing|fatal|panic|exception|traceback|assert(?:ion)?|denied|segfault)\b|✗|✘|×/i,E=[/^\s*[✓✔√]\s+\S/,/^\s*PASS\s+\S/,/^\s*ok \d+ - /,/\sPASSED(?:\s+\[\s*\d+%\])?\s*$/,/^\s*--- PASS: /,/^=== (?:RUN|PAUSE|CONT|NAME)\s/,/^test \S.* \.\.\. ok$/],m=/\bwarn(?:ing)?s?\b/i,M=10,O=8,R=.15;function D(o){const t=o.split(`
2
2
  `).map(e=>{const n=e.lastIndexOf("\r",e.length-2);return n===-1?e:e.slice(n+1)}),N=t.filter(e=>E.some(n=>n.test(e))).length>=10,s=[],f=new Set;let r=0,a=-1,l=0,c=0,i=0;for(const e of t){const n=g.test(e);if(N&&!n&&E.some(u=>u.test(e))){r++,a===-1&&(a=s.length,s.push(""));continue}const h=s.length>0?s[s.length-1]:void 0;if(!n&&e.trim()!==""&&e===h){i++,c++;continue}if(i>0&&(s.push(`[previous line repeated ${i} more times]`),i=0),!n&&m.test(e)){const u=e.trim();if(f.has(u)){l++;continue}f.add(u)}s.push(e)}i>0&&s.push(`[previous line repeated ${i} more times]`),a!==-1&&(s[a]=`[${r} passing test lines collapsed]`);const _=r+l+c,S=s.join(`
3
- `);if(_<8||S.length>o.length*(1-.15))return;const p=[];return r>0&&p.push(`${r} passing test lines collapsed`),l>0&&p.push(`${l} duplicate warning lines removed`),c>0&&p.push(`${c} repeated lines collapsed`),{text:S,summary:p.join(", ")}}d(D,"condenseShellOutput");function P(o=process.env){const t=o.DAL_TOOL_OUTPUT_CONDENSE?.trim().toLowerCase();return t==="0"||t==="off"||t==="false"}d(P,"outputCondenseDisabled");export{D as condenseShellOutput,P as outputCondenseDisabled};
3
+ `);if(_<8||S.length>o.length*(1-.15))return;const p=[];return r>0&&p.push(`${r} passing test lines collapsed`),l>0&&p.push(`${l} duplicate warning lines removed`),c>0&&p.push(`${c} repeated lines collapsed`),{text:S,summary:p.join(", ")}}d(D,"condenseShellOutput");function P(o=process.env){const t=o.DAL_TOOL_OUTPUT_CONDENSE?.trim().toLowerCase();return t==="0"||t==="off"||t==="false"}d(P,"outputCondenseDisabled");export{g as ERROR_LINE,D as condenseShellOutput,P as outputCondenseDisabled};
@@ -2,12 +2,11 @@ import { type Static, Type } from "typebox";
2
2
  import type { BackgroundProcessInfo, BackgroundProcessManager } from "../background-processes.ts";
3
3
  import type { ToolDefinition } from "../extensions/types.ts";
4
4
  declare const processSchema: Type.TObject<{
5
- action: Type.TUnion<[Type.TLiteral<"start">, Type.TLiteral<"output">, Type.TLiteral<"status">, Type.TLiteral<"stop">, Type.TLiteral<"list">]>;
5
+ action: Type.TUnion<[Type.TLiteral<"start">, Type.TLiteral<"poll">, Type.TLiteral<"stdin">, Type.TLiteral<"kill">, Type.TLiteral<"list">]>;
6
6
  command: Type.TOptional<Type.TString>;
7
- name: Type.TOptional<Type.TString>;
8
7
  id: Type.TOptional<Type.TString>;
9
- tail: Type.TOptional<Type.TNumber>;
10
- wait_seconds: Type.TOptional<Type.TNumber>;
8
+ input: Type.TOptional<Type.TString>;
9
+ wait: Type.TOptional<Type.TNumber>;
11
10
  }>;
12
11
  export type ProcessToolInput = Static<typeof processSchema>;
13
12
  export interface ProcessToolDetails {
@@ -1,22 +1,22 @@
1
- var L=Object.defineProperty;var l=(t,e)=>L(t,"name",{value:e,configurable:!0});import{ToolExecutionError as _}from"@earendil-works/pi-agent-core";import{Text as $}from"@earendil-works/pi-tui";import{Type as n}from"typebox";import{theme as x}from"../../modes/interactive/theme/theme.js";import{describeDenialForModel as g}from"../sandbox/denial.js";import{sandboxEscalationSchema as E}from"./bash.js";import{getTextOutput as U}from"./render-utils.js";import{truncateTail as k}from"./truncate.js";const S=n.Object({action:n.Union([n.Literal("start"),n.Literal("output"),n.Literal("status"),n.Literal("stop"),n.Literal("list")],{description:'"start" a command; read its "output" (new output since the last read, or the last `tail` lines); "status" (running?, exit code, listening ports); "stop" it; "list" all.'}),command:n.Optional(n.String({description:'Shell command to start (action "start")'})),name:n.Optional(n.String({description:'Short label, e.g. "dev server" (action "start")'})),id:n.Optional(n.String({description:'Process id returned by "start" (output / status / stop)'})),tail:n.Optional(n.Number({description:'Return the last N lines instead of new output (action "output")'})),wait_seconds:n.Optional(n.Number({description:'Seconds to wait before reporting, so a starting server can print its URL (start / output; default 2 for "start", max 30)'}))}),P=n.Object({...S.properties,sandbox_escalation:E}),j=400,v=32*1024;function p(t){const e=[`${t.id}${t.name?` (${t.name})`:""}: ${t.state}`];t.pid&&e.push(`pid ${t.pid}`),t.state!=="running"&&t.exitCode!==void 0&&e.push(`exit code ${t.exitCode??"none"}`),t.signal&&e.push(`signal ${t.signal}`),t.ports.length>0&&e.push(`ports ${t.ports.join(", ")}`),t.urls.length>0&&e.push(`urls ${t.urls.join(" ")}`),t.sandboxed&&e.push("sandboxed");const i=[e.join(", "),`command: ${t.command}`,`log: ${t.logFile}`];return t.sandboxed&&!t.portsReachableFromHost&&t.ports.length>0&&i.push("note: on Linux the sandbox gives the process its own network namespace; these ports are not reachable from outside the sandbox."),i.join(`
2
- `)}l(p,"describe");function y(t,e){return new Promise(i=>{if(t<=0||e?.aborted)return i();const a=setTimeout(i,t);e?.addEventListener("abort",()=>{clearTimeout(a),i()},{once:!0})})}l(y,"sleep");function T(t,e){const i=typeof t=="number"&&Number.isFinite(t)&&t>=0?t:e;return Math.min(i,30)*1e3}l(T,"waitMs");function f(t){if(!t)return"(no new output)";const e=k(t,{maxLines:j,maxBytes:v});return e.truncated?`[showing the last ${e.outputLines} of ${e.totalLines} lines]
3
- ${e.content}`:e.content}l(f,"limitOutput");function G(t,e,i={}){return{name:"process",label:"process",description:'Run long-lived commands in the background \u2014 dev servers, watchers, anything that does not exit by itself \u2014 and check on them later. "start" returns an id right away; use "output" to read what it printed, "status" to see whether it runs and which ports it listens on, "stop" to end it. Use bash, not this, for commands that finish. Processes are stopped when the session ends.'+(i.sandboxed?" Processes run in the same OS sandbox as bash; they may listen on localhost, but outbound network follows the sandbox rules.":""),promptSnippet:"Start and manage background processes (dev servers, watchers)",promptGuidelines:['Start dev servers and watchers with the process tool (action "start"), not bash: bash waits for the command to finish and kills it at its timeout.'],parameters:i.sandboxed?P:S,async execute(a,s,m,h,d){const r=s.action;if(r==="list"){const o=e.list();return{content:[{type:"text",text:o.length>0?o.map(p).join(`
1
+ var _=Object.defineProperty;var m=(t,e)=>_(t,"name",{value:e,configurable:!0});import{ToolExecutionError as F}from"@earendil-works/pi-agent-core";import{Text as g}from"@earendil-works/pi-tui";import{Type as n}from"typebox";import{theme as w}from"../../modes/interactive/theme/theme.js";import{describeDenialForModel as S}from"../sandbox/denial.js";import{sandboxEscalationSchema as y}from"./bash.js";import{getTextOutput as k}from"./render-utils.js";import{SHELL_OUTPUT_MAX_CHARS as C,truncateHeadTail as U}from"./truncate.js";const T=n.Object({action:n.Union([n.Literal("start"),n.Literal("poll"),n.Literal("stdin"),n.Literal("kill"),n.Literal("list")],{description:'"start" a command in the background; "poll": new output and state; "stdin": send `input`; "kill"; "list"'}),command:n.Optional(n.String({description:'For "start"'})),id:n.Optional(n.String({description:'Process id (from bash or "start")'})),input:n.Optional(n.String({description:'For "stdin"; end with \\n to send a line'})),wait:n.Optional(n.Number({description:'Seconds to wait; "poll" returns early when it exits (default 30, max 300)'}))}),P=n.Object({...T.properties,sandbox_escalation:y}),j=30,D=300,E=2;function x(t){const e=[`${t.id}${t.name?` (${t.name})`:""}: ${t.state}`];t.pid&&e.push(`pid ${t.pid}`),t.state!=="running"&&t.exitCode!==void 0&&e.push(`exit code ${t.exitCode??"none"}`),t.signal&&e.push(`signal ${t.signal}`),t.ports.length>0&&e.push(`ports ${t.ports.join(", ")}`),t.urls.length>0&&e.push(`urls ${t.urls.join(" ")}`),t.sandboxed&&e.push("sandboxed");const o=[e.join(", "),`command: ${t.command}`,`log: ${t.logFile}`];return t.sandboxed&&!t.portsReachableFromHost&&t.ports.length>0&&o.push("note: on Linux the sandbox gives the process its own network namespace; these ports are not reachable from outside the sandbox."),o.join(`
2
+ `)}m(x,"describe");function O(t,e){return new Promise(o=>{if(t<=0||e?.aborted)return o();const d=setTimeout(o,t);e?.addEventListener("abort",()=>{clearTimeout(d),o()},{once:!0})})}m(O,"sleep");function $(t,e){const o=typeof t=="number"&&Number.isFinite(t)&&t>=0?t:e;return Math.min(o,D)*1e3}m($,"waitMs");function f(t,e){if(!t)return"(no new output)";const o=U(t,C);return o.truncated?`${o.content}
3
+ [Truncated; full output: ${e}]`:o.content}m(f,"limitOutput");function q(t,e,o={}){return{name:"process",label:"process",description:'Background processes: commands bash moved to the background at their timeout, or started here. "poll" waits for new output and returns it with the state (exit code, listening ports and URLs). Processes stop when the session ends.'+(o.sandboxed?' Under the sandbox only commands started here may listen on localhost: start dev servers with "start".':""),promptSnippet:"Poll, feed or stop background processes",parameters:o.sandboxed?P:T,async execute(d,i,u,h,l){const s=i.action;if(s==="list"){const r=e.list();return{content:[{type:"text",text:r.length>0?r.map(x).join(`
4
4
 
5
- `):"No background processes."}],details:{processes:o}}}if(r==="start"){const o=s.command?.trim();if(!o)throw new Error('action "start" needs a command');const b=await e.start({command:o,cwd:d?.cwd||t,...s.name?{name:s.name}:{},toolCallId:a,escalation:s.sandbox_escalation,ctx:d});await y(T(s.wait_seconds,2),m);const{text:w,info:c}=e.read(b.id);if(c.denial)throw new _(`${p(c)}
5
+ `):"No background processes."}],details:{processes:r}}}if(s==="start"){const r=i.command?.trim();if(!r)throw new Error('action "start" needs a command');const b=await e.start({command:r,cwd:l?.cwd||t,toolCallId:d,escalation:i.sandbox_escalation,ctx:l});await O($(i.wait,E),u);const{text:c,info:a}=e.read(b.id);if(a.denial)throw new F(`${x(a)}
6
6
 
7
- ${f(w)}
7
+ ${f(c,a.logFile)}
8
8
 
9
- ${g(c.denial)}`,{process:c});return{content:[{type:"text",text:`Started.
10
- ${p(c)}
9
+ ${S(a.denial)}`,{process:a});return{content:[{type:"text",text:`Started.
10
+ ${x(a)}
11
11
 
12
12
  Output so far:
13
- ${f(w)}`}],details:{process:c}}}const u=s.id?.trim();if(!u)throw new Error(`action "${r}" needs the id returned by "start"`);if(r==="output"){await y(T(s.wait_seconds,0),m);const o=typeof s.tail=="number"&&s.tail>0?Math.floor(s.tail):void 0,{text:b,truncated:w,info:c}=e.read(u,o!==void 0?{tail:o}:{}),O=w?`
14
- [earlier output is in ${c.logFile}]`:"";return{content:[{type:"text",text:`${p(c)}
13
+ ${f(c,a.logFile)}`}],details:{process:a}}}const p=i.id?.trim();if(!p)throw new Error(`action "${s}" needs the process id`);if(s==="poll"||s==="stdin"){if(s==="stdin"){if(typeof i.input!="string")throw new Error('action "stdin" needs input');e.write(p,i.input),await O($(i.wait,E),u)}else await e.waitForExit(p,$(i.wait,j),u);const{text:r,truncated:b}=e.read(p),c=e.status(p),a=b?`
14
+ [earlier output is in ${c.logFile}]`:"",L=c.denial?`
15
15
 
16
- ${f(b)}${O}`}],details:{process:c}}}if(r==="status"){const o=e.status(u),b=o.denial?`
16
+ ${S(c.denial)}`:"";return{content:[{type:"text",text:`${x(c)}
17
17
 
18
- ${g(o.denial)}`:"";return{content:[{type:"text",text:`${p(o)}${b}`}],details:{process:o}}}if(r==="stop"){const o=await e.stop(u);return{content:[{type:"text",text:`Stopped.
19
- ${p(o)}`}],details:{process:o}}}throw new Error(`Unknown action: ${String(r)}`)},renderCall(a,s,m){const h=m.lastComponent??new $("",0,0),d=a?.action??"\u2026",r=d==="start"?a?.name??a?.command??"":a?.id??"";return h.setText(`${x.fg("toolTitle",x.bold(`process ${d}`))} ${x.fg("dim",String(r))}`),h},renderResult(a,s,m,h){const d=h.lastComponent??new $("",0,0),r=U(a,!1).trim(),u=r.split(`
20
- `);return d.setText(s.expanded?`
21
- ${x.fg("toolOutput",r)}`:`
22
- ${x.fg("toolOutput",u[0]??"")}`),d}}}l(G,"createProcessToolDefinition");export{G as createProcessToolDefinition};
18
+ ${f(r,c.logFile)}${a}${L}`}],details:{process:c}}}if(s==="kill"){const r=await e.stop(p);return{content:[{type:"text",text:`Stopped.
19
+ ${x(r)}`}],details:{process:r}}}throw new Error(`Unknown action: ${String(s)}`)},renderCall(d,i,u){const h=u.lastComponent??new g("",0,0),l=d?.action??"\u2026",s=l==="start"?d?.command??"":d?.id??"";return h.setText(`${w.fg("toolTitle",w.bold(`process ${l}`))} ${w.fg("dim",String(s))}`),h},renderResult(d,i,u,h){const l=h.lastComponent??new g("",0,0),s=k(d,!1).trim(),p=s.split(`
20
+ `);return l.setText(i.expanded?`
21
+ ${w.fg("toolOutput",s)}`:`
22
+ ${w.fg("toolOutput",p[0]??"")}`),l}}}m(q,"createProcessToolDefinition");export{q as createProcessToolDefinition};