dal-code 1.0.33 → 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 +8 -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/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/tools/bash.js +18 -14
- package/dist/core/tools/output-accumulator.js +3 -3
- package/dist/core/tools/output-condense.js +3 -0
- package/dist/core/tools/powershell.js +1 -1
- package/dist/dal/manifest.js +1 -1
- 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-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 +2 -2
- 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/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};
|
|
@@ -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};
|
package/dist/core/tools/bash.js
CHANGED
|
@@ -1,21 +1,25 @@
|
|
|
1
|
-
var
|
|
2
|
-
Cannot execute ${t} commands.`)}const p=x.commandTransport==="stdin",r=
|
|
3
|
-
${
|
|
1
|
+
var he=Object.defineProperty;var u=(t,e)=>he(t,"name",{value:e,configurable:!0});import{constants as Se}from"node:fs";import{access as we}from"node:fs/promises";import{constants as be}from"node:os";import{ToolExecutionError as xe}from"@earendil-works/pi-agent-core";import{Container as Oe,Text as k,truncateToWidth as Ee}from"@earendil-works/pi-tui";import{spawn as _e}from"child_process";import{Type as m}from"typebox";import{fill as I,t as $}from"../../dal/i18n.js";import{keyHint as $e}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as ye}from"../../modes/interactive/components/visual-truncate.js";import{theme as w}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as Pe}from"../../utils/child-process.js";import{writeOutputFile as Le}from"../../utils/output-files.js";import{getShellConfig as ee,getShellEnv as te,killProcessTree as ne,trackDetachedChildPid as Te,untrackDetachedChildPid as Ce}from"../../utils/shell.js";import{describeDenialForModel as ge}from"../sandbox/denial.js";import{getProcessShellSandbox as ve}from"../sandbox/shell-sandbox.js";import{isReadOnlyBashCommand as Ie}from"./bash-read-only.js";import{OutputAccumulator as De}from"./output-accumulator.js";import{condenseShellOutput as Ae,outputCondenseDisabled as Fe}from"./output-condense.js";import{countOutputLines as Me,formatCollapsedSummary as Ne,getTextOutput as oe,invalidArgText as ke,str as ie,truncateDisplay as Re}from"./render-utils.js";import{wrapToolDefinition as Be}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as V,DEFAULT_MAX_LINES as Ue,formatSize as R}from"./truncate.js";const se=2147483647,Ge=1024*1024,je=se/1e3,re=12e4;function Ve(t){if(t===void 0)return re;if(!Number.isFinite(t)||t<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const e=t*1e3;if(e>se)throw new Error(`Invalid timeout: maximum is ${je} seconds`);return e}u(Ve,"resolveTimeoutMs");const ae=m.Object({command:m.String({description:"Shell command to execute"}),description:m.String({description:`One short line, in the user's language, saying what this command does and why \u2014 shown in place of the command itself. Describe the intent, not the syntax: "Find hardcoded key names", not "run grep with --exclude-dir". 3-10 words.`}),timeout:m.Optional(m.Number({description:"Timeout in seconds. Defaults to 120; raise it for genuinely long-running commands."}))}),We=m.Optional(m.Object({mode:m.Union([m.Literal("allow"),m.Literal("unsandboxed")],{description:'"allow": run sandboxed with the extra domains / writable paths below. "unsandboxed": run outside the sandbox entirely.'}),justification:m.String({description:"One sentence for the user saying why this access is needed. The user must approve it."}),allow_domains:m.Optional(m.Array(m.String(),{description:"Domains to allow, e.g. registry.npmjs.org"})),allow_write:m.Optional(m.Array(m.String(),{description:"Paths to make writable"}))},{description:"Only after the sandbox blocked this command: ask the user for the access it needs. Never use it pre-emptively."})),He=m.Object({...ae.properties,sandbox_escalation:We}),de={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect DAL_* environment variables for current model and session details."]},Xe=m.Object({output:m.String({description:"Combined stdout and stderr, possibly truncated"}),truncated:m.Boolean(),full_output_path:m.Optional(m.String({description:"Full output, when truncated"})),exit_code:m.Number(),wall_time_seconds:m.Number()});function Ke(t,e){return{exec:u(async(o,s,{onData:c,signal:a,timeout:O,env:h})=>{const l=Ve(O);if(a?.aborted)throw new Error("aborted");const x=e();try{await we(s,Se.F_OK)}catch{throw new Error(`Working directory does not exist: ${s}
|
|
2
|
+
Cannot execute ${t} commands.`)}const p=x.commandTransport==="stdin",r=_e(x.shell,p?x.args:[...x.args,o],{cwd:s,detached:process.platform!=="win32",env:h??te(),stdio:[p?"pipe":"ignore","pipe","pipe"],windowsHide:!0});p&&(r.stdin?.on("error",()=>{}),r.stdin?.end(o)),r.pid&&Te(r.pid);let S=!1,n;const i=u(()=>{r.pid&&ne(r.pid)},"onAbort");try{l!==void 0&&(n=setTimeout(()=>{S=!0,r.pid&&ne(r.pid)},l)),r.stdout?.on("data",c),r.stderr?.on("data",c),a&&(a.aborted?i():a.addEventListener("abort",i,{once:!0}));const f=await Pe(r);if(a?.aborted)throw new Error("aborted");if(S)throw new Error(`timeout:${(l??re)/1e3}`);const L=r.signalCode;return{exitCode:f??(L?128+(be.signals[L]??0):1)}}finally{r.pid&&Ce(r.pid),n&&clearTimeout(n),a&&a.removeEventListener("abort",i)}},"exec")}}u(Ke,"createLocalShellOperations");function Ye(t){return Ke("bash",()=>ee(t?.shellPath))}u(Ye,"createLocalBashOperations");const W=new Set;function It(t){return W.add(t),()=>{W.delete(t)}}u(It,"registerShellExecutionGuard");async function ze(t){for(const e of W){let o;try{o=await e(t)}catch(s){return`Command refused: the safety check could not run (${s instanceof Error?s.message:String(s)}).`}if(o!==void 0)return o}}u(ze,"shellExecutionRefusal");const qe=["SESSION_ID","SESSION_FILE","PROVIDER","MODEL","REASONING_LEVEL"];function Je(t,e,o,s,c){const a={...te()};if(delete a.PI_SESSION_ID,delete a.PI_SESSION_FILE,delete a.PI_PROVIDER,delete a.PI_MODEL,delete a.PI_REASONING_LEVEL,s&&c){const h=c.model;a.PI_SESSION_ID=c.sessionManager.getSessionId();const l=c.sessionManager.getSessionFile();l&&(a.PI_SESSION_FILE=l),h&&(a.PI_PROVIDER=h.provider,a.PI_MODEL=h.id),c.thinkingLevel&&(a.PI_REASONING_LEVEL=c.thinkingLevel)}for(const h of qe){delete a[`DAL_${h}`];const l=a[`PI_${h}`];l!==void 0&&(a[`DAL_${h}`]=l)}const O={command:t,cwd:e,env:a};return o?o(O):O}u(Je,"resolveSpawnContext");const Qe=5,Ze=100;class et extends Oe{static{u(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function tt(t){const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const o=Math.floor(e),s=Math.floor(o/60),c=o%60;return s<60?`${s}m ${c}s`:`${Math.floor(s/60)}h ${s%60}m ${c}s`}u(tt,"formatDuration");function nt(t,e,o=!1){const s=ie(t?.command),c=ie(t?.description)?.trim(),a=t?.timeout,O=a?w.fg("muted",I($(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:a})):"";if(c){const l=w.fg("toolTitle",w.bold(c))+O;return!o||!s?l:`${l}
|
|
3
|
+
${w.fg("muted",` \u23BF ${e} ${s.trim()}`)}`}const h=s===null?ke(w):s?w.fg("dim",Re(s.replace(/\s+/g," ").trim(),42)):w.fg("dim","\u2026");return`${w.fg("toolTitle",w.bold(e))} ${h}${O}`}u(nt,"formatShellCall");function ot(t,e,o,s,c,a,O,h){const l=t.state;t.clear();const x=it(o,c,a,h);if(!o.expanded&&!O){const n=oe(e,s),i=Me(n),f=[];i>0&&f.push(I($("{count} \u884C"),{count:i})),x&&f.push(x);const L=Ne(w,f);L&&t.addChild(new k(L,0,0));return}let p=oe(e,s).trim();const r=e.details?.truncation,S=e.details?.fullOutputPath;if(!o.isPartial&&r?.truncated&&S&&p.endsWith("]")){const n=p.lastIndexOf(`
|
|
4
4
|
|
|
5
5
|
[`);n!==-1&&p.slice(n).includes(S)&&(p=p.slice(0,n).trimEnd())}if(p){const n=p.split(`
|
|
6
|
-
`).map(i=>
|
|
7
|
-
`);o.expanded?t.addChild(new
|
|
8
|
-
${n}`,0,0)):t.addChild({render:u(i=>{if(l.cachedLines===void 0||l.cachedWidth!==i){const f=
|
|
9
|
-
${
|
|
10
|
-
${
|
|
11
|
-
${f}`:f,
|
|
6
|
+
`).map(i=>w.fg("toolOutput",i)).join(`
|
|
7
|
+
`);o.expanded?t.addChild(new k(`
|
|
8
|
+
${n}`,0,0)):t.addChild({render:u(i=>{if(l.cachedLines===void 0||l.cachedWidth!==i){const f=ye(n,Qe,i);l.cachedLines=f.visualLines,l.cachedSkipped=f.skippedCount,l.cachedWidth=i}if(l.cachedSkipped&&l.cachedSkipped>0){const f=w.fg("muted",I($("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:l.cachedSkipped}))+` ${$e("app.tools.expand",$("\u5373\u53EF\u5C55\u5F00"))}${w.fg("muted",")")}`;return["",Ee(f,i,"..."),...l.cachedLines??[]]}return["",...l.cachedLines??[]]},"render"),invalidate:u(()=>{l.cachedWidth=void 0,l.cachedLines=void 0,l.cachedSkipped=void 0},"invalidate")})}if(r?.truncated||S){const n=[];S&&n.push(I($("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:S})),r?.truncated&&(r.truncatedBy==="lines"?n.push(I($("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:r.outputLines,total:r.totalLines})):n.push(I($("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:r.outputLines,limit:R(r.maxBytes??V)}))),t.addChild(new k(`
|
|
9
|
+
${w.fg("warning",`[${n.join(". ")}]`)}`,0,0))}x&&t.addChild(new k(`
|
|
10
|
+
${w.fg("muted",x)}`,0,0))}u(ot,"rebuildBashResultRenderComponent");function it(t,e,o,s){let c;if(!t.isPartial&&s!==void 0)c=s;else if(e!==void 0)c=(o??Date.now())-e;else return;if(!(!t.isPartial&&c<100))return`${t.isPartial?$("\u5DF2\u8FD0\u884C"):$("\u8017\u65F6")} ${tt(c)}`}u(it,"bashTimingLabel");function st(t,e,o){const s=o?.operations??e.defaultOperations?.()??Ye({shellPath:o?.shellPath}),c=o?.commandPrefix,a=o?.exposeSessionEnvironment??!0,O=o?.spawnHook,h=o?.sandbox,l=o?.operations===void 0,x=h?.describeForModel();return{name:e.name,label:e.label,description:`Execute a ${e.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${Ue} lines or ${V/1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.${x?` ${x}`:""}`,promptSnippet:e.promptSnippet,promptGuidelines:a&&e.promptGuidelines?[...e.promptGuidelines]:void 0,executionMode:"sequential",executionModeFor:e.readOnlyCommand&&!c?p=>e.readOnlyCommand?.(p?.command)?"parallel":void 0:void 0,parameters:h?.active?He:ae,outputSchema:Xe,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(p,r,S,n,i){const{command:f,timeout:L}=r;n&&n({content:[],details:void 0});const H=await ze({toolName:e.name,command:f,cwd:i?.cwd||t,sessionFile:i?.sessionManager?.getSessionFile()});if(H!==void 0)throw new Error(H);const le=c?`${c}
|
|
11
|
+
${f}`:f,g=Je(le,i?.cwd||t,O,a,i),B=h??(l?ve():void 0);let y;if(B?.active){if(!e.sandboxShell)throw new Error(`Command refused: ${e.shellName} commands cannot run inside the OS sandbox yet, and the sandbox level is "${B.level}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);y=await B.prepare({command:g.command,cwd:g.cwd,shell:e.sandboxShell(o?.shellPath),shellKind:e.sandboxShellKind??"bash",env:g.env,toolCallId:p,toolName:e.name,escalation:r.sandbox_escalation,ctx:i,signal:S})}const T=new De({tempFilePrefix:e.tempFilePrefix});let X=!0,D,U=!1,K=0;const G=u(()=>{if(!n||!U)return;U=!1,K=Date.now();const d=T.snapshot({persistIfTruncated:!0});n({content:[{type:"text",text:d.content||""}],details:{truncation:d.truncation.truncated?d.truncation:void 0,fullOutputPath:d.fullOutputPath}})},"emitOutputUpdate"),j=u(()=>{D&&(clearTimeout(D),D=void 0)},"clearUpdateTimer"),ue=u(()=>{if(!n)return;U=!0;const d=Ze-(Date.now()-K);if(d<=0){j(),G();return}D??=setTimeout(()=>{D=void 0,G()},d)},"scheduleOutputUpdate"),ce=u(d=>{X&&(T.append(d),ue())},"handleData"),Y=u(async()=>{X=!1,T.finish(),j(),G();const d=T.snapshot({persistIfTruncated:!0});return await T.closeTempFile(),d},"finishOutput"),z=u((d,E="(no output)",P)=>{const b=d.truncation;let _=P?.text||d.content||E;P&&(_+=b.truncated?`
|
|
12
12
|
|
|
13
|
-
[
|
|
13
|
+
[Condensed: ${P.summary}.]`:`
|
|
14
14
|
|
|
15
|
-
[
|
|
15
|
+
[Condensed: ${P.summary}. Full output: ${P.fullOutputPath}]`);let v;if(b.truncated){v={truncation:b,fullOutputPath:d.fullOutputPath};const F=b.totalLines-b.outputLines+1,M=b.totalLines;if(b.lastLinePartial){const N=R(T.getLastLineBytes());_+=`
|
|
16
16
|
|
|
17
|
-
[Showing
|
|
17
|
+
[Showing last ${R(b.outputBytes)} of line ${M} (line is ${N}). Full output: ${d.fullOutputPath}]`}else b.truncatedBy==="lines"?_+=`
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
[Showing lines ${F}-${M} of ${b.totalLines}. Full output: ${d.fullOutputPath}]`:_+=`
|
|
20
20
|
|
|
21
|
-
${
|
|
21
|
+
[Showing lines ${F}-${M} of ${b.totalLines} (${R(V)} limit). Full output: ${d.fullOutputPath}]`}return{text:_,details:v}},"formatOutput"),A=u((d,E)=>`${d?`${d}
|
|
22
|
+
|
|
23
|
+
`:""}${E}`,"appendStatus"),me=performance.now();try{let d;try{d=(await s.exec(y?.command??g.command,g.cwd,{onData:ce,signal:S,timeout:L,env:g.env})).exitCode}catch(C){const pe=await Y(),{text:Z}=z(pe,"");if(await y?.finish(null,""),C instanceof Error&&C.message==="aborted")throw new Error(A(Z,"Command aborted"));if(C instanceof Error&&C.message.startsWith("timeout:")){const fe=C.message.split(":")[1];throw new Error(A(Z,`Command timed out after ${fe} seconds`))}throw C}const E=await Y(),P=Fe()?void 0:Ae(E.content),b=P&&{...P,fullOutputPath:E.fullOutputPath??await Le(e.tempFilePrefix,".log",E.content)},{text:_,details:v}=z(E,void 0,b),F=await y?.finish(d,E.content||"");if(F&&y)throw new xe(`${A(_,`Command exited with code ${d??"(none)"}`)}
|
|
24
|
+
|
|
25
|
+
${ge(F)}`,{...v,sandbox:y.details});if(d===null)throw new Error(A(_,"Command terminated without an exit code"));const M=Math.round((performance.now()-me)/100)/10,N=await T.readFullOutput(Ge),q={output:N.content,truncated:N.truncated,...N.truncated&&E.fullOutputPath?{full_output_path:E.fullOutputPath}:{},exit_code:d,wall_time_seconds:M},J=y?.details.escalation?y.details:void 0,Q=J?{...v,sandbox:J}:v;return d!==0?{content:[{type:"text",text:A(_,`Command exited with code ${d}`)}],details:Q,structuredContent:q,isError:!0}:{content:[{type:"text",text:_}],details:Q,structuredContent:q}}finally{j()}},renderCall(p,r,S){const n=S.state;S.executionStarted&&n.startedAt===void 0&&(n.startedAt=Date.now(),n.endedAt=void 0);const i=S.lastComponent??new k("",0,0);return i.setText(nt(p,e.prompt,S.expanded===!0)),i},renderResult(p,r,S,n){const i=n.state;i.startedAt!==void 0&&r.isPartial&&!i.interval&&(i.interval=setInterval(()=>n.invalidate(),1e3)),(!r.isPartial||n.isError)&&(i.endedAt??=Date.now(),i.interval&&(clearInterval(i.interval),i.interval=void 0));const f=n.lastComponent??new et;return ot(f,p,r,n.showImages,i.startedAt,i.endedAt,n.isError,n.durationMs),f.invalidate(),f}}}u(st,"createShellToolDefinition");const rt={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:de.snippet,promptGuidelines:de.guidelines,tempFilePrefix:"dal-bash",readOnlyCommand:Ie,sandboxShell:u(t=>ee(t).shell,"sandboxShell")};function at(t,e){return st(t,rt,e)}u(at,"createBashToolDefinition");function Dt(t,e){const o=at(t,e),s=Be(o);return Object.assign(s,{promptSnippet:o.promptSnippet,promptGuidelines:o.promptGuidelines}),s}u(Dt,"createBashTool");export{de as bashToolSystemPromptContribution,Dt as createBashTool,at as createBashToolDefinition,Ye as createLocalBashOperations,Ke as createLocalShellOperations,st as createShellToolDefinition,It as registerShellExecutionGuard,We as sandboxEscalationSchema};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var f=Object.defineProperty;var a=(r,t)=>f(r,"name",{value:t,configurable:!0});import{open as p}from"node:fs/promises";import{createOutputFileStream as x}from"../../utils/output-files.js";import{DEFAULT_MAX_BYTES as y,DEFAULT_MAX_LINES as B,truncateTail as L}from"./truncate.js";function c(r){return Buffer.byteLength(r,"utf-8")}a(c,"byteLength");class S{static{a(this,"OutputAccumulator")}maxLines;maxBytes;maxRollingBytes;tempFilePrefix;decoder=new TextDecoder;rawChunks=[];tailText="";tailBytes=0;tailStartsAtLineBoundary=!0;totalRawBytes=0;totalDecodedBytes=0;completedLines=0;totalLines=0;currentLineBytes=0;hasOpenLine=!1;finished=!1;tempFilePath;tempFileStream;constructor(t={}){this.maxLines=t.maxLines??B,this.maxBytes=t.maxBytes??y,this.maxRollingBytes=Math.max(this.maxBytes*2,1),this.tempFilePrefix=t.tempFilePrefix??"
|
|
1
|
+
var f=Object.defineProperty;var a=(r,t)=>f(r,"name",{value:t,configurable:!0});import{open as p}from"node:fs/promises";import{createOutputFileStream as x}from"../../utils/output-files.js";import{DEFAULT_MAX_BYTES as y,DEFAULT_MAX_LINES as B,truncateTail as L}from"./truncate.js";function c(r){return Buffer.byteLength(r,"utf-8")}a(c,"byteLength");class S{static{a(this,"OutputAccumulator")}maxLines;maxBytes;maxRollingBytes;tempFilePrefix;decoder=new TextDecoder;rawChunks=[];tailText="";tailBytes=0;tailStartsAtLineBoundary=!0;totalRawBytes=0;totalDecodedBytes=0;completedLines=0;totalLines=0;currentLineBytes=0;hasOpenLine=!1;finished=!1;tempFilePath;tempFileStream;constructor(t={}){this.maxLines=t.maxLines??B,this.maxBytes=t.maxBytes??y,this.maxRollingBytes=Math.max(this.maxBytes*2,1),this.tempFilePrefix=t.tempFilePrefix??"dal-output"}append(t){if(this.finished)throw new Error("Cannot append to a finished output accumulator");this.totalRawBytes+=t.length,this.appendDecodedText(this.decoder.decode(t,{stream:!0})),this.tempFileStream||this.shouldUseTempFile()?(this.ensureTempFile(),this.tempFileStream?.write(t)):t.length>0&&this.rawChunks.push(t)}finish(){this.finished||(this.finished=!0,this.appendDecodedText(this.decoder.decode()),this.shouldUseTempFile()&&this.ensureTempFile())}snapshot(t={}){const e=L(this.getSnapshotText(),{maxLines:this.maxLines,maxBytes:this.maxBytes}),s=this.totalLines>this.maxLines||this.totalDecodedBytes>this.maxBytes,n=s?e.truncatedBy??(this.totalDecodedBytes>this.maxBytes?"bytes":"lines"):null,i={...e,truncated:s,truncatedBy:n,totalLines:this.totalLines,totalBytes:this.totalDecodedBytes,maxLines:this.maxLines,maxBytes:this.maxBytes};return t.persistIfTruncated&&i.truncated&&this.ensureTempFile(),{content:i.content,truncation:i,fullOutputPath:this.tempFilePath}}async closeTempFile(){if(!this.tempFileStream)return;const t=this.tempFileStream;this.tempFileStream=void 0,await new Promise((e,s)=>{const n=a(l=>{t.off("finish",i),s(l)},"onError"),i=a(()=>{t.off("error",n),e()},"onFinish");t.once("error",n),t.once("finish",i),t.end()})}async readFullOutput(t){if(!this.tempFilePath)return{content:new TextDecoder().decode(Buffer.concat(this.rawChunks)),truncated:!1};const e=await p(this.tempFilePath,"r");try{const s=(await e.stat()).size;if(s<=t)return{content:new TextDecoder().decode(await e.readFile()),truncated:!1};const n=Math.floor(t/2),i=t-n,l=Buffer.alloc(n),h=Buffer.alloc(i);await e.read(l,0,n,0),await e.read(h,0,i,s-i);const u=new TextDecoder().decode(l,{stream:!0});let o=0;for(;o<h.length&&(h[o]&192)===128;)o++;const d=new TextDecoder().decode(h.subarray(o)),m=s-n-i;return{content:`${u}
|
|
2
2
|
|
|
3
|
-
[... ${
|
|
3
|
+
[... ${m} bytes omitted ...]
|
|
4
4
|
|
|
5
|
-
${
|
|
5
|
+
${d}`,truncated:!0}}finally{await e.close()}}getLastLineBytes(){return this.currentLineBytes}appendDecodedText(t){if(t.length===0)return;const e=c(t);this.totalDecodedBytes+=e,this.tailText+=t,this.tailBytes+=e,this.tailBytes>this.maxRollingBytes*2&&this.trimTail();let s=0,n=-1;for(let i=t.indexOf(`
|
|
6
6
|
`);i!==-1;i=t.indexOf(`
|
|
7
7
|
`,i+1))s++,n=i;if(s===0)this.currentLineBytes+=e,this.hasOpenLine=!0;else{this.completedLines+=s;const i=t.slice(n+1);this.currentLineBytes=c(i),this.hasOpenLine=i.length>0}this.totalLines=this.completedLines+(this.hasOpenLine?1:0)}trimTail(){const t=Buffer.from(this.tailText,"utf-8");if(t.length<=this.maxRollingBytes){this.tailBytes=t.length;return}let e=t.length-this.maxRollingBytes;for(;e<t.length&&(t[e]&192)===128;)e++;this.tailStartsAtLineBoundary=e===0?this.tailStartsAtLineBoundary:t[e-1]===10,this.tailText=t.subarray(e).toString("utf-8"),this.tailBytes=c(this.tailText)}getSnapshotText(){if(this.tailStartsAtLineBoundary)return this.tailText;const t=this.tailText.indexOf(`
|
|
8
8
|
`);return t===-1?this.tailText:this.tailText.slice(t+1)}shouldUseTempFile(){return this.totalRawBytes>this.maxBytes||this.totalDecodedBytes>this.maxBytes||this.totalLines>this.maxLines}ensureTempFile(){if(this.tempFilePath)return;const{path:t,stream:e}=x(this.tempFilePrefix,".log");this.tempFilePath=t,this.tempFileStream=e;for(const s of this.rawChunks)this.tempFileStream.write(s);this.rawChunks=[]}}export{S as OutputAccumulator};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var I=Object.defineProperty;var d=(o,t)=>I(o,"name",{value:t,configurable:!0});const g=/\b(?:error|errors|fail|failed|failure|failing|fatal|panic|exception|traceback|assert(?:ion)?|denied|segfault)\b|✗|✘|×/i,E=[/^\s*[✓✔√]\s+\S/,/^\s*PASS\s+\S/,/^\s*ok \d+ - /,/\sPASSED(?:\s+\[\s*\d+%\])?\s*$/,/^\s*--- PASS: /,/^=== (?:RUN|PAUSE|CONT|NAME)\s/,/^test \S.* \.\.\. ok$/],m=/\bwarn(?:ing)?s?\b/i,M=10,O=8,R=.15;function D(o){const t=o.split(`
|
|
2
|
+
`).map(e=>{const n=e.lastIndexOf("\r",e.length-2);return n===-1?e:e.slice(n+1)}),N=t.filter(e=>E.some(n=>n.test(e))).length>=10,s=[],f=new Set;let r=0,a=-1,l=0,c=0,i=0;for(const e of t){const n=g.test(e);if(N&&!n&&E.some(u=>u.test(e))){r++,a===-1&&(a=s.length,s.push(""));continue}const h=s.length>0?s[s.length-1]:void 0;if(!n&&e.trim()!==""&&e===h){i++,c++;continue}if(i>0&&(s.push(`[previous line repeated ${i} more times]`),i=0),!n&&m.test(e)){const u=e.trim();if(f.has(u)){l++;continue}f.add(u)}s.push(e)}i>0&&s.push(`[previous line repeated ${i} more times]`),a!==-1&&(s[a]=`[${r} passing test lines collapsed]`);const _=r+l+c,S=s.join(`
|
|
3
|
+
`);if(_<8||S.length>o.length*(1-.15))return;const p=[];return r>0&&p.push(`${r} passing test lines collapsed`),l>0&&p.push(`${l} duplicate warning lines removed`),c>0&&p.push(`${c} repeated lines collapsed`),{text:S,summary:p.join(", ")}}d(D,"condenseShellOutput");function P(o=process.env){const t=o.DAL_TOOL_OUTPUT_CONDENSE?.trim().toLowerCase();return t==="0"||t==="off"||t==="false"}d(P,"outputCondenseDisabled");export{D as condenseShellOutput,P as outputCondenseDisabled};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var p=Object.defineProperty;var t=(e,o)=>p(e,"name",{value:o,configurable:!0});import{getPowerShellConfig as r}from"../../utils/shell.js";import{createLocalShellOperations as s,createShellToolDefinition as c}from"./bash.js";import{wrapToolDefinition as a}from"./tool-definition-wrapper.js";const m=`try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}
|
|
2
|
-
`,i={snippet:"Execute PowerShell commands",guidelines:["You can inspect DAL_* environment variables for current model and session details."]};function h(){const e=s("PowerShell",r);return{exec:t((o,n
|
|
2
|
+
`,i={snippet:"Execute PowerShell commands",guidelines:["You can inspect DAL_* environment variables for current model and session details."]};function h(){const e=s("PowerShell",r);return{exec:t((o,l,n)=>e.exec(`${m}${o}`,l,n),"exec")}}t(h,"createLocalPowerShellOperations");const u={name:"powershell",label:"powershell",shellName:"PowerShell",prompt:"PS>",promptSnippet:i.snippet,promptGuidelines:i.guidelines,tempFilePrefix:"dal-powershell",defaultOperations:h,sandboxShell:t(()=>process.platform==="win32"?r().shell:"pwsh","sandboxShell"),sandboxShellKind:"powershell"};function d(e,o){return c(e,u,o)}t(d,"createPowerShellToolDefinition");function x(e,o){const l=d(e,o),n=a(l);return Object.assign(n,{promptSnippet:l.promptSnippet,promptGuidelines:l.promptGuidelines}),n}t(x,"createPowerShellTool");export{h as createLocalPowerShellOperations,x as createPowerShellTool,d as createPowerShellToolDefinition,i as powershellToolSystemPromptContribution};
|