dal-code 1.0.41 → 1.0.42

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 (87) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/NOTICE +2 -1
  3. package/PRIVACY.md +6 -0
  4. package/dist/cli/startup-ui.js +1 -1
  5. package/dist/core/bug-report.js +5 -5
  6. package/dist/core/settings-manager.d.ts +0 -5
  7. package/dist/core/settings-manager.js +1 -1
  8. package/dist/modes/rpc/rpc-client.d.ts +5 -1
  9. package/dist/modes/rpc/rpc-client.js +3 -3
  10. package/dist/modes/rpc/rpc-mode.js +1 -1
  11. package/dist/modes/rpc/rpc-types.d.ts +25 -0
  12. package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
  13. package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
  14. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  15. package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
  16. package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
  17. package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
  18. package/dist/node_modules/@dalcode/dal-dap/src/install.js +2 -2
  19. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  20. package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
  21. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  22. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  23. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  24. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  25. package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
  26. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  27. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  28. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  29. package/dist/node_modules/@dalcode/dal-office/src/index.d.ts +1 -0
  30. package/dist/node_modules/@dalcode/dal-office/src/index.js +1 -1
  31. package/dist/node_modules/@dalcode/dal-office/src/render/deck-source.d.ts +10 -0
  32. package/dist/node_modules/@dalcode/dal-office/src/render/deck-source.js +2 -0
  33. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.js +3 -3
  34. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
  35. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  36. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
  37. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  38. package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
  39. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  40. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  41. package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
  42. package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
  43. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  44. package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
  45. package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
  46. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  47. package/dist/node_modules/@dalcode/dal-telemetry/package.json +4 -3
  48. package/dist/node_modules/@dalcode/dal-telemetry/src/config.js +3 -3
  49. package/dist/node_modules/@dalcode/dal-telemetry/src/consent.js +1 -0
  50. package/dist/node_modules/@dalcode/dal-telemetry/src/failure-reporting.js +2 -2
  51. package/dist/node_modules/@dalcode/dal-telemetry/src/index.js +4 -4
  52. package/dist/node_modules/@dalcode/dal-telemetry/src/reporter.js +1 -1
  53. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  54. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  55. package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
  56. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  57. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  58. package/dist/node_modules/@dalcode/dal-workflow/src/lean-code.js +1 -1
  59. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  60. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  61. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  62. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  63. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
  64. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  65. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  66. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
  67. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  68. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  69. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  70. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  71. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  72. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  73. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  74. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  75. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  76. package/dist/sdk/index.d.ts +1 -1
  77. package/dist/sdk/office.d.ts +1 -1
  78. package/dist/sdk/office.js +1 -1
  79. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  80. package/examples/extensions/gondolin/package-lock.json +2 -2
  81. package/examples/extensions/gondolin/package.json +1 -1
  82. package/examples/extensions/sandbox/package-lock.json +2 -2
  83. package/examples/extensions/sandbox/package.json +1 -1
  84. package/examples/extensions/with-deps/package-lock.json +2 -2
  85. package/examples/extensions/with-deps/package.json +1 -1
  86. package/npm-shrinkwrap.json +2 -2
  87. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -8,6 +8,12 @@ DAL Code 的发布说明。这里只写用户看得见的变化。
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [1.0.42] - 2026-10-18
12
+
13
+ - 助手生成的 PPT 会在文件里一并保存这份演示的大纲和所用风格:在 DAL Code 里对它「换风格」时直接按原内容重新排版,不用再让助手重做一遍。用 PowerPoint、WPS、Keynote 打开不受影响。
14
+ - 在 DAL Code 桌面应用里回答"是否允许发送匿名使用统计 / 失败症状"后,选择会立即生效,不用重启:选"不允许"时立刻停止,尚未发出的内容直接丢弃,不会再发(在终端里用 `/telemetry off` 关闭时也是如此)。你之前在终端里拒绝过的,桌面应用不会把它改回"允许"。
15
+ - “精简改动”改为默认开启:在内部评测里,开启后通过率不变,平均少走一轮,改动的代码行数少了约一成。助手会优先复用项目里已有的代码,不加任务用不到的抽象和配置;输入校验、错误处理和安全照常保留。不想要的话在设置里写 `leanCode: false`,或设环境变量 `DAL_LEAN_CODE=off`。
16
+
11
17
  ## [1.0.41] - 2026-10-18
12
18
 
13
19
  - 长对话不再因为“上下文超长”先失败一次:快接近模型上限时(按模型的上下文窗口减去给回答预留的空间来算),会在发出请求之前就先压缩,包括你刚贴进一大段内容、或者接着一个很长的旧会话提问的时候。压缩时界面会显示“正在压缩”。压缩后紧接着的那次请求就带上待办清单和任务台账,助手不会忘了做到哪一步。
package/NOTICE CHANGED
@@ -234,7 +234,8 @@ pinned to one version and checked against its SHA-256:
234
234
  Microsoft Corporation, MIT License; its LICENSE ships inside the package.
235
235
  vscode-js-debug 1.140.0 (https://github.com/microsoft/vscode-js-debug),
236
236
  Copyright (c) Microsoft Corporation, MIT License; its LICENSE ships inside
237
- the downloaded archive.
237
+ the downloaded archive. The same archive, unchanged, is redistributed as the
238
+ npm package @deepailab/js-debug-dap, with that LICENSE alongside it.
238
239
 
239
240
  The visual skills (@dalcode/dal-skills: src/bundled/web-design,
240
241
  diagram-design, poster-design, print-design and the shared
package/PRIVACY.md CHANGED
@@ -70,6 +70,12 @@ export DO_NOT_TRACK=1 # 跨厂商通用约定
70
70
  一旦你用 `/telemetry off` 关闭,**环境变量无法把它重新打开**。
71
71
  用 `/telemetry` 可查看当前状态和关闭原因。
72
72
 
73
+ 在 DAL Code 桌面应用里,同一个问题由桌面应用在自己的窗口里问,你的回答会交给 `dal` 记下,
74
+ 效果与 `/telemetry on|off` 相同,立即生效;选"不允许"时尚未发出的内容会直接丢弃。
75
+ 桌面应用启动 `dal` 时也可以通过 `DAL_TELEMETRY_CONSENT=granted|denied`
76
+ (失败症状为 `DAL_FAILURE_REPORTS_CONSENT`)带上你在桌面里的选择,但这只在你还没有在 `dal` 里
77
+ 做过选择时才会被采用:**你在 `dal` 里拒绝过的,桌面应用或环境变量都无法改回"允许"**。
78
+
73
79
  你的选择与匿名 ID 存放在 `~/.dal/agent/telemetry.json`(权限 0600),只在你回答后才写入;
74
80
  删除该文件等同于重置(重新变为未同意)。
75
81
 
@@ -1 +1 @@
1
- var A=Object.defineProperty;var o=(e,t)=>A(e,"name",{value:t,configurable:!0});import{ProcessTerminal as g,setCapabilityOverrides as y,setKeybindings as v,TuiMainScreen as F}from"@earendil-works/pi-tui";import{existsSync as P}from"fs";import{APP_NAME as _,CONFIG_DIR_NAME as N,ENV_AGENT_DIR as I,getAgentDir as T,getSettingsPath as b,PACKAGE_NAME as x}from"../config.js";import{areExperimentalFeaturesEnabled as M}from"../core/experimental.js";import{KeybindingsManager as O}from"../core/keybindings.js";import{DefaultPackageManager as k}from"../core/package-manager.js";import{SettingsManager as D}from"../core/settings-manager.js";import{ExtensionInputComponent as R}from"../modes/interactive/components/extension-input.js";import{ExtensionSelectorComponent as G}from"../modes/interactive/components/extension-selector.js";import{FirstTimeSetupComponent as q}from"../modes/interactive/components/first-time-setup.js";import{SYSTEM_THEME_NAME as w}from"../modes/interactive/theme/system-theme.js";import{DEFAULT_THEME_SETTING as l,getTerminalTheme as p,initTheme as K,loadThemeFromPath as L,markTerminalColorsPending as H,resolveThemeSetting as d,setRegisteredThemes as j,setTerminalColors as U,setTheme as u}from"../modes/interactive/theme/theme.js";import{requestTerminalColors as V}from"../modes/interactive/theme/theme-controller.js";const Y="@earendil-works/pi-coding-agent",z="pi",B=".pi";function J({packageName:e,appName:t,configDirName:i}){return e===Y&&t===z&&i===B}o(J,"isOfficialDistribution");function Q(e){const t=[],i=new Set;for(const n of e)if(n.enabled)try{const a=L(n.path);if(a.name){if(i.has(a.name))continue;i.add(a.name)}t.push(a)}catch{}return t}o(Q,"loadThemes");async function W(e){const t=D.inMemory(e.getGlobalSettings(),{projectTrusted:!1}),n=await new k({cwd:process.cwd(),agentDir:T(),settingsManager:t}).resolve(async()=>"skip");return Q(n.themes)}o(W,"loadStartupThemes");async function f(e){y(e.getTerminalCapabilityOverrides()),j(await W(e)),H(),K(d(e.getThemeSetting()??l,p())??w),v(O.create());const t=new F(new g,e.getShowHardwareCursor(),T());return t.setClearOnShrink(e.getClearOnShrink()),t}o(f,"createStartupTui");function S(e,t){e.start();const i=t.getThemeSetting();C(e,()=>{u(d(i??l,p())??w)})}o(S,"startStartupTui");function C(e,t){V(e,i=>{U(i),t(),e.invalidate(),e.requestRender()})}o(C,"queryStartupTerminalColors");async function h(e){e.clear(),e.requestRender(),await new Promise(t=>setTimeout(t,25))}o(h,"clearStartupTui");function le(e=b()){return!J({packageName:x,appName:_,configDirName:N})||!M()||process.env[I]?!1:!P(e)}o(le,"shouldRunFirstTimeSetup");async function pe(e,t,i){const n=await f(e);return new Promise(a=>{let m=!1;const s=o(async r=>{m||(m=!0,await h(n),n.stop(),a(r))},"finish"),c=new G(t,i.map(r=>r.label),r=>{s(i.find(E=>E.label===r)?.value)},()=>{s(void 0)},{tui:n});n.addChild(c),n.setFocus(c),S(n,e)})}o(pe,"showStartupSelector");async function de(e){const t=await f(e);return new Promise(i=>{let n=!1;const a=o(async r=>{n||(n=!0,r&&(e.setTheme(r.theme),e.setEnableAnalytics(r.shareAnalytics),await e.flush()),await h(t),t.stop(),i())},"finish");t.start();const m=o(r=>d(r,p())??r,"concrete");let s=m(l);u(s);const c=new q({onThemePreview:o(r=>{s=m(r),u(s),t.requestRender()},"onThemePreview"),onSubmit:o(r=>{a(r)},"onSubmit"),onCancel:o(()=>{a(void 0)},"onCancel")});t.addChild(c),t.setFocus(c),t.requestRender(),C(t,()=>u(s))})}o(de,"showFirstTimeSetup");async function fe(e,t,i){const n=await f(e);return new Promise(a=>{let m=!1;const s=o(async r=>{m||(m=!0,c.dispose(),await h(n),n.stop(),a(r))},"finish"),c=new R(t,i,r=>{s(r)},()=>{s(void 0)},{tui:n});n.addChild(c),n.setFocus(c),S(n,e)})}o(fe,"showStartupInput");export{f as createStartupTui,le as shouldRunFirstTimeSetup,de as showFirstTimeSetup,fe as showStartupInput,pe as showStartupSelector,S as startStartupTui};
1
+ var g=Object.defineProperty;var o=(e,t)=>g(e,"name",{value:t,configurable:!0});import{ProcessTerminal as C,setCapabilityOverrides as y,setKeybindings as _,TuiMainScreen as v}from"@earendil-works/pi-tui";import{existsSync as P}from"fs";import{APP_NAME as F,CONFIG_DIR_NAME as N,ENV_AGENT_DIR as b,getAgentDir as h,getSettingsPath as I,PACKAGE_NAME as x}from"../config.js";import{areExperimentalFeaturesEnabled as M}from"../core/experimental.js";import{KeybindingsManager as O}from"../core/keybindings.js";import{DefaultPackageManager as R}from"../core/package-manager.js";import{SettingsManager as k}from"../core/settings-manager.js";import{ExtensionInputComponent as D}from"../modes/interactive/components/extension-input.js";import{ExtensionSelectorComponent as G}from"../modes/interactive/components/extension-selector.js";import{FirstTimeSetupComponent as q}from"../modes/interactive/components/first-time-setup.js";import{SYSTEM_THEME_NAME as S}from"../modes/interactive/theme/system-theme.js";import{DEFAULT_THEME_SETTING as l,getTerminalTheme as p,initTheme as L,loadThemeFromPath as K,markTerminalColorsPending as H,resolveThemeSetting as d,setRegisteredThemes as U,setTerminalColors as Y,setTheme as u}from"../modes/interactive/theme/theme.js";import{requestTerminalColors as j}from"../modes/interactive/theme/theme-controller.js";const V="@earendil-works/pi-coding-agent",W="pi",z=".pi";function B({packageName:e,appName:t,configDirName:i}){return e===V&&t===W&&i===z}o(B,"isOfficialDistribution");function J(e){const t=[],i=new Set;for(const n of e)if(n.enabled)try{const a=K(n.path);if(a.name){if(i.has(a.name))continue;i.add(a.name)}t.push(a)}catch{}return t}o(J,"loadThemes");async function Q(e){const t=k.inMemory(e.getGlobalSettings(),{projectTrusted:!1}),n=await new R({cwd:process.cwd(),agentDir:h(),settingsManager:t}).resolve(async()=>"skip");return J(n.themes)}o(Q,"loadStartupThemes");async function f(e){y(e.getTerminalCapabilityOverrides()),U(await Q(e)),H(),L(d(e.getThemeSetting()??l,p())??S),_(O.create());const t=new v(new C,e.getShowHardwareCursor(),h());return t.setClearOnShrink(e.getClearOnShrink()),t}o(f,"createStartupTui");function w(e,t){e.start();const i=t.getThemeSetting();E(e,()=>{u(d(i??l,p())??S)})}o(w,"startStartupTui");function E(e,t){j(e,i=>{Y(i),t(),e.invalidate(),e.requestRender()})}o(E,"queryStartupTerminalColors");async function T(e){e.clear(),e.requestRender(),await new Promise(t=>setTimeout(t,25))}o(T,"clearStartupTui");function de(e=I()){return!B({packageName:x,appName:F,configDirName:N})||!M()||process.env[b]?!1:!P(e)}o(de,"shouldRunFirstTimeSetup");async function fe(e,t,i){const n=await f(e);return new Promise(a=>{let m=!1;const s=o(async r=>{m||(m=!0,await T(n),n.stop(),a(r))},"finish"),c=new G(t,i.map(r=>r.label),r=>{s(i.find(A=>A.label===r)?.value)},()=>{s(void 0)},{tui:n});n.addChild(c),n.setFocus(c),w(n,e)})}o(fe,"showStartupSelector");const X=Symbol.for("dalcode.telemetry.startupAnswer");function Z(e){globalThis[X]=e}o(Z,"handOverStartupTelemetryAnswer");async function Te(e){const t=await f(e);return new Promise(i=>{let n=!1;const a=o(async r=>{n||(n=!0,r&&(e.setTheme(r.theme),Z(r.shareAnalytics),await e.flush()),await T(t),t.stop(),i())},"finish");t.start();const m=o(r=>d(r,p())??r,"concrete");let s=m(l);u(s);const c=new q({onThemePreview:o(r=>{s=m(r),u(s),t.requestRender()},"onThemePreview"),onSubmit:o(r=>{a(r)},"onSubmit"),onCancel:o(()=>{a(void 0)},"onCancel")});t.addChild(c),t.setFocus(c),t.requestRender(),E(t,()=>u(s))})}o(Te,"showFirstTimeSetup");async function he(e,t,i){const n=await f(e);return new Promise(a=>{let m=!1;const s=o(async r=>{m||(m=!0,c.dispose(),await T(n),n.stop(),a(r))},"finish"),c=new D(t,i,r=>{s(r)},()=>{s(void 0)},{tui:n});n.addChild(c),n.setFocus(c),w(n,e)})}o(he,"showStartupInput");export{X as STARTUP_TELEMETRY_ANSWER_SLOT,f as createStartupTui,Z as handOverStartupTelemetryAnswer,de as shouldRunFirstTimeSetup,Te as showFirstTimeSetup,he as showStartupInput,fe as showStartupSelector,w as startStartupTui};
@@ -1,8 +1,8 @@
1
- var R=Object.defineProperty;var o=(e,t)=>R(e,"name",{value:t,configurable:!0});import*as g from"node:os";import{contentText as T,normalizeContext as x,uuidv7 as E}from"@earendil-works/pi-ai";import{APP_TITLE as h,VERSION as f}from"../config.js";import{getPiUserAgent as I}from"../utils/pi-user-agent.js";import{writeZipArchive as _}from"../utils/zip.js";import{completeSummarization as O,getSummarizationFailure as b}from"./compaction/compaction.js";import{estimateTokens as k,serializeConversation as M}from"./compaction/utils.js";import{convertToLlm as N}from"./messages.js";const H="pi.bug-report",y=1,v="<redacted>",P=/(?:^|[-_])(api[-_]?key|secret|token|password|passwd|credential|authorization|cookie)(?:$|[-_])/i;function w(e){return P.test(e.replace(/([a-z0-9])([A-Z])/g,"$1_$2"))}o(w,"isSensitiveKey");function u(e){const t=/^([a-z][a-z0-9+.-]*:)([a-z][a-z0-9+.-]*:\/\/.*)$/i.exec(e);if(t)return`${t[1]}${u(t[2])}`;try{const n=new URL(e);let s=!1;(n.username||n.password)&&(n.username="",n.password="",s=!0);for(const a of n.searchParams.keys())w(a)&&(n.searchParams.set(a,v),s=!0);return s?n.toString():e}catch{return e}}o(u,"redactUrl");function m(e){if(e!==void 0)return JSON.parse(JSON.stringify(e,(t,n)=>n!=null&&w(t)?v:typeof n=="string"?u(n):n))}o(m,"redactJsonValue");function S(e){const{trackingId:t,deviceId:n,...s}=e;return m(s)}o(S,"redactSettings");function U(){const e=o(t=>process.env[t]||null,"env");return{version:f,userAgent:I(f),runtime:process.versions.bun?`bun/${process.versions.bun}`:`node/${process.version}`,platform:process.platform,arch:process.arch,osRelease:g.release(),osVersion:g.version(),shell:process.env.SHELL?.split(/[\\/]/).pop()||null,terminal:{term:e("TERM"),program:e("TERM_PROGRAM"),programVersion:e("TERM_PROGRAM_VERSION"),colorterm:e("COLORTERM"),tmux:!!process.env.TMUX,ssh:!!(process.env.SSH_CONNECTION||process.env.SSH_CLIENT||process.env.SSH_TTY),ci:!!process.env.CI},piEnvironmentVariables:Object.keys(process.env).filter(t=>t.startsWith("PI_")).sort()}}o(U,"collectEnvironment");function $(e){return{provider:e.provider,id:e.id,name:e.name,api:e.api,baseUrl:u(e.baseUrl),reasoning:e.reasoning,input:e.input,contextWindow:e.contextWindow,maxTokens:e.maxTokens,samplingParams:e.samplingParams?m(e.samplingParams):null,compat:e.compat?m(e.compat):null,thinkingLevelMap:e.thinkingLevelMap??null,headerNames:Object.keys(e.headers??{}).sort()}}o($,"describeModel");function A(e,t){const n=[];return t.auth.apiKey&&n.push("api_key"),t.auth.oauth&&n.push("oauth"),{id:t.id,name:t.name,baseUrl:t.baseUrl?u(t.baseUrl):null,headerNames:Object.keys(t.headers??{}).sort(),authTypes:n,authStatus:e.getProviderAuthStatus(t.id),usingOAuth:e.isUsingOAuth(t.id),registeredByExtension:e.getRegisteredProviderIds().includes(t.id)}}o(A,"describeProvider");function C(e){return{path:e.path,source:u(e.sourceInfo.source),scope:e.sourceInfo.scope,origin:e.sourceInfo.origin,hidden:e.hidden===!0}}o(C,"describeExtension");function q(e){const t=e.hint?.trim()||null,n=e.model?e.modelRuntime.getProvider(e.model.provider):void 0;return{schemaVersion:y,id:e.id??E(),createdAt:new Date().toISOString(),hint:t,environment:U(),session:{id:e.sessionId,included:e.includeSession,summaryIncluded:e.includeSummary,messageCount:e.messageCount,...e.includeSession?{cwd:e.cwd}:{}},model:e.model?$(e.model):null,provider:n?A(e.modelRuntime,n):null,thinkingLevel:e.thinkingLevel,extensions:e.extensions.map(C),extensionErrors:e.extensionErrors.map(({path:s,error:a})=>({path:s,error:a})),settings:{global:S(e.globalSettings),project:S(e.projectSettings)}}}o(q,"collectBugReportMetadata");function Z(e,t=[]){const n=e.getEntries(),s=[];let a=0;for(const i of n){if(i.type!=="message"||i.message.role!=="assistant")continue;a++;const r=i.message,c=r.diagnostics??[];c.length===0&&r.stopReason!=="error"&&r.stopReason!=="aborted"&&!r.errorMessage||s.push({entryId:i.id,timestamp:i.timestamp,provider:r.provider,model:r.model,api:r.api,stopReason:r.stopReason,...r.rawStopReason===void 0?{}:{rawStopReason:r.rawStopReason},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},diagnostics:c})}return{schemaVersion:y,sessionId:e.getSessionId(),entryCount:n.length,assistantMessageCount:a,assistant:s,crashes:t.map(({notified:i,...r})=>r)}}o(Z,"collectBugReportDiagnostics");function B(e){const t=[{name:"report.json",contentType:"application/json",data:`${JSON.stringify(e.metadata,null,2)}
1
+ var R=Object.defineProperty;var s=(e,t)=>R(e,"name",{value:t,configurable:!0});import*as g from"node:os";import{contentText as T,normalizeContext as x,uuidv7 as E}from"@earendil-works/pi-ai";import{APP_TITLE as h,VERSION as f}from"../config.js";import{getPiUserAgent as I}from"../utils/pi-user-agent.js";import{writeZipArchive as O}from"../utils/zip.js";import{completeSummarization as _,getSummarizationFailure as b}from"./compaction/compaction.js";import{estimateTokens as k,serializeConversation as M}from"./compaction/utils.js";import{convertToLlm as N}from"./messages.js";const H="pi.bug-report",y=1,v="<redacted>",P=/(?:^|[-_])(api[-_]?key|secret|token|password|passwd|credential|authorization|cookie)(?:$|[-_])/i;function w(e){return P.test(e.replace(/([a-z0-9])([A-Z])/g,"$1_$2"))}s(w,"isSensitiveKey");function u(e){const t=/^([a-z][a-z0-9+.-]*:)([a-z][a-z0-9+.-]*:\/\/.*)$/i.exec(e);if(t)return`${t[1]}${u(t[2])}`;try{const n=new URL(e);let o=!1;(n.username||n.password)&&(n.username="",n.password="",o=!0);for(const a of n.searchParams.keys())w(a)&&(n.searchParams.set(a,v),o=!0);return o?n.toString():e}catch{return e}}s(u,"redactUrl");function m(e){if(e!==void 0)return JSON.parse(JSON.stringify(e,(t,n)=>n!=null&&w(t)?v:typeof n=="string"?u(n):n))}s(m,"redactJsonValue");function S(e){const{deviceId:t,...n}=e;return m(n)}s(S,"redactSettings");function U(){const e=s(t=>process.env[t]||null,"env");return{version:f,userAgent:I(f),runtime:process.versions.bun?`bun/${process.versions.bun}`:`node/${process.version}`,platform:process.platform,arch:process.arch,osRelease:g.release(),osVersion:g.version(),shell:process.env.SHELL?.split(/[\\/]/).pop()||null,terminal:{term:e("TERM"),program:e("TERM_PROGRAM"),programVersion:e("TERM_PROGRAM_VERSION"),colorterm:e("COLORTERM"),tmux:!!process.env.TMUX,ssh:!!(process.env.SSH_CONNECTION||process.env.SSH_CLIENT||process.env.SSH_TTY),ci:!!process.env.CI},piEnvironmentVariables:Object.keys(process.env).filter(t=>t.startsWith("PI_")).sort()}}s(U,"collectEnvironment");function $(e){return{provider:e.provider,id:e.id,name:e.name,api:e.api,baseUrl:u(e.baseUrl),reasoning:e.reasoning,input:e.input,contextWindow:e.contextWindow,maxTokens:e.maxTokens,samplingParams:e.samplingParams?m(e.samplingParams):null,compat:e.compat?m(e.compat):null,thinkingLevelMap:e.thinkingLevelMap??null,headerNames:Object.keys(e.headers??{}).sort()}}s($,"describeModel");function A(e,t){const n=[];return t.auth.apiKey&&n.push("api_key"),t.auth.oauth&&n.push("oauth"),{id:t.id,name:t.name,baseUrl:t.baseUrl?u(t.baseUrl):null,headerNames:Object.keys(t.headers??{}).sort(),authTypes:n,authStatus:e.getProviderAuthStatus(t.id),usingOAuth:e.isUsingOAuth(t.id),registeredByExtension:e.getRegisteredProviderIds().includes(t.id)}}s(A,"describeProvider");function C(e){return{path:e.path,source:u(e.sourceInfo.source),scope:e.sourceInfo.scope,origin:e.sourceInfo.origin,hidden:e.hidden===!0}}s(C,"describeExtension");function q(e){const t=e.hint?.trim()||null,n=e.model?e.modelRuntime.getProvider(e.model.provider):void 0;return{schemaVersion:y,id:e.id??E(),createdAt:new Date().toISOString(),hint:t,environment:U(),session:{id:e.sessionId,included:e.includeSession,summaryIncluded:e.includeSummary,messageCount:e.messageCount,...e.includeSession?{cwd:e.cwd}:{}},model:e.model?$(e.model):null,provider:n?A(e.modelRuntime,n):null,thinkingLevel:e.thinkingLevel,extensions:e.extensions.map(C),extensionErrors:e.extensionErrors.map(({path:o,error:a})=>({path:o,error:a})),settings:{global:S(e.globalSettings),project:S(e.projectSettings)}}}s(q,"collectBugReportMetadata");function Z(e,t=[]){const n=e.getEntries(),o=[];let a=0;for(const i of n){if(i.type!=="message"||i.message.role!=="assistant")continue;a++;const r=i.message,c=r.diagnostics??[];c.length===0&&r.stopReason!=="error"&&r.stopReason!=="aborted"&&!r.errorMessage||o.push({entryId:i.id,timestamp:i.timestamp,provider:r.provider,model:r.model,api:r.api,stopReason:r.stopReason,...r.rawStopReason===void 0?{}:{rawStopReason:r.rawStopReason},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},diagnostics:c})}return{schemaVersion:y,sessionId:e.getSessionId(),entryCount:n.length,assistantMessageCount:a,assistant:o,crashes:t.map(({notified:i,...r})=>r)}}s(Z,"collectBugReportDiagnostics");function B(e){const t=[{name:"report.json",contentType:"application/json",data:`${JSON.stringify(e.metadata,null,2)}
2
2
  `},{name:"diagnostics.json",contentType:"application/json",data:`${JSON.stringify(e.diagnostics,null,2)}
3
3
  `}];return e.sessionJsonl!==void 0&&t.push({name:"session.jsonl",contentType:"application/x-ndjson",data:e.sessionJsonl}),e.summary!==void 0&&t.push({name:"summary.md",contentType:"text/markdown",data:e.summary.endsWith(`
4
4
  `)?e.summary:`${e.summary}
5
- `}),t}o(B,"bugReportFiles");function Q(e,t){return _(t,B(e))}o(Q,"writeBugReportArchive");function X(e){return`dal-bug-report-${e}.zip`}o(X,"bugReportArchiveFileName");const L=`You are helping a user file a bug report about ${h}, the coding agent they are talking to. You will be shown the conversation transcript. Write a report for the ${h} developers describing what the user was doing and what went wrong.
5
+ `}),t}s(B,"bugReportFiles");function Q(e,t){return O(t,B(e))}s(Q,"writeBugReportArchive");function X(e){return`dal-bug-report-${e}.zip`}s(X,"bugReportArchiveFileName");const L=`You are helping a user file a bug report about ${h}, the coding agent they are talking to. You will be shown the conversation transcript. Write a report for the ${h} developers describing what the user was doing and what went wrong.
6
6
 
7
7
  Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the report.`,j=`Write the bug report in Markdown with these sections:
8
8
 
@@ -18,10 +18,10 @@ Numbered list, as specific as the transcript allows.
18
18
  ## Relevant details
19
19
  Tool calls involved, files touched, model behavior, anything else that helps a developer reproduce or locate the problem.
20
20
 
21
- Do not include file contents, secrets, or credentials from the transcript; refer to files by path only. Keep the report factual and concise.`;function z(e,t){const n=[];let s=0;for(let a=e.length-1;a>=0;a--){const i=e[a],r=k(i);if(n.length>0&&s+r>t)break;n.push(i),s+=r}return n.reverse()}o(z,"selectMessages");async function ee(e){const{model:t}=e,n=t.contextWindow>0?t.contextWindow:128e3,s=z(e.messages,Math.floor(n*.6)),a=e.hint?.trim(),i=[s.length<e.messages.length?`Note: only the last ${s.length} of ${e.messages.length} messages are shown.`:void 0,`<conversation>
22
- ${M(N(s))}
21
+ Do not include file contents, secrets, or credentials from the transcript; refer to files by path only. Keep the report factual and concise.`;function z(e,t){const n=[];let o=0;for(let a=e.length-1;a>=0;a--){const i=e[a],r=k(i);if(n.length>0&&o+r>t)break;n.push(i),o+=r}return n.reverse()}s(z,"selectMessages");async function ee(e){const{model:t}=e,n=t.contextWindow>0?t.contextWindow:128e3,o=z(e.messages,Math.floor(n*.6)),a=e.hint?.trim(),i=[o.length<e.messages.length?`Note: only the last ${o.length} of ${e.messages.length} messages are shown.`:void 0,`<conversation>
22
+ ${M(N(o))}
23
23
  </conversation>`,a?`<user-report>
24
24
  ${a}
25
25
  </user-report>`:void 0,j].filter(l=>l!==void 0).join(`
26
26
 
27
- `),r={maxTokens:Math.min(4096,t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY),signal:e.signal,apiKey:e.apiKey,headers:e.headers,env:e.env,sessionId:e.sessionId,...t.reasoning&&e.thinkingLevel&&e.thinkingLevel!=="off"?{reasoning:e.thinkingLevel}:{}},c=await O(t,x({systemPrompt:L,messages:[{role:"user",content:[{type:"text",text:i}],timestamp:Date.now()}]}),r,e.streamFn,e.retry);if(c.stopReason==="aborted")throw new Error("Bug report summary was cancelled");const p=b(c,"Bug report summary");if(p)throw new Error(p);if(c.content.some(l=>l.type==="toolCall"))throw new Error("Bug report summary attempted to call a tool");const d=T(c.content).trim();if(!d)throw new Error("Bug report summary was empty");return d}o(ee,"generateBugReportSummary");export{H as BUG_REPORT_CUSTOM_ENTRY_TYPE,X as bugReportArchiveFileName,B as bugReportFiles,Z as collectBugReportDiagnostics,q as collectBugReportMetadata,ee as generateBugReportSummary,m as redactJsonValue,u as redactUrl,Q as writeBugReportArchive};
27
+ `),r={maxTokens:Math.min(4096,t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY),signal:e.signal,apiKey:e.apiKey,headers:e.headers,env:e.env,sessionId:e.sessionId,...t.reasoning&&e.thinkingLevel&&e.thinkingLevel!=="off"?{reasoning:e.thinkingLevel}:{}},c=await _(t,x({systemPrompt:L,messages:[{role:"user",content:[{type:"text",text:i}],timestamp:Date.now()}]}),r,e.streamFn,e.retry);if(c.stopReason==="aborted")throw new Error("Bug report summary was cancelled");const p=b(c,"Bug report summary");if(p)throw new Error(p);if(c.content.some(l=>l.type==="toolCall"))throw new Error("Bug report summary attempted to call a tool");const d=T(c.content).trim();if(!d)throw new Error("Bug report summary was empty");return d}s(ee,"generateBugReportSummary");export{H as BUG_REPORT_CUSTOM_ENTRY_TYPE,X as bugReportArchiveFileName,B as bugReportFiles,Z as collectBugReportDiagnostics,q as collectBugReportMetadata,ee as generateBugReportSummary,m as redactJsonValue,u as redactUrl,Q as writeBugReportArchive};
@@ -114,8 +114,6 @@ export interface Settings {
114
114
  npmCommand?: string[];
115
115
  collapseChangelog?: boolean;
116
116
  enableInstallTelemetry?: boolean;
117
- enableAnalytics?: boolean;
118
- trackingId?: string;
119
117
  deviceId?: string;
120
118
  packages?: PackageSource[];
121
119
  extensions?: string[];
@@ -323,9 +321,6 @@ export declare class SettingsManager {
323
321
  setCollapseChangelog(collapse: boolean): void;
324
322
  getEnableInstallTelemetry(): boolean;
325
323
  setEnableInstallTelemetry(enabled: boolean): void;
326
- getEnableAnalytics(): boolean;
327
- getTrackingId(): string | undefined;
328
- setEnableAnalytics(enabled: boolean): void;
329
324
  getOrCreateDeviceId(): string;
330
325
  getPackages(): PackageSource[];
331
326
  setPackages(packages: PackageSource[]): void;
@@ -1 +1 @@
1
- var O=Object.defineProperty;var a=(o,e)=>O(o,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as A}from"@earendil-works/pi-ai";import{randomUUID as v}from"crypto";import{existsSync as P,mkdirSync as N,readFileSync as D}from"fs";import{dirname as R,join as m}from"path";import W from"proper-lockfile";import{CONFIG_DIR_NAME as j,getAgentDir as _}from"../config.js";import{normalizePath as C,resolvePath as f}from"../utils/paths.js";import{stripBom as E}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as $,parseHttpIdleTimeoutMs as U}from"./http-dispatcher.js";import{declaredDataFormat as S,reportNewerDataFormat as B,writeFileAtomicSync as H}from"./shared-data.js";const V=8e4,q={reserveTokens:16384,keepRecentTokens:2e4,maxContextTokens:V},X=32e3,G=5,K=["off","streaming","idle"];function b(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}a(b,"isMergeableObject");function w(o,e){const t={...o};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const r=o[s];t[s]=b(r)&&b(i)?w(r,i):i}return t}a(w,"deepMergeObjects");const Q=["read","bash","edit","write"];function p(o){return typeof o=="string"&&(o.startsWith("+")||o.startsWith("-"))}a(p,"isToolModifier");function ce(o){const e=o.filter(p);if(e.length===0)return;if(e.length<o.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(ce,"getToolListError");function z(o,e){const t=[...o];for(const s of e){if(!p(s))continue;const i=s.slice(1),r=t.indexOf(i);s.startsWith("+")&&r===-1&&i?t.push(i):s.startsWith("-")&&r!==-1&&t.splice(r,1)}return t}a(z,"applyToolModifiers");function J(o,e){return e===void 0?o:!Array.isArray(o)||!Array.isArray(e)||!e.every(p)?e:[...o,...e]}a(J,"mergeDefaultTools");function Y(o){const e=o.filter(t=>!p(t));return z(e.length>0||o.length===0?e:Q,o)}a(Y,"resolveDefaultTools");function h(o,e){const t=w(o,e),s=J(o.defaultTools,e.defaultTools);return s===void 0?t:{...t,defaultTools:s}}a(h,"deepMergeSettings");function x(o,e){const t=U(o);if(t!==void 0)return t;if(o!==void 0)throw new Error(`Invalid ${e} setting: ${String(o)}`)}a(x,"parseTimeoutSetting");const k=1;function M(o,e,t){return{scope:o,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}a(M,"toSettingsError");class Z{static{a(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=f(e),i=f(t);this.globalSettingsPath=m(i,"settings.json"),this.projectSettingsPath=m(s,j,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let r=1;r<=100;r++)try{return W.lockSync(e,{realpath:!1})}catch(n){if((typeof n=="object"&&n!==null&&"code"in n?String(n.code):void 0)!=="ELOCKED"||r===100)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=R(s);let r;try{const n=P(s);n&&(r=this.acquireLockSyncWithRetry(s));const l=n?D(s,"utf-8"):void 0,g=t(l);g!==void 0&&(P(i)||N(i,{recursive:!0}),r||(r=this.acquireLockSyncWithRetry(s)),H(s,g))}finally{r&&r()}}}class ee{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,r=null,n=[],l=!0,g={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=l,this.globalSettingsLoadError=i,this.projectSettingsLoadError=r,this.errors=[...n],this.settingsPaths=g,this.settings=h(this.globalSettings,this.projectSettings),this.reportNewerFormatScopes()}static create(e,t=_(),s={}){const i=f(e),r=f(t),n=new Z(i,r);return d.fromStorageWithPaths(n,s,{global:m(r,"settings.json"),project:m(i,j,"settings.json")})}static fromStorage(e,t={}){return d.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,r=d.tryLoadFromStorage(e,"global"),n=d.tryLoadFromStorage(e,"project",i),l=[];return r.error&&l.push(M("global",r.error,s.global)),n.error&&l.push(M("project",n.error,s.project)),new d(e,r.settings,n.settings,r.error,n.error,l,i,s)}static inMemory(e={},t={}){const s=new ee,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 r=JSON.parse(E(i));return d.migrateSettings(r)}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),this.reportNewerFormatScopes()}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")}reportNewerFormat(e){B(this.settingsPaths[e]??`${e} settings.json`)}reportNewerFormatScopes(){S(this.globalSettings)>k&&this.reportNewerFormat("global"),S(this.projectSettings)>k&&this.reportNewerFormat("project")}recordError(e,t){this.errors.push(M(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 n=r?JSON.parse(E(r)):{};if(S(n)>k){this.reportNewerFormat(e);return}const l=r?d.migrateSettings(n):{},g={...l};for(const c of s){const u=t[c];if(i.has(c)&&typeof u=="object"&&u!==null){const F=i.get(c),L=l[c]??{},I=u,T={...L};for(const y of F)T[y]=I[y];g[c]=T}else g[c]=u}return JSON.stringify(g,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&&C(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,n=r!==void 0?s?.modelOverrides?.[r]:void 0;if(n!==void 0&&!b(n))throw new Error(`Invalid compaction.modelOverrides["${r}"] 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["${r}"].${e} setting: ${String(l)}. Expected a non-negative safe integer.`);return l??i??q[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??G,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??A}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return X;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 x(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??$}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&&K.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 x(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&&C(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=v(),this.markModified("trackingId")),this.save()}getOrCreateDeviceId(){return this.globalSettings.deviceId||(this.globalSettings.deviceId=v(),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 Y(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{K as CACHE_WARMING_MODES,V as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,X as DEFAULT_MAX_OUTPUT_TOKENS,G as DEFAULT_MAX_RETRIES,Q as DEFAULT_TOOL_NAMES,Z as FileSettingsStorage,ee as InMemorySettingsStorage,k as SETTINGS_FORMAT_VERSION,d as SettingsManager,z as applyToolModifiers,ce as getToolListError,p as isToolModifier};
1
+ var N=Object.defineProperty;var a=(r,e)=>N(r,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as O}from"@earendil-works/pi-ai";import{randomUUID as A}from"crypto";import{existsSync as P,mkdirSync as D,readFileSync as R}from"fs";import{dirname as W,join as m}from"path";import _ from"proper-lockfile";import{CONFIG_DIR_NAME as E,getAgentDir as $}from"../config.js";import{normalizePath as w,resolvePath as f}from"../utils/paths.js";import{stripBom as k}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as U,parseHttpIdleTimeoutMs as B}from"./http-dispatcher.js";import{declaredDataFormat as p,reportNewerDataFormat as H,writeFileAtomicSync as V}from"./shared-data.js";const q=8e4,X={reserveTokens:16384,keepRecentTokens:2e4,maxContextTokens:q},K=32e3,G=5,Q=["off","streaming","idle"];function M(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}a(M,"isMergeableObject");function C(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]=M(o)&&M(i)?C(o,i):i}return t}a(C,"deepMergeObjects");const z=["read","bash","edit","write"];function S(r){return typeof r=="string"&&(r.startsWith("+")||r.startsWith("-"))}a(S,"isToolModifier");function me(r){const e=r.filter(S);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(me,"getToolListError");function J(r,e){const t=[...r];for(const s of e){if(!S(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(J,"applyToolModifiers");function Y(r,e){return e===void 0?r:!Array.isArray(r)||!Array.isArray(e)||!e.every(S)?e:[...r,...e]}a(Y,"mergeDefaultTools");function Z(r){const e=r.filter(t=>!S(t));return J(e.length>0||r.length===0?e:z,r)}a(Z,"resolveDefaultTools");function h(r,e){const t=C(r,e),s=Y(r.defaultTools,e.defaultTools);return s===void 0?t:{...t,defaultTools:s}}a(h,"deepMergeSettings");function x(r,e){const t=B(r);if(t!==void 0)return t;if(r!==void 0)throw new Error(`Invalid ${e} setting: ${String(r)}`)}a(x,"parseTimeoutSetting");const b=1,T=["enableAnalytics","trackingId"];function ee(r){let e;try{e=JSON.parse(k(r))}catch{return}if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e;if(!(p(t)>b)&&T.some(s=>s in t)){for(const s of T)delete t[s];return JSON.stringify(t,null,2)}}a(ee,"withoutRetiredKeys");function y(r,e,t){return{scope:r,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}a(y,"toSettingsError");class te{static{a(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=f(e),i=f(t);this.globalSettingsPath=m(i,"settings.json"),this.projectSettingsPath=m(s,E,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let o=1;o<=100;o++)try{return _.lockSync(e,{realpath:!1})}catch(n){if((typeof n=="object"&&n!==null&&"code"in n?String(n.code):void 0)!=="ELOCKED"||o===100)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=W(s);let o;try{const n=P(s);n&&(o=this.acquireLockSyncWithRetry(s));const l=n?R(s,"utf-8"):void 0,g=t(l);g!==void 0&&(P(i)||D(i,{recursive:!0}),o||(o=this.acquireLockSyncWithRetry(s)),V(s,g))}finally{o&&o()}}}class se{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),this.reportNewerFormatScopes()}static create(e,t=$(),s={}){const i=f(e),o=f(t),n=new te(i,o);return d.fromStorageWithPaths(n,s,{global:m(o,"settings.json"),project:m(i,E,"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(y("global",o.error,s.global)),n.error&&l.push(y("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 se,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,t==="global"&&n?ee(n):void 0)),!i)return{};const o=JSON.parse(k(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){for(const t of T)delete e[t];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),this.reportNewerFormatScopes()}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")}reportNewerFormat(e){H(this.settingsPaths[e]??`${e} settings.json`)}reportNewerFormatScopes(){p(this.globalSettings)>b&&this.reportNewerFormat("global"),p(this.projectSettings)>b&&this.reportNewerFormat("project")}recordError(e,t){this.errors.push(y(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?JSON.parse(k(o)):{};if(p(n)>b){this.reportNewerFormat(e);return}const l=o?d.migrateSettings(n):{},g={...l};for(const c of s){const u=t[c];if(i.has(c)&&typeof u=="object"&&u!==null){const F=i.get(c),L=l[c]??{},I=u,v={...L};for(const j of F)v[j]=I[j];g[c]=v}else g[c]=u}return JSON.stringify(g,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&&w(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&&!M(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??X[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??G,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??O}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return K;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 x(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??U}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 x(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&&w(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()}getOrCreateDeviceId(){return this.globalSettings.deviceId||(this.globalSettings.deviceId=A(),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 Z(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,q as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,K as DEFAULT_MAX_OUTPUT_TOKENS,G as DEFAULT_MAX_RETRIES,z as DEFAULT_TOOL_NAMES,te as FileSettingsStorage,se as InMemorySettingsStorage,b as SETTINGS_FORMAT_VERSION,d as SettingsManager,J as applyToolModifiers,me as getToolListError,S as isToolModifier};
@@ -8,7 +8,7 @@ import type { HostCapability } from "../../core/host-capabilities.ts";
8
8
  import type { SandboxStatus } from "../../core/sandbox/shell-sandbox.ts";
9
9
  import type { SessionEntry, SessionTreeNode } from "../../core/session-manager.ts";
10
10
  import type { JsonAgentSessionEvent } from "../json-event.ts";
11
- import type { RpcExtensionUIRequest, RpcExtensionUIResponse, RpcHostRequest, RpcSessionState, RpcSlashCommand } from "./rpc-types.ts";
11
+ import type { RpcExtensionUIRequest, RpcExtensionUIResponse, RpcHostRequest, RpcSessionState, RpcSlashCommand, TelemetryConsentStatus } from "./rpc-types.ts";
12
12
  export interface RpcClientOptions {
13
13
  cliPath?: string;
14
14
  cwd?: string;
@@ -111,6 +111,10 @@ export declare class RpcClient {
111
111
  set?: Record<string, string>;
112
112
  unset?: string[];
113
113
  }): Promise<string[]>;
114
+ setTelemetryConsent(consent: {
115
+ usage: boolean;
116
+ failures?: boolean;
117
+ }): Promise<TelemetryConsentStatus>;
114
118
  getSessionStats(): Promise<SessionStats>;
115
119
  exportHtml(outputPath?: string): Promise<{
116
120
  path: string;
@@ -1,4 +1,4 @@
1
- var y=Object.defineProperty;var h=(d,t)=>y(d,"name",{value:t,configurable:!0});import{spawn as w}from"node:child_process";import{attachJsonlLineReader as _,serializeJsonLine as p}from"./jsonl.js";const f=20,l=2e3;function m(d){const e=d.split(/\r?\n/u).filter(s=>s.trim().length>0).slice(-f).join(`
2
- `);return e.length>l?e.slice(-l):e}h(m,"rpcStderrTail");const E=new Set(["select","confirm","input","editor","requestInput","requestChoice"]);class S{static{h(this,"RpcClient")}process=null;stopReadingStdout=null;eventListeners=[];pendingRequests=new Map;requestId=0;extensionUIHandler=null;hostRequestHandler=null;stderr="";exitError=null;options;exitListeners=new Set;exitInfo;stopping=!1;turnInFlight=!1;constructor(t={}){this.options=t}async start(){if(this.process)throw new Error("Client already started");this.exitError=null,this.exitInfo=void 0,this.stopping=!1,this.turnInFlight=!1;const t=this.options.cliPath??"dist/cli.js",e=["--mode","rpc"];this.options.provider&&e.push("--provider",this.options.provider),this.options.model&&e.push("--model",this.options.model),this.options.args&&e.push(...this.options.args);const s=w(process.execPath,[t,...e],{cwd:this.options.cwd,env:{...this.options.inheritEnv===!1?{}:process.env,...this.options.env},stdio:["pipe","pipe","pipe"]});if(this.process=s,s.stderr?.on("data",r=>{this.stderr+=r.toString(),process.stderr.write(r)}),s.once("exit",(r,n)=>{if(this.process!==s)return;this.reportExit({code:r,signal:n});const i=this.createProcessExitError(r,n);this.exitError=i,this.rejectPendingRequests(i)}),s.once("error",r=>{if(this.process!==s)return;const n=new Error(`Agent process error: ${r.message}. Stderr: ${this.stderr}`);s.exitCode===null&&s.signalCode===null&&this.reportExit({code:null,signal:null,error:r.message}),this.exitError=n,this.rejectPendingRequests(n)}),s.stdin?.on("error",r=>{if(this.process!==s)return;const n=this.exitError??new Error(`Agent process stdin error: ${r.message}. Stderr: ${this.stderr}`);this.exitError=n,this.rejectPendingRequests(n)}),this.stopReadingStdout=_(s.stdout,r=>{this.handleLine(r)}),await new Promise(r=>setTimeout(r,100)),this.process.exitCode!==null){const r=this.exitError??this.createProcessExitError(this.process.exitCode,this.process.signalCode);throw this.exitError=r,r}}async stop(){this.process&&(this.stopReadingStdout?.(),this.stopReadingStdout=null,this.stopping=!0,this.process.kill("SIGTERM"),await new Promise(t=>{const e=setTimeout(()=>{this.process?.kill("SIGKILL"),t()},1e3);this.process?.on("exit",()=>{clearTimeout(e),t()})}),this.process=null,this.pendingRequests.clear())}onExit(t){const e=this.exitInfo;return e?(queueMicrotask(()=>t(e)),()=>{}):(this.exitListeners.add(t),()=>{this.exitListeners.delete(t)})}getExit(){return this.exitInfo}onEvent(t){return this.eventListeners.push(t),()=>{const e=this.eventListeners.indexOf(t);e!==-1&&this.eventListeners.splice(e,1)}}setExtensionUIHandler(t){this.extensionUIHandler=t}getStderr(){return this.stderr}async prompt(t,e,s){const r=await this.send({type:"prompt",message:t,images:e,streamingBehavior:s}),{disposition:n}=this.getData(r);return n!=="handled"&&(this.turnInFlight=!0),n}async steer(t,e){const s=await this.send({type:"steer",message:t,images:e});return this.getData(s).disposition}async followUp(t,e){const s=await this.send({type:"follow_up",message:t,images:e});return this.getData(s).disposition}async abort(){await this.send({type:"abort"})}async clearQueue(){const t=await this.send({type:"clear_queue"});return this.getData(t)}async newSession(t){const e=await this.send({type:"new_session",parentSession:t});return this.getData(e)}async getState(){const t=await this.send({type:"get_state"});return this.getData(t)}async setModel(t,e){const s=await this.send({type:"set_model",provider:t,modelId:e});return this.getData(s)}async cycleModel(){const t=await this.send({type:"cycle_model"});return this.getData(t)}async getAvailableModels(){const t=await this.send({type:"get_available_models"});return this.getData(t).models}async setThinkingLevel(t){await this.send({type:"set_thinking_level",level:t})}async cycleThinkingLevel(){const t=await this.send({type:"cycle_thinking_level"});return this.getData(t)}async getAvailableThinkingLevels(){const t=await this.send({type:"get_available_thinking_levels"});return this.getData(t).levels}async setSteeringMode(t){await this.send({type:"set_steering_mode",mode:t})}async setFollowUpMode(t){await this.send({type:"set_follow_up_mode",mode:t})}async compact(t){const e=await this.send({type:"compact",customInstructions:t});return this.getData(e)}async setAutoCompaction(t){await this.send({type:"set_auto_compaction",enabled:t})}async setAutoRetry(t){await this.send({type:"set_auto_retry",enabled:t})}async abortRetry(){await this.send({type:"abort_retry"})}async bash(t){const e=await this.send({type:"bash",command:t});return this.getData(e)}async abortBash(){await this.send({type:"abort_bash"})}async getSandboxStatus(){const t=await this.send({type:"get_sandbox_status"});return this.getData(t)}async listBackgroundProcesses(){const t=await this.send({type:"list_background_processes"});return this.getData(t).processes}async readBackgroundProcess(t,e){const s=await this.send({type:"read_background_process",processId:t,...e!==void 0?{tail:e}:{}});return this.getData(s)}async stopBackgroundProcess(t){const e=await this.send({type:"stop_background_process",processId:t});return this.getData(e).process}async setEnvironment(t){const e=await this.send({type:"set_environment",...t});return this.getData(e).changed}async getSessionStats(){const t=await this.send({type:"get_session_stats"});return this.getData(t)}async exportHtml(t){const e=await this.send({type:"export_html",outputPath:t});return this.getData(e)}async switchSession(t){const e=await this.send({type:"switch_session",sessionPath:t});return this.getData(e)}async fork(t){const e=await this.send({type:"fork",entryId:t});return this.getData(e)}async clone(){const t=await this.send({type:"clone"});return this.getData(t)}async getForkMessages(){const t=await this.send({type:"get_fork_messages"});return this.getData(t).messages}async getEntries(t){const e=await this.send({type:"get_entries",since:t});return this.getData(e)}async getTree(){const t=await this.send({type:"get_tree"});return this.getData(t)}async getLastAssistantText(){const t=await this.send({type:"get_last_assistant_text"});return this.getData(t).text}async setSessionName(t){await this.send({type:"set_session_name",name:t})}async getMessages(){const t=await this.send({type:"get_messages"});return this.getData(t).messages}async getCommands(){const t=await this.send({type:"get_commands"});return this.getData(t).commands}async setHostCapabilities(t,e){this.hostRequestHandler=e;const s=await this.send({type:"set_host_capabilities",capabilities:t});return this.getData(s).capabilities}waitForIdle(t=6e4){return new Promise((e,s)=>{const r=setTimeout(()=>{n(),i(),s(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`))},t),n=this.onEvent(o=>{o.type==="agent_settled"&&(clearTimeout(r),n(),i(),e())}),i=this.onExit(o=>{clearTimeout(r),n(),s(this.createExitWhileWaitingError(o))})})}collectEvents(t=6e4){return new Promise((e,s)=>{const r=[],n=setTimeout(()=>{i(),o(),s(new Error(`Timeout collecting events. Stderr: ${this.stderr}`))},t),i=this.onEvent(a=>{r.push(a),a.type==="agent_settled"&&(clearTimeout(n),i(),o(),e(r))}),o=this.onExit(a=>{clearTimeout(n),i(),s(this.createExitWhileWaitingError(a))})})}async promptAndWait(t,e,s=6e4){const r=this.collectEvents(s);return await this.prompt(t,e),r}handleLine(t){try{const e=JSON.parse(t);if(e.type==="agent_start"?this.turnInFlight=!0:e.type==="agent_settled"&&(this.turnInFlight=!1),e.type==="response"&&e.id&&this.pendingRequests.has(e.id)){const s=this.pendingRequests.get(e.id);this.pendingRequests.delete(e.id),s.resolve(e);return}if(e.type==="extension_ui_request"&&E.has(e.method)&&this.answerExtensionUIRequest(e),e.type==="host_request"){this.answerHostRequest(e);return}for(const s of[...this.eventListeners])s(e)}catch{}}async answerExtensionUIRequest(t){const e={type:"extension_ui_response",id:t.id,cancelled:!0};let s=e;if(this.extensionUIHandler)try{s=await this.extensionUIHandler(t)??e}catch{s=e}const r=this.process?.stdin;if(!(!r||r.destroyed||!r.writable))try{r.write(p({...s,id:t.id}))}catch{}}async answerHostRequest(t){let e;if(!this.hostRequestHandler)e={type:"host_response",id:t.id,error:"host has no handler for host requests"};else try{const r=await this.hostRequestHandler(t);e={type:"host_response",id:t.id,result:r??null}}catch(r){e={type:"host_response",id:t.id,error:r instanceof Error?r.message:String(r)}}const s=this.process?.stdin;if(!(!s||s.destroyed||!s.writable))try{s.write(p(e))}catch{}}reportExit(t){if(this.exitInfo)return;const e={code:t.code,signal:t.signal,stderrTail:m(this.stderr),expected:this.stopping,turnInFlight:this.turnInFlight,...t.error?{error:t.error}:{}};this.exitInfo=e,this.turnInFlight=!1;const s=[...this.exitListeners];this.exitListeners.clear();for(const r of s)try{r(e)}catch{}}createExitWhileWaitingError(t){const e=t.signal?`signal ${t.signal}`:`code ${t.code??"unknown"}`,s=t.stderrTail?`
1
+ var y=Object.defineProperty;var h=(d,t)=>y(d,"name",{value:t,configurable:!0});import{spawn as w}from"node:child_process";import{attachJsonlLineReader as f,serializeJsonLine as p}from"./jsonl.js";const _=20,l=2e3;function m(d){const e=d.split(/\r?\n/u).filter(s=>s.trim().length>0).slice(-_).join(`
2
+ `);return e.length>l?e.slice(-l):e}h(m,"rpcStderrTail");const E=new Set(["select","confirm","input","editor","requestInput","requestChoice"]);class D{static{h(this,"RpcClient")}process=null;stopReadingStdout=null;eventListeners=[];pendingRequests=new Map;requestId=0;extensionUIHandler=null;hostRequestHandler=null;stderr="";exitError=null;options;exitListeners=new Set;exitInfo;stopping=!1;turnInFlight=!1;constructor(t={}){this.options=t}async start(){if(this.process)throw new Error("Client already started");this.exitError=null,this.exitInfo=void 0,this.stopping=!1,this.turnInFlight=!1;const t=this.options.cliPath??"dist/cli.js",e=["--mode","rpc"];this.options.provider&&e.push("--provider",this.options.provider),this.options.model&&e.push("--model",this.options.model),this.options.args&&e.push(...this.options.args);const s=w(process.execPath,[t,...e],{cwd:this.options.cwd,env:{...this.options.inheritEnv===!1?{}:process.env,...this.options.env},stdio:["pipe","pipe","pipe"]});if(this.process=s,s.stderr?.on("data",r=>{this.stderr+=r.toString(),process.stderr.write(r)}),s.once("exit",(r,n)=>{if(this.process!==s)return;this.reportExit({code:r,signal:n});const i=this.createProcessExitError(r,n);this.exitError=i,this.rejectPendingRequests(i)}),s.once("error",r=>{if(this.process!==s)return;const n=new Error(`Agent process error: ${r.message}. Stderr: ${this.stderr}`);s.exitCode===null&&s.signalCode===null&&this.reportExit({code:null,signal:null,error:r.message}),this.exitError=n,this.rejectPendingRequests(n)}),s.stdin?.on("error",r=>{if(this.process!==s)return;const n=this.exitError??new Error(`Agent process stdin error: ${r.message}. Stderr: ${this.stderr}`);this.exitError=n,this.rejectPendingRequests(n)}),this.stopReadingStdout=f(s.stdout,r=>{this.handleLine(r)}),await new Promise(r=>setTimeout(r,100)),this.process.exitCode!==null){const r=this.exitError??this.createProcessExitError(this.process.exitCode,this.process.signalCode);throw this.exitError=r,r}}async stop(){this.process&&(this.stopReadingStdout?.(),this.stopReadingStdout=null,this.stopping=!0,this.process.kill("SIGTERM"),await new Promise(t=>{const e=setTimeout(()=>{this.process?.kill("SIGKILL"),t()},1e3);this.process?.on("exit",()=>{clearTimeout(e),t()})}),this.process=null,this.pendingRequests.clear())}onExit(t){const e=this.exitInfo;return e?(queueMicrotask(()=>t(e)),()=>{}):(this.exitListeners.add(t),()=>{this.exitListeners.delete(t)})}getExit(){return this.exitInfo}onEvent(t){return this.eventListeners.push(t),()=>{const e=this.eventListeners.indexOf(t);e!==-1&&this.eventListeners.splice(e,1)}}setExtensionUIHandler(t){this.extensionUIHandler=t}getStderr(){return this.stderr}async prompt(t,e,s){const r=await this.send({type:"prompt",message:t,images:e,streamingBehavior:s}),{disposition:n}=this.getData(r);return n!=="handled"&&(this.turnInFlight=!0),n}async steer(t,e){const s=await this.send({type:"steer",message:t,images:e});return this.getData(s).disposition}async followUp(t,e){const s=await this.send({type:"follow_up",message:t,images:e});return this.getData(s).disposition}async abort(){await this.send({type:"abort"})}async clearQueue(){const t=await this.send({type:"clear_queue"});return this.getData(t)}async newSession(t){const e=await this.send({type:"new_session",parentSession:t});return this.getData(e)}async getState(){const t=await this.send({type:"get_state"});return this.getData(t)}async setModel(t,e){const s=await this.send({type:"set_model",provider:t,modelId:e});return this.getData(s)}async cycleModel(){const t=await this.send({type:"cycle_model"});return this.getData(t)}async getAvailableModels(){const t=await this.send({type:"get_available_models"});return this.getData(t).models}async setThinkingLevel(t){await this.send({type:"set_thinking_level",level:t})}async cycleThinkingLevel(){const t=await this.send({type:"cycle_thinking_level"});return this.getData(t)}async getAvailableThinkingLevels(){const t=await this.send({type:"get_available_thinking_levels"});return this.getData(t).levels}async setSteeringMode(t){await this.send({type:"set_steering_mode",mode:t})}async setFollowUpMode(t){await this.send({type:"set_follow_up_mode",mode:t})}async compact(t){const e=await this.send({type:"compact",customInstructions:t});return this.getData(e)}async setAutoCompaction(t){await this.send({type:"set_auto_compaction",enabled:t})}async setAutoRetry(t){await this.send({type:"set_auto_retry",enabled:t})}async abortRetry(){await this.send({type:"abort_retry"})}async bash(t){const e=await this.send({type:"bash",command:t});return this.getData(e)}async abortBash(){await this.send({type:"abort_bash"})}async getSandboxStatus(){const t=await this.send({type:"get_sandbox_status"});return this.getData(t)}async listBackgroundProcesses(){const t=await this.send({type:"list_background_processes"});return this.getData(t).processes}async readBackgroundProcess(t,e){const s=await this.send({type:"read_background_process",processId:t,...e!==void 0?{tail:e}:{}});return this.getData(s)}async stopBackgroundProcess(t){const e=await this.send({type:"stop_background_process",processId:t});return this.getData(e).process}async setEnvironment(t){const e=await this.send({type:"set_environment",...t});return this.getData(e).changed}async setTelemetryConsent(t){const e=await this.send({type:"set_telemetry_consent",usage:t.usage,...t.failures!==void 0?{failures:t.failures}:{}});return this.getData(e)}async getSessionStats(){const t=await this.send({type:"get_session_stats"});return this.getData(t)}async exportHtml(t){const e=await this.send({type:"export_html",outputPath:t});return this.getData(e)}async switchSession(t){const e=await this.send({type:"switch_session",sessionPath:t});return this.getData(e)}async fork(t){const e=await this.send({type:"fork",entryId:t});return this.getData(e)}async clone(){const t=await this.send({type:"clone"});return this.getData(t)}async getForkMessages(){const t=await this.send({type:"get_fork_messages"});return this.getData(t).messages}async getEntries(t){const e=await this.send({type:"get_entries",since:t});return this.getData(e)}async getTree(){const t=await this.send({type:"get_tree"});return this.getData(t)}async getLastAssistantText(){const t=await this.send({type:"get_last_assistant_text"});return this.getData(t).text}async setSessionName(t){await this.send({type:"set_session_name",name:t})}async getMessages(){const t=await this.send({type:"get_messages"});return this.getData(t).messages}async getCommands(){const t=await this.send({type:"get_commands"});return this.getData(t).commands}async setHostCapabilities(t,e){this.hostRequestHandler=e;const s=await this.send({type:"set_host_capabilities",capabilities:t});return this.getData(s).capabilities}waitForIdle(t=6e4){return new Promise((e,s)=>{const r=setTimeout(()=>{n(),i(),s(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`))},t),n=this.onEvent(o=>{o.type==="agent_settled"&&(clearTimeout(r),n(),i(),e())}),i=this.onExit(o=>{clearTimeout(r),n(),s(this.createExitWhileWaitingError(o))})})}collectEvents(t=6e4){return new Promise((e,s)=>{const r=[],n=setTimeout(()=>{i(),o(),s(new Error(`Timeout collecting events. Stderr: ${this.stderr}`))},t),i=this.onEvent(a=>{r.push(a),a.type==="agent_settled"&&(clearTimeout(n),i(),o(),e(r))}),o=this.onExit(a=>{clearTimeout(n),i(),s(this.createExitWhileWaitingError(a))})})}async promptAndWait(t,e,s=6e4){const r=this.collectEvents(s);return await this.prompt(t,e),r}handleLine(t){try{const e=JSON.parse(t);if(e.type==="agent_start"?this.turnInFlight=!0:e.type==="agent_settled"&&(this.turnInFlight=!1),e.type==="response"&&e.id&&this.pendingRequests.has(e.id)){const s=this.pendingRequests.get(e.id);this.pendingRequests.delete(e.id),s.resolve(e);return}if(e.type==="extension_ui_request"&&E.has(e.method)&&this.answerExtensionUIRequest(e),e.type==="host_request"){this.answerHostRequest(e);return}for(const s of[...this.eventListeners])s(e)}catch{}}async answerExtensionUIRequest(t){const e={type:"extension_ui_response",id:t.id,cancelled:!0};let s=e;if(this.extensionUIHandler)try{s=await this.extensionUIHandler(t)??e}catch{s=e}const r=this.process?.stdin;if(!(!r||r.destroyed||!r.writable))try{r.write(p({...s,id:t.id}))}catch{}}async answerHostRequest(t){let e;if(!this.hostRequestHandler)e={type:"host_response",id:t.id,error:"host has no handler for host requests"};else try{const r=await this.hostRequestHandler(t);e={type:"host_response",id:t.id,result:r??null}}catch(r){e={type:"host_response",id:t.id,error:r instanceof Error?r.message:String(r)}}const s=this.process?.stdin;if(!(!s||s.destroyed||!s.writable))try{s.write(p(e))}catch{}}reportExit(t){if(this.exitInfo)return;const e={code:t.code,signal:t.signal,stderrTail:m(this.stderr),expected:this.stopping,turnInFlight:this.turnInFlight,...t.error?{error:t.error}:{}};this.exitInfo=e,this.turnInFlight=!1;const s=[...this.exitListeners];this.exitListeners.clear();for(const r of s)try{r(e)}catch{}}createExitWhileWaitingError(t){const e=t.signal?`signal ${t.signal}`:`code ${t.code??"unknown"}`,s=t.stderrTail?`
3
3
  Last stderr output:
4
- ${t.stderrTail}`:"";return new Error(`Agent process exited (${e}) before the turn finished.${s}`)}createProcessExitError(t,e){return new Error(`Agent process exited (code=${t} signal=${e}). Stderr: ${this.stderr}`)}rejectPendingRequests(t){for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}async send(t){const e=this.process,s=e?.stdin;if(!e||!s)throw new Error("Client not started");if(this.exitError)throw this.exitError;if(e.exitCode!==null){const i=this.createProcessExitError(e.exitCode,e.signalCode);throw this.exitError=i,i}if(s.destroyed||!s.writable){const i=new Error(`Agent process stdin is not writable. Stderr: ${this.stderr}`);throw this.exitError=i,i}const r=`req_${++this.requestId}`,n={...t,id:r};return new Promise((i,o)=>{const a=setTimeout(()=>{this.pendingRequests.delete(r),o(new Error(`Timeout waiting for response to ${t.type}. Stderr: ${this.stderr}`))},this.options.requestTimeoutMs??3e4);this.pendingRequests.set(r,{resolve:h(c=>{clearTimeout(a),i(c)},"resolve"),reject:h(c=>{clearTimeout(a),o(c)},"reject")});try{s.write(p(n))}catch(c){const u=c instanceof Error?c:new Error(String(c)),g=this.pendingRequests.get(r);this.pendingRequests.delete(r),g?.reject(u)}})}getData(t){if(!t.success){const s=t;throw new Error(s.error)}return t.data}}export{S as RpcClient,m as rpcStderrTail};
4
+ ${t.stderrTail}`:"";return new Error(`Agent process exited (${e}) before the turn finished.${s}`)}createProcessExitError(t,e){return new Error(`Agent process exited (code=${t} signal=${e}). Stderr: ${this.stderr}`)}rejectPendingRequests(t){for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}async send(t){const e=this.process,s=e?.stdin;if(!e||!s)throw new Error("Client not started");if(this.exitError)throw this.exitError;if(e.exitCode!==null){const i=this.createProcessExitError(e.exitCode,e.signalCode);throw this.exitError=i,i}if(s.destroyed||!s.writable){const i=new Error(`Agent process stdin is not writable. Stderr: ${this.stderr}`);throw this.exitError=i,i}const r=`req_${++this.requestId}`,n={...t,id:r};return new Promise((i,o)=>{const a=setTimeout(()=>{this.pendingRequests.delete(r),o(new Error(`Timeout waiting for response to ${t.type}. Stderr: ${this.stderr}`))},this.options.requestTimeoutMs??3e4);this.pendingRequests.set(r,{resolve:h(c=>{clearTimeout(a),i(c)},"resolve"),reject:h(c=>{clearTimeout(a),o(c)},"reject")});try{s.write(p(n))}catch(c){const u=c instanceof Error?c:new Error(String(c)),g=this.pendingRequests.get(r);this.pendingRequests.delete(r),g?.reject(u)}})}getData(t){if(!t.success){const s=t;throw new Error(s.error)}return t.data}}export{D as RpcClient,m as rpcStderrTail};
@@ -1 +1 @@
1
- var N=Object.defineProperty;var i=(u,o)=>N(u,"name",{value:o,configurable:!0});import*as p from"node:crypto";import{resolveExtensionNotify as O}from"../../core/extensions/index.js";import{DEFAULT_HOST_CALL_TIMEOUT_MS as G,getHostCapabilities as L,HostCallError as x,parseHostCapabilities as $}from"../../core/host-capabilities.js";import{flushRawStdout as J,takeOverStdout as W,waitForRawStdoutBackpressure as I,writeRawStdout as j}from"../../core/output-guard.js";import{killTrackedDetachedChildren as H}from"../../utils/shell.js";import{theme as z}from"../interactive/theme/theme.js";import{toJsonEvent as K}from"../json-event.js";import{applyEnvironmentUpdate as Q}from"./environment-update.js";import{attachJsonlLineReader as X,serializeJsonLine as Y}from"./jsonl.js";const Z="Prompt aborted before it started";async function ce(u){W();let o=u.session,k,S;const c=i(e=>{j(Y(e))},"output"),r=i((e,t,s)=>s===void 0?{id:e,type:"response",command:t,success:!0}:{id:e,type:"response",command:t,success:!0,data:s},"success"),d=i((e,t,s)=>({id:e,type:"response",command:t,success:!1,error:s}),"error"),m=new Map,b=new Map,q=i((e,t)=>{const s=p.randomUUID();return new Promise((n,a)=>{const l=i(()=>{clearTimeout(w),t.signal?.removeEventListener("abort",f),b.delete(s)},"cleanup"),y=i(g=>{l(),c({type:"host_request_cancelled",id:s}),a(g)},"giveUp"),f=i(()=>y(new x("aborted","host call aborted")),"onAbort"),w=setTimeout(()=>y(new x("timeout","host did not answer in time")),t.timeoutMs??G);t.signal?.addEventListener("abort",f,{once:!0}),b.set(s,{resolve:i(g=>{l(),n(g)},"resolve"),reject:i(g=>{l(),a(g)},"reject")});const v={type:"host_request",id:s,capability:e.capability,method:e.method,params:e.params};c(v)})},"rpcHostTransport");let E=!1,C=!1;const U=[];function h(e,t,s,n){if(e?.signal?.aborted)return Promise.resolve(t);const a=p.randomUUID();return new Promise((l,y)=>{let f;const w=i(()=>{f&&clearTimeout(f),e?.signal?.removeEventListener("abort",v),m.delete(a)},"cleanup"),v=i(()=>{w(),l(t)},"onAbort");e?.signal?.addEventListener("abort",v,{once:!0}),e?.timeout&&(f=setTimeout(()=>{w(),l(t)},e.timeout)),m.set(a,{resolve:i(g=>{w(),l(n(g))},"resolve"),reject:y}),c({type:"extension_ui_request",id:a,...s})})}i(h,"createDialogPromise");const F=i(()=>({select:i((e,t,s)=>h(s,void 0,{method:"select",title:e,options:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?void 0:"value"in n?n.value:void 0),"select"),confirm:i((e,t,s)=>h(s,!1,{method:"confirm",title:e,message:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?!1:"confirmed"in n?n.confirmed:!1),"confirm"),input:i((e,t,s)=>h(s,void 0,{method:"input",title:e,placeholder:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?void 0:"value"in n?n.value:void 0),"input"),notify(e,t){const s=O(e,t);c({type:"extension_ui_request",id:p.randomUUID(),method:"notify",message:s.message,notifyType:s.type})},setPanel(e,t){c({type:"extension_ui_request",id:p.randomUUID(),method:"setPanel",panelId:e,panel:t})},requestInput:i(e=>h(e,void 0,{method:"requestInput",title:e.title,placeholder:e.placeholder,timeout:e.timeout},t=>"cancelled"in t&&t.cancelled?void 0:"value"in t?t.value:void 0),"requestInput"),requestChoice:i(e=>h(e,void 0,{method:"requestChoice",title:e.title,items:e.items,timeout:e.timeout},t=>"cancelled"in t&&t.cancelled?void 0:"value"in t?t.value:void 0),"requestChoice"),onTerminalInput(){return()=>{}},setStatus(e,t){c({type:"extension_ui_request",id:p.randomUUID(),method:"setStatus",statusKey:e,statusText:t})},setWorkingMessage(e){},setWorkingVisible(e){},setWorkingIndicator(e){},setHiddenThinkingLabel(e){},setWidget(e,t,s){(t===void 0||Array.isArray(t))&&c({type:"extension_ui_request",id:p.randomUUID(),method:"setWidget",widgetKey:e,widgetLines:t,widgetPlacement:s?.placement})},setFooter(e){},setHeader(e){},setTitle(e){c({type:"extension_ui_request",id:p.randomUUID(),method:"setTitle",title:e})},async custom(){},pasteToEditor(e){this.setEditorText(e)},setEditorText(e){c({type:"extension_ui_request",id:p.randomUUID(),method:"set_editor_text",text:e})},getEditorText(){return""},async editor(e,t){const s=p.randomUUID();return new Promise((n,a)=>{m.set(s,{resolve:i(l=>{"cancelled"in l&&l.cancelled?n(void 0):"value"in l?n(l.value):n(void 0)},"resolve"),reject:a}),c({type:"extension_ui_request",id:s,method:"editor",title:e,prefill:t})})},addAutocompleteProvider(){},setEditorComponent(){},getEditorComponent(){},get theme(){return z},getAllThemes(){return[]},getTheme(e){},setTheme(e){return{success:!1,error:"Theme switching not supported in RPC mode"}},getToolsExpanded(){return!1},setToolsExpanded(e){}}),"createExtensionUIContext");u.setRebindSession(async()=>{await _()});const _=i(async()=>{o=u.session,k?.(),S?.(),k=o.subscribe(e=>{c(K(e)),e.type==="agent_settled"&&R()}),S=o.agent.subscribe(async()=>{await I()}),await o.bindExtensions({uiContext:F(),mode:"rpc",commandContextActions:{waitForIdle:i(()=>o.waitForIdle(),"waitForIdle"),newSession:i(async e=>u.newSession(e),"newSession"),fork:i(async(e,t)=>({cancelled:(await u.fork(e,t)).cancelled}),"fork"),navigateTree:i(async(e,t)=>({cancelled:(await o.navigateTree(e,{summarize:t?.summarize,customInstructions:t?.customInstructions,replaceInstructions:t?.replaceInstructions,label:t?.label})).cancelled}),"navigateTree"),switchSession:i(async(e,t)=>u.switchSession(e,t),"switchSession"),reload:i(async()=>{await o.reload()},"reload")},shutdownHandler:i(()=>{E=!0},"shutdownHandler"),onError:i(e=>{c({type:"extension_error",extensionPath:e.extensionPath,event:e.event,error:e.error})},"onError")})},"rebindSession"),A=i(()=>{const e=["SIGTERM","SIGINT"];process.platform!=="win32"&&e.push("SIGHUP");for(const t of e){const s=i(()=>{H(),T(t==="SIGHUP"?129:t==="SIGINT"?130:143,t)},"handler");process.on(t,s),U.push(()=>process.off(t,s))}},"registerSignalHandlers");await _(),A();const D=i(async e=>{const t=e.id;switch(e.type){case"prompt":{let s=!1,n=!1;o.prompt(e.message,{images:e.images,streamingBehavior:e.streamingBehavior,source:"rpc",preflightResult:i(a=>{if(a==="cancelled"){n=!0;return}s=!0,c(r(t,"prompt",{disposition:a}))},"preflightResult")}).then(()=>{n&&!s&&c(d(t,"prompt",Z))},a=>{s||c(d(t,"prompt",a.message))});return}case"steer":{const s=await o.steer(e.message,e.images,{source:"rpc"});return r(t,"steer",{disposition:s})}case"follow_up":{const s=await o.followUp(e.message,e.images,{source:"rpc"});return r(t,"follow_up",{disposition:s})}case"abort":return await o.abort(),r(t,"abort");case"clear_queue":return r(t,"clear_queue",o.clearQueue());case"new_session":{const s=e.parentSession?{parentSession:e.parentSession}:void 0,n=await u.newSession(s);return n.cancelled||await _(),r(t,"new_session",n)}case"get_state":{const s={model:o.model,thinkingLevel:o.thinkingLevel,isStreaming:o.isStreaming,isCompacting:o.isCompacting,steeringMode:o.steeringMode,followUpMode:o.followUpMode,sessionFile:o.sessionFile,sessionId:o.sessionId,sessionName:o.sessionName,autoCompactionEnabled:o.autoCompactionEnabled,messageCount:o.messages.length,pendingMessageCount:o.pendingMessageCount};return r(t,"get_state",s)}case"set_model":{const n=o.modelRuntime.getAvailableSnapshot().find(a=>a.provider===e.provider&&a.id===e.modelId);return n?(await o.setModel(n),r(t,"set_model",n)):d(t,"set_model",`Model not found: ${e.provider}/${e.modelId}`)}case"cycle_model":{const s=await o.cycleModel();return s?r(t,"cycle_model",s):r(t,"cycle_model",null)}case"get_available_models":{const s=o.modelRuntime.getAvailableSnapshot();return r(t,"get_available_models",{models:s})}case"set_thinking_level":return o.setThinkingLevel(e.level),r(t,"set_thinking_level");case"cycle_thinking_level":{const s=o.cycleThinkingLevel();return s?r(t,"cycle_thinking_level",{level:s}):r(t,"cycle_thinking_level",null)}case"get_available_thinking_levels":{const s=o.getAvailableThinkingLevels();return r(t,"get_available_thinking_levels",{levels:s})}case"set_steering_mode":return o.setSteeringMode(e.mode),r(t,"set_steering_mode");case"set_follow_up_mode":return o.setFollowUpMode(e.mode),r(t,"set_follow_up_mode");case"compact":{const s=await o.compact(e.customInstructions);return r(t,"compact",s)}case"set_auto_compaction":return o.setAutoCompactionEnabled(e.enabled),r(t,"set_auto_compaction");case"set_auto_retry":return o.setAutoRetryEnabled(e.enabled),r(t,"set_auto_retry");case"abort_retry":return o.abortRetry(),r(t,"abort_retry");case"bash":{const s=await o.extensionRunner.emitUserBash({type:"user_bash",command:e.command,excludeFromContext:e.excludeFromContext??!1,cwd:o.sessionManager.getCwd()});if(s?.result)return o.recordBashResult(e.command,s.result,{excludeFromContext:e.excludeFromContext}),r(t,"bash",s.result);const n=await o.executeBash(e.command,void 0,{excludeFromContext:e.excludeFromContext,id:t,operations:s?.operations});return r(t,"bash",n)}case"abort_bash":return o.abortBash(),r(t,"abort_bash");case"get_sandbox_status":return r(t,"get_sandbox_status",o.getSandboxStatus()??null);case"list_background_processes":return r(t,"list_background_processes",{processes:o.backgroundProcesses.list()});case"read_background_process":{const{text:s,truncated:n,info:a}=o.backgroundProcesses.read(e.processId,e.tail!==void 0?{tail:e.tail}:{tail:200});return r(t,"read_background_process",{text:s,truncated:n,process:a})}case"stop_background_process":{const s=await o.backgroundProcesses.stop(e.processId);return r(t,"stop_background_process",{process:s})}case"get_session_stats":{const s=o.getSessionStats();return r(t,"get_session_stats",s)}case"export_html":{const s=await o.exportToHtml(e.outputPath);return r(t,"export_html",{path:s})}case"switch_session":{const s=await u.switchSession(e.sessionPath);return s.cancelled||await _(),r(t,"switch_session",s)}case"fork":{const s=await u.fork(e.entryId);return s.cancelled||await _(),r(t,"fork",{text:s.selectedText,cancelled:s.cancelled})}case"clone":{const s=o.sessionManager.getLeafId();if(!s)return d(t,"clone","Cannot clone session: no current entry selected");const n=await u.fork(s,{position:"at"});return n.cancelled||await _(),r(t,"clone",{cancelled:n.cancelled})}case"get_fork_messages":{const s=o.getUserMessagesForForking();return r(t,"get_fork_messages",{messages:s})}case"get_entries":{const s=o.sessionManager;let n=s.getEntries();if(e.since!==void 0){const a=n.findIndex(l=>l.id===e.since);if(a===-1)return d(t,"get_entries",`Entry not found: ${e.since}`);n=n.slice(a+1)}return r(t,"get_entries",{entries:n,leafId:s.getLeafId()})}case"get_tree":{const s=o.sessionManager;return r(t,"get_tree",{tree:s.getTree(),leafId:s.getLeafId()})}case"get_last_assistant_text":{const s=o.getLastAssistantText();return r(t,"get_last_assistant_text",{text:s})}case"set_session_name":{const s=e.name.trim();return s?(o.setSessionName(s),r(t,"set_session_name")):d(t,"set_session_name","Session name cannot be empty")}case"get_messages":return r(t,"get_messages",{messages:o.messages});case"get_commands":{const s=[];for(const n of o.extensionRunner.getRegisteredCommands())s.push({name:n.invocationName,description:n.description,source:"extension",sourceInfo:n.sourceInfo});for(const n of o.promptTemplates)s.push({name:n.name,description:n.description,source:"prompt",sourceInfo:n.sourceInfo});for(const n of o.resourceLoader.getSkills().skills)s.push({name:`skill:${n.name}`,description:n.description,source:"skill",sourceInfo:n.sourceInfo});return r(t,"get_commands",{commands:s})}case"set_host_capabilities":{const s=L();return s.set("rpc",$(e.capabilities),q),r(t,"set_host_capabilities",{capabilities:s.list()})}case"set_environment":{const s=Q({set:e.set,unset:e.unset});return r(t,"set_environment",{changed:s})}default:{const s=e;return d(t,s.type,`Unknown command: ${s.type}`)}}},"handleCommand");let M=i(()=>{},"detachInput");async function T(e=0,t){C&&process.exit(e),C=!0;for(const s of U)s();k?.(),S?.(),L().clear("rpc");for(const s of b.values())s.reject(new x("unavailable","RPC host disconnected"));await u.dispose(),M(),process.stdin.pause(),t!=="SIGTERM"&&await J(),process.exit(e)}i(T,"shutdown");async function R(){E&&await T()}i(R,"checkShutdownRequested");const B=i(async e=>{let t;try{t=JSON.parse(e)}catch(n){c(d(void 0,"parse",`Failed to parse command: ${n instanceof Error?n.message:String(n)}`)),await I();return}if(typeof t=="object"&&t!==null&&"type"in t&&t.type==="extension_ui_response"){const n=t,a=m.get(n.id);a&&(m.delete(n.id),a.resolve(n));return}if(typeof t=="object"&&t!==null&&"type"in t&&t.type==="host_response"){const n=t,a=b.get(n.id);a&&("error"in n?a.reject(new x("host_error",String(n.error))):a.resolve(n.result));return}const s=t;try{const n=await D(s);n&&(c(n),await I()),await R()}catch(n){c(d(s.id,s.type,n instanceof Error?n.message:String(n))),await I()}},"handleInputLine"),P=i(()=>{T()},"onInputEnd");return process.stdin.on("end",P),M=(()=>{const e=X(process.stdin,t=>{B(t)});return()=>{e(),process.stdin.off("end",P)}})(),new Promise(()=>{})}i(ce,"runRpcMode");export{Z as PROMPT_ABORTED_BEFORE_START,ce as runRpcMode};
1
+ var N=Object.defineProperty;var i=(u,o)=>N(u,"name",{value:o,configurable:!0});import*as p from"node:crypto";import{resolveExtensionNotify as O}from"../../core/extensions/index.js";import{DEFAULT_HOST_CALL_TIMEOUT_MS as G,getHostCapabilities as L,HostCallError as x,parseHostCapabilities as $}from"../../core/host-capabilities.js";import{flushRawStdout as J,takeOverStdout as W,waitForRawStdoutBackpressure as I,writeRawStdout as j}from"../../core/output-guard.js";import{killTrackedDetachedChildren as H}from"../../utils/shell.js";import{theme as z}from"../interactive/theme/theme.js";import{toJsonEvent as K}from"../json-event.js";import{applyEnvironmentUpdate as Q}from"./environment-update.js";import{attachJsonlLineReader as X,serializeJsonLine as Y}from"./jsonl.js";const Z="Prompt aborted before it started";async function ce(u){W();let o=u.session,k,S;const c=i(e=>{j(Y(e))},"output"),r=i((e,t,s)=>s===void 0?{id:e,type:"response",command:t,success:!0}:{id:e,type:"response",command:t,success:!0,data:s},"success"),d=i((e,t,s)=>({id:e,type:"response",command:t,success:!1,error:s}),"error"),m=new Map,y=new Map,q=i((e,t)=>{const s=p.randomUUID();return new Promise((n,a)=>{const l=i(()=>{clearTimeout(b),t.signal?.removeEventListener("abort",g),y.delete(s)},"cleanup"),w=i(_=>{l(),c({type:"host_request_cancelled",id:s}),a(_)},"giveUp"),g=i(()=>w(new x("aborted","host call aborted")),"onAbort"),b=setTimeout(()=>w(new x("timeout","host did not answer in time")),t.timeoutMs??G);t.signal?.addEventListener("abort",g,{once:!0}),y.set(s,{resolve:i(_=>{l(),n(_)},"resolve"),reject:i(_=>{l(),a(_)},"reject")});const v={type:"host_request",id:s,capability:e.capability,method:e.method,params:e.params};c(v)})},"rpcHostTransport");let E=!1,C=!1;const U=[];function h(e,t,s,n){if(e?.signal?.aborted)return Promise.resolve(t);const a=p.randomUUID();return new Promise((l,w)=>{let g;const b=i(()=>{g&&clearTimeout(g),e?.signal?.removeEventListener("abort",v),m.delete(a)},"cleanup"),v=i(()=>{b(),l(t)},"onAbort");e?.signal?.addEventListener("abort",v,{once:!0}),e?.timeout&&(g=setTimeout(()=>{b(),l(t)},e.timeout)),m.set(a,{resolve:i(_=>{b(),l(n(_))},"resolve"),reject:w}),c({type:"extension_ui_request",id:a,...s})})}i(h,"createDialogPromise");const A=i(()=>({select:i((e,t,s)=>h(s,void 0,{method:"select",title:e,options:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?void 0:"value"in n?n.value:void 0),"select"),confirm:i((e,t,s)=>h(s,!1,{method:"confirm",title:e,message:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?!1:"confirmed"in n?n.confirmed:!1),"confirm"),input:i((e,t,s)=>h(s,void 0,{method:"input",title:e,placeholder:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?void 0:"value"in n?n.value:void 0),"input"),notify(e,t){const s=O(e,t);c({type:"extension_ui_request",id:p.randomUUID(),method:"notify",message:s.message,notifyType:s.type})},setPanel(e,t){c({type:"extension_ui_request",id:p.randomUUID(),method:"setPanel",panelId:e,panel:t})},requestInput:i(e=>h(e,void 0,{method:"requestInput",title:e.title,placeholder:e.placeholder,timeout:e.timeout},t=>"cancelled"in t&&t.cancelled?void 0:"value"in t?t.value:void 0),"requestInput"),requestChoice:i(e=>h(e,void 0,{method:"requestChoice",title:e.title,items:e.items,timeout:e.timeout},t=>"cancelled"in t&&t.cancelled?void 0:"value"in t?t.value:void 0),"requestChoice"),onTerminalInput(){return()=>{}},setStatus(e,t){c({type:"extension_ui_request",id:p.randomUUID(),method:"setStatus",statusKey:e,statusText:t})},setWorkingMessage(e){},setWorkingVisible(e){},setWorkingIndicator(e){},setHiddenThinkingLabel(e){},setWidget(e,t,s){(t===void 0||Array.isArray(t))&&c({type:"extension_ui_request",id:p.randomUUID(),method:"setWidget",widgetKey:e,widgetLines:t,widgetPlacement:s?.placement})},setFooter(e){},setHeader(e){},setTitle(e){c({type:"extension_ui_request",id:p.randomUUID(),method:"setTitle",title:e})},async custom(){},pasteToEditor(e){this.setEditorText(e)},setEditorText(e){c({type:"extension_ui_request",id:p.randomUUID(),method:"set_editor_text",text:e})},getEditorText(){return""},async editor(e,t){const s=p.randomUUID();return new Promise((n,a)=>{m.set(s,{resolve:i(l=>{"cancelled"in l&&l.cancelled?n(void 0):"value"in l?n(l.value):n(void 0)},"resolve"),reject:a}),c({type:"extension_ui_request",id:s,method:"editor",title:e,prefill:t})})},addAutocompleteProvider(){},setEditorComponent(){},getEditorComponent(){},get theme(){return z},getAllThemes(){return[]},getTheme(e){},setTheme(e){return{success:!1,error:"Theme switching not supported in RPC mode"}},getToolsExpanded(){return!1},setToolsExpanded(e){}}),"createExtensionUIContext");u.setRebindSession(async()=>{await f()});const f=i(async()=>{o=u.session,k?.(),S?.(),k=o.subscribe(e=>{c(K(e)),e.type==="agent_settled"&&R()}),S=o.agent.subscribe(async()=>{await I()}),await o.bindExtensions({uiContext:A(),mode:"rpc",commandContextActions:{waitForIdle:i(()=>o.waitForIdle(),"waitForIdle"),newSession:i(async e=>u.newSession(e),"newSession"),fork:i(async(e,t)=>({cancelled:(await u.fork(e,t)).cancelled}),"fork"),navigateTree:i(async(e,t)=>({cancelled:(await o.navigateTree(e,{summarize:t?.summarize,customInstructions:t?.customInstructions,replaceInstructions:t?.replaceInstructions,label:t?.label})).cancelled}),"navigateTree"),switchSession:i(async(e,t)=>u.switchSession(e,t),"switchSession"),reload:i(async()=>{await o.reload()},"reload")},shutdownHandler:i(()=>{E=!0},"shutdownHandler"),onError:i(e=>{c({type:"extension_error",extensionPath:e.extensionPath,event:e.event,error:e.error})},"onError")})},"rebindSession"),F=i(()=>{const e=["SIGTERM","SIGINT"];process.platform!=="win32"&&e.push("SIGHUP");for(const t of e){const s=i(()=>{H(),T(t==="SIGHUP"?129:t==="SIGINT"?130:143,t)},"handler");process.on(t,s),U.push(()=>process.off(t,s))}},"registerSignalHandlers");await f(),F();const D=i(async e=>{const t=e.id;switch(e.type){case"prompt":{let s=!1,n=!1;o.prompt(e.message,{images:e.images,streamingBehavior:e.streamingBehavior,source:"rpc",preflightResult:i(a=>{if(a==="cancelled"){n=!0;return}s=!0,c(r(t,"prompt",{disposition:a}))},"preflightResult")}).then(()=>{n&&!s&&c(d(t,"prompt",Z))},a=>{s||c(d(t,"prompt",a.message))});return}case"steer":{const s=await o.steer(e.message,e.images,{source:"rpc"});return r(t,"steer",{disposition:s})}case"follow_up":{const s=await o.followUp(e.message,e.images,{source:"rpc"});return r(t,"follow_up",{disposition:s})}case"abort":return await o.abort(),r(t,"abort");case"clear_queue":return r(t,"clear_queue",o.clearQueue());case"new_session":{const s=e.parentSession?{parentSession:e.parentSession}:void 0,n=await u.newSession(s);return n.cancelled||await f(),r(t,"new_session",n)}case"get_state":{const s={model:o.model,thinkingLevel:o.thinkingLevel,isStreaming:o.isStreaming,isCompacting:o.isCompacting,steeringMode:o.steeringMode,followUpMode:o.followUpMode,sessionFile:o.sessionFile,sessionId:o.sessionId,sessionName:o.sessionName,autoCompactionEnabled:o.autoCompactionEnabled,messageCount:o.messages.length,pendingMessageCount:o.pendingMessageCount};return r(t,"get_state",s)}case"set_model":{const n=o.modelRuntime.getAvailableSnapshot().find(a=>a.provider===e.provider&&a.id===e.modelId);return n?(await o.setModel(n),r(t,"set_model",n)):d(t,"set_model",`Model not found: ${e.provider}/${e.modelId}`)}case"cycle_model":{const s=await o.cycleModel();return s?r(t,"cycle_model",s):r(t,"cycle_model",null)}case"get_available_models":{const s=o.modelRuntime.getAvailableSnapshot();return r(t,"get_available_models",{models:s})}case"set_thinking_level":return o.setThinkingLevel(e.level),r(t,"set_thinking_level");case"cycle_thinking_level":{const s=o.cycleThinkingLevel();return s?r(t,"cycle_thinking_level",{level:s}):r(t,"cycle_thinking_level",null)}case"get_available_thinking_levels":{const s=o.getAvailableThinkingLevels();return r(t,"get_available_thinking_levels",{levels:s})}case"set_steering_mode":return o.setSteeringMode(e.mode),r(t,"set_steering_mode");case"set_follow_up_mode":return o.setFollowUpMode(e.mode),r(t,"set_follow_up_mode");case"compact":{const s=await o.compact(e.customInstructions);return r(t,"compact",s)}case"set_auto_compaction":return o.setAutoCompactionEnabled(e.enabled),r(t,"set_auto_compaction");case"set_auto_retry":return o.setAutoRetryEnabled(e.enabled),r(t,"set_auto_retry");case"abort_retry":return o.abortRetry(),r(t,"abort_retry");case"bash":{const s=await o.extensionRunner.emitUserBash({type:"user_bash",command:e.command,excludeFromContext:e.excludeFromContext??!1,cwd:o.sessionManager.getCwd()});if(s?.result)return o.recordBashResult(e.command,s.result,{excludeFromContext:e.excludeFromContext}),r(t,"bash",s.result);const n=await o.executeBash(e.command,void 0,{excludeFromContext:e.excludeFromContext,id:t,operations:s?.operations});return r(t,"bash",n)}case"abort_bash":return o.abortBash(),r(t,"abort_bash");case"get_sandbox_status":return r(t,"get_sandbox_status",o.getSandboxStatus()??null);case"list_background_processes":return r(t,"list_background_processes",{processes:o.backgroundProcesses.list()});case"read_background_process":{const{text:s,truncated:n,info:a}=o.backgroundProcesses.read(e.processId,e.tail!==void 0?{tail:e.tail}:{tail:200});return r(t,"read_background_process",{text:s,truncated:n,process:a})}case"stop_background_process":{const s=await o.backgroundProcesses.stop(e.processId);return r(t,"stop_background_process",{process:s})}case"get_session_stats":{const s=o.getSessionStats();return r(t,"get_session_stats",s)}case"export_html":{const s=await o.exportToHtml(e.outputPath);return r(t,"export_html",{path:s})}case"switch_session":{const s=await u.switchSession(e.sessionPath);return s.cancelled||await f(),r(t,"switch_session",s)}case"fork":{const s=await u.fork(e.entryId);return s.cancelled||await f(),r(t,"fork",{text:s.selectedText,cancelled:s.cancelled})}case"clone":{const s=o.sessionManager.getLeafId();if(!s)return d(t,"clone","Cannot clone session: no current entry selected");const n=await u.fork(s,{position:"at"});return n.cancelled||await f(),r(t,"clone",{cancelled:n.cancelled})}case"get_fork_messages":{const s=o.getUserMessagesForForking();return r(t,"get_fork_messages",{messages:s})}case"get_entries":{const s=o.sessionManager;let n=s.getEntries();if(e.since!==void 0){const a=n.findIndex(l=>l.id===e.since);if(a===-1)return d(t,"get_entries",`Entry not found: ${e.since}`);n=n.slice(a+1)}return r(t,"get_entries",{entries:n,leafId:s.getLeafId()})}case"get_tree":{const s=o.sessionManager;return r(t,"get_tree",{tree:s.getTree(),leafId:s.getLeafId()})}case"get_last_assistant_text":{const s=o.getLastAssistantText();return r(t,"get_last_assistant_text",{text:s})}case"set_session_name":{const s=e.name.trim();return s?(o.setSessionName(s),r(t,"set_session_name")):d(t,"set_session_name","Session name cannot be empty")}case"get_messages":return r(t,"get_messages",{messages:o.messages});case"get_commands":{const s=[];for(const n of o.extensionRunner.getRegisteredCommands())s.push({name:n.invocationName,description:n.description,source:"extension",sourceInfo:n.sourceInfo});for(const n of o.promptTemplates)s.push({name:n.name,description:n.description,source:"prompt",sourceInfo:n.sourceInfo});for(const n of o.resourceLoader.getSkills().skills)s.push({name:`skill:${n.name}`,description:n.description,source:"skill",sourceInfo:n.sourceInfo});return r(t,"get_commands",{commands:s})}case"set_host_capabilities":{const s=L();return s.set("rpc",$(e.capabilities),q),r(t,"set_host_capabilities",{capabilities:s.list()})}case"set_environment":{const s=Q({set:e.set,unset:e.unset});return r(t,"set_environment",{changed:s})}case"set_telemetry_consent":{const{usage:s,failures:n}=e;if(typeof s!="boolean"||n!==void 0&&typeof n!="boolean")return d(t,"set_telemetry_consent","set_telemetry_consent: usage must be a boolean, failures a boolean or omitted");const a=globalThis[Symbol.for("dalcode.telemetry.consentApi")];return a?r(t,"set_telemetry_consent",a.set({usage:s,failures:n})):d(t,"set_telemetry_consent","set_telemetry_consent: telemetry is not loaded in this engine")}default:{const s=e;return d(t,s.type,`Unknown command: ${s.type}`)}}},"handleCommand");let M=i(()=>{},"detachInput");async function T(e=0,t){C&&process.exit(e),C=!0;for(const s of U)s();k?.(),S?.(),L().clear("rpc");for(const s of y.values())s.reject(new x("unavailable","RPC host disconnected"));await u.dispose(),M(),process.stdin.pause(),t!=="SIGTERM"&&await J(),process.exit(e)}i(T,"shutdown");async function R(){E&&await T()}i(R,"checkShutdownRequested");const B=i(async e=>{let t;try{t=JSON.parse(e)}catch(n){c(d(void 0,"parse",`Failed to parse command: ${n instanceof Error?n.message:String(n)}`)),await I();return}if(typeof t=="object"&&t!==null&&"type"in t&&t.type==="extension_ui_response"){const n=t,a=m.get(n.id);a&&(m.delete(n.id),a.resolve(n));return}if(typeof t=="object"&&t!==null&&"type"in t&&t.type==="host_response"){const n=t,a=y.get(n.id);a&&("error"in n?a.reject(new x("host_error",String(n.error))):a.resolve(n.result));return}const s=t;try{const n=await D(s);n&&(c(n),await I()),await R()}catch(n){c(d(s.id,s.type,n instanceof Error?n.message:String(n))),await I()}},"handleInputLine"),P=i(()=>{T()},"onInputEnd");return process.stdin.on("end",P),M=(()=>{const e=X(process.stdin,t=>{B(t)});return()=>{e(),process.stdin.off("end",P)}})(),new Promise(()=>{})}i(ce,"runRpcMode");export{Z as PROMPT_ABORTED_BEFORE_START,ce as runRpcMode};
@@ -154,7 +154,26 @@ export type RpcCommand = {
154
154
  type: "set_environment";
155
155
  set?: Record<string, string>;
156
156
  unset?: string[];
157
+ } | {
158
+ id?: string;
159
+ type: "set_telemetry_consent";
160
+ usage: boolean;
161
+ failures?: boolean;
157
162
  };
163
+ export interface TelemetryConsentStatus {
164
+ usage: {
165
+ decided: boolean;
166
+ enabled: boolean;
167
+ active: boolean;
168
+ reason?: "not-decided" | "opted-out" | "do-not-track" | "env" | "ci" | "unreadable" | "unconfigured";
169
+ };
170
+ failures: {
171
+ decided: boolean;
172
+ enabled: boolean;
173
+ active: boolean;
174
+ reason?: "not-decided" | "declined" | "opted-out" | "do-not-track" | "env" | "ci" | "unconfigured" | "unreadable";
175
+ };
176
+ }
158
177
  export interface RpcSlashCommand {
159
178
  name: string;
160
179
  description?: string;
@@ -459,6 +478,12 @@ export type RpcResponse = {
459
478
  data: {
460
479
  changed: string[];
461
480
  };
481
+ } | {
482
+ id?: string;
483
+ type: "response";
484
+ command: "set_telemetry_consent";
485
+ success: true;
486
+ data: TelemetryConsentStatus;
462
487
  } | {
463
488
  id?: string;
464
489
  type: "response";
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-advisor",
3
- "version": "1.0.41",
3
+ "version": "1.0.42",
4
4
  "private": true,
5
5
  "description": "advisor: the model asks another strong model to review its current plan and point out risks. Adapted from @juicesharp/rpiv-advisor 2.13.8 (MIT).",
6
6
  "license": "MIT",
@@ -20,8 +20,8 @@
20
20
  ]
21
21
  },
22
22
  "dependencies": {
23
- "@dalcode/dal-pi-kit": "1.0.41",
24
- "@dalcode/dal-router": "1.0.41",
23
+ "@dalcode/dal-pi-kit": "1.0.42",
24
+ "@dalcode/dal-router": "1.0.42",
25
25
  "typebox": "1.3.27"
26
26
  },
27
27
  "peerDependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-awake",
3
- "version": "1.0.41",
3
+ "version": "1.0.42",
4
4
  "private": true,
5
5
  "description": "Keeps the computer from going to sleep while a long agent run is in progress, and lets it sleep again when the run ends. Adapted from @narumitw/pi-caffeinate (MIT).",
6
6
  "type": "module",
@@ -18,7 +18,7 @@
18
18
  ]
19
19
  },
20
20
  "dependencies": {
21
- "@dalcode/dal-pi-kit": "1.0.41"
21
+ "@dalcode/dal-pi-kit": "1.0.42"
22
22
  },
23
23
  "peerDependencies": {
24
24
  "@earendil-works/pi-coding-agent": "^1.0.9"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-bridge",
3
- "version": "1.0.41",
3
+ "version": "1.0.42",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -18,7 +18,7 @@
18
18
  ]
19
19
  },
20
20
  "dependencies": {
21
- "@dalcode/dal-pi-kit": "1.0.41",
21
+ "@dalcode/dal-pi-kit": "1.0.42",
22
22
  "typebox": "1.3.7"
23
23
  },
24
24
  "peerDependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-capabilities",
3
- "version": "1.0.41",
3
+ "version": "1.0.42",
4
4
  "private": true,
5
5
  "description": "Capability center for DAL: switches on the reviewed MCP connectors, skills and engine packages a task needs (installed automatically from the signed DAL market), with /capabilities to list, disable and enable them.",
6
6
  "license": "MIT",
@@ -23,9 +23,9 @@
23
23
  ]
24
24
  },
25
25
  "dependencies": {
26
- "@dalcode/dal-mcp": "1.0.41",
27
- "@dalcode/dal-pi-kit": "1.0.41",
28
- "@dalcode/deepailab": "1.0.41"
26
+ "@dalcode/dal-mcp": "1.0.42",
27
+ "@dalcode/dal-pi-kit": "1.0.42",
28
+ "@dalcode/deepailab": "1.0.42"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@earendil-works/pi-coding-agent": "^1.0.9"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-compat",
3
- "version": "1.0.41",
3
+ "version": "1.0.42",
4
4
  "private": true,
5
5
  "description": "Claude Code compatibility: the user's and project's .claude/rules/ and .claude/CLAUDE.md apply in DAL. Grown from the claude-rules extension example.",
6
6
  "type": "module",
@@ -18,7 +18,7 @@
18
18
  ]
19
19
  },
20
20
  "dependencies": {
21
- "@dalcode/dal-pi-kit": "1.0.41",
21
+ "@dalcode/dal-pi-kit": "1.0.42",
22
22
  "minimatch": "10.2.6"
23
23
  },
24
24
  "peerDependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-dap",
3
- "version": "1.0.41",
3
+ "version": "1.0.42",
4
4
  "private": true,
5
5
  "description": "Debugger for DAL: breakpoints, stepping, call stacks and variables in Node.js and Python programs over the Debug Adapter Protocol, installing the adapter on first use. The DAP client is adapted from oh-my-pi's src/dap (MIT).",
6
6
  "license": "MIT",
@@ -24,7 +24,7 @@
24
24
  ]
25
25
  },
26
26
  "dependencies": {
27
- "@dalcode/dal-pi-kit": "1.0.41",
27
+ "@dalcode/dal-pi-kit": "1.0.42",
28
28
  "typebox": "1.3.27"
29
29
  },
30
30
  "peerDependencies": {