dal-code 1.0.20 → 1.0.23

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 (113) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/bun/register-bedrock.js +1 -0
  3. package/dist/core/agent-session.js +3 -3
  4. package/dist/core/http-dispatcher.js +1 -1
  5. package/dist/core/model-resolver.js +1 -1
  6. package/dist/core/model-runtime.js +1 -1
  7. package/dist/core/provider-composer.js +1 -1
  8. package/dist/core/sdk.js +1 -1
  9. package/dist/core/settings-manager.js +1 -1
  10. package/dist/core/system-prompt.js +8 -8
  11. package/dist/core/tools/bash-read-only.js +4 -0
  12. package/dist/core/tools/bash.js +13 -13
  13. package/dist/core/tools/tool-definition-wrapper.js +1 -1
  14. package/dist/modes/interactive/interactive-mode.js +14 -14
  15. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  16. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  17. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  18. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  19. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  20. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  21. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  22. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  23. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
  24. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  25. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
  26. package/dist/node_modules/@dalcode/dal-plugins/package.json +2 -2
  27. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  28. package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
  29. package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
  30. package/dist/node_modules/@dalcode/dal-router/src/pool.js +1 -1
  31. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  32. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  33. package/dist/node_modules/@dalcode/dal-subagent/src/agents.js +2 -2
  34. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +9 -7
  35. package/dist/node_modules/@dalcode/dal-subagent/src/process-runner.js +3 -0
  36. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  37. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  38. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  39. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  40. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  41. package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
  42. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  43. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +1 -1
  44. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.js +1 -0
  45. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/errors.js +1 -0
  46. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-repo.js +1 -0
  47. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-storage.js +5 -0
  48. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl.js +1 -0
  49. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-repo.js +1 -0
  50. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-storage.js +1 -0
  51. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/repo-utils.js +1 -0
  52. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/state.js +1 -0
  53. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance.js +1 -0
  54. package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/scanning.js +1 -0
  55. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +4 -4
  56. package/dist/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-gateway-binding.js +1 -0
  57. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  58. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  59. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  60. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  61. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  62. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  63. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js +1 -1
  64. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  65. package/dist/node_modules/@earendil-works/pi-client/dist/session-handle.js +1 -0
  66. package/dist/node_modules/@earendil-works/pi-client/dist/state.js +1 -0
  67. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  68. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  69. package/dist/node_modules/@earendil-works/pi-server/dist/cli.js +16 -0
  70. package/dist/node_modules/@earendil-works/pi-server/dist/config.js +1 -0
  71. package/dist/node_modules/@earendil-works/pi-server/dist/handler.js +1 -0
  72. package/dist/node_modules/@earendil-works/pi-server/dist/ipc/client.js +2 -0
  73. package/dist/node_modules/@earendil-works/pi-server/dist/ipc/protocol.js +2 -0
  74. package/dist/node_modules/@earendil-works/pi-server/dist/ipc/server.js +3 -0
  75. package/dist/node_modules/@earendil-works/pi-server/dist/protocol.js +1 -0
  76. package/dist/node_modules/@earendil-works/pi-server/dist/radius.js +1 -0
  77. package/dist/node_modules/@earendil-works/pi-server/dist/rpc-process.js +4 -0
  78. package/dist/node_modules/@earendil-works/pi-server/dist/serve.js +1 -0
  79. package/dist/node_modules/@earendil-works/pi-server/dist/sessions.js +1 -0
  80. package/dist/node_modules/@earendil-works/pi-server/dist/snapshots.js +1 -0
  81. package/dist/node_modules/@earendil-works/pi-server/dist/storage.js +1 -0
  82. package/dist/node_modules/@earendil-works/pi-server/dist/supervisor.js +1 -0
  83. package/dist/node_modules/@earendil-works/pi-server/dist/testing/service.js +1 -0
  84. package/dist/node_modules/@earendil-works/pi-server/package.json +5 -5
  85. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/branch-cache.js +7 -0
  86. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/search-backend.js +36 -0
  87. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/branch-entries.js +25 -0
  88. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/branch-tips.js +2 -0
  89. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/entries.js +7 -0
  90. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/facts.js +20 -0
  91. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/lanes.js +26 -0
  92. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/records.js +9 -0
  93. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/session-sequences.js +1 -0
  94. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/session-stats.js +10 -0
  95. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/sessions.js +29 -0
  96. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/dist/sqlite/storage/writer-leases.js +14 -0
  97. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/package.json +3 -3
  98. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  99. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  100. package/dist/server/create-harness.js +1 -0
  101. package/dist/utils/clipboard-image.js +1 -1
  102. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  103. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  104. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  105. package/examples/extensions/gondolin/package-lock.json +2 -2
  106. package/examples/extensions/gondolin/package.json +1 -1
  107. package/examples/extensions/sandbox/package-lock.json +2 -2
  108. package/examples/extensions/sandbox/package.json +1 -1
  109. package/examples/extensions/with-deps/package-lock.json +2 -2
  110. package/examples/extensions/with-deps/package.json +1 -1
  111. package/npm-shrinkwrap.json +2 -2
  112. package/package.json +1 -1
  113. package/dist/node_modules/@earendil-works/pi-agent-core/dist/__probe.js +0 -1
