dal-code 1.0.37 → 1.0.39
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.
- package/CHANGELOG.md +14 -0
- package/dal-docs/settings.md +1 -1
- package/dist/core/agent-session.js +4 -4
- package/dist/core/auth-storage.js +1 -1
- package/dist/core/compaction/compaction.js +31 -13
- package/dist/core/package-manager.d.ts +4 -0
- package/dist/core/package-manager.js +2 -2
- package/dist/core/permissions/tool-policy.js +1 -1
- package/dist/core/project-facts.d.ts +16 -0
- package/dist/core/project-facts.js +2 -0
- package/dist/core/sandbox/policy.js +1 -1
- package/dist/core/sandbox/windows.js +1 -1
- package/dist/core/session-manager.d.ts +3 -0
- package/dist/core/session-manager.js +12 -12
- package/dist/core/settings-diagnostics.js +1 -1
- package/dist/core/settings-manager.d.ts +3 -0
- package/dist/core/settings-manager.js +1 -1
- package/dist/core/shared-data.js +1 -0
- package/dist/core/system-prompt.d.ts +1 -0
- package/dist/core/system-prompt.js +13 -13
- package/dist/core/trust-manager.js +2 -2
- package/dist/core/workspace-lock.d.ts +29 -0
- package/dist/core/workspace-lock.js +3 -0
- package/dist/dal/reviewed/endorsed-cli.js +1 -0
- package/dist/dal/reviewed/endorsed-plan.js +1 -0
- package/dist/dal/reviewed/endorsed.js +1 -0
- package/dist/dal/reviewed/version.js +1 -0
- package/dist/extensions/mcp/config.js +2 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/main.js +3 -3
- package/dist/modes/print-mode.js +5 -5
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-goal/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-guard/src/attribution.js +1 -0
- package/dist/node_modules/@dalcode/dal-guard/src/credentials.js +1 -1
- package/dist/node_modules/@dalcode/dal-guard/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-guard/src/mode.js +2 -2
- package/dist/node_modules/@dalcode/dal-guard/src/package-manager.js +1 -0
- package/dist/node_modules/@dalcode/dal-guard/src/workspace.js +2 -0
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-mcp/src/config-edit.js +2 -2
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +4 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/shared-data.js +1 -0
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +4 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/shared-data.js +1 -0
- package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-plugins/src/state.js +2 -2
- package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-router/package.json +5 -4
- package/dist/node_modules/@dalcode/dal-router/src/commands.js +7 -7
- package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +3 -1
- package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
- package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-router/src/runtime.js +1 -1
- package/dist/node_modules/@dalcode/dal-router/src/subagent.js +1 -1
- package/dist/node_modules/@dalcode/dal-router/src/suggest.js +2 -0
- package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-subagent/src/index.js +12 -12
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-telemetry/src/config.js +2 -2
- package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-workflow/src/completion-check.js +4 -0
- package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-workflow/src/ledger.js +3 -0
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/chord/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/dist/package-manager-cli.js +72 -72
- package/dist/utils/version-check.d.ts +1 -0
- package/dist/utils/version-check.js +2 -2
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);for(const n of t)if(n.trim())try{const s=JSON.parse(n);e.push(s)}catch{}return e}c(
|
|
3
|
-
`,u);for(;p!==-1;){const m=
|
|
4
|
-
`,u)}n=n.slice(u)}n+=o.end();const d=
|
|
5
|
-
`),t)}c(
|
|
6
|
-
`,u);for(;p!==-1;){s.push(a.slice(u,p));const m=
|
|
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()),
|
|
8
|
-
`)
|
|
9
|
-
`);else{if(!this._hasConversation())return;const t=
|
|
10
|
-
`)}finally{
|
|
11
|
-
`,{flag:"wx"});for(const w of l)w.type!=="session"
|
|
12
|
-
`);return new
|
|
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
|
|
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,28 +1,28 @@
|
|
|
1
|
-
var
|
|
1
|
+
var v=Object.defineProperty;var c=(e,t)=>v(e,"name",{value:t,configurable:!0});import{join as P}from"node:path";import{getSystemMessageText as j}from"@earendil-works/pi-ai";import{APP_NAME as E,APP_TITLE as p,getDalDocsPath as $,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{describeProjectFacts as D}from"./project-facts.js";import{formatSkillsForPrompt as F}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,projectFacts:e.projectFacts,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}c(R,"normalizeBuildSystemPromptOptions");function C(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(
|
|
6
|
-
`)}c(
|
|
7
|
-
`):"(none)";
|
|
5
|
+
`)}c(C,"renderProjectContext");function G(e,t,n){const r=[],d=new Set,s=c(l=>{const m=l.trim();!m||d.has(m)||(d.add(m),r.push(m))},"addRule"),h=e.includes("bash"),f=e.includes("powershell"),a=e.includes("grep"),u=e.includes("find"),y=e.includes("ls");(h||f)&&!a&&!u&&!y&&s(h&&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]??[])s(m);for(const l of n)s(l);return e.length>0&&(s("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"),s("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"),s("During longer work, tell the user every few tool rounds, in a sentence or two, what you found and what you will check next"),s("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"),s("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"),s("Verify the behaviours the request names and the edge cases it implies; do not write exhaustive or randomized test sweeps unless asked"),s("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"),s("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"),s("When a protection refuses a call, stop that step and tell the user why; never reach the same data another way (a copy, another tool or path)"),s(`Adapt instructions written for another agent before following or delegating them; drop what conflicts with your protections. You are ${p}: co-author trailer "Co-Authored-By: ${p} <noreply@deepailab.ai>", never Claude, Codex or Copilot`),s("Before calling a multi-part task done, match each part to its evidence and name what is not done or partly done; a load check is not a review")),s(`Text inside <${A} type="..."> tags comes from ${p} 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`),s("Be concise in your responses"),s("Show file paths clearly when working with files"),r.map(l=>`- ${l}`).join(`
|
|
6
|
+
`)}c(G,"buildRules");function B(e){const t=R(e),{customPrompt:n,selectedTools:r,hiddenTools:d,toolSnippets:s,toolGuidelines:h,promptGuidelines:f,appendSystemPrompt:a,sections:u,cwd:y,contextFiles:l,skills:m}=t;for(const o of Object.keys(u))if(!M.test(o)||o==="preamble")throw new Error(`Invalid system prompt section name: ${o}`);const b=r.filter(o=>!d.includes(o)),i={};if(n)i.preamble=n;else{i.preamble=`You are an expert coding assistant operating inside ${p} (${E}). You help users by reading files, executing commands, editing code, and writing new files.`;const o=b.filter(w=>!!s[w]),g=o.length>0?o.map(w=>`- ${w}: ${s[w]}`).join(`
|
|
7
|
+
`):"(none)";i.tools=`${g}
|
|
8
8
|
|
|
9
|
-
In addition to the tools above, you may have access to other custom tools depending on the project.`,
|
|
10
|
-
${
|
|
11
|
-
</${
|
|
12
|
-
${
|
|
9
|
+
In addition to the tools above, you may have access to other custom tools depending on the project.`,i.rules=G(b,h,f),i.docs=z()}a&&(i.addendum=a),l.length>0&&(i.project_context=C(l));const k=["read","bash"],S=k.find(o=>b.includes(o))??(k.some(o=>r.includes(o))?"indirect":void 0);if(S&&m.length>0){const o=F(m,S).trim();o&&(i.skills=o)}if(i.cwd=y.replace(/\\/g,"/"),t.gitState&&!u.git_state&&(i.git=N(y)),t.projectFacts&&!u.project){const o=D(y);o&&(i.project=o)}for(const[o,g]of Object.entries(u))g&&(i[o]=g);const x={preamble:i.preamble};for(const[o,g]of Object.entries(i))o!=="preamble"&&(x[o]=`<${o}>
|
|
10
|
+
${g}
|
|
11
|
+
</${o}>`);return x}c(B,"buildSystemPromptSections");const L="cwd",U="Environment of this session, part of the system prompt. Later updates to these sections arrive as system prompt updates.";function Z(e){const t=e[0];if(!t||t.role!=="system"||!t.sections)return e;const n=Object.keys(t.sections),r=n.indexOf(L);if(r===-1)return e;const d=n.slice(r).map(a=>t.sections?.[a]).filter(a=>typeof a=="string"&&a.length>0),s=Object.fromEntries(n.slice(0,r).map(a=>[a,t.sections?.[a]??null])),h={...t,sections:s};if(d.length===0)return[h,...e.slice(1)];const f={role:"user",content:[{type:"text",text:`<session_environment>
|
|
12
|
+
${U}
|
|
13
13
|
|
|
14
14
|
${d.join(`
|
|
15
15
|
|
|
16
16
|
`)}
|
|
17
|
-
</session_environment>`}],timestamp:t.timestamp};return[
|
|
18
|
-
- Start with: ${
|
|
17
|
+
</session_environment>`}],timestamp:t.timestamp};return[h,f,...e.slice(1)]}c(Z,"moveSessionEnvironmentOutOfSystemPrompt");function W(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:B(e)}}c(W,"buildSystemPromptState");function ee(e){return j({role:"system",...W(e),timestamp:0})}c(ee,"buildSystemPrompt");function te(e,t){const n={};for(const[r,d]of Object.entries(t))e[r]!==d&&(n[r]=d);for(const r of Object.keys(e))t[r]===void 0&&(n[r]=null);return Object.keys(n).length>0?n:void 0}c(te,"diffSystemPromptSections");function z(){if(I){const e=$();return`${p} documentation (read only when the user asks about ${p} itself: its commands, settings, skills, prompt templates, extensions, packages, themes or keybindings):
|
|
18
|
+
- Start with: ${P(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 ${
|
|
21
|
+
- Read the relevant file completely before answering or implementing, and describe the product as ${p}`}return`${p} documentation (read only when the user asks about ${p} itself, its SDK, extensions, themes, skills, or TUI):
|
|
22
22
|
- Main documentation: ${_()}
|
|
23
|
-
- Additional docs: ${
|
|
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)
|
|
27
27
|
- When working on these topics, read the docs and examples, and follow .md cross-references before implementing
|
|
28
|
-
- Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}c(
|
|
28
|
+
- Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}c(z,"buildDocumentationSection");export{L as SESSION_ENVIRONMENT_FIRST_SECTION,ee as buildSystemPrompt,B as buildSystemPromptSections,W as buildSystemPromptState,te as diffSystemPromptSections,Z as moveSessionEnvironmentOutOfSystemPrompt,R as normalizeBuildSystemPromptOptions};
|
|
@@ -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
|
|
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}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,29 @@
|
|
|
1
|
+
export declare const WORKSPACE_LOCK_FILE = "dal-workspace.lock";
|
|
2
|
+
export declare const STALE_AFTER_MS: number;
|
|
3
|
+
export interface WorkspaceLock {
|
|
4
|
+
pid: number;
|
|
5
|
+
host: string;
|
|
6
|
+
sessionId: string;
|
|
7
|
+
startedAt: string;
|
|
8
|
+
refreshedAt: string;
|
|
9
|
+
worktree?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface WorkspaceClaim {
|
|
12
|
+
gitDir: string;
|
|
13
|
+
worktree?: string;
|
|
14
|
+
heldBy?: WorkspaceLock;
|
|
15
|
+
}
|
|
16
|
+
export declare function gitDirOf(dir: string): {
|
|
17
|
+
gitDir: string;
|
|
18
|
+
worktree?: string;
|
|
19
|
+
} | undefined;
|
|
20
|
+
export declare function workspaceOwnerSessionId(sessionId: string, env?: NodeJS.ProcessEnv): string;
|
|
21
|
+
export declare function readWorkspaceLock(gitDir: string): WorkspaceLock | undefined;
|
|
22
|
+
export declare function workspaceLockIsLive(lock: WorkspaceLock, now?: number): boolean;
|
|
23
|
+
export declare function claimWorkspace(dir: string, sessionId: string, options?: {
|
|
24
|
+
now?: number;
|
|
25
|
+
env?: NodeJS.ProcessEnv;
|
|
26
|
+
force?: boolean;
|
|
27
|
+
}): WorkspaceClaim | undefined;
|
|
28
|
+
export declare function releaseWorkspace(gitDir: string): void;
|
|
29
|
+
export declare function shellCommandDirectory(command: string, cwd: string): string;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var l=Object.defineProperty;var c=(t,e)=>l(t,"name",{value:e,configurable:!0});import{execFileSync as m}from"node:child_process";import{readFileSync as k,renameSync as y,rmSync as D,writeFileSync as A}from"node:fs";import{hostname as p}from"node:os";import{isAbsolute as E,join as u,resolve as f}from"node:path";const a="dal-workspace.lock",I=7200*1e3,O=60*1e3,x="DALCODE_PARENT_SESSION_ID",w=new Map;function _(t){const e=f(t),n=w.get(e);if(n!==void 0)return n??void 0;let r=null;try{const i=m("git",["rev-parse","--git-dir","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim().split(`
|
|
2
|
+
`),o=i[0]?.trim();o&&(r={gitDir:E(o)?o:f(e,o),worktree:i[1]?.trim()})}catch{r=null}return w.set(e,r),r??void 0}c(_,"gitDirOf");function v(t,e=process.env){return e[x]||t}c(v,"workspaceOwnerSessionId");function S(t){try{const e=JSON.parse(k(u(t,a),"utf8"));return typeof e.pid!="number"||typeof e.sessionId!="string"||typeof e.host!="string"?void 0:{pid:e.pid,host:e.host,sessionId:e.sessionId,startedAt:typeof e.startedAt=="string"?e.startedAt:new Date(0).toISOString(),refreshedAt:typeof e.refreshedAt=="string"?e.refreshedAt:new Date(0).toISOString(),...typeof e.worktree=="string"?{worktree:e.worktree}:{}}}catch{return}}c(S,"readWorkspaceLock");function L(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}c(L,"processAlive");function g(t,e=Date.now()){const n=Date.parse(t.refreshedAt);return!Number.isFinite(n)||e-n>I?!1:t.host===p()?L(t.pid):!0}c(g,"workspaceLockIsLive");function h(t,e){const n=u(t,a),r=`${n}.${process.pid}.tmp`;A(r,`${JSON.stringify(e,null,2)}
|
|
3
|
+
`),y(r,n)}c(h,"writeLock");function $(t,e,n={}){const r=_(t);if(!r)return;const i=n.now??Date.now(),o=v(e,n.env),s=S(r.gitDir),d={gitDir:r.gitDir,...r.worktree?{worktree:r.worktree}:{}};if(s&&s.sessionId!==o&&g(s,i)&&!n.force)return{...d,heldBy:s};if(s?.sessionId===o&&g(s,i)){if(!(s.pid===process.pid&&s.host===p())||i-Date.parse(s.refreshedAt)<O)return d;try{h(r.gitDir,{...s,refreshedAt:new Date(i).toISOString()})}catch{}return d}try{h(r.gitDir,{pid:process.pid,host:p(),sessionId:o,startedAt:new Date(i).toISOString(),refreshedAt:new Date(i).toISOString(),...r.worktree?{worktree:r.worktree}:{}})}catch{return}return d}c($,"claimWorkspace");function H(t){const e=S(t);if(!(!e||e.pid!==process.pid||e.host!==p()))try{D(u(t,a),{force:!0})}catch{}}c(H,"releaseWorkspace");function P(t,e){let n=e;for(const i of t.split(/&&|;|\n/)){const o=/^\s*cd\s+("([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(i);if(!o)break;const s=(o[2]??o[3]??o[4]??"").replace(/^~(?=\/|$)/,process.env.HOME??"~");n=f(n,s)}const r=/\bgit\s+-C\s+("([^"]+)"|'([^']+)'|(\S+))/.exec(t);return r&&(n=f(n,r[2]??r[3]??r[4]??".")),n}c(P,"shellCommandDirectory");export{I as STALE_AFTER_MS,a as WORKSPACE_LOCK_FILE,$ as claimWorkspace,_ as gitDirOf,S as readWorkspaceLock,H as releaseWorkspace,P as shellCommandDirectory,g as workspaceLockIsLive,v as workspaceOwnerSessionId};
|
|
@@ -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
|
|
2
|
-
`)}d(
|
|
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
|
@@ -19,6 +19,7 @@ export type { PackageManager, PathMetadata, ProgressCallback, ProgressEvent, Res
|
|
|
19
19
|
export { DefaultPackageManager } from "./core/package-manager.ts";
|
|
20
20
|
export { buildRuleSet, matchPermissionRules, type PermissionBehavior, type PermissionRule, type PermissionRuleSet, type PermissionRuleSource, parsePermissionRule, type RuleCall, type RuleVerdict, } from "./core/permissions/rules.ts";
|
|
21
21
|
export { evaluateToolPolicy, type PermissionAskHandler, type PermissionAskRequest, readAccessDenial, registerPermissionAskHandler, type ToolPolicyDecision, } from "./core/permissions/tool-policy.ts";
|
|
22
|
+
export { describeProjectFacts, detectProjectFacts, type PackageManagerName, type ProjectFacts, projectPackageManager, } from "./core/project-facts.ts";
|
|
22
23
|
export { buildProjectMap, formatProjectMapPrompt, type ProjectMap, type ProjectMapOptions, } from "./core/project-map.ts";
|
|
23
24
|
export type { ResourceCollision, ResourceDiagnostic, ResourceLoader } from "./core/resource-loader.ts";
|
|
24
25
|
export { DefaultResourceLoader, loadProjectContextFiles } from "./core/resource-loader.ts";
|
|
@@ -32,6 +33,7 @@ export { type EditDiffResult, generateDiffString, generateUnifiedPatch } from ".
|
|
|
32
33
|
export { type BashOperations, type BashSpawnContext, type BashSpawnHook, type BashToolDetails, type BashToolInput, type BashToolOptions, createBashToolDefinition, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLocalBashOperations, createLocalPowerShellOperations, createLsToolDefinition, createPowerShellToolDefinition, createProcessToolDefinition, createReadToolDefinition, createWriteToolDefinition, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type EditOperations, type EditToolDetails, type EditToolInput, type EditToolOptions, type FindOperations, type FindToolDetails, type FindToolInput, type FindToolOptions, formatSize, type GrepOperations, type GrepToolDetails, type GrepToolInput, type GrepToolOptions, type LsOperations, type LsToolDetails, type LsToolInput, type LsToolOptions, type PowerShellOperations, type PowerShellSpawnContext, type PowerShellSpawnHook, type PowerShellToolDetails, type PowerShellToolInput, type PowerShellToolOptions, type ProcessToolDetails, type ProcessToolInput, type ReadOperations, type ReadToolDetails, type ReadToolInput, type ReadToolOptions, registerShellExecutionGuard, type ShellExecutionGuard, type ShellExecutionRequest, type ToolsOptions, type TruncationOptions, type TruncationResult, truncateHead, truncateLine, truncateTail, type WriteOperations, type WriteToolInput, type WriteToolOptions, withFileMutationQueue, } from "./core/tools/index.ts";
|
|
33
34
|
export { hasTrustRequiringProjectResources, type ProjectTrustDecision, ProjectTrustStore, type ProjectTrustStoreEntry, type ProjectTrustUpdate, } from "./core/trust-manager.ts";
|
|
34
35
|
export { type ModelRoute, type ModelRouteReason, type ModelRouteRequest, VIRTUAL_MODEL_STATE_ENTRY, type VirtualModelDefinition, type VirtualModelStateData, } from "./core/virtual-models.ts";
|
|
36
|
+
export { claimWorkspace, gitDirOf, readWorkspaceLock, releaseWorkspace, STALE_AFTER_MS, shellCommandDirectory, WORKSPACE_LOCK_FILE, type WorkspaceClaim, type WorkspaceLock, workspaceLockIsLive, workspaceOwnerSessionId, } from "./core/workspace-lock.ts";
|
|
35
37
|
export { applyShellEnvironmentPolicy, DEFAULT_SHELL_ENV_EXCLUDES, isDalCodeCredentialName, type ShellEnvironmentPolicy, withoutDalCodeCredentials, } from "./dal/child-env.ts";
|
|
36
38
|
export * from "./dal/hooks/index.ts";
|
|
37
39
|
export { isHostExtensionPath, markHostExtensionPaths } from "./dal/host-extensions.ts";
|