dal-code 1.0.33 → 1.0.35
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 +18 -0
- package/NOTICE +8 -0
- package/dist/core/agent-session.d.ts +5 -0
- package/dist/core/agent-session.js +8 -8
- package/dist/core/background-processes.d.ts +14 -1
- package/dist/core/background-processes.js +7 -6
- 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/git-state.js +1 -0
- package/dist/core/model-config.d.ts +30 -0
- package/dist/core/model-config.js +2 -2
- package/dist/core/sandbox/denial.d.ts +1 -0
- package/dist/core/sandbox/denial.js +4 -3
- package/dist/core/sandbox/shell-sandbox.js +5 -5
- package/dist/core/settings-manager.d.ts +11 -2
- package/dist/core/settings-manager.js +1 -1
- package/dist/core/source-info.d.ts +1 -0
- package/dist/core/source-info.js +1 -1
- package/dist/core/system-prompt.d.ts +1 -0
- package/dist/core/system-prompt.js +12 -12
- package/dist/core/tools/bash.d.ts +7 -0
- package/dist/core/tools/bash.js +14 -16
- package/dist/core/tools/output-accumulator.js +2 -2
- package/dist/core/tools/output-condense.js +3 -0
- package/dist/core/tools/powershell.js +1 -1
- package/dist/core/tools/process.d.ts +3 -4
- package/dist/core/tools/process.js +15 -15
- package/dist/core/tools/truncate.d.ts +12 -0
- package/dist/core/tools/truncate.js +12 -5
- 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-gateway/src/index.js +1 -1
- 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-mcp/src/index.js +18 -18
- 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-skills/src/catalog.js +2 -2
- package/dist/node_modules/@dalcode/dal-skills/src/index.js +10 -10
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-subagent/src/index.js +14 -16
- 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-tool-catalog/src/groups.js +1 -1
- package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -5
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
- package/dist/node_modules/@dalcode/deepailab/src/model-defaults.js +1 -1
- 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/api/openai-completions.d.ts +2 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +5 -5
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/types.d.ts +1 -0
- 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/dist/utils/output-files.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
package/dist/core/bug-report.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var R=Object.defineProperty;var o=(e,t)=>R(e,"name",{value:t,configurable:!0});import*as g from"node:os";import{contentText as T,normalizeContext as x,uuidv7 as E}from"@earendil-works/pi-ai";import{APP_TITLE as h,VERSION as f}from"../config.js";import{getPiUserAgent as I}from"../utils/pi-user-agent.js";import{writeZipArchive as _}from"../utils/zip.js";import{completeSummarization as O,
|
|
1
|
+
var R=Object.defineProperty;var o=(e,t)=>R(e,"name",{value:t,configurable:!0});import*as g from"node:os";import{contentText as T,normalizeContext as x,uuidv7 as E}from"@earendil-works/pi-ai";import{APP_TITLE as h,VERSION as f}from"../config.js";import{getPiUserAgent as I}from"../utils/pi-user-agent.js";import{writeZipArchive as _}from"../utils/zip.js";import{completeSummarization as O,getSummarizationFailure as b}from"./compaction/compaction.js";import{estimateTokens as k,serializeConversation as M}from"./compaction/utils.js";import{convertToLlm as N}from"./messages.js";const H="pi.bug-report",y=1,v="<redacted>",P=/(?:^|[-_])(api[-_]?key|secret|token|password|passwd|credential|authorization|cookie)(?:$|[-_])/i;function w(e){return P.test(e.replace(/([a-z0-9])([A-Z])/g,"$1_$2"))}o(w,"isSensitiveKey");function u(e){const t=/^([a-z][a-z0-9+.-]*:)([a-z][a-z0-9+.-]*:\/\/.*)$/i.exec(e);if(t)return`${t[1]}${u(t[2])}`;try{const n=new URL(e);let s=!1;(n.username||n.password)&&(n.username="",n.password="",s=!0);for(const a of n.searchParams.keys())w(a)&&(n.searchParams.set(a,v),s=!0);return s?n.toString():e}catch{return e}}o(u,"redactUrl");function m(e){if(e!==void 0)return JSON.parse(JSON.stringify(e,(t,n)=>n!=null&&w(t)?v:typeof n=="string"?u(n):n))}o(m,"redactJsonValue");function S(e){const{trackingId:t,deviceId:n,...s}=e;return m(s)}o(S,"redactSettings");function U(){const e=o(t=>process.env[t]||null,"env");return{version:f,userAgent:I(f),runtime:process.versions.bun?`bun/${process.versions.bun}`:`node/${process.version}`,platform:process.platform,arch:process.arch,osRelease:g.release(),osVersion:g.version(),shell:process.env.SHELL?.split(/[\\/]/).pop()||null,terminal:{term:e("TERM"),program:e("TERM_PROGRAM"),programVersion:e("TERM_PROGRAM_VERSION"),colorterm:e("COLORTERM"),tmux:!!process.env.TMUX,ssh:!!(process.env.SSH_CONNECTION||process.env.SSH_CLIENT||process.env.SSH_TTY),ci:!!process.env.CI},piEnvironmentVariables:Object.keys(process.env).filter(t=>t.startsWith("PI_")).sort()}}o(U,"collectEnvironment");function $(e){return{provider:e.provider,id:e.id,name:e.name,api:e.api,baseUrl:u(e.baseUrl),reasoning:e.reasoning,input:e.input,contextWindow:e.contextWindow,maxTokens:e.maxTokens,samplingParams:e.samplingParams?m(e.samplingParams):null,compat:e.compat?m(e.compat):null,thinkingLevelMap:e.thinkingLevelMap??null,headerNames:Object.keys(e.headers??{}).sort()}}o($,"describeModel");function A(e,t){const n=[];return t.auth.apiKey&&n.push("api_key"),t.auth.oauth&&n.push("oauth"),{id:t.id,name:t.name,baseUrl:t.baseUrl?u(t.baseUrl):null,headerNames:Object.keys(t.headers??{}).sort(),authTypes:n,authStatus:e.getProviderAuthStatus(t.id),usingOAuth:e.isUsingOAuth(t.id),registeredByExtension:e.getRegisteredProviderIds().includes(t.id)}}o(A,"describeProvider");function C(e){return{path:e.path,source:u(e.sourceInfo.source),scope:e.sourceInfo.scope,origin:e.sourceInfo.origin,hidden:e.hidden===!0}}o(C,"describeExtension");function q(e){const t=e.hint?.trim()||null,n=e.model?e.modelRuntime.getProvider(e.model.provider):void 0;return{schemaVersion:y,id:e.id??E(),createdAt:new Date().toISOString(),hint:t,environment:U(),session:{id:e.sessionId,included:e.includeSession,summaryIncluded:e.includeSummary,messageCount:e.messageCount,...e.includeSession?{cwd:e.cwd}:{}},model:e.model?$(e.model):null,provider:n?A(e.modelRuntime,n):null,thinkingLevel:e.thinkingLevel,extensions:e.extensions.map(C),extensionErrors:e.extensionErrors.map(({path:s,error:a})=>({path:s,error:a})),settings:{global:S(e.globalSettings),project:S(e.projectSettings)}}}o(q,"collectBugReportMetadata");function Z(e,t=[]){const n=e.getEntries(),s=[];let a=0;for(const i of n){if(i.type!=="message"||i.message.role!=="assistant")continue;a++;const r=i.message,c=r.diagnostics??[];c.length===0&&r.stopReason!=="error"&&r.stopReason!=="aborted"&&!r.errorMessage||s.push({entryId:i.id,timestamp:i.timestamp,provider:r.provider,model:r.model,api:r.api,stopReason:r.stopReason,...r.rawStopReason===void 0?{}:{rawStopReason:r.rawStopReason},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},diagnostics:c})}return{schemaVersion:y,sessionId:e.getSessionId(),entryCount:n.length,assistantMessageCount:a,assistant:s,crashes:t.map(({notified:i,...r})=>r)}}o(Z,"collectBugReportDiagnostics");function B(e){const t=[{name:"report.json",contentType:"application/json",data:`${JSON.stringify(e.metadata,null,2)}
|
|
2
2
|
`},{name:"diagnostics.json",contentType:"application/json",data:`${JSON.stringify(e.diagnostics,null,2)}
|
|
3
3
|
`}];return e.sessionJsonl!==void 0&&t.push({name:"session.jsonl",contentType:"application/x-ndjson",data:e.sessionJsonl}),e.summary!==void 0&&t.push({name:"summary.md",contentType:"text/markdown",data:e.summary.endsWith(`
|
|
4
4
|
`)?e.summary:`${e.summary}
|
|
5
|
-
`}),t}o(B,"bugReportFiles");function Q(e,t){return _(t,B(e))}o(Q,"writeBugReportArchive");function X(e){return`
|
|
5
|
+
`}),t}o(B,"bugReportFiles");function Q(e,t){return _(t,B(e))}o(Q,"writeBugReportArchive");function X(e){return`dal-bug-report-${e}.zip`}o(X,"bugReportArchiveFileName");const L=`You are helping a user file a bug report about ${h}, the coding agent they are talking to. You will be shown the conversation transcript. Write a report for the ${h} developers describing what the user was doing and what went wrong.
|
|
6
6
|
|
|
7
7
|
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the report.`,j=`Write the bug report in Markdown with these sections:
|
|
8
8
|
|
|
@@ -18,10 +18,10 @@ Numbered list, as specific as the transcript allows.
|
|
|
18
18
|
## Relevant details
|
|
19
19
|
Tool calls involved, files touched, model behavior, anything else that helps a developer reproduce or locate the problem.
|
|
20
20
|
|
|
21
|
-
Do not include file contents, secrets, or credentials from the transcript; refer to files by path only. Keep the report factual and concise.`;function z(e,t){const n=[];let s=0;for(let a=e.length-1;a>=0;a--){const i=e[a],r=
|
|
21
|
+
Do not include file contents, secrets, or credentials from the transcript; refer to files by path only. Keep the report factual and concise.`;function z(e,t){const n=[];let s=0;for(let a=e.length-1;a>=0;a--){const i=e[a],r=k(i);if(n.length>0&&s+r>t)break;n.push(i),s+=r}return n.reverse()}o(z,"selectMessages");async function ee(e){const{model:t}=e,n=t.contextWindow>0?t.contextWindow:128e3,s=z(e.messages,Math.floor(n*.6)),a=e.hint?.trim(),i=[s.length<e.messages.length?`Note: only the last ${s.length} of ${e.messages.length} messages are shown.`:void 0,`<conversation>
|
|
22
22
|
${M(N(s))}
|
|
23
23
|
</conversation>`,a?`<user-report>
|
|
24
24
|
${a}
|
|
25
25
|
</user-report>`:void 0,j].filter(l=>l!==void 0).join(`
|
|
26
26
|
|
|
27
|
-
`),r={maxTokens:Math.min(4096,t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY),signal:e.signal,apiKey:e.apiKey,headers:e.headers,env:e.env,sessionId:e.sessionId,...t.reasoning&&e.thinkingLevel&&e.thinkingLevel!=="off"?{reasoning:e.thinkingLevel}:{}},c=await O(t,x({systemPrompt:L,messages:[{role:"user",content:[{type:"text",text:i}],timestamp:Date.now()}]}),r,e.streamFn,e.retry);if(c.stopReason==="aborted")throw new Error("Bug report summary was cancelled");const p=
|
|
27
|
+
`),r={maxTokens:Math.min(4096,t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY),signal:e.signal,apiKey:e.apiKey,headers:e.headers,env:e.env,sessionId:e.sessionId,...t.reasoning&&e.thinkingLevel&&e.thinkingLevel!=="off"?{reasoning:e.thinkingLevel}:{}},c=await O(t,x({systemPrompt:L,messages:[{role:"user",content:[{type:"text",text:i}],timestamp:Date.now()}]}),r,e.streamFn,e.retry);if(c.stopReason==="aborted")throw new Error("Bug report summary was cancelled");const p=b(c,"Bug report summary");if(p)throw new Error(p);if(c.content.some(l=>l.type==="toolCall"))throw new Error("Bug report summary attempted to call a tool");const d=T(c.content).trim();if(!d)throw new Error("Bug report summary was empty");return d}o(ee,"generateBugReportSummary");export{H as BUG_REPORT_CUSTOM_ENTRY_TYPE,X as bugReportArchiveFileName,B as bugReportFiles,Z as collectBugReportDiagnostics,q as collectBugReportMetadata,ee as generateBugReportSummary,m as redactJsonValue,u as redactUrl,Q as writeBugReportArchive};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var I=Object.defineProperty;var u=(e,o)=>I(e,"name",{value:o,configurable:!0});import{contentText as P,normalizeContext as O}from"@earendil-works/pi-ai";import{convertToLlm as C,createBranchSummaryMessage as R,createCompactionSummaryMessage as E,createCustomMessage as N}from"../messages.js";import{completeSummarization as z,
|
|
1
|
+
var I=Object.defineProperty;var u=(e,o)=>I(e,"name",{value:o,configurable:!0});import{contentText as P,normalizeContext as O}from"@earendil-works/pi-ai";import{convertToLlm as C,createBranchSummaryMessage as R,createCompactionSummaryMessage as E,createCustomMessage as N}from"../messages.js";import{completeSummarization as z,getSummarizationFailure as W}from"./compaction.js";import{computeFileLists as D,createFileOps as U,estimateTokens as Y,extractFileOpsFromMessage as $,formatFileOperations as q,SUMMARIZATION_SYSTEM_PROMPT as H,serializeConversation as K}from"./utils.js";function ne(e,o,i){if(!o)return{entries:[],commonAncestorId:null};const c=new Set(e.getBranch(o).map(s=>s.id)),a=e.getBranch(i);let n=null;for(let s=a.length-1;s>=0;s--)if(c.has(a[s].id)){n=a[s].id;break}const r=[];let t=o;for(;t&&t!==n;){const s=e.getEntry(t);if(!s)break;r.push(s),t=s.parentId}return r.reverse(),{entries:r,commonAncestorId:n}}u(ne,"collectEntriesForBranchSummary");function G(e){switch(e.type){case"message":return e.message.role==="toolResult"?void 0:e.message;case"custom_message":return N(e.customType,e.content,e.display,e.details,e.timestamp);case"branch_summary":return R(e.summary,e.fromId,e.timestamp);case"compaction":return E(e.summary,e.tokensBefore,e.timestamp);case"thinking_level_change":case"model_change":case"custom":case"label":case"session_info":return}}u(G,"getMessageFromEntry");function L(e,o=0){const i=[],c=U();let a=0;for(const n of e)if(n.type==="branch_summary"&&!n.fromHook&&n.details){const r=n.details;if(Array.isArray(r.readFiles))for(const t of r.readFiles)c.read.add(t);if(Array.isArray(r.modifiedFiles))for(const t of r.modifiedFiles)c.edited.add(t)}for(let n=e.length-1;n>=0;n--){const r=e[n],t=G(r);if(!t)continue;$(t,c);const s=Y(t);if(o>0&&a+s>o){(r.type==="compaction"||r.type==="branch_summary")&&a<o*.9&&(i.unshift(t),a+=s);break}i.unshift(t),a+=s}return{messages:i,fileOps:c,totalTokens:a}}u(L,"prepareBranchEntries");const V=`The user explored a different conversation branch before returning here.
|
|
2
2
|
Summary of that exploration:
|
|
3
3
|
|
|
4
4
|
`,y=`Create a structured summary of this conversation branch for context when returning later.
|
|
@@ -34,4 +34,4 @@ Additional focus: ${t}`:l=y;const _=[{role:"user",content:[{type:"text",text:`<c
|
|
|
34
34
|
${S}
|
|
35
35
|
</conversation>
|
|
36
36
|
|
|
37
|
-
${l}`}],timestamp:Date.now()}],v=Math.min(4096,i.maxTokens>0?i.maxTokens:Number.POSITIVE_INFINITY),w=O({systemPrompt:H,messages:_}),m=await z(i,w,{apiKey:c,headers:a,env:n,signal:r,maxTokens:v},T,M,k);if(m.stopReason==="aborted")return{aborted:!0};const d=
|
|
37
|
+
${l}`}],timestamp:Date.now()}],v=Math.min(4096,i.maxTokens>0?i.maxTokens:Number.POSITIVE_INFINITY),w=O({systemPrompt:H,messages:_}),m=await z(i,w,{apiKey:c,headers:a,env:n,signal:r,maxTokens:v},T,M,k);if(m.stopReason==="aborted")return{aborted:!0};const d=W(m,"Branch summarization");if(d)return{error:d};if(m.content.some(B=>B.type==="toolCall"))return{error:"Branch summarization attempted to call a tool"};let f=P(m.content);f=V+f;const{readFiles:h,modifiedFiles:g}=D(A);return f+=q(h,g),{summary:f||"No summary generated",usage:m.usage,readFiles:h,modifiedFiles:g}}u(re,"generateBranchSummary");export{ne as collectEntriesForBranchSummary,re as generateBranchSummary,L as prepareBranchEntries};
|
|
@@ -20,6 +20,7 @@ export interface CompactionSettings {
|
|
|
20
20
|
reserveTokens: number;
|
|
21
21
|
keepRecentTokens: number;
|
|
22
22
|
maxContextTokens?: number;
|
|
23
|
+
pruneToolOutputs?: boolean;
|
|
23
24
|
}
|
|
24
25
|
export declare const DEFAULT_COMPACTION_SETTINGS: CompactionSettings;
|
|
25
26
|
export declare function calculateContextTokens(usage: Usage): number;
|
|
@@ -32,8 +33,9 @@ export interface ContextUsageEstimate {
|
|
|
32
33
|
}
|
|
33
34
|
export declare function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate;
|
|
34
35
|
export declare function estimateProjectedContextTokens(projection: SessionProjection, branchEntries: SessionEntry[]): ContextUsageEstimate;
|
|
35
|
-
export declare
|
|
36
|
-
export declare function
|
|
36
|
+
export declare const MIN_COMPACTION_HEADROOM_TOKENS = 32000;
|
|
37
|
+
export declare function compactionThreshold(contextWindow: number, settings: CompactionSettings, baseTokens?: number): number;
|
|
38
|
+
export declare function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings, baseTokens?: number): boolean;
|
|
37
39
|
export declare function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number;
|
|
38
40
|
export interface CutPointResult {
|
|
39
41
|
firstKeptEntryIndex: number;
|
|
@@ -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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var d=Object.defineProperty;var o=(i,t)=>d(i,"name",{value:t,configurable:!0});import{readFileSync as s,statSync as u}from"node:fs";import{dirname as c,join as f,resolve as a}from"node:path";function h(i){let t=a(i);for(;;){const n=f(t,".git");try{const r=u(n);if(r.isDirectory()||r.isFile())return{path:n,isFile:r.isFile()}}catch{}const e=c(t);if(e===t)return;t=e}}o(h,"findGitEntry");function l(i){if(!i.isFile)return i.path;try{const t=/^gitdir:\s*(.+)\s*$/m.exec(s(i.path,"utf8"));return t?a(c(i.path),t[1].trim()):void 0}catch{return}}o(l,"resolveGitDir");function G(i){const t=h(i);if(!t)return"Not a git repository: git commands will fail here, so do not run them.";const n=l(t);let e;try{e=n?s(f(n,"HEAD"),"utf8").trim():void 0}catch{e=void 0}if(!e)return"Git repository.";const r=/^ref:\s*refs\/heads\/(.+)$/.exec(e);return r?`Git repository, on branch ${r[1]}.`:/^[0-9a-f]{7,}$/i.test(e)?`Git repository, detached HEAD at ${e.slice(0,7)}.`:"Git repository."}o(G,"describeGitState");export{G as describeGitState};
|
|
@@ -123,6 +123,12 @@ declare const ModelDefinitionSchema: Type.TObject<{
|
|
|
123
123
|
sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
|
|
124
124
|
supportsLongCacheRetention: Type.TOptional<Type.TBoolean>;
|
|
125
125
|
vllmPriority: Type.TOptional<Type.TNumber>;
|
|
126
|
+
responseModelCosts: Type.TOptional<Type.TRecord<"^.*$", Type.TObject<{
|
|
127
|
+
input: Type.TNumber;
|
|
128
|
+
output: Type.TNumber;
|
|
129
|
+
cacheRead: Type.TNumber;
|
|
130
|
+
cacheWrite: Type.TNumber;
|
|
131
|
+
}>>>;
|
|
126
132
|
}>, Type.TObject<{
|
|
127
133
|
supportsDeveloperRole: Type.TOptional<Type.TBoolean>;
|
|
128
134
|
sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
|
|
@@ -280,6 +286,12 @@ declare const ModelOverrideSchema: Type.TObject<{
|
|
|
280
286
|
sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
|
|
281
287
|
supportsLongCacheRetention: Type.TOptional<Type.TBoolean>;
|
|
282
288
|
vllmPriority: Type.TOptional<Type.TNumber>;
|
|
289
|
+
responseModelCosts: Type.TOptional<Type.TRecord<"^.*$", Type.TObject<{
|
|
290
|
+
input: Type.TNumber;
|
|
291
|
+
output: Type.TNumber;
|
|
292
|
+
cacheRead: Type.TNumber;
|
|
293
|
+
cacheWrite: Type.TNumber;
|
|
294
|
+
}>>>;
|
|
283
295
|
}>, Type.TObject<{
|
|
284
296
|
supportsDeveloperRole: Type.TOptional<Type.TBoolean>;
|
|
285
297
|
sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
|
|
@@ -388,6 +400,12 @@ declare const ProviderConfigSchema: Type.TObject<{
|
|
|
388
400
|
sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
|
|
389
401
|
supportsLongCacheRetention: Type.TOptional<Type.TBoolean>;
|
|
390
402
|
vllmPriority: Type.TOptional<Type.TNumber>;
|
|
403
|
+
responseModelCosts: Type.TOptional<Type.TRecord<"^.*$", Type.TObject<{
|
|
404
|
+
input: Type.TNumber;
|
|
405
|
+
output: Type.TNumber;
|
|
406
|
+
cacheRead: Type.TNumber;
|
|
407
|
+
cacheWrite: Type.TNumber;
|
|
408
|
+
}>>>;
|
|
391
409
|
}>, Type.TObject<{
|
|
392
410
|
supportsDeveloperRole: Type.TOptional<Type.TBoolean>;
|
|
393
411
|
sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
|
|
@@ -548,6 +566,12 @@ declare const ProviderConfigSchema: Type.TObject<{
|
|
|
548
566
|
sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
|
|
549
567
|
supportsLongCacheRetention: Type.TOptional<Type.TBoolean>;
|
|
550
568
|
vllmPriority: Type.TOptional<Type.TNumber>;
|
|
569
|
+
responseModelCosts: Type.TOptional<Type.TRecord<"^.*$", Type.TObject<{
|
|
570
|
+
input: Type.TNumber;
|
|
571
|
+
output: Type.TNumber;
|
|
572
|
+
cacheRead: Type.TNumber;
|
|
573
|
+
cacheWrite: Type.TNumber;
|
|
574
|
+
}>>>;
|
|
551
575
|
}>, Type.TObject<{
|
|
552
576
|
supportsDeveloperRole: Type.TOptional<Type.TBoolean>;
|
|
553
577
|
sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
|
|
@@ -705,6 +729,12 @@ declare const ProviderConfigSchema: Type.TObject<{
|
|
|
705
729
|
sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
|
|
706
730
|
supportsLongCacheRetention: Type.TOptional<Type.TBoolean>;
|
|
707
731
|
vllmPriority: Type.TOptional<Type.TNumber>;
|
|
732
|
+
responseModelCosts: Type.TOptional<Type.TRecord<"^.*$", Type.TObject<{
|
|
733
|
+
input: Type.TNumber;
|
|
734
|
+
output: Type.TNumber;
|
|
735
|
+
cacheRead: Type.TNumber;
|
|
736
|
+
cacheWrite: Type.TNumber;
|
|
737
|
+
}>>>;
|
|
708
738
|
}>, Type.TObject<{
|
|
709
739
|
supportsDeveloperRole: Type.TOptional<Type.TBoolean>;
|
|
710
740
|
sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var w=Object.defineProperty;var c=(t,o)=>w(t,"name",{value:o,configurable:!0});import{readFile as v}from"node:fs/promises";import{Type as e}from"typebox";import{Compile as x}from"typebox/compile";import{stripJsonComments as T}from"../utils/json.js";import{normalizePath as k}from"../utils/paths.js";import{stripBom as A}from"../utils/text.js";const g=e.Object({p50:e.Optional(e.Number()),p75:e.Optional(e.Number()),p90:e.Optional(e.Number()),p99:e.Optional(e.Number())}),C=e.Object({allow_fallbacks:e.Optional(e.Boolean()),require_parameters:e.Optional(e.Boolean()),data_collection:e.Optional(e.Union([e.Literal("deny"),e.Literal("allow")])),zdr:e.Optional(e.Boolean()),enforce_distillable_text:e.Optional(e.Boolean()),order:e.Optional(e.Array(e.String())),only:e.Optional(e.Array(e.String())),ignore:e.Optional(e.Array(e.String())),quantizations:e.Optional(e.Array(e.String())),sort:e.Optional(e.Union([e.String(),e.Object({by:e.Optional(e.String()),partition:e.Optional(e.Union([e.String(),e.Null()]))})])),max_price:e.Optional(e.Object({prompt:e.Optional(e.Union([e.Number(),e.String()])),completion:e.Optional(e.Union([e.Number(),e.String()])),image:e.Optional(e.Union([e.Number(),e.String()])),audio:e.Optional(e.Union([e.Number(),e.String()])),request:e.Optional(e.Union([e.Number(),e.String()]))})),preferred_min_throughput:e.Optional(e.Union([e.Number(),g])),preferred_max_latency:e.Optional(e.Union([e.Number(),g]))}),U=e.Object({only:e.Optional(e.Array(e.String())),order:e.Optional(e.Array(e.String()))}),l=e.Union([e.String(),e.Null()]),h=e.Object({off:e.Optional(l),minimal:e.Optional(l),low:e.Optional(l),medium:e.Optional(l),high:e.Optional(l),xhigh:e.Optional(l),max:e.Optional(l)}),i=e.Record(e.String(),e.Unknown()),d=e.Object({off:e.Optional(i),minimal:e.Optional(i),low:e.Optional(i),medium:e.Optional(i),high:e.Optional(i),xhigh:e.Optional(i),max:e.Optional(i)}),M=e.Union([e.String(),e.Number(),e.Boolean(),e.Null()]),P=e.Object({$var:e.Union([e.Literal("thinking.enabled"),e.Literal("thinking.effort")]),omitWhenOff:e.Optional(e.Boolean())}),S=e.Union([M,P]),I=e.Object({supportsStore:e.Optional(e.Boolean()),supportsDeveloperRole:e.Optional(e.Boolean()),supportsReasoningEffort:e.Optional(e.Boolean()),supportsUsageInStreaming:e.Optional(e.Boolean()),supportsFinishReason:e.Optional(e.Boolean()),maxTokensField:e.Optional(e.Union([e.Literal("max_completion_tokens"),e.Literal("max_tokens")])),requiresToolResultName:e.Optional(e.Boolean()),requiresAssistantAfterToolResult:e.Optional(e.Boolean()),requiresThinkingAsText:e.Optional(e.Boolean()),requiresReasoningContentOnAssistantMessages:e.Optional(e.Boolean()),thinkingFormat:e.Optional(e.Union([e.Literal("openai"),e.Literal("openrouter"),e.Literal("together"),e.Literal("baseten"),e.Literal("deepseek"),e.Literal("zai"),e.Literal("qwen"),e.Literal("chat-template"),e.Literal("qwen-chat-template"),e.Literal("string-thinking"),e.Literal("ant-ling")])),chatTemplateKwargs:e.Optional(e.Record(e.String(),S)),chatTemplateArgs:e.Optional(e.Record(e.String(),S)),cacheControlFormat:e.Optional(e.Literal("anthropic")),openRouterRouting:e.Optional(C),vercelGatewayRouting:e.Optional(U),supportsOpenAIGrammarTools:e.Optional(e.Boolean()),supportsStrictMode:e.Optional(e.Boolean()),sendSessionAffinityHeaders:e.Optional(e.Boolean()),sessionAffinityFormat:e.Optional(e.Union([e.Literal("openai"),e.Literal("openai-nosession"),e.Literal("openrouter")])),supportsLongCacheRetention:e.Optional(e.Boolean()),vllmPriority:e.Optional(e.Number()),responseModelCosts:e.Optional(e.Record(e.String(),e.Object({input:e.Number(),output:e.Number(),cacheRead:e.Number(),cacheWrite:e.Number()})))}),q=e.Object({supportsDeveloperRole:e.Optional(e.Boolean()),sessionAffinityFormat:e.Optional(e.Union([e.Literal("openai"),e.Literal("openai-nosession"),e.Literal("openrouter")])),supportsLongCacheRetention:e.Optional(e.Boolean()),supportsStrictMode:e.Optional(e.Boolean()),supportsOpenAIGrammarTools:e.Optional(e.Boolean()),supportsMaxOutputTokens:e.Optional(e.Boolean())}),b={input:e.Number(),output:e.Number(),cacheRead:e.Number(),cacheWrite:e.Number()},L=e.Object({inputTokensAbove:e.Number(),...b}),f=e.Object({...b,tiers:e.Optional(e.Array(L))}),B=e.Object({short:e.Optional(e.Number({exclusiveMinimum:0})),long:e.Optional(e.Number({exclusiveMinimum:0}))}),F=e.Object({maxWidth:e.Optional(e.Integer({minimum:1})),maxHeight:e.Optional(e.Integer({minimum:1})),maxBytes:e.Optional(e.Integer({minimum:1})),jpegQuality:e.Optional(e.Integer({minimum:1,maximum:100}))}),y=e.Object({maxRequestBytes:e.Optional(e.Integer({minimum:1})),images:e.Optional(e.Object({resize:e.Optional(F),maxPerMessage:e.Optional(e.Integer({minimum:1})),maxPerRequest:e.Optional(e.Integer({minimum:1}))}))}),$=e.Object({supportsEagerToolInputStreaming:e.Optional(e.Boolean()),supportsLongCacheRetention:e.Optional(e.Boolean()),sendSessionAffinityHeaders:e.Optional(e.Boolean()),supportsCacheControlOnTools:e.Optional(e.Boolean()),supportsTemperature:e.Optional(e.Boolean()),forceAdaptiveThinking:e.Optional(e.Boolean()),allowEmptySignature:e.Optional(e.Boolean()),supportsStrictTools:e.Optional(e.Boolean()),supportsMidConvoEffort:e.Optional(e.Boolean()),allowedFallbackModels:e.Optional(e.Array(e.Object({provider:e.String({minLength:1}),model:e.String({minLength:1}),cost:f}),{maxItems:3}))}),O=e.Union([I,q,$]),E=e.Object({id:e.String({minLength:1}),name:e.Optional(e.String({minLength:1})),api:e.Optional(e.String({minLength:1})),baseUrl:e.Optional(e.String({minLength:1})),reasoning:e.Optional(e.Boolean()),thinkingLevelMap:e.Optional(h),input:e.Optional(e.Array(e.Union([e.Literal("text"),e.Literal("image")]))),inputLimits:e.Optional(y),cost:e.Optional(f),promptCache:e.Optional(B),contextWindow:e.Optional(e.Number()),maxTokens:e.Optional(e.Number()),samplingParams:e.Optional(i),samplingParamsByThinkingLevel:e.Optional(d),headers:e.Optional(e.Record(e.String(),e.String())),compat:e.Optional(O)}),z=e.Object({name:e.Optional(e.String({minLength:1})),reasoning:e.Optional(e.Boolean()),thinkingLevelMap:e.Optional(h),input:e.Optional(e.Array(e.Union([e.Literal("text"),e.Literal("image")]))),inputLimits:e.Optional(y),cost:e.Optional(e.Object({input:e.Optional(e.Number()),output:e.Optional(e.Number()),cacheRead:e.Optional(e.Number()),cacheWrite:e.Optional(e.Number()),tiers:e.Optional(e.Array(L))})),promptCache:e.Optional(B),contextWindow:e.Optional(e.Number()),maxTokens:e.Optional(e.Number()),samplingParams:e.Optional(i),samplingParamsByThinkingLevel:e.Optional(d),headers:e.Optional(e.Record(e.String(),e.String())),compat:e.Optional(O)}),W=e.Object({name:e.Optional(e.String({minLength:1})),baseUrl:e.Optional(e.String({minLength:1})),apiKey:e.Optional(e.String({minLength:1})),api:e.Optional(e.String({minLength:1})),oauth:e.Optional(e.Literal("radius")),headers:e.Optional(e.Record(e.String(),e.String())),compat:e.Optional(O),authHeader:e.Optional(e.Boolean()),models:e.Optional(e.Array(E)),modelOverrides:e.Optional(e.Record(e.String(),z))}),_=e.Object({providers:e.Record(e.String(),W)}),N=x(_);function K(t){if(t.keyword==="required"){const s=t.params.requiredProperties?.[0];if(s){const r=t.instancePath.replace(/^\//,"").replace(/\//g,".");return r?`${r}.${s}`:s}}return t.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}c(K,"formatValidationPath");function j(t){if(typeof t!="object"||t===null||Object.isFrozen(t))return t;for(const o of Object.values(t))j(o);return Object.freeze(t)}c(j,"deepFreeze");class p{static{c(this,"ModelConfig")}providers;error;constructor(o,a){this.providers=o,this.error=a}static async load(o){if(!o)return new p(new Map);const a=k(o);let s;try{s=await v(a,"utf-8")}catch(n){return n.code==="ENOENT"?new p(new Map):new p(new Map,`Failed to load models.json: ${n instanceof Error?n.message:n}
|
|
2
2
|
|
|
3
3
|
File: ${a}`)}let r;try{r=JSON.parse(T(A(s)))}catch(n){return new p(new Map,`Failed to parse models.json: ${n instanceof Error?n.message:n}
|
|
4
4
|
|
|
@@ -6,4 +6,4 @@ File: ${a}`)}if(!N.Check(r)){const n=N.Errors(r).map(m=>` - ${K(m)}: ${m.messag
|
|
|
6
6
|
`)||"Unknown schema error";return new p(new Map,`Invalid models.json schema:
|
|
7
7
|
${n}
|
|
8
8
|
|
|
9
|
-
File: ${a}`)}const
|
|
9
|
+
File: ${a}`)}const R=r,u=new Map;for(const[n,m]of Object.entries(R.providers))u.set(n,j(structuredClone(m)));return new p(u)}getProvider(o){return this.providers.get(o)}getProviderIds(){return[...this.providers.keys()]}getError(){return this.error}}export{p as ModelConfig};
|
|
@@ -14,6 +14,7 @@ export interface SandboxDenial {
|
|
|
14
14
|
cwd: string;
|
|
15
15
|
blocked: SandboxBlockedAccess[];
|
|
16
16
|
networkProxyError?: string;
|
|
17
|
+
scratchDir?: string;
|
|
17
18
|
}
|
|
18
19
|
export declare function parseViolationLine(line: string): SandboxBlockedAccess | undefined;
|
|
19
20
|
export declare function parseOutput(output: string): SandboxBlockedAccess[];
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
var u=Object.defineProperty;var
|
|
2
|
-
`)){const e=
|
|
3
|
-
`)}
|
|
1
|
+
var u=Object.defineProperty;var d=(o,r)=>u(o,"name",{value:r,configurable:!0});function f(o,r){const t=o.replace(/\\/g,"/");for(const e of r){if(!e)continue;const s=e.replace(/\\/g,"/").replace(/\/$/,"");if(t===s||t.startsWith(`${s}/`))return!1}return/^\/(?:private\/)?(?:var\/)?tmp(?:\/|$)/.test(t)||/^\/(?:private\/)?var\/folders\/[^/]+\/[^/]+\/T(?:\/|$)/.test(t)||/^[A-Za-z]:\/(?:Windows\/Temp|Users\/[^/]+\/AppData\/Local\/Temp)(?:\/|$)/i.test(t)}d(f,"isSystemTempPath");const p=20;function h(o){const r=/deny(?:\(\d+\))?\s+(?<operation>[\w-]+)\s+(?<target>.+?)\s*$/.exec(o);if(!r?.groups)return;const{operation:t,target:e}=r.groups;if(t.startsWith("file-write"))return{kind:"file-write",target:e,source:"kernel",detail:t};if(t.startsWith("file-read"))return{kind:"file-read",target:e,source:"kernel",detail:t};if(t.startsWith("network"))return{kind:"network",target:e,source:"kernel",detail:t}}d(h,"parseViolationLine");const g=[{regex:/(?<target>\/[^\s:'"`]+)['"`]?:\s*Read-only file system/,kind:"file-write"},{regex:/Read-only file system[^/\n]*(?<target>\/[^\s'"`]+)/,kind:"file-write"},{regex:/['"`]?(?<target>\/[^\s:'"`]+)['"`]?:\s*Operation not permitted/,kind:"file-write"},{regex:/EPERM: operation not permitted, \w+ ['"](?<target>(?:\/|[A-Za-z]:\\)[^'"]+)['"]/,kind:"file-write"},{regex:/EROFS: read-only file system, \w+ ['"](?<target>\/[^'"]+)['"]/,kind:"file-write"},{regex:/EACCES: permission denied, \w+ ['"](?<target>[A-Za-z]:\\[^'"]+)['"]/,kind:"file-write"},{regex:/Access to the path ['"](?<target>[A-Za-z]:\\[^'"]+)['"] is denied/,kind:"file-write"},{regex:/['"`](?<target>\/[A-Za-z]\/[^'"`]+)['"`]:\s*Permission denied/,kind:"file-write"},{regex:/Could not resolve host:\s*(?<target>[\w.-]+)/,kind:"network"},{regex:/getaddrinfo (?:ENOTFOUND|EAI_AGAIN) (?<target>[\w.-]+)/,kind:"network"},{regex:/Failed to connect to (?<target>[\w.-]+) port (?<port>\d+)/,kind:"network"},{regex:/Temporary failure in name resolution.*?(?<target>[\w-]+(?:\.[\w-]+)+)?/,kind:"network"}],w=/^(?:\S*\/)?(?:cat|head|tail|less|more|grep|rg|ls|find|wc|stat|file|diff|cmp|od|xxd|strings|base64|sha\d*sum|md5|openssl)\b[^:]*:/;function k(o){const r=[];for(const t of o.split(`
|
|
2
|
+
`)){const e=t.trim();for(const{regex:s,kind:i}of g){const a=s.exec(e);if(!a)continue;const n=a.groups?.target;if(!n){i==="network"&&r.push({kind:i,target:"(unknown host)",source:"output",detail:e});break}const c=a.groups?.port,l=i==="file-write"&&/Operation not permitted|Permission denied/.test(e)&&w.test(e)?"file-read":i;r.push({kind:l,target:c?`${n}:${c}`:n,source:"output",detail:e.slice(0,200)});break}}return r}d(k,"parseOutput");function m(o){const r=new Set,t=[];for(const e of o){const s=`${e.kind}\0${e.target}`;if(!r.has(s)&&(r.add(s),t.push(e),t.length>=p))break}return t}d(m,"dedupe");function y(o){const r=[...o.refusals.map(e=>({kind:"network",target:e.port!==void 0?`${e.host}:${e.port}`:e.host,source:"proxy"})),...o.violations.flatMap(e=>{const s=h(e.line);return s?[s]:[]})];(r.length===0||r.every(e=>e.kind==="network"&&e.target.startsWith("/")))&&r.push(...k(o.output));const t=m(r);return t.length>0?t:void 0}d(y,"collectBlockedAccesses");function $(o){const r=[`[sandbox] The OS sandbox (${o.level}, network off except allowlisted domains) blocked this command:`];for(const n of o.blocked){const c=n.source==="output"?" (inferred from the output)":"";r.push(` - ${n.kind}: ${n.target}${c}`)}o.networkProxyError&&r.push(` (allowlisted domains are unreachable too: the network proxy could not start: ${o.networkProxyError})`);const t=o.blocked.filter(n=>n.kind==="network"&&!n.target.startsWith("/")),e=o.blocked.filter(n=>n.kind==="file-write"),s=e.filter(n=>f(n.target,[o.scratchDir,o.cwd])),i=e.filter(n=>!s.includes(n));if(s.length>0){const n=o.scratchDir?`$TMPDIR (${o.scratchDir})`:"$TMPDIR";if(r.push(`Temporary files go in ${n}: it is the temp directory this sandbox lets commands write, the others are blocked. Rerun the command with those paths under $TMPDIR; do not ask to write the system temp directory.`),i.length===0&&t.length===0)return r.join(`
|
|
3
|
+
`)}const a={mode:"allow",justification:"<why this is needed>"};return t.length>0&&(a.allow_domains=t.map(n=>n.target.replace(/:\d+$/,""))),i.length>0&&(a.allow_write=i.map(n=>n.target)),r.push(`Do not try to work around the sandbox. If the task genuinely needs this access, call the tool again with the same command and sandbox_escalation: ${JSON.stringify(t.length>0||i.length>0?a:{mode:"unsandboxed",justification:"<why this is needed>"})} (or mode "unsandboxed" to run outside the sandbox). The user will be asked to approve.`),r.join(`
|
|
4
|
+
`)}d($,"describeDenialForModel");export{y as collectBlockedAccesses,$ as describeDenialForModel,k as parseOutput,h as parseViolationLine};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var G=Object.defineProperty;var m=(n,e)=>G(n,"name",{value:e,configurable:!0});import{spawnSync as Q}from"node:child_process";import{mkdirSync as V,mkdtempSync as z,rmSync as J}from"node:fs";import{tmpdir as Z}from"node:os";import{isAbsolute as P,join as q,relative as ee,resolve as oe}from"node:path";import{fill as y,t as h}from"../../dal/i18n.js";import{detectSandboxAvailability as ne}from"./availability.js";import{collectBlockedAccesses as O}from"./denial.js";import{detectNetworkCommand as T,FAIL_FAST_NETWORK_ENV as
|
|
2
|
-
`)){const i=s.trim();if(!i)continue;const t=P(i)?i:oe(n,i),a=ee(n,t);(a.startsWith("..")||P(a))&&r.push(t)}const l=[...new Set(r)];return K.set(n,l),l}m(fe,"gitDirsOutside");function S(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}m(S,"cleanList");let
|
|
3
|
-
`)}planNetworkEscalation(e){if(this.policy.level!=="workspace-write"||!this.availability().available)return;const o=T(e.command);if(!o)return;const r=[...this.policy.network.allowedDomains,...this.sessionDomains],l=this.policy.network.deniedDomains,s=te(o,e.cwd).filter(t=>!r.some(a=>
|
|
4
|
-
${e.command}`,X=Date.now()
|
|
5
|
-
`),a=n.mode==="unsandboxed"?[r,s]:[r,l,s],d=await e.ui.select(t,a,o?{signal:o}:void 0);return o?.aborted?{approved:!1,message:"the turn was interrupted before the user answered"}:d===r?{approved:!0,scope:"once"}:d===l?{approved:!0,scope:"session"}:{approved:!1,message:"the user declined"}}m(
|
|
1
|
+
var G=Object.defineProperty;var m=(n,e)=>G(n,"name",{value:e,configurable:!0});import{spawnSync as Q}from"node:child_process";import{mkdirSync as V,mkdtempSync as z,rmSync as J}from"node:fs";import{tmpdir as Z}from"node:os";import{isAbsolute as P,join as q,relative as ee,resolve as oe}from"node:path";import{fill as y,t as h}from"../../dal/i18n.js";import{detectSandboxAvailability as ne}from"./availability.js";import{collectBlockedAccesses as O}from"./denial.js";import{detectNetworkCommand as T,FAIL_FAST_NETWORK_ENV as U,networkDomainsFor as te,packageCacheDirs as ie}from"./package-managers.js";import{domainMatches as B,expandPath as L,filesystemRules as ae}from"./policy.js";import{acquireSandboxRuntime as se,ensureFilteringProxy as re,proxyUnavailableReason as M,registerNetworkGrant as le,releaseSandboxRuntime as de,violationsForCommand as ce,wrapCommand as me}from"./runtime.js";import{prepareWindowsCommand as he}from"./windows.js";const j=Symbol.for("dal.sandbox.escalationHandlers"),k=globalThis;k[j]instanceof Set||(k[j]=new Set);const R=k[j];function Re(n){return R.add(n),()=>{R.delete(n)}}m(Re,"registerSandboxEscalationHandler");const F=Symbol.for("dal.sandbox.processSandbox");function Ae(n){k[F]=n}m(Ae,"setProcessShellSandbox");function Ne(){return k[F]}m(Ne,"getProcessShellSandbox");const K=new Map;function fe(n){const e=K.get(n);if(e)return e;const o=Q("git",["rev-parse","--absolute-git-dir","--git-common-dir"],{cwd:n,encoding:"utf8",timeout:3e3}),r=[];if(o.status===0)for(const s of o.stdout.split(`
|
|
2
|
+
`)){const i=s.trim();if(!i)continue;const t=P(i)?i:oe(n,i),a=ee(n,t);(a.startsWith("..")||P(a))&&r.push(t)}const l=[...new Set(r)];return K.set(n,l),l}m(fe,"gitDirsOutside");function S(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}m(S,"cleanList");let pe=0;class Ie{static{m(this,"ShellSandbox")}policy;onEscalation;onEvent;availabilityOverride;sessionDomains=new Set;sessionWritable=new Set;holdsRuntime=!1;sharedScratch;ownScratch;constructor(e){this.policy=e.policy,this.onEscalation=e.onEscalation,this.onEvent=e.onEvent,this.availabilityOverride=e.availability,this.sharedScratch=e.scratchDir,this.active&&(se(),this.holdsRuntime=!0)}scratchDir(){return this.sharedScratch?this.sharedScratch():(this.ownScratch??=we(),this.ownScratch)}async dispose(){this.ownScratch&&(J(this.ownScratch,{recursive:!0,force:!0}),this.ownScratch=void 0),this.holdsRuntime&&(this.holdsRuntime=!1,await de())}get level(){return this.policy.level}get active(){return this.policy.level!=="off"}availability(){return this.availabilityOverride??ne()}status(){const e=this.availability(),o=M();return{level:this.policy.level,levelSource:this.policy.levelSource,enforced:this.active&&e.available,platform:e.platform,...e.mechanism?{mechanism:e.mechanism}:{},...this.active&&!e.available&&e.reason?{unavailableReason:e.reason}:{},...e.isolationTier?{isolationTier:e.isolationTier}:{},...e.limitations?.length?{limitations:[...e.limitations]}:{},network:{allowedDomains:[...this.policy.network.allowedDomains],deniedDomains:[...this.policy.network.deniedDomains],...o?{proxyError:o}:{}},sessionAllowances:{domains:[...this.sessionDomains],writablePaths:[...this.sessionWritable]}}}describeForModel(){if(!this.active)return;const e=this.policy.level==="read-only"?"writes only to $TMPDIR (session scratch)":"writes only to the working directory, $TMPDIR (session scratch) and package caches (agent/editor config, git hooks and .env stay read-only)",o=this.policy.network.allowedDomains,r=(o.length>0?`network off except ${o.join(", ")}`:"network off")+(this.policy.level==="workspace-write"?" (package installs via npm/pnpm/yarn/pip/uv/cargo/go and curl/wget/git clone ask the user for their hosts by themselves: run them plainly, without sandbox_escalation)":"");return`OS sandbox (${this.policy.level}): ${e}; ${r}; ~/.ssh and other credentials unreadable. Use sandbox_escalation only after the result says the sandbox blocked something the task needs.`}unavailableRefusal(){if(!this.active)return;const e=this.availability();if(!e.available)return[`Command refused: the sandbox level is "${this.policy.level}", but ${e.reason??"the OS sandbox is unavailable."}`,"Commands are not run without the sandbox unless the user says so explicitly.",'The user can fix the sandbox, or opt out explicitly with `dal --sandbox off` or "sandbox": { "level": "off" } in ~/.dal/agent/settings.json.','A single command can still run if the user approves it: retry with sandbox_escalation {"mode":"unsandboxed","justification":"..."}.'].join(`
|
|
3
|
+
`)}planNetworkEscalation(e){if(this.policy.level!=="workspace-write"||!this.availability().available)return;const o=T(e.command);if(!o)return;const r=[...this.policy.network.allowedDomains,...this.sessionDomains],l=this.policy.network.deniedDomains,s=te(o,e.cwd).filter(t=>!r.some(a=>B(t,a))&&!l.some(a=>B(t,a)));if(s.length===0)return;const i=o.ecosystems.length>0?"package-install":"download";return{mode:"allow",allow_domains:s,trigger:i,justification:i==="package-install"?h("\u8FD9\u6761\u547D\u4EE4\u8981\u5B89\u88C5\u4F9D\u8D56\uFF0C\u9700\u8981\u4ECE\u8F6F\u4EF6\u6E90\u4E0B\u8F7D\u3002"):h("\u8FD9\u6761\u547D\u4EE4\u8981\u4ECE\u7F51\u4E0A\u4E0B\u8F7D\u6587\u4EF6\u3002")}}async prepare(e){const o=this.policy.level;if(o==="off")return H(e.command,{level:o,sandboxed:!1});const r=this.unavailableRefusal();if(r&&e.escalation?.mode!=="unsandboxed")throw new Error(r);let l=[],s=[],i;const t=e.escalation||r?void 0:this.planNetworkEscalation(e),a=t?await this.approveEscalation(e,t,t.trigger):void 0;if(t&&a&&a.decidedBy!=="none"){const f={request:a.request,decision:a.decision};if(i=f,!f.decision.approved)throw new Error(`The user did not allow network access for this command${f.decision.message?` (${f.decision.message})`:""}: it needs ${t.allow_domains.join(", ")}. Do not retry it with sandbox_escalation; continue without it or ask the user.`);l=a.allowDomains,s=a.allowWrite}else if(e.escalation){const{decidedBy:f,allowDomains:x,allowWrite:_,...w}=await this.approveEscalation(e,e.escalation);if(i=w,!w.decision.approved)throw new Error(`Sandbox escalation refused${w.decision.message?`: ${w.decision.message}`:"."} Do not retry the same escalation; continue without it or ask the user.`);if(w.request.mode==="unsandboxed")return H(e.command,{level:o,sandboxed:!1,escalation:i});l=x,s=_}const d=this.availability(),v=e.shellKind??"bash";if(v!=="bash"&&d.mechanism!=="mxc")throw new Error(`Command refused: ${v} commands cannot run inside the ${d.mechanism??"OS"} sandbox, and the sandbox level is "${o}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);const p=this.scratchDir();o==="workspace-write"&&ue(T(e.command)?.managers);const u=ae(this.policy,e.cwd,{gitDirs:this.policy.level==="workspace-write"?fe(e.cwd):[],extraWrite:[...this.sessionWritable,...s],scratchDir:p}),c={allowedDomains:[...this.policy.network.allowedDomains,...this.sessionDomains,...l],deniedDomains:this.policy.network.deniedDomains,refusals:[]},D=`${process.pid}-${++pe}`,g=c.allowedDomains.length===0;if(d.mechanism==="mxc"&&d.mxc){const f=g?{...e.env??process.env,...U}:e.env;return this.prepareWindows({...e,...f?{env:f}:{}},{level:o,shellKind:v,scratch:p,rules:u,grant:c,runId:D,escalation:i,availability:d})}const b=ve(p),E=g?Object.entries(U).map(([f,x])=>` ${f}=${x}`).join(""):"",A=`export DAL_SANDBOX_RUN=${D} TMPDIR=${b} TMP=${b} TEMP=${b}${E}
|
|
4
|
+
${e.command}`,X=Date.now(),$=await me({command:A,shell:e.shell,allowWrite:u.allowWrite,denyWrite:u.denyWrite,denyRead:u.denyRead,allowLocalBinding:e.background===!0||this.policy.network.allowLocalBinding,...d.ripgrep?{ripgrep:d.ripgrep}:{}},c),W={level:o,sandboxed:!0,...i?{escalation:i}:{}};let N=!1;return{command:$.command,sandboxed:!0,details:W,finish:m(async(f,x)=>{if(N)return W.denial;if(N=!0,$.release(),f===0)return;const _=d.platform==="darwin"?await ce(A,X,400):[],w=O({refusals:c.refusals,violations:_,output:x});if(!w)return;const I=$.proxied?void 0:M(),C={level:o,platform:d.platform,command:e.command,cwd:e.cwd,blocked:w,scratchDir:p,...I&&w.some(Y=>Y.kind==="network")?{networkProxyError:I}:{}};return W.denial=C,this.onEvent?.({type:"sandbox_denied",toolCallId:e.toolCallId,toolName:e.toolName,denial:C}),C},"finish")}}async prepareWindows(e,o){const{level:r,grant:l,availability:s}=o,i=s.mxc;if(!i)throw new Error("Command refused: the Windows sandbox (mxc) is not loaded.");let t,a;if(l.allowedDomains.length>0){const c=await re();"port"in c?t=c.port:a=c.error}const d=he({runtime:i,kind:o.shellKind,shellPath:e.shell,command:e.command,cwd:e.cwd,level:r,rules:o.rules,env:e.env??process.env,scratchDir:o.scratch,runId:o.runId,...t!==void 0?{proxyPort:t}:{},allowLocalNetwork:e.background===!0||this.policy.network.allowLocalBinding}),v=le(l),p={level:r,sandboxed:!0,...o.escalation?{escalation:o.escalation}:{}};let u=!1;return{command:d.command,sandboxed:!0,details:p,finish:m(async(c,D)=>{if(u)return p.denial;if(u=!0,v(),d.cleanup(),c===0)return;const g=O({refusals:l.refusals,violations:[],output:D});if(!g)return;const b={level:r,platform:s.platform,command:e.command,cwd:e.cwd,blocked:g,scratchDir:o.scratch,...a&&g.some(E=>E.kind==="network")?{networkProxyError:a}:{}};return p.denial=b,this.onEvent?.({type:"sandbox_denied",toolCallId:e.toolCallId,toolName:e.toolName,denial:b}),b},"finish")}}uiApprovals=Promise.resolve();queueUiApproval(e){const o=this.uiApprovals.then(e,e);return this.uiApprovals=o.catch(()=>{}),o}async approveEscalation(e,o,r){const l=o.mode==="unsandboxed"?"unsandboxed":"allow",s={toolCallId:e.toolCallId,toolName:e.toolName,command:e.command,cwd:e.cwd,level:this.policy.level,mode:l,justification:typeof o.justification=="string"?o.justification.trim():"",allowDomains:l==="allow"?S(o.allow_domains):[],allowWrite:l==="allow"?S(o.allow_write).map(t=>L(t,e.cwd)):[],background:e.background===!0,...r?{trigger:r}:{}},i=m((t,a)=>{const d=t.approved&&t.scope==="session"&&l==="unsandboxed"?{...t,scope:"once"}:t,v=d.approved&&l==="allow"?d.grant:void 0,p=[...new Set([...s.allowDomains,...S(v?.allowDomains)])],u=[...new Set([...s.allowWrite,...S(v?.allowWrite).map(c=>L(c,e.cwd))])];if(d.approved&&d.scope==="session"){for(const c of p)this.sessionDomains.add(c);for(const c of u)this.sessionWritable.add(c)}return r&&a==="none"||this.onEvent?.({type:"sandbox_escalation",toolCallId:e.toolCallId,toolName:e.toolName,request:s,decision:d,decidedBy:a}),{request:s,decision:d,decidedBy:a,allowDomains:p,allowWrite:u}},"finish");if(!s.justification)return i({approved:!1,message:"an escalation needs a justification"},"none");if(l==="allow"&&s.allowDomains.length===0&&s.allowWrite.length===0)return i({approved:!1,message:'mode "allow" needs allow_domains or allow_write'},"none");if(this.onEscalation){const t=await this.onEscalation(s,e.ctx);if(t)return i(t,"sdk")}for(const t of R){const a=await t(s,e.ctx);if(a)return i(a,"handler")}if(e.ctx?.hasUI){const t=e.ctx;return i(await this.queueUiApproval(()=>be(s,t,e.signal)),"ui")}return i({approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"},"none")}}function H(n,e){return{command:n,sandboxed:!1,details:e,finish:m(async()=>{},"finish")}}m(H,"passthrough");function ue(n){if(!(!n||n.length===0))for(const e of ie(n))try{V(e,{recursive:!0,mode:448})}catch{}}m(ue,"ensurePackageCaches");function we(){return z(q(Z(),"dal-sandbox-"))}m(we,"createScratchDir");function ve(n){return`'${n.replace(/'/g,"'\\''")}'`}m(ve,"shellQuote");async function be(n,e,o){if(o?.aborted)return{approved:!1,message:"the turn was interrupted before the user answered"};const r=h("\u4EC5\u672C\u6B21\u5141\u8BB8"),l=h("\u672C\u4F1A\u8BDD\u5185\u90FD\u5141\u8BB8"),s=h("\u62D2\u7EDD"),i=n.mode==="unsandboxed"?h("\u5728\u6C99\u7BB1\u4E4B\u5916\u8FD0\u884C\u547D\u4EE4\uFF08\u53EF\u8BBF\u95EE\u4F60\u7684\u5168\u90E8\u6587\u4EF6\u548C\u7F51\u7EDC\uFF09"):[n.allowDomains.length>0?y(h("\u8BBF\u95EE {domains}"),{domains:n.allowDomains.join(", ")}):"",n.allowWrite.length>0?y(h("\u5199\u5165 {paths}"),{paths:n.allowWrite.join(", ")}):""].filter(Boolean).join(h("\uFF0C\u5E76")),t=[y(h("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:i}),y(h("\u547D\u4EE4\uFF1A{command}"),{command:n.command}),y(h("\u76EE\u5F55\uFF1A{cwd}"),{cwd:n.cwd}),n.trigger?y(h("\u539F\u56E0\uFF1A{reason}"),{reason:n.justification}):y(h("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:n.justification})].join(`
|
|
5
|
+
`),a=n.mode==="unsandboxed"?[r,s]:[r,l,s],d=await e.ui.select(t,a,o?{signal:o}:void 0);return o?.aborted?{approved:!1,message:"the turn was interrupted before the user answered"}:d===r?{approved:!0,scope:"once"}:d===l?{approved:!0,scope:"session"}:{approved:!1,message:"the user declined"}}m(be,"askThroughUi");export{Ie as ShellSandbox,we as createScratchDir,Ne as getProcessShellSandbox,Re as registerSandboxEscalationHandler,Ae as setProcessShellSandbox};
|