@@ -1 +1 @@
1
- var E=Object.defineProperty;var g=(a,e)=>E(a,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as F}from"@earendil-works/pi-ai";import{randomUUID as x}from"crypto";import{existsSync as k,mkdirSync as L,readFileSync as I,writeFileSync as N}from"fs";import{dirname as A,join as m}from"path";import D from"proper-lockfile";import{CONFIG_DIR_NAME as M,getAgentDir as O}from"../config.js";import{normalizePath as y,resolvePath as u}from"../utils/paths.js";import{stripBom as v}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as R,parseHttpIdleTimeoutMs as W}from"./http-dispatcher.js";const $={reserveTokens:16384,keepRecentTokens:2e4},B=128e3,H=["off","streaming","idle"];function f(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)}g(f,"isMergeableObject");function T(a,e){const t={...a};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const r=a[s];t[s]=f(r)&&f(i)?T(r,i):i}return t}g(T,"deepMergeObjects");function h(a,e){return T(a,e)}g(h,"deepMergeSettings");function P(a,e){const t=W(a);if(t!==void 0)return t;if(a!==void 0)throw new Error(`Invalid ${e} setting: ${String(a)}`)}g(P,"parseTimeoutSetting");function S(a,e,t){return{scope:a,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}g(S,"toSettingsError");class U{static{g(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=u(e),i=u(t);this.globalSettingsPath=m(i,"settings.json"),this.projectSettingsPath=m(s,M,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let r=1;r<=10;r++)try{return D.lockSync(e,{realpath:!1})}catch(o){if((typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0)!=="ELOCKED"||r===10)throw o;i=o;const d=Date.now();for(;Date.now()-d<20;);}throw i??new Error("Failed to acquire settings lock")}withLock(e,t){const s=e==="global"?this.globalSettingsPath:this.projectSettingsPath,i=A(s);let r;try{const o=k(s);o&&(r=this.acquireLockSyncWithRetry(s));const n=o?I(s,"utf-8"):void 0,d=t(n);d!==void 0&&(k(i)||L(i,{recursive:!0}),r||(r=this.acquireLockSyncWithRetry(s)),N(s,d,"utf-8"))}finally{r&&r()}}}class q{static{g(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 l{static{g(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,r=null,o=[],n=!0,d={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=n,this.globalSettingsLoadError=i,this.projectSettingsLoadError=r,this.errors=[...o],this.settingsPaths=d,this.settings=h(this.globalSettings,this.projectSettings)}static create(e,t=O(),s={}){const i=u(e),r=u(t),o=new U(i,r);return l.fromStorageWithPaths(o,s,{global:m(r,"settings.json"),project:m(i,M,"settings.json")})}static fromStorage(e,t={}){return l.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,r=l.tryLoadFromStorage(e,"global"),o=l.tryLoadFromStorage(e,"project",i),n=[];return r.error&&n.push(S("global",r.error,s.global)),o.error&&n.push(S("project",o.error,s.project)),new l(e,r.settings,o.settings,r.error,o.error,n,i,s)}static inMemory(e={},t={}){const s=new q,i=l.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),l.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 r=JSON.parse(v(i));return l.migrateSettings(r)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:l.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}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=l.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=l.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=l.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,r=>{const o=r?l.migrateSettings(JSON.parse(v(r))):{},n={...o};for(const d of s){const c=t[d];if(i.has(d)&&typeof c=="object"&&c!==null){const j=i.get(d),C=o[d]??{},w=c,p={...C};for(const b of j)p[b]=w[b];n[d]=p}else n[d]=c}return JSON.stringify(n,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&&y(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 r=t?`${t.provider}/${t.id}`:void 0,o=r!==void 0?s?.modelOverrides?.[r]:void 0;if(o!==void 0&&!f(o))throw new Error(`Invalid compaction.modelOverrides["${r}"] setting: ${String(o)}. Expected an object.`);const n=o?.[e];if(n!==void 0&&(typeof n!="number"||!Number.isSafeInteger(n)||n<0))throw new Error(`Invalid compaction.modelOverrides["${r}"].${e} setting: ${String(n)}. Expected a non-negative safe integer.`);return n??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 B;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??3,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??F}}getHttpIdleTimeoutMs(){return P(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??R}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&&H.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 P(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&&y(e)}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){return this.settings.quietStartup??!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}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=x(),this.markModified("trackingId")),this.save()}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()}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;return e?[...e]:void 0}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{H as CACHE_WARMING_MODES,B as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,U as FileSettingsStorage,q as InMemorySettingsStorage,l as SettingsManager};
1
+ var w=Object.defineProperty;var g=(a,e)=>w(a,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as x}from"@earendil-works/pi-ai";import{randomUUID as F}from"crypto";import{existsSync as k,mkdirSync as L,readFileSync as I,writeFileSync as A}from"fs";import{dirname as N,join as u}from"path";import O from"proper-lockfile";import{CONFIG_DIR_NAME as M,getAgentDir as D}from"../config.js";import{normalizePath as T,resolvePath as m}from"../utils/paths.js";import{stripBom as y}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as R,parseHttpIdleTimeoutMs as W}from"./http-dispatcher.js";const $={reserveTokens:16384,keepRecentTokens:2e4},_=128e3,U=32e3,B=5,H=["off","streaming","idle"];function f(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)}g(f,"isMergeableObject");function v(a,e){const t={...a};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const r=a[s];t[s]=f(r)&&f(i)?v(r,i):i}return t}g(v,"deepMergeObjects");function h(a,e){return v(a,e)}g(h,"deepMergeSettings");function P(a,e){const t=W(a);if(t!==void 0)return t;if(a!==void 0)throw new Error(`Invalid ${e} setting: ${String(a)}`)}g(P,"parseTimeoutSetting");function p(a,e,t){return{scope:a,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}g(p,"toSettingsError");class q{static{g(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=m(e),i=m(t);this.globalSettingsPath=u(i,"settings.json"),this.projectSettingsPath=u(s,M,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let r=1;r<=10;r++)try{return O.lockSync(e,{realpath:!1})}catch(o){if((typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0)!=="ELOCKED"||r===10)throw o;i=o;const d=Date.now();for(;Date.now()-d<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 r;try{const o=k(s);o&&(r=this.acquireLockSyncWithRetry(s));const n=o?I(s,"utf-8"):void 0,d=t(n);d!==void 0&&(k(i)||L(i,{recursive:!0}),r||(r=this.acquireLockSyncWithRetry(s)),A(s,d,"utf-8"))}finally{r&&r()}}}class V{static{g(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 l{static{g(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,r=null,o=[],n=!0,d={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=n,this.globalSettingsLoadError=i,this.projectSettingsLoadError=r,this.errors=[...o],this.settingsPaths=d,this.settings=h(this.globalSettings,this.projectSettings)}static create(e,t=D(),s={}){const i=m(e),r=m(t),o=new q(i,r);return l.fromStorageWithPaths(o,s,{global:u(r,"settings.json"),project:u(i,M,"settings.json")})}static fromStorage(e,t={}){return l.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,r=l.tryLoadFromStorage(e,"global"),o=l.tryLoadFromStorage(e,"project",i),n=[];return r.error&&n.push(p("global",r.error,s.global)),o.error&&n.push(p("project",o.error,s.project)),new l(e,r.settings,o.settings,r.error,o.error,n,i,s)}static inMemory(e={},t={}){const s=new V,i=l.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),l.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 r=JSON.parse(y(i));return l.migrateSettings(r)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:l.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}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=l.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=l.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=l.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(p(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,r=>{const o=r?l.migrateSettings(JSON.parse(y(r))):{},n={...o};for(const d of s){const c=t[d];if(i.has(d)&&typeof c=="object"&&c!==null){const j=i.get(d),C=o[d]??{},E=c,S={...C};for(const b of j)S[b]=E[b];n[d]=S}else n[d]=c}return JSON.stringify(n,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&&T(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 r=t?`${t.provider}/${t.id}`:void 0,o=r!==void 0?s?.modelOverrides?.[r]:void 0;if(o!==void 0&&!f(o))throw new Error(`Invalid compaction.modelOverrides["${r}"] setting: ${String(o)}. Expected an object.`);const n=o?.[e];if(n!==void 0&&(typeof n!="number"||!Number.isSafeInteger(n)||n<0))throw new Error(`Invalid compaction.modelOverrides["${r}"].${e} setting: ${String(n)}. Expected a non-negative safe integer.`);return n??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 _;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??B,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??x}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return U;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 P(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??R}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&&H.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 P(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&&T(e)}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){return this.settings.quietStartup??!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}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=F(),this.markModified("trackingId")),this.save()}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()}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;return e?[...e]:void 0}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{H as CACHE_WARMING_MODES,_ as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,U as DEFAULT_MAX_OUTPUT_TOKENS,B as DEFAULT_MAX_RETRIES,q as FileSettingsStorage,V as InMemorySettingsStorage,l as SettingsManager};
@@ -1,18 +1,18 @@
1
- var y=Object.defineProperty;var c=(e,t)=>y(e,"name",{value:t,configurable:!0});import{getSystemMessageText as k}from"@earendil-works/pi-ai";import{APP_NAME as x,APP_TITLE as b,getDocsPath as w,getExamplesPath as $,getReadmePath as j}from"../config.js";import{formatSkillsForPrompt as O}from"./skills.js";const v=/^[a-z][a-z0-9_-]*$/;function E(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],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,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}c(E,"normalizeBuildSystemPromptOptions");function T(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:n})=>`<project_instructions path="${t}">
1
+ var y=Object.defineProperty;var c=(e,t)=>y(e,"name",{value:t,configurable:!0});import{getSystemMessageText as k}from"@earendil-works/pi-ai";import{APP_NAME as x,APP_TITLE as b,getDocsPath as w,getExamplesPath as $,getReadmePath as j}from"../config.js";import{formatSkillsForPrompt as v}from"./skills.js";const E=/^[a-z][a-z0-9_-]*$/;function O(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],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,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}c(O,"normalizeBuildSystemPromptOptions");function _(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:n})=>`<project_instructions path="${t}">
2
2
  ${n}
3
3
  </project_instructions>`)].join(`
4
4
 
5
- `)}c(T,"renderProjectContext");function _(e,t,n){const i=[],d=new Set,l=c(r=>{const o=r.trim();!o||d.has(o)||(d.add(o),i.push(o))},"addRule"),p=e.includes("bash"),m=e.includes("powershell"),f=e.includes("grep"),g=e.includes("find"),u=e.includes("ls");(p||m)&&!f&&!g&&!u&&l(p&&m?"Use bash or PowerShell for file operations like listing, searching, and finding files":m?"Use PowerShell for file operations like listing, searching, and finding files":"Use bash for file operations like ls, rg, find");for(const r of e)for(const o of t[r]??[])l(o);for(const r of n)l(r);return l("Be concise in your responses"),l("Show file paths clearly when working with files"),i.map(r=>`- ${r}`).join(`
6
- `)}c(_,"buildRules");function A(e){const t=E(e),{customPrompt:n,selectedTools:i,toolSnippets:d,toolGuidelines:l,promptGuidelines:p,appendSystemPrompt:m,sections:f,cwd:g,contextFiles:u,skills:r}=t;for(const s of Object.keys(f))if(!v.test(s)||s==="preamble")throw new Error(`Invalid system prompt section name: ${s}`);const o={};if(n)o.preamble=n;else{o.preamble=`You are an expert coding assistant operating inside ${b} (${x}). You help users by reading files, executing commands, editing code, and writing new files.`;const s=i.filter(h=>!!d[h]),a=s.length>0?s.map(h=>`- ${h}: ${d[h]}`).join(`
7
- `):"(none)";o.tools=`${a}
5
+ `)}c(_,"renderProjectContext");function A(e,t,n){const i=[],d=new Set,r=c(l=>{const s=l.trim();!s||d.has(s)||(d.add(s),i.push(s))},"addRule"),p=e.includes("bash"),a=e.includes("powershell"),f=e.includes("grep"),g=e.includes("find"),u=e.includes("ls");(p||a)&&!f&&!g&&!u&&r(p&&a?"Use bash or PowerShell for file operations like listing, searching, and finding files":a?"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 s of t[l]??[])r(s);for(const l of n)r(l);return e.length>0&&r("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"),r("Be concise in your responses"),r("Show file paths clearly when working with files"),i.map(l=>`- ${l}`).join(`
6
+ `)}c(A,"buildRules");function I(e){const t=O(e),{customPrompt:n,selectedTools:i,toolSnippets:d,toolGuidelines:r,promptGuidelines:p,appendSystemPrompt:a,sections:f,cwd:g,contextFiles:u,skills:l}=t;for(const o of Object.keys(f))if(!E.test(o)||o==="preamble")throw new Error(`Invalid system prompt section name: ${o}`);const s={};if(n)s.preamble=n;else{s.preamble=`You are an expert coding assistant operating inside ${b} (${x}). You help users by reading files, executing commands, editing code, and writing new files.`;const o=i.filter(h=>!!d[h]),m=o.length>0?o.map(h=>`- ${h}: ${d[h]}`).join(`
7
+ `):"(none)";s.tools=`${m}
8
8
 
9
- In addition to the tools above, you may have access to other custom tools depending on the project.`,o.rules=_(i,l,p),o.docs=`${b} documentation (read only when the user asks about ${b} itself, its SDK, extensions, themes, skills, or TUI):
9
+ In addition to the tools above, you may have access to other custom tools depending on the project.`,s.rules=A(i,r,p),s.docs=`${b} documentation (read only when the user asks about ${b} itself, its SDK, extensions, themes, skills, or TUI):
10
10
  - Main documentation: ${j()}
11
11
  - Additional docs: ${w()}
12
12
  - Examples: ${$()} (extensions, custom tools, SDK)
13
13
  - When reading these docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory
14
14
  - 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)
15
15
  - When working on these topics, read the docs and examples, and follow .md cross-references before implementing
16
- - Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}m&&(o.addendum=m),u.length>0&&(o.project_context=T(u));const S=["read","bash"].find(s=>i.includes(s));if(S&&r.length>0){const s=O(r,S).trim();s&&(o.skills=s)}o.cwd=g.replace(/\\/g,"/");for(const[s,a]of Object.entries(f))a&&(o[s]=a);const P={preamble:o.preamble};for(const[s,a]of Object.entries(o))s!=="preamble"&&(P[s]=`<${s}>
17
- ${a}
18
- </${s}>`);return P}c(A,"buildSystemPromptSections");function I(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:A(e)}}c(I,"buildSystemPromptState");function R(e){return k({role:"system",...I(e),timestamp:0})}c(R,"buildSystemPrompt");function z(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(z,"diffSystemPromptSections");export{R as buildSystemPrompt,A as buildSystemPromptSections,I as buildSystemPromptState,z as diffSystemPromptSections,E as normalizeBuildSystemPromptOptions};
16
+ - Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}a&&(s.addendum=a),u.length>0&&(s.project_context=_(u));const S=["read","bash"].find(o=>i.includes(o));if(S&&l.length>0){const o=v(l,S).trim();o&&(s.skills=o)}s.cwd=g.replace(/\\/g,"/");for(const[o,m]of Object.entries(f))m&&(s[o]=m);const P={preamble:s.preamble};for(const[o,m]of Object.entries(s))o!=="preamble"&&(P[o]=`<${o}>
17
+ ${m}
18
+ </${o}>`);return P}c(I,"buildSystemPromptSections");function T(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:I(e)}}c(T,"buildSystemPromptState");function R(e){return k({role:"system",...T(e),timestamp:0})}c(R,"buildSystemPrompt");function z(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(z,"diffSystemPromptSections");export{R as buildSystemPrompt,I as buildSystemPromptSections,T as buildSystemPromptState,z as diffSystemPromptSections,O as normalizeBuildSystemPromptOptions};
@@ -0,0 +1,4 @@
1
+ var p=Object.defineProperty;var l=(e,t)=>p(e,"name",{value:t,configurable:!0});const w=new Set(["basename","cat","cd","cmp","column","comm","cut","df","diff","dirname","du","echo","egrep","false","fgrep","file","fold","grep","head","hexdump","id","jq","ls","lsof","md5","md5sum","nl","od","pgrep","printenv","printf","ps","pwd","readlink","realpath","rg","sha1sum","sha256sum","shasum","sleep","stat","strings","tail","test","tr","true","type","uname","wc","whereis","which","whoami","xxd","[","[[","]]"]),v={find:/^-(delete|exec|execdir|ok|okdir|fprint|fprint0|fprintf|fls)$/,sort:/^(-o|--output)/,tree:/^-o$/,date:/^(-s|--set)/},m=new Set(["blame","cat-file","describe","diff","for-each-ref","grep","log","ls-files","ls-remote","ls-tree","merge-base","name-rev","rev-list","rev-parse","shortlog","show","show-ref","status","whatchanged"]),O={branch:l(e=>e.every(t=>/^(-a|-r|-v|-vv|--all|--remotes|--list|--show-current|--verbose|--no-color|--color)$/.test(t)),"branch"),tag:l(e=>e.length===0||e[0]==="-l"||e[0]==="--list","tag"),remote:l(e=>e.length===0||e[0]==="-v"||e[0]==="get-url"||e[0]==="show","remote"),stash:l(e=>e[0]==="list"||e[0]==="show","stash"),worktree:l(e=>e[0]==="list","worktree"),config:l(e=>e.length>0&&/^(--get|--get-all|--get-regexp|--list|-l)$/.test(e[0]),"config"),reflog:l(e=>e.length===0||e[0]==="show","reflog")};function y(e){const t=[];let s=[],n="",r=!1,i;const a=l(()=>{r&&s.push(n),n="",r=!1},"endWord"),d=l(()=>{a(),s.length>0&&t.push(s),s=[]},"endCommand");for(let f=0;f<e.length;f++){const u=e[f],o=e[f+1];if(i==="'"){u==="'"?i=void 0:n+=u;continue}if(u==="`")return;if(u==="$"&&o==="("){const c=_(e,f+2);if(c===void 0||!$(e.slice(f+2,c)))return;n+=e.slice(f,c+1),r=!0,f=c;continue}if(u==="\\"){o===`
2
+ `?f++:o!==void 0&&(n+=o,r=!0,f++);continue}if(i==='"'){u==='"'?i=void 0:n+=u;continue}switch(u){case"'":case'"':i=u,r=!0;continue;case" ":case" ":a();continue;case`
3
+ `:case";":d();continue;case"|":d(),o==="|"&&f++;continue;case"&":if(o==="&"){d(),f++;continue}if(o===">")continue;return;case">":{if(o===">")return;/^\d$/.test(n)&&r&&(n="",r=!1);const c=e.slice(f+1),g=/^(&\d|\s*\/dev\/null)(?=$|[\s;|&)])/.exec(c);if(!g)return;f+=g[0].length;continue}case"<":if(o==="<"||o==="(")return;a();continue;case"(":case")":case"{":case"}":if(r){n+=u;continue}return;case"#":if(!r){for(;f+1<e.length&&e[f+1]!==`
4
+ `;)f++;continue}n+=u;continue;default:n+=u,r=!0}}if(!i)return d(),{commands:t}}l(y,"scan");function _(e,t){let s=1,n;for(let r=t;r<e.length;r++){const i=e[r];if(n==="'")i==="'"&&(n=void 0);else if(i==="\\")r++;else if(n==='"')i==='"'&&(n=void 0);else if(i==="'"||i==='"')n=i;else if(i==="(")s++;else if(i===")"&&--s===0)return r}}l(_,"substitutionEnd");const h=/^[A-Za-z_][A-Za-z0-9_]*=/,x=new Set(["if","then","else","elif","do","while","until","!","export"]),R=new Set(["fi","done"]);function S(e){let t=e;for(;t.length>0&&(x.has(t[0])||h.test(t[0]));){if(t[0]==="export")return t.slice(1).every(i=>h.test(i)||/^[A-Za-z_][A-Za-z0-9_]*$/.test(i));t=t.slice(1)}if(t.length===0)return!0;const[s,...n]=t;if(R.has(s))return n.length===0;if(s==="for")return n.length>=2&&n[1]==="in";if(w.has(s))return!0;const r=v[s];return r?!n.some(i=>r.test(i)):s==="uniq"?n.filter(i=>!i.startsWith("-")).length<=1:s==="hostname"?n.every(i=>i.startsWith("-")):s==="env"?n.every(i=>h.test(i)||i==="-0"||i==="--null"):s==="sed"?A(n):s==="awk"?n.every(i=>!/system|getline|[>|]/.test(i)):s==="git"?N(n):!1}l(S,"isReadOnlySimpleCommand");function A(e){return e.every(t=>/^(-i|--in-place|-I)/.test(t)?!1:!/(^|[;\n{}\d$/]|\/[a-zA-Z0-9]*)\s*[wWe](\s|$|;)/.test(t))}l(A,"isReadOnlySed");function N(e){let t=e;for(;t.length>0&&t[0].startsWith("-");)if(t[0]==="-C")t=t.slice(2);else if(t[0]==="--no-pager"||t[0]==="--no-optional-locks")t=t.slice(1);else if(/^--(git-dir|work-tree)=/.test(t[0]))t=t.slice(1);else return!1;const[s,...n]=t;return s===void 0||n.some(r=>/^--(output|ext-diff|textconv)/.test(r))?!1:m.has(s)?!0:O[s]?.(n)??!1}l(N,"isReadOnlyGit");function $(e){if(typeof e!="string"||e.trim()==="")return!1;const t=y(e);return t?t.commands.every(S):!1}l($,"isReadOnlyBashCommand");export{$ as isReadOnlyBashCommand};
@@ -1,19 +1,19 @@
1
- var J=Object.defineProperty;var l=(e,n)=>J(e,"name",{value:n,configurable:!0});import{constants as Q}from"node:fs";import{access as Z}from"node:fs/promises";import{constants as tt}from"node:os";import{Container as et,Text as I,truncateToWidth as nt}from"@earendil-works/pi-tui";import{spawn as it}from"child_process";import{Type as b}from"typebox";import{fill as _,t as E}from"../../dal/i18n.js";import{keyHint as ot}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as st}from"../../modes/interactive/components/visual-truncate.js";import{theme as h}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as rt}from"../../utils/child-process.js";import{getShellConfig as at,getShellEnv as G,killProcessTree as H,trackDetachedChildPid as dt,untrackDetachedChildPid as ut}from"../../utils/shell.js";import{OutputAccumulator as lt}from"./output-accumulator.js";import{countOutputLines as ct,formatCollapsedSummary as pt,getTextOutput as U,invalidArgText as mt,str as V,truncateDisplay as ft}from"./render-utils.js";import{wrapToolDefinition as ht}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as N,DEFAULT_MAX_LINES as wt,formatSize as D}from"./truncate.js";const j=2147483647,St=j/1e3,X=12e4;function Et(e){if(e===void 0)return X;if(!Number.isFinite(e)||e<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const n=e*1e3;if(n>j)throw new Error(`Invalid timeout: maximum is ${St} seconds`);return n}l(Et,"resolveTimeoutMs");const $t=b.Object({command:b.String({description:"Shell command to execute"}),description:b.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:b.Optional(b.Number({description:"Timeout in seconds. Defaults to 120; raise it for genuinely long-running commands."}))}),z={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect PI_* environment variables for current model and session details."]};function Tt(e,n){return{exec:l(async(i,d,{onData:u,signal:o,timeout:S,env:s})=>{const a=Et(S);if(o?.aborted)throw new Error("aborted");const m=n();try{await Z(d,Q.F_OK)}catch{throw new Error(`Working directory does not exist: ${d}
2
- Cannot execute ${e} commands.`)}const c=m.commandTransport==="stdin",t=it(m.shell,c?m.args:[...m.args,i],{cwd:d,detached:process.platform!=="win32",env:s??G(),stdio:[c?"pipe":"ignore","pipe","pipe"],windowsHide:!0});c&&(t.stdin?.on("error",()=>{}),t.stdin?.end(i)),t.pid&&dt(t.pid);let p=!1,f;const $=l(()=>{t.pid&&H(t.pid)},"onAbort");try{a!==void 0&&(f=setTimeout(()=>{p=!0,t.pid&&H(t.pid)},a)),t.stdout?.on("data",u),t.stderr?.on("data",u),o&&(o.aborted?$():o.addEventListener("abort",$,{once:!0}));const O=await rt(t);if(o?.aborted)throw new Error("aborted");if(p)throw new Error(`timeout:${(a??X)/1e3}`);const P=t.signalCode;return{exitCode:O??(P?128+(tt.signals[P]??0):1)}}finally{t.pid&&ut(t.pid),f&&clearTimeout(f),o&&o.removeEventListener("abort",$)}},"exec")}}l(Tt,"createLocalShellOperations");function Ot(e){return Tt("bash",()=>at(e?.shellPath))}l(Ot,"createLocalBashOperations");function Pt(e,n,i,d,u){const o={...G()};if(delete o.PI_SESSION_ID,delete o.PI_SESSION_FILE,delete o.PI_PROVIDER,delete o.PI_MODEL,delete o.PI_REASONING_LEVEL,d&&u){const s=u.model;o.PI_SESSION_ID=u.sessionManager.getSessionId();const a=u.sessionManager.getSessionFile();a&&(o.PI_SESSION_FILE=a),s&&(o.PI_PROVIDER=s.provider,o.PI_MODEL=s.id),u.thinkingLevel&&(o.PI_REASONING_LEVEL=u.thinkingLevel)}const S={command:e,cwd:n,env:o};return i?i(S):S}l(Pt,"resolveSpawnContext");const Lt=5,gt=100;class xt extends et{static{l(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function K(e){const n=e/1e3;if(n<60)return`${n.toFixed(1)}s`;const i=Math.floor(n),d=Math.floor(i/60),u=i%60;return d<60?`${d}m ${u}s`:`${Math.floor(d/60)}h ${d%60}m ${u}s`}l(K,"formatDuration");function _t(e,n,i=!1){const d=V(e?.command),u=V(e?.description)?.trim(),o=e?.timeout,S=o?h.fg("muted",_(E(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:o})):"";if(u){const a=h.fg("toolTitle",h.bold(u))+S;return!i||!d?a:`${a}
3
- ${h.fg("muted",` \u23BF ${n} ${d.trim()}`)}`}const s=d===null?mt(h):d?h.fg("dim",ft(d.replace(/\s+/g," ").trim(),42)):h.fg("dim","\u2026");return`${h.fg("toolTitle",h.bold(n))} ${s}${S}`}l(_t,"formatShellCall");function Ct(e,n,i,d,u,o,S){const s=e.state;if(e.clear(),!i.expanded&&!S){const t=U(n,d),p=ct(t),f=[];if(p>0&&f.push(_(E("{count} \u884C"),{count:p})),u!==void 0){const P=(o??Date.now())-u;if(i.isPartial||P>=100){const L=i.isPartial?E("\u5DF2\u8FD0\u884C"):E("\u8017\u65F6");f.push(`${L} ${K(P)}`)}}const $=pt(h,f);$&&e.addChild(new I($,0,0));return}let a=U(n,d).trim();const m=n.details?.truncation,c=n.details?.fullOutputPath;if(!i.isPartial&&m?.truncated&&c&&a.endsWith("]")){const t=a.lastIndexOf(`
1
+ var J=Object.defineProperty;var u=(n,e)=>J(n,"name",{value:e,configurable:!0});import{constants as Q}from"node:fs";import{access as Z}from"node:fs/promises";import{constants as tt}from"node:os";import{Container as et,Text as y,truncateToWidth as nt}from"@earendil-works/pi-tui";import{spawn as it}from"child_process";import{Type as I}from"typebox";import{fill as _,t as E}from"../../dal/i18n.js";import{keyHint as ot}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as rt}from"../../modes/interactive/components/visual-truncate.js";import{theme as h}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as st}from"../../utils/child-process.js";import{getShellConfig as at,getShellEnv as G,killProcessTree as H,trackDetachedChildPid as dt,untrackDetachedChildPid as lt}from"../../utils/shell.js";import{isReadOnlyBashCommand as ut}from"./bash-read-only.js";import{OutputAccumulator as ct}from"./output-accumulator.js";import{countOutputLines as mt,formatCollapsedSummary as pt,getTextOutput as U,invalidArgText as ft,str as V,truncateDisplay as ht}from"./render-utils.js";import{wrapToolDefinition as wt}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as B,DEFAULT_MAX_LINES as St,formatSize as D}from"./truncate.js";const j=2147483647,Et=j/1e3,X=12e4;function $t(n){if(n===void 0)return X;if(!Number.isFinite(n)||n<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const e=n*1e3;if(e>j)throw new Error(`Invalid timeout: maximum is ${Et} seconds`);return e}u($t,"resolveTimeoutMs");const Ot=I.Object({command:I.String({description:"Shell command to execute"}),description:I.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:I.Optional(I.Number({description:"Timeout in seconds. Defaults to 120; raise it for genuinely long-running commands."}))}),z={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect PI_* environment variables for current model and session details."]};function Tt(n,e){return{exec:u(async(i,d,{onData:l,signal:o,timeout:S,env:r})=>{const a=$t(S);if(o?.aborted)throw new Error("aborted");const p=e();try{await Z(d,Q.F_OK)}catch{throw new Error(`Working directory does not exist: ${d}
2
+ Cannot execute ${n} commands.`)}const c=p.commandTransport==="stdin",t=it(p.shell,c?p.args:[...p.args,i],{cwd:d,detached:process.platform!=="win32",env:r??G(),stdio:[c?"pipe":"ignore","pipe","pipe"],windowsHide:!0});c&&(t.stdin?.on("error",()=>{}),t.stdin?.end(i)),t.pid&&dt(t.pid);let m=!1,f;const $=u(()=>{t.pid&&H(t.pid)},"onAbort");try{a!==void 0&&(f=setTimeout(()=>{m=!0,t.pid&&H(t.pid)},a)),t.stdout?.on("data",l),t.stderr?.on("data",l),o&&(o.aborted?$():o.addEventListener("abort",$,{once:!0}));const T=await st(t);if(o?.aborted)throw new Error("aborted");if(m)throw new Error(`timeout:${(a??X)/1e3}`);const P=t.signalCode;return{exitCode:T??(P?128+(tt.signals[P]??0):1)}}finally{t.pid&&lt(t.pid),f&&clearTimeout(f),o&&o.removeEventListener("abort",$)}},"exec")}}u(Tt,"createLocalShellOperations");function Pt(n){return Tt("bash",()=>at(n?.shellPath))}u(Pt,"createLocalBashOperations");function xt(n,e,i,d,l){const o={...G()};if(delete o.PI_SESSION_ID,delete o.PI_SESSION_FILE,delete o.PI_PROVIDER,delete o.PI_MODEL,delete o.PI_REASONING_LEVEL,d&&l){const r=l.model;o.PI_SESSION_ID=l.sessionManager.getSessionId();const a=l.sessionManager.getSessionFile();a&&(o.PI_SESSION_FILE=a),r&&(o.PI_PROVIDER=r.provider,o.PI_MODEL=r.id),l.thinkingLevel&&(o.PI_REASONING_LEVEL=l.thinkingLevel)}const S={command:n,cwd:e,env:o};return i?i(S):S}u(xt,"resolveSpawnContext");const Ct=5,Lt=100;class _t extends et{static{u(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function K(n){const e=n/1e3;if(e<60)return`${e.toFixed(1)}s`;const i=Math.floor(e),d=Math.floor(i/60),l=i%60;return d<60?`${d}m ${l}s`:`${Math.floor(d/60)}h ${d%60}m ${l}s`}u(K,"formatDuration");function gt(n,e,i=!1){const d=V(n?.command),l=V(n?.description)?.trim(),o=n?.timeout,S=o?h.fg("muted",_(E(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:o})):"";if(l){const a=h.fg("toolTitle",h.bold(l))+S;return!i||!d?a:`${a}
3
+ ${h.fg("muted",` \u23BF ${e} ${d.trim()}`)}`}const r=d===null?ft(h):d?h.fg("dim",ht(d.replace(/\s+/g," ").trim(),42)):h.fg("dim","\u2026");return`${h.fg("toolTitle",h.bold(e))} ${r}${S}`}u(gt,"formatShellCall");function yt(n,e,i,d,l,o,S){const r=n.state;if(n.clear(),!i.expanded&&!S){const t=U(e,d),m=mt(t),f=[];if(m>0&&f.push(_(E("{count} \u884C"),{count:m})),l!==void 0){const P=(o??Date.now())-l;if(i.isPartial||P>=100){const x=i.isPartial?E("\u5DF2\u8FD0\u884C"):E("\u8017\u65F6");f.push(`${x} ${K(P)}`)}}const $=pt(h,f);$&&n.addChild(new y($,0,0));return}let a=U(e,d).trim();const p=e.details?.truncation,c=e.details?.fullOutputPath;if(!i.isPartial&&p?.truncated&&c&&a.endsWith("]")){const t=a.lastIndexOf(`
4
4
 
5
5
  [`);t!==-1&&a.slice(t).includes(c)&&(a=a.slice(0,t).trimEnd())}if(a){const t=a.split(`
6
- `).map(p=>h.fg("toolOutput",p)).join(`
7
- `);i.expanded?e.addChild(new I(`
8
- ${t}`,0,0)):e.addChild({render:l(p=>{if(s.cachedLines===void 0||s.cachedWidth!==p){const f=st(t,Lt,p);s.cachedLines=f.visualLines,s.cachedSkipped=f.skippedCount,s.cachedWidth=p}if(s.cachedSkipped&&s.cachedSkipped>0){const f=h.fg("muted",_(E("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:s.cachedSkipped}))+` ${ot("app.tools.expand",E("\u5373\u53EF\u5C55\u5F00"))}${h.fg("muted",")")}`;return["",nt(f,p,"..."),...s.cachedLines??[]]}return["",...s.cachedLines??[]]},"render"),invalidate:l(()=>{s.cachedWidth=void 0,s.cachedLines=void 0,s.cachedSkipped=void 0},"invalidate")})}if(m?.truncated||c){const t=[];c&&t.push(_(E("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:c})),m?.truncated&&(m.truncatedBy==="lines"?t.push(_(E("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:m.outputLines,total:m.totalLines})):t.push(_(E("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:m.outputLines,limit:D(m.maxBytes??N)}))),e.addChild(new I(`
9
- ${h.fg("warning",`[${t.join(". ")}]`)}`,0,0))}if(u!==void 0){const p=(o??Date.now())-u;if(i.isPartial||p>=100){const f=i.isPartial?E("\u5DF2\u8FD0\u884C"):E("\u8017\u65F6");e.addChild(new I(`
10
- ${h.fg("muted",`${f} ${K(p)}`)}`,0,0))}}}l(Ct,"rebuildBashResultRenderComponent");function It(e,n,i){const d=i?.operations??Ot({shellPath:i?.shellPath}),u=i?.commandPrefix,o=i?.exposeSessionEnvironment??!0,S=i?.spawnHook;return{name:n.name,label:n.label,description:`Execute a ${n.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${wt} lines or ${N/1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,promptSnippet:n.promptSnippet,promptGuidelines:o&&n.promptGuidelines?[...n.promptGuidelines]:void 0,executionMode:"sequential",parameters:$t,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(s,{command:a,timeout:m},c,t,p){const f=u?`${u}
11
- ${a}`:a,$=Pt(f,p?.cwd||e,S,o,p),O=new lt({tempFilePrefix:n.tempFilePrefix});let P=!0,L,M=!1,B=0;const A=l(()=>{if(!t||!M)return;M=!1,B=Date.now();const r=O.snapshot({persistIfTruncated:!0});t({content:[{type:"text",text:r.content||""}],details:{truncation:r.truncation.truncated?r.truncation:void 0,fullOutputPath:r.fullOutputPath}})},"emitOutputUpdate"),F=l(()=>{L&&(clearTimeout(L),L=void 0)},"clearUpdateTimer"),Y=l(()=>{if(!t)return;M=!0;const r=gt-(Date.now()-B);if(r<=0){F(),A();return}L??=setTimeout(()=>{L=void 0,A()},r)},"scheduleOutputUpdate");t&&t({content:[],details:void 0});const q=l(r=>{P&&(O.append(r),Y())},"handleData"),R=l(async()=>{P=!1,O.finish(),F(),A();const r=O.snapshot({persistIfTruncated:!0});return await O.closeTempFile(),r},"finishOutput"),W=l((r,C="(no output)")=>{const w=r.truncation;let g=r.content||C,T;if(w.truncated){T={truncation:w,fullOutputPath:r.fullOutputPath};const y=w.totalLines-w.outputLines+1,x=w.totalLines;if(w.lastLinePartial){const k=D(O.getLastLineBytes());g+=`
6
+ `).map(m=>h.fg("toolOutput",m)).join(`
7
+ `);i.expanded?n.addChild(new y(`
8
+ ${t}`,0,0)):n.addChild({render:u(m=>{if(r.cachedLines===void 0||r.cachedWidth!==m){const f=rt(t,Ct,m);r.cachedLines=f.visualLines,r.cachedSkipped=f.skippedCount,r.cachedWidth=m}if(r.cachedSkipped&&r.cachedSkipped>0){const f=h.fg("muted",_(E("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:r.cachedSkipped}))+` ${ot("app.tools.expand",E("\u5373\u53EF\u5C55\u5F00"))}${h.fg("muted",")")}`;return["",nt(f,m,"..."),...r.cachedLines??[]]}return["",...r.cachedLines??[]]},"render"),invalidate:u(()=>{r.cachedWidth=void 0,r.cachedLines=void 0,r.cachedSkipped=void 0},"invalidate")})}if(p?.truncated||c){const t=[];c&&t.push(_(E("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:c})),p?.truncated&&(p.truncatedBy==="lines"?t.push(_(E("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:p.outputLines,total:p.totalLines})):t.push(_(E("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:p.outputLines,limit:D(p.maxBytes??B)}))),n.addChild(new y(`
9
+ ${h.fg("warning",`[${t.join(". ")}]`)}`,0,0))}if(l!==void 0){const m=(o??Date.now())-l;if(i.isPartial||m>=100){const f=i.isPartial?E("\u5DF2\u8FD0\u884C"):E("\u8017\u65F6");n.addChild(new y(`
10
+ ${h.fg("muted",`${f} ${K(m)}`)}`,0,0))}}}u(yt,"rebuildBashResultRenderComponent");function It(n,e,i){const d=i?.operations??Pt({shellPath:i?.shellPath}),l=i?.commandPrefix,o=i?.exposeSessionEnvironment??!0,S=i?.spawnHook;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 ${St} lines or ${B/1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,promptSnippet:e.promptSnippet,promptGuidelines:o&&e.promptGuidelines?[...e.promptGuidelines]:void 0,executionMode:"sequential",executionModeFor:e.readOnlyCommand&&!l?r=>e.readOnlyCommand?.(r?.command)?"parallel":void 0:void 0,parameters:Ot,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(r,{command:a,timeout:p},c,t,m){const f=l?`${l}
11
+ ${a}`:a,$=xt(f,m?.cwd||n,S,o,m),T=new ct({tempFilePrefix:e.tempFilePrefix});let P=!0,x,M=!1,N=0;const F=u(()=>{if(!t||!M)return;M=!1,N=Date.now();const s=T.snapshot({persistIfTruncated:!0});t({content:[{type:"text",text:s.content||""}],details:{truncation:s.truncation.truncated?s.truncation:void 0,fullOutputPath:s.fullOutputPath}})},"emitOutputUpdate"),A=u(()=>{x&&(clearTimeout(x),x=void 0)},"clearUpdateTimer"),Y=u(()=>{if(!t)return;M=!0;const s=Lt-(Date.now()-N);if(s<=0){A(),F();return}x??=setTimeout(()=>{x=void 0,F()},s)},"scheduleOutputUpdate");t&&t({content:[],details:void 0});const q=u(s=>{P&&(T.append(s),Y())},"handleData"),R=u(async()=>{P=!1,T.finish(),A(),F();const s=T.snapshot({persistIfTruncated:!0});return await T.closeTempFile(),s},"finishOutput"),W=u((s,g="(no output)")=>{const w=s.truncation;let C=s.content||g,O;if(w.truncated){O={truncation:w,fullOutputPath:s.fullOutputPath};const v=w.totalLines-w.outputLines+1,L=w.totalLines;if(w.lastLinePartial){const k=D(T.getLastLineBytes());C+=`
12
12
 
13
- [Showing last ${D(w.outputBytes)} of line ${x} (line is ${k}). Full output: ${r.fullOutputPath}]`}else w.truncatedBy==="lines"?g+=`
13
+ [Showing last ${D(w.outputBytes)} of line ${L} (line is ${k}). Full output: ${s.fullOutputPath}]`}else w.truncatedBy==="lines"?C+=`
14
14
 
15
- [Showing lines ${y}-${x} of ${w.totalLines}. Full output: ${r.fullOutputPath}]`:g+=`
15
+ [Showing lines ${v}-${L} of ${w.totalLines}. Full output: ${s.fullOutputPath}]`:C+=`
16
16
 
17
- [Showing lines ${y}-${x} of ${w.totalLines} (${D(N)} limit). Full output: ${r.fullOutputPath}]`}return{text:g,details:T}},"formatOutput"),v=l((r,C)=>`${r?`${r}
17
+ [Showing lines ${v}-${L} of ${w.totalLines} (${D(B)} limit). Full output: ${s.fullOutputPath}]`}return{text:C,details:O}},"formatOutput"),b=u((s,g)=>`${s?`${s}
18
18
 
19
- `:""}${C}`,"appendStatus");try{let r;try{r=(await d.exec($.command,$.cwd,{onData:q,signal:c,timeout:m,env:$.env})).exitCode}catch(T){const y=await R(),{text:x}=W(y,"");if(T instanceof Error&&T.message==="aborted")throw new Error(v(x,"Command aborted"));if(T instanceof Error&&T.message.startsWith("timeout:")){const k=T.message.split(":")[1];throw new Error(v(x,`Command timed out after ${k} seconds`))}throw T}const C=await R(),{text:w,details:g}=W(C);if(r===null)throw new Error(v(w,"Command terminated without an exit code"));if(r!==0)throw new Error(v(w,`Command exited with code ${r}`));return{content:[{type:"text",text:w}],details:g}}finally{F()}},renderCall(s,a,m){const c=m.state;m.executionStarted&&c.startedAt===void 0&&(c.startedAt=Date.now(),c.endedAt=void 0);const t=m.lastComponent??new I("",0,0);return t.setText(_t(s,n.prompt,m.expanded===!0)),t},renderResult(s,a,m,c){const t=c.state;t.startedAt!==void 0&&a.isPartial&&!t.interval&&(t.interval=setInterval(()=>c.invalidate(),1e3)),(!a.isPartial||c.isError)&&(t.endedAt??=Date.now(),t.interval&&(clearInterval(t.interval),t.interval=void 0));const p=c.lastComponent??new xt;return Ct(p,s,a,c.showImages,t.startedAt,t.endedAt,c.isError),p.invalidate(),p}}}l(It,"createShellToolDefinition");const bt={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:z.snippet,promptGuidelines:z.guidelines,tempFilePrefix:"pi-bash"};function vt(e,n){return It(e,bt,n)}l(vt,"createBashToolDefinition");function Kt(e,n){const i=vt(e,n),d=ht(i);return Object.assign(d,{promptSnippet:i.promptSnippet,promptGuidelines:i.promptGuidelines}),d}l(Kt,"createBashTool");export{z as bashToolSystemPromptContribution,Kt as createBashTool,vt as createBashToolDefinition,Ot as createLocalBashOperations,Tt as createLocalShellOperations,It as createShellToolDefinition};
19
+ `:""}${g}`,"appendStatus");try{let s;try{s=(await d.exec($.command,$.cwd,{onData:q,signal:c,timeout:p,env:$.env})).exitCode}catch(O){const v=await R(),{text:L}=W(v,"");if(O instanceof Error&&O.message==="aborted")throw new Error(b(L,"Command aborted"));if(O instanceof Error&&O.message.startsWith("timeout:")){const k=O.message.split(":")[1];throw new Error(b(L,`Command timed out after ${k} seconds`))}throw O}const g=await R(),{text:w,details:C}=W(g);if(s===null)throw new Error(b(w,"Command terminated without an exit code"));if(s!==0)throw new Error(b(w,`Command exited with code ${s}`));return{content:[{type:"text",text:w}],details:C}}finally{A()}},renderCall(r,a,p){const c=p.state;p.executionStarted&&c.startedAt===void 0&&(c.startedAt=Date.now(),c.endedAt=void 0);const t=p.lastComponent??new y("",0,0);return t.setText(gt(r,e.prompt,p.expanded===!0)),t},renderResult(r,a,p,c){const t=c.state;t.startedAt!==void 0&&a.isPartial&&!t.interval&&(t.interval=setInterval(()=>c.invalidate(),1e3)),(!a.isPartial||c.isError)&&(t.endedAt??=Date.now(),t.interval&&(clearInterval(t.interval),t.interval=void 0));const m=c.lastComponent??new _t;return yt(m,r,a,c.showImages,t.startedAt,t.endedAt,c.isError),m.invalidate(),m}}}u(It,"createShellToolDefinition");const bt={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:z.snippet,promptGuidelines:z.guidelines,tempFilePrefix:"pi-bash",readOnlyCommand:ut};function vt(n,e){return It(n,bt,e)}u(vt,"createBashToolDefinition");function qt(n,e){const i=vt(n,e),d=wt(i);return Object.assign(d,{promptSnippet:i.promptSnippet,promptGuidelines:i.promptGuidelines}),d}u(qt,"createBashTool");export{z as bashToolSystemPromptContribution,qt as createBashTool,vt as createBashToolDefinition,Pt as createLocalBashOperations,Tt as createLocalShellOperations,It as createShellToolDefinition};
@@ -1 +1 @@
1
- var s=Object.defineProperty;var a=(e,r)=>s(e,"name",{value:r,configurable:!0});function u(e,r){return{name:e.name,label:e.label,description:e.description,parameters:e.parameters,constrainedSampling:e.constrainedSampling,prepareArguments:e.prepareArguments,executionMode:e.executionMode,execute:a((n,p,t,c,m)=>e.execute(n,p,t,c,m??r?.()),"execute")}}a(u,"wrapToolDefinition");function i(e,r){return e.map(n=>u(n,r))}a(i,"wrapToolDefinitions");function x(e){return{name:e.name,label:e.label,description:e.description,parameters:e.parameters,constrainedSampling:e.constrainedSampling,prepareArguments:e.prepareArguments,executionMode:e.executionMode,execute:a(async(r,n,p,t)=>e.execute(r,n,p,t),"execute")}}a(x,"createToolDefinitionFromAgentTool");export{x as createToolDefinitionFromAgentTool,u as wrapToolDefinition,i as wrapToolDefinitions};
1
+ var u=Object.defineProperty;var a=(e,r)=>u(e,"name",{value:r,configurable:!0});function m(e,r){return{name:e.name,label:e.label,description:e.description,parameters:e.parameters,constrainedSampling:e.constrainedSampling,prepareArguments:e.prepareArguments,executionMode:e.executionMode,executionModeFor:e.executionModeFor,execute:a((n,p,t,c,o)=>e.execute(n,p,t,c,o??r?.()),"execute")}}a(m,"wrapToolDefinition");function x(e,r){return e.map(n=>m(n,r))}a(x,"wrapToolDefinitions");function i(e){return{name:e.name,label:e.label,description:e.description,parameters:e.parameters,constrainedSampling:e.constrainedSampling,prepareArguments:e.prepareArguments,executionMode:e.executionMode,executionModeFor:e.executionModeFor,execute:a(async(r,n,p,t)=>e.execute(r,n,p,t),"execute")}}a(i,"createToolDefinitionFromAgentTool");export{i as createToolDefinitionFromAgentTool,m as wrapToolDefinition,x as wrapToolDefinitions};