dal-code 1.0.36 → 1.0.38

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 (121) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/core/agent-session.d.ts +4 -1
  3. package/dist/core/agent-session.js +8 -8
  4. package/dist/core/auth-storage.js +1 -1
  5. package/dist/core/compaction/utils.js +5 -6
  6. package/dist/core/extensions/index.d.ts +1 -1
  7. package/dist/core/extensions/runner.d.ts +3 -2
  8. package/dist/core/extensions/runner.js +1 -1
  9. package/dist/core/extensions/types.d.ts +11 -3
  10. package/dist/core/model-runtime.js +2 -2
  11. package/dist/core/package-manager.d.ts +4 -0
  12. package/dist/core/package-manager.js +2 -2
  13. package/dist/core/session-manager.d.ts +3 -0
  14. package/dist/core/session-manager.js +12 -12
  15. package/dist/core/settings-diagnostics.js +1 -1
  16. package/dist/core/settings-manager.d.ts +3 -0
  17. package/dist/core/settings-manager.js +1 -1
  18. package/dist/core/shared-data.js +1 -0
  19. package/dist/core/system-prompt.js +10 -10
  20. package/dist/core/trust-manager.js +2 -2
  21. package/dist/dal/reviewed/endorsed-cli.js +1 -0
  22. package/dist/dal/reviewed/endorsed-plan.js +1 -0
  23. package/dist/dal/reviewed/endorsed.js +1 -0
  24. package/dist/dal/reviewed/version.js +1 -0
  25. package/dist/extensions/mcp/config.js +2 -2
  26. package/dist/index.d.ts +1 -1
  27. package/dist/modes/print-mode.js +5 -5
  28. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  29. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  30. package/dist/node_modules/@dalcode/dal-goal/package.json +2 -2
  31. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  32. package/dist/node_modules/@dalcode/dal-guard/src/mode.js +2 -2
  33. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  34. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  35. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  36. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  37. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  38. package/dist/node_modules/@dalcode/dal-mcp/src/config-edit.js +2 -2
  39. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  40. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
  41. package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
  42. package/dist/node_modules/@dalcode/dal-pi-kit/dist/shared-data.js +1 -0
  43. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  44. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
  45. package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
  46. package/dist/node_modules/@dalcode/dal-pi-kit/src/shared-data.js +1 -0
  47. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  48. package/dist/node_modules/@dalcode/dal-plugins/src/state.js +2 -2
  49. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  50. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  51. package/dist/node_modules/@dalcode/dal-rewind/src/index.js +1 -1
  52. package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
  53. package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +1 -1
  54. package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
  55. package/dist/node_modules/@dalcode/dal-router/src/index.js +1 -1
  56. package/dist/node_modules/@dalcode/dal-router/src/runtime.js +1 -1
  57. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  58. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  59. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +14 -12
  60. package/dist/node_modules/@dalcode/dal-subagent/src/process-runner.js +2 -2
  61. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  62. package/dist/node_modules/@dalcode/dal-telemetry/src/config.js +2 -2
  63. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  64. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  65. package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -4
  66. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  67. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  68. package/dist/node_modules/@dalcode/dal-workflow/src/plan-mode.js +14 -14
  69. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  70. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  71. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  72. package/dist/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +5 -5
  73. package/dist/node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.js +1 -1
  74. package/dist/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js +4 -4
  75. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +5 -5
  76. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +4 -4
  77. package/dist/node_modules/@earendil-works/pi-ai/dist/api/transform-messages.js +1 -1
  78. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  79. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  80. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  81. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  82. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  83. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  84. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
  85. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
  86. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
  87. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi.json +1 -1
  88. package/dist/node_modules/@earendil-works/pi-ai/dist/types.d.ts +1 -0
  89. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/json-parse.d.ts +2 -0
  90. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/json-parse.js +5 -2
  91. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts +1 -1
  92. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +1 -1
  93. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +1 -1
  94. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/validation.js +2 -2
  95. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -6
  96. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  97. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  98. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  99. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  100. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  101. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  102. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  103. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  104. package/dist/package-manager-cli.js +72 -72
  105. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  106. package/examples/extensions/gondolin/package-lock.json +2 -2
  107. package/examples/extensions/gondolin/package.json +1 -1
  108. package/examples/extensions/plan-mode/index.ts +6 -2
  109. package/examples/extensions/sandbox/package-lock.json +2 -2
  110. package/examples/extensions/sandbox/package.json +1 -1
  111. package/examples/extensions/with-deps/package-lock.json +2 -2
  112. package/examples/extensions/with-deps/package.json +1 -1
  113. package/npm-shrinkwrap.json +2 -2
  114. package/package.json +1 -1
  115. package/dist/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic.js +0 -1
  116. package/dist/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot.js +0 -1
  117. package/dist/node_modules/@earendil-works/pi-ai/dist/auth/oauth/openai-codex.js +0 -1
  118. package/dist/node_modules/@earendil-works/pi-ai/dist/bun-oauth.js +0 -1
  119. package/examples/extensions/custom-provider-anthropic/index.ts +0 -617
  120. package/examples/extensions/custom-provider-anthropic/package-lock.json +0 -24
  121. package/examples/extensions/custom-provider-anthropic/package.json +0 -19
@@ -1,12 +1,12 @@
1
- var me=Object.defineProperty;var c=(i,e)=>me(i,"name",{value:e,configurable:!0});import{getCurrentSystemMessage as ye,uuidv7 as Ie}from"@earendil-works/pi-ai";import{randomUUID as Y}from"crypto";import{appendFileSync as $,closeSync as A,createReadStream as ge,existsSync as C,mkdirSync as j,openSync as B,readdirSync as X,readSync as k,statSync as G,writeFileSync as H}from"fs";import{readdir as U,stat as q}from"fs/promises";import{basename as Q,join as x,resolve as Se}from"path";import{createInterface as we}from"readline";import{StringDecoder as ee}from"string_decoder";import{APP_NAME as Ee,getAgentDir as te,getSessionsDir as be}from"../config.js";import{normalizePath as _,resolvePath as b}from"../utils/paths.js";import{createBranchSummaryMessage as _e,createCompactionSummaryMessage as xe,createCustomMessage as Ce}from"./messages.js";const M=3;function P(){return Ie()}c(P,"createSessionId");function ne(i){if(!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(i))throw new Error("Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character")}c(ne,"assertValidSessionId");function S(i){for(let e=0;e<100;e++){const t=Y().slice(0,8);if(!i.has(t))return t}return Y()}c(S,"generateId");function Te(i){const e=new Set;let t=null;for(const n of i){if(n.type==="session"){n.version=2;continue}if(n.id=S(e),n.parentId=t,t=n.id,n.type==="compaction"){const s=n;if(typeof s.firstKeptEntryIndex=="number"){const r=i[s.firstKeptEntryIndex];r&&r.type!=="session"&&(s.firstKeptEntryId=r.id),delete s.firstKeptEntryIndex}}}}c(Te,"migrateV1ToV2");function ve(i){for(const e of i){if(e.type==="session"){e.version=3;continue}if(e.type==="message"){const t=e;t.message&&t.message.role==="hookMessage"&&(t.message.role="custom")}}}c(ve,"migrateV2ToV3");function se(i){const t=i.find(n=>n.type==="session")?.version??1;return t>=M?!1:(t<2&&Te(i),t<3&&ve(i),!0)}c(se,"migrateToCurrentVersion");function qe(i){se(i)}c(qe,"migrateSessionEntries");function Qe(i){const e=[],t=i.trim().split(`
2
- `);for(const n of t)if(n.trim())try{const s=JSON.parse(n);e.push(s)}catch{}return e}c(Qe,"parseSessionEntries");function et(i){for(let e=i.length-1;e>=0;e--)if(i[e].type==="compaction")return i[e];return null}c(et,"getLatestCompactionEntry");function De(i,e){if(e)return e;const t=new Map;for(const n of i)t.set(n.id,n);return t}c(De,"buildEntryIndex");function ie(i,e,t){const n=De(i,t);let s;if(e===null)return[];if(e&&(s=n.get(e)),s??=i[i.length-1],!s)return[];const r=[];let o=s;for(;o;)r.push(o),o=o.parentId?n.get(o.parentId):void 0;return r.reverse(),r}c(ie,"buildSessionPath");function Ne(i){let e="off",t=null;for(const n of i)n.type==="thinking_level_change"?e=n.thinkingLevel:n.type==="model_change"?t={provider:n.provider,modelId:n.modelId}:n.type==="message"&&n.message.role==="assistant"&&(t={provider:n.message.provider,modelId:n.message.model});return{thinkingLevel:e,model:t}}c(Ne,"getSessionContextSettings");function Fe(i){if(i.type==="message"){const e=i.message;return e.role==="system"&&e.content==null?[{...e,content:""}]:(e.role==="user"||e.role==="assistant"||e.role==="toolResult")&&e.content==null?[{...e,content:[]}]:[e]}if(i.type==="custom_message")return[Ce(i.customType,i.content??[],i.display,i.details,i.timestamp)];if(i.type==="branch_summary"&&i.summary)return[_e(i.summary,i.fromId,i.timestamp)];if(i.type==="compaction"){const e=xe(i.summary,i.tokensBefore,i.timestamp);return i.systemMessage?[i.systemMessage,e]:[e]}return[]}c(Fe,"sessionEntryToContextMessages");function re(i,e,t){const n=ie(i,e,t);let s=null;for(const d of n)d.type==="compaction"&&(s=d);if(!s)return n;const r=n.findIndex(d=>d.id===s.id);if(r<0)return n;const o=[s];let l=!1;for(let d=0;d<r;d++){const a=n[d];a.id===s.firstKeptEntryId&&(l=!0),l&&!(a.type==="message"&&a.message.role==="system")&&o.push(a)}return o.push(...n.slice(r+1)),o}c(re,"buildContextEntries");function Ae(i,e){const t=Fe(i);if(!e)return t;const n=e.replacement;return n===null?[]:t.map(s=>{if(s.role!=="user"&&s.role!=="assistant"&&s.role!=="toolResult"&&s.role!=="custom")return s;const r=(s.role==="assistant"||s.role==="toolResult")&&typeof n.content=="string"?[{type:"text",text:n.content}]:n.content;return{...s,content:r}})}c(Ae,"projectContextEntry");function oe(i,e,t){const n=ie(i,e,t),{thinkingLevel:s,model:r}=Ne(n),o=re(i,e,t),l=new Map;for(const a of o)a.type==="context_edit"&&l.set(a.targetId,a);const d=o.map((a,u)=>({sourceEntry:a,messages:a.type==="compaction"&&u>0?[]:Ae(a,l.get(a.id))}));return{entries:d,messages:d.flatMap(a=>a.messages),thinkingLevel:s,model:r}}c(oe,"buildSessionProjection");function tt(i,e,t){const{messages:n,thinkingLevel:s,model:r}=oe(i,e,t);return{messages:n,thinkingLevel:s,model:r}}c(tt,"buildSessionContext");function D(i,e=te()){const t=b(i),n=b(e),s=`--${t.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`;return x(n,"sessions",s)}c(D,"getDefaultSessionDirPath");function N(i,e=te()){const t=D(i,e);return C(t)||j(t,{recursive:!0}),t}c(N,"getDefaultSessionDir");const Be=1024*1024,Me=4096,V=1024*1024;class ae extends Error{static{c(this,"SessionHeaderScanLimitError")}constructor(e){super(`Session header exceeds ${V}-byte scan limit: ${e}`),this.name="SessionHeaderScanLimitError"}}function L(i){if(!i.trim())return null;try{return JSON.parse(i)}catch{return null}}c(L,"parseSessionEntryLine");function K(i){const e=_(i);if(!C(e))return[];const t=[];let n="";const s=B(e,"r");try{const o=new ee("utf8"),l=Buffer.allocUnsafe(Be);for(;;){const a=k(s,l,0,l.length,null);if(a===0)break;n+=o.write(l.subarray(0,a));let u=0,p=n.indexOf(`
3
- `,u);for(;p!==-1;){const m=L(n.slice(u,p));m&&t.push(m),u=p+1,p=n.indexOf(`
4
- `,u)}n=n.slice(u)}n+=o.end();const d=L(n);d&&t.push(d)}finally{A(s)}if(t.length===0)return t;const r=t[0];return r.type!=="session"||typeof r.id!="string"?[]:(n&&$(e,`
5
- `),t)}c(K,"loadEntriesFromFile");function W(i){if(!i.trim())return;const e=L(i);if(e)return e.type!=="session"||typeof e.id!="string"?null:e}c(W,"parseSessionHeaderCandidate");function le(i){const e=B(i,"r");try{const t=new ee("utf8"),n=Buffer.allocUnsafe(Me),s=[];let r=0;for(;r<V;){const l=Math.min(n.length,V-r),d=k(e,n,0,l,null);if(d===0)return s.push(t.end()),W(s.join(""))??null;r+=d;const a=t.write(n.subarray(0,d));let u=0,p=a.indexOf(`
6
- `,u);for(;p!==-1;){s.push(a.slice(u,p));const m=W(s.join(""));if(m!==void 0)return m;s.length=0,u=p+1,p=a.indexOf(`
7
- `,u)}s.push(a.slice(u))}const o=Buffer.allocUnsafe(1);if(k(e,o,0,o.length,null)===0)return s.push(t.end()),W(s.join(""))??null;throw new ae(i)}finally{A(e)}}c(le,"readSessionHeader");function de(i){try{return le(i)}catch{return null}}c(de,"readSessionHeaderForDiscovery");function z(i){const e=i.cwd;return typeof e=="string"?e:void 0}c(z,"getSessionHeaderCwd");function J(i,e){return i!==void 0&&i!==""&&b(i)===e}c(J,"sessionCwdMatches");function Le(i,e){const t=_(i),n=e?b(e):void 0;try{const s=X(t).filter(r=>r.endsWith(".jsonl")).map(r=>x(t,r)).map(r=>({path:r,mtime:G(r).mtimeMs})).sort((r,o)=>o.mtime-r.mtime);for(const{path:r}of s){const o=de(r);if(o&&(!n||J(z(o),n)))return r}return null}catch{return null}}c(Le,"findMostRecentSession");function ce(i){return typeof i.role=="string"&&"content"in i}c(ce,"isMessageWithContent");function Re(i){const e=i.content;return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(" ")}c(Re,"extractTextContent");function Oe(i){const e=i.message;if(!ce(e)||e.role!=="user"&&e.role!=="assistant")return;const t=e.timestamp;if(typeof t=="number")return t;const n=new Date(i.timestamp).getTime();return Number.isNaN(n)?void 0:n}c(Oe,"getMessageActivityTime");async function $e(i,e,t){try{const n=t??await q(i);let s=null,r=0,o="";const l=[];let d,a;const u=we({input:ge(i,{encoding:"utf8",signal:e}),crlfDelay:1/0});for await(const w of u){const g=L(w);if(!g)continue;if(!s){if(g.type!=="session")return null;s=g;continue}if(g.type==="session_info"&&(d=g.name?.trim()||void 0),g.type!=="message")continue;r++;const h=Oe(g);typeof h=="number"&&(a=Math.max(a??0,h));const f=g.message;if(!ce(f)||f.role!=="user"&&f.role!=="assistant")continue;const y=Re(f);y&&(l.push(y),!o&&f.role==="user"&&(o=y))}if(!s)return null;const p=typeof s.cwd=="string"?s.cwd:"",m=s.parentSession,I=typeof s.timestamp=="string"?new Date(s.timestamp).getTime():NaN,E=typeof a=="number"&&a>0?new Date(a):Number.isNaN(I)?n.mtime:new Date(I);return{path:i,id:s.id,cwd:p,name:d,parentSessionPath:m,created:new Date(s.timestamp),modified:E,messageCount:r,firstMessage:o||"(no messages)",allMessagesText:l.join(" ")}}catch{return e?.throwIfAborted(),null}}c($e,"buildSessionInfo");const je=10,fe=64,ke=10,He=100;async function Z(i,e,t,n){const s=new Array(i.length);let r=0;const o=c(async()=>{for(;r<i.length;){n?.throwIfAborted();const l=r++;s[l]=await t(i[l],l)}},"worker");return await Promise.all(Array.from({length:Math.min(e,i.length)},()=>o())),s}c(Z,"mapWithConcurrency");function F(i){return i.sort((e,t)=>t.modified.getTime()-e.modified.getTime())}c(F,"sortSessionInfos");function ue(i,e,t){return Z(i,je,async(n,s)=>{const r=await $e(n.path,t,n.stats);return e(r,s),r},t)}c(ue,"buildSessionInfosWithConcurrency");async function he(i,e,t){if(t?.throwIfAborted(),!C(i))return[];try{const s=(await U(i)).filter(a=>a.endsWith(".jsonl")).sort((a,u)=>u.localeCompare(a)).map(a=>({path:x(i,a)})),r=s.length,o=[];let l=0;return(await ue(s,a=>{l++,a&&o.push(a);const u=l===1||l%ke===0||l===s.length;e?.(l,r,u?F([...o]):void 0)},t)).filter(a=>a!==null)}catch{return t?.throwIfAborted(),[]}}c(he,"listSessionsFromDir");class T{static{c(this,"SessionManager")}sessionId="";sessionFile;sessionDir;cwd;persist;flushed=!1;fileEntries=[];byId=new Map;labelsById=new Map;labelTimestampsById=new Map;leafId=null;constructor(e,t,n,s,r,o){this.cwd=b(e),this.sessionDir=_(t),this.persist=s,s&&this.sessionDir&&!C(this.sessionDir)&&j(this.sessionDir,{recursive:!0}),n?this._setSessionFile(n,o):o?.length?this._loadEntries(o,r):this.newSession(r)}setSessionFile(e){this._setSessionFile(e)}_setSessionFile(e,t){if(this.sessionFile=b(e),C(this.sessionFile)){const n=t??K(this.sessionFile);if(n.length===0){const s=this.sessionFile;if(G(s).size>0)throw new Error(`Session file is not a valid ${Ee} session: ${s}`);this.newSession(),this.sessionFile=s,this._rewriteFile(),this.flushed=!0;return}this._loadEntries(n),this.flushed=!0}else{const n=this.sessionFile;this.newSession(),this.sessionFile=n}}newSession(e){e?.id!==void 0&&ne(e.id),this.sessionId=e?.id??P();const t=new Date().toISOString(),n={type:"session",version:M,id:this.sessionId,timestamp:t,cwd:this.cwd,parentSession:e?.parentSession};if(this.fileEntries=[n],this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null,this.flushed=!1,this.persist){const s=t.replace(/[:.]/g,"-");this.sessionFile=x(this.getSessionDir(),`${s}_${this.sessionId}.jsonl`)}return this.sessionFile}_loadEntries(e,t){const n=e.find(s=>s.type==="session");n?(this.fileEntries=e,this.sessionId=n.id,se(this.fileEntries)&&this._rewriteFile()):(this.newSession(t),this.fileEntries=this.fileEntries.concat(e)),this._buildIndex()}_buildIndex(){this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null;for(const e of this.fileEntries)e.type!=="session"&&(this.byId.set(e.id,e),this.leafId=e.id,e.type==="label"&&(e.label?(this.labelsById.set(e.targetId,e.label),this.labelTimestampsById.set(e.targetId,e.timestamp)):(this.labelsById.delete(e.targetId),this.labelTimestampsById.delete(e.targetId))))}_rewriteFile(){if(!this.persist||!this.sessionFile)return;const e=B(this.sessionFile,"w");try{for(const t of this.fileEntries)H(e,`${JSON.stringify(t)}
8
- `)}finally{A(e)}}isPersisted(){return this.persist}getCwd(){return this.cwd}getSessionDir(){return this.sessionDir}usesDefaultSessionDir(){return this.sessionDir===D(this.cwd)}getSessionId(){return this.sessionId}getSessionFile(){return this.sessionFile}_hasConversation(){return this.fileEntries.some(e=>e.type==="message"&&(e.message.role==="user"||e.message.role==="assistant"))}_persist(e){if(!(!this.persist||!this.sessionFile))if(this.flushed)$(this.sessionFile,`${JSON.stringify(e)}
9
- `);else{if(!this._hasConversation())return;const t=B(this.sessionFile,"wx");try{for(const n of this.fileEntries)H(t,`${JSON.stringify(n)}
10
- `)}finally{A(t)}this.flushed=!0}}_appendEntry(e){this.fileEntries.push(e),this.byId.set(e.id,e),this.leafId=e.id,this._persist(e)}appendMessage(e){const t={type:"message",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),message:e};return this._appendEntry(t),t.id}appendThinkingLevelChange(e){const t={type:"thinking_level_change",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),thinkingLevel:e};return this._appendEntry(t),t.id}appendModelChange(e,t){const n={type:"model_change",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),provider:e,modelId:t};return this._appendEntry(n),n.id}appendUsage(e,t,n,s,r){const o={type:"usage",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),kind:e,provider:t,model:n,usage:s,...r?{note:r}:{}};return this._appendEntry(o),o}appendCompaction(e,t,n,s,r,o){const l=new Date().toISOString(),d=ye(this.buildSessionProjection().messages),a=S(this.byId),u={type:"compaction",id:a,parentId:this.leafId,timestamp:l,summary:e,firstKeptEntryId:t??a,tokensBefore:n,details:s,usage:o,fromHook:r,...d?{systemMessage:{...d,timestamp:new Date(l).getTime()}}:{}};return this._appendEntry(u),u.id}appendCustomEntry(e,t){const n={type:"custom",customType:e,data:t,id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(n),n.id}appendSessionInfo(e){const t=e.replace(/[\r\n]+/g," ").trim(),n={type:"session_info",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),name:t};return this._appendEntry(n),n.id}getSessionName(){for(let e=this.fileEntries.length-1;e>=0;e--){const t=this.fileEntries[e];if(t.type==="session_info")return t.name?.trim()||void 0}}appendCustomMessageEntry(e,t,n,s){const r={type:"custom_message",customType:e,content:t,display:n,details:s,id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(r),r.id}appendContextEdit(e,t){if(t!==null&&(typeof t!="object"||!("content"in t)||typeof t.content!="string"&&!Array.isArray(t.content)))throw new Error("Context edit replacement must be null or contain string/array content");const n=this.byId.get(e);if(!n)throw new Error(`Entry ${e} not found`);if(!this.getBranch().some(d=>d.id===e))throw new Error(`Entry ${e} is not on the active branch`);if(!(n.type==="custom_message"||n.type==="message"&&(n.message.role==="user"||n.message.role==="assistant"||n.message.role==="toolResult")))throw new Error(`Entry ${e} does not contribute editable model content`);const r=n.type==="message"?n.message.role:"custom",o=t!==null&&(r==="assistant"||r==="toolResult")&&typeof t.content=="string"?{content:[{type:"text",text:t.content}]}:t,l={type:"context_edit",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),targetId:e,replacement:o};return this._appendEntry(l),l.id}getLeafId(){return this.leafId}getLeafEntry(){return this.leafId?this.byId.get(this.leafId):void 0}getEntry(e){return this.byId.get(e)}getChildren(e){const t=[];for(const n of this.byId.values())n.parentId===e&&t.push(n);return t}getLabel(e){return this.labelsById.get(e)}appendLabelChange(e,t){if(!this.byId.has(e))throw new Error(`Entry ${e} not found`);const n={type:"label",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),targetId:e,label:t};return this._appendEntry(n),t?(this.labelsById.set(e,t),this.labelTimestampsById.set(e,n.timestamp)):(this.labelsById.delete(e),this.labelTimestampsById.delete(e)),n.id}getBranch(e){const t=[],n=e??this.leafId;let s=n?this.byId.get(n):void 0;for(;s;)t.push(s),s=s.parentId?this.byId.get(s.parentId):void 0;return t.reverse(),t}buildContextEntries(){return re(this.getEntries(),this.leafId,this.byId)}buildSessionProjection(){return oe(this.getEntries(),this.leafId,this.byId)}buildSessionContext(){const{messages:e,thinkingLevel:t,model:n}=this.buildSessionProjection();return{messages:e,thinkingLevel:t,model:n}}getHeader(){const e=this.fileEntries.find(t=>t.type==="session");return e||null}getEntryCount(){return this.byId.size}getEntries(){return this.fileEntries.filter(e=>e.type!=="session")}getTree(){const e=this.getEntries(),t=new Map,n=[];for(const r of e){const o=this.labelsById.get(r.id),l=this.labelTimestampsById.get(r.id);t.set(r.id,{entry:r,children:[],label:o,labelTimestamp:l})}for(const r of e){const o=t.get(r.id);if(r.parentId===null||r.parentId===r.id)n.push(o);else{const l=t.get(r.parentId);l?l.children.push(o):n.push(o)}}const s=[...n];for(;s.length>0;){const r=s.pop();r.children.sort((o,l)=>new Date(o.entry.timestamp).getTime()-new Date(l.entry.timestamp).getTime()),s.push(...r.children)}return n}branch(e){if(!this.byId.has(e))throw new Error(`Entry ${e} not found`);this.leafId=e}resetLeaf(){this.leafId=null}branchWithSummary(e,t,n,s,r){if(e!==null&&!this.byId.has(e))throw new Error(`Entry ${e} not found`);const o=this.leafId??"root";this.leafId=e;const l={type:"branch_summary",id:S(this.byId),parentId:e,timestamp:new Date().toISOString(),fromId:o,summary:t,details:n,usage:r,fromHook:s};return this._appendEntry(l),l.id}createBranchedSession(e){const t=this.sessionFile,n=this.getBranch(e);if(n.length===0)throw new Error(`Entry ${e} not found`);const s=[],r=new Map,o=[];let l=null;for(const h of n){if(h.type==="label"){o.push(h.id);continue}for(const f of o)r.set(f,h.id);o.length=0,s.push(h.type==="compaction"?{...h,parentId:l,firstKeptEntryId:h.firstKeptEntryId===h.id?h.id:r.get(h.firstKeptEntryId)??h.firstKeptEntryId}:{...h,parentId:l}),l=h.id}const d=P(),a=new Date().toISOString(),u=a.replace(/[:.]/g,"-"),p=x(this.getSessionDir(),`${u}_${d}.jsonl`),m={type:"session",version:M,id:d,timestamp:a,cwd:this.cwd,parentSession:this.persist?t:void 0},I=new Set(s.map(h=>h.id)),E=[];for(const[h,f]of this.labelsById)I.has(h)&&E.push({targetId:h,label:f,timestamp:this.labelTimestampsById.get(h)});if(this.persist){let f=s[s.length-1]?.id||null;const y=[];for(const{targetId:v,label:R,timestamp:pe}of E){const O={type:"label",id:S(new Set(I)),parentId:f,timestamp:pe,targetId:v,label:R};I.add(O.id),y.push(O),f=O.id}return this.fileEntries=[m,...s,...y],this.sessionId=d,this.sessionFile=p,this._buildIndex(),this._hasConversation()?(this._rewriteFile(),this.flushed=!0):this.flushed=!1,p}const w=[];let g=s[s.length-1]?.id||null;for(const{targetId:h,label:f,timestamp:y}of E){const v={type:"label",id:S(new Set([...I,...w.map(R=>R.id)])),parentId:g,timestamp:y,targetId:h,label:f};w.push(v),g=v.id}this.fileEntries=[m,...s,...w],this.sessionId=d,this._buildIndex()}static create(e,t,n){const s=t?_(t):N(e);return new T(e,s,void 0,!0,n)}static open(e,t,n){const s=b(e);let r=null,o;if(n===void 0&&C(s))try{r=le(s)}catch(a){if(!(a instanceof ae))throw a;o=K(s);const u=o[0];r=u?.type==="session"?u:null}const l=n??(r?z(r):void 0)??process.cwd(),d=t?_(t):Se(s,"..");return new T(l,d,s,!0,void 0,o)}static continueRecent(e,t){const n=t?_(t):N(e),s=t!==void 0&&n!==D(e),r=Le(n,s?e:void 0);return r?new T(e,n,r,!0):new T(e,n,void 0,!0)}static inMemory(e=process.cwd(),t,n){return new T(e,"",void 0,!1,t,n)}static forkFrom(e,t,n,s){const r=b(e),o=b(t),l=K(r);if(l.length===0)throw new Error(`Cannot fork: source session file is empty or invalid: ${r}`);if(!l.find(w=>w.type==="session"))throw new Error(`Cannot fork: source session has no header: ${r}`);const a=n?_(n):N(o);C(a)||j(a,{recursive:!0}),s?.id!==void 0&&ne(s.id);const u=s?.id??P(),p=new Date().toISOString(),m=p.replace(/[:.]/g,"-"),I=x(a,`${m}_${u}.jsonl`);H(I,`${JSON.stringify({type:"session",version:M,id:u,timestamp:p,cwd:o,parentSession:r})}
11
- `,{flag:"wx"});for(const w of l)w.type!=="session"&&$(I,`${JSON.stringify(w)}
12
- `);return new T(o,a,I,!0)}static findById(e,t,n){const s=n?_(n):N(e),r=n!==void 0&&s!==D(e),o=b(e);try{for(const l of X(s)){if(!l.endsWith(".jsonl"))continue;const d=x(s,l),a=de(d);if(a?.id===t&&!(r&&!J(z(a),o)))return d}}catch{}}static async list(e,t,n,s){const r=t?_(t):N(e),o=t!==void 0&&r!==D(e),l=b(e),d=c(p=>!o||J(p.cwd,l),"includeSession"),u=(await he(r,n?(p,m,I)=>n(p,m,I?.filter(d)):void 0,s)).filter(d);return F(u)}static async listAll(e,t,n){const s=typeof e=="string"?_(e):void 0,r=typeof e=="function"?e:typeof t=="function"?t:void 0,o=typeof e=="string"||typeof t=="function"?n:t??n;if(o?.throwIfAborted(),s)return F(await he(s,r,o));const l=be();try{if(!C(l))return[];const a=(await U(l,{withFileTypes:!0})).filter(f=>f.isDirectory()||f.isSymbolicLink()).map(f=>x(l,f.name)),p=(await Z(a,fe,async f=>{try{return(await U(f)).filter(y=>y.endsWith(".jsonl")).map(y=>x(f,y))}catch{return[]}},o)).flat(),m=await Z(p,fe,async f=>{try{return{path:f,stats:await q(f)}}catch{return{path:f}}},o);m.sort((f,y)=>(y.stats?.mtimeMs??Number.NEGATIVE_INFINITY)-(f.stats?.mtimeMs??Number.NEGATIVE_INFINITY)||Q(y.path).localeCompare(Q(f.path)));const I=m.length;let E=0,w=!1;const g=[],h=await ue(m,(f,y)=>{E++,y===0&&(w=!0),f&&g.push(f);const v=w&&(y===0||E%He===0||E===I);r?.(E,I,v?F([...g]):void 0)},o);return F(h.filter(f=>f!==null))}catch{return o?.throwIfAborted(),[]}}}export{M as CURRENT_SESSION_VERSION,T as SessionManager,ne as assertValidSessionId,re as buildContextEntries,tt as buildSessionContext,oe as buildSessionProjection,Le as findMostRecentSession,N as getDefaultSessionDir,et as getLatestCompactionEntry,K as loadEntriesFromFile,qe as migrateSessionEntries,Qe as parseSessionEntries,Fe as sessionEntryToContextMessages};
1
+ var ye=Object.defineProperty;var c=(i,e)=>ye(i,"name",{value:e,configurable:!0});import{getCurrentSystemMessage as Ie,uuidv7 as ge}from"@earendil-works/pi-ai";import{randomUUID as Z}from"crypto";import{appendFileSync as R,closeSync as O,createReadStream as Se,existsSync as C,mkdirSync as $,openSync as j,readdirSync as Y,readSync as k,statSync as X,writeFileSync as G}from"fs";import{readdir as P,stat as q}from"fs/promises";import{basename as Q,join as x,resolve as we}from"path";import{createInterface as Ee}from"readline";import{StringDecoder as ee}from"string_decoder";import{APP_NAME as be,APP_TITLE as _e,getAgentDir as te,getSessionsDir as xe}from"../config.js";import{fill as Ce,t as Fe}from"../dal/i18n.js";import{normalizePath as _,resolvePath as b}from"../utils/paths.js";import{createBranchSummaryMessage as Te,createCompactionSummaryMessage as ve,createCustomMessage as De}from"./messages.js";import{reportNewerDataFormat as Ne,writeFileAtomicSync as Ae}from"./shared-data.js";const v=3;function ne(i){return typeof i?.version=="number"&&i.version>v}c(ne,"isNewerSessionFormat");function H(){return ge()}c(H,"createSessionId");function se(i){if(!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(i))throw new Error("Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character")}c(se,"assertValidSessionId");function S(i){for(let e=0;e<100;e++){const t=Z().slice(0,8);if(!i.has(t))return t}return Z()}c(S,"generateId");function Be(i){const e=new Set;let t=null;for(const n of i){if(n.type==="session"){n.version=2;continue}if(n.id=S(e),n.parentId=t,t=n.id,n.type==="compaction"){const s=n;if(typeof s.firstKeptEntryIndex=="number"){const r=i[s.firstKeptEntryIndex];r&&r.type!=="session"&&(s.firstKeptEntryId=r.id),delete s.firstKeptEntryIndex}}}}c(Be,"migrateV1ToV2");function Me(i){for(const e of i){if(e.type==="session"){e.version=3;continue}if(e.type==="message"){const t=e;t.message&&t.message.role==="hookMessage"&&(t.message.role="custom")}}}c(Me,"migrateV2ToV3");function ie(i){const t=i.find(n=>n.type==="session")?.version??1;return t>=v?!1:(t<2&&Be(i),t<3&&Me(i),!0)}c(ie,"migrateToCurrentVersion");function ot(i){ie(i)}c(ot,"migrateSessionEntries");function at(i){const e=[],t=i.trim().split(`
2
+ `);for(const n of t)if(n.trim())try{const s=JSON.parse(n);e.push(s)}catch{}return e}c(at,"parseSessionEntries");function lt(i){for(let e=i.length-1;e>=0;e--)if(i[e].type==="compaction")return i[e];return null}c(lt,"getLatestCompactionEntry");function Le(i,e){if(e)return e;const t=new Map;for(const n of i)t.set(n.id,n);return t}c(Le,"buildEntryIndex");function re(i,e,t){const n=Le(i,t);let s;if(e===null)return[];if(e&&(s=n.get(e)),s??=i[i.length-1],!s)return[];const r=[];let o=s;for(;o;)r.push(o),o=o.parentId?n.get(o.parentId):void 0;return r.reverse(),r}c(re,"buildSessionPath");function Re(i){let e="off",t=null;for(const n of i)n.type==="thinking_level_change"?e=n.thinkingLevel:n.type==="model_change"?t={provider:n.provider,modelId:n.modelId}:n.type==="message"&&n.message.role==="assistant"&&(t={provider:n.message.provider,modelId:n.message.model});return{thinkingLevel:e,model:t}}c(Re,"getSessionContextSettings");function Oe(i){if(i.type==="message"){const e=i.message;return e.role==="system"&&e.content==null?[{...e,content:""}]:(e.role==="user"||e.role==="assistant"||e.role==="toolResult")&&e.content==null?[{...e,content:[]}]:[e]}if(i.type==="custom_message")return[De(i.customType,i.content??[],i.display,i.details,i.timestamp)];if(i.type==="branch_summary"&&i.summary)return[Te(i.summary,i.fromId,i.timestamp)];if(i.type==="compaction"){const e=ve(i.summary,i.tokensBefore,i.timestamp);return i.systemMessage?[i.systemMessage,e]:[e]}return[]}c(Oe,"sessionEntryToContextMessages");function oe(i,e,t){const n=re(i,e,t);let s=null;for(const d of n)d.type==="compaction"&&(s=d);if(!s)return n;const r=n.findIndex(d=>d.id===s.id);if(r<0)return n;const o=[s];let l=!1;for(let d=0;d<r;d++){const a=n[d];a.id===s.firstKeptEntryId&&(l=!0),l&&!(a.type==="message"&&a.message.role==="system")&&o.push(a)}return o.push(...n.slice(r+1)),o}c(oe,"buildContextEntries");function $e(i,e){const t=Oe(i);if(!e)return t;const n=e.replacement;return n===null?[]:t.map(s=>{if(s.role!=="user"&&s.role!=="assistant"&&s.role!=="toolResult"&&s.role!=="custom")return s;const r=(s.role==="assistant"||s.role==="toolResult")&&typeof n.content=="string"?[{type:"text",text:n.content}]:n.content;return{...s,content:r}})}c($e,"projectContextEntry");function ae(i,e,t){const n=re(i,e,t),{thinkingLevel:s,model:r}=Re(n),o=oe(i,e,t),l=new Map;for(const a of o)a.type==="context_edit"&&l.set(a.targetId,a);const d=o.map((a,u)=>({sourceEntry:a,messages:a.type==="compaction"&&u>0?[]:$e(a,l.get(a.id))}));return{entries:d,messages:d.flatMap(a=>a.messages),thinkingLevel:s,model:r}}c(ae,"buildSessionProjection");function dt(i,e,t){const{messages:n,thinkingLevel:s,model:r}=ae(i,e,t);return{messages:n,thinkingLevel:s,model:r}}c(dt,"buildSessionContext");function D(i,e=te()){const t=b(i),n=b(e),s=`--${t.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`;return x(n,"sessions",s)}c(D,"getDefaultSessionDirPath");function N(i,e=te()){const t=D(i,e);return C(t)||$(t,{recursive:!0}),t}c(N,"getDefaultSessionDir");const je=1024*1024,ke=4096,U=1024*1024;class le extends Error{static{c(this,"SessionHeaderScanLimitError")}constructor(e){super(`Session header exceeds ${U}-byte scan limit: ${e}`),this.name="SessionHeaderScanLimitError"}}function B(i){if(!i.trim())return null;try{return JSON.parse(i)}catch{return null}}c(B,"parseSessionEntryLine");function V(i){const e=_(i);if(!C(e))return[];const t=[];let n="";const s=j(e,"r");try{const o=new ee("utf8"),l=Buffer.allocUnsafe(je);for(;;){const a=k(s,l,0,l.length,null);if(a===0)break;n+=o.write(l.subarray(0,a));let u=0,p=n.indexOf(`
3
+ `,u);for(;p!==-1;){const m=B(n.slice(u,p));m&&t.push(m),u=p+1,p=n.indexOf(`
4
+ `,u)}n=n.slice(u)}n+=o.end();const d=B(n);d&&t.push(d)}finally{O(s)}if(t.length===0)return t;const r=t[0];return r.type!=="session"||typeof r.id!="string"?[]:(n&&R(e,`
5
+ `),t)}c(V,"loadEntriesFromFile");function K(i){if(!i.trim())return;const e=B(i);if(e)return e.type!=="session"||typeof e.id!="string"?null:e}c(K,"parseSessionHeaderCandidate");function de(i){const e=j(i,"r");try{const t=new ee("utf8"),n=Buffer.allocUnsafe(ke),s=[];let r=0;for(;r<U;){const l=Math.min(n.length,U-r),d=k(e,n,0,l,null);if(d===0)return s.push(t.end()),K(s.join(""))??null;r+=d;const a=t.write(n.subarray(0,d));let u=0,p=a.indexOf(`
6
+ `,u);for(;p!==-1;){s.push(a.slice(u,p));const m=K(s.join(""));if(m!==void 0)return m;s.length=0,u=p+1,p=a.indexOf(`
7
+ `,u)}s.push(a.slice(u))}const o=Buffer.allocUnsafe(1);if(k(e,o,0,o.length,null)===0)return s.push(t.end()),K(s.join(""))??null;throw new le(i)}finally{O(e)}}c(de,"readSessionHeader");function ce(i){try{return de(i)}catch{return null}}c(ce,"readSessionHeaderForDiscovery");function W(i){const e=i.cwd;return typeof e=="string"?e:void 0}c(W,"getSessionHeaderCwd");function z(i,e){return i!==void 0&&i!==""&&b(i)===e}c(z,"sessionCwdMatches");function Pe(i,e){const t=_(i),n=e?b(e):void 0;try{const s=Y(t).filter(r=>r.endsWith(".jsonl")).map(r=>x(t,r)).map(r=>({path:r,mtime:X(r).mtimeMs})).sort((r,o)=>o.mtime-r.mtime);for(const{path:r}of s){const o=ce(r);if(o&&(!n||z(W(o),n)))return r}return null}catch{return null}}c(Pe,"findMostRecentSession");function fe(i){return typeof i.role=="string"&&"content"in i}c(fe,"isMessageWithContent");function He(i){const e=i.content;return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(" ")}c(He,"extractTextContent");function Ue(i){const e=i.message;if(!fe(e)||e.role!=="user"&&e.role!=="assistant")return;const t=e.timestamp;if(typeof t=="number")return t;const n=new Date(i.timestamp).getTime();return Number.isNaN(n)?void 0:n}c(Ue,"getMessageActivityTime");async function Ve(i,e,t){try{const n=t??await q(i);let s=null,r=0,o="";const l=[];let d,a;const u=Ee({input:Se(i,{encoding:"utf8",signal:e}),crlfDelay:1/0});for await(const w of u){const g=B(w);if(!g)continue;if(!s){if(g.type!=="session")return null;s=g;continue}if(g.type==="session_info"&&(d=g.name?.trim()||void 0),g.type!=="message")continue;r++;const h=Ue(g);typeof h=="number"&&(a=Math.max(a??0,h));const f=g.message;if(!fe(f)||f.role!=="user"&&f.role!=="assistant")continue;const y=He(f);y&&(l.push(y),!o&&f.role==="user"&&(o=y))}if(!s)return null;const p=typeof s.cwd=="string"?s.cwd:"",m=s.parentSession,I=typeof s.timestamp=="string"?new Date(s.timestamp).getTime():NaN,E=typeof a=="number"&&a>0?new Date(a):Number.isNaN(I)?n.mtime:new Date(I);return{path:i,id:s.id,cwd:p,name:d,parentSessionPath:m,created:new Date(s.timestamp),modified:E,messageCount:r,firstMessage:o||"(no messages)",allMessagesText:l.join(" ")}}catch{return e?.throwIfAborted(),null}}c(Ve,"buildSessionInfo");const Ke=10,ue=64,We=10,ze=100;async function J(i,e,t,n){const s=new Array(i.length);let r=0;const o=c(async()=>{for(;r<i.length;){n?.throwIfAborted();const l=r++;s[l]=await t(i[l],l)}},"worker");return await Promise.all(Array.from({length:Math.min(e,i.length)},()=>o())),s}c(J,"mapWithConcurrency");function A(i){return i.sort((e,t)=>t.modified.getTime()-e.modified.getTime())}c(A,"sortSessionInfos");function he(i,e,t){return J(i,Ke,async(n,s)=>{const r=await Ve(n.path,t,n.stats);return e(r,s),r},t)}c(he,"buildSessionInfosWithConcurrency");async function pe(i,e,t){if(t?.throwIfAborted(),!C(i))return[];try{const s=(await P(i)).filter(a=>a.endsWith(".jsonl")).sort((a,u)=>u.localeCompare(a)).map(a=>({path:x(i,a)})),r=s.length,o=[];let l=0;return(await he(s,a=>{l++,a&&o.push(a);const u=l===1||l%We===0||l===s.length;e?.(l,r,u?A([...o]):void 0)},t)).filter(a=>a!==null)}catch{return t?.throwIfAborted(),[]}}c(pe,"listSessionsFromDir");class F{static{c(this,"SessionManager")}sessionId="";sessionFile;sessionDir;cwd;persist;flushed=!1;newerFormat=!1;fileEntries=[];byId=new Map;labelsById=new Map;labelTimestampsById=new Map;leafId=null;constructor(e,t,n,s,r,o){this.cwd=b(e),this.sessionDir=_(t),this.persist=s,s&&this.sessionDir&&!C(this.sessionDir)&&$(this.sessionDir,{recursive:!0}),n?this._setSessionFile(n,o):o?.length?this._loadEntries(o,r):this.newSession(r)}setSessionFile(e){this._setSessionFile(e)}_setSessionFile(e,t){if(this.sessionFile=b(e),C(this.sessionFile)){const n=t??V(this.sessionFile);if(n.length===0){const s=this.sessionFile;if(X(s).size>0)throw new Error(`Session file is not a valid ${be} session: ${s}`);this.newSession(),this.sessionFile=s,this._rewriteFile(),this.flushed=!0;return}this._loadEntries(n),this.flushed=!0}else{const n=this.sessionFile;this.newSession(),this.sessionFile=n}}newSession(e){e?.id!==void 0&&se(e.id),this.sessionId=e?.id??H();const t=new Date().toISOString(),n={type:"session",version:v,id:this.sessionId,timestamp:t,cwd:this.cwd,parentSession:e?.parentSession};if(this.fileEntries=[n],this.newerFormat=!1,this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null,this.flushed=!1,this.persist){const s=t.replace(/[:.]/g,"-");this.sessionFile=x(this.getSessionDir(),`${s}_${this.sessionId}.jsonl`)}return this.sessionFile}_loadEntries(e,t){const n=e.find(s=>s.type==="session");n?(this.fileEntries=e,this.sessionId=n.id,this.newerFormat=ne(n),this.newerFormat?Ne(this.sessionFile??n.id):ie(this.fileEntries)&&this._rewriteFile()):(this.newSession(t),this.fileEntries=this.fileEntries.concat(e)),this._buildIndex()}_buildIndex(){this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null;for(const e of this.fileEntries)e.type!=="session"&&(this.byId.set(e.id,e),this.leafId=e.id,e.type==="label"&&(e.label?(this.labelsById.set(e.targetId,e.label),this.labelTimestampsById.set(e.targetId,e.timestamp)):(this.labelsById.delete(e.targetId),this.labelTimestampsById.delete(e.targetId))))}_rewriteFile(){!this.persist||!this.sessionFile||this.newerFormat||Ae(this.sessionFile,this.fileEntries.map(e=>`${JSON.stringify(e)}
8
+ `).join(""))}isPersisted(){return this.persist}isReadOnly(){return this.newerFormat}getCwd(){return this.cwd}getSessionDir(){return this.sessionDir}usesDefaultSessionDir(){return this.sessionDir===D(this.cwd)}getSessionId(){return this.sessionId}getSessionFile(){return this.sessionFile}_hasConversation(){return this.fileEntries.some(e=>e.type==="message"&&(e.message.role==="user"||e.message.role==="assistant"))}_persist(e){if(!(!this.persist||!this.sessionFile||this.newerFormat))if(this.flushed)R(this.sessionFile,`${JSON.stringify(e)}
9
+ `);else{if(!this._hasConversation())return;const t=j(this.sessionFile,"wx");try{for(const n of this.fileEntries)G(t,`${JSON.stringify(n)}
10
+ `)}finally{O(t)}this.flushed=!0}}_appendEntry(e){this.fileEntries.push(e),this.byId.set(e.id,e),this.leafId=e.id,this._persist(e)}appendMessage(e){const t={type:"message",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),message:e};return this._appendEntry(t),t.id}appendThinkingLevelChange(e){const t={type:"thinking_level_change",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),thinkingLevel:e};return this._appendEntry(t),t.id}appendModelChange(e,t){const n={type:"model_change",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),provider:e,modelId:t};return this._appendEntry(n),n.id}appendUsage(e,t,n,s,r){const o={type:"usage",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),kind:e,provider:t,model:n,usage:s,...r?{note:r}:{}};return this._appendEntry(o),o}appendCompaction(e,t,n,s,r,o){const l=new Date().toISOString(),d=Ie(this.buildSessionProjection().messages),a=S(this.byId),u={type:"compaction",id:a,parentId:this.leafId,timestamp:l,summary:e,firstKeptEntryId:t??a,tokensBefore:n,details:s,usage:o,fromHook:r,...d?{systemMessage:{...d,timestamp:new Date(l).getTime()}}:{}};return this._appendEntry(u),u.id}appendCustomEntry(e,t){const n={type:"custom",customType:e,data:t,id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(n),n.id}appendSessionInfo(e){const t=e.replace(/[\r\n]+/g," ").trim(),n={type:"session_info",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),name:t};return this._appendEntry(n),n.id}getSessionName(){for(let e=this.fileEntries.length-1;e>=0;e--){const t=this.fileEntries[e];if(t.type==="session_info")return t.name?.trim()||void 0}}appendCustomMessageEntry(e,t,n,s){const r={type:"custom_message",customType:e,content:t,display:n,details:s,id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(r),r.id}appendContextEdit(e,t){if(t!==null&&(typeof t!="object"||!("content"in t)||typeof t.content!="string"&&!Array.isArray(t.content)))throw new Error("Context edit replacement must be null or contain string/array content");const n=this.byId.get(e);if(!n)throw new Error(`Entry ${e} not found`);if(!this.getBranch().some(d=>d.id===e))throw new Error(`Entry ${e} is not on the active branch`);if(!(n.type==="custom_message"||n.type==="message"&&(n.message.role==="user"||n.message.role==="assistant"||n.message.role==="toolResult")))throw new Error(`Entry ${e} does not contribute editable model content`);const r=n.type==="message"?n.message.role:"custom",o=t!==null&&(r==="assistant"||r==="toolResult")&&typeof t.content=="string"?{content:[{type:"text",text:t.content}]}:t,l={type:"context_edit",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),targetId:e,replacement:o};return this._appendEntry(l),l.id}getLeafId(){return this.leafId}getLeafEntry(){return this.leafId?this.byId.get(this.leafId):void 0}getEntry(e){return this.byId.get(e)}getChildren(e){const t=[];for(const n of this.byId.values())n.parentId===e&&t.push(n);return t}getLabel(e){return this.labelsById.get(e)}appendLabelChange(e,t){if(!this.byId.has(e))throw new Error(`Entry ${e} not found`);const n={type:"label",id:S(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),targetId:e,label:t};return this._appendEntry(n),t?(this.labelsById.set(e,t),this.labelTimestampsById.set(e,n.timestamp)):(this.labelsById.delete(e),this.labelTimestampsById.delete(e)),n.id}getBranch(e){const t=[],n=e??this.leafId;let s=n?this.byId.get(n):void 0;for(;s;)t.push(s),s=s.parentId?this.byId.get(s.parentId):void 0;return t.reverse(),t}buildContextEntries(){return oe(this.getEntries(),this.leafId,this.byId)}buildSessionProjection(){return ae(this.getEntries(),this.leafId,this.byId)}buildSessionContext(){const{messages:e,thinkingLevel:t,model:n}=this.buildSessionProjection();return{messages:e,thinkingLevel:t,model:n}}getHeader(){const e=this.fileEntries.find(t=>t.type==="session");return e||null}getEntryCount(){return this.byId.size}getEntries(){return this.fileEntries.filter(e=>e.type!=="session")}getTree(){const e=this.getEntries(),t=new Map,n=[];for(const r of e){const o=this.labelsById.get(r.id),l=this.labelTimestampsById.get(r.id);t.set(r.id,{entry:r,children:[],label:o,labelTimestamp:l})}for(const r of e){const o=t.get(r.id);if(r.parentId===null||r.parentId===r.id)n.push(o);else{const l=t.get(r.parentId);l?l.children.push(o):n.push(o)}}const s=[...n];for(;s.length>0;){const r=s.pop();r.children.sort((o,l)=>new Date(o.entry.timestamp).getTime()-new Date(l.entry.timestamp).getTime()),s.push(...r.children)}return n}branch(e){if(!this.byId.has(e))throw new Error(`Entry ${e} not found`);this.leafId=e}resetLeaf(){this.leafId=null}branchWithSummary(e,t,n,s,r){if(e!==null&&!this.byId.has(e))throw new Error(`Entry ${e} not found`);const o=this.leafId??"root";this.leafId=e;const l={type:"branch_summary",id:S(this.byId),parentId:e,timestamp:new Date().toISOString(),fromId:o,summary:t,details:n,usage:r,fromHook:s};return this._appendEntry(l),l.id}createBranchedSession(e){const t=this.sessionFile,n=this.getBranch(e);if(n.length===0)throw new Error(`Entry ${e} not found`);const s=[],r=new Map,o=[];let l=null;for(const h of n){if(h.type==="label"){o.push(h.id);continue}for(const f of o)r.set(f,h.id);o.length=0,s.push(h.type==="compaction"?{...h,parentId:l,firstKeptEntryId:h.firstKeptEntryId===h.id?h.id:r.get(h.firstKeptEntryId)??h.firstKeptEntryId}:{...h,parentId:l}),l=h.id}const d=H(),a=new Date().toISOString(),u=a.replace(/[:.]/g,"-"),p=x(this.getSessionDir(),`${u}_${d}.jsonl`),m={type:"session",version:v,id:d,timestamp:a,cwd:this.cwd,parentSession:this.persist?t:void 0},I=new Set(s.map(h=>h.id)),E=[];for(const[h,f]of this.labelsById)I.has(h)&&E.push({targetId:h,label:f,timestamp:this.labelTimestampsById.get(h)});if(this.persist){let f=s[s.length-1]?.id||null;const y=[];for(const{targetId:T,label:M,timestamp:me}of E){const L={type:"label",id:S(new Set(I)),parentId:f,timestamp:me,targetId:T,label:M};I.add(L.id),y.push(L),f=L.id}return this.fileEntries=[m,...s,...y],this.sessionId=d,this.sessionFile=p,this._buildIndex(),this._hasConversation()?(this._rewriteFile(),this.flushed=!0):this.flushed=!1,p}const w=[];let g=s[s.length-1]?.id||null;for(const{targetId:h,label:f,timestamp:y}of E){const T={type:"label",id:S(new Set([...I,...w.map(M=>M.id)])),parentId:g,timestamp:y,targetId:h,label:f};w.push(T),g=T.id}this.fileEntries=[m,...s,...w],this.sessionId=d,this._buildIndex()}static create(e,t,n){const s=t?_(t):N(e);return new F(e,s,void 0,!0,n)}static open(e,t,n){const s=b(e);let r=null,o;if(n===void 0&&C(s))try{r=de(s)}catch(a){if(!(a instanceof le))throw a;o=V(s);const u=o[0];r=u?.type==="session"?u:null}const l=n??(r?W(r):void 0)??process.cwd(),d=t?_(t):we(s,"..");return new F(l,d,s,!0,void 0,o)}static continueRecent(e,t){const n=t?_(t):N(e),s=t!==void 0&&n!==D(e),r=Pe(n,s?e:void 0);return r?new F(e,n,r,!0):new F(e,n,void 0,!0)}static inMemory(e=process.cwd(),t,n){return new F(e,"",void 0,!1,t,n)}static forkFrom(e,t,n,s){const r=b(e),o=b(t),l=V(r);if(l.length===0)throw new Error(`Cannot fork: source session file is empty or invalid: ${r}`);const d=l.find(w=>w.type==="session");if(!d)throw new Error(`Cannot fork: source session has no header: ${r}`);if(ne(d))throw new Error(Ce(Fe("{path} \u7531\u66F4\u65B0\u7248\u672C\u7684 {app} \u5199\u5165\uFF0C\u5F53\u524D\u7248\u672C\u53EA\u8BFB\uFF0C\u4E0D\u4F1A\u6539\u52A8\u5B83\uFF1B\u8BF7\u5347\u7EA7 {app}\u3002"),{path:r,app:_e}));const a=n?_(n):N(o);C(a)||$(a,{recursive:!0}),s?.id!==void 0&&se(s.id);const u=s?.id??H(),p=new Date().toISOString(),m=p.replace(/[:.]/g,"-"),I=x(a,`${m}_${u}.jsonl`);G(I,`${JSON.stringify({type:"session",version:v,id:u,timestamp:p,cwd:o,parentSession:r})}
11
+ `,{flag:"wx"});for(const w of l)w.type!=="session"&&R(I,`${JSON.stringify(w)}
12
+ `);return new F(o,a,I,!0)}static findById(e,t,n){const s=n?_(n):N(e),r=n!==void 0&&s!==D(e),o=b(e);try{for(const l of Y(s)){if(!l.endsWith(".jsonl"))continue;const d=x(s,l),a=ce(d);if(a?.id===t&&!(r&&!z(W(a),o)))return d}}catch{}}static async list(e,t,n,s){const r=t?_(t):N(e),o=t!==void 0&&r!==D(e),l=b(e),d=c(p=>!o||z(p.cwd,l),"includeSession"),u=(await pe(r,n?(p,m,I)=>n(p,m,I?.filter(d)):void 0,s)).filter(d);return A(u)}static async listAll(e,t,n){const s=typeof e=="string"?_(e):void 0,r=typeof e=="function"?e:typeof t=="function"?t:void 0,o=typeof e=="string"||typeof t=="function"?n:t??n;if(o?.throwIfAborted(),s)return A(await pe(s,r,o));const l=xe();try{if(!C(l))return[];const a=(await P(l,{withFileTypes:!0})).filter(f=>f.isDirectory()||f.isSymbolicLink()).map(f=>x(l,f.name)),p=(await J(a,ue,async f=>{try{return(await P(f)).filter(y=>y.endsWith(".jsonl")).map(y=>x(f,y))}catch{return[]}},o)).flat(),m=await J(p,ue,async f=>{try{return{path:f,stats:await q(f)}}catch{return{path:f}}},o);m.sort((f,y)=>(y.stats?.mtimeMs??Number.NEGATIVE_INFINITY)-(f.stats?.mtimeMs??Number.NEGATIVE_INFINITY)||Q(y.path).localeCompare(Q(f.path)));const I=m.length;let E=0,w=!1;const g=[],h=await he(m,(f,y)=>{E++,y===0&&(w=!0),f&&g.push(f);const T=w&&(y===0||E%ze===0||E===I);r?.(E,I,T?A([...g]):void 0)},o);return A(h.filter(f=>f!==null))}catch{return o?.throwIfAborted(),[]}}}export{v as CURRENT_SESSION_VERSION,F as SessionManager,se as assertValidSessionId,oe as buildContextEntries,dt as buildSessionContext,ae as buildSessionProjection,Pe as findMostRecentSession,N as getDefaultSessionDir,lt as getLatestCompactionEntry,ne as isNewerSessionFormat,V as loadEntriesFromFile,ot as migrateSessionEntries,at as parseSessionEntries,Oe as sessionEntryToContextMessages};
@@ -1 +1 @@
1
- var r=Object.defineProperty;var i=(t,e)=>r(t,"name",{value:e,configurable:!0});function g(t){return t.drainErrors().map(({scope:e,path:s,error:n})=>({type:"warning",message:s?`Invalid settings file ${s}: ${n.message}`:`Invalid ${e} settings: ${n.message}`}))}i(g,"collectSettingsDiagnostics");function c(t){const e=new Set;return t.filter(s=>{const n=`${s.type}\0${s.message}`;return e.has(n)?!1:(e.add(n),!0)})}i(c,"deduplicateDiagnostics");export{g as collectSettingsDiagnostics,c as deduplicateDiagnostics};
1
+ var r=Object.defineProperty;var i=(t,e)=>r(t,"name",{value:e,configurable:!0});import{collectNewerDataFormatDiagnostics as a}from"./shared-data.js";function g(t){return[...t.drainErrors().map(({scope:e,path:s,error:n})=>({type:"warning",message:s?`Invalid settings file ${s}: ${n.message}`:`Invalid ${e} settings: ${n.message}`})),...a()]}i(g,"collectSettingsDiagnostics");function l(t){const e=new Set;return t.filter(s=>{const n=`${s.type}\0${s.message}`;return e.has(n)?!1:(e.add(n),!0)})}i(l,"deduplicateDiagnostics");export{g as collectSettingsDiagnostics,l as deduplicateDiagnostics};
@@ -155,6 +155,7 @@ export declare function isToolModifier(entry: unknown): boolean;
155
155
  export declare function getToolListError(entries: readonly string[]): string | undefined;
156
156
  export declare function applyToolModifiers(base: readonly string[], entries: readonly string[]): string[];
157
157
  export type SettingsScope = "global" | "project";
158
+ export declare const SETTINGS_FORMAT_VERSION = 1;
158
159
  export interface SettingsManagerCreateOptions {
159
160
  projectTrusted?: boolean;
160
161
  }
@@ -211,6 +212,8 @@ export declare class SettingsManager {
211
212
  private markModified;
212
213
  private markProjectModified;
213
214
  private assertProjectTrustedForWrite;
215
+ private reportNewerFormat;
216
+ private reportNewerFormatScopes;
214
217
  private recordError;
215
218
  private clearModifiedScope;
216
219
  private enqueueWrite;
@@ -1 +1 @@
1
- var F=Object.defineProperty;var a=(r,e)=>F(r,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as L}from"@earendil-works/pi-ai";import{randomUUID as M}from"crypto";import{existsSync as T,mkdirSync as I,readFileSync as O,writeFileSync as A}from"fs";import{dirname as D,join as u}from"path";import N from"proper-lockfile";import{CONFIG_DIR_NAME as y,getAgentDir as R}from"../config.js";import{normalizePath as v,resolvePath as m}from"../utils/paths.js";import{stripBom as P}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as W,parseHttpIdleTimeoutMs as $}from"./http-dispatcher.js";const _=8e4,U={reserveTokens:16384,keepRecentTokens:2e4,maxContextTokens:_},B=32e3,H=5,q=["off","streaming","idle"];function p(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}a(p,"isMergeableObject");function j(r,e){const t={...r};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const o=r[s];t[s]=p(o)&&p(i)?j(o,i):i}return t}a(j,"deepMergeObjects");const V=["read","bash","edit","write"];function f(r){return typeof r=="string"&&(r.startsWith("+")||r.startsWith("-"))}a(f,"isToolModifier");function le(r){const e=r.filter(f);if(e.length===0)return;if(e.length<r.length)return"tool names cannot be mixed with +name or -name entries";const t=e.find(s=>s.includes("*"));if(t)return`+name and -name entries take exact tool names, not patterns: ${t}`}a(le,"getToolListError");function X(r,e){const t=[...r];for(const s of e){if(!f(s))continue;const i=s.slice(1),o=t.indexOf(i);s.startsWith("+")&&o===-1&&i?t.push(i):s.startsWith("-")&&o!==-1&&t.splice(o,1)}return t}a(X,"applyToolModifiers");function K(r,e){return e===void 0?r:!Array.isArray(r)||!Array.isArray(e)||!e.every(f)?e:[...r,...e]}a(K,"mergeDefaultTools");function Q(r){const e=r.filter(t=>!f(t));return X(e.length>0||r.length===0?e:V,r)}a(Q,"resolveDefaultTools");function h(r,e){const t=j(r,e),s=K(r.defaultTools,e.defaultTools);return s===void 0?t:{...t,defaultTools:s}}a(h,"deepMergeSettings");function C(r,e){const t=$(r);if(t!==void 0)return t;if(r!==void 0)throw new Error(`Invalid ${e} setting: ${String(r)}`)}a(C,"parseTimeoutSetting");function S(r,e,t){return{scope:r,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}a(S,"toSettingsError");class z{static{a(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=m(e),i=m(t);this.globalSettingsPath=u(i,"settings.json"),this.projectSettingsPath=u(s,y,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let o=1;o<=10;o++)try{return N.lockSync(e,{realpath:!1})}catch(n){if((typeof n=="object"&&n!==null&&"code"in n?String(n.code):void 0)!=="ELOCKED"||o===10)throw n;i=n;const g=Date.now();for(;Date.now()-g<20;);}throw i??new Error("Failed to acquire settings lock")}withLock(e,t){const s=e==="global"?this.globalSettingsPath:this.projectSettingsPath,i=D(s);let o;try{const n=T(s);n&&(o=this.acquireLockSyncWithRetry(s));const l=n?O(s,"utf-8"):void 0,g=t(l);g!==void 0&&(T(i)||I(i,{recursive:!0}),o||(o=this.acquireLockSyncWithRetry(s)),A(s,g,"utf-8"))}finally{o&&o()}}}class G{static{a(this,"InMemorySettingsStorage")}global;project;withLock(e,t){const s=e==="global"?this.global:this.project,i=t(s);i!==void 0&&(e==="global"?this.global=i:this.project=i)}}class d{static{a(this,"SettingsManager")}storage;globalSettings;projectSettings;settings;projectTrusted;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(e,t,s,i=null,o=null,n=[],l=!0,g={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=l,this.globalSettingsLoadError=i,this.projectSettingsLoadError=o,this.errors=[...n],this.settingsPaths=g,this.settings=h(this.globalSettings,this.projectSettings)}static create(e,t=R(),s={}){const i=m(e),o=m(t),n=new z(i,o);return d.fromStorageWithPaths(n,s,{global:u(o,"settings.json"),project:u(i,y,"settings.json")})}static fromStorage(e,t={}){return d.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,o=d.tryLoadFromStorage(e,"global"),n=d.tryLoadFromStorage(e,"project",i),l=[];return o.error&&l.push(S("global",o.error,s.global)),n.error&&l.push(S("project",n.error,s.project)),new d(e,o.settings,n.settings,o.error,n.error,l,i,s)}static inMemory(e={},t={}){const s=new G,i=d.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),d.fromStorage(s,t)}static loadFromStorage(e,t,s=!0){if(t==="project"&&!s)return{};let i;if(e.withLock(t,n=>{i=n}),!i)return{};const o=JSON.parse(P(i));return d.migrateSettings(o)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:d.loadFromStorage(e,t,s),error:null}}catch(i){return{settings:{},error:i}}}static migrateSettings(e){if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),!("transport"in e)&&typeof e.websockets=="boolean"&&(e.transport=e.websockets?"websocket":"sse",delete e.websockets),"skills"in e&&typeof e.skills=="object"&&e.skills!==null&&!Array.isArray(e.skills)){const t=e.skills;t.enableSkillCommands!==void 0&&e.enableSkillCommands===void 0&&(e.enableSkillCommands=t.enableSkillCommands),Array.isArray(t.customDirectories)&&t.customDirectories.length>0?e.skills=t.customDirectories:delete e.skills}if("retry"in e&&typeof e.retry=="object"&&e.retry!==null&&!Array.isArray(e.retry)){const t=e.retry,s=typeof t.provider=="object"&&t.provider!==null?t.provider:void 0;typeof t.maxDelayMs=="number"&&(s?.maxRetryDelayMs===void 0||s?.maxRetryDelayMs===null)&&(t.provider={...s??{},maxRetryDelayMs:t.maxDelayMs}),delete t.maxDelayMs}return e}getSettings(){return structuredClone(this.settings)}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}isProjectTrusted(){return this.projectTrusted}setProjectTrusted(e){if(this.projectTrusted===e)return;if(this.projectTrusted=e,this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear(),!e){this.projectSettings={},this.projectSettingsLoadError=null,this.settings=h(this.globalSettings,this.projectSettings);return}const t=d.tryLoadFromStorage(this.storage,"project",e);this.projectSettings=t.settings,this.projectSettingsLoadError=t.error,t.error&&this.recordError("project",t.error),this.settings=h(this.globalSettings,this.projectSettings)}async reload(){await this.writeQueue;const e=d.tryLoadFromStorage(this.storage,"global");e.error?(this.globalSettingsLoadError=e.error,this.recordError("global",e.error)):(this.globalSettings=e.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();const t=d.tryLoadFromStorage(this.storage,"project",this.projectTrusted);t.error?(this.projectSettingsLoadError=t.error,this.recordError("project",t.error)):(this.projectSettings=t.settings,this.projectSettingsLoadError=null),this.settings=h(this.globalSettings,this.projectSettings)}applyOverrides(e){this.settings=h(this.settings,e)}markModified(e,t){this.modifiedFields.add(e),t&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(t))}markProjectModified(e,t){this.modifiedProjectFields.add(e),t&&(this.modifiedProjectNestedFields.has(e)||this.modifiedProjectNestedFields.set(e,new Set),this.modifiedProjectNestedFields.get(e).add(t))}assertProjectTrustedForWrite(){if(!this.projectTrusted)throw new Error("Project is not trusted; refusing to write project settings")}recordError(e,t){this.errors.push(S(e,t,this.settingsPaths[e]))}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,t){this.writeQueue=this.writeQueue.then(()=>{e==="project"&&this.assertProjectTrustedForWrite(),t(),this.clearModifiedScope(e)}).catch(s=>{this.recordError(e,s)})}cloneModifiedNestedFields(e){const t=new Map;for(const[s,i]of e.entries())t.set(s,new Set(i));return t}persistScopedSettings(e,t,s,i){this.storage.withLock(e,o=>{const n=o?d.migrateSettings(JSON.parse(P(o))):{},l={...n};for(const g of s){const c=t[g];if(i.has(g)&&typeof c=="object"&&c!==null){const E=i.get(g),w=n[g]??{},x=c,b={...w};for(const k of E)b[k]=x[k];l[g]=b}else l[g]=c}return JSON.stringify(l,null,2)})}save(){if(this.settings=h(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;const e=structuredClone(this.globalSettings),t=new Set(this.modifiedFields),s=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",e,t,s)})}saveProjectSettings(e){if(this.assertProjectTrustedForWrite(),this.projectSettings=structuredClone(e),this.settings=h(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;const t=structuredClone(this.projectSettings),s=new Set(this.modifiedProjectFields),i=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",t,s,i)})}updateProjectSettings(e,t){this.assertProjectTrustedForWrite();const s=structuredClone(this.projectSettings);t(s),this.markProjectModified(e),this.saveProjectSettings(s)}async flush(){await this.writeQueue}drainErrors(){const e=[...this.errors];return this.errors=[],e}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getSessionDir(){const e=this.settings.sessionDir;return e&&v(e)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,t){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=t,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getThemeSetting(){const e=this.settings.theme;if(typeof e=="string")return e}getTheme(){const e=this.getThemeSetting();return e?.includes("/")?void 0:e}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(e,t){return this.settings.modelThinkingLevels?.[`${e}/${t}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(e,t,s){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${e}/${t}`]=s,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(e,t){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${e}/${t}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??"auto"}setTransport(e){this.globalSettings.transport=e,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionTokenSetting(e,t){const s=this.settings.compaction,i=s?.[e];if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<0))throw new Error(`Invalid compaction.${e} setting: ${String(i)}. Expected a non-negative safe integer.`);const o=t?`${t.provider}/${t.id}`:void 0,n=o!==void 0?s?.modelOverrides?.[o]:void 0;if(n!==void 0&&!p(n))throw new Error(`Invalid compaction.modelOverrides["${o}"] setting: ${String(n)}. Expected an object.`);const l=n?.[e];if(l!==void 0&&(typeof l!="number"||!Number.isSafeInteger(l)||l<0))throw new Error(`Invalid compaction.modelOverrides["${o}"].${e} setting: ${String(l)}. Expected a non-negative safe integer.`);return l??i??U[e]}getCompactionReserveTokens(e){return this.getCompactionTokenSetting("reserveTokens",e)}getCompactionKeepRecentTokens(e){return this.getCompactionTokenSetting("keepRecentTokens",e)}getCompactionSettings(e){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(e),keepRecentTokens:this.getCompactionKeepRecentTokens(e),maxContextTokens:this.getCompactionMaxContextTokens(e),pruneToolOutputs:this.getCompactionPruneToolOutputs()}}getCompactionMaxContextTokens(e){return this.getCompactionTokenSetting("maxContextTokens",e)}getCompactionPruneToolOutputs(){const e=this.settings.compaction?.pruneToolOutputs;if(e!==void 0&&typeof e!="boolean")throw new Error(`Invalid compaction.pruneToolOutputs setting: ${String(e)}. Expected a boolean.`);return e??!0}getCompactionSummaryModel(){const e=this.settings.compaction?.summaryModel;if(e===void 0||e==="")return;const t=typeof e=="string"?e.indexOf("/"):-1;if(typeof e!="string"||t<=0||t===e.length-1)throw new Error(`Invalid compaction.summaryModel setting: ${String(e)}. Expected "provider/modelId".`);return{provider:e.slice(0,t),modelId:e.slice(t+1)}}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??H,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??L}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return B;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid maxOutputTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getOutputTokenLimit(e){const t=this.getMaxOutputTokens();return t>0&&(e<=0||e>t)?t:e}getHttpIdleTimeoutMs(){return C(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??W}setHttpIdleTimeoutMs(e){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(e),this.markModified("httpIdleTimeoutMs"),this.save()}getCacheWarmingMode(){const e=this.globalSettings.cacheWarming;return e!==void 0&&q.includes(e)?e:"streaming"}setCacheWarmingMode(e){this.globalSettings.cacheWarming=e,this.markModified("cacheWarming"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getWebSocketConnectTimeoutMs(){return C(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!0}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??!1}getExternalEditorCommand(){const e=this.settings.externalEditor;if(typeof e=="string"&&e.trim()!=="")return e;const t=process.env.VISUAL||process.env.EDITOR;return t||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(e){this.globalSettings.showCacheMissNotices=e,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){const e=this.settings.shellPath;return e&&v(e)}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){const e=this.settings.quietStartup;return e===!1?!1:e==="header"?e:!0}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getDefaultProjectTrust(){const e=this.globalSettings.defaultProjectTrust;return e==="always"||e==="never"?e:"ask"}setDefaultProjectTrust(e){this.globalSettings.defaultProjectTrust=e,this.markModified("defaultProjectTrust"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}getShellEnvironmentPolicy(){const e=this.globalSettings.shellEnvironment??{},t=[...e.exclude??[],...this.projectSettings.shellEnvironment?.exclude??[]];return{...e.inherit!==void 0?{inherit:e.inherit}:{},...t.length>0?{exclude:t}:{},...e.include!==void 0?{include:[...e.include]}:{},...e.set!==void 0?{set:{...e.set}}:{}}}getPermissionRuleSources(){return{...this.globalSettings.permissions?{user:structuredClone(this.globalSettings.permissions)}:{},...this.projectSettings.permissions?{project:structuredClone(this.projectSettings.permissions)}:{}}}getSandboxSettingsSources(){return{...this.globalSettings.sandbox?{global:structuredClone(this.globalSettings.sandbox)}:{},...this.projectSettings.sandbox?{project:structuredClone(this.projectSettings.sandbox)}:{}}}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(e){this.globalSettings.npmCommand=e?[...e]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!0}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??!0}setEnableInstallTelemetry(e){this.globalSettings.enableInstallTelemetry=e,this.markModified("enableInstallTelemetry"),this.save()}getEnableAnalytics(){return this.settings.enableAnalytics??!1}getTrackingId(){return this.settings.trackingId}setEnableAnalytics(e){this.globalSettings.enableAnalytics=e,this.markModified("enableAnalytics"),e&&!this.globalSettings.trackingId&&(this.globalSettings.trackingId=M(),this.markModified("trackingId")),this.save()}getOrCreateDeviceId(){return this.globalSettings.deviceId||(this.globalSettings.deviceId=M(),this.markModified("deviceId"),this.save()),this.globalSettings.deviceId}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){this.updateProjectSettings("packages",t=>{t.packages=e})}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){this.updateProjectSettings("extensions",t=>{t.extensions=e})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){this.updateProjectSettings("skills",t=>{t.skills=e})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){this.updateProjectSettings("prompts",t=>{t.prompts=e})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){this.updateProjectSettings("themes",t=>{t.themes=e})}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getFactoryEnabled(){return this.settings.factoryEnabled??!0}setFactoryEnabled(e){this.globalSettings.factoryEnabled=e,this.markModified("factoryEnabled"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){const e=this.settings.terminal,t=e?.images;return{...t==="kitty"||t==="iterm2"?{images:t}:t===!1?{images:null}:{},...typeof e?.trueColor=="boolean"?{trueColor:e.trueColor}:{},...typeof e?.hyperlinks=="boolean"?{hyperlinks:e.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){const e=this.settings.terminal?.imageWidthCells;return typeof e!="number"||!Number.isFinite(e)?60:Math.max(1,Math.floor(e))}setImageWidthCells(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(e)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:process.env.PI_CLEAR_ON_SHRINK==="1"}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=e,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":(this.settings.tuiMode==="regular"||this.settings.tuiMode,"regular")}setTuiMode(e){this.globalSettings.tuiMode=e,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":"transcript"}setFullscreenExitOutput(e){this.globalSettings.fullscreenExitOutput=e,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){const e=this.settings.fullscreenScrollbar;return e==="always"||e==="hidden"?e:"auto"}setFullscreenScrollbar(e){this.globalSettings.fullscreenScrollbar=e,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??!0}setFullscreenCopyOnSelect(e){this.globalSettings.fullscreenCopyOnSelect=e,this.markModified("fullscreenCopyOnSelect"),this.save()}getFullscreenWheelScrollLines(){const e=this.settings.fullscreenWheelScrollLines;return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.min(100,Math.floor(e))):"auto"}setFullscreenWheelScrollLines(e){this.globalSettings.fullscreenWheelScrollLines=e==="auto"?e:Math.max(1,Math.min(100,Math.floor(e))),this.markModified("fullscreenWheelScrollLines"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){const e=this.settings.defaultTools;if(e!==void 0)return Q(Array.isArray(e)?e.filter(t=>typeof t=="string"):[])}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){const e=this.settings.treeFilterMode;return e&&["default","no-tools","user-only","labeled-only","all"].includes(e)?e:"default"}setTreeFilterMode(e){this.globalSettings.treeFilterMode=e,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??process.env.PI_HARDWARE_CURSOR==="1"}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??1}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===1?1:0}setOutputPad(e){this.globalSettings.outputPad=e,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getMermaidRenderingMode(){const e=this.settings.markdown?.mermaid;return e==="off"||e==="final"?e:"streaming"}setMermaidRenderingMode(e){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=e,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(e){this.globalSettings.warnings={...e},this.markModified("warnings"),this.save()}}export{q as CACHE_WARMING_MODES,_ as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,B as DEFAULT_MAX_OUTPUT_TOKENS,H as DEFAULT_MAX_RETRIES,V as DEFAULT_TOOL_NAMES,z as FileSettingsStorage,G as InMemorySettingsStorage,d as SettingsManager,X as applyToolModifiers,le as getToolListError,f as isToolModifier};
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};
@@ -0,0 +1 @@
1
+ var e=Object.defineProperty;var t=(r,a)=>e(r,"name",{value:a,configurable:!0});import{drainNewerDataFormatFiles as o}from"@dalcode/dal-pi-kit";import{APP_TITLE as i}from"../config.js";import{fill as m,t as p}from"../dal/i18n.js";import{DATA_FORMAT_KEY as s,declaredDataFormat as A,isNewerDataFormatFile as N,reportNewerDataFormat as T,withFileLockSync as d,writeFileAtomicSync as g}from"@dalcode/dal-pi-kit";function w(){return o().map(r=>({type:"warning",message:m(p("{path} \u7531\u66F4\u65B0\u7248\u672C\u7684 {app} \u5199\u5165\uFF0C\u5F53\u524D\u7248\u672C\u53EA\u8BFB\uFF0C\u4E0D\u4F1A\u6539\u52A8\u5B83\uFF1B\u8BF7\u5347\u7EA7 {app}\u3002"),{path:r,app:i})}))}t(w,"collectNewerDataFormatDiagnostics");export{s as DATA_FORMAT_KEY,w as collectNewerDataFormatDiagnostics,A as declaredDataFormat,N as isNewerDataFormatFile,T as reportNewerDataFormat,d as withFileLockSync,g as writeFileAtomicSync};
@@ -1,26 +1,26 @@
1
- var P=Object.defineProperty;var c=(e,t)=>P(e,"name",{value:t,configurable:!0});import{join as v}from"node:path";import{getSystemMessageText as E}from"@earendil-works/pi-ai";import{APP_NAME as $,APP_TITLE as u,getDalDocsPath as T,getDocsPath as j,getExamplesPath as O,getReadmePath as _,IS_WHITE_LABEL_BUILD as I}from"../config.js";import{describeGitState as N}from"./git-state.js";import{INJECTED_CONTEXT_TAG as A}from"./messages.js";import{formatSkillsForPrompt as D}from"./skills.js";const M=/^[a-z][a-z0-9_-]*$/;function R(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],hiddenTools:[...e.hiddenTools??[]],toolSnippets:{...e.toolSnippets??{}},toolGuidelines:Object.fromEntries(Object.entries(e.toolGuidelines??{}).map(([t,n])=>[t,[...n]])),promptGuidelines:[...e.promptGuidelines??[]],appendSystemPrompt:e.appendSystemPrompt??"",sections:{...e.sections??{}},cwd:e.cwd,gitState:e.gitState,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}c(R,"normalizeBuildSystemPromptOptions");function G(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:n})=>`<project_instructions path="${t}">
1
+ var P=Object.defineProperty;var c=(e,t)=>P(e,"name",{value:t,configurable:!0});import{join as v}from"node:path";import{getSystemMessageText as E}from"@earendil-works/pi-ai";import{APP_NAME as $,APP_TITLE as f,getDalDocsPath as j,getDocsPath as T,getExamplesPath as O,getReadmePath as _,IS_WHITE_LABEL_BUILD as I}from"../config.js";import{describeGitState as N}from"./git-state.js";import{INJECTED_CONTEXT_TAG as A}from"./messages.js";import{formatSkillsForPrompt as D}from"./skills.js";const M=/^[a-z][a-z0-9_-]*$/;function R(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],hiddenTools:[...e.hiddenTools??[]],toolSnippets:{...e.toolSnippets??{}},toolGuidelines:Object.fromEntries(Object.entries(e.toolGuidelines??{}).map(([t,n])=>[t,[...n]])),promptGuidelines:[...e.promptGuidelines??[]],appendSystemPrompt:e.appendSystemPrompt??"",sections:{...e.sections??{}},cwd:e.cwd,gitState:e.gitState,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}c(R,"normalizeBuildSystemPromptOptions");function G(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:n})=>`<project_instructions path="${t}">
2
2
  ${n}
3
3
  </project_instructions>`)].join(`
4
4
 
5
- `)}c(G,"renderProjectContext");function L(e,t,n){const i=[],d=new Set,o=c(l=>{const m=l.trim();!m||d.has(m)||(d.add(m),i.push(m))},"addRule"),p=e.includes("bash"),f=e.includes("powershell"),a=e.includes("grep"),g=e.includes("find"),y=e.includes("ls");(p||f)&&!a&&!g&&!y&&o(p&&f?"Use bash or PowerShell for file operations like listing, searching, and finding files":f?"Use PowerShell for file operations like listing, searching, and finding files":"Use bash for file operations like ls, rg, find");for(const l of e)for(const m of t[l]??[])o(m);for(const l of n)o(l);return e.length>0&&(o("When several tool calls do not depend on each other's results (reading multiple files, independent searches or commands), make them all in one response; they run in parallel. Each extra round trip costs the user seconds"),o("Answer as soon as you can: once you know enough, give the answer or your best current conclusion, then offer to dig further. Do not investigate everything before saying anything"),o("During longer work, tell the user every few tool rounds, in a sentence or two, what you found and what you will check next"),o("If you cannot tell which product, project or file the user means, ask instead of searching widely on a guess. When the user writes while you are working, respond to that message first: it may change the direction"),o("In a small project, read every source file the task touches in one response (parallel reads, or one command that prints them) instead of exploring one file per round"),o("Verify the behaviours the request names and the edge cases it implies; do not write exhaustive or randomized test sweeps unless asked"),o("Before reporting done, run every code path you added at least once, including backward-compatibility, fallback and error branches: a branch that never ran is not verified")),o(`Text inside <${A} type="..."> tags comes from ${u} itself, not from the user: follow its instructions, but do not mistake it for the user's request or reply to it as if the user had written it`),o("Be concise in your responses"),o("Show file paths clearly when working with files"),i.map(l=>`- ${l}`).join(`
6
- `)}c(L,"buildRules");function F(e){const t=R(e),{customPrompt:n,selectedTools:i,hiddenTools:d,toolSnippets:o,toolGuidelines:p,promptGuidelines:f,appendSystemPrompt:a,sections:g,cwd:y,contextFiles:l,skills:m}=t;for(const s of Object.keys(g))if(!M.test(s)||s==="preamble")throw new Error(`Invalid system prompt section name: ${s}`);const S=i.filter(s=>!d.includes(s)),r={};if(n)r.preamble=n;else{r.preamble=`You are an expert coding assistant operating inside ${u} (${$}). You help users by reading files, executing commands, editing code, and writing new files.`;const s=S.filter(b=>!!o[b]),h=s.length>0?s.map(b=>`- ${b}: ${o[b]}`).join(`
7
- `):"(none)";r.tools=`${h}
5
+ `)}c(G,"renderProjectContext");function L(e,t,n){const i=[],d=new Set,o=c(l=>{const m=l.trim();!m||d.has(m)||(d.add(m),i.push(m))},"addRule"),p=e.includes("bash"),h=e.includes("powershell"),a=e.includes("grep"),g=e.includes("find"),y=e.includes("ls");(p||h)&&!a&&!g&&!y&&o(p&&h?"Use bash or PowerShell for file operations like listing, searching, and finding files":h?"Use PowerShell for file operations like listing, searching, and finding files":"Use bash for file operations like ls, rg, find");for(const l of e)for(const m of t[l]??[])o(m);for(const l of n)o(l);return e.length>0&&(o("When several tool calls do not depend on each other's results (reading multiple files, independent searches or commands), make them all in one response; they run in parallel. Each extra round trip costs the user seconds"),o("Answer as soon as you can: once you know enough, give the answer or your best current conclusion, then offer to dig further. Do not investigate everything before saying anything"),o("During longer work, tell the user every few tool rounds, in a sentence or two, what you found and what you will check next"),o("If you cannot tell which product, project or file the user means, ask instead of searching widely on a guess. When the user writes while you are working, respond to that message first: it may change the direction"),o("In a small project, read every source file the task touches in one response (parallel reads, or one command that prints them) instead of exploring one file per round"),o("Verify the behaviours the request names and the edge cases it implies; do not write exhaustive or randomized test sweeps unless asked"),o("Before reporting done, run every code path you added at least once, including backward-compatibility, fallback and error branches: a branch that never ran is not verified"),o("If the request's premise does not match what the code, data or tests show (the reported bug is absent, the named text is already correct), say so with the evidence and do not change anything just to satisfy the request; ask how to proceed or stop")),o(`Text inside <${A} type="..."> tags comes from ${f} itself, not from the user: follow its instructions, but do not mistake it for the user's request or reply to it as if the user had written it`),o("Be concise in your responses"),o("Show file paths clearly when working with files"),i.map(l=>`- ${l}`).join(`
6
+ `)}c(L,"buildRules");function F(e){const t=R(e),{customPrompt:n,selectedTools:i,hiddenTools:d,toolSnippets:o,toolGuidelines:p,promptGuidelines:h,appendSystemPrompt:a,sections:g,cwd:y,contextFiles:l,skills:m}=t;for(const s of Object.keys(g))if(!M.test(s)||s==="preamble")throw new Error(`Invalid system prompt section name: ${s}`);const w=i.filter(s=>!d.includes(s)),r={};if(n)r.preamble=n;else{r.preamble=`You are an expert coding assistant operating inside ${f} (${$}). You help users by reading files, executing commands, editing code, and writing new files.`;const s=w.filter(b=>!!o[b]),u=s.length>0?s.map(b=>`- ${b}: ${o[b]}`).join(`
7
+ `):"(none)";r.tools=`${u}
8
8
 
9
- In addition to the tools above, you may have access to other custom tools depending on the project.`,r.rules=L(S,p,f),r.docs=W()}a&&(r.addendum=a),l.length>0&&(r.project_context=G(l));const k=["read","bash"],w=k.find(s=>S.includes(s))??(k.some(s=>i.includes(s))?"indirect":void 0);if(w&&m.length>0){const s=D(m,w).trim();s&&(r.skills=s)}r.cwd=y.replace(/\\/g,"/"),t.gitState&&!g.git_state&&(r.git=N(y));for(const[s,h]of Object.entries(g))h&&(r[s]=h);const x={preamble:r.preamble};for(const[s,h]of Object.entries(r))s!=="preamble"&&(x[s]=`<${s}>
10
- ${h}
11
- </${s}>`);return x}c(F,"buildSystemPromptSections");const U="cwd",B="Environment of this session, part of the system prompt. Later updates to these sections arrive as system prompt updates.";function X(e){const t=e[0];if(!t||t.role!=="system"||!t.sections)return e;const n=Object.keys(t.sections),i=n.indexOf(U);if(i===-1)return e;const d=n.slice(i).map(a=>t.sections?.[a]).filter(a=>typeof a=="string"&&a.length>0),o=Object.fromEntries(n.slice(0,i).map(a=>[a,t.sections?.[a]??null])),p={...t,sections:o};if(d.length===0)return[p,...e.slice(1)];const f={role:"user",content:[{type:"text",text:`<session_environment>
9
+ In addition to the tools above, you may have access to other custom tools depending on the project.`,r.rules=L(w,p,h),r.docs=W()}a&&(r.addendum=a),l.length>0&&(r.project_context=G(l));const S=["read","bash"],k=S.find(s=>w.includes(s))??(S.some(s=>i.includes(s))?"indirect":void 0);if(k&&m.length>0){const s=D(m,k).trim();s&&(r.skills=s)}r.cwd=y.replace(/\\/g,"/"),t.gitState&&!g.git_state&&(r.git=N(y));for(const[s,u]of Object.entries(g))u&&(r[s]=u);const x={preamble:r.preamble};for(const[s,u]of Object.entries(r))s!=="preamble"&&(x[s]=`<${s}>
10
+ ${u}
11
+ </${s}>`);return x}c(F,"buildSystemPromptSections");const U="cwd",B="Environment of this session, part of the system prompt. Later updates to these sections arrive as system prompt updates.";function X(e){const t=e[0];if(!t||t.role!=="system"||!t.sections)return e;const n=Object.keys(t.sections),i=n.indexOf(U);if(i===-1)return e;const d=n.slice(i).map(a=>t.sections?.[a]).filter(a=>typeof a=="string"&&a.length>0),o=Object.fromEntries(n.slice(0,i).map(a=>[a,t.sections?.[a]??null])),p={...t,sections:o};if(d.length===0)return[p,...e.slice(1)];const h={role:"user",content:[{type:"text",text:`<session_environment>
12
12
  ${B}
13
13
 
14
14
  ${d.join(`
15
15
 
16
16
  `)}
17
- </session_environment>`}],timestamp:t.timestamp};return[p,f,...e.slice(1)]}c(X,"moveSessionEnvironmentOutOfSystemPrompt");function C(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:F(e)}}c(C,"buildSystemPromptState");function Q(e){return E({role:"system",...C(e),timestamp:0})}c(Q,"buildSystemPrompt");function Z(e,t){const n={};for(const[i,d]of Object.entries(t))e[i]!==d&&(n[i]=d);for(const i of Object.keys(e))t[i]===void 0&&(n[i]=null);return Object.keys(n).length>0?n:void 0}c(Z,"diffSystemPromptSections");function W(){if(I){const e=T();return`${u} documentation (read only when the user asks about ${u} itself: its commands, settings, skills, prompt templates, extensions, packages, themes or keybindings):
17
+ </session_environment>`}],timestamp:t.timestamp};return[p,h,...e.slice(1)]}c(X,"moveSessionEnvironmentOutOfSystemPrompt");function C(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:F(e)}}c(C,"buildSystemPromptState");function Q(e){return E({role:"system",...C(e),timestamp:0})}c(Q,"buildSystemPrompt");function Z(e,t){const n={};for(const[i,d]of Object.entries(t))e[i]!==d&&(n[i]=d);for(const i of Object.keys(e))t[i]===void 0&&(n[i]=null);return Object.keys(n).length>0?n:void 0}c(Z,"diffSystemPromptSections");function W(){if(I){const e=j();return`${f} documentation (read only when the user asks about ${f} itself: its commands, settings, skills, prompt templates, extensions, packages, themes or keybindings):
18
18
  - Start with: ${v(e,"README.md")}
19
19
  - Topics, in the same folder: skills.md, prompt-templates.md, extensions.md, packages.md, themes.md, keybindings.md, settings.md
20
20
  - Resolve those file names under ${e}, not the current working directory
21
- - Read the relevant file completely before answering or implementing, and describe the product as ${u}`}return`${u} documentation (read only when the user asks about ${u} itself, its SDK, extensions, themes, skills, or TUI):
21
+ - Read the relevant file completely before answering or implementing, and describe the product as ${f}`}return`${f} documentation (read only when the user asks about ${f} itself, its SDK, extensions, themes, skills, or TUI):
22
22
  - Main documentation: ${_()}
23
- - Additional docs: ${j()}
23
+ - Additional docs: ${T()}
24
24
  - Examples: ${O()} (extensions, custom tools, SDK)
25
25
  - When reading these docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory
26
26
  - When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), packages (docs/packages.md), environment variables (docs/environment-variables.md), MCP servers (docs/mcp.md), codemode scripts and non-LLM models such as classifiers and image models (docs/codemode.md)
@@ -1,2 +1,2 @@
1
- var D=Object.defineProperty;var i=(o,t)=>D(o,"name",{value:t,configurable:!0});import{existsSync as h,mkdirSync as m,readFileSync as T,writeFileSync as w}from"node:fs";import{homedir as O}from"node:os";import{dirname as c,join as l}from"node:path";import k from"proper-lockfile";import{CONFIG_DIR_NAME as j,SHARED_SKILL_CONFIG_DIRS as y}from"../config.js";import{projectFileDeclaresHooks as R,TRUST_REQUIRING_PROJECT_HOOK_FILES as g}from"../dal/hooks/config.js";import{canonicalizePath as p,resolvePath as a}from"../utils/paths.js";import{stripBom as _}from"../utils/text.js";const v=["settings.json","mcp.json","extensions","mcp.json","lsp.json","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"];function f(o){return p(a(o))}i(f,"normalizeCwd");function I(o,t){let r=f(t);for(;;){const e=o[r];if(e===!0||e===!1)return{path:r,decision:e};const s=c(r);if(s===r)return null;r=s}}i(I,"findNearestTrustEntry");function F(o){const t=f(o),r=c(t);return r===t?void 0:r}i(F,"getProjectTrustParentPath");function H(o,t){const r=f(o),e=[{label:"Trust",trusted:!0,updates:[{path:r,decision:!0}],savedPath:r}],s=F(o);return s!==void 0&&e.push({label:`Trust parent folder (${s})`,trusted:!0,updates:[{path:s,decision:!0},{path:r,decision:null}],savedPath:s}),t?.includeSessionOnly&&e.push({label:"Trust (this session only)",trusted:!0,updates:[]}),e.push({label:"Do not trust",trusted:!1,updates:[{path:r,decision:!1}],savedPath:r}),t?.includeSessionOnly&&e.push({label:"Do not trust (this session only)",trusted:!1,updates:[]}),e}i(H,"getProjectTrustOptions");function S(o){if(!h(o))return{};let t;try{t=JSON.parse(_(T(o,"utf-8")))}catch(e){const s=e instanceof Error?e.message:String(e);throw new Error(`Failed to read trust store ${o}: ${s}`)}if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`Invalid trust store ${o}: expected an object`);const r={};for(const[e,s]of Object.entries(t)){if(s!==!0&&s!==!1&&s!==null)throw new Error(`Invalid trust store ${o}: value for ${JSON.stringify(e)} must be true, false, or null`);r[e]=s}return r}i(S,"readTrustFile");function b(o,t){const r={};for(const e of Object.keys(t).sort()){const s=t[e];(s===!0||s===!1||s===null)&&(r[e]=s)}m(c(o),{recursive:!0}),w(o,`${JSON.stringify(r,null,2)}
2
- `,"utf-8")}i(b,"writeTrustFile");function N(o){const t=c(o);m(t,{recursive:!0});const r=10,e=20;let s;for(let n=1;n<=r;n++)try{return k.lockSync(t,{realpath:!1,lockfilePath:`${o}.lock`})}catch(u){if((typeof u=="object"&&u!==null&&"code"in u?String(u.code):void 0)!=="ELOCKED"||n===r)throw u;s=u;const E=Date.now();for(;Date.now()-E<e;);}throw s instanceof Error?s:new Error("Failed to acquire trust store lock")}i(N,"acquireTrustLockSync");function P(o,t){const r=N(o);try{return t()}finally{r()}}i(P,"withTrustFileLock");function q(o){const t=p(a(process.env.HOME||O())),r=new Set(y.map(n=>l(t,n,"skills")));let e=p(a(o));const s=l(e,j);if(v.some(n=>h(l(s,n)))||g.some(n=>R(l(e,n))))return!0;for(;;){for(const u of y){const d=l(e,u,"skills");if(!r.has(d)&&h(d))return!0}const n=c(e);if(n===e)return!1;e=n}}i(q,"hasTrustRequiringProjectResources");class K{static{i(this,"ProjectTrustStore")}trustPath;constructor(t){this.trustPath=l(a(t),"trust.json")}get(t){return this.getEntry(t)?.decision??null}getEntry(t){return P(this.trustPath,()=>{const r=S(this.trustPath);return I(r,t)})}set(t,r){this.setMany([{path:t,decision:r}])}setMany(t){P(this.trustPath,()=>{const r=S(this.trustPath);for(const{path:e,decision:s}of t){const n=f(e);s===null?delete r[n]:r[n]=s}b(this.trustPath,r)})}}export{K as ProjectTrustStore,H as getProjectTrustOptions,F as getProjectTrustParentPath,q as hasTrustRequiringProjectResources};
1
+ var D=Object.defineProperty;var i=(o,t)=>D(o,"name",{value:t,configurable:!0});import{existsSync as h,mkdirSync as m,readFileSync as T}from"node:fs";import{homedir as w}from"node:os";import{dirname as l,join as c}from"node:path";import O from"proper-lockfile";import{CONFIG_DIR_NAME as k,SHARED_SKILL_CONFIG_DIRS as y}from"../config.js";import{projectFileDeclaresHooks as j,TRUST_REQUIRING_PROJECT_HOOK_FILES as R}from"../dal/hooks/config.js";import{canonicalizePath as p,resolvePath as a}from"../utils/paths.js";import{stripBom as g}from"../utils/text.js";import{writeFileAtomicSync as _}from"./shared-data.js";const v=["settings.json","mcp.json","extensions","mcp.json","lsp.json","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"];function f(o){return p(a(o))}i(f,"normalizeCwd");function I(o,t){let r=f(t);for(;;){const e=o[r];if(e===!0||e===!1)return{path:r,decision:e};const s=l(r);if(s===r)return null;r=s}}i(I,"findNearestTrustEntry");function F(o){const t=f(o),r=l(t);return r===t?void 0:r}i(F,"getProjectTrustParentPath");function q(o,t){const r=f(o),e=[{label:"Trust",trusted:!0,updates:[{path:r,decision:!0}],savedPath:r}],s=F(o);return s!==void 0&&e.push({label:`Trust parent folder (${s})`,trusted:!0,updates:[{path:s,decision:!0},{path:r,decision:null}],savedPath:s}),t?.includeSessionOnly&&e.push({label:"Trust (this session only)",trusted:!0,updates:[]}),e.push({label:"Do not trust",trusted:!1,updates:[{path:r,decision:!1}],savedPath:r}),t?.includeSessionOnly&&e.push({label:"Do not trust (this session only)",trusted:!1,updates:[]}),e}i(q,"getProjectTrustOptions");function S(o){if(!h(o))return{};let t;try{t=JSON.parse(g(T(o,"utf-8")))}catch(e){const s=e instanceof Error?e.message:String(e);throw new Error(`Failed to read trust store ${o}: ${s}`)}if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`Invalid trust store ${o}: expected an object`);const r={};for(const[e,s]of Object.entries(t)){if(s!==!0&&s!==!1&&s!==null)throw new Error(`Invalid trust store ${o}: value for ${JSON.stringify(e)} must be true, false, or null`);r[e]=s}return r}i(S,"readTrustFile");function b(o,t){const r={};for(const e of Object.keys(t).sort()){const s=t[e];(s===!0||s===!1||s===null)&&(r[e]=s)}m(l(o),{recursive:!0}),_(o,`${JSON.stringify(r,null,2)}
2
+ `)}i(b,"writeTrustFile");function N(o){const t=l(o);m(t,{recursive:!0});const r=100,e=20;let s;for(let n=1;n<=r;n++)try{return O.lockSync(t,{realpath:!1,lockfilePath:`${o}.lock`})}catch(u){if((typeof u=="object"&&u!==null&&"code"in u?String(u.code):void 0)!=="ELOCKED"||n===r)throw u;s=u;const E=Date.now();for(;Date.now()-E<e;);}throw s instanceof Error?s:new Error("Failed to acquire trust store lock")}i(N,"acquireTrustLockSync");function P(o,t){const r=N(o);try{return t()}finally{r()}}i(P,"withTrustFileLock");function K(o){const t=p(a(process.env.HOME||w())),r=new Set(y.map(n=>c(t,n,"skills")));let e=p(a(o));const s=c(e,k);if(v.some(n=>h(c(s,n)))||R.some(n=>j(c(e,n))))return!0;for(;;){for(const u of y){const d=c(e,u,"skills");if(!r.has(d)&&h(d))return!0}const n=l(e);if(n===e)return!1;e=n}}i(K,"hasTrustRequiringProjectResources");class z{static{i(this,"ProjectTrustStore")}trustPath;constructor(t){this.trustPath=c(a(t),"trust.json")}get(t){return this.getEntry(t)?.decision??null}getEntry(t){return P(this.trustPath,()=>{const r=S(this.trustPath);return I(r,t)})}set(t,r){this.setMany([{path:t,decision:r}])}setMany(t){P(this.trustPath,()=>{const r=S(this.trustPath);for(const{path:e,decision:s}of t){const n=f(e);s===null?delete r[n]:r[n]=s}b(this.trustPath,r)})}}export{z as ProjectTrustStore,q as getProjectTrustOptions,F as getProjectTrustParentPath,K as hasTrustRequiringProjectResources};
@@ -0,0 +1 @@
1
+ var h=Object.defineProperty;var f=(e,n)=>h(e,"name",{value:n,configurable:!0});import{t as m}from"../i18n.js";import{packageNameOf as $,readReviewedCatalogue as y}from"./endorsed.js";import{heldBackByCatalogue as k,planEndorsedUpdates as v,revocationsToApply as w,updatesToApply as b}from"./endorsed-plan.js";import{packageNameOf as N}from"./endorsed.js";function c(e){return e.to?`${e.name}@${e.to}`:e.name}f(c,"label");async function E(e,n){const a=e.integrity;if(!a)return{ok:!0};const i=(e.install??`npm:${e.name}@${e.to??""}`).replace(/^npm:/,"");if(n.registryIntegrity){let o;try{o=await n.registryIntegrity(`npm:${i}`)}catch{o=void 0}if(!o)return{ok:!1,detail:`the registry would not confirm an integrity for ${i}`};if(o!==a)return{ok:!1,detail:`the registry serves ${o} for ${i}, not the reviewed ${a}`}}return{ok:!0}}f(E,"integrityHolds");function S(e,n){const a=e.integrity;if(!a||!n.recordedIntegrity)return{ok:!0};const r=n.recordedIntegrity(e.name,e.scope);return r===void 0?{ok:!0}:r===a?{ok:!0}:{ok:!1,detail:r?`what was installed for ${e.name} hashes to ${r}, not the reviewed ${a}`:`the install root recorded no integrity for ${e.name}`}}f(S,"recordedIntegrityHolds");async function A(e){let n;try{n=y({...e.env?{env:e.env}:{},...e.catalogueFile?{file:e.catalogueFile}:{}})}catch(t){const l=t instanceof Error?t.message:String(t);return{plan:{unavailable:l,decisions:[]},updated:[],revoked:[],refused:[],failed:[],heldBack:[],problem:l}}const a=e.installed(),r=v(n,a);if(r.unavailable)return a.some(t=>t.source.startsWith("npm:"))&&e.warn(m("\u6CA1\u6709\u53EF\u7528\u7684\u5DF2\u5BA1\u6838\u76EE\u5F55\uFF0C\u5DF2\u5B89\u88C5\u7684\u6269\u5C55\u4FDD\u6301\u539F\u6837\u3002")),{plan:r,updated:[],revoked:[],refused:[],failed:[],heldBack:[],problem:r.unavailable};const i=[],o=[],d=[],u=[],g=k(r).map(t=>t.kind==="leave-unpinned"?t.name:c(t));for(const t of w(r))try{await e.remove(t.name,t.scope),o.push(t.name)}catch(l){u.push(`${t.name}: ${l instanceof Error?l.message:String(l)}`)}for(const t of b(r)){if(!t.install)continue;const l=await E(t,e);if(!l.ok){d.push(`${c(t)}: ${l.detail}`);continue}try{await e.install(t.install,t.scope)}catch(s){u.push(`${c(t)}: ${s instanceof Error?s.message:String(s)}`);continue}const p=S(t,e);if(!p.ok){if(!t.from){u.push(`${c(t)}: ${p.detail}; no previous version to restore`);continue}try{await e.install(`npm:${t.name}@${t.from}`,t.scope)}catch(s){u.push(`${c(t)}: ${p.detail}; restoring ${t.from} failed: ${s instanceof Error?s.message:String(s)}`);continue}d.push(`${c(t)}: ${p.detail}`);continue}i.push(c(t))}i.length>0&&e.log(m("\u5DF2\u968F DAL \u66F4\u65B0 {count} \u4E2A\u5DF2\u5BA1\u6838\u6269\u5C55\uFF1A{list}").replace("{count}",String(i.length)).replace("{list}",i.join("\u3001"))),o.length>0&&e.warn(m("\u5DF2\u505C\u7528\u88AB\u64A4\u56DE\u7684\u5DF2\u5BA1\u6838\u6269\u5C55\uFF1A{list}").replace("{list}",o.join("\u3001")));for(const t of d)e.warn(m("\u5B8C\u6574\u6027\u6821\u9A8C\u672A\u901A\u8FC7\uFF0C\u5DF2\u4FDD\u6301\u539F\u7248\u672C\uFF1A{item}").replace("{item}",t));for(const t of u)e.warn(m("\u672A\u80FD\u66F4\u65B0\u6269\u5C55\uFF1A{item}").replace("{item}",t));return g.length>0&&e.warn(m("\u5DF2\u5BA1\u6838\u76EE\u5F55\u672A\u56FA\u5B9A\u7248\u672C\u7684\u6269\u5C55\u4FDD\u6301\u539F\u6837\uFF1A{list}").replace("{list}",g.join("\u3001"))),{plan:r,updated:i,revoked:o,refused:d,failed:u,heldBack:g}}f(A,"syncEndorsedExtensions");function C(e,n){const a=new Set(e.decisions.filter(r=>r.kind!=="leave-third-party").map(r=>r.name));return n.filter(r=>r.source.startsWith("npm:")&&!a.has($(r.source))).map(r=>r.source)}f(C,"thirdPartySources");export{N as packageNameOf,A as syncEndorsedExtensions,C as thirdPartySources};
@@ -0,0 +1 @@
1
+ var d=Object.defineProperty;var t=(n,r)=>d(n,"name",{value:r,configurable:!0});import{packageNameOf as a,versionOfSpec as u}from"./endorsed.js";import{compareVersions as v}from"./version.js";function f(n,r,p){return n.revoked.some(o=>o.id===r&&(o.version==="*"||o.version===p))}t(f,"isRevoked");function k(n,r){if(n.problem)return{unavailable:n.problem,decisions:[]};const p=new Map;for(const e of n.packages)p.set(a(e.source).toLowerCase(),e);const o=[];for(const e of r){const s=a(e.source);if(!e.source.startsWith("npm:")||e.source.includes("#")){o.push({kind:"leave-third-party",name:s,reason:"not an npm package",scope:e.scope});continue}const i=p.get(s.toLowerCase());if(!i){if(n.unpinned.includes(s.toLowerCase())){o.push({kind:"leave-unpinned",name:s,from:e.version,reason:"the reviewed catalogue lists it without a pinned version",scope:e.scope});continue}o.push({kind:"leave-third-party",name:s,from:e.version,reason:"not in the reviewed catalogue",scope:e.scope});continue}if(f(n,i.id,e.version)){o.push({kind:"revoke",name:s,from:e.version,reason:"the reviewed version installed here has been withdrawn",scope:e.scope});continue}const c=v(i.version,e.version);if(e.version&&c!==void 0&&c<0){if(i.security===!0){o.push({kind:"update",name:s,from:e.version,to:i.version,reason:"the reviewed pin is a security rollback",install:`npm:${i.source}`,integrity:i.integrity,scope:e.scope});continue}o.push({kind:"leave-newer",name:s,from:e.version,to:i.version,reason:"newer than the reviewed pin",scope:e.scope});continue}if(e.version&&c===0&&u(e.source)===i.version){o.push({kind:"leave-current",name:s,from:e.version,reason:"already on the reviewed version",scope:e.scope});continue}o.push({kind:"update",name:s,from:e.version,to:i.version,reason:"the reviewed catalogue pins a newer version",install:`npm:${i.source}`,integrity:i.integrity,scope:e.scope})}return{decisions:o}}t(k,"planEndorsedUpdates");function w(n){return n.decisions.filter(r=>r.kind==="update")}t(w,"updatesToApply");function y(n){return n.decisions.filter(r=>r.kind==="revoke")}t(y,"revocationsToApply");function g(n){return n.decisions.filter(r=>r.kind==="leave-unpinned"||r.kind==="leave-newer")}t(g,"heldBackByCatalogue");export{g as heldBackByCatalogue,k as planEndorsedUpdates,y as revocationsToApply,w as updatesToApply};
@@ -0,0 +1 @@
1
+ var b=Object.defineProperty;var a=(e,n)=>b(e,"name",{value:n,configurable:!0});import{createPublicKey as h,verify as E}from"node:crypto";import{readFileSync as A}from"node:fs";import{homedir as x}from"node:os";import{join as k}from"node:path";const _="dal-market-signed/v1",O=Buffer.from("302a300506032b6570032100","hex");function S(e=x()){return k(e,".dal","market","index.json")}a(S,"marketCachePath");function m(e){if(e===null||typeof e=="boolean"||typeof e=="string")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new Error("signed payloads may only contain safe integers");return String(e)}if(Array.isArray(e))return`[${e.map(m).join(",")}]`;if(typeof e=="object"){const n=e;return`{${Object.keys(n).filter(r=>n[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${m(n[r])}`).join(",")}}`}throw new Error(`unsupported value in signed payload: ${typeof e}`)}a(m,"canonicalJson");function w(e){const n=Buffer.from(e,"base64");if(n.length!==32)throw new Error("an Ed25519 public key is 32 bytes");return h({key:Buffer.concat([O,n]),format:"der",type:"spki"})}a(w,"ed25519PublicKeyFromBase64");function I(e=process.env){const n=new Map;for(const o of(e.DALCODE_MARKET_PUBLIC_KEYS??"").split(",")){const r=o.trim();if(!r)continue;const c=r.indexOf(":");if(c<=0)throw new Error("DALCODE_MARKET_PUBLIC_KEYS entries are keyId:base64");n.set(r.slice(0,c),w(r.slice(c+1)))}return n}a(I,"readMarketKeys");const l={packages:[],unpinned:[],revoked:[]};function D(e){const n=e.replace(/^npm:/,""),o=n.lastIndexOf("@");return o>0?n.slice(o+1):void 0}a(D,"versionOfSpec");function C(e){const n=e.replace(/^npm:/,""),o=n.lastIndexOf("@");return o>0?n.slice(0,o):n}a(C,"packageNameOf");function N(e){return typeof e=="string"&&/^sha512-[A-Za-z0-9+/]{86}==$/.test(e)}a(N,"isSha512Integrity");const R=/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*@\d+\.\d+\.\d+([-+][0-9A-Za-z.-]+)?$/;function f(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(f,"isRecord");function s(e){return typeof e=="string"&&e.trim()?e.trim():void 0}a(s,"text");function z(e={}){const n=e.env??process.env;let o;try{o=I(n)}catch(d){return{...l,problem:d instanceof Error?d.message:String(d)}}if(o.size===0)return{...l,problem:"no pinned market key"};const r=n.DALCODE_MARKET_CACHE_DIR?.trim(),c=e.file??(r?k(r,"index.json"):S());let i;try{i=JSON.parse(A(c,"utf8"))}catch{return{...l,problem:"no cached catalogue"}}const u=f(i)?i.sections?.packages:void 0,y=f(u)?u.body:void 0,t=K(y,o,e.now??new Date);return t.ok?{packages:t.packages,unpinned:t.unpinned,revoked:t.revoked}:{...l,problem:t.detail}}a(z,"readReviewedCatalogue");function K(e,n,o){if(!f(e))return{ok:!1,detail:"cached catalogue is not signed"};if(e.format!==_)return{ok:!1,detail:"cached catalogue is not signed"};const r=s(e.keyId),c=s(e.signature),i=e.payload;if(!r||!c||!f(i))return{ok:!1,detail:"cached catalogue is not signed"};const u=n.get(r);if(!u)return{ok:!1,detail:`unknown market key ${r}`};let y;try{y=E(null,Buffer.from(m(i),"utf8"),u,Buffer.from(c,"base64"))}catch(p){return{ok:!1,detail:p instanceof Error?p.message:String(p)}}if(!y)return{ok:!1,detail:"cached catalogue signature does not verify"};const t=s(i.expiresAt);if(t&&Number.isNaN(Date.parse(t)))return{ok:!1,detail:"cached catalogue has no readable expiry"};if(t&&Date.parse(t)<=o.getTime())return{ok:!1,detail:"cached catalogue has expired"};const d=(Array.isArray(i.revoked)?i.revoked:[]).filter(f).map(p=>({id:s(p.id)??"",version:s(p.version)??"*"})).filter(p=>p.id!==""),g=P(i);return{ok:!0,packages:g.packages,unpinned:g.unpinned,revoked:d}}a(K,"verifyEnvelope");function P(e){if(!f(e)||!Array.isArray(e.packages))return{packages:[],unpinned:[]};const n=[],o=[];for(const r of e.packages){if(!f(r))continue;const c=s(r.id);if(!c)continue;const i=r.source,u=typeof i=="string"?i:f(i)?s(i.spec)??s(r.spec):s(r.spec),y=f(i)?i.integrity??r.integrity:r.integrity,t=u?.replace(/^npm:/,""),d=(t?D(t):void 0)??s(r.version),g=!!t&&R.test(t);if(!t||!d||!g||!N(y)){o.push((t?C(t):c).toLowerCase());continue}n.push({id:c,source:t,version:d,integrity:y,...s(r.name)?{name:s(r.name)}:{},...s(r.description)?{summary:s(r.description)}:{},...r.security===!0?{security:!0}:{}})}return{packages:n,unpinned:o}}a(P,"packageRows");export{_ as MARKET_ENVELOPE_FORMAT,m as canonicalJson,w as ed25519PublicKeyFromBase64,S as marketCachePath,C as packageNameOf,I as readMarketKeys,z as readReviewedCatalogue,D as versionOfSpec};
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var t=(o,r)=>c(o,"name",{value:r,configurable:!0});function a(o){const r=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(o?.trim()??"");return r?{major:Number(r[1]),minor:Number(r[2]),patch:Number(r[3]),pre:r[4]??""}:void 0}t(a,"parse");function i(o,r){const e=a(o),n=a(r);if(!e||!n)return;const p=e.major-n.major||e.minor-n.minor||e.patch-n.patch;return p!==0?p:e.pre===n.pre?0:e.pre?n.pre?e.pre.localeCompare(n.pre):-1:1}t(i,"compareVersions");export{i as compareVersions};
@@ -1,2 +1,2 @@
1
- var E=Object.defineProperty;var d=(e,n)=>E(e,"name",{value:n,configurable:!0});import{existsSync as m,mkdirSync as w,readFileSync as b,writeFileSync as M}from"node:fs";import{dirname as O,join as S}from"node:path";import{CONFIG_DIR_NAME as N}from"../../config.js";import{mcpNamespace as g,validateMcpServerConfig as $}from"../../core/mcp-servers.js";import{getMcpToolExposure as P}from"../../core/mcp-servers.js";const x=["enabled","exposure","toolExposure"];function j(e){return e.command===void 0&&e.url===void 0&&e.type===void 0}d(j,"isOverride");function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}d(c,"isRecord");function y(e,n,o){const{servers:t,errors:s}=o;if(!m(e))return;let i;try{i=JSON.parse(b(e,"utf8"))}catch(r){s.push(`${e}: ${r instanceof Error?r.message:String(r)}`);return}if(!c(i)||i.mcpServers!==void 0&&!c(i.mcpServers)){s.push(`${e}: expected an object with an "mcpServers" object`);return}typeof i.autoEnableCodemode=="boolean"?o.autoEnableCodemode=i.autoEnableCodemode:i.autoEnableCodemode!==void 0&&s.push(`${e}: autoEnableCodemode must be a boolean`);for(const[r,u]of Object.entries(i.mcpServers??{})){if(n==="project"&&c(u)&&j(u)){const f=t.get(r),C=Object.keys(u).filter(a=>!x.includes(a));if(!f)s.push(`${e}: server "${r}" needs "command" or "url", or a global server to override`);else if(C.length>0)s.push(`${e}: server "${r}": an override can only set ${x.join(", ")}`);else{const a=$(r,{...f.config,...u});typeof a=="string"?s.push(`${e}: ${a}`):t.set(r,{...f,config:a,override:e})}continue}const l=$(r,u);if(typeof l=="string"){s.push(`${e}: ${l}`);continue}const v=[...t.keys()].find(f=>f!==r&&g(f)===g(r));if(v){s.push(`${e}: server "${r}" conflicts with "${v}"`);continue}if(n==="project"&&"url"in l&&l.auth){s.push(`${e}: server "${r}": auth is only allowed in the global mcp.json`);continue}t.set(r,{name:r,config:l,source:e,scope:n})}}d(y,"readConfigFile");function I(e){const n={servers:new Map,errors:[]};y(S(e.agentDir,"mcp.json"),"global",n);const o=e.projectTrusted?S(e.cwd,N,"mcp.json"):void 0;return o&&y(o,"project",n),{servers:[...n.servers.values()],...n.autoEnableCodemode===void 0?{}:{autoEnableCodemode:n.autoEnableCodemode},errors:n.errors,...o?{projectConfig:o}:{}}}d(I,"loadMcpConfig");function J(e,n,o,t={}){p(e,(s,i)=>{let r=s?.[n];if(r===void 0&&t.override&&(r={},i.mcpServers={...s,[n]:r}),!c(r))throw new Error(`${e} does not define MCP server "${n}"`);const u=j(r);return o.enabled!==void 0&&(o.enabled&&!u?delete r.enabled:r.enabled=o.enabled),o.exposure!==void 0&&(o.exposure==="codemode"&&!u?delete r.exposure:r.exposure=o.exposure),!0})}d(J,"updateMcpServerConfig");function _(e,n,o){let t=!1;return p(e,(s,i)=>{const r=s??{};return t=r[n]!==void 0,r[n]=o,i.mcpServers=r,!0}),t}d(_,"addMcpServerConfig");function T(e,n){if(!m(e))return!1;let o=!1;return p(e,t=>!t||t[n]===void 0?!1:(delete t[n],o=!0,!0)),o}d(T,"removeMcpServerConfig");function p(e,n){const o=m(e)?b(e,"utf8"):void 0,t=o===void 0?{}:JSON.parse(o);if(!c(t)||t.mcpServers!==void 0&&!c(t.mcpServers))throw new Error(`${e}: expected an object with an "mcpServers" object`);const s=c(t.mcpServers)?t.mcpServers:void 0;if(!n(s,t))return;const i=o&&/^([ \t]+)\S/m.exec(o)?.[1]||" ";w(O(e),{recursive:!0}),M(e,`${JSON.stringify(t,null,i)}
2
- `)}d(p,"editMcpServers");export{_ as addMcpServerConfig,P as getMcpToolExposure,I as loadMcpConfig,T as removeMcpServerConfig,J as updateMcpServerConfig};
1
+ var E=Object.defineProperty;var d=(e,n)=>E(e,"name",{value:n,configurable:!0});import{existsSync as p,readFileSync as b}from"node:fs";import{join as S}from"node:path";import{CONFIG_DIR_NAME as w}from"../../config.js";import{mcpNamespace as g,validateMcpServerConfig as $}from"../../core/mcp-servers.js";import{withFileLockSync as M,writeFileAtomicSync as O}from"../../core/shared-data.js";import{getMcpToolExposure as L}from"../../core/mcp-servers.js";const x=["enabled","exposure","toolExposure"];function j(e){return e.command===void 0&&e.url===void 0&&e.type===void 0}d(j,"isOverride");function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}d(c,"isRecord");function y(e,n,o){const{servers:t,errors:i}=o;if(!p(e))return;let s;try{s=JSON.parse(b(e,"utf8"))}catch(r){i.push(`${e}: ${r instanceof Error?r.message:String(r)}`);return}if(!c(s)||s.mcpServers!==void 0&&!c(s.mcpServers)){i.push(`${e}: expected an object with an "mcpServers" object`);return}typeof s.autoEnableCodemode=="boolean"?o.autoEnableCodemode=s.autoEnableCodemode:s.autoEnableCodemode!==void 0&&i.push(`${e}: autoEnableCodemode must be a boolean`);for(const[r,u]of Object.entries(s.mcpServers??{})){if(n==="project"&&c(u)&&j(u)){const f=t.get(r),C=Object.keys(u).filter(m=>!x.includes(m));if(!f)i.push(`${e}: server "${r}" needs "command" or "url", or a global server to override`);else if(C.length>0)i.push(`${e}: server "${r}": an override can only set ${x.join(", ")}`);else{const m=$(r,{...f.config,...u});typeof m=="string"?i.push(`${e}: ${m}`):t.set(r,{...f,config:m,override:e})}continue}const l=$(r,u);if(typeof l=="string"){i.push(`${e}: ${l}`);continue}const v=[...t.keys()].find(f=>f!==r&&g(f)===g(r));if(v){i.push(`${e}: server "${r}" conflicts with "${v}"`);continue}if(n==="project"&&"url"in l&&l.auth){i.push(`${e}: server "${r}": auth is only allowed in the global mcp.json`);continue}t.set(r,{name:r,config:l,source:e,scope:n})}}d(y,"readConfigFile");function I(e){const n={servers:new Map,errors:[]};y(S(e.agentDir,"mcp.json"),"global",n);const o=e.projectTrusted?S(e.cwd,w,"mcp.json"):void 0;return o&&y(o,"project",n),{servers:[...n.servers.values()],...n.autoEnableCodemode===void 0?{}:{autoEnableCodemode:n.autoEnableCodemode},errors:n.errors,...o?{projectConfig:o}:{}}}d(I,"loadMcpConfig");function J(e,n,o,t={}){a(e,(i,s)=>{let r=i?.[n];if(r===void 0&&t.override&&(r={},s.mcpServers={...i,[n]:r}),!c(r))throw new Error(`${e} does not define MCP server "${n}"`);const u=j(r);return o.enabled!==void 0&&(o.enabled&&!u?delete r.enabled:r.enabled=o.enabled),o.exposure!==void 0&&(o.exposure==="codemode"&&!u?delete r.exposure:r.exposure=o.exposure),!0})}d(J,"updateMcpServerConfig");function _(e,n,o){let t=!1;return a(e,(i,s)=>{const r=i??{};return t=r[n]!==void 0,r[n]=o,s.mcpServers=r,!0}),t}d(_,"addMcpServerConfig");function T(e,n){if(!p(e))return!1;let o=!1;return a(e,t=>!t||t[n]===void 0?!1:(delete t[n],o=!0,!0)),o}d(T,"removeMcpServerConfig");function a(e,n){M(e,()=>{const o=p(e)?b(e,"utf8"):void 0,t=o===void 0?{}:JSON.parse(o);if(!c(t)||t.mcpServers!==void 0&&!c(t.mcpServers))throw new Error(`${e}: expected an object with an "mcpServers" object`);const i=c(t.mcpServers)?t.mcpServers:void 0;if(!n(i,t))return;const s=o&&/^([ \t]+)\S/m.exec(o)?.[1]||" ";O(e,`${JSON.stringify(t,null,s)}
2
+ `)})}d(a,"editMcpServers");export{_ as addMcpServerConfig,L as getMcpToolExposure,I as loadMcpConfig,T as removeMcpServerConfig,J as updateMcpServerConfig};
package/dist/index.d.ts CHANGED
@@ -6,7 +6,7 @@ export { type BackgroundProcessEvent, type BackgroundProcessInfo, BackgroundProc
6
6
  export type { CacheWarmingDecision, CacheWarmingStatus } from "./core/cache-warmer.ts";
7
7
  export { type BranchPreparation, type BranchSummaryResult, type CollectEntriesResult, type CompactionResult, type CutPointResult, calculateContextTokens, collectEntriesForBranchSummary, compact, DEFAULT_COMPACTION_SETTINGS, estimateTokens, type FileOperations, findCutPoint, findTurnStartIndex, type GenerateBranchSummaryOptions, generateBranchSummary, generateSummary, generateSummaryWithUsage, getLastAssistantUsage, prepareBranchEntries, serializeConversation, shouldCompact, } from "./core/compaction/index.ts";
8
8
  export { createEventBus, type EventBus, type EventBusController } from "./core/event-bus.ts";
9
- export type { AfterProviderResponseEvent, AgentActivityOutcome, AgentBeforeSettleEvent, AgentBeforeSettleEventResult, AgentEndEvent, AgentSettledEvent, AgentStartEvent, AgentToolResult, AgentToolUpdateCallback, AppKeybinding, AutocompleteProviderFactory, BashToolCallEvent, BeforeAgentStartEvent, BeforeAgentStartEventResult, BeforeProviderHeadersEvent, BeforeProviderRequestEvent, BeforeProviderRequestEventResult, BoundaryContextPreview, BoundaryResult, BoundaryState, BuildSystemPromptOptions, CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult, CompactionEntryDraft, CompactOptions, ContextEditEntryDraft, ContextEvent, ContextEventResult, ContextUsage, ContextWithSystemEvent, CustomEntryDraft, CustomMessageEntryDraft, CustomToolCallEvent, EditToolCallEvent, EntryRenderer, EntryRenderOptions, ExecOptions, ExecResult, ExecuteToolOptions, Extension, ExtensionActions, ExtensionAPI, ExtensionCommandContext, ExtensionCommandContextActions, ExtensionContext, ExtensionContextActions, ExtensionError, ExtensionEvent, ExtensionFactory, ExtensionFlag, ExtensionHandler, ExtensionRuntime, ExtensionShortcut, ExtensionToolContext, ExtensionUIContext, ExtensionUIDialogOptions, ExtensionVirtualModel, ExtensionWidgetOptions, FindToolCallEvent, GrepToolCallEvent, InlineExtension, InputEvent, InputEventResult, InputSource, KeybindingsManager, LoadExtensionsResult, LsToolCallEvent, MarkdownTransformContext, MarkdownTransformer, McpServersChangeEvent, MessageEndEvent, MessageEndEventResult, MessageRenderer, MessageRenderOptions, MessageStartEvent, MessageUpdateEvent, ModelPickerEntry, ModelPickerEntryState, ModelSelectEvent, ModelSelectSource, NormalizedBuildSystemPromptOptions, PowerShellToolCallEvent, ProjectTrustContext, ProjectTrustEvent, ProjectTrustEventDecision, ProjectTrustEventResult, ProjectTrustHandler, ProviderChatModelConfig, ProviderConfig, ProviderModelConfig, ProviderStreamEvent, ReadToolCallEvent, RegisteredCommand, RegisteredModelPickerEntry, RegisteredTool, ResolvedCommand, ResourcesDiscoverEvent, ResourcesDiscoverResult, SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionBeforeForkEvent, SessionBeforeForkResult, SessionBeforeSwitchEvent, SessionBeforeSwitchResult, SessionBeforeTreeEvent, SessionBeforeTreeResult, SessionBoundaryDraft, SessionCompactEvent, SessionCompactFailedEvent, SessionInfoChangedEvent, SessionShutdownEvent, SessionStartEvent, SessionTreeEvent, SlashCommandInfo, SlashCommandSource, SourceInfo, TerminalInputHandler, ThinkingLevelSelectEvent, ToolAnnotations, ToolCallEvent, ToolCallEventResult, ToolDefinition, ToolExecutionEndEvent, ToolExecutionMode, ToolExecutionStartEvent, ToolExecutionUpdateEvent, ToolExposure, ToolInfo, ToolLoadout, ToolLoadoutChanges, ToolNamespace, ToolRendererResolver, ToolRenderers, ToolRenderResultOptions, ToolResultEvent, ToolResultEventResult, TurnEndEvent, TurnEndEventResult, TurnStartEvent, UIPromptEndEvent, UIPromptKind, UIPromptStartEvent, UserBashEvent, UserBashEventResult, WidgetPlacement, WorkingIndicatorOptions, WriteToolCallEvent, } from "./core/extensions/index.ts";
9
+ export type { AfterProviderResponseEvent, AgentActivityOutcome, AgentBeforeSettleEvent, AgentBeforeSettleEventResult, AgentEndEvent, AgentSettledEvent, AgentStartEvent, AgentToolResult, AgentToolUpdateCallback, AppKeybinding, AutocompleteProviderFactory, BashToolCallEvent, BeforeAgentStartCustomEvent, BeforeAgentStartEvent, BeforeAgentStartEventResult, BeforeAgentStartUserEvent, BeforeProviderHeadersEvent, BeforeProviderRequestEvent, BeforeProviderRequestEventResult, BoundaryContextPreview, BoundaryResult, BoundaryState, BuildSystemPromptOptions, CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult, CompactionEntryDraft, CompactOptions, ContextEditEntryDraft, ContextEvent, ContextEventResult, ContextUsage, ContextWithSystemEvent, CustomEntryDraft, CustomMessageEntryDraft, CustomToolCallEvent, EditToolCallEvent, EntryRenderer, EntryRenderOptions, ExecOptions, ExecResult, ExecuteToolOptions, Extension, ExtensionActions, ExtensionAPI, ExtensionCommandContext, ExtensionCommandContextActions, ExtensionContext, ExtensionContextActions, ExtensionError, ExtensionEvent, ExtensionFactory, ExtensionFlag, ExtensionHandler, ExtensionRuntime, ExtensionShortcut, ExtensionToolContext, ExtensionUIContext, ExtensionUIDialogOptions, ExtensionVirtualModel, ExtensionWidgetOptions, FindToolCallEvent, GrepToolCallEvent, InlineExtension, InputEvent, InputEventResult, InputSource, KeybindingsManager, LoadExtensionsResult, LsToolCallEvent, MarkdownTransformContext, MarkdownTransformer, McpServersChangeEvent, MessageEndEvent, MessageEndEventResult, MessageRenderer, MessageRenderOptions, MessageStartEvent, MessageUpdateEvent, ModelPickerEntry, ModelPickerEntryState, ModelSelectEvent, ModelSelectSource, NormalizedBuildSystemPromptOptions, PowerShellToolCallEvent, ProjectTrustContext, ProjectTrustEvent, ProjectTrustEventDecision, ProjectTrustEventResult, ProjectTrustHandler, ProviderChatModelConfig, ProviderConfig, ProviderModelConfig, ProviderStreamEvent, ReadToolCallEvent, RegisteredCommand, RegisteredModelPickerEntry, RegisteredTool, ResolvedCommand, ResourcesDiscoverEvent, ResourcesDiscoverResult, SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionBeforeForkEvent, SessionBeforeForkResult, SessionBeforeSwitchEvent, SessionBeforeSwitchResult, SessionBeforeTreeEvent, SessionBeforeTreeResult, SessionBoundaryDraft, SessionCompactEvent, SessionCompactFailedEvent, SessionInfoChangedEvent, SessionShutdownEvent, SessionStartEvent, SessionTreeEvent, SlashCommandInfo, SlashCommandSource, SourceInfo, TerminalInputHandler, ThinkingLevelSelectEvent, ToolAnnotations, ToolCallEvent, ToolCallEventResult, ToolDefinition, ToolExecutionEndEvent, ToolExecutionMode, ToolExecutionStartEvent, ToolExecutionUpdateEvent, ToolExposure, ToolInfo, ToolLoadout, ToolLoadoutChanges, ToolNamespace, ToolRendererResolver, ToolRenderers, ToolRenderResultOptions, ToolResultEvent, ToolResultEventResult, TurnEndEvent, TurnEndEventResult, TurnStartEvent, UIPromptEndEvent, UIPromptKind, UIPromptStartEvent, UserBashEvent, UserBashEventResult, WidgetPlacement, WorkingIndicatorOptions, WriteToolCallEvent, } from "./core/extensions/index.ts";
10
10
  export { createExtensionRuntime, defineTool, discoverAndLoadExtensions, ExtensionRunner, isBashToolResult, isEditToolResult, isFindToolResult, isGrepToolResult, isLsToolResult, isPowerShellToolResult, isReadToolResult, isToolCallEventType, isWriteToolResult, wrapRegisteredTool, wrapRegisteredTools, } from "./core/extensions/index.ts";
11
11
  export type { ReadonlyFooterDataProvider } from "./core/footer-data-provider.ts";
12
12
  export { getHostCapabilities, HOST_CAPABILITIES_ENV, HOST_TOKEN_ENV, HOST_TOKEN_HEADER, HOST_URL_ENV, HostCallError, type HostCallErrorCode, type HostCallOptions, type HostCallRequest, HostCapabilities, type HostCapabilitiesListener, type HostCapability, type HostCapabilitySource, type HostTransport, parseHostCapabilities, } from "./core/host-capabilities.ts";
@@ -1,6 +1,6 @@
1
- var x=Object.defineProperty;var n=(r,l)=>x(r,"name",{value:l,configurable:!0});import{flushRawStdout as I,waitForRawStdoutBackpressure as R,writeRawStdout as c}from"../core/output-guard.js";import{fill as M,t as u}from"../dal/i18n.js";import{killTrackedDetachedChildren as j}from"../utils/shell.js";import{toJsonEvent as k}from"./json-event.js";async function G(r,l){const{mode:i,messages:b=[],initialMessage:p,initialImages:h}=l;let g=0,o=r.session,f,d,m=!1;const w=[],y=n(async()=>{m||(m=!0,f?.(),d?.(),await r.dispose())},"disposeRuntime");n(()=>{const e=["SIGTERM"];process.platform!=="win32"&&e.push("SIGHUP");for(const s of e){const t=n(()=>{j(),y().finally(()=>{process.exit(s==="SIGHUP"?129:143)})},"handler");process.on(s,t),w.push(()=>process.off(s,t))}},"registerSignalHandlers")(),r.setRebindSession(async()=>{await S()});const S=n(async()=>{o=r.session,await o.bindExtensions({mode:i==="json"?"json":"print",commandContextActions:{waitForIdle:n(()=>o.waitForIdle(),"waitForIdle"),newSession:n(async e=>r.newSession(e),"newSession"),fork:n(async(e,s)=>({cancelled:(await r.fork(e,s)).cancelled}),"fork"),navigateTree:n(async(e,s)=>({cancelled:(await o.navigateTree(e,{summarize:s?.summarize,customInstructions:s?.customInstructions,replaceInstructions:s?.replaceInstructions,label:s?.label})).cancelled}),"navigateTree"),switchSession:n(async(e,s)=>r.switchSession(e,s),"switchSession"),reload:n(async()=>{await o.reload()},"reload")},onError:n(e=>{console.error(M(u("\u6269\u5C55\u51FA\u9519\uFF08{path}\uFF09\uFF1A{error}"),{path:e.extensionPath,error:String(e.error)}))},"onError")}),f?.(),d?.(),f=o.subscribe(e=>{i==="json"&&c(`${JSON.stringify(k(e))}
2
- `)}),d=i==="json"?o.agent.subscribe(async()=>{await R()}):void 0},"rebindSession");try{if(i==="json"){const e=o.sessionManager.getHeader();e&&c(`${JSON.stringify(e)}
3
- `)}await S(),p&&await o.prompt(p,{images:h});for(const e of b)await o.prompt(e);if(i==="text"){const e=o.state,s=e.messages[e.messages.length-1];if(s?.role==="custom"&&s.display){const t=typeof s.content=="string"?s.content:s.content.filter(a=>a.type==="text").map(a=>a.text).join(`
1
+ var R=Object.defineProperty;var n=(r,f)=>R(r,"name",{value:f,configurable:!0});import{flushRawStdout as I,waitForRawStdoutBackpressure as M,writeRawStdout as c}from"../core/output-guard.js";import{fill as j,t as l}from"../dal/i18n.js";import{killTrackedDetachedChildren as k}from"../utils/shell.js";import{toJsonEvent as E}from"./json-event.js";async function J(r,f){const{mode:i,messages:h=[],initialMessage:m,initialImages:x}=f;let d=0,p,o=r.session,u,g,w=!1;const y=[],S=n(async()=>{w||(w=!0,u?.(),g?.(),await r.dispose())},"disposeRuntime");n(()=>{const s=["SIGTERM"];process.platform!=="win32"&&s.push("SIGHUP");for(const e of s){const t=n(()=>{k(),S().finally(()=>{process.exit(e==="SIGHUP"?129:143)})},"handler");process.on(e,t),y.push(()=>process.off(e,t))}},"registerSignalHandlers")(),r.setRebindSession(async()=>{await b()});const b=n(async()=>{o=r.session,await o.bindExtensions({mode:i==="json"?"json":"print",commandContextActions:{waitForIdle:n(()=>o.waitForIdle(),"waitForIdle"),newSession:n(async s=>r.newSession(s),"newSession"),fork:n(async(s,e)=>({cancelled:(await r.fork(s,e)).cancelled}),"fork"),navigateTree:n(async(s,e)=>({cancelled:(await o.navigateTree(s,{summarize:e?.summarize,customInstructions:e?.customInstructions,replaceInstructions:e?.replaceInstructions,label:e?.label})).cancelled}),"navigateTree"),switchSession:n(async(s,e)=>r.switchSession(s,e),"switchSession"),reload:n(async()=>{await o.reload()},"reload")},onError:n(s=>{console.error(j(l("\u6269\u5C55\u51FA\u9519\uFF08{path}\uFF09\uFF1A{error}"),{path:s.extensionPath,error:String(s.error)}))},"onError")}),u?.(),g?.(),u=o.subscribe(s=>{s.type==="message_end"&&s.message.role==="assistant"&&(p=s.message),i==="json"&&c(`${JSON.stringify(E(s))}
2
+ `)}),g=i==="json"?o.agent.subscribe(async()=>{await M()}):void 0},"rebindSession");try{if(i==="json"){const s=o.sessionManager.getHeader();s&&c(`${JSON.stringify(s)}
3
+ `)}await b(),m&&await o.prompt(m,{images:x});for(const s of h)await o.prompt(s);if(i==="text"){const s=o.state,e=s.messages[s.messages.length-1];if(e?.role==="custom"&&e.display){const t=typeof e.content=="string"?e.content:e.content.filter(a=>a.type==="text").map(a=>a.text).join(`
4
4
  `);t&&c(`${t}
5
- `)}else if(s?.role==="assistant"){const t=s;if(t.stopReason==="error"||t.stopReason==="aborted")console.error(t.errorMessage||(t.stopReason==="aborted"?u("\u8BF7\u6C42\u5DF2\u4E2D\u6B62"):u("\u8BF7\u6C42\u51FA\u9519"))),g=1;else for(const a of t.content)a.type==="text"&&c(`${a.text}
6
- `)}}return g}catch(e){return console.error(e instanceof Error?e.message:String(e)),1}finally{for(const e of w)e();await y(),await I()}}n(G,"runPrintMode");export{G as runPrintMode};
5
+ `)}else if(p||e?.role==="assistant"){const t=p??e;if(t.stopReason==="error"||t.stopReason==="aborted")console.error(t.errorMessage||(t.stopReason==="aborted"?l("\u8BF7\u6C42\u5DF2\u4E2D\u6B62"):l("\u8BF7\u6C42\u51FA\u9519"))),d=1;else{for(const a of t.content)a.type==="text"&&c(`${a.text}
6
+ `);t.stopReason==="length"&&(console.error(l("\u56DE\u7B54\u88AB\u622A\u65AD\uFF1A\u6A21\u578B\u5DF2\u8FBE\u5230\u8F93\u51FA\u957F\u5EA6\u4E0A\u9650\u3002")),d=1)}}}return d}catch(s){return console.error(s instanceof Error?s.message:String(s)),1}finally{for(const s of y)s();await S(),await I()}}n(J,"runPrintMode");export{J as runPrintMode};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-bridge",
3
- "version": "1.0.36",
3
+ "version": "1.0.38",
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.36",
21
+ "@dalcode/dal-pi-kit": "1.0.38",
22
22
  "typebox": "1.3.7"
23
23
  },
24
24
  "peerDependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-gateway",
3
- "version": "1.0.36",
3
+ "version": "1.0.38",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -17,7 +17,7 @@
17
17
  ]
18
18
  },
19
19
  "dependencies": {
20
- "@dalcode/deepailab": "1.0.36"
20
+ "@dalcode/deepailab": "1.0.38"
21
21
  },
22
22
  "peerDependencies": {
23
23
  "@earendil-works/pi-coding-agent": "^1.0.9"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-goal",
3
- "version": "1.0.36",
3
+ "version": "1.0.38",
4
4
  "private": true,
5
5
  "description": "Goal mode for DAL: /goal keeps the agent working on one objective until it is verified complete, with token and continuation limits. Adapted from @narumitw/pi-goal 0.54.11 (MIT, narumiruna).",
6
6
  "license": "MIT",
@@ -21,7 +21,7 @@
21
21
  ]
22
22
  },
23
23
  "dependencies": {
24
- "@dalcode/dal-pi-kit": "1.0.36",
24
+ "@dalcode/dal-pi-kit": "1.0.38",
25
25
  "typebox": "1.3.27"
26
26
  },
27
27
  "peerDependencies": {