dal-code 1.0.33 → 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 (120) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/NOTICE +8 -0
  3. package/dist/core/agent-session.d.ts +5 -0
  4. package/dist/core/agent-session.js +8 -8
  5. package/dist/core/background-processes.d.ts +14 -1
  6. package/dist/core/background-processes.js +7 -6
  7. package/dist/core/bash-executor.js +1 -1
  8. package/dist/core/bug-report.js +4 -4
  9. package/dist/core/compaction/branch-summarization.js +2 -2
  10. package/dist/core/compaction/compaction.d.ts +4 -2
  11. package/dist/core/compaction/compaction.js +13 -13
  12. package/dist/core/compaction/index.d.ts +1 -0
  13. package/dist/core/compaction/index.js +1 -1
  14. package/dist/core/compaction/tool-output-pruning.d.ts +19 -0
  15. package/dist/core/compaction/tool-output-pruning.js +7 -0
  16. package/dist/core/compaction/utils.d.ts +1 -0
  17. package/dist/core/compaction/utils.js +9 -9
  18. package/dist/core/git-state.js +1 -0
  19. package/dist/core/model-config.d.ts +30 -0
  20. package/dist/core/model-config.js +2 -2
  21. package/dist/core/sandbox/denial.d.ts +1 -0
  22. package/dist/core/sandbox/denial.js +4 -3
  23. package/dist/core/sandbox/shell-sandbox.js +5 -5
  24. package/dist/core/settings-manager.d.ts +11 -2
  25. package/dist/core/settings-manager.js +1 -1
  26. package/dist/core/source-info.d.ts +1 -0
  27. package/dist/core/source-info.js +1 -1
  28. package/dist/core/system-prompt.d.ts +1 -0
  29. package/dist/core/system-prompt.js +12 -12
  30. package/dist/core/tools/bash.d.ts +7 -0
  31. package/dist/core/tools/bash.js +14 -16
  32. package/dist/core/tools/output-accumulator.js +2 -2
  33. package/dist/core/tools/output-condense.js +3 -0
  34. package/dist/core/tools/powershell.js +1 -1
  35. package/dist/core/tools/process.d.ts +3 -4
  36. package/dist/core/tools/process.js +15 -15
  37. package/dist/core/tools/truncate.d.ts +12 -0
  38. package/dist/core/tools/truncate.js +12 -5
  39. package/dist/dal/manifest.js +1 -1
  40. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  41. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  42. package/dist/node_modules/@dalcode/dal-gateway/src/index.js +1 -1
  43. package/dist/node_modules/@dalcode/dal-goal/LICENSE +45 -0
  44. package/dist/node_modules/@dalcode/dal-goal/package.json +35 -0
  45. package/dist/node_modules/@dalcode/dal-goal/src/core.js +10 -0
  46. package/dist/node_modules/@dalcode/dal-goal/src/index.js +7 -0
  47. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  48. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  49. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  50. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  51. package/dist/node_modules/@dalcode/dal-lsp/package.json +4 -3
  52. package/dist/node_modules/@dalcode/dal-lsp/src/checkers.js +4 -0
  53. package/dist/node_modules/@dalcode/dal-lsp/src/index.js +8 -6
  54. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  55. package/dist/node_modules/@dalcode/dal-mcp/src/index.js +18 -18
  56. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  57. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +3 -2
  58. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  59. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +3 -2
  60. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -2
  61. package/dist/node_modules/@dalcode/dal-plugins/src/brand.d.ts +17 -0
  62. package/dist/node_modules/@dalcode/dal-plugins/src/brand.js +1 -1
  63. package/dist/node_modules/@dalcode/dal-plugins/src/index.js +12 -8
  64. package/dist/node_modules/@dalcode/dal-plugins/src/manage.js +8 -8
  65. package/dist/node_modules/@dalcode/dal-plugins/src/market.js +4 -0
  66. package/dist/node_modules/@dalcode/dal-plugins/src/settings.js +1 -1
  67. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  68. package/dist/node_modules/@dalcode/dal-rewind/LICENSE +24 -0
  69. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  70. package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
  71. package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
  72. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  73. package/dist/node_modules/@dalcode/dal-skills/src/catalog.js +2 -2
  74. package/dist/node_modules/@dalcode/dal-skills/src/index.js +10 -10
  75. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  76. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +14 -16
  77. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  78. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  79. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  80. package/dist/node_modules/@dalcode/dal-tool-catalog/src/groups.js +1 -1
  81. package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -5
  82. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  83. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  84. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  85. package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
  86. package/dist/node_modules/@dalcode/deepailab/src/model-defaults.js +1 -1
  87. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  88. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  89. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.d.ts +2 -1
  90. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +5 -5
  91. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  92. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  93. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  94. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  95. package/dist/node_modules/@earendil-works/pi-ai/dist/types.d.ts +1 -0
  96. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  97. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  98. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  99. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  100. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  101. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  102. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  103. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  104. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  105. package/dist/sdk/index.d.ts +1 -0
  106. package/dist/sdk/index.js +1 -1
  107. package/dist/utils/clipboard-image.js +1 -1
  108. package/dist/utils/clipboard.js +1 -1
  109. package/dist/utils/output-files.js +1 -1
  110. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  111. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  112. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  113. package/examples/extensions/gondolin/package-lock.json +2 -2
  114. package/examples/extensions/gondolin/package.json +1 -1
  115. package/examples/extensions/sandbox/package-lock.json +2 -2
  116. package/examples/extensions/sandbox/package.json +1 -1
  117. package/examples/extensions/with-deps/package-lock.json +2 -2
  118. package/examples/extensions/with-deps/package.json +1 -1
  119. package/npm-shrinkwrap.json +2 -2
  120. package/package.json +1 -1
@@ -6,15 +6,18 @@ import type { SandboxSettings, SandboxSettingsSources } from "./sandbox/policy.t
6
6
  export interface CompactionModelOverride {
7
7
  reserveTokens?: number;
8
8
  keepRecentTokens?: number;
9
+ maxContextTokens?: number;
9
10
  }
11
+ export declare const DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS = 80000;
10
12
  export interface CompactionSettings {
11
13
  enabled?: boolean;
12
14
  reserveTokens?: number;
13
15
  keepRecentTokens?: number;
14
16
  modelOverrides?: Record<string, CompactionModelOverride>;
15
17
  maxContextTokens?: number;
18
+ summaryModel?: string;
19
+ pruneToolOutputs?: boolean;
16
20
  }
17
- export declare const DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS = 128000;
18
21
  export declare const DEFAULT_MAX_OUTPUT_TOKENS = 32000;
19
22
  export declare const DEFAULT_MAX_RETRIES = 5;
20
23
  export interface BranchSummarySettings {
@@ -251,8 +254,14 @@ export declare class SettingsManager {
251
254
  reserveTokens: number;
252
255
  keepRecentTokens: number;
253
256
  maxContextTokens: number;
257
+ pruneToolOutputs: boolean;
254
258
  };
255
- getCompactionMaxContextTokens(): number;
259
+ getCompactionMaxContextTokens(model?: Pick<Model<string>, "provider" | "id">): number;
260
+ getCompactionPruneToolOutputs(): boolean;
261
+ getCompactionSummaryModel(): {
262
+ provider: string;
263
+ modelId: string;
264
+ } | undefined;
256
265
  getBranchSummarySettings(): {
257
266
  reserveTokens: number;
258
267
  skipPrompt: boolean;
@@ -1 +1 @@
1
- var F=Object.defineProperty;var a=(r,e)=>F(r,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as L}from"@earendil-works/pi-ai";import{randomUUID as M}from"crypto";import{existsSync as y,mkdirSync as I,readFileSync as A,writeFileSync as O}from"fs";import{dirname as N,join as u}from"path";import D from"proper-lockfile";import{CONFIG_DIR_NAME as T,getAgentDir as R}from"../config.js";import{normalizePath as v,resolvePath as m}from"../utils/paths.js";import{stripBom as P}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as W,parseHttpIdleTimeoutMs as _}from"./http-dispatcher.js";const $={reserveTokens:16384,keepRecentTokens:2e4},U=128e3,B=32e3,H=5,q=["off","streaming","idle"];function p(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}a(p,"isMergeableObject");function j(r,e){const t={...r};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const n=r[s];t[s]=p(n)&&p(i)?j(n,i):i}return t}a(j,"deepMergeObjects");const V=["read","bash","edit","write"];function f(r){return typeof r=="string"&&(r.startsWith("+")||r.startsWith("-"))}a(f,"isToolModifier");function le(r){const e=r.filter(f);if(e.length===0)return;if(e.length<r.length)return"tool names cannot be mixed with +name or -name entries";const t=e.find(s=>s.includes("*"));if(t)return`+name and -name entries take exact tool names, not patterns: ${t}`}a(le,"getToolListError");function X(r,e){const t=[...r];for(const s of e){if(!f(s))continue;const i=s.slice(1),n=t.indexOf(i);s.startsWith("+")&&n===-1&&i?t.push(i):s.startsWith("-")&&n!==-1&&t.splice(n,1)}return t}a(X,"applyToolModifiers");function K(r,e){return e===void 0?r:!Array.isArray(r)||!Array.isArray(e)||!e.every(f)?e:[...r,...e]}a(K,"mergeDefaultTools");function Q(r){const e=r.filter(t=>!f(t));return X(e.length>0||r.length===0?e:V,r)}a(Q,"resolveDefaultTools");function h(r,e){const t=j(r,e),s=K(r.defaultTools,e.defaultTools);return s===void 0?t:{...t,defaultTools:s}}a(h,"deepMergeSettings");function C(r,e){const t=_(r);if(t!==void 0)return t;if(r!==void 0)throw new Error(`Invalid ${e} setting: ${String(r)}`)}a(C,"parseTimeoutSetting");function S(r,e,t){return{scope:r,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}a(S,"toSettingsError");class z{static{a(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=m(e),i=m(t);this.globalSettingsPath=u(i,"settings.json"),this.projectSettingsPath=u(s,T,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let n=1;n<=10;n++)try{return D.lockSync(e,{realpath:!1})}catch(o){if((typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0)!=="ELOCKED"||n===10)throw o;i=o;const g=Date.now();for(;Date.now()-g<20;);}throw i??new Error("Failed to acquire settings lock")}withLock(e,t){const s=e==="global"?this.globalSettingsPath:this.projectSettingsPath,i=N(s);let n;try{const o=y(s);o&&(n=this.acquireLockSyncWithRetry(s));const l=o?A(s,"utf-8"):void 0,g=t(l);g!==void 0&&(y(i)||I(i,{recursive:!0}),n||(n=this.acquireLockSyncWithRetry(s)),O(s,g,"utf-8"))}finally{n&&n()}}}class G{static{a(this,"InMemorySettingsStorage")}global;project;withLock(e,t){const s=e==="global"?this.global:this.project,i=t(s);i!==void 0&&(e==="global"?this.global=i:this.project=i)}}class d{static{a(this,"SettingsManager")}storage;globalSettings;projectSettings;settings;projectTrusted;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(e,t,s,i=null,n=null,o=[],l=!0,g={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=l,this.globalSettingsLoadError=i,this.projectSettingsLoadError=n,this.errors=[...o],this.settingsPaths=g,this.settings=h(this.globalSettings,this.projectSettings)}static create(e,t=R(),s={}){const i=m(e),n=m(t),o=new z(i,n);return d.fromStorageWithPaths(o,s,{global:u(n,"settings.json"),project:u(i,T,"settings.json")})}static fromStorage(e,t={}){return d.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,n=d.tryLoadFromStorage(e,"global"),o=d.tryLoadFromStorage(e,"project",i),l=[];return n.error&&l.push(S("global",n.error,s.global)),o.error&&l.push(S("project",o.error,s.project)),new d(e,n.settings,o.settings,n.error,o.error,l,i,s)}static inMemory(e={},t={}){const s=new G,i=d.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),d.fromStorage(s,t)}static loadFromStorage(e,t,s=!0){if(t==="project"&&!s)return{};let i;if(e.withLock(t,o=>{i=o}),!i)return{};const n=JSON.parse(P(i));return d.migrateSettings(n)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:d.loadFromStorage(e,t,s),error:null}}catch(i){return{settings:{},error:i}}}static migrateSettings(e){if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),!("transport"in e)&&typeof e.websockets=="boolean"&&(e.transport=e.websockets?"websocket":"sse",delete e.websockets),"skills"in e&&typeof e.skills=="object"&&e.skills!==null&&!Array.isArray(e.skills)){const t=e.skills;t.enableSkillCommands!==void 0&&e.enableSkillCommands===void 0&&(e.enableSkillCommands=t.enableSkillCommands),Array.isArray(t.customDirectories)&&t.customDirectories.length>0?e.skills=t.customDirectories:delete e.skills}if("retry"in e&&typeof e.retry=="object"&&e.retry!==null&&!Array.isArray(e.retry)){const t=e.retry,s=typeof t.provider=="object"&&t.provider!==null?t.provider:void 0;typeof t.maxDelayMs=="number"&&(s?.maxRetryDelayMs===void 0||s?.maxRetryDelayMs===null)&&(t.provider={...s??{},maxRetryDelayMs:t.maxDelayMs}),delete t.maxDelayMs}return e}getSettings(){return structuredClone(this.settings)}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}isProjectTrusted(){return this.projectTrusted}setProjectTrusted(e){if(this.projectTrusted===e)return;if(this.projectTrusted=e,this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear(),!e){this.projectSettings={},this.projectSettingsLoadError=null,this.settings=h(this.globalSettings,this.projectSettings);return}const t=d.tryLoadFromStorage(this.storage,"project",e);this.projectSettings=t.settings,this.projectSettingsLoadError=t.error,t.error&&this.recordError("project",t.error),this.settings=h(this.globalSettings,this.projectSettings)}async reload(){await this.writeQueue;const e=d.tryLoadFromStorage(this.storage,"global");e.error?(this.globalSettingsLoadError=e.error,this.recordError("global",e.error)):(this.globalSettings=e.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();const t=d.tryLoadFromStorage(this.storage,"project",this.projectTrusted);t.error?(this.projectSettingsLoadError=t.error,this.recordError("project",t.error)):(this.projectSettings=t.settings,this.projectSettingsLoadError=null),this.settings=h(this.globalSettings,this.projectSettings)}applyOverrides(e){this.settings=h(this.settings,e)}markModified(e,t){this.modifiedFields.add(e),t&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(t))}markProjectModified(e,t){this.modifiedProjectFields.add(e),t&&(this.modifiedProjectNestedFields.has(e)||this.modifiedProjectNestedFields.set(e,new Set),this.modifiedProjectNestedFields.get(e).add(t))}assertProjectTrustedForWrite(){if(!this.projectTrusted)throw new Error("Project is not trusted; refusing to write project settings")}recordError(e,t){this.errors.push(S(e,t,this.settingsPaths[e]))}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,t){this.writeQueue=this.writeQueue.then(()=>{e==="project"&&this.assertProjectTrustedForWrite(),t(),this.clearModifiedScope(e)}).catch(s=>{this.recordError(e,s)})}cloneModifiedNestedFields(e){const t=new Map;for(const[s,i]of e.entries())t.set(s,new Set(i));return t}persistScopedSettings(e,t,s,i){this.storage.withLock(e,n=>{const o=n?d.migrateSettings(JSON.parse(P(n))):{},l={...o};for(const g of s){const c=t[g];if(i.has(g)&&typeof c=="object"&&c!==null){const E=i.get(g),w=o[g]??{},x=c,b={...w};for(const k of E)b[k]=x[k];l[g]=b}else l[g]=c}return JSON.stringify(l,null,2)})}save(){if(this.settings=h(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;const e=structuredClone(this.globalSettings),t=new Set(this.modifiedFields),s=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",e,t,s)})}saveProjectSettings(e){if(this.assertProjectTrustedForWrite(),this.projectSettings=structuredClone(e),this.settings=h(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;const t=structuredClone(this.projectSettings),s=new Set(this.modifiedProjectFields),i=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",t,s,i)})}updateProjectSettings(e,t){this.assertProjectTrustedForWrite();const s=structuredClone(this.projectSettings);t(s),this.markProjectModified(e),this.saveProjectSettings(s)}async flush(){await this.writeQueue}drainErrors(){const e=[...this.errors];return this.errors=[],e}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getSessionDir(){const e=this.settings.sessionDir;return e&&v(e)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,t){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=t,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getThemeSetting(){const e=this.settings.theme;if(typeof e=="string")return e}getTheme(){const e=this.getThemeSetting();return e?.includes("/")?void 0:e}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(e,t){return this.settings.modelThinkingLevels?.[`${e}/${t}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(e,t,s){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${e}/${t}`]=s,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(e,t){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${e}/${t}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??"auto"}setTransport(e){this.globalSettings.transport=e,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionTokenSetting(e,t){const s=this.settings.compaction,i=s?.[e];if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<0))throw new Error(`Invalid compaction.${e} setting: ${String(i)}. Expected a non-negative safe integer.`);const n=t?`${t.provider}/${t.id}`:void 0,o=n!==void 0?s?.modelOverrides?.[n]:void 0;if(o!==void 0&&!p(o))throw new Error(`Invalid compaction.modelOverrides["${n}"] setting: ${String(o)}. Expected an object.`);const l=o?.[e];if(l!==void 0&&(typeof l!="number"||!Number.isSafeInteger(l)||l<0))throw new Error(`Invalid compaction.modelOverrides["${n}"].${e} setting: ${String(l)}. Expected a non-negative safe integer.`);return l??i??$[e]}getCompactionReserveTokens(e){return this.getCompactionTokenSetting("reserveTokens",e)}getCompactionKeepRecentTokens(e){return this.getCompactionTokenSetting("keepRecentTokens",e)}getCompactionSettings(e){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(e),keepRecentTokens:this.getCompactionKeepRecentTokens(e),maxContextTokens:this.getCompactionMaxContextTokens()}}getCompactionMaxContextTokens(){const e=this.settings.compaction?.maxContextTokens;if(e===void 0)return U;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid compaction.maxContextTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??H,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??L}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return B;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid maxOutputTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getOutputTokenLimit(e){const t=this.getMaxOutputTokens();return t>0&&(e<=0||e>t)?t:e}getHttpIdleTimeoutMs(){return C(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??W}setHttpIdleTimeoutMs(e){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(e),this.markModified("httpIdleTimeoutMs"),this.save()}getCacheWarmingMode(){const e=this.globalSettings.cacheWarming;return e!==void 0&&q.includes(e)?e:"streaming"}setCacheWarmingMode(e){this.globalSettings.cacheWarming=e,this.markModified("cacheWarming"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getWebSocketConnectTimeoutMs(){return C(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!0}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??!1}getExternalEditorCommand(){const e=this.settings.externalEditor;if(typeof e=="string"&&e.trim()!=="")return e;const t=process.env.VISUAL||process.env.EDITOR;return t||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(e){this.globalSettings.showCacheMissNotices=e,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){const e=this.settings.shellPath;return e&&v(e)}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){const e=this.settings.quietStartup;return e===!1?!1:e==="header"?e:!0}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getDefaultProjectTrust(){const e=this.globalSettings.defaultProjectTrust;return e==="always"||e==="never"?e:"ask"}setDefaultProjectTrust(e){this.globalSettings.defaultProjectTrust=e,this.markModified("defaultProjectTrust"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}getShellEnvironmentPolicy(){const e=this.globalSettings.shellEnvironment??{},t=[...e.exclude??[],...this.projectSettings.shellEnvironment?.exclude??[]];return{...e.inherit!==void 0?{inherit:e.inherit}:{},...t.length>0?{exclude:t}:{},...e.include!==void 0?{include:[...e.include]}:{},...e.set!==void 0?{set:{...e.set}}:{}}}getPermissionRuleSources(){return{...this.globalSettings.permissions?{user:structuredClone(this.globalSettings.permissions)}:{},...this.projectSettings.permissions?{project:structuredClone(this.projectSettings.permissions)}:{}}}getSandboxSettingsSources(){return{...this.globalSettings.sandbox?{global:structuredClone(this.globalSettings.sandbox)}:{},...this.projectSettings.sandbox?{project:structuredClone(this.projectSettings.sandbox)}:{}}}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(e){this.globalSettings.npmCommand=e?[...e]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!0}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??!0}setEnableInstallTelemetry(e){this.globalSettings.enableInstallTelemetry=e,this.markModified("enableInstallTelemetry"),this.save()}getEnableAnalytics(){return this.settings.enableAnalytics??!1}getTrackingId(){return this.settings.trackingId}setEnableAnalytics(e){this.globalSettings.enableAnalytics=e,this.markModified("enableAnalytics"),e&&!this.globalSettings.trackingId&&(this.globalSettings.trackingId=M(),this.markModified("trackingId")),this.save()}getOrCreateDeviceId(){return this.globalSettings.deviceId||(this.globalSettings.deviceId=M(),this.markModified("deviceId"),this.save()),this.globalSettings.deviceId}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){this.updateProjectSettings("packages",t=>{t.packages=e})}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){this.updateProjectSettings("extensions",t=>{t.extensions=e})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){this.updateProjectSettings("skills",t=>{t.skills=e})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){this.updateProjectSettings("prompts",t=>{t.prompts=e})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){this.updateProjectSettings("themes",t=>{t.themes=e})}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getFactoryEnabled(){return this.settings.factoryEnabled??!0}setFactoryEnabled(e){this.globalSettings.factoryEnabled=e,this.markModified("factoryEnabled"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){const e=this.settings.terminal,t=e?.images;return{...t==="kitty"||t==="iterm2"?{images:t}:t===!1?{images:null}:{},...typeof e?.trueColor=="boolean"?{trueColor:e.trueColor}:{},...typeof e?.hyperlinks=="boolean"?{hyperlinks:e.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){const e=this.settings.terminal?.imageWidthCells;return typeof e!="number"||!Number.isFinite(e)?60:Math.max(1,Math.floor(e))}setImageWidthCells(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(e)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:process.env.PI_CLEAR_ON_SHRINK==="1"}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=e,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":(this.settings.tuiMode==="regular"||this.settings.tuiMode,"regular")}setTuiMode(e){this.globalSettings.tuiMode=e,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":"transcript"}setFullscreenExitOutput(e){this.globalSettings.fullscreenExitOutput=e,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){const e=this.settings.fullscreenScrollbar;return e==="always"||e==="hidden"?e:"auto"}setFullscreenScrollbar(e){this.globalSettings.fullscreenScrollbar=e,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??!0}setFullscreenCopyOnSelect(e){this.globalSettings.fullscreenCopyOnSelect=e,this.markModified("fullscreenCopyOnSelect"),this.save()}getFullscreenWheelScrollLines(){const e=this.settings.fullscreenWheelScrollLines;return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.min(100,Math.floor(e))):"auto"}setFullscreenWheelScrollLines(e){this.globalSettings.fullscreenWheelScrollLines=e==="auto"?e:Math.max(1,Math.min(100,Math.floor(e))),this.markModified("fullscreenWheelScrollLines"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){const e=this.settings.defaultTools;if(e!==void 0)return Q(Array.isArray(e)?e.filter(t=>typeof t=="string"):[])}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){const e=this.settings.treeFilterMode;return e&&["default","no-tools","user-only","labeled-only","all"].includes(e)?e:"default"}setTreeFilterMode(e){this.globalSettings.treeFilterMode=e,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??process.env.PI_HARDWARE_CURSOR==="1"}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??1}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===1?1:0}setOutputPad(e){this.globalSettings.outputPad=e,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getMermaidRenderingMode(){const e=this.settings.markdown?.mermaid;return e==="off"||e==="final"?e:"streaming"}setMermaidRenderingMode(e){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=e,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(e){this.globalSettings.warnings={...e},this.markModified("warnings"),this.save()}}export{q as CACHE_WARMING_MODES,U as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,B as DEFAULT_MAX_OUTPUT_TOKENS,H as DEFAULT_MAX_RETRIES,V as DEFAULT_TOOL_NAMES,z as FileSettingsStorage,G as InMemorySettingsStorage,d as SettingsManager,X as applyToolModifiers,le as getToolListError,f as isToolModifier};
1
+ var F=Object.defineProperty;var a=(r,e)=>F(r,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as L}from"@earendil-works/pi-ai";import{randomUUID as M}from"crypto";import{existsSync as T,mkdirSync as I,readFileSync as O,writeFileSync as A}from"fs";import{dirname as D,join as u}from"path";import N from"proper-lockfile";import{CONFIG_DIR_NAME as y,getAgentDir as R}from"../config.js";import{normalizePath as v,resolvePath as m}from"../utils/paths.js";import{stripBom as P}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as W,parseHttpIdleTimeoutMs as $}from"./http-dispatcher.js";const _=8e4,U={reserveTokens:16384,keepRecentTokens:2e4,maxContextTokens:_},B=32e3,H=5,q=["off","streaming","idle"];function p(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}a(p,"isMergeableObject");function j(r,e){const t={...r};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const o=r[s];t[s]=p(o)&&p(i)?j(o,i):i}return t}a(j,"deepMergeObjects");const V=["read","bash","edit","write"];function f(r){return typeof r=="string"&&(r.startsWith("+")||r.startsWith("-"))}a(f,"isToolModifier");function le(r){const e=r.filter(f);if(e.length===0)return;if(e.length<r.length)return"tool names cannot be mixed with +name or -name entries";const t=e.find(s=>s.includes("*"));if(t)return`+name and -name entries take exact tool names, not patterns: ${t}`}a(le,"getToolListError");function X(r,e){const t=[...r];for(const s of e){if(!f(s))continue;const i=s.slice(1),o=t.indexOf(i);s.startsWith("+")&&o===-1&&i?t.push(i):s.startsWith("-")&&o!==-1&&t.splice(o,1)}return t}a(X,"applyToolModifiers");function K(r,e){return e===void 0?r:!Array.isArray(r)||!Array.isArray(e)||!e.every(f)?e:[...r,...e]}a(K,"mergeDefaultTools");function Q(r){const e=r.filter(t=>!f(t));return X(e.length>0||r.length===0?e:V,r)}a(Q,"resolveDefaultTools");function h(r,e){const t=j(r,e),s=K(r.defaultTools,e.defaultTools);return s===void 0?t:{...t,defaultTools:s}}a(h,"deepMergeSettings");function C(r,e){const t=$(r);if(t!==void 0)return t;if(r!==void 0)throw new Error(`Invalid ${e} setting: ${String(r)}`)}a(C,"parseTimeoutSetting");function S(r,e,t){return{scope:r,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}a(S,"toSettingsError");class z{static{a(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=m(e),i=m(t);this.globalSettingsPath=u(i,"settings.json"),this.projectSettingsPath=u(s,y,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let o=1;o<=10;o++)try{return N.lockSync(e,{realpath:!1})}catch(n){if((typeof n=="object"&&n!==null&&"code"in n?String(n.code):void 0)!=="ELOCKED"||o===10)throw n;i=n;const g=Date.now();for(;Date.now()-g<20;);}throw i??new Error("Failed to acquire settings lock")}withLock(e,t){const s=e==="global"?this.globalSettingsPath:this.projectSettingsPath,i=D(s);let o;try{const n=T(s);n&&(o=this.acquireLockSyncWithRetry(s));const l=n?O(s,"utf-8"):void 0,g=t(l);g!==void 0&&(T(i)||I(i,{recursive:!0}),o||(o=this.acquireLockSyncWithRetry(s)),A(s,g,"utf-8"))}finally{o&&o()}}}class G{static{a(this,"InMemorySettingsStorage")}global;project;withLock(e,t){const s=e==="global"?this.global:this.project,i=t(s);i!==void 0&&(e==="global"?this.global=i:this.project=i)}}class d{static{a(this,"SettingsManager")}storage;globalSettings;projectSettings;settings;projectTrusted;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(e,t,s,i=null,o=null,n=[],l=!0,g={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=l,this.globalSettingsLoadError=i,this.projectSettingsLoadError=o,this.errors=[...n],this.settingsPaths=g,this.settings=h(this.globalSettings,this.projectSettings)}static create(e,t=R(),s={}){const i=m(e),o=m(t),n=new z(i,o);return d.fromStorageWithPaths(n,s,{global:u(o,"settings.json"),project:u(i,y,"settings.json")})}static fromStorage(e,t={}){return d.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,o=d.tryLoadFromStorage(e,"global"),n=d.tryLoadFromStorage(e,"project",i),l=[];return o.error&&l.push(S("global",o.error,s.global)),n.error&&l.push(S("project",n.error,s.project)),new d(e,o.settings,n.settings,o.error,n.error,l,i,s)}static inMemory(e={},t={}){const s=new G,i=d.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),d.fromStorage(s,t)}static loadFromStorage(e,t,s=!0){if(t==="project"&&!s)return{};let i;if(e.withLock(t,n=>{i=n}),!i)return{};const o=JSON.parse(P(i));return d.migrateSettings(o)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:d.loadFromStorage(e,t,s),error:null}}catch(i){return{settings:{},error:i}}}static migrateSettings(e){if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),!("transport"in e)&&typeof e.websockets=="boolean"&&(e.transport=e.websockets?"websocket":"sse",delete e.websockets),"skills"in e&&typeof e.skills=="object"&&e.skills!==null&&!Array.isArray(e.skills)){const t=e.skills;t.enableSkillCommands!==void 0&&e.enableSkillCommands===void 0&&(e.enableSkillCommands=t.enableSkillCommands),Array.isArray(t.customDirectories)&&t.customDirectories.length>0?e.skills=t.customDirectories:delete e.skills}if("retry"in e&&typeof e.retry=="object"&&e.retry!==null&&!Array.isArray(e.retry)){const t=e.retry,s=typeof t.provider=="object"&&t.provider!==null?t.provider:void 0;typeof t.maxDelayMs=="number"&&(s?.maxRetryDelayMs===void 0||s?.maxRetryDelayMs===null)&&(t.provider={...s??{},maxRetryDelayMs:t.maxDelayMs}),delete t.maxDelayMs}return e}getSettings(){return structuredClone(this.settings)}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}isProjectTrusted(){return this.projectTrusted}setProjectTrusted(e){if(this.projectTrusted===e)return;if(this.projectTrusted=e,this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear(),!e){this.projectSettings={},this.projectSettingsLoadError=null,this.settings=h(this.globalSettings,this.projectSettings);return}const t=d.tryLoadFromStorage(this.storage,"project",e);this.projectSettings=t.settings,this.projectSettingsLoadError=t.error,t.error&&this.recordError("project",t.error),this.settings=h(this.globalSettings,this.projectSettings)}async reload(){await this.writeQueue;const e=d.tryLoadFromStorage(this.storage,"global");e.error?(this.globalSettingsLoadError=e.error,this.recordError("global",e.error)):(this.globalSettings=e.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();const t=d.tryLoadFromStorage(this.storage,"project",this.projectTrusted);t.error?(this.projectSettingsLoadError=t.error,this.recordError("project",t.error)):(this.projectSettings=t.settings,this.projectSettingsLoadError=null),this.settings=h(this.globalSettings,this.projectSettings)}applyOverrides(e){this.settings=h(this.settings,e)}markModified(e,t){this.modifiedFields.add(e),t&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(t))}markProjectModified(e,t){this.modifiedProjectFields.add(e),t&&(this.modifiedProjectNestedFields.has(e)||this.modifiedProjectNestedFields.set(e,new Set),this.modifiedProjectNestedFields.get(e).add(t))}assertProjectTrustedForWrite(){if(!this.projectTrusted)throw new Error("Project is not trusted; refusing to write project settings")}recordError(e,t){this.errors.push(S(e,t,this.settingsPaths[e]))}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,t){this.writeQueue=this.writeQueue.then(()=>{e==="project"&&this.assertProjectTrustedForWrite(),t(),this.clearModifiedScope(e)}).catch(s=>{this.recordError(e,s)})}cloneModifiedNestedFields(e){const t=new Map;for(const[s,i]of e.entries())t.set(s,new Set(i));return t}persistScopedSettings(e,t,s,i){this.storage.withLock(e,o=>{const n=o?d.migrateSettings(JSON.parse(P(o))):{},l={...n};for(const g of s){const c=t[g];if(i.has(g)&&typeof c=="object"&&c!==null){const E=i.get(g),w=n[g]??{},x=c,b={...w};for(const k of E)b[k]=x[k];l[g]=b}else l[g]=c}return JSON.stringify(l,null,2)})}save(){if(this.settings=h(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;const e=structuredClone(this.globalSettings),t=new Set(this.modifiedFields),s=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",e,t,s)})}saveProjectSettings(e){if(this.assertProjectTrustedForWrite(),this.projectSettings=structuredClone(e),this.settings=h(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;const t=structuredClone(this.projectSettings),s=new Set(this.modifiedProjectFields),i=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",t,s,i)})}updateProjectSettings(e,t){this.assertProjectTrustedForWrite();const s=structuredClone(this.projectSettings);t(s),this.markProjectModified(e),this.saveProjectSettings(s)}async flush(){await this.writeQueue}drainErrors(){const e=[...this.errors];return this.errors=[],e}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getSessionDir(){const e=this.settings.sessionDir;return e&&v(e)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,t){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=t,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getThemeSetting(){const e=this.settings.theme;if(typeof e=="string")return e}getTheme(){const e=this.getThemeSetting();return e?.includes("/")?void 0:e}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(e,t){return this.settings.modelThinkingLevels?.[`${e}/${t}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(e,t,s){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${e}/${t}`]=s,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(e,t){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${e}/${t}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??"auto"}setTransport(e){this.globalSettings.transport=e,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionTokenSetting(e,t){const s=this.settings.compaction,i=s?.[e];if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<0))throw new Error(`Invalid compaction.${e} setting: ${String(i)}. Expected a non-negative safe integer.`);const o=t?`${t.provider}/${t.id}`:void 0,n=o!==void 0?s?.modelOverrides?.[o]:void 0;if(n!==void 0&&!p(n))throw new Error(`Invalid compaction.modelOverrides["${o}"] setting: ${String(n)}. Expected an object.`);const l=n?.[e];if(l!==void 0&&(typeof l!="number"||!Number.isSafeInteger(l)||l<0))throw new Error(`Invalid compaction.modelOverrides["${o}"].${e} setting: ${String(l)}. Expected a non-negative safe integer.`);return l??i??U[e]}getCompactionReserveTokens(e){return this.getCompactionTokenSetting("reserveTokens",e)}getCompactionKeepRecentTokens(e){return this.getCompactionTokenSetting("keepRecentTokens",e)}getCompactionSettings(e){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(e),keepRecentTokens:this.getCompactionKeepRecentTokens(e),maxContextTokens:this.getCompactionMaxContextTokens(e),pruneToolOutputs:this.getCompactionPruneToolOutputs()}}getCompactionMaxContextTokens(e){return this.getCompactionTokenSetting("maxContextTokens",e)}getCompactionPruneToolOutputs(){const e=this.settings.compaction?.pruneToolOutputs;if(e!==void 0&&typeof e!="boolean")throw new Error(`Invalid compaction.pruneToolOutputs setting: ${String(e)}. Expected a boolean.`);return e??!0}getCompactionSummaryModel(){const e=this.settings.compaction?.summaryModel;if(e===void 0||e==="")return;const t=typeof e=="string"?e.indexOf("/"):-1;if(typeof e!="string"||t<=0||t===e.length-1)throw new Error(`Invalid compaction.summaryModel setting: ${String(e)}. Expected "provider/modelId".`);return{provider:e.slice(0,t),modelId:e.slice(t+1)}}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??H,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??L}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return B;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid maxOutputTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getOutputTokenLimit(e){const t=this.getMaxOutputTokens();return t>0&&(e<=0||e>t)?t:e}getHttpIdleTimeoutMs(){return C(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??W}setHttpIdleTimeoutMs(e){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(e),this.markModified("httpIdleTimeoutMs"),this.save()}getCacheWarmingMode(){const e=this.globalSettings.cacheWarming;return e!==void 0&&q.includes(e)?e:"streaming"}setCacheWarmingMode(e){this.globalSettings.cacheWarming=e,this.markModified("cacheWarming"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getWebSocketConnectTimeoutMs(){return C(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!0}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??!1}getExternalEditorCommand(){const e=this.settings.externalEditor;if(typeof e=="string"&&e.trim()!=="")return e;const t=process.env.VISUAL||process.env.EDITOR;return t||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(e){this.globalSettings.showCacheMissNotices=e,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){const e=this.settings.shellPath;return e&&v(e)}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){const e=this.settings.quietStartup;return e===!1?!1:e==="header"?e:!0}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getDefaultProjectTrust(){const e=this.globalSettings.defaultProjectTrust;return e==="always"||e==="never"?e:"ask"}setDefaultProjectTrust(e){this.globalSettings.defaultProjectTrust=e,this.markModified("defaultProjectTrust"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}getShellEnvironmentPolicy(){const e=this.globalSettings.shellEnvironment??{},t=[...e.exclude??[],...this.projectSettings.shellEnvironment?.exclude??[]];return{...e.inherit!==void 0?{inherit:e.inherit}:{},...t.length>0?{exclude:t}:{},...e.include!==void 0?{include:[...e.include]}:{},...e.set!==void 0?{set:{...e.set}}:{}}}getPermissionRuleSources(){return{...this.globalSettings.permissions?{user:structuredClone(this.globalSettings.permissions)}:{},...this.projectSettings.permissions?{project:structuredClone(this.projectSettings.permissions)}:{}}}getSandboxSettingsSources(){return{...this.globalSettings.sandbox?{global:structuredClone(this.globalSettings.sandbox)}:{},...this.projectSettings.sandbox?{project:structuredClone(this.projectSettings.sandbox)}:{}}}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(e){this.globalSettings.npmCommand=e?[...e]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!0}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??!0}setEnableInstallTelemetry(e){this.globalSettings.enableInstallTelemetry=e,this.markModified("enableInstallTelemetry"),this.save()}getEnableAnalytics(){return this.settings.enableAnalytics??!1}getTrackingId(){return this.settings.trackingId}setEnableAnalytics(e){this.globalSettings.enableAnalytics=e,this.markModified("enableAnalytics"),e&&!this.globalSettings.trackingId&&(this.globalSettings.trackingId=M(),this.markModified("trackingId")),this.save()}getOrCreateDeviceId(){return this.globalSettings.deviceId||(this.globalSettings.deviceId=M(),this.markModified("deviceId"),this.save()),this.globalSettings.deviceId}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){this.updateProjectSettings("packages",t=>{t.packages=e})}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){this.updateProjectSettings("extensions",t=>{t.extensions=e})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){this.updateProjectSettings("skills",t=>{t.skills=e})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){this.updateProjectSettings("prompts",t=>{t.prompts=e})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){this.updateProjectSettings("themes",t=>{t.themes=e})}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getFactoryEnabled(){return this.settings.factoryEnabled??!0}setFactoryEnabled(e){this.globalSettings.factoryEnabled=e,this.markModified("factoryEnabled"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){const e=this.settings.terminal,t=e?.images;return{...t==="kitty"||t==="iterm2"?{images:t}:t===!1?{images:null}:{},...typeof e?.trueColor=="boolean"?{trueColor:e.trueColor}:{},...typeof e?.hyperlinks=="boolean"?{hyperlinks:e.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){const e=this.settings.terminal?.imageWidthCells;return typeof e!="number"||!Number.isFinite(e)?60:Math.max(1,Math.floor(e))}setImageWidthCells(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(e)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:process.env.PI_CLEAR_ON_SHRINK==="1"}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=e,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":(this.settings.tuiMode==="regular"||this.settings.tuiMode,"regular")}setTuiMode(e){this.globalSettings.tuiMode=e,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":"transcript"}setFullscreenExitOutput(e){this.globalSettings.fullscreenExitOutput=e,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){const e=this.settings.fullscreenScrollbar;return e==="always"||e==="hidden"?e:"auto"}setFullscreenScrollbar(e){this.globalSettings.fullscreenScrollbar=e,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??!0}setFullscreenCopyOnSelect(e){this.globalSettings.fullscreenCopyOnSelect=e,this.markModified("fullscreenCopyOnSelect"),this.save()}getFullscreenWheelScrollLines(){const e=this.settings.fullscreenWheelScrollLines;return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.min(100,Math.floor(e))):"auto"}setFullscreenWheelScrollLines(e){this.globalSettings.fullscreenWheelScrollLines=e==="auto"?e:Math.max(1,Math.min(100,Math.floor(e))),this.markModified("fullscreenWheelScrollLines"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){const e=this.settings.defaultTools;if(e!==void 0)return Q(Array.isArray(e)?e.filter(t=>typeof t=="string"):[])}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){const e=this.settings.treeFilterMode;return e&&["default","no-tools","user-only","labeled-only","all"].includes(e)?e:"default"}setTreeFilterMode(e){this.globalSettings.treeFilterMode=e,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??process.env.PI_HARDWARE_CURSOR==="1"}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??1}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===1?1:0}setOutputPad(e){this.globalSettings.outputPad=e,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getMermaidRenderingMode(){const e=this.settings.markdown?.mermaid;return e==="off"||e==="final"?e:"streaming"}setMermaidRenderingMode(e){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=e,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(e){this.globalSettings.warnings={...e},this.markModified("warnings"),this.save()}}export{q as CACHE_WARMING_MODES,_ as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,B as DEFAULT_MAX_OUTPUT_TOKENS,H as DEFAULT_MAX_RETRIES,V as DEFAULT_TOOL_NAMES,z as FileSettingsStorage,G as InMemorySettingsStorage,d as SettingsManager,X as applyToolModifiers,le as getToolListError,f as isToolModifier};
@@ -7,6 +7,7 @@ export interface SourceInfo {
7
7
  scope: SourceScope;
8
8
  origin: SourceOrigin;
9
9
  baseDir?: string;
10
+ packageName?: string;
10
11
  }
11
12
  export declare const BUILTIN_PATH_PREFIX = "builtin:";
12
13
  export declare function getSyntheticPathSource(path: string): string | undefined;
@@ -1 +1 @@
1
- var n=Object.defineProperty;var t=(r,e)=>n(r,"name",{value:e,configurable:!0});const i="builtin:";function c(r){if(r.startsWith(i))return"builtin";if(r.startsWith("<")&&r.endsWith(">"))return r.slice(1,-1).split(":")[0]||"temporary"}t(c,"getSyntheticPathSource");function s(r){return r.startsWith(i)||r.startsWith("<")}t(s,"isSyntheticPath");function u(r,e){return{path:r,source:e.source,scope:e.scope,origin:e.origin,baseDir:e.baseDir}}t(u,"createSourceInfo");function f(r,e){return{path:r,source:e.source,scope:e.scope??"temporary",origin:e.origin??"top-level",baseDir:e.baseDir}}t(f,"createSyntheticSourceInfo");export{i as BUILTIN_PATH_PREFIX,u as createSourceInfo,f as createSyntheticSourceInfo,c as getSyntheticPathSource,s as isSyntheticPath};
1
+ var o=Object.defineProperty;var n=(e,r)=>o(e,"name",{value:r,configurable:!0});import{readFileSync as s}from"node:fs";import{join as u}from"node:path";const c="builtin:";function h(e){if(e.startsWith(c))return"builtin";if(e.startsWith("<")&&e.endsWith(">"))return e.slice(1,-1).split(":")[0]||"temporary"}n(h,"getSyntheticPathSource");function l(e){return e.startsWith(c)||e.startsWith("<")}n(l,"isSyntheticPath");const i=new Map;function a(e){if(!i.has(e)){let r;try{const t=JSON.parse(s(u(e,"package.json"),"utf8"));r=typeof t.name=="string"?t.name:void 0}catch{r=void 0}i.set(e,r)}return i.get(e)}n(a,"packageNameAt");function y(e,r){const t=r.packageRoot?a(r.packageRoot):void 0;return{path:e,source:r.source,scope:r.scope,origin:r.origin,baseDir:r.baseDir,...t?{packageName:t}:{}}}n(y,"createSourceInfo");function S(e,r){return{path:e,source:r.source,scope:r.scope??"temporary",origin:r.origin??"top-level",baseDir:r.baseDir}}n(S,"createSyntheticSourceInfo");export{c as BUILTIN_PATH_PREFIX,y as createSourceInfo,S as createSyntheticSourceInfo,h as getSyntheticPathSource,l as isSyntheticPath};
@@ -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,21 +1,19 @@
1
- var pe=Object.defineProperty;var u=(t,e)=>pe(t,"name",{value:e,configurable:!0});import{constants as fe}from"node:fs";import{access as he}from"node:fs/promises";import{constants as Se}from"node:os";import{ToolExecutionError as we}from"@earendil-works/pi-agent-core";import{Container as be,Text as M,truncateToWidth as xe}from"@earendil-works/pi-tui";import{spawn as Ee}from"child_process";import{Type as m}from"typebox";import{fill as v,t as O}from"../../dal/i18n.js";import{keyHint as Oe}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as _e}from"../../modes/interactive/components/visual-truncate.js";import{theme as b}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as $e}from"../../utils/child-process.js";import{getShellConfig as Q,getShellEnv as Z,killProcessTree as ee,trackDetachedChildPid as Le,untrackDetachedChildPid as ye}from"../../utils/shell.js";import{describeDenialForModel as Te}from"../sandbox/denial.js";import{getProcessShellSandbox as Pe}from"../sandbox/shell-sandbox.js";import{isReadOnlyBashCommand as ge}from"./bash-read-only.js";import{OutputAccumulator as Ce}from"./output-accumulator.js";import{countOutputLines as ve,formatCollapsedSummary as Ie,getTextOutput as te,invalidArgText as De,str as ne,truncateDisplay as Ae}from"./render-utils.js";import{wrapToolDefinition as Me}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as j,DEFAULT_MAX_LINES as Ne,formatSize as k}from"./truncate.js";const oe=2147483647,Fe=1024*1024,ke=oe/1e3,ie=12e4;function Re(t){if(t===void 0)return ie;if(!Number.isFinite(t)||t<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const e=t*1e3;if(e>oe)throw new Error(`Invalid timeout: maximum is ${ke} seconds`);return e}u(Re,"resolveTimeoutMs");const se=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."}))}),Be=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."})),Ue=m.Object({...se.properties,sandbox_escalation:Be}),re={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect DAL_* environment variables for current model and session details."]},Ge=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 je(t,e){return{exec:u(async(o,s,{onData:c,signal:a,timeout:E,env:h})=>{const l=Re(E);if(a?.aborted)throw new Error("aborted");const x=e();try{await he(s,fe.F_OK)}catch{throw new Error(`Working directory does not exist: ${s}
2
- Cannot execute ${t} commands.`)}const p=x.commandTransport==="stdin",r=Ee(x.shell,p?x.args:[...x.args,o],{cwd:s,detached:process.platform!=="win32",env:h??Z(),stdio:[p?"pipe":"ignore","pipe","pipe"],windowsHide:!0});p&&(r.stdin?.on("error",()=>{}),r.stdin?.end(o)),r.pid&&Le(r.pid);let S=!1,n;const i=u(()=>{r.pid&&ee(r.pid)},"onAbort");try{l!==void 0&&(n=setTimeout(()=>{S=!0,r.pid&&ee(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 $e(r);if(a?.aborted)throw new Error("aborted");if(S)throw new Error(`timeout:${(l??ie)/1e3}`);const y=r.signalCode;return{exitCode:f??(y?128+(Se.signals[y]??0):1)}}finally{r.pid&&ye(r.pid),n&&clearTimeout(n),a&&a.removeEventListener("abort",i)}},"exec")}}u(je,"createLocalShellOperations");function Ve(t){return je("bash",()=>Q(t?.shellPath))}u(Ve,"createLocalBashOperations");const V=new Set;function Lt(t){return V.add(t),()=>{V.delete(t)}}u(Lt,"registerShellExecutionGuard");async function We(t){for(const e of V){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(We,"shellExecutionRefusal");const He=["SESSION_ID","SESSION_FILE","PROVIDER","MODEL","REASONING_LEVEL"];function Xe(t,e,o,s,c){const a={...Z()};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 He){delete a[`DAL_${h}`];const l=a[`PI_${h}`];l!==void 0&&(a[`DAL_${h}`]=l)}const E={command:t,cwd:e,env:a};return o?o(E):E}u(Xe,"resolveSpawnContext");const Ke=5,Ye=100;class ze extends be{static{u(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function qe(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(qe,"formatDuration");function Je(t,e,o=!1){const s=ne(t?.command),c=ne(t?.description)?.trim(),a=t?.timeout,E=a?b.fg("muted",v(O(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:a})):"";if(c){const l=b.fg("toolTitle",b.bold(c))+E;return!o||!s?l:`${l}
3
- ${b.fg("muted",` \u23BF ${e} ${s.trim()}`)}`}const h=s===null?De(b):s?b.fg("dim",Ae(s.replace(/\s+/g," ").trim(),42)):b.fg("dim","\u2026");return`${b.fg("toolTitle",b.bold(e))} ${h}${E}`}u(Je,"formatShellCall");function Qe(t,e,o,s,c,a,E,h){const l=t.state;t.clear();const x=Ze(o,c,a,h);if(!o.expanded&&!E){const n=te(e,s),i=ve(n),f=[];i>0&&f.push(v(O("{count} \u884C"),{count:i})),x&&f.push(x);const y=Ie(b,f);y&&t.addChild(new M(y,0,0));return}let p=te(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=>b.fg("toolOutput",i)).join(`
7
- `);o.expanded?t.addChild(new M(`
8
- ${n}`,0,0)):t.addChild({render:u(i=>{if(l.cachedLines===void 0||l.cachedWidth!==i){const f=_e(n,Ke,i);l.cachedLines=f.visualLines,l.cachedSkipped=f.skippedCount,l.cachedWidth=i}if(l.cachedSkipped&&l.cachedSkipped>0){const f=b.fg("muted",v(O("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:l.cachedSkipped}))+` ${Oe("app.tools.expand",O("\u5373\u53EF\u5C55\u5F00"))}${b.fg("muted",")")}`;return["",xe(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(v(O("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:S})),r?.truncated&&(r.truncatedBy==="lines"?n.push(v(O("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:r.outputLines,total:r.totalLines})):n.push(v(O("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:r.outputLines,limit:k(r.maxBytes??j)}))),t.addChild(new M(`
9
- ${b.fg("warning",`[${n.join(". ")}]`)}`,0,0))}x&&t.addChild(new M(`
10
- ${b.fg("muted",x)}`,0,0))}u(Qe,"rebuildBashResultRenderComponent");function Ze(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?O("\u5DF2\u8FD0\u884C"):O("\u8017\u65F6")} ${qe(c)}`}u(Ze,"bashTimingLabel");function et(t,e,o){const s=o?.operations??e.defaultOperations?.()??Ve({shellPath:o?.shellPath}),c=o?.commandPrefix,a=o?.exposeSessionEnvironment??!0,E=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 ${Ne} lines or ${j/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?Ue:se,outputSchema:Ge,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(p,r,S,n,i){const{command:f,timeout:y}=r;n&&n({content:[],details:void 0});const W=await We({toolName:e.name,command:f,cwd:i?.cwd||t,sessionFile:i?.sessionManager?.getSessionFile()});if(W!==void 0)throw new Error(W);const ae=c?`${c}
11
- ${f}`:f,C=Xe(ae,i?.cwd||t,E,a,i),R=h??(l?Pe():void 0);let _;if(R?.active){if(!e.sandboxShell)throw new Error(`Command refused: ${e.shellName} commands cannot run inside the OS sandbox yet, and the sandbox level is "${R.level}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);_=await R.prepare({command:C.command,cwd:C.cwd,shell:e.sandboxShell(o?.shellPath),shellKind:e.sandboxShellKind??"bash",env:C.env,toolCallId:p,toolName:e.name,escalation:r.sandbox_escalation,ctx:i,signal:S})}const T=new Ce({tempFilePrefix:e.tempFilePrefix});let H=!0,I,B=!1,X=0;const U=u(()=>{if(!n||!B)return;B=!1,X=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"),G=u(()=>{I&&(clearTimeout(I),I=void 0)},"clearUpdateTimer"),de=u(()=>{if(!n)return;B=!0;const d=Ye-(Date.now()-X);if(d<=0){G(),U();return}I??=setTimeout(()=>{I=void 0,U()},d)},"scheduleOutputUpdate"),le=u(d=>{H&&(T.append(d),de())},"handleData"),K=u(async()=>{H=!1,T.finish(),G(),U();const d=T.snapshot({persistIfTruncated:!0});return await T.closeTempFile(),d},"finishOutput"),Y=u((d,$="(no output)")=>{const w=d.truncation;let L=d.content||$,A;if(w.truncated){A={truncation:w,fullOutputPath:d.fullOutputPath};const N=w.totalLines-w.outputLines+1,P=w.totalLines;if(w.lastLinePartial){const F=k(T.getLastLineBytes());L+=`
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
- [Showing last ${k(w.outputBytes)} of line ${P} (line is ${F}). Full output: ${d.fullOutputPath}]`}else w.truncatedBy==="lines"?L+=`
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
- [Showing lines ${N}-${P} of ${w.totalLines}. Full output: ${d.fullOutputPath}]`:L+=`
15
+ [Condensed: ${C.summary}. Full output: ${D}]`),{text:F,details:N,snapshot:g}},"modelOutput"),M=r((c,g)=>`${c?`${c}
16
16
 
17
- [Showing lines ${N}-${P} of ${w.totalLines} (${k(j)} limit). Full output: ${d.fullOutputPath}]`}return{text:L,details:A}},"formatOutput"),D=u((d,$)=>`${d?`${d}
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
- `:""}${$}`,"appendStatus"),ue=performance.now();try{let d;try{d=(await s.exec(_?.command??C.command,C.cwd,{onData:le,signal:S,timeout:y,env:C.env})).exitCode}catch(g){const ce=await K(),{text:J}=Y(ce,"");if(await _?.finish(null,""),g instanceof Error&&g.message==="aborted")throw new Error(D(J,"Command aborted"));if(g instanceof Error&&g.message.startsWith("timeout:")){const me=g.message.split(":")[1];throw new Error(D(J,`Command timed out after ${me} seconds`))}throw g}const $=await K(),{text:w,details:L}=Y($),A=await _?.finish(d,$.content||"");if(A&&_)throw new we(`${D(w,`Command exited with code ${d??"(none)"}`)}
20
-
21
- ${Te(A)}`,{...L,sandbox:_.details});if(d===null)throw new Error(D(w,"Command terminated without an exit code"));const N=Math.round((performance.now()-ue)/100)/10,P=await T.readFullOutput(Fe),F={output:P.content,truncated:P.truncated,...P.truncated&&$.fullOutputPath?{full_output_path:$.fullOutputPath}:{},exit_code:d,wall_time_seconds:N},z=_?.details.escalation?_.details:void 0,q=z?{...L,sandbox:z}:L;return d!==0?{content:[{type:"text",text:D(w,`Command exited with code ${d}`)}],details:q,structuredContent:F,isError:!0}:{content:[{type:"text",text:w}],details:q,structuredContent:F}}finally{G()}},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 M("",0,0);return i.setText(Je(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 ze;return Qe(f,p,r,n.showImages,i.startedAt,i.endedAt,n.isError,n.durationMs),f.invalidate(),f}}}u(et,"createShellToolDefinition");const tt={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:re.snippet,promptGuidelines:re.guidelines,tempFilePrefix:"pi-bash",readOnlyCommand:ge,sandboxShell:u(t=>Q(t).shell,"sandboxShell")};function nt(t,e){return et(t,tt,e)}u(nt,"createBashToolDefinition");function yt(t,e){const o=nt(t,e),s=Me(o);return Object.assign(s,{promptSnippet:o.promptSnippet,promptGuidelines:o.promptGuidelines}),s}u(yt,"createBashTool");export{re as bashToolSystemPromptContribution,yt as createBashTool,nt as createBashToolDefinition,Ve as createLocalBashOperations,je as createLocalShellOperations,et as createShellToolDefinition,Lt as registerShellExecutionGuard,Be 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??"pi-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}
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
3
  [... ${d} bytes omitted ...]
4
4
 
5
- ${m}`,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};
@@ -0,0 +1,3 @@
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
+ `).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{g as ERROR_LINE,D as condenseShellOutput,P as outputCondenseDisabled};
@@ -1,2 +1,2 @@
1
1
  var p=Object.defineProperty;var t=(e,o)=>p(e,"name",{value:o,configurable:!0});import{getPowerShellConfig as r}from"../../utils/shell.js";import{createLocalShellOperations as s,createShellToolDefinition as c}from"./bash.js";import{wrapToolDefinition as a}from"./tool-definition-wrapper.js";const m=`try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}
2
- `,i={snippet:"Execute PowerShell commands",guidelines:["You can inspect DAL_* environment variables for current model and session details."]};function h(){const e=s("PowerShell",r);return{exec:t((o,n,l)=>e.exec(`${m}${o}`,n,l),"exec")}}t(h,"createLocalPowerShellOperations");const u={name:"powershell",label:"powershell",shellName:"PowerShell",prompt:"PS>",promptSnippet:i.snippet,promptGuidelines:i.guidelines,tempFilePrefix:"pi-powershell",defaultOperations:h,sandboxShell:t(()=>process.platform==="win32"?r().shell:"pwsh","sandboxShell"),sandboxShellKind:"powershell"};function S(e,o){return c(e,u,o)}t(S,"createPowerShellToolDefinition");function x(e,o){const n=S(e,o),l=a(n);return Object.assign(l,{promptSnippet:n.promptSnippet,promptGuidelines:n.promptGuidelines}),l}t(x,"createPowerShellTool");export{h as createLocalPowerShellOperations,x as createPowerShellTool,S as createPowerShellToolDefinition,i as powershellToolSystemPromptContribution};
2
+ `,i={snippet:"Execute PowerShell commands",guidelines:["You can inspect DAL_* environment variables for current model and session details."]};function h(){const e=s("PowerShell",r);return{exec:t((o,l,n)=>e.exec(`${m}${o}`,l,n),"exec")}}t(h,"createLocalPowerShellOperations");const u={name:"powershell",label:"powershell",shellName:"PowerShell",prompt:"PS>",promptSnippet:i.snippet,promptGuidelines:i.guidelines,tempFilePrefix:"dal-powershell",defaultOperations:h,sandboxShell:t(()=>process.platform==="win32"?r().shell:"pwsh","sandboxShell"),sandboxShellKind:"powershell"};function d(e,o){return c(e,u,o)}t(d,"createPowerShellToolDefinition");function x(e,o){const l=d(e,o),n=a(l);return Object.assign(n,{promptSnippet:l.promptSnippet,promptGuidelines:l.promptGuidelines}),n}t(x,"createPowerShellTool");export{h as createLocalPowerShellOperations,x as createPowerShellTool,d as createPowerShellToolDefinition,i as powershellToolSystemPromptContribution};
@@ -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};