dal-code 1.0.32 → 1.0.34
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/NOTICE +8 -0
- package/dist/core/agent-session.d.ts +3 -0
- package/dist/core/agent-session.js +8 -8
- package/dist/core/bash-executor.js +1 -1
- package/dist/core/bug-report.js +4 -4
- package/dist/core/compaction/branch-summarization.js +2 -2
- package/dist/core/compaction/compaction.d.ts +4 -2
- package/dist/core/compaction/compaction.js +13 -13
- package/dist/core/compaction/index.d.ts +1 -0
- package/dist/core/compaction/index.js +1 -1
- package/dist/core/compaction/tool-output-pruning.d.ts +19 -0
- package/dist/core/compaction/tool-output-pruning.js +7 -0
- package/dist/core/compaction/utils.d.ts +1 -0
- package/dist/core/compaction/utils.js +9 -9
- package/dist/core/sdk.js +1 -1
- package/dist/core/settings-manager.d.ts +11 -2
- package/dist/core/settings-manager.js +1 -1
- package/dist/core/source-info.d.ts +1 -0
- package/dist/core/source-info.js +1 -1
- package/dist/core/system-prompt.d.ts +3 -0
- package/dist/core/system-prompt.js +19 -13
- package/dist/core/tools/bash.d.ts +1 -1
- package/dist/core/tools/bash.js +19 -15
- package/dist/core/tools/output-accumulator.js +3 -3
- package/dist/core/tools/output-condense.js +3 -0
- package/dist/core/tools/powershell.d.ts +1 -1
- package/dist/core/tools/powershell.js +1 -1
- package/dist/dal/manifest.js +1 -1
- package/dist/modes/interactive/interactive-mode.js +13 -13
- 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/LICENSE +45 -0
- package/dist/node_modules/@dalcode/dal-goal/package.json +35 -0
- package/dist/node_modules/@dalcode/dal-goal/src/core.js +10 -0
- package/dist/node_modules/@dalcode/dal-goal/src/index.js +7 -0
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- 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 +4 -3
- package/dist/node_modules/@dalcode/dal-lsp/src/checkers.js +4 -0
- package/dist/node_modules/@dalcode/dal-lsp/src/index.js +8 -6
- package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +3 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +3 -2
- package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -2
- package/dist/node_modules/@dalcode/dal-plugins/src/brand.d.ts +17 -0
- package/dist/node_modules/@dalcode/dal-plugins/src/brand.js +1 -1
- package/dist/node_modules/@dalcode/dal-plugins/src/index.js +12 -8
- package/dist/node_modules/@dalcode/dal-plugins/src/manage.js +8 -8
- package/dist/node_modules/@dalcode/dal-plugins/src/market.js +4 -0
- package/dist/node_modules/@dalcode/dal-plugins/src/settings.js +1 -1
- package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-rewind/LICENSE +24 -0
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
- 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 +14 -13
- package/dist/node_modules/@dalcode/dal-subagent/src/process-runner.js +3 -3
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +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/deepailab/package.json +3 -3
- package/dist/node_modules/@dalcode/deepailab/src/index.js +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/nvidia.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/utils/retry.d.ts +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/retry.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/sdk/index.d.ts +1 -0
- package/dist/sdk/index.js +1 -1
- package/dist/utils/clipboard-image.js +1 -1
- package/dist/utils/clipboard.js +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- 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,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var q=Object.defineProperty;var f=(e,t)=>q(e,"name",{value:t,configurable:!0});import{contentText as b,getCurrentSystemMessage as G,normalizeContext as Y,retryAssistantCall as H,uuidv7 as J}from"@earendil-works/pi-ai";import{completeSimple as Q}from"@earendil-works/pi-ai/compat";import{convertToLlm as N}from"../messages.js";import{buildSessionProjection as ee,sessionEntryToContextMessages as C}from"../session-manager.js";import{DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS as te}from"../settings-manager.js";import{combineUsage as ne}from"../usage-totals.js";import{shrinkToolResultsForSummary as se}from"./tool-output-pruning.js";import{computeFileLists as oe,createFileOps as re,estimateTokens as P,extractFileOpsFromMessage as _,formatFileOperations as ie,SUMMARIZATION_SYSTEM_PROMPT as ae,serializeConversation as D}from"./utils.js";function ce(e,t,o){const n=re();if(o>=0){const s=t[o];if(!s.fromHook&&s.details){const i=s.details;if(Array.isArray(i.readFiles))for(const a of i.readFiles)n.read.add(a);if(Array.isArray(i.modifiedFiles))for(const a of i.modifiedFiles)n.edited.add(a)}}for(const s of e)_(s,n);return n}f(ce,"extractFileOperations");function F(e){return e.sourceEntry.type==="compaction"?[]:e.messages.filter(t=>t.role!=="system")}f(F,"getMessagesFromProjectedEntryForCompaction");const Ue={enabled:!0,reserveTokens:16384,keepRecentTokens:2e4};function z(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}f(z,"calculateContextTokens");function K(e){if(e.role==="assistant"&&"usage"in e){const t=e;if(t.stopReason!=="aborted"&&t.stopReason!=="error"&&t.usage&&z(t.usage)>0)return t.usage}}f(K,"getAssistantUsage");function be(e){for(let t=e.length-1;t>=0;t--){const o=e[t];if(o.type==="message"){const n=K(o.message);if(n)return n}}}f(be,"getLastAssistantUsage");function ue(e){for(let t=e.length-1;t>=0;t--){const o=K(e[t]);if(o)return{usage:o,index:t}}}f(ue,"getLastAssistantUsageInfo");function fe(e){const t=ue(e);if(!t){let s=0;for(const i of e)s+=P(i);return{tokens:s,usageTokens:0,trailingTokens:s,lastUsageIndex:null}}const o=z(t.usage);let n=0;for(let s=t.index+1;s<e.length;s++)n+=P(e[s]);return{tokens:o+n,usageTokens:o,trailingTokens:n,lastUsageIndex:t.index}}f(fe,"estimateContextTokens");function me(e,t){const o=fe(e.messages);if(o.lastUsageIndex!==null){let i=0,a;for(const m of e.entries){const c=i+m.messages.length;if(o.lastUsageIndex<c){a=m.sourceEntry.id;break}i=c}const u=a?t.findIndex(m=>m.id===a):-1;let l=-1;for(let m=t.length-1;m>=0;m--){const c=t[m];if(c.type==="context_edit"||c.type==="compaction"){l=m;break}}if(u>l)return o}const n=G(e.messages);let s=n?P(n):0;for(const i of e.messages)i.role!=="system"&&(s+=P(i));return{tokens:s,usageTokens:0,trailingTokens:s,lastUsageIndex:null}}f(me,"estimateProjectedContextTokens");const le=32e3;function pe(e,t,o=0){const n=e-t.reserveTokens;if(!t.maxContextTokens)return n;if(t.maxContextTokens!==te)return Math.min(n,t.maxContextTokens);const s=o+t.keepRecentTokens+le;return Math.min(n,Math.max(t.maxContextTokens,s))}f(pe,"compactionThreshold");function Ne(e,t,o,n=0){return o.enabled?e>pe(t,o,n):!1}f(Ne,"shouldCompact");function $(e){switch(e.role){case"user":case"assistant":case"bashExecution":case"custom":case"branchSummary":case"compactionSummary":return!0;case"toolResult":return!1}return!1}f($,"isCutPointMessage");function B(e){switch(e.role){case"user":case"bashExecution":case"custom":case"branchSummary":case"compactionSummary":return!0;case"assistant":case"toolResult":return!1}return!1}f(B,"isTurnStartMessage");function L(e){return e.type==="compaction"?!1:C(e).some(B)}f(L,"isTurnStartEntry");function de(e,t,o){const n=[];for(let s=t;s<o;s++){const i=e[s];i.type!=="compaction"&&C(i).some($)&&n.push(s)}return n}f(de,"findValidCutPoints");function ge(e,t,o){for(let n=t;n>=o;n--)if(L(e[n]))return n;return-1}f(ge,"findTurnStartIndex");function _e(e,t,o,n){const s=de(e,t,o);if(s.length===0)return{firstKeptEntryIndex:t,turnStartIndex:-1,isSplitTurn:!1};let i=0,a=s[0];for(let c=o-1;c>=t;c--){const d=e[c],x=C(d).reduce((y,T)=>y+P(T),0);if(x!==0&&(i+=x,i>=n)){a=s.find(y=>y>=c)??s[s.length-1];break}}for(;a>t;){const c=e[a-1];if(c.type==="compaction"||C(c).length>0)break;a--}const u=e[a],l=L(u),m=l?-1:ge(e,a,t);return{firstKeptEntryIndex:a,turnStartIndex:m,isSplitTurn:!l&&m!==-1}}f(_e,"findCutPoint");const xe=`The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
|
|
2
2
|
|
|
3
3
|
Use this EXACT format:
|
|
4
4
|
|
|
@@ -29,7 +29,7 @@ Use this EXACT format:
|
|
|
29
29
|
- [Any data, examples, or references needed to continue]
|
|
30
30
|
- [Or "(none)" if not applicable]
|
|
31
31
|
|
|
32
|
-
Keep each section concise. Preserve exact file paths, function names, and error messages.`,
|
|
32
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`,ye=`Update the existing structured summary with new information. RULES:
|
|
33
33
|
- PRESERVE all existing information from the previous summary
|
|
34
34
|
- ADD new progress, decisions, and context from the new messages
|
|
35
35
|
- UPDATE the Progress section: move items from "In Progress" to "Done" when completed
|
|
@@ -64,19 +64,19 @@ Use this EXACT format:
|
|
|
64
64
|
## Critical Context
|
|
65
65
|
- [Preserve important context, add new if needed]
|
|
66
66
|
|
|
67
|
-
Keep each section concise. Preserve exact file paths, function names, and error messages.`,
|
|
67
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`,Te=`The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
|
|
68
68
|
|
|
69
|
-
${
|
|
69
|
+
${ye}`;function j(e,t){if(e.stopReason==="error")return`${t} failed: ${e.errorMessage||"Unknown error"}`;if(e.stopReason==="length")return`${t} failed: generation hit the token cap and the summary is incomplete`}f(j,"getSummarizationFailure");function V(e,t,o,n,s,i,a,u){const l={maxTokens:t,signal:i,apiKey:o,headers:n,env:s,sessionId:u};return e.reasoning&&a&&a!=="off"&&(l.reasoning=a),l}f(V,"createSummarizationOptions");async function W(e,t,o,n,s,i){const a={...o,cacheRetention:"none",sessionId:o.sessionId??J()};return H(f(async()=>n?(await n(e,t,a)).result():Q(e,t,a),"produce"),s,a.signal,i)}f(W,"completeSummarization");async function De(e,t,o,n,s,i,a,u,l,m,c,d,x,y){return(await A(e,t,o,n,s,i,a,u,l,m,c,d,x,y)).text}f(De,"generateSummary");function X(e){return Y({systemPrompt:ae,messages:[{role:"user",content:[{type:"text",text:e}],timestamp:Date.now()}]})}f(X,"buildSummarizationContext");async function A(e,t,o,n,s,i,a,u,l,m,c,d,x,y){const T=Math.min(Math.floor(.8*o),t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY);let g=u?Te:xe;a&&(g=`${g}
|
|
70
70
|
|
|
71
|
-
Additional focus: ${a}`);const r=N(e);let
|
|
72
|
-
${
|
|
71
|
+
Additional focus: ${a}`);const r=N(e);let h=`<conversation>
|
|
72
|
+
${D(r)}
|
|
73
73
|
</conversation>
|
|
74
74
|
|
|
75
|
-
`;
|
|
76
|
-
${
|
|
75
|
+
`;u&&(h+=`<previous-summary>
|
|
76
|
+
${u}
|
|
77
77
|
</previous-summary>
|
|
78
78
|
|
|
79
|
-
`),
|
|
79
|
+
`),h+=g;const S=V(t,T,n,s,c,i,l,y),E=await W(t,X(h),S,m,d,x),k=j(E,"Summarization");if(k)throw new Error(k);if(E.content.some(v=>v.type==="toolCall"))throw new Error("Summarization attempted to call a tool");return{text:b(E.content),usage:E.usage}}f(A,"generateSummaryWithUsage");function Z(e){return e.sourceEntry.type==="compaction"?!1:e.messages.some(B)}f(Z,"isProjectedTurnStart");function he(e,t,o){for(let n=t;n>=o;n--)if(Z(e[n]))return n;return-1}f(he,"findProjectedTurnStartIndex");function Se(e,t,o,n){const s=[];for(let r=t;r<o;r++){const p=e[r];p.sourceEntry.type!=="compaction"&&p.messages.some($)&&s.push(r)}if(s.length===0)return{firstKeptEntryIndex:t,turnStartIndex:-1,isSplitTurn:!1};let i=0,a=!1,u=s[0];for(let r=o-1;r>=t;r--){const p=e[r].messages.reduce((h,S)=>h+P(S),0);if(p!==0&&(i+=p,i>=n)){a=!0,u=s.find(h=>h>=r)??s[s.length-1];break}}const l=e.slice(u+1,o),m=f(r=>r.sourceEntry.type!=="context_edit"&&C(r.sourceEntry).length>0,"isIntrinsicallyVisible"),c=f(r=>m(r)&&r.messages.length===0,"isOmitted"),d=new Set(l.filter(c).map(r=>r.sourceEntry.id)),x=l.some(r=>r.sourceEntry.type==="context_edit"&&r.sourceEntry.replacement!==null&&!d.has(r.sourceEntry.targetId));for(a&&!x&&l.some(r=>r.sourceEntry.type==="message"&&r.sourceEntry.message.role==="assistant"&&c(r))&&l.every(r=>r.sourceEntry.type!=="compaction"&&(!m(r)||c(r)))&&u++;u>t;){const r=e[u-1];if(r.sourceEntry.type==="compaction"||r.messages.length>0)break;u--}const T=Z(e[u]),g=T?-1:he(e,u,t);return{firstKeptEntryIndex:u,turnStartIndex:g,isSplitTurn:!T&&g!==-1}}f(Se,"findProjectedCutPoint");function Fe(e,t){if(e.length>0&&e[e.length-1].type==="compaction")return;const o=ee(e),n=o.entries,s=n.map(p=>p.sourceEntry),i=n.findIndex(p=>p.sourceEntry.type==="compaction"&&p.messages.length>0);let a,u=0;i>=0&&(a=n[i].sourceEntry.summary,u=i+1);const l=n.length,m=me(o,e).tokens,c=Se(n,u,l,t.keepRecentTokens),d=n[c.firstKeptEntryIndex]?.sourceEntry;if(!d?.id)return;const x=d.id,y=c.isSplitTurn?c.turnStartIndex:c.firstKeptEntryIndex,T=n.slice(u,y).flatMap(F),g=c.isSplitTurn?n.slice(c.turnStartIndex,c.firstKeptEntryIndex).flatMap(F):[];if(T.length===0&&g.length===0)return;const r=ce(T,s,i);if(c.isSplitTurn)for(const p of g)_(p,r);return{firstKeptEntryId:x,messagesToSummarize:T,turnPrefixMessages:g,isSplitTurn:c.isSplitTurn,tokensBefore:m,previousSummary:a,fileOps:r,settings:t}}f(Fe,"prepareCompaction");const Ee=`The messages above are earlier context from an ongoing conversation. Later messages are stored separately and do not need to be reconstructed.
|
|
80
80
|
|
|
81
81
|
Create a concise checkpoint of the user's request and the progress shown above. This checkpoint will be placed before the later messages so the conversation can continue with the necessary context.
|
|
82
82
|
|
|
@@ -89,14 +89,14 @@ Create a concise checkpoint of the user's request and the progress shown above.
|
|
|
89
89
|
## Context Needed to Continue
|
|
90
90
|
- [Information from these messages needed to understand the later work]
|
|
91
91
|
|
|
92
|
-
Only summarize information explicitly present above. Do not infer or recreate later messages.`;async function
|
|
92
|
+
Only summarize information explicitly present above. Do not infer or recreate later messages.`;async function ze(e,t,o,n,s,i,a,u,l,m,c,d){const{firstKeptEntryId:x,isSplitTurn:y,tokensBefore:T,previousSummary:g,fileOps:r,settings:p}=e,h=p.pruneToolOutputs===!1?I=>I:se,S=h(e.messagesToSummarize),E=h(e.turnPrefixMessages);let k,w;if(y&&E.length>0){let I=g??"No prior history.",M;if(S.length>0){const U=await A(S,t,p.reserveTokens,o,n,i,s,g,a,u,l,m,c,d);I=U.text,M=U.usage}const O=await ke(E,t,p.reserveTokens,o,n,l,i,a,u,m,c,d);k=`${I}
|
|
93
93
|
|
|
94
94
|
---
|
|
95
95
|
|
|
96
96
|
**Turn Context (split turn):**
|
|
97
97
|
|
|
98
|
-
${
|
|
99
|
-
${
|
|
98
|
+
${O.text}`,w=M?ne(M,O.usage):O.usage}else{const I=await A(S,t,p.reserveTokens,o,n,i,s,g,a,u,l,m,c,d);k=I.text,w=I.usage}const{readFiles:v,modifiedFiles:R}=oe(r);if(k+=ie(v,R),!x)throw new Error("First kept entry has no UUID - session may need migration");return{summary:k,firstKeptEntryId:x,tokensBefore:T,usage:w,details:{readFiles:v,modifiedFiles:R}}}f(ze,"compact");async function ke(e,t,o,n,s,i,a,u,l,m,c,d){const x=Math.min(Math.floor(.5*o),t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY),y=N(e),g=`# Conversation
|
|
99
|
+
${D(y)}
|
|
100
100
|
|
|
101
101
|
# Instructions
|
|
102
|
-
${
|
|
102
|
+
${Ee}`,r=await W(t,X(g),V(t,x,n,s,i,a,u,d),l,m,c),p=j(r,"Turn prefix summarization");if(p)throw new Error(p);if(r.content.some(h=>h.type==="toolCall"))throw new Error("Turn prefix summarization attempted to call a tool");return{text:b(r.content),usage:r.usage}}f(ke,"generateTurnPrefixSummary");export{Ue as DEFAULT_COMPACTION_SETTINGS,le as MIN_COMPACTION_HEADROOM_TOKENS,z as calculateContextTokens,ze as compact,pe as compactionThreshold,W as completeSummarization,fe as estimateContextTokens,me as estimateProjectedContextTokens,_e as findCutPoint,ge as findTurnStartIndex,De as generateSummary,A as generateSummaryWithUsage,be as getLastAssistantUsage,j as getSummarizationFailure,Fe as prepareCompaction,Ne as shouldCompact};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./branch-summarization.js";export*from"./compaction.js";export*from"./utils.js";
|
|
1
|
+
export*from"./branch-summarization.js";export*from"./compaction.js";export*from"./tool-output-pruning.js";export*from"./utils.js";
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { ToolResultMessage } from "@earendil-works/pi-ai";
|
|
3
|
+
import type { SessionProjection } from "../session-manager.ts";
|
|
4
|
+
export declare const PRUNED_OUTPUT_MARKER = "[Earlier tool output shortened to save context";
|
|
5
|
+
export declare const MIN_PRUNE_TOKENS = 600;
|
|
6
|
+
export interface ToolOutputPruneEdit {
|
|
7
|
+
targetId: string;
|
|
8
|
+
content: ToolResultMessage["content"];
|
|
9
|
+
tokensBefore: number;
|
|
10
|
+
tokensAfter: number;
|
|
11
|
+
}
|
|
12
|
+
export interface ToolOutputPrunePlan {
|
|
13
|
+
edits: ToolOutputPruneEdit[];
|
|
14
|
+
tokensSaved: number;
|
|
15
|
+
}
|
|
16
|
+
export declare function shrinkToolResultsForSummary(messages: AgentMessage[]): AgentMessage[];
|
|
17
|
+
export declare function shrinkToolOutput(text: string, toolName: string, args: Record<string, unknown> | undefined): string | undefined;
|
|
18
|
+
export declare function planToolOutputPruning(projection: SessionProjection, keepRecentTokens: number): ToolOutputPrunePlan;
|
|
19
|
+
export declare const PRUNE_TARGET_RATIO = 0.6;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
var N=Object.defineProperty;var u=(t,o)=>N(t,"name",{value:o,configurable:!0});import{estimateTokens as g}from"./utils.js";const m="[Earlier tool output shortened to save context",R=600,y=8,$=15,P=20,E=300,L=/\b(?:error|errors|fail|failed|failure|failing|fatal|panic|exception|traceback|assert(?:ion)?|denied|segfault|cannot|unable)\b|✗|✘|×/i,O=/Full output: ([^\]\n]+?)(?:\]|$)/m;function I(t){const o=new Map;for(const n of t)if(n.role==="assistant")for(const e of n.content)e.type==="toolCall"&&o.set(e.id,e.arguments);return o}u(I,"toolArgs");function A(t,o){if(t.role!=="toolResult"||t.content.some(s=>s.type!=="text")||g(t)<R)return;const n=t.content.map(s=>s.type==="text"?s.text:"").join(`
|
|
2
|
+
`),e=S(n,t.toolName,o.get(t.toolCallId));return e===void 0?void 0:[{type:"text",text:e}]}u(A,"shrinkToolResult");function b(t){const o=I(t);return t.map(n=>{const e=A(n,o);return e?{...n,content:e}:n})}u(b,"shrinkToolResultsForSummary");function T(t){return t.length>E?`${t.slice(0,E)}\u2026`:t}u(T,"clipLine");function k(t,o,n){const e=O.exec(t)?.[1]?.trim();if(e)return`Full output: ${e} (read it if you need more).`;if(o==="bash"&&typeof n?.command=="string"){const l=n.command.replace(/\s+/g," ").trim();return`Re-run \`${l.length>200?`${l.slice(0,200)}\u2026`:l}\` if you need the full output.`}const s=typeof n?.path=="string"?n.path:typeof n?.file_path=="string"?n.file_path:"";return o==="read"&&s?`Re-read ${s} if you need it (it may have changed since).`:`Repeat the ${o} call if you need the full result.`}u(k,"recoveryHint");function S(t,o,n){if(t.includes(m))return;const e=t.split(`
|
|
3
|
+
`);if(e.length<=y+$+2){if(t.length<4*R)return;const c=t.slice(0,1200),d=t.slice(-1200),_=`${m}: ${t.length} chars \u2192 ${c.length+d.length} shown. ${k(t,o,n)}]
|
|
4
|
+
${c}
|
|
5
|
+
\u2026 (${t.length-c.length-d.length} chars omitted)
|
|
6
|
+
${d}`;return _.length*2<=t.length?_:void 0}const s=e.slice(0,y).map(T),l=e.slice(-$).map(T),p=e.slice(y,e.length-$),a=p.filter(c=>L.test(c)),r=a.slice(0,P).map(T),f=s.length+r.length+l.length,i=[`${m}: ${e.length} lines \u2192 ${f} shown. ${k(t,o,n)}]`,...s,`\u2026 (${p.length-r.length} lines omitted${r.length>0?"; error lines kept below":""})`,...r];a.length>r.length&&i.push(`\u2026 (${a.length-r.length} more error lines omitted)`),i.push(...l);const h=i.join(`
|
|
7
|
+
`);return h.length*2<=t.length?h:void 0}u(S,"shrinkToolOutput");function w(t,o){const n=t.entries;let e=n.length,s=0;for(;e>0&&s<o;){e--;for(const r of n[e].messages)s+=g(r)}const l=I(t.messages),p=[];let a=0;for(let r=0;r<e;r++){const f=n[r];if(f.sourceEntry.type!=="message"||f.messages.length!==1)continue;const i=f.messages[0];if(i.role!=="toolResult")continue;const h=A(i,l);if(!h)continue;const c=g(i),d=g({...i,content:h});p.push({targetId:f.sourceEntry.id,content:h,tokensBefore:c,tokensAfter:d}),a+=c-d}return{edits:p,tokensSaved:a}}u(w,"planToolOutputPruning");const C=.6;export{R as MIN_PRUNE_TOKENS,m as PRUNED_OUTPUT_MARKER,C as PRUNE_TARGET_RATIO,w as planToolOutputPruning,S as shrinkToolOutput,b as shrinkToolResultsForSummary};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import { type Message } from "@earendil-works/pi-ai";
|
|
3
|
+
export declare function estimateTokens(message: AgentMessage): number;
|
|
3
4
|
export interface FileOperations {
|
|
4
5
|
read: Set<string>;
|
|
5
6
|
written: Set<string>;
|
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var p=Object.defineProperty;var
|
|
2
|
-
${n.join(`
|
|
3
|
-
`)}
|
|
4
|
-
</read-files>`),e.length>0&&t.push(`<modified-files>
|
|
1
|
+
var p=Object.defineProperty;var i=(e,n)=>p(e,"name",{value:n,configurable:!0});import{contentText as c}from"@earendil-works/pi-ai";const m=4800;function a(e){if(typeof e=="string")return e.length;let n=0;for(const t of e)t.type==="text"&&t.text?n+=t.text.length:t.type==="image"&&(n+=m);return n}i(a,"estimateTextAndImageContentChars");function k(e){let n=0;switch(e.role){case"system":{const t=e;if(n=a(t.content),t.sections)for(const o of Object.values(t.sections))o&&(n+=o.length);return t.toolsAdded&&(n+=JSON.stringify(t.toolsAdded).length),Math.ceil(n/4)}case"user":return n=a(e.content),Math.ceil(n/4);case"assistant":{const t=e;for(const o of t.content)o.type==="text"?n+=o.text.length:o.type==="thinking"?n+=o.thinking.length:o.type==="toolCall"&&(n+=o.name.length+JSON.stringify(o.arguments).length);return Math.ceil(n/4)}case"custom":case"toolResult":return n=a(e.content),Math.ceil(n/4);case"bashExecution":return n=e.command.length+e.output.length,Math.ceil(n/4);case"branchSummary":case"compactionSummary":return n=e.summary.length,Math.ceil(n/4)}return 0}i(k,"estimateTokens");function x(){return{read:new Set,written:new Set,edited:new Set}}i(x,"createFileOps");function M(e,n){if(e.role==="toolResult"){for(const t of e.nestedCalls?.calls??[])l(t.name,t.arguments,n);return}if(e.role==="assistant"&&!(!("content"in e)||!Array.isArray(e.content)))for(const t of e.content)typeof t!="object"||t===null||!("type"in t)||t.type!=="toolCall"||!("arguments"in t)||!("name"in t)||l(t.name,t.arguments,n)}i(M,"extractFileOpsFromMessage");function l(e,n,t){const o=typeof n?.path=="string"?n.path:void 0;if(o)switch(e){case"read":t.read.add(o);break;case"write":t.written.add(o);break;case"edit":t.edited.add(o);break}}i(l,"addFileOp");function $(e){const n=new Set([...e.edited,...e.written]),t=[...e.read].filter(s=>!n.has(s)).sort(),o=[...n].sort();return{readFiles:t,modifiedFiles:o}}i($,"computeFileLists");function b(e,n){const t=[];return e.length>0&&t.push(`<read-files>
|
|
5
2
|
${e.join(`
|
|
6
3
|
`)}
|
|
4
|
+
</read-files>`),n.length>0&&t.push(`<modified-files>
|
|
5
|
+
${n.join(`
|
|
6
|
+
`)}
|
|
7
7
|
</modified-files>`),t.length===0?"":`
|
|
8
8
|
|
|
9
9
|
${t.join(`
|
|
10
10
|
|
|
11
|
-
`)}`}
|
|
11
|
+
`)}`}i(b,"formatFileOperations");const g=2e3;function y(e,n){if(e.length<=n)return e;const t=e.length-n;return`${e.slice(0,n)}
|
|
12
12
|
|
|
13
|
-
[... ${t} more characters truncated]`}
|
|
14
|
-
`)}`),t.content.some(
|
|
13
|
+
[... ${t} more characters truncated]`}i(y,"truncateForSummary");function T(e){const n=[];for(const t of e)if(t.role==="user"){const o=c(t.content,"");o&&n.push(`[User]: ${o}`)}else if(t.role==="assistant"){const o=[],s=[];for(const r of t.content)if(r.type==="thinking")o.push(r.thinking);else if(r.type==="toolCall"){const u=r.arguments,f=Object.entries(u).map(([h,d])=>`${h}=${JSON.stringify(d)}`).join(", ");s.push(`${r.name}(${f})`)}o.length>0&&n.push(`[Assistant thinking]: ${o.join(`
|
|
14
|
+
`)}`),t.content.some(r=>r.type==="text")&&n.push(`[Assistant]: ${c(t.content)}`),s.length>0&&n.push(`[Assistant tool calls]: ${s.join("; ")}`)}else if(t.role==="toolResult"){const o=c(t.content,"");o&&n.push(`[Tool result]: ${y(o,g)}`)}return n.join(`
|
|
15
15
|
|
|
16
|
-
`)}
|
|
16
|
+
`)}i(T,"serializeConversation");const w=`You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.
|
|
17
17
|
|
|
18
|
-
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;export{
|
|
18
|
+
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;export{w as SUMMARIZATION_SYSTEM_PROMPT,$ as computeFileLists,x as createFileOps,k as estimateTokens,M as extractFileOpsFromMessage,b as formatFileOperations,T as serializeConversation};
|
package/dist/core/sdk.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var z=Object.defineProperty;var d=(
|
|
1
|
+
var z=Object.defineProperty;var d=(o,u)=>z(o,"name",{value:u,configurable:!0});import{join as A}from"node:path";import{Agent as J,setDefaultStreamFn as X}from"@earendil-works/pi-agent-core";import{clampThinkingLevel as Y,streamSimple as Z}from"@earendil-works/pi-ai/compat";import{getAgentDir as ee}from"../config.js";import{resolvePath as b}from"../utils/paths.js";import{AgentSession as te}from"./agent-session.js";import{formatNoModelsAvailableMessage as oe}from"./auth-guidance.js";import{CacheWarmer as re}from"./cache-warmer.js";import{DEFAULT_THINKING_LEVEL as B}from"./defaults.js";import{createToolNameMatcher as ne}from"./mcp-servers.js";import{convertToLlm as se}from"./messages.js";import{findInitialModel as ie}from"./model-resolver.js";import{ModelRuntime as ae}from"./model-runtime.js";import{mergeProviderAttributionHeaders as de}from"./provider-attribution.js";import{DefaultResourceLoader as le}from"./resource-loader.js";import{getDefaultSessionDir as me,SessionManager as ce}from"./session-manager.js";import{applyToolModifiers as ue,DEFAULT_TOOL_NAMES as ge,getToolListError as fe,isToolModifier as ve,SettingsManager as Te}from"./settings-manager.js";import{moveSessionEnvironmentOutOfSystemPrompt as he}from"./system-prompt.js";import{time as pe}from"./timings.js";import{createBashTool as Me,createCodingTools as ye,createEditTool as xe,createFindTool as Le,createGrepTool as ke,createLsTool as Se,createPowerShellTool as De,createReadOnlyTools as Re,createReadTool as Ie,createWriteTool as we,withFileMutationQueue as Ce}from"./tools/index.js";import{getBranchSelection as Pe}from"./virtual-models.js";X(Z);export*from"./agent-session-runtime.js";function Ee(){return ee()}d(Ee,"getDefaultAgentDir");async function et(o={}){const u=b(o.cwd??o.sessionManager?.getCwd()??process.cwd()),h=o.agentDir?b(o.agentDir):Ee();let p=o.resourceLoader;const N=o.agentDir?A(h,"auth.json"):void 0,H=o.agentDir?A(h,"models.json"):void 0,g=o.modelRuntime??await ae.create({authPath:N,modelsPath:H}),r=o.settingsManager??Te.create(u,h),l=o.sessionManager??ce.create(u,me(u,h));p||(p=new le({cwd:u,agentDir:h,settingsManager:r}),await p.reload(),pe("resourceLoader.reload"));const D=l.buildSessionContext(),k=D.messages.length>0,w=l.getBranch().some(e=>e.type==="thinking_level_change");let n=o.model,M,R;const f=Pe(l.getBranch(),(e,t)=>g.getModel(e,t));if(!n&&k&&f){const e=g.getModel(f.provider,f.modelId);e&&g.hasConfiguredAuth(e.provider)&&(n=e),n||(M=`Could not restore model ${f.provider}/${f.modelId}`,R={provider:f.provider,modelId:f.modelId})}if(!n){const e=r.getDefaultProvider(),t=r.getDefaultModel();n=(await ie({scopedModels:[],isContinuing:k,defaultProvider:e,defaultModelId:t,defaultThinkingLevel:r.getDefaultThinkingLevel(),modelThinkingLevels:r.getAllModelThinkingLevels(),modelRuntime:g})).model,n?M&&(M+=`. Using ${n.provider}/${n.id}`):M=oe(),e&&t&&(!n||n.provider!==e||n.id!==t)&&(R={provider:e,modelId:t})}let i=o.thinkingLevel;if(i===void 0&&k&&(i=w?D.thinkingLevel:r.getDefaultThinkingLevel()??B),i===void 0&&n){const e=r.getModelThinkingLevel(n.provider,n.id);e&&(i=e)}i===void 0&&(i=r.getDefaultThinkingLevel()??B),n?i=Y(n,i):i="off";const C=o.tools?fe(o.tools):void 0;if(C)throw new Error(`Invalid tools option: ${C}`);const P=o.noTools?[]:r.getDefaultTools()??o.defaultActiveTools??ge,y=o.tools?.some(ve)?o.tools:void 0,E=y?ue(P,y):o.tools,F=y?o.noTools==="all"?E:void 0:o.tools??(o.noTools==="all"?[]:void 0),I=o.excludeTools,O=I?ne(I):void 0,W=(E??P).filter(e=>!O?.(e)),U=d(e=>{const t=se(e);return r.getBlockImages()?t.map(s=>{if(s.role==="user"||s.role==="toolResult"){const a=s.content;if(Array.isArray(a)&&a.some(m=>m.type==="image")){const m=a.map(c=>c.type==="image"?{type:"text",text:"Image reading is disabled."}:c).filter((c,x,L)=>!(c.type==="text"&&c.text==="Image reading is disabled."&&x>0&&L[x-1].type==="text"&&L[x-1].text==="Image reading is disabled."));return{...s,content:m}}}return s}):t},"convertToLlmWithBlockImages"),v={},_=new re(g,l,()=>r.getCacheWarmingMode(),async e=>v.current?.emitCacheWarmingDecision(e)??e.action),$=d((e,t={})=>{const s=r.getProviderRetrySettings(),a=r.getHttpIdleTimeoutMs(),T=a===0?2147483647:a,m=v.current,c=r.getOutputTokenLimit(e.maxTokens);return{...t,maxTokens:t.maxTokens??(c!==e.maxTokens?c:void 0),timeoutMs:t.timeoutMs??s.timeoutMs??T,websocketConnectTimeoutMs:t.websocketConnectTimeoutMs??r.getWebSocketConnectTimeoutMs(),maxRetries:t.maxRetries??s.maxRetries,maxRetryDelayMs:t.maxRetryDelayMs??s.maxRetryDelayMs,transformHeaders:d(async x=>{const L=de(e,r,t.sessionId,x);return m?.hasHandlers("before_provider_headers")?m.emitBeforeProviderHeaders(L??{}):L??{}},"transformHeaders")}},"buildRequestOptions"),j=d(e=>{const t=S.state.messages;return()=>{const s=S.state.model,a=S.state.messages;return s.provider===e.provider&&s.id===e.id&&t.length<=a.length&&t.every((T,m)=>a[m]===T)}},"cacheContextIsCurrent"),q=d(async e=>{const t=v.current;return t?.hasHandlers("before_provider_request")?t.emitBeforeProviderRequest(e):e},"transformProviderPayload"),G=d(async e=>{const t=v.current;t?.hasHandlers("after_provider_response")&&await t.emit({type:"after_provider_response",status:e.status,headers:e.headers})},"handleProviderResponse"),K=d(async(e,t)=>{const s=v.current;s?.hasHandlers("provider_stream_event")&&await s.emit({data:e,type:"provider_stream_event",provider:t.provider,api:t.api,model:t.id})},"handleProviderStreamEvent"),S=new J({initialState:{systemPrompt:"",model:n,thinkingLevel:i,tools:[],messages:D.messages},convertToLlm:U,streamFn:d(async(e,t,s)=>{const a=$(e,s),T={...t,messages:he(t.messages)};return s?.sessionId===l.getSessionId()&&_.start({model:e,context:T,options:a},j(e)),g.streamSimple(e,T,a)},"streamFn"),onPayload:q,onResponse:G,onProviderStreamEvent:K,sessionId:l.getSessionId(),transformContext:d(async e=>{const t=v.current;return t?t.emitContext(e):e},"transformContext"),steeringMode:r.getSteeringMode(),followUpMode:r.getFollowUpMode(),transport:r.getTransport(),thinkingBudgets:r.getThinkingBudgets(),maxRetryDelayMs:r.getProviderRetrySettings().maxRetryDelayMs});k?w||l.appendThinkingLevelChange(i):(n&&l.appendModelChange(n.provider,n.id),l.appendThinkingLevelChange(i));const Q=new te({agent:S,sessionManager:l,settingsManager:r,cwd:u,scopedModels:o.scopedModels,resourceLoader:p,customTools:o.customTools,modelRuntime:g,cacheWarmer:_,initialActiveToolNames:W,usesDefaultTools:(o.tools===void 0||y!==void 0)&&!o.noTools,defaultToolModifiers:y,allowedToolNames:F,excludedToolNames:I,extensionRunnerRef:v,sessionStartEvent:o.sessionStartEvent,desiredModel:R,sandbox:o.sandbox}),V=p.getExtensions();return{session:Q,extensionsResult:V,modelFallbackMessage:M}}d(et,"createAgentSession");export{et as createAgentSession,Me as createBashTool,ye as createCodingTools,xe as createEditTool,Le as createFindTool,ke as createGrepTool,Se as createLsTool,De as createPowerShellTool,Re as createReadOnlyTools,Ie as createReadTool,we as createWriteTool,Ce as withFileMutationQueue};
|
|
@@ -6,15 +6,18 @@ import type { SandboxSettings, SandboxSettingsSources } from "./sandbox/policy.t
|
|
|
6
6
|
export interface CompactionModelOverride {
|
|
7
7
|
reserveTokens?: number;
|
|
8
8
|
keepRecentTokens?: number;
|
|
9
|
+
maxContextTokens?: number;
|
|
9
10
|
}
|
|
11
|
+
export declare const DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS = 80000;
|
|
10
12
|
export interface CompactionSettings {
|
|
11
13
|
enabled?: boolean;
|
|
12
14
|
reserveTokens?: number;
|
|
13
15
|
keepRecentTokens?: number;
|
|
14
16
|
modelOverrides?: Record<string, CompactionModelOverride>;
|
|
15
17
|
maxContextTokens?: number;
|
|
18
|
+
summaryModel?: string;
|
|
19
|
+
pruneToolOutputs?: boolean;
|
|
16
20
|
}
|
|
17
|
-
export declare const DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS = 128000;
|
|
18
21
|
export declare const DEFAULT_MAX_OUTPUT_TOKENS = 32000;
|
|
19
22
|
export declare const DEFAULT_MAX_RETRIES = 5;
|
|
20
23
|
export interface BranchSummarySettings {
|
|
@@ -251,8 +254,14 @@ export declare class SettingsManager {
|
|
|
251
254
|
reserveTokens: number;
|
|
252
255
|
keepRecentTokens: number;
|
|
253
256
|
maxContextTokens: number;
|
|
257
|
+
pruneToolOutputs: boolean;
|
|
254
258
|
};
|
|
255
|
-
getCompactionMaxContextTokens(): number;
|
|
259
|
+
getCompactionMaxContextTokens(model?: Pick<Model<string>, "provider" | "id">): number;
|
|
260
|
+
getCompactionPruneToolOutputs(): boolean;
|
|
261
|
+
getCompactionSummaryModel(): {
|
|
262
|
+
provider: string;
|
|
263
|
+
modelId: string;
|
|
264
|
+
} | undefined;
|
|
256
265
|
getBranchSummarySettings(): {
|
|
257
266
|
reserveTokens: number;
|
|
258
267
|
skipPrompt: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var F=Object.defineProperty;var a=(r,e)=>F(r,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as L}from"@earendil-works/pi-ai";import{randomUUID as M}from"crypto";import{existsSync as y,mkdirSync as I,readFileSync as A,writeFileSync as O}from"fs";import{dirname as N,join as u}from"path";import D from"proper-lockfile";import{CONFIG_DIR_NAME as T,getAgentDir as R}from"../config.js";import{normalizePath as v,resolvePath as m}from"../utils/paths.js";import{stripBom as P}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as W,parseHttpIdleTimeoutMs as _}from"./http-dispatcher.js";const $={reserveTokens:16384,keepRecentTokens:2e4},U=128e3,B=32e3,H=5,q=["off","streaming","idle"];function p(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}a(p,"isMergeableObject");function j(r,e){const t={...r};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const n=r[s];t[s]=p(n)&&p(i)?j(n,i):i}return t}a(j,"deepMergeObjects");const V=["read","bash","edit","write"];function f(r){return typeof r=="string"&&(r.startsWith("+")||r.startsWith("-"))}a(f,"isToolModifier");function le(r){const e=r.filter(f);if(e.length===0)return;if(e.length<r.length)return"tool names cannot be mixed with +name or -name entries";const t=e.find(s=>s.includes("*"));if(t)return`+name and -name entries take exact tool names, not patterns: ${t}`}a(le,"getToolListError");function X(r,e){const t=[...r];for(const s of e){if(!f(s))continue;const i=s.slice(1),n=t.indexOf(i);s.startsWith("+")&&n===-1&&i?t.push(i):s.startsWith("-")&&n!==-1&&t.splice(n,1)}return t}a(X,"applyToolModifiers");function K(r,e){return e===void 0?r:!Array.isArray(r)||!Array.isArray(e)||!e.every(f)?e:[...r,...e]}a(K,"mergeDefaultTools");function Q(r){const e=r.filter(t=>!f(t));return X(e.length>0||r.length===0?e:V,r)}a(Q,"resolveDefaultTools");function h(r,e){const t=j(r,e),s=K(r.defaultTools,e.defaultTools);return s===void 0?t:{...t,defaultTools:s}}a(h,"deepMergeSettings");function C(r,e){const t=_(r);if(t!==void 0)return t;if(r!==void 0)throw new Error(`Invalid ${e} setting: ${String(r)}`)}a(C,"parseTimeoutSetting");function S(r,e,t){return{scope:r,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}a(S,"toSettingsError");class z{static{a(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=m(e),i=m(t);this.globalSettingsPath=u(i,"settings.json"),this.projectSettingsPath=u(s,T,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let n=1;n<=10;n++)try{return D.lockSync(e,{realpath:!1})}catch(o){if((typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0)!=="ELOCKED"||n===10)throw o;i=o;const g=Date.now();for(;Date.now()-g<20;);}throw i??new Error("Failed to acquire settings lock")}withLock(e,t){const s=e==="global"?this.globalSettingsPath:this.projectSettingsPath,i=N(s);let n;try{const o=y(s);o&&(n=this.acquireLockSyncWithRetry(s));const l=o?A(s,"utf-8"):void 0,g=t(l);g!==void 0&&(y(i)||I(i,{recursive:!0}),n||(n=this.acquireLockSyncWithRetry(s)),O(s,g,"utf-8"))}finally{n&&n()}}}class G{static{a(this,"InMemorySettingsStorage")}global;project;withLock(e,t){const s=e==="global"?this.global:this.project,i=t(s);i!==void 0&&(e==="global"?this.global=i:this.project=i)}}class d{static{a(this,"SettingsManager")}storage;globalSettings;projectSettings;settings;projectTrusted;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(e,t,s,i=null,n=null,o=[],l=!0,g={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=l,this.globalSettingsLoadError=i,this.projectSettingsLoadError=n,this.errors=[...o],this.settingsPaths=g,this.settings=h(this.globalSettings,this.projectSettings)}static create(e,t=R(),s={}){const i=m(e),n=m(t),o=new z(i,n);return d.fromStorageWithPaths(o,s,{global:u(n,"settings.json"),project:u(i,T,"settings.json")})}static fromStorage(e,t={}){return d.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,n=d.tryLoadFromStorage(e,"global"),o=d.tryLoadFromStorage(e,"project",i),l=[];return n.error&&l.push(S("global",n.error,s.global)),o.error&&l.push(S("project",o.error,s.project)),new d(e,n.settings,o.settings,n.error,o.error,l,i,s)}static inMemory(e={},t={}){const s=new G,i=d.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),d.fromStorage(s,t)}static loadFromStorage(e,t,s=!0){if(t==="project"&&!s)return{};let i;if(e.withLock(t,o=>{i=o}),!i)return{};const n=JSON.parse(P(i));return d.migrateSettings(n)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:d.loadFromStorage(e,t,s),error:null}}catch(i){return{settings:{},error:i}}}static migrateSettings(e){if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),!("transport"in e)&&typeof e.websockets=="boolean"&&(e.transport=e.websockets?"websocket":"sse",delete e.websockets),"skills"in e&&typeof e.skills=="object"&&e.skills!==null&&!Array.isArray(e.skills)){const t=e.skills;t.enableSkillCommands!==void 0&&e.enableSkillCommands===void 0&&(e.enableSkillCommands=t.enableSkillCommands),Array.isArray(t.customDirectories)&&t.customDirectories.length>0?e.skills=t.customDirectories:delete e.skills}if("retry"in e&&typeof e.retry=="object"&&e.retry!==null&&!Array.isArray(e.retry)){const t=e.retry,s=typeof t.provider=="object"&&t.provider!==null?t.provider:void 0;typeof t.maxDelayMs=="number"&&(s?.maxRetryDelayMs===void 0||s?.maxRetryDelayMs===null)&&(t.provider={...s??{},maxRetryDelayMs:t.maxDelayMs}),delete t.maxDelayMs}return e}getSettings(){return structuredClone(this.settings)}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}isProjectTrusted(){return this.projectTrusted}setProjectTrusted(e){if(this.projectTrusted===e)return;if(this.projectTrusted=e,this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear(),!e){this.projectSettings={},this.projectSettingsLoadError=null,this.settings=h(this.globalSettings,this.projectSettings);return}const t=d.tryLoadFromStorage(this.storage,"project",e);this.projectSettings=t.settings,this.projectSettingsLoadError=t.error,t.error&&this.recordError("project",t.error),this.settings=h(this.globalSettings,this.projectSettings)}async reload(){await this.writeQueue;const e=d.tryLoadFromStorage(this.storage,"global");e.error?(this.globalSettingsLoadError=e.error,this.recordError("global",e.error)):(this.globalSettings=e.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();const t=d.tryLoadFromStorage(this.storage,"project",this.projectTrusted);t.error?(this.projectSettingsLoadError=t.error,this.recordError("project",t.error)):(this.projectSettings=t.settings,this.projectSettingsLoadError=null),this.settings=h(this.globalSettings,this.projectSettings)}applyOverrides(e){this.settings=h(this.settings,e)}markModified(e,t){this.modifiedFields.add(e),t&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(t))}markProjectModified(e,t){this.modifiedProjectFields.add(e),t&&(this.modifiedProjectNestedFields.has(e)||this.modifiedProjectNestedFields.set(e,new Set),this.modifiedProjectNestedFields.get(e).add(t))}assertProjectTrustedForWrite(){if(!this.projectTrusted)throw new Error("Project is not trusted; refusing to write project settings")}recordError(e,t){this.errors.push(S(e,t,this.settingsPaths[e]))}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,t){this.writeQueue=this.writeQueue.then(()=>{e==="project"&&this.assertProjectTrustedForWrite(),t(),this.clearModifiedScope(e)}).catch(s=>{this.recordError(e,s)})}cloneModifiedNestedFields(e){const t=new Map;for(const[s,i]of e.entries())t.set(s,new Set(i));return t}persistScopedSettings(e,t,s,i){this.storage.withLock(e,n=>{const o=n?d.migrateSettings(JSON.parse(P(n))):{},l={...o};for(const g of s){const c=t[g];if(i.has(g)&&typeof c=="object"&&c!==null){const E=i.get(g),w=o[g]??{},x=c,b={...w};for(const k of E)b[k]=x[k];l[g]=b}else l[g]=c}return JSON.stringify(l,null,2)})}save(){if(this.settings=h(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;const e=structuredClone(this.globalSettings),t=new Set(this.modifiedFields),s=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",e,t,s)})}saveProjectSettings(e){if(this.assertProjectTrustedForWrite(),this.projectSettings=structuredClone(e),this.settings=h(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;const t=structuredClone(this.projectSettings),s=new Set(this.modifiedProjectFields),i=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",t,s,i)})}updateProjectSettings(e,t){this.assertProjectTrustedForWrite();const s=structuredClone(this.projectSettings);t(s),this.markProjectModified(e),this.saveProjectSettings(s)}async flush(){await this.writeQueue}drainErrors(){const e=[...this.errors];return this.errors=[],e}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getSessionDir(){const e=this.settings.sessionDir;return e&&v(e)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,t){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=t,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getThemeSetting(){const e=this.settings.theme;if(typeof e=="string")return e}getTheme(){const e=this.getThemeSetting();return e?.includes("/")?void 0:e}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(e,t){return this.settings.modelThinkingLevels?.[`${e}/${t}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(e,t,s){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${e}/${t}`]=s,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(e,t){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${e}/${t}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??"auto"}setTransport(e){this.globalSettings.transport=e,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionTokenSetting(e,t){const s=this.settings.compaction,i=s?.[e];if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<0))throw new Error(`Invalid compaction.${e} setting: ${String(i)}. Expected a non-negative safe integer.`);const n=t?`${t.provider}/${t.id}`:void 0,o=n!==void 0?s?.modelOverrides?.[n]:void 0;if(o!==void 0&&!p(o))throw new Error(`Invalid compaction.modelOverrides["${n}"] setting: ${String(o)}. Expected an object.`);const l=o?.[e];if(l!==void 0&&(typeof l!="number"||!Number.isSafeInteger(l)||l<0))throw new Error(`Invalid compaction.modelOverrides["${n}"].${e} setting: ${String(l)}. Expected a non-negative safe integer.`);return l??i??$[e]}getCompactionReserveTokens(e){return this.getCompactionTokenSetting("reserveTokens",e)}getCompactionKeepRecentTokens(e){return this.getCompactionTokenSetting("keepRecentTokens",e)}getCompactionSettings(e){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(e),keepRecentTokens:this.getCompactionKeepRecentTokens(e),maxContextTokens:this.getCompactionMaxContextTokens()}}getCompactionMaxContextTokens(){const e=this.settings.compaction?.maxContextTokens;if(e===void 0)return U;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid compaction.maxContextTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??H,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??L}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return B;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid maxOutputTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getOutputTokenLimit(e){const t=this.getMaxOutputTokens();return t>0&&(e<=0||e>t)?t:e}getHttpIdleTimeoutMs(){return C(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??W}setHttpIdleTimeoutMs(e){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(e),this.markModified("httpIdleTimeoutMs"),this.save()}getCacheWarmingMode(){const e=this.globalSettings.cacheWarming;return e!==void 0&&q.includes(e)?e:"streaming"}setCacheWarmingMode(e){this.globalSettings.cacheWarming=e,this.markModified("cacheWarming"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getWebSocketConnectTimeoutMs(){return C(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!0}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??!1}getExternalEditorCommand(){const e=this.settings.externalEditor;if(typeof e=="string"&&e.trim()!=="")return e;const t=process.env.VISUAL||process.env.EDITOR;return t||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(e){this.globalSettings.showCacheMissNotices=e,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){const e=this.settings.shellPath;return e&&v(e)}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){const e=this.settings.quietStartup;return e===!1?!1:e==="header"?e:!0}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getDefaultProjectTrust(){const e=this.globalSettings.defaultProjectTrust;return e==="always"||e==="never"?e:"ask"}setDefaultProjectTrust(e){this.globalSettings.defaultProjectTrust=e,this.markModified("defaultProjectTrust"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}getShellEnvironmentPolicy(){const e=this.globalSettings.shellEnvironment??{},t=[...e.exclude??[],...this.projectSettings.shellEnvironment?.exclude??[]];return{...e.inherit!==void 0?{inherit:e.inherit}:{},...t.length>0?{exclude:t}:{},...e.include!==void 0?{include:[...e.include]}:{},...e.set!==void 0?{set:{...e.set}}:{}}}getPermissionRuleSources(){return{...this.globalSettings.permissions?{user:structuredClone(this.globalSettings.permissions)}:{},...this.projectSettings.permissions?{project:structuredClone(this.projectSettings.permissions)}:{}}}getSandboxSettingsSources(){return{...this.globalSettings.sandbox?{global:structuredClone(this.globalSettings.sandbox)}:{},...this.projectSettings.sandbox?{project:structuredClone(this.projectSettings.sandbox)}:{}}}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(e){this.globalSettings.npmCommand=e?[...e]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!0}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??!0}setEnableInstallTelemetry(e){this.globalSettings.enableInstallTelemetry=e,this.markModified("enableInstallTelemetry"),this.save()}getEnableAnalytics(){return this.settings.enableAnalytics??!1}getTrackingId(){return this.settings.trackingId}setEnableAnalytics(e){this.globalSettings.enableAnalytics=e,this.markModified("enableAnalytics"),e&&!this.globalSettings.trackingId&&(this.globalSettings.trackingId=M(),this.markModified("trackingId")),this.save()}getOrCreateDeviceId(){return this.globalSettings.deviceId||(this.globalSettings.deviceId=M(),this.markModified("deviceId"),this.save()),this.globalSettings.deviceId}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){this.updateProjectSettings("packages",t=>{t.packages=e})}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){this.updateProjectSettings("extensions",t=>{t.extensions=e})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){this.updateProjectSettings("skills",t=>{t.skills=e})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){this.updateProjectSettings("prompts",t=>{t.prompts=e})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){this.updateProjectSettings("themes",t=>{t.themes=e})}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getFactoryEnabled(){return this.settings.factoryEnabled??!0}setFactoryEnabled(e){this.globalSettings.factoryEnabled=e,this.markModified("factoryEnabled"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){const e=this.settings.terminal,t=e?.images;return{...t==="kitty"||t==="iterm2"?{images:t}:t===!1?{images:null}:{},...typeof e?.trueColor=="boolean"?{trueColor:e.trueColor}:{},...typeof e?.hyperlinks=="boolean"?{hyperlinks:e.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){const e=this.settings.terminal?.imageWidthCells;return typeof e!="number"||!Number.isFinite(e)?60:Math.max(1,Math.floor(e))}setImageWidthCells(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(e)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:process.env.PI_CLEAR_ON_SHRINK==="1"}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=e,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":(this.settings.tuiMode==="regular"||this.settings.tuiMode,"regular")}setTuiMode(e){this.globalSettings.tuiMode=e,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":"transcript"}setFullscreenExitOutput(e){this.globalSettings.fullscreenExitOutput=e,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){const e=this.settings.fullscreenScrollbar;return e==="always"||e==="hidden"?e:"auto"}setFullscreenScrollbar(e){this.globalSettings.fullscreenScrollbar=e,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??!0}setFullscreenCopyOnSelect(e){this.globalSettings.fullscreenCopyOnSelect=e,this.markModified("fullscreenCopyOnSelect"),this.save()}getFullscreenWheelScrollLines(){const e=this.settings.fullscreenWheelScrollLines;return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.min(100,Math.floor(e))):"auto"}setFullscreenWheelScrollLines(e){this.globalSettings.fullscreenWheelScrollLines=e==="auto"?e:Math.max(1,Math.min(100,Math.floor(e))),this.markModified("fullscreenWheelScrollLines"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){const e=this.settings.defaultTools;if(e!==void 0)return Q(Array.isArray(e)?e.filter(t=>typeof t=="string"):[])}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){const e=this.settings.treeFilterMode;return e&&["default","no-tools","user-only","labeled-only","all"].includes(e)?e:"default"}setTreeFilterMode(e){this.globalSettings.treeFilterMode=e,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??process.env.PI_HARDWARE_CURSOR==="1"}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??1}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===1?1:0}setOutputPad(e){this.globalSettings.outputPad=e,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getMermaidRenderingMode(){const e=this.settings.markdown?.mermaid;return e==="off"||e==="final"?e:"streaming"}setMermaidRenderingMode(e){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=e,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(e){this.globalSettings.warnings={...e},this.markModified("warnings"),this.save()}}export{q as CACHE_WARMING_MODES,U as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,B as DEFAULT_MAX_OUTPUT_TOKENS,H as DEFAULT_MAX_RETRIES,V as DEFAULT_TOOL_NAMES,z as FileSettingsStorage,G as InMemorySettingsStorage,d as SettingsManager,X as applyToolModifiers,le as getToolListError,f as isToolModifier};
|
|
1
|
+
var F=Object.defineProperty;var a=(r,e)=>F(r,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as L}from"@earendil-works/pi-ai";import{randomUUID as M}from"crypto";import{existsSync as T,mkdirSync as I,readFileSync as O,writeFileSync as A}from"fs";import{dirname as D,join as u}from"path";import N from"proper-lockfile";import{CONFIG_DIR_NAME as y,getAgentDir as R}from"../config.js";import{normalizePath as v,resolvePath as m}from"../utils/paths.js";import{stripBom as P}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as W,parseHttpIdleTimeoutMs as $}from"./http-dispatcher.js";const _=8e4,U={reserveTokens:16384,keepRecentTokens:2e4,maxContextTokens:_},B=32e3,H=5,q=["off","streaming","idle"];function p(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}a(p,"isMergeableObject");function j(r,e){const t={...r};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const o=r[s];t[s]=p(o)&&p(i)?j(o,i):i}return t}a(j,"deepMergeObjects");const V=["read","bash","edit","write"];function f(r){return typeof r=="string"&&(r.startsWith("+")||r.startsWith("-"))}a(f,"isToolModifier");function le(r){const e=r.filter(f);if(e.length===0)return;if(e.length<r.length)return"tool names cannot be mixed with +name or -name entries";const t=e.find(s=>s.includes("*"));if(t)return`+name and -name entries take exact tool names, not patterns: ${t}`}a(le,"getToolListError");function X(r,e){const t=[...r];for(const s of e){if(!f(s))continue;const i=s.slice(1),o=t.indexOf(i);s.startsWith("+")&&o===-1&&i?t.push(i):s.startsWith("-")&&o!==-1&&t.splice(o,1)}return t}a(X,"applyToolModifiers");function K(r,e){return e===void 0?r:!Array.isArray(r)||!Array.isArray(e)||!e.every(f)?e:[...r,...e]}a(K,"mergeDefaultTools");function Q(r){const e=r.filter(t=>!f(t));return X(e.length>0||r.length===0?e:V,r)}a(Q,"resolveDefaultTools");function h(r,e){const t=j(r,e),s=K(r.defaultTools,e.defaultTools);return s===void 0?t:{...t,defaultTools:s}}a(h,"deepMergeSettings");function C(r,e){const t=$(r);if(t!==void 0)return t;if(r!==void 0)throw new Error(`Invalid ${e} setting: ${String(r)}`)}a(C,"parseTimeoutSetting");function S(r,e,t){return{scope:r,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}a(S,"toSettingsError");class z{static{a(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=m(e),i=m(t);this.globalSettingsPath=u(i,"settings.json"),this.projectSettingsPath=u(s,y,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let o=1;o<=10;o++)try{return N.lockSync(e,{realpath:!1})}catch(n){if((typeof n=="object"&&n!==null&&"code"in n?String(n.code):void 0)!=="ELOCKED"||o===10)throw n;i=n;const g=Date.now();for(;Date.now()-g<20;);}throw i??new Error("Failed to acquire settings lock")}withLock(e,t){const s=e==="global"?this.globalSettingsPath:this.projectSettingsPath,i=D(s);let o;try{const n=T(s);n&&(o=this.acquireLockSyncWithRetry(s));const l=n?O(s,"utf-8"):void 0,g=t(l);g!==void 0&&(T(i)||I(i,{recursive:!0}),o||(o=this.acquireLockSyncWithRetry(s)),A(s,g,"utf-8"))}finally{o&&o()}}}class G{static{a(this,"InMemorySettingsStorage")}global;project;withLock(e,t){const s=e==="global"?this.global:this.project,i=t(s);i!==void 0&&(e==="global"?this.global=i:this.project=i)}}class d{static{a(this,"SettingsManager")}storage;globalSettings;projectSettings;settings;projectTrusted;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(e,t,s,i=null,o=null,n=[],l=!0,g={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=l,this.globalSettingsLoadError=i,this.projectSettingsLoadError=o,this.errors=[...n],this.settingsPaths=g,this.settings=h(this.globalSettings,this.projectSettings)}static create(e,t=R(),s={}){const i=m(e),o=m(t),n=new z(i,o);return d.fromStorageWithPaths(n,s,{global:u(o,"settings.json"),project:u(i,y,"settings.json")})}static fromStorage(e,t={}){return d.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,o=d.tryLoadFromStorage(e,"global"),n=d.tryLoadFromStorage(e,"project",i),l=[];return o.error&&l.push(S("global",o.error,s.global)),n.error&&l.push(S("project",n.error,s.project)),new d(e,o.settings,n.settings,o.error,n.error,l,i,s)}static inMemory(e={},t={}){const s=new G,i=d.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),d.fromStorage(s,t)}static loadFromStorage(e,t,s=!0){if(t==="project"&&!s)return{};let i;if(e.withLock(t,n=>{i=n}),!i)return{};const o=JSON.parse(P(i));return d.migrateSettings(o)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:d.loadFromStorage(e,t,s),error:null}}catch(i){return{settings:{},error:i}}}static migrateSettings(e){if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),!("transport"in e)&&typeof e.websockets=="boolean"&&(e.transport=e.websockets?"websocket":"sse",delete e.websockets),"skills"in e&&typeof e.skills=="object"&&e.skills!==null&&!Array.isArray(e.skills)){const t=e.skills;t.enableSkillCommands!==void 0&&e.enableSkillCommands===void 0&&(e.enableSkillCommands=t.enableSkillCommands),Array.isArray(t.customDirectories)&&t.customDirectories.length>0?e.skills=t.customDirectories:delete e.skills}if("retry"in e&&typeof e.retry=="object"&&e.retry!==null&&!Array.isArray(e.retry)){const t=e.retry,s=typeof t.provider=="object"&&t.provider!==null?t.provider:void 0;typeof t.maxDelayMs=="number"&&(s?.maxRetryDelayMs===void 0||s?.maxRetryDelayMs===null)&&(t.provider={...s??{},maxRetryDelayMs:t.maxDelayMs}),delete t.maxDelayMs}return e}getSettings(){return structuredClone(this.settings)}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}isProjectTrusted(){return this.projectTrusted}setProjectTrusted(e){if(this.projectTrusted===e)return;if(this.projectTrusted=e,this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear(),!e){this.projectSettings={},this.projectSettingsLoadError=null,this.settings=h(this.globalSettings,this.projectSettings);return}const t=d.tryLoadFromStorage(this.storage,"project",e);this.projectSettings=t.settings,this.projectSettingsLoadError=t.error,t.error&&this.recordError("project",t.error),this.settings=h(this.globalSettings,this.projectSettings)}async reload(){await this.writeQueue;const e=d.tryLoadFromStorage(this.storage,"global");e.error?(this.globalSettingsLoadError=e.error,this.recordError("global",e.error)):(this.globalSettings=e.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();const t=d.tryLoadFromStorage(this.storage,"project",this.projectTrusted);t.error?(this.projectSettingsLoadError=t.error,this.recordError("project",t.error)):(this.projectSettings=t.settings,this.projectSettingsLoadError=null),this.settings=h(this.globalSettings,this.projectSettings)}applyOverrides(e){this.settings=h(this.settings,e)}markModified(e,t){this.modifiedFields.add(e),t&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(t))}markProjectModified(e,t){this.modifiedProjectFields.add(e),t&&(this.modifiedProjectNestedFields.has(e)||this.modifiedProjectNestedFields.set(e,new Set),this.modifiedProjectNestedFields.get(e).add(t))}assertProjectTrustedForWrite(){if(!this.projectTrusted)throw new Error("Project is not trusted; refusing to write project settings")}recordError(e,t){this.errors.push(S(e,t,this.settingsPaths[e]))}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,t){this.writeQueue=this.writeQueue.then(()=>{e==="project"&&this.assertProjectTrustedForWrite(),t(),this.clearModifiedScope(e)}).catch(s=>{this.recordError(e,s)})}cloneModifiedNestedFields(e){const t=new Map;for(const[s,i]of e.entries())t.set(s,new Set(i));return t}persistScopedSettings(e,t,s,i){this.storage.withLock(e,o=>{const n=o?d.migrateSettings(JSON.parse(P(o))):{},l={...n};for(const g of s){const c=t[g];if(i.has(g)&&typeof c=="object"&&c!==null){const E=i.get(g),w=n[g]??{},x=c,b={...w};for(const k of E)b[k]=x[k];l[g]=b}else l[g]=c}return JSON.stringify(l,null,2)})}save(){if(this.settings=h(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;const e=structuredClone(this.globalSettings),t=new Set(this.modifiedFields),s=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",e,t,s)})}saveProjectSettings(e){if(this.assertProjectTrustedForWrite(),this.projectSettings=structuredClone(e),this.settings=h(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;const t=structuredClone(this.projectSettings),s=new Set(this.modifiedProjectFields),i=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",t,s,i)})}updateProjectSettings(e,t){this.assertProjectTrustedForWrite();const s=structuredClone(this.projectSettings);t(s),this.markProjectModified(e),this.saveProjectSettings(s)}async flush(){await this.writeQueue}drainErrors(){const e=[...this.errors];return this.errors=[],e}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getSessionDir(){const e=this.settings.sessionDir;return e&&v(e)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,t){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=t,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getThemeSetting(){const e=this.settings.theme;if(typeof e=="string")return e}getTheme(){const e=this.getThemeSetting();return e?.includes("/")?void 0:e}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(e,t){return this.settings.modelThinkingLevels?.[`${e}/${t}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(e,t,s){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${e}/${t}`]=s,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(e,t){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${e}/${t}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??"auto"}setTransport(e){this.globalSettings.transport=e,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionTokenSetting(e,t){const s=this.settings.compaction,i=s?.[e];if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<0))throw new Error(`Invalid compaction.${e} setting: ${String(i)}. Expected a non-negative safe integer.`);const o=t?`${t.provider}/${t.id}`:void 0,n=o!==void 0?s?.modelOverrides?.[o]:void 0;if(n!==void 0&&!p(n))throw new Error(`Invalid compaction.modelOverrides["${o}"] setting: ${String(n)}. Expected an object.`);const l=n?.[e];if(l!==void 0&&(typeof l!="number"||!Number.isSafeInteger(l)||l<0))throw new Error(`Invalid compaction.modelOverrides["${o}"].${e} setting: ${String(l)}. Expected a non-negative safe integer.`);return l??i??U[e]}getCompactionReserveTokens(e){return this.getCompactionTokenSetting("reserveTokens",e)}getCompactionKeepRecentTokens(e){return this.getCompactionTokenSetting("keepRecentTokens",e)}getCompactionSettings(e){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(e),keepRecentTokens:this.getCompactionKeepRecentTokens(e),maxContextTokens:this.getCompactionMaxContextTokens(e),pruneToolOutputs:this.getCompactionPruneToolOutputs()}}getCompactionMaxContextTokens(e){return this.getCompactionTokenSetting("maxContextTokens",e)}getCompactionPruneToolOutputs(){const e=this.settings.compaction?.pruneToolOutputs;if(e!==void 0&&typeof e!="boolean")throw new Error(`Invalid compaction.pruneToolOutputs setting: ${String(e)}. Expected a boolean.`);return e??!0}getCompactionSummaryModel(){const e=this.settings.compaction?.summaryModel;if(e===void 0||e==="")return;const t=typeof e=="string"?e.indexOf("/"):-1;if(typeof e!="string"||t<=0||t===e.length-1)throw new Error(`Invalid compaction.summaryModel setting: ${String(e)}. Expected "provider/modelId".`);return{provider:e.slice(0,t),modelId:e.slice(t+1)}}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??H,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??L}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return B;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid maxOutputTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getOutputTokenLimit(e){const t=this.getMaxOutputTokens();return t>0&&(e<=0||e>t)?t:e}getHttpIdleTimeoutMs(){return C(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??W}setHttpIdleTimeoutMs(e){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(e),this.markModified("httpIdleTimeoutMs"),this.save()}getCacheWarmingMode(){const e=this.globalSettings.cacheWarming;return e!==void 0&&q.includes(e)?e:"streaming"}setCacheWarmingMode(e){this.globalSettings.cacheWarming=e,this.markModified("cacheWarming"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getWebSocketConnectTimeoutMs(){return C(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!0}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??!1}getExternalEditorCommand(){const e=this.settings.externalEditor;if(typeof e=="string"&&e.trim()!=="")return e;const t=process.env.VISUAL||process.env.EDITOR;return t||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(e){this.globalSettings.showCacheMissNotices=e,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){const e=this.settings.shellPath;return e&&v(e)}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){const e=this.settings.quietStartup;return e===!1?!1:e==="header"?e:!0}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getDefaultProjectTrust(){const e=this.globalSettings.defaultProjectTrust;return e==="always"||e==="never"?e:"ask"}setDefaultProjectTrust(e){this.globalSettings.defaultProjectTrust=e,this.markModified("defaultProjectTrust"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}getShellEnvironmentPolicy(){const e=this.globalSettings.shellEnvironment??{},t=[...e.exclude??[],...this.projectSettings.shellEnvironment?.exclude??[]];return{...e.inherit!==void 0?{inherit:e.inherit}:{},...t.length>0?{exclude:t}:{},...e.include!==void 0?{include:[...e.include]}:{},...e.set!==void 0?{set:{...e.set}}:{}}}getPermissionRuleSources(){return{...this.globalSettings.permissions?{user:structuredClone(this.globalSettings.permissions)}:{},...this.projectSettings.permissions?{project:structuredClone(this.projectSettings.permissions)}:{}}}getSandboxSettingsSources(){return{...this.globalSettings.sandbox?{global:structuredClone(this.globalSettings.sandbox)}:{},...this.projectSettings.sandbox?{project:structuredClone(this.projectSettings.sandbox)}:{}}}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(e){this.globalSettings.npmCommand=e?[...e]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!0}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??!0}setEnableInstallTelemetry(e){this.globalSettings.enableInstallTelemetry=e,this.markModified("enableInstallTelemetry"),this.save()}getEnableAnalytics(){return this.settings.enableAnalytics??!1}getTrackingId(){return this.settings.trackingId}setEnableAnalytics(e){this.globalSettings.enableAnalytics=e,this.markModified("enableAnalytics"),e&&!this.globalSettings.trackingId&&(this.globalSettings.trackingId=M(),this.markModified("trackingId")),this.save()}getOrCreateDeviceId(){return this.globalSettings.deviceId||(this.globalSettings.deviceId=M(),this.markModified("deviceId"),this.save()),this.globalSettings.deviceId}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){this.updateProjectSettings("packages",t=>{t.packages=e})}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){this.updateProjectSettings("extensions",t=>{t.extensions=e})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){this.updateProjectSettings("skills",t=>{t.skills=e})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){this.updateProjectSettings("prompts",t=>{t.prompts=e})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){this.updateProjectSettings("themes",t=>{t.themes=e})}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getFactoryEnabled(){return this.settings.factoryEnabled??!0}setFactoryEnabled(e){this.globalSettings.factoryEnabled=e,this.markModified("factoryEnabled"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){const e=this.settings.terminal,t=e?.images;return{...t==="kitty"||t==="iterm2"?{images:t}:t===!1?{images:null}:{},...typeof e?.trueColor=="boolean"?{trueColor:e.trueColor}:{},...typeof e?.hyperlinks=="boolean"?{hyperlinks:e.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){const e=this.settings.terminal?.imageWidthCells;return typeof e!="number"||!Number.isFinite(e)?60:Math.max(1,Math.floor(e))}setImageWidthCells(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(e)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:process.env.PI_CLEAR_ON_SHRINK==="1"}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=e,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":(this.settings.tuiMode==="regular"||this.settings.tuiMode,"regular")}setTuiMode(e){this.globalSettings.tuiMode=e,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":"transcript"}setFullscreenExitOutput(e){this.globalSettings.fullscreenExitOutput=e,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){const e=this.settings.fullscreenScrollbar;return e==="always"||e==="hidden"?e:"auto"}setFullscreenScrollbar(e){this.globalSettings.fullscreenScrollbar=e,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??!0}setFullscreenCopyOnSelect(e){this.globalSettings.fullscreenCopyOnSelect=e,this.markModified("fullscreenCopyOnSelect"),this.save()}getFullscreenWheelScrollLines(){const e=this.settings.fullscreenWheelScrollLines;return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.min(100,Math.floor(e))):"auto"}setFullscreenWheelScrollLines(e){this.globalSettings.fullscreenWheelScrollLines=e==="auto"?e:Math.max(1,Math.min(100,Math.floor(e))),this.markModified("fullscreenWheelScrollLines"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){const e=this.settings.defaultTools;if(e!==void 0)return Q(Array.isArray(e)?e.filter(t=>typeof t=="string"):[])}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){const e=this.settings.treeFilterMode;return e&&["default","no-tools","user-only","labeled-only","all"].includes(e)?e:"default"}setTreeFilterMode(e){this.globalSettings.treeFilterMode=e,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??process.env.PI_HARDWARE_CURSOR==="1"}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??1}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===1?1:0}setOutputPad(e){this.globalSettings.outputPad=e,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getMermaidRenderingMode(){const e=this.settings.markdown?.mermaid;return e==="off"||e==="final"?e:"streaming"}setMermaidRenderingMode(e){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=e,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(e){this.globalSettings.warnings={...e},this.markModified("warnings"),this.save()}}export{q as CACHE_WARMING_MODES,_ as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,B as DEFAULT_MAX_OUTPUT_TOKENS,H as DEFAULT_MAX_RETRIES,V as DEFAULT_TOOL_NAMES,z as FileSettingsStorage,G as InMemorySettingsStorage,d as SettingsManager,X as applyToolModifiers,le as getToolListError,f as isToolModifier};
|
|
@@ -7,6 +7,7 @@ export interface SourceInfo {
|
|
|
7
7
|
scope: SourceScope;
|
|
8
8
|
origin: SourceOrigin;
|
|
9
9
|
baseDir?: string;
|
|
10
|
+
packageName?: string;
|
|
10
11
|
}
|
|
11
12
|
export declare const BUILTIN_PATH_PREFIX = "builtin:";
|
|
12
13
|
export declare function getSyntheticPathSource(path: string): string | undefined;
|
package/dist/core/source-info.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var o=Object.defineProperty;var n=(e,r)=>o(e,"name",{value:r,configurable:!0});import{readFileSync as s}from"node:fs";import{join as u}from"node:path";const c="builtin:";function h(e){if(e.startsWith(c))return"builtin";if(e.startsWith("<")&&e.endsWith(">"))return e.slice(1,-1).split(":")[0]||"temporary"}n(h,"getSyntheticPathSource");function l(e){return e.startsWith(c)||e.startsWith("<")}n(l,"isSyntheticPath");const i=new Map;function a(e){if(!i.has(e)){let r;try{const t=JSON.parse(s(u(e,"package.json"),"utf8"));r=typeof t.name=="string"?t.name:void 0}catch{r=void 0}i.set(e,r)}return i.get(e)}n(a,"packageNameAt");function y(e,r){const t=r.packageRoot?a(r.packageRoot):void 0;return{path:e,source:r.source,scope:r.scope,origin:r.origin,baseDir:r.baseDir,...t?{packageName:t}:{}}}n(y,"createSourceInfo");function S(e,r){return{path:e,source:r.source,scope:r.scope??"temporary",origin:r.origin??"top-level",baseDir:r.baseDir}}n(S,"createSyntheticSourceInfo");export{c as BUILTIN_PATH_PREFIX,y as createSourceInfo,S as createSyntheticSourceInfo,h as getSyntheticPathSource,l as isSyntheticPath};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Message } from "@earendil-works/pi-ai";
|
|
1
2
|
import { type Skill } from "./skills.ts";
|
|
2
3
|
export interface BuildSystemPromptOptions {
|
|
3
4
|
customPrompt?: string;
|
|
@@ -33,6 +34,8 @@ export type NormalizedBuildSystemPromptOptions = BuildSystemPromptOptions & {
|
|
|
33
34
|
export type SystemPromptSections = Record<string, string>;
|
|
34
35
|
export declare function normalizeBuildSystemPromptOptions(input: BuildSystemPromptOptions): NormalizedBuildSystemPromptOptions;
|
|
35
36
|
export declare function buildSystemPromptSections(input: BuildSystemPromptOptions): SystemPromptSections;
|
|
37
|
+
export declare const SESSION_ENVIRONMENT_FIRST_SECTION = "cwd";
|
|
38
|
+
export declare function moveSessionEnvironmentOutOfSystemPrompt(messages: Message[]): Message[];
|
|
36
39
|
export declare function buildSystemPromptState(input: BuildSystemPromptOptions): {
|
|
37
40
|
content: string;
|
|
38
41
|
sections?: SystemPromptSections;
|
|
@@ -1,22 +1,28 @@
|
|
|
1
|
-
var x=Object.defineProperty;var l=(e,
|
|
2
|
-
${
|
|
1
|
+
var x=Object.defineProperty;var l=(e,t)=>x(e,"name",{value:t,configurable:!0});import{join as v}from"node:path";import{getSystemMessageText as E}from"@earendil-works/pi-ai";import{APP_NAME as $,APP_TITLE as h,getDalDocsPath as j,getDocsPath as O,getExamplesPath as T,getReadmePath as _,IS_WHITE_LABEL_BUILD as I}from"../config.js";import{formatSkillsForPrompt as N}from"./skills.js";const A=/^[a-z][a-z0-9_-]*$/;function D(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],hiddenTools:[...e.hiddenTools??[]],toolSnippets:{...e.toolSnippets??{}},toolGuidelines:Object.fromEntries(Object.entries(e.toolGuidelines??{}).map(([t,o])=>[t,[...o]])),promptGuidelines:[...e.promptGuidelines??[]],appendSystemPrompt:e.appendSystemPrompt??"",sections:{...e.sections??{}},cwd:e.cwd,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}l(D,"normalizeBuildSystemPromptOptions");function M(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:o})=>`<project_instructions path="${t}">
|
|
2
|
+
${o}
|
|
3
3
|
</project_instructions>`)].join(`
|
|
4
4
|
|
|
5
|
-
`)}l(
|
|
6
|
-
`)}l(
|
|
7
|
-
`):"(none)";
|
|
5
|
+
`)}l(M,"renderProjectContext");function R(e,t,o){const i=[],d=new Set,n=l(a=>{const m=a.trim();!m||d.has(m)||(d.add(m),i.push(m))},"addRule"),p=e.includes("bash"),f=e.includes("powershell"),r=e.includes("grep"),g=e.includes("find"),S=e.includes("ls");(p||f)&&!r&&!g&&!S&&n(p&&f?"Use bash or PowerShell for file operations like listing, searching, and finding files":f?"Use PowerShell for file operations like listing, searching, and finding files":"Use bash for file operations like ls, rg, find");for(const a of e)for(const m of t[a]??[])n(m);for(const a of o)n(a);return e.length>0&&(n("When several tool calls do not depend on each other's results (reading multiple files, independent searches or commands), make them all in one response; they run in parallel. Each extra round trip costs the user seconds"),n("Answer as soon as you can: once you know enough, give the answer or your best current conclusion, then offer to dig further. Do not investigate everything before saying anything"),n("During longer work, tell the user every few tool rounds, in a sentence or two, what you found and what you will check next"),n("If you cannot tell which product, project or file the user means, ask instead of searching widely on a guess. When the user writes while you are working, respond to that message first: it may change the direction")),n("Be concise in your responses"),n("Show file paths clearly when working with files"),i.map(a=>`- ${a}`).join(`
|
|
6
|
+
`)}l(R,"buildRules");function L(e){const t=D(e),{customPrompt:o,selectedTools:i,hiddenTools:d,toolSnippets:n,toolGuidelines:p,promptGuidelines:f,appendSystemPrompt:r,sections:g,cwd:S,contextFiles:a,skills:m}=t;for(const s of Object.keys(g))if(!A.test(s)||s==="preamble")throw new Error(`Invalid system prompt section name: ${s}`);const b=i.filter(s=>!d.includes(s)),c={};if(o)c.preamble=o;else{c.preamble=`You are an expert coding assistant operating inside ${h} (${$}). You help users by reading files, executing commands, editing code, and writing new files.`;const s=b.filter(y=>!!n[y]),u=s.length>0?s.map(y=>`- ${y}: ${n[y]}`).join(`
|
|
7
|
+
`):"(none)";c.tools=`${u}
|
|
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.`,c.rules=R(b,p,f),c.docs=W()}r&&(c.addendum=r),a.length>0&&(c.project_context=M(a));const k=["read","bash"],w=k.find(s=>b.includes(s))??(k.some(s=>i.includes(s))?"indirect":void 0);if(w&&m.length>0){const s=N(m,w).trim();s&&(c.skills=s)}c.cwd=S.replace(/\\/g,"/");for(const[s,u]of Object.entries(g))u&&(c[s]=u);const P={preamble:c.preamble};for(const[s,u]of Object.entries(c))s!=="preamble"&&(P[s]=`<${s}>
|
|
10
|
+
${u}
|
|
11
|
+
</${s}>`);return P}l(L,"buildSystemPromptSections");const F="cwd",G="Environment of this session, part of the system prompt. Later updates to these sections arrive as system prompt updates.";function V(e){const t=e[0];if(!t||t.role!=="system"||!t.sections)return e;const o=Object.keys(t.sections),i=o.indexOf(F);if(i===-1)return e;const d=o.slice(i).map(r=>t.sections?.[r]).filter(r=>typeof r=="string"&&r.length>0),n=Object.fromEntries(o.slice(0,i).map(r=>[r,t.sections?.[r]??null])),p={...t,sections:n};if(d.length===0)return[p,...e.slice(1)];const f={role:"user",content:[{type:"text",text:`<session_environment>
|
|
12
|
+
${G}
|
|
13
|
+
|
|
14
|
+
${d.join(`
|
|
15
|
+
|
|
16
|
+
`)}
|
|
17
|
+
</session_environment>`}],timestamp:t.timestamp};return[p,f,...e.slice(1)]}l(V,"moveSessionEnvironmentOutOfSystemPrompt");function U(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:L(e)}}l(U,"buildSystemPromptState");function H(e){return E({role:"system",...U(e),timestamp:0})}l(H,"buildSystemPrompt");function q(e,t){const o={};for(const[i,d]of Object.entries(t))e[i]!==d&&(o[i]=d);for(const i of Object.keys(e))t[i]===void 0&&(o[i]=null);return Object.keys(o).length>0?o:void 0}l(q,"diffSystemPromptSections");function W(){if(I){const e=j();return`${h} documentation (read only when the user asks about ${h} itself: its commands, settings, skills, prompt templates, extensions, packages, themes or keybindings):
|
|
18
|
+
- Start with: ${v(e,"README.md")}
|
|
13
19
|
- Topics, in the same folder: skills.md, prompt-templates.md, extensions.md, packages.md, themes.md, keybindings.md, settings.md
|
|
14
20
|
- Resolve those file names under ${e}, not the current working directory
|
|
15
|
-
- 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 ${h}`}return`${h} documentation (read only when the user asks about ${h} itself, its SDK, extensions, themes, skills, or TUI):
|
|
16
22
|
- Main documentation: ${_()}
|
|
17
|
-
- Additional docs: ${
|
|
18
|
-
- Examples: ${
|
|
23
|
+
- Additional docs: ${O()}
|
|
24
|
+
- Examples: ${T()} (extensions, custom tools, SDK)
|
|
19
25
|
- When reading these docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory
|
|
20
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)
|
|
21
27
|
- When working on these topics, read the docs and examples, and follow .md cross-references before implementing
|
|
22
|
-
- Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}l(
|
|
28
|
+
- Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}l(W,"buildDocumentationSection");export{F as SESSION_ENVIRONMENT_FIRST_SECTION,H as buildSystemPrompt,L as buildSystemPromptSections,U as buildSystemPromptState,q as diffSystemPromptSections,V as moveSessionEnvironmentOutOfSystemPrompt,D as normalizeBuildSystemPromptOptions};
|
|
@@ -17,7 +17,7 @@ export declare const sandboxEscalationSchema: Type.TOptional<Type.TObject<{
|
|
|
17
17
|
}>>;
|
|
18
18
|
export declare const bashToolSystemPromptContribution: {
|
|
19
19
|
readonly snippet: "Execute bash commands (ls, grep, find, etc.)";
|
|
20
|
-
readonly guidelines: readonly ["You can inspect
|
|
20
|
+
readonly guidelines: readonly ["You can inspect DAL_* environment variables for current model and session details."];
|
|
21
21
|
};
|
|
22
22
|
export type BashToolInput = Static<typeof bashSchema>;
|
|
23
23
|
declare const bashOutputSchema: Type.TObject<{
|