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
|
@@ -6,15 +6,18 @@ import type { SandboxSettings, SandboxSettingsSources } from "./sandbox/policy.t
|
|
|
6
6
|
export interface CompactionModelOverride {
|
|
7
7
|
reserveTokens?: number;
|
|
8
8
|
keepRecentTokens?: number;
|
|
9
|
+
maxContextTokens?: number;
|
|
9
10
|
}
|
|
11
|
+
export declare const DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS = 80000;
|
|
10
12
|
export interface CompactionSettings {
|
|
11
13
|
enabled?: boolean;
|
|
12
14
|
reserveTokens?: number;
|
|
13
15
|
keepRecentTokens?: number;
|
|
14
16
|
modelOverrides?: Record<string, CompactionModelOverride>;
|
|
15
17
|
maxContextTokens?: number;
|
|
18
|
+
summaryModel?: string;
|
|
19
|
+
pruneToolOutputs?: boolean;
|
|
16
20
|
}
|
|
17
|
-
export declare const DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS = 128000;
|
|
18
21
|
export declare const DEFAULT_MAX_OUTPUT_TOKENS = 32000;
|
|
19
22
|
export declare const DEFAULT_MAX_RETRIES = 5;
|
|
20
23
|
export interface BranchSummarySettings {
|
|
@@ -251,8 +254,14 @@ export declare class SettingsManager {
|
|
|
251
254
|
reserveTokens: number;
|
|
252
255
|
keepRecentTokens: number;
|
|
253
256
|
maxContextTokens: number;
|
|
257
|
+
pruneToolOutputs: boolean;
|
|
254
258
|
};
|
|
255
|
-
getCompactionMaxContextTokens(): number;
|
|
259
|
+
getCompactionMaxContextTokens(model?: Pick<Model<string>, "provider" | "id">): number;
|
|
260
|
+
getCompactionPruneToolOutputs(): boolean;
|
|
261
|
+
getCompactionSummaryModel(): {
|
|
262
|
+
provider: string;
|
|
263
|
+
modelId: string;
|
|
264
|
+
} | undefined;
|
|
256
265
|
getBranchSummarySettings(): {
|
|
257
266
|
reserveTokens: number;
|
|
258
267
|
skipPrompt: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var F=Object.defineProperty;var a=(r,e)=>F(r,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as L}from"@earendil-works/pi-ai";import{randomUUID as M}from"crypto";import{existsSync as y,mkdirSync as I,readFileSync as A,writeFileSync as O}from"fs";import{dirname as N,join as u}from"path";import D from"proper-lockfile";import{CONFIG_DIR_NAME as T,getAgentDir as R}from"../config.js";import{normalizePath as v,resolvePath as m}from"../utils/paths.js";import{stripBom as P}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as W,parseHttpIdleTimeoutMs as _}from"./http-dispatcher.js";const $={reserveTokens:16384,keepRecentTokens:2e4},U=128e3,B=32e3,H=5,q=["off","streaming","idle"];function p(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}a(p,"isMergeableObject");function j(r,e){const t={...r};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const n=r[s];t[s]=p(n)&&p(i)?j(n,i):i}return t}a(j,"deepMergeObjects");const V=["read","bash","edit","write"];function f(r){return typeof r=="string"&&(r.startsWith("+")||r.startsWith("-"))}a(f,"isToolModifier");function le(r){const e=r.filter(f);if(e.length===0)return;if(e.length<r.length)return"tool names cannot be mixed with +name or -name entries";const t=e.find(s=>s.includes("*"));if(t)return`+name and -name entries take exact tool names, not patterns: ${t}`}a(le,"getToolListError");function X(r,e){const t=[...r];for(const s of e){if(!f(s))continue;const i=s.slice(1),n=t.indexOf(i);s.startsWith("+")&&n===-1&&i?t.push(i):s.startsWith("-")&&n!==-1&&t.splice(n,1)}return t}a(X,"applyToolModifiers");function K(r,e){return e===void 0?r:!Array.isArray(r)||!Array.isArray(e)||!e.every(f)?e:[...r,...e]}a(K,"mergeDefaultTools");function Q(r){const e=r.filter(t=>!f(t));return X(e.length>0||r.length===0?e:V,r)}a(Q,"resolveDefaultTools");function h(r,e){const t=j(r,e),s=K(r.defaultTools,e.defaultTools);return s===void 0?t:{...t,defaultTools:s}}a(h,"deepMergeSettings");function C(r,e){const t=_(r);if(t!==void 0)return t;if(r!==void 0)throw new Error(`Invalid ${e} setting: ${String(r)}`)}a(C,"parseTimeoutSetting");function S(r,e,t){return{scope:r,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}a(S,"toSettingsError");class z{static{a(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=m(e),i=m(t);this.globalSettingsPath=u(i,"settings.json"),this.projectSettingsPath=u(s,T,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let n=1;n<=10;n++)try{return D.lockSync(e,{realpath:!1})}catch(o){if((typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0)!=="ELOCKED"||n===10)throw o;i=o;const g=Date.now();for(;Date.now()-g<20;);}throw i??new Error("Failed to acquire settings lock")}withLock(e,t){const s=e==="global"?this.globalSettingsPath:this.projectSettingsPath,i=N(s);let n;try{const o=y(s);o&&(n=this.acquireLockSyncWithRetry(s));const l=o?A(s,"utf-8"):void 0,g=t(l);g!==void 0&&(y(i)||I(i,{recursive:!0}),n||(n=this.acquireLockSyncWithRetry(s)),O(s,g,"utf-8"))}finally{n&&n()}}}class G{static{a(this,"InMemorySettingsStorage")}global;project;withLock(e,t){const s=e==="global"?this.global:this.project,i=t(s);i!==void 0&&(e==="global"?this.global=i:this.project=i)}}class d{static{a(this,"SettingsManager")}storage;globalSettings;projectSettings;settings;projectTrusted;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(e,t,s,i=null,n=null,o=[],l=!0,g={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=l,this.globalSettingsLoadError=i,this.projectSettingsLoadError=n,this.errors=[...o],this.settingsPaths=g,this.settings=h(this.globalSettings,this.projectSettings)}static create(e,t=R(),s={}){const i=m(e),n=m(t),o=new z(i,n);return d.fromStorageWithPaths(o,s,{global:u(n,"settings.json"),project:u(i,T,"settings.json")})}static fromStorage(e,t={}){return d.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,n=d.tryLoadFromStorage(e,"global"),o=d.tryLoadFromStorage(e,"project",i),l=[];return n.error&&l.push(S("global",n.error,s.global)),o.error&&l.push(S("project",o.error,s.project)),new d(e,n.settings,o.settings,n.error,o.error,l,i,s)}static inMemory(e={},t={}){const s=new G,i=d.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),d.fromStorage(s,t)}static loadFromStorage(e,t,s=!0){if(t==="project"&&!s)return{};let i;if(e.withLock(t,o=>{i=o}),!i)return{};const n=JSON.parse(P(i));return d.migrateSettings(n)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:d.loadFromStorage(e,t,s),error:null}}catch(i){return{settings:{},error:i}}}static migrateSettings(e){if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),!("transport"in e)&&typeof e.websockets=="boolean"&&(e.transport=e.websockets?"websocket":"sse",delete e.websockets),"skills"in e&&typeof e.skills=="object"&&e.skills!==null&&!Array.isArray(e.skills)){const t=e.skills;t.enableSkillCommands!==void 0&&e.enableSkillCommands===void 0&&(e.enableSkillCommands=t.enableSkillCommands),Array.isArray(t.customDirectories)&&t.customDirectories.length>0?e.skills=t.customDirectories:delete e.skills}if("retry"in e&&typeof e.retry=="object"&&e.retry!==null&&!Array.isArray(e.retry)){const t=e.retry,s=typeof t.provider=="object"&&t.provider!==null?t.provider:void 0;typeof t.maxDelayMs=="number"&&(s?.maxRetryDelayMs===void 0||s?.maxRetryDelayMs===null)&&(t.provider={...s??{},maxRetryDelayMs:t.maxDelayMs}),delete t.maxDelayMs}return e}getSettings(){return structuredClone(this.settings)}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}isProjectTrusted(){return this.projectTrusted}setProjectTrusted(e){if(this.projectTrusted===e)return;if(this.projectTrusted=e,this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear(),!e){this.projectSettings={},this.projectSettingsLoadError=null,this.settings=h(this.globalSettings,this.projectSettings);return}const t=d.tryLoadFromStorage(this.storage,"project",e);this.projectSettings=t.settings,this.projectSettingsLoadError=t.error,t.error&&this.recordError("project",t.error),this.settings=h(this.globalSettings,this.projectSettings)}async reload(){await this.writeQueue;const e=d.tryLoadFromStorage(this.storage,"global");e.error?(this.globalSettingsLoadError=e.error,this.recordError("global",e.error)):(this.globalSettings=e.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();const t=d.tryLoadFromStorage(this.storage,"project",this.projectTrusted);t.error?(this.projectSettingsLoadError=t.error,this.recordError("project",t.error)):(this.projectSettings=t.settings,this.projectSettingsLoadError=null),this.settings=h(this.globalSettings,this.projectSettings)}applyOverrides(e){this.settings=h(this.settings,e)}markModified(e,t){this.modifiedFields.add(e),t&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(t))}markProjectModified(e,t){this.modifiedProjectFields.add(e),t&&(this.modifiedProjectNestedFields.has(e)||this.modifiedProjectNestedFields.set(e,new Set),this.modifiedProjectNestedFields.get(e).add(t))}assertProjectTrustedForWrite(){if(!this.projectTrusted)throw new Error("Project is not trusted; refusing to write project settings")}recordError(e,t){this.errors.push(S(e,t,this.settingsPaths[e]))}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,t){this.writeQueue=this.writeQueue.then(()=>{e==="project"&&this.assertProjectTrustedForWrite(),t(),this.clearModifiedScope(e)}).catch(s=>{this.recordError(e,s)})}cloneModifiedNestedFields(e){const t=new Map;for(const[s,i]of e.entries())t.set(s,new Set(i));return t}persistScopedSettings(e,t,s,i){this.storage.withLock(e,n=>{const o=n?d.migrateSettings(JSON.parse(P(n))):{},l={...o};for(const g of s){const c=t[g];if(i.has(g)&&typeof c=="object"&&c!==null){const E=i.get(g),w=o[g]??{},x=c,b={...w};for(const k of E)b[k]=x[k];l[g]=b}else l[g]=c}return JSON.stringify(l,null,2)})}save(){if(this.settings=h(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;const e=structuredClone(this.globalSettings),t=new Set(this.modifiedFields),s=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",e,t,s)})}saveProjectSettings(e){if(this.assertProjectTrustedForWrite(),this.projectSettings=structuredClone(e),this.settings=h(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;const t=structuredClone(this.projectSettings),s=new Set(this.modifiedProjectFields),i=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",t,s,i)})}updateProjectSettings(e,t){this.assertProjectTrustedForWrite();const s=structuredClone(this.projectSettings);t(s),this.markProjectModified(e),this.saveProjectSettings(s)}async flush(){await this.writeQueue}drainErrors(){const e=[...this.errors];return this.errors=[],e}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getSessionDir(){const e=this.settings.sessionDir;return e&&v(e)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,t){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=t,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getThemeSetting(){const e=this.settings.theme;if(typeof e=="string")return e}getTheme(){const e=this.getThemeSetting();return e?.includes("/")?void 0:e}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(e,t){return this.settings.modelThinkingLevels?.[`${e}/${t}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(e,t,s){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${e}/${t}`]=s,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(e,t){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${e}/${t}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??"auto"}setTransport(e){this.globalSettings.transport=e,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionTokenSetting(e,t){const s=this.settings.compaction,i=s?.[e];if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<0))throw new Error(`Invalid compaction.${e} setting: ${String(i)}. Expected a non-negative safe integer.`);const n=t?`${t.provider}/${t.id}`:void 0,o=n!==void 0?s?.modelOverrides?.[n]:void 0;if(o!==void 0&&!p(o))throw new Error(`Invalid compaction.modelOverrides["${n}"] setting: ${String(o)}. Expected an object.`);const l=o?.[e];if(l!==void 0&&(typeof l!="number"||!Number.isSafeInteger(l)||l<0))throw new Error(`Invalid compaction.modelOverrides["${n}"].${e} setting: ${String(l)}. Expected a non-negative safe integer.`);return l??i??$[e]}getCompactionReserveTokens(e){return this.getCompactionTokenSetting("reserveTokens",e)}getCompactionKeepRecentTokens(e){return this.getCompactionTokenSetting("keepRecentTokens",e)}getCompactionSettings(e){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(e),keepRecentTokens:this.getCompactionKeepRecentTokens(e),maxContextTokens:this.getCompactionMaxContextTokens()}}getCompactionMaxContextTokens(){const e=this.settings.compaction?.maxContextTokens;if(e===void 0)return U;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid compaction.maxContextTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??H,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??L}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return B;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid maxOutputTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getOutputTokenLimit(e){const t=this.getMaxOutputTokens();return t>0&&(e<=0||e>t)?t:e}getHttpIdleTimeoutMs(){return C(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??W}setHttpIdleTimeoutMs(e){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(e),this.markModified("httpIdleTimeoutMs"),this.save()}getCacheWarmingMode(){const e=this.globalSettings.cacheWarming;return e!==void 0&&q.includes(e)?e:"streaming"}setCacheWarmingMode(e){this.globalSettings.cacheWarming=e,this.markModified("cacheWarming"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getWebSocketConnectTimeoutMs(){return C(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!0}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??!1}getExternalEditorCommand(){const e=this.settings.externalEditor;if(typeof e=="string"&&e.trim()!=="")return e;const t=process.env.VISUAL||process.env.EDITOR;return t||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(e){this.globalSettings.showCacheMissNotices=e,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){const e=this.settings.shellPath;return e&&v(e)}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){const e=this.settings.quietStartup;return e===!1?!1:e==="header"?e:!0}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getDefaultProjectTrust(){const e=this.globalSettings.defaultProjectTrust;return e==="always"||e==="never"?e:"ask"}setDefaultProjectTrust(e){this.globalSettings.defaultProjectTrust=e,this.markModified("defaultProjectTrust"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}getShellEnvironmentPolicy(){const e=this.globalSettings.shellEnvironment??{},t=[...e.exclude??[],...this.projectSettings.shellEnvironment?.exclude??[]];return{...e.inherit!==void 0?{inherit:e.inherit}:{},...t.length>0?{exclude:t}:{},...e.include!==void 0?{include:[...e.include]}:{},...e.set!==void 0?{set:{...e.set}}:{}}}getPermissionRuleSources(){return{...this.globalSettings.permissions?{user:structuredClone(this.globalSettings.permissions)}:{},...this.projectSettings.permissions?{project:structuredClone(this.projectSettings.permissions)}:{}}}getSandboxSettingsSources(){return{...this.globalSettings.sandbox?{global:structuredClone(this.globalSettings.sandbox)}:{},...this.projectSettings.sandbox?{project:structuredClone(this.projectSettings.sandbox)}:{}}}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(e){this.globalSettings.npmCommand=e?[...e]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!0}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??!0}setEnableInstallTelemetry(e){this.globalSettings.enableInstallTelemetry=e,this.markModified("enableInstallTelemetry"),this.save()}getEnableAnalytics(){return this.settings.enableAnalytics??!1}getTrackingId(){return this.settings.trackingId}setEnableAnalytics(e){this.globalSettings.enableAnalytics=e,this.markModified("enableAnalytics"),e&&!this.globalSettings.trackingId&&(this.globalSettings.trackingId=M(),this.markModified("trackingId")),this.save()}getOrCreateDeviceId(){return this.globalSettings.deviceId||(this.globalSettings.deviceId=M(),this.markModified("deviceId"),this.save()),this.globalSettings.deviceId}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){this.updateProjectSettings("packages",t=>{t.packages=e})}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){this.updateProjectSettings("extensions",t=>{t.extensions=e})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){this.updateProjectSettings("skills",t=>{t.skills=e})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){this.updateProjectSettings("prompts",t=>{t.prompts=e})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){this.updateProjectSettings("themes",t=>{t.themes=e})}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getFactoryEnabled(){return this.settings.factoryEnabled??!0}setFactoryEnabled(e){this.globalSettings.factoryEnabled=e,this.markModified("factoryEnabled"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){const e=this.settings.terminal,t=e?.images;return{...t==="kitty"||t==="iterm2"?{images:t}:t===!1?{images:null}:{},...typeof e?.trueColor=="boolean"?{trueColor:e.trueColor}:{},...typeof e?.hyperlinks=="boolean"?{hyperlinks:e.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){const e=this.settings.terminal?.imageWidthCells;return typeof e!="number"||!Number.isFinite(e)?60:Math.max(1,Math.floor(e))}setImageWidthCells(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(e)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:process.env.PI_CLEAR_ON_SHRINK==="1"}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=e,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":(this.settings.tuiMode==="regular"||this.settings.tuiMode,"regular")}setTuiMode(e){this.globalSettings.tuiMode=e,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":"transcript"}setFullscreenExitOutput(e){this.globalSettings.fullscreenExitOutput=e,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){const e=this.settings.fullscreenScrollbar;return e==="always"||e==="hidden"?e:"auto"}setFullscreenScrollbar(e){this.globalSettings.fullscreenScrollbar=e,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??!0}setFullscreenCopyOnSelect(e){this.globalSettings.fullscreenCopyOnSelect=e,this.markModified("fullscreenCopyOnSelect"),this.save()}getFullscreenWheelScrollLines(){const e=this.settings.fullscreenWheelScrollLines;return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.min(100,Math.floor(e))):"auto"}setFullscreenWheelScrollLines(e){this.globalSettings.fullscreenWheelScrollLines=e==="auto"?e:Math.max(1,Math.min(100,Math.floor(e))),this.markModified("fullscreenWheelScrollLines"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){const e=this.settings.defaultTools;if(e!==void 0)return Q(Array.isArray(e)?e.filter(t=>typeof t=="string"):[])}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){const e=this.settings.treeFilterMode;return e&&["default","no-tools","user-only","labeled-only","all"].includes(e)?e:"default"}setTreeFilterMode(e){this.globalSettings.treeFilterMode=e,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??process.env.PI_HARDWARE_CURSOR==="1"}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??1}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===1?1:0}setOutputPad(e){this.globalSettings.outputPad=e,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getMermaidRenderingMode(){const e=this.settings.markdown?.mermaid;return e==="off"||e==="final"?e:"streaming"}setMermaidRenderingMode(e){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=e,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(e){this.globalSettings.warnings={...e},this.markModified("warnings"),this.save()}}export{q as CACHE_WARMING_MODES,U as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,B as DEFAULT_MAX_OUTPUT_TOKENS,H as DEFAULT_MAX_RETRIES,V as DEFAULT_TOOL_NAMES,z as FileSettingsStorage,G as InMemorySettingsStorage,d as SettingsManager,X as applyToolModifiers,le as getToolListError,f as isToolModifier};
|
|
1
|
+
var F=Object.defineProperty;var a=(r,e)=>F(r,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as L}from"@earendil-works/pi-ai";import{randomUUID as M}from"crypto";import{existsSync as T,mkdirSync as I,readFileSync as O,writeFileSync as A}from"fs";import{dirname as D,join as u}from"path";import N from"proper-lockfile";import{CONFIG_DIR_NAME as y,getAgentDir as R}from"../config.js";import{normalizePath as v,resolvePath as m}from"../utils/paths.js";import{stripBom as P}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as W,parseHttpIdleTimeoutMs as $}from"./http-dispatcher.js";const _=8e4,U={reserveTokens:16384,keepRecentTokens:2e4,maxContextTokens:_},B=32e3,H=5,q=["off","streaming","idle"];function p(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}a(p,"isMergeableObject");function j(r,e){const t={...r};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const o=r[s];t[s]=p(o)&&p(i)?j(o,i):i}return t}a(j,"deepMergeObjects");const V=["read","bash","edit","write"];function f(r){return typeof r=="string"&&(r.startsWith("+")||r.startsWith("-"))}a(f,"isToolModifier");function le(r){const e=r.filter(f);if(e.length===0)return;if(e.length<r.length)return"tool names cannot be mixed with +name or -name entries";const t=e.find(s=>s.includes("*"));if(t)return`+name and -name entries take exact tool names, not patterns: ${t}`}a(le,"getToolListError");function X(r,e){const t=[...r];for(const s of e){if(!f(s))continue;const i=s.slice(1),o=t.indexOf(i);s.startsWith("+")&&o===-1&&i?t.push(i):s.startsWith("-")&&o!==-1&&t.splice(o,1)}return t}a(X,"applyToolModifiers");function K(r,e){return e===void 0?r:!Array.isArray(r)||!Array.isArray(e)||!e.every(f)?e:[...r,...e]}a(K,"mergeDefaultTools");function Q(r){const e=r.filter(t=>!f(t));return X(e.length>0||r.length===0?e:V,r)}a(Q,"resolveDefaultTools");function h(r,e){const t=j(r,e),s=K(r.defaultTools,e.defaultTools);return s===void 0?t:{...t,defaultTools:s}}a(h,"deepMergeSettings");function C(r,e){const t=$(r);if(t!==void 0)return t;if(r!==void 0)throw new Error(`Invalid ${e} setting: ${String(r)}`)}a(C,"parseTimeoutSetting");function S(r,e,t){return{scope:r,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}a(S,"toSettingsError");class z{static{a(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=m(e),i=m(t);this.globalSettingsPath=u(i,"settings.json"),this.projectSettingsPath=u(s,y,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let o=1;o<=10;o++)try{return N.lockSync(e,{realpath:!1})}catch(n){if((typeof n=="object"&&n!==null&&"code"in n?String(n.code):void 0)!=="ELOCKED"||o===10)throw n;i=n;const g=Date.now();for(;Date.now()-g<20;);}throw i??new Error("Failed to acquire settings lock")}withLock(e,t){const s=e==="global"?this.globalSettingsPath:this.projectSettingsPath,i=D(s);let o;try{const n=T(s);n&&(o=this.acquireLockSyncWithRetry(s));const l=n?O(s,"utf-8"):void 0,g=t(l);g!==void 0&&(T(i)||I(i,{recursive:!0}),o||(o=this.acquireLockSyncWithRetry(s)),A(s,g,"utf-8"))}finally{o&&o()}}}class G{static{a(this,"InMemorySettingsStorage")}global;project;withLock(e,t){const s=e==="global"?this.global:this.project,i=t(s);i!==void 0&&(e==="global"?this.global=i:this.project=i)}}class d{static{a(this,"SettingsManager")}storage;globalSettings;projectSettings;settings;projectTrusted;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(e,t,s,i=null,o=null,n=[],l=!0,g={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=l,this.globalSettingsLoadError=i,this.projectSettingsLoadError=o,this.errors=[...n],this.settingsPaths=g,this.settings=h(this.globalSettings,this.projectSettings)}static create(e,t=R(),s={}){const i=m(e),o=m(t),n=new z(i,o);return d.fromStorageWithPaths(n,s,{global:u(o,"settings.json"),project:u(i,y,"settings.json")})}static fromStorage(e,t={}){return d.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,o=d.tryLoadFromStorage(e,"global"),n=d.tryLoadFromStorage(e,"project",i),l=[];return o.error&&l.push(S("global",o.error,s.global)),n.error&&l.push(S("project",n.error,s.project)),new d(e,o.settings,n.settings,o.error,n.error,l,i,s)}static inMemory(e={},t={}){const s=new G,i=d.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),d.fromStorage(s,t)}static loadFromStorage(e,t,s=!0){if(t==="project"&&!s)return{};let i;if(e.withLock(t,n=>{i=n}),!i)return{};const o=JSON.parse(P(i));return d.migrateSettings(o)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:d.loadFromStorage(e,t,s),error:null}}catch(i){return{settings:{},error:i}}}static migrateSettings(e){if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),!("transport"in e)&&typeof e.websockets=="boolean"&&(e.transport=e.websockets?"websocket":"sse",delete e.websockets),"skills"in e&&typeof e.skills=="object"&&e.skills!==null&&!Array.isArray(e.skills)){const t=e.skills;t.enableSkillCommands!==void 0&&e.enableSkillCommands===void 0&&(e.enableSkillCommands=t.enableSkillCommands),Array.isArray(t.customDirectories)&&t.customDirectories.length>0?e.skills=t.customDirectories:delete e.skills}if("retry"in e&&typeof e.retry=="object"&&e.retry!==null&&!Array.isArray(e.retry)){const t=e.retry,s=typeof t.provider=="object"&&t.provider!==null?t.provider:void 0;typeof t.maxDelayMs=="number"&&(s?.maxRetryDelayMs===void 0||s?.maxRetryDelayMs===null)&&(t.provider={...s??{},maxRetryDelayMs:t.maxDelayMs}),delete t.maxDelayMs}return e}getSettings(){return structuredClone(this.settings)}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}isProjectTrusted(){return this.projectTrusted}setProjectTrusted(e){if(this.projectTrusted===e)return;if(this.projectTrusted=e,this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear(),!e){this.projectSettings={},this.projectSettingsLoadError=null,this.settings=h(this.globalSettings,this.projectSettings);return}const t=d.tryLoadFromStorage(this.storage,"project",e);this.projectSettings=t.settings,this.projectSettingsLoadError=t.error,t.error&&this.recordError("project",t.error),this.settings=h(this.globalSettings,this.projectSettings)}async reload(){await this.writeQueue;const e=d.tryLoadFromStorage(this.storage,"global");e.error?(this.globalSettingsLoadError=e.error,this.recordError("global",e.error)):(this.globalSettings=e.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();const t=d.tryLoadFromStorage(this.storage,"project",this.projectTrusted);t.error?(this.projectSettingsLoadError=t.error,this.recordError("project",t.error)):(this.projectSettings=t.settings,this.projectSettingsLoadError=null),this.settings=h(this.globalSettings,this.projectSettings)}applyOverrides(e){this.settings=h(this.settings,e)}markModified(e,t){this.modifiedFields.add(e),t&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(t))}markProjectModified(e,t){this.modifiedProjectFields.add(e),t&&(this.modifiedProjectNestedFields.has(e)||this.modifiedProjectNestedFields.set(e,new Set),this.modifiedProjectNestedFields.get(e).add(t))}assertProjectTrustedForWrite(){if(!this.projectTrusted)throw new Error("Project is not trusted; refusing to write project settings")}recordError(e,t){this.errors.push(S(e,t,this.settingsPaths[e]))}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,t){this.writeQueue=this.writeQueue.then(()=>{e==="project"&&this.assertProjectTrustedForWrite(),t(),this.clearModifiedScope(e)}).catch(s=>{this.recordError(e,s)})}cloneModifiedNestedFields(e){const t=new Map;for(const[s,i]of e.entries())t.set(s,new Set(i));return t}persistScopedSettings(e,t,s,i){this.storage.withLock(e,o=>{const n=o?d.migrateSettings(JSON.parse(P(o))):{},l={...n};for(const g of s){const c=t[g];if(i.has(g)&&typeof c=="object"&&c!==null){const E=i.get(g),w=n[g]??{},x=c,b={...w};for(const k of E)b[k]=x[k];l[g]=b}else l[g]=c}return JSON.stringify(l,null,2)})}save(){if(this.settings=h(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;const e=structuredClone(this.globalSettings),t=new Set(this.modifiedFields),s=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",e,t,s)})}saveProjectSettings(e){if(this.assertProjectTrustedForWrite(),this.projectSettings=structuredClone(e),this.settings=h(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;const t=structuredClone(this.projectSettings),s=new Set(this.modifiedProjectFields),i=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",t,s,i)})}updateProjectSettings(e,t){this.assertProjectTrustedForWrite();const s=structuredClone(this.projectSettings);t(s),this.markProjectModified(e),this.saveProjectSettings(s)}async flush(){await this.writeQueue}drainErrors(){const e=[...this.errors];return this.errors=[],e}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getSessionDir(){const e=this.settings.sessionDir;return e&&v(e)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,t){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=t,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getThemeSetting(){const e=this.settings.theme;if(typeof e=="string")return e}getTheme(){const e=this.getThemeSetting();return e?.includes("/")?void 0:e}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(e,t){return this.settings.modelThinkingLevels?.[`${e}/${t}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(e,t,s){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${e}/${t}`]=s,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(e,t){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${e}/${t}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??"auto"}setTransport(e){this.globalSettings.transport=e,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionTokenSetting(e,t){const s=this.settings.compaction,i=s?.[e];if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<0))throw new Error(`Invalid compaction.${e} setting: ${String(i)}. Expected a non-negative safe integer.`);const o=t?`${t.provider}/${t.id}`:void 0,n=o!==void 0?s?.modelOverrides?.[o]:void 0;if(n!==void 0&&!p(n))throw new Error(`Invalid compaction.modelOverrides["${o}"] setting: ${String(n)}. Expected an object.`);const l=n?.[e];if(l!==void 0&&(typeof l!="number"||!Number.isSafeInteger(l)||l<0))throw new Error(`Invalid compaction.modelOverrides["${o}"].${e} setting: ${String(l)}. Expected a non-negative safe integer.`);return l??i??U[e]}getCompactionReserveTokens(e){return this.getCompactionTokenSetting("reserveTokens",e)}getCompactionKeepRecentTokens(e){return this.getCompactionTokenSetting("keepRecentTokens",e)}getCompactionSettings(e){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(e),keepRecentTokens:this.getCompactionKeepRecentTokens(e),maxContextTokens:this.getCompactionMaxContextTokens(e),pruneToolOutputs:this.getCompactionPruneToolOutputs()}}getCompactionMaxContextTokens(e){return this.getCompactionTokenSetting("maxContextTokens",e)}getCompactionPruneToolOutputs(){const e=this.settings.compaction?.pruneToolOutputs;if(e!==void 0&&typeof e!="boolean")throw new Error(`Invalid compaction.pruneToolOutputs setting: ${String(e)}. Expected a boolean.`);return e??!0}getCompactionSummaryModel(){const e=this.settings.compaction?.summaryModel;if(e===void 0||e==="")return;const t=typeof e=="string"?e.indexOf("/"):-1;if(typeof e!="string"||t<=0||t===e.length-1)throw new Error(`Invalid compaction.summaryModel setting: ${String(e)}. Expected "provider/modelId".`);return{provider:e.slice(0,t),modelId:e.slice(t+1)}}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??H,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??L}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return B;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid maxOutputTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getOutputTokenLimit(e){const t=this.getMaxOutputTokens();return t>0&&(e<=0||e>t)?t:e}getHttpIdleTimeoutMs(){return C(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??W}setHttpIdleTimeoutMs(e){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(e),this.markModified("httpIdleTimeoutMs"),this.save()}getCacheWarmingMode(){const e=this.globalSettings.cacheWarming;return e!==void 0&&q.includes(e)?e:"streaming"}setCacheWarmingMode(e){this.globalSettings.cacheWarming=e,this.markModified("cacheWarming"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getWebSocketConnectTimeoutMs(){return C(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!0}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??!1}getExternalEditorCommand(){const e=this.settings.externalEditor;if(typeof e=="string"&&e.trim()!=="")return e;const t=process.env.VISUAL||process.env.EDITOR;return t||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(e){this.globalSettings.showCacheMissNotices=e,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){const e=this.settings.shellPath;return e&&v(e)}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){const e=this.settings.quietStartup;return e===!1?!1:e==="header"?e:!0}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getDefaultProjectTrust(){const e=this.globalSettings.defaultProjectTrust;return e==="always"||e==="never"?e:"ask"}setDefaultProjectTrust(e){this.globalSettings.defaultProjectTrust=e,this.markModified("defaultProjectTrust"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}getShellEnvironmentPolicy(){const e=this.globalSettings.shellEnvironment??{},t=[...e.exclude??[],...this.projectSettings.shellEnvironment?.exclude??[]];return{...e.inherit!==void 0?{inherit:e.inherit}:{},...t.length>0?{exclude:t}:{},...e.include!==void 0?{include:[...e.include]}:{},...e.set!==void 0?{set:{...e.set}}:{}}}getPermissionRuleSources(){return{...this.globalSettings.permissions?{user:structuredClone(this.globalSettings.permissions)}:{},...this.projectSettings.permissions?{project:structuredClone(this.projectSettings.permissions)}:{}}}getSandboxSettingsSources(){return{...this.globalSettings.sandbox?{global:structuredClone(this.globalSettings.sandbox)}:{},...this.projectSettings.sandbox?{project:structuredClone(this.projectSettings.sandbox)}:{}}}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(e){this.globalSettings.npmCommand=e?[...e]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!0}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??!0}setEnableInstallTelemetry(e){this.globalSettings.enableInstallTelemetry=e,this.markModified("enableInstallTelemetry"),this.save()}getEnableAnalytics(){return this.settings.enableAnalytics??!1}getTrackingId(){return this.settings.trackingId}setEnableAnalytics(e){this.globalSettings.enableAnalytics=e,this.markModified("enableAnalytics"),e&&!this.globalSettings.trackingId&&(this.globalSettings.trackingId=M(),this.markModified("trackingId")),this.save()}getOrCreateDeviceId(){return this.globalSettings.deviceId||(this.globalSettings.deviceId=M(),this.markModified("deviceId"),this.save()),this.globalSettings.deviceId}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){this.updateProjectSettings("packages",t=>{t.packages=e})}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){this.updateProjectSettings("extensions",t=>{t.extensions=e})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){this.updateProjectSettings("skills",t=>{t.skills=e})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){this.updateProjectSettings("prompts",t=>{t.prompts=e})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){this.updateProjectSettings("themes",t=>{t.themes=e})}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getFactoryEnabled(){return this.settings.factoryEnabled??!0}setFactoryEnabled(e){this.globalSettings.factoryEnabled=e,this.markModified("factoryEnabled"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){const e=this.settings.terminal,t=e?.images;return{...t==="kitty"||t==="iterm2"?{images:t}:t===!1?{images:null}:{},...typeof e?.trueColor=="boolean"?{trueColor:e.trueColor}:{},...typeof e?.hyperlinks=="boolean"?{hyperlinks:e.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){const e=this.settings.terminal?.imageWidthCells;return typeof e!="number"||!Number.isFinite(e)?60:Math.max(1,Math.floor(e))}setImageWidthCells(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(e)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:process.env.PI_CLEAR_ON_SHRINK==="1"}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=e,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":(this.settings.tuiMode==="regular"||this.settings.tuiMode,"regular")}setTuiMode(e){this.globalSettings.tuiMode=e,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":"transcript"}setFullscreenExitOutput(e){this.globalSettings.fullscreenExitOutput=e,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){const e=this.settings.fullscreenScrollbar;return e==="always"||e==="hidden"?e:"auto"}setFullscreenScrollbar(e){this.globalSettings.fullscreenScrollbar=e,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??!0}setFullscreenCopyOnSelect(e){this.globalSettings.fullscreenCopyOnSelect=e,this.markModified("fullscreenCopyOnSelect"),this.save()}getFullscreenWheelScrollLines(){const e=this.settings.fullscreenWheelScrollLines;return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.min(100,Math.floor(e))):"auto"}setFullscreenWheelScrollLines(e){this.globalSettings.fullscreenWheelScrollLines=e==="auto"?e:Math.max(1,Math.min(100,Math.floor(e))),this.markModified("fullscreenWheelScrollLines"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){const e=this.settings.defaultTools;if(e!==void 0)return Q(Array.isArray(e)?e.filter(t=>typeof t=="string"):[])}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){const e=this.settings.treeFilterMode;return e&&["default","no-tools","user-only","labeled-only","all"].includes(e)?e:"default"}setTreeFilterMode(e){this.globalSettings.treeFilterMode=e,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??process.env.PI_HARDWARE_CURSOR==="1"}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??1}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===1?1:0}setOutputPad(e){this.globalSettings.outputPad=e,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getMermaidRenderingMode(){const e=this.settings.markdown?.mermaid;return e==="off"||e==="final"?e:"streaming"}setMermaidRenderingMode(e){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=e,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(e){this.globalSettings.warnings={...e},this.markModified("warnings"),this.save()}}export{q as CACHE_WARMING_MODES,_ as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,B as DEFAULT_MAX_OUTPUT_TOKENS,H as DEFAULT_MAX_RETRIES,V as DEFAULT_TOOL_NAMES,z as FileSettingsStorage,G as InMemorySettingsStorage,d as SettingsManager,X as applyToolModifiers,le as getToolListError,f as isToolModifier};
|
|
@@ -7,6 +7,7 @@ export interface SourceInfo {
|
|
|
7
7
|
scope: SourceScope;
|
|
8
8
|
origin: SourceOrigin;
|
|
9
9
|
baseDir?: string;
|
|
10
|
+
packageName?: string;
|
|
10
11
|
}
|
|
11
12
|
export declare const BUILTIN_PATH_PREFIX = "builtin:";
|
|
12
13
|
export declare function getSyntheticPathSource(path: string): string | undefined;
|
package/dist/core/source-info.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var o=Object.defineProperty;var n=(e,r)=>o(e,"name",{value:r,configurable:!0});import{readFileSync as s}from"node:fs";import{join as u}from"node:path";const c="builtin:";function h(e){if(e.startsWith(c))return"builtin";if(e.startsWith("<")&&e.endsWith(">"))return e.slice(1,-1).split(":")[0]||"temporary"}n(h,"getSyntheticPathSource");function l(e){return e.startsWith(c)||e.startsWith("<")}n(l,"isSyntheticPath");const i=new Map;function a(e){if(!i.has(e)){let r;try{const t=JSON.parse(s(u(e,"package.json"),"utf8"));r=typeof t.name=="string"?t.name:void 0}catch{r=void 0}i.set(e,r)}return i.get(e)}n(a,"packageNameAt");function y(e,r){const t=r.packageRoot?a(r.packageRoot):void 0;return{path:e,source:r.source,scope:r.scope,origin:r.origin,baseDir:r.baseDir,...t?{packageName:t}:{}}}n(y,"createSourceInfo");function S(e,r){return{path:e,source:r.source,scope:r.scope??"temporary",origin:r.origin??"top-level",baseDir:r.baseDir}}n(S,"createSyntheticSourceInfo");export{c as BUILTIN_PATH_PREFIX,y as createSourceInfo,S as createSyntheticSourceInfo,h as getSyntheticPathSource,l as isSyntheticPath};
|
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
var
|
|
2
|
-
${
|
|
1
|
+
var P=Object.defineProperty;var c=(e,t)=>P(e,"name",{value:t,configurable:!0});import{join as v}from"node:path";import{getSystemMessageText as E}from"@earendil-works/pi-ai";import{APP_NAME as $,APP_TITLE as h,getDalDocsPath as j,getDocsPath as O,getExamplesPath as _,getReadmePath as I,IS_WHITE_LABEL_BUILD as T}from"../config.js";import{describeGitState as N}from"./git-state.js";import{formatSkillsForPrompt as A}from"./skills.js";const D=/^[a-z][a-z0-9_-]*$/;function M(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],hiddenTools:[...e.hiddenTools??[]],toolSnippets:{...e.toolSnippets??{}},toolGuidelines:Object.fromEntries(Object.entries(e.toolGuidelines??{}).map(([t,n])=>[t,[...n]])),promptGuidelines:[...e.promptGuidelines??[]],appendSystemPrompt:e.appendSystemPrompt??"",sections:{...e.sections??{}},cwd:e.cwd,gitState:e.gitState,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}c(M,"normalizeBuildSystemPromptOptions");function R(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:n})=>`<project_instructions path="${t}">
|
|
2
|
+
${n}
|
|
3
3
|
</project_instructions>`)].join(`
|
|
4
4
|
|
|
5
|
-
`)}
|
|
6
|
-
`)}
|
|
7
|
-
`):"(none)";
|
|
5
|
+
`)}c(R,"renderProjectContext");function G(e,t,n){const i=[],d=new Set,o=c(l=>{const m=l.trim();!m||d.has(m)||(d.add(m),i.push(m))},"addRule"),p=e.includes("bash"),f=e.includes("powershell"),a=e.includes("grep"),g=e.includes("find"),y=e.includes("ls");(p||f)&&!a&&!g&&!y&&o(p&&f?"Use bash or PowerShell for file operations like listing, searching, and finding files":f?"Use PowerShell for file operations like listing, searching, and finding files":"Use bash for file operations like ls, rg, find");for(const l of e)for(const m of t[l]??[])o(m);for(const l of n)o(l);return e.length>0&&(o("When several tool calls do not depend on each other's results (reading multiple files, independent searches or commands), make them all in one response; they run in parallel. Each extra round trip costs the user seconds"),o("Answer as soon as you can: once you know enough, give the answer or your best current conclusion, then offer to dig further. Do not investigate everything before saying anything"),o("During longer work, tell the user every few tool rounds, in a sentence or two, what you found and what you will check next"),o("If you cannot tell which product, project or file the user means, ask instead of searching widely on a guess. When the user writes while you are working, respond to that message first: it may change the direction"),o("In a small project, read every source file the task touches in one response (parallel reads, or one command that prints them) instead of exploring one file per round"),o("Verify the behaviours the request names and the edge cases it implies; do not write exhaustive or randomized test sweeps unless asked"),o("Before reporting done, run every code path you added at least once, including backward-compatibility, fallback and error branches: a branch that never ran is not verified")),o("Be concise in your responses"),o("Show file paths clearly when working with files"),i.map(l=>`- ${l}`).join(`
|
|
6
|
+
`)}c(G,"buildRules");function L(e){const t=M(e),{customPrompt:n,selectedTools:i,hiddenTools:d,toolSnippets:o,toolGuidelines:p,promptGuidelines:f,appendSystemPrompt:a,sections:g,cwd:y,contextFiles:l,skills:m}=t;for(const s of Object.keys(g))if(!D.test(s)||s==="preamble")throw new Error(`Invalid system prompt section name: ${s}`);const S=i.filter(s=>!d.includes(s)),r={};if(n)r.preamble=n;else{r.preamble=`You are an expert coding assistant operating inside ${h} (${$}). You help users by reading files, executing commands, editing code, and writing new files.`;const s=S.filter(b=>!!o[b]),u=s.length>0?s.map(b=>`- ${b}: ${o[b]}`).join(`
|
|
7
|
+
`):"(none)";r.tools=`${u}
|
|
8
8
|
|
|
9
|
-
In addition to the tools above, you may have access to other custom tools depending on the project.`,
|
|
9
|
+
In addition to the tools above, you may have access to other custom tools depending on the project.`,r.rules=G(S,p,f),r.docs=W()}a&&(r.addendum=a),l.length>0&&(r.project_context=R(l));const k=["read","bash"],w=k.find(s=>S.includes(s))??(k.some(s=>i.includes(s))?"indirect":void 0);if(w&&m.length>0){const s=A(m,w).trim();s&&(r.skills=s)}r.cwd=y.replace(/\\/g,"/"),t.gitState&&!g.git_state&&(r.git=N(y));for(const[s,u]of Object.entries(g))u&&(r[s]=u);const x={preamble:r.preamble};for(const[s,u]of Object.entries(r))s!=="preamble"&&(x[s]=`<${s}>
|
|
10
10
|
${u}
|
|
11
|
-
</${s}>`);return
|
|
12
|
-
${
|
|
11
|
+
</${s}>`);return x}c(L,"buildSystemPromptSections");const F="cwd",U="Environment of this session, part of the system prompt. Later updates to these sections arrive as system prompt updates.";function H(e){const t=e[0];if(!t||t.role!=="system"||!t.sections)return e;const n=Object.keys(t.sections),i=n.indexOf(F);if(i===-1)return e;const d=n.slice(i).map(a=>t.sections?.[a]).filter(a=>typeof a=="string"&&a.length>0),o=Object.fromEntries(n.slice(0,i).map(a=>[a,t.sections?.[a]??null])),p={...t,sections:o};if(d.length===0)return[p,...e.slice(1)];const f={role:"user",content:[{type:"text",text:`<session_environment>
|
|
12
|
+
${U}
|
|
13
13
|
|
|
14
14
|
${d.join(`
|
|
15
15
|
|
|
16
16
|
`)}
|
|
17
|
-
</session_environment>`}],timestamp:t.timestamp};return[p,f,...e.slice(1)]}
|
|
17
|
+
</session_environment>`}],timestamp:t.timestamp};return[p,f,...e.slice(1)]}c(H,"moveSessionEnvironmentOutOfSystemPrompt");function B(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:L(e)}}c(B,"buildSystemPromptState");function J(e){return E({role:"system",...B(e),timestamp:0})}c(J,"buildSystemPrompt");function Q(e,t){const n={};for(const[i,d]of Object.entries(t))e[i]!==d&&(n[i]=d);for(const i of Object.keys(e))t[i]===void 0&&(n[i]=null);return Object.keys(n).length>0?n:void 0}c(Q,"diffSystemPromptSections");function W(){if(T){const e=j();return`${h} documentation (read only when the user asks about ${h} itself: its commands, settings, skills, prompt templates, extensions, packages, themes or keybindings):
|
|
18
18
|
- Start with: ${v(e,"README.md")}
|
|
19
19
|
- Topics, in the same folder: skills.md, prompt-templates.md, extensions.md, packages.md, themes.md, keybindings.md, settings.md
|
|
20
20
|
- Resolve those file names under ${e}, not the current working directory
|
|
21
21
|
- Read the relevant file completely before answering or implementing, and describe the product as ${h}`}return`${h} documentation (read only when the user asks about ${h} itself, its SDK, extensions, themes, skills, or TUI):
|
|
22
|
-
- Main documentation: ${
|
|
22
|
+
- Main documentation: ${I()}
|
|
23
23
|
- Additional docs: ${O()}
|
|
24
|
-
- Examples: ${
|
|
24
|
+
- Examples: ${_()} (extensions, custom tools, SDK)
|
|
25
25
|
- When reading these docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory
|
|
26
26
|
- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), packages (docs/packages.md), environment variables (docs/environment-variables.md), MCP servers (docs/mcp.md), codemode scripts and non-LLM models such as classifiers and image models (docs/codemode.md)
|
|
27
27
|
- When working on these topics, read the docs and examples, and follow .md cross-references before implementing
|
|
28
|
-
- Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}
|
|
28
|
+
- Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}c(W,"buildDocumentationSection");export{F as SESSION_ENVIRONMENT_FIRST_SECTION,J as buildSystemPrompt,L as buildSystemPromptSections,B as buildSystemPromptState,Q as diffSystemPromptSections,H as moveSessionEnvironmentOutOfSystemPrompt,M as normalizeBuildSystemPromptOptions};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { type AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import { type ChildProcess } from "child_process";
|
|
2
3
|
import { type Static, Type } from "typebox";
|
|
3
4
|
import { type ShellConfig } from "../../utils/shell.ts";
|
|
5
|
+
import type { BackgroundProcessInfo, BackgroundProcessManager } from "../background-processes.ts";
|
|
4
6
|
import type { ToolDefinition } from "../extensions/types.ts";
|
|
5
7
|
import { type SandboxRunDetails, type ShellSandbox } from "../sandbox/shell-sandbox.ts";
|
|
6
8
|
import { type TruncationResult } from "./truncate.ts";
|
|
@@ -25,6 +27,7 @@ declare const bashOutputSchema: Type.TObject<{
|
|
|
25
27
|
truncated: Type.TBoolean;
|
|
26
28
|
full_output_path: Type.TOptional<Type.TString>;
|
|
27
29
|
exit_code: Type.TNumber;
|
|
30
|
+
background_id: Type.TOptional<Type.TString>;
|
|
28
31
|
wall_time_seconds: Type.TNumber;
|
|
29
32
|
}>;
|
|
30
33
|
export type BashToolOutput = Static<typeof bashOutputSchema>;
|
|
@@ -32,6 +35,7 @@ export interface BashToolDetails {
|
|
|
32
35
|
truncation?: TruncationResult;
|
|
33
36
|
fullOutputPath?: string;
|
|
34
37
|
sandbox?: SandboxRunDetails;
|
|
38
|
+
background?: BackgroundProcessInfo;
|
|
35
39
|
}
|
|
36
40
|
export interface BashOperations {
|
|
37
41
|
exec: (command: string, cwd: string, options: {
|
|
@@ -39,8 +43,10 @@ export interface BashOperations {
|
|
|
39
43
|
signal?: AbortSignal;
|
|
40
44
|
timeout?: number;
|
|
41
45
|
env?: NodeJS.ProcessEnv;
|
|
46
|
+
yieldTo?: (child: ChildProcess) => boolean;
|
|
42
47
|
}) => Promise<{
|
|
43
48
|
exitCode: number | null;
|
|
49
|
+
yielded?: boolean;
|
|
44
50
|
}>;
|
|
45
51
|
}
|
|
46
52
|
export declare function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations;
|
|
@@ -68,6 +74,7 @@ export interface BashToolOptions {
|
|
|
68
74
|
exposeSessionEnvironment?: boolean;
|
|
69
75
|
spawnHook?: BashSpawnHook;
|
|
70
76
|
sandbox?: ShellSandbox;
|
|
77
|
+
background?: BackgroundProcessManager;
|
|
71
78
|
}
|
|
72
79
|
export type BashRenderState = {
|
|
73
80
|
startedAt: number | undefined;
|
package/dist/core/tools/bash.js
CHANGED
|
@@ -1,21 +1,19 @@
|
|
|
1
|
-
var
|
|
2
|
-
Cannot execute ${t} commands.`)}const
|
|
3
|
-
${
|
|
1
|
+
var _e=Object.defineProperty;var r=(t,e)=>_e(t,"name",{value:e,configurable:!0});import{constants as ye}from"node:fs";import{access as ge}from"node:fs/promises";import{constants as $e}from"node:os";import{ToolExecutionError as Le}from"@earendil-works/pi-agent-core";import{Container as Ce,Text as G,truncateToWidth as Te}from"@earendil-works/pi-tui";import{spawn as Pe}from"child_process";import{Type as d}from"typebox";import{fill as R,t as I}from"../../dal/i18n.js";import{keyHint as Ie}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as ve}from"../../modes/interactive/components/visual-truncate.js";import{theme as x}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as De}from"../../utils/child-process.js";import{writeOutputFile as Ae}from"../../utils/output-files.js";import{getShellConfig as ae,getShellEnv as de,killProcessTree as le,trackDetachedChildPid as ke,untrackDetachedChildPid as Fe}from"../../utils/shell.js";import{describeDenialForModel as Me}from"../sandbox/denial.js";import{getProcessShellSandbox as Ne}from"../sandbox/shell-sandbox.js";import{isReadOnlyBashCommand as Be}from"./bash-read-only.js";import{OutputAccumulator as Re}from"./output-accumulator.js";import{condenseShellOutput as Ue,outputCondenseDisabled as je}from"./output-condense.js";import{countOutputLines as Ge,formatCollapsedSummary as We,getTextOutput as ue,invalidArgText as He,str as ce,truncateDisplay as Ve}from"./render-utils.js";import{wrapToolDefinition as Xe}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as Ye,formatSize as Ke,SHELL_OUTPUT_MAX_CHARS as ee,truncateHeadTail as qe}from"./truncate.js";const me=2147483647,pe=1024*1024,ze=8*1024*1024,Je=me/1e3,te=12e4,ne=30;function Qe(t){if(t===void 0)return te;if(!Number.isFinite(t)||t<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const e=t*1e3;if(e>me)throw new Error(`Invalid timeout: maximum is ${Je} seconds`);return e}r(Qe,"resolveTimeoutMs");const fe=d.Object({command:d.String({description:"Shell command to execute"}),description:d.String({description:`What it does and why, 3-10 words in the user's language, shown instead of the command: "Find hardcoded key names", not "run grep"`}),timeout:d.Optional(d.Number({description:"Seconds to wait for the command (default in the tool description). Raise it for long builds."}))}),Ze=d.Optional(d.Object({mode:d.Union([d.Literal("allow"),d.Literal("unsandboxed")],{description:'"allow": stay sandboxed with the domains/paths below; "unsandboxed": run outside the sandbox'}),justification:d.String({description:"Why, in one sentence for the user, who must approve it"}),allow_domains:d.Optional(d.Array(d.String(),{description:"e.g. registry.npmjs.org"})),allow_write:d.Optional(d.Array(d.String(),{description:"Paths to make writable"}))},{description:"Only after the sandbox blocked this command: the access it needs. Never pre-emptively."})),et=d.Object({...fe.properties,sandbox_escalation:Ze}),he={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect DAL_* environment variables for current model and session details."]},tt=d.Object({output:d.String({description:"Combined stdout and stderr, possibly truncated"}),truncated:d.Boolean(),full_output_path:d.Optional(d.String({description:"Full output, when truncated"})),exit_code:d.Number({description:"-1 while the command runs in the background"}),background_id:d.Optional(d.String({description:"Background process id, when it is still running"})),wall_time_seconds:d.Number()});function nt(t,e){return{exec:r(async(n,o,{onData:l,signal:i,timeout:_,env:w,yieldTo:s})=>{const y=Qe(_);if(i?.aborted)throw new Error("aborted");const S=e();try{await ge(o,ye.F_OK)}catch{throw new Error(`Working directory does not exist: ${o}
|
|
2
|
+
Cannot execute ${t} commands.`)}const b=S.commandTransport==="stdin",u=Pe(S.shell,b?S.args:[...S.args,n],{cwd:o,detached:process.platform!=="win32",env:w??de(),stdio:[b?"pipe":"ignore","pipe","pipe"],windowsHide:!0});b&&(u.stdin?.on("error",()=>{}),u.stdin?.end(n)),u.pid&&ke(u.pid);let a=!1,m=!1,h;const p=new Promise(A=>{h=r(()=>A("yielded"),"onYielded")});let f;const O=r(()=>{u.pid&&le(u.pid)},"onAbort");try{y!==void 0&&(f=setTimeout(()=>{if(s&&u.exitCode===null&&u.signalCode===null&&s(u)){m=!0,h?.();return}a=!0,u.pid&&le(u.pid)},y)),u.stdout?.on("data",l),u.stderr?.on("data",l),i&&(i.aborted?O():i.addEventListener("abort",O,{once:!0}));const A=De(u),U=await Promise.race([A,p]);if(U==="yielded")return A.catch(()=>{}),{exitCode:null,yielded:!0};const V=U;if(i?.aborted)throw new Error("aborted");if(a)throw new Error(`timeout:${(y??te)/1e3}`);const $=u.signalCode;return{exitCode:V??($?128+($e.signals[$]??0):1)}}finally{u.pid&&!m&&Fe(u.pid),f&&clearTimeout(f),i&&i.removeEventListener("abort",O)}},"exec")}}r(nt,"createLocalShellOperations");function ot(t){return nt("bash",()=>ae(t?.shellPath))}r(ot,"createLocalBashOperations");const oe=new Set;function Ut(t){return oe.add(t),()=>{oe.delete(t)}}r(Ut,"registerShellExecutionGuard");async function it(t){for(const e of oe){let n;try{n=await e(t)}catch(o){return`Command refused: the safety check could not run (${o instanceof Error?o.message:String(o)}).`}if(n!==void 0)return n}}r(it,"shellExecutionRefusal");const st=["SESSION_ID","SESSION_FILE","PROVIDER","MODEL","REASONING_LEVEL"];function rt(t,e,n,o,l){const i={...de()};if(delete i.PI_SESSION_ID,delete i.PI_SESSION_FILE,delete i.PI_PROVIDER,delete i.PI_MODEL,delete i.PI_REASONING_LEVEL,o&&l){const w=l.model;i.PI_SESSION_ID=l.sessionManager.getSessionId();const s=l.sessionManager.getSessionFile();s&&(i.PI_SESSION_FILE=s),w&&(i.PI_PROVIDER=w.provider,i.PI_MODEL=w.id),l.thinkingLevel&&(i.PI_REASONING_LEVEL=l.thinkingLevel)}for(const w of st){delete i[`DAL_${w}`];const s=i[`PI_${w}`];s!==void 0&&(i[`DAL_${w}`]=s)}const _={command:t,cwd:e,env:i};return n?n(_):_}r(rt,"resolveSpawnContext");const at=5,dt=100;class lt extends Ce{static{r(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function ut(t){const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const n=Math.floor(e),o=Math.floor(n/60),l=n%60;return o<60?`${o}m ${l}s`:`${Math.floor(o/60)}h ${o%60}m ${l}s`}r(ut,"formatDuration");function ct(t,e,n=!1){const o=ce(t?.command),l=ce(t?.description)?.trim(),i=t?.timeout,_=i?x.fg("muted",R(I(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:i})):"";if(l){const s=x.fg("toolTitle",x.bold(l))+_;return!n||!o?s:`${s}
|
|
3
|
+
${x.fg("muted",` \u23BF ${e} ${o.trim()}`)}`}const w=o===null?He(x):o?x.fg("dim",Ve(o.replace(/\s+/g," ").trim(),42)):x.fg("dim","\u2026");return`${x.fg("toolTitle",x.bold(e))} ${w}${_}`}r(ct,"formatShellCall");function mt(t,e,n,o,l,i,_,w){const s=t.state;t.clear();const y=pt(n,l,i,w);if(!n.expanded&&!_){const a=ue(e,o),m=Ge(a),h=[];m>0&&h.push(R(I("{count} \u884C"),{count:m})),y&&h.push(y);const p=We(x,h);p&&t.addChild(new G(p,0,0));return}let S=ue(e,o).trim();const b=e.details?.truncation,u=e.details?.fullOutputPath;if(!n.isPartial&&b?.truncated&&u&&S.endsWith("]")){const a=S.lastIndexOf(`
|
|
4
4
|
|
|
5
|
-
[`);
|
|
6
|
-
`).map(
|
|
7
|
-
`);
|
|
8
|
-
${
|
|
9
|
-
${
|
|
10
|
-
${
|
|
11
|
-
${
|
|
5
|
+
[`);a!==-1&&S.slice(a).includes(u)&&(S=S.slice(0,a).trimEnd())}if(S){const a=S.split(`
|
|
6
|
+
`).map(m=>x.fg("toolOutput",m)).join(`
|
|
7
|
+
`);n.expanded?t.addChild(new G(`
|
|
8
|
+
${a}`,0,0)):t.addChild({render:r(m=>{if(s.cachedLines===void 0||s.cachedWidth!==m){const h=ve(a,at,m);s.cachedLines=h.visualLines,s.cachedSkipped=h.skippedCount,s.cachedWidth=m}if(s.cachedSkipped&&s.cachedSkipped>0){const h=x.fg("muted",R(I("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:s.cachedSkipped}))+` ${Ie("app.tools.expand",I("\u5373\u53EF\u5C55\u5F00"))}${x.fg("muted",")")}`;return["",Te(h,m,"..."),...s.cachedLines??[]]}return["",...s.cachedLines??[]]},"render"),invalidate:r(()=>{s.cachedWidth=void 0,s.cachedLines=void 0,s.cachedSkipped=void 0},"invalidate")})}if(b?.truncated||u){const a=[];u&&a.push(R(I("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:u})),b?.truncated&&(b.truncatedBy==="lines"?a.push(R(I("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:b.outputLines,total:b.totalLines})):a.push(R(I("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:b.outputLines,limit:Ke(b.maxBytes??Ye)}))),t.addChild(new G(`
|
|
9
|
+
${x.fg("warning",`[${a.join(". ")}]`)}`,0,0))}y&&t.addChild(new G(`
|
|
10
|
+
${x.fg("muted",y)}`,0,0))}r(mt,"rebuildBashResultRenderComponent");function pt(t,e,n,o){let l;if(!t.isPartial&&o!==void 0)l=o;else if(e!==void 0)l=(n??Date.now())-e;else return;if(!(!t.isPartial&&l<100))return`${t.isPartial?I("\u5DF2\u8FD0\u884C"):I("\u8017\u65F6")} ${ut(l)}`}r(pt,"bashTimingLabel");function ft(t,e,n){const o=n?.operations??e.defaultOperations?.()??ot({shellPath:n?.shellPath}),l=n?.commandPrefix,i=n?.exposeSessionEnvironment??!0,_=n?.spawnHook,w=n?.sandbox,s=n?.operations===void 0,y=w?.describeForModel(),S=n?.background;let b=!1;const u=r(a=>`Execute a ${e.shellName} command in the current working directory; returns stdout and stderr. Long output is cut to its start and end (error lines kept) and the full output saved to a file named in the result. ${a?`A command still running after \`timeout\` seconds (default ${ne}) keeps running in the background: you get its id and the output so far, then use the process tool to poll or kill it.`:`A command still running after \`timeout\` seconds (default ${te/1e3}) is killed.`}${y?` ${y}`:""}`,"describe");return{name:e.name,label:e.label,description:u(!1),prepareLoadout:S&&s?a=>(b=a.declared.some(m=>m.name==="process"),b?{descriptions:{[e.name]:u(!0)}}:void 0):void 0,promptSnippet:e.promptSnippet,promptGuidelines:i&&e.promptGuidelines?[...e.promptGuidelines]:void 0,executionMode:"sequential",executionModeFor:e.readOnlyCommand&&!l?a=>e.readOnlyCommand?.(a?.command)?"parallel":void 0:void 0,parameters:w?.active?et:fe,outputSchema:tt,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(a,m,h,p,f){const{command:O,timeout:A}=m;p&&p({content:[],details:void 0});const U=await it({toolName:e.name,command:O,cwd:f?.cwd||t,sessionFile:f?.sessionManager?.getSessionFile()});if(U!==void 0)throw new Error(U);const V=l?`${l}
|
|
11
|
+
${O}`:O,$=rt(V,f?.cwd||t,_,i,f),X=w??(s?Ne():void 0);let L;if(X?.active){if(!e.sandboxShell)throw new Error(`Command refused: ${e.shellName} commands cannot run inside the OS sandbox yet, and the sandbox level is "${X.level}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);L=await X.prepare({command:$.command,cwd:$.cwd,shell:e.sandboxShell(n?.shellPath),shellKind:e.sandboxShellKind??"bash",env:$.env,toolCallId:a,toolName:e.name,escalation:m.sandbox_escalation,ctx:f,signal:h})}const T=new Re({tempFilePrefix:e.tempFilePrefix,maxBytes:ee});let W=!0,j,Y=!1,ie=0;const K=r(()=>{if(!p||!Y)return;Y=!1,ie=Date.now();const c=T.snapshot({persistIfTruncated:!0});p({content:[{type:"text",text:c.content||""}],details:{truncation:c.truncation.truncated?c.truncation:void 0,fullOutputPath:c.fullOutputPath}})},"emitOutputUpdate"),q=r(()=>{j&&(clearTimeout(j),j=void 0)},"clearUpdateTimer"),we=r(()=>{if(!p)return;Y=!0;const c=dt-(Date.now()-ie);if(c<=0){q(),K();return}j??=setTimeout(()=>{j=void 0,K()},c)},"scheduleOutputUpdate"),Se=r(c=>{W&&(T.append(c),we())},"handleData"),be=r(async()=>{W=!1,T.finish(),q(),K();const c=T.snapshot({persistIfTruncated:!0});return await T.closeTempFile(),c},"finishOutput"),z=r(async(c="(no output)")=>{const g=await be(),k=await T.readFullOutput(ze),C=je()?void 0:Ue(k.content),E=qe(C?.text??k.content,ee);let D=g.fullOutputPath;(E.truncated||C)&&!D&&(D=await Ae(e.tempFilePrefix,".log",k.content));let F=E.content||c,N;const B=g.truncation.totalLines;return E.truncated?(N={truncation:{content:E.content,truncated:!0,truncatedBy:"bytes",totalLines:B,totalBytes:g.truncation.totalBytes,outputLines:E.headLines+E.tailLines,outputBytes:Buffer.byteLength(E.content,"utf-8"),lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:B,maxBytes:ee},fullOutputPath:D},F+=`
|
|
12
12
|
|
|
13
|
-
[
|
|
13
|
+
[Truncated: first ${E.headLines} and last ${E.tailLines} of ${E.totalLines} lines shown${C?`, after condensing ${B} lines (${C.summary})`:""}; read more with read (offset/limit) or grep. Full output: ${D}]`):C&&(N={fullOutputPath:D},F+=`
|
|
14
14
|
|
|
15
|
-
[
|
|
15
|
+
[Condensed: ${C.summary}. Full output: ${D}]`),{text:F,details:N,snapshot:g}},"modelOutput"),M=r((c,g)=>`${c?`${c}
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
`:""}${g}`,"appendStatus"),se=performance.now();let v;const J=S&&s&&b?c=>{W=!1;try{return v=S.adopt({child:c,command:O,cwd:$.cwd,...L?{prepared:L}:{},...T.handOff()}),!0}catch{return W=!0,!1}}:void 0;try{let c;try{const P=await o.exec(L?.command??$.command,$.cwd,{onData:Se,signal:h,timeout:A??(J?ne:void 0),env:$.env,...J?{yieldTo:J}:{}});if(P.yielded&&v){const{text:H,details:Z}=await z(""),xe=A??ne,Ee=v.urls.length>0?` It printed ${v.urls.join(" ")}.`:"",Oe=`[Still running after ${xe}s, now in the background as ${v.id}.${Ee} For new output and the exit code call process with action "poll" and id "${v.id}"; "kill" stops it.]`,re=await T.readFullOutput(pe);return{content:[{type:"text",text:M(H,Oe)}],details:{...Z,background:v},structuredContent:{output:re.content,truncated:re.truncated,exit_code:-1,background_id:v.id,wall_time_seconds:Math.round((performance.now()-se)/100)/10}}}c=P.exitCode}catch(P){const{text:H}=await z("");if(await L?.finish(null,""),P instanceof Error&&P.message==="aborted")throw new Error(M(H,"Command aborted"));if(P instanceof Error&&P.message.startsWith("timeout:")){const Z=P.message.split(":")[1];throw new Error(M(H,`Command timed out after ${Z} seconds`))}throw P}const{text:g,details:k,snapshot:C}=await z(),E=await L?.finish(c,C.content||"");if(E&&L)throw new Le(`${M(g,`Command exited with code ${c??"(none)"}`)}
|
|
18
18
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
${Te(A)}`,{...L,sandbox:_.details});if(d===null)throw new Error(D(w,"Command terminated without an exit code"));const N=Math.round((performance.now()-ue)/100)/10,P=await T.readFullOutput(Fe),F={output:P.content,truncated:P.truncated,...P.truncated&&$.fullOutputPath?{full_output_path:$.fullOutputPath}:{},exit_code:d,wall_time_seconds:N},z=_?.details.escalation?_.details:void 0,q=z?{...L,sandbox:z}:L;return d!==0?{content:[{type:"text",text:D(w,`Command exited with code ${d}`)}],details:q,structuredContent:F,isError:!0}:{content:[{type:"text",text:w}],details:q,structuredContent:F}}finally{G()}},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 M("",0,0);return i.setText(Je(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 ze;return Qe(f,p,r,n.showImages,i.startedAt,i.endedAt,n.isError,n.durationMs),f.invalidate(),f}}}u(et,"createShellToolDefinition");const tt={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:re.snippet,promptGuidelines:re.guidelines,tempFilePrefix:"pi-bash",readOnlyCommand:ge,sandboxShell:u(t=>Q(t).shell,"sandboxShell")};function nt(t,e){return et(t,tt,e)}u(nt,"createBashToolDefinition");function yt(t,e){const o=nt(t,e),s=Me(o);return Object.assign(s,{promptSnippet:o.promptSnippet,promptGuidelines:o.promptGuidelines}),s}u(yt,"createBashTool");export{re as bashToolSystemPromptContribution,yt as createBashTool,nt as createBashToolDefinition,Ve as createLocalBashOperations,je as createLocalShellOperations,et as createShellToolDefinition,Lt as registerShellExecutionGuard,Be as sandboxEscalationSchema};
|
|
19
|
+
${Me(E)}`,{...k,sandbox:L.details});if(c===null)throw new Error(M(g,"Command terminated without an exit code"));const D=Math.round((performance.now()-se)/100)/10,F=await T.readFullOutput(pe),N={output:F.content,truncated:F.truncated,...F.truncated&&C.fullOutputPath?{full_output_path:C.fullOutputPath}:{},exit_code:c,wall_time_seconds:D},B=L?.details.escalation?L.details:void 0,Q=B?{...k,sandbox:B}:k;return c!==0?{content:[{type:"text",text:M(g,`Command exited with code ${c}`)}],details:Q,structuredContent:N,isError:!0}:{content:[{type:"text",text:g}],details:Q,structuredContent:N}}finally{q()}},renderCall(a,m,h){const p=h.state;h.executionStarted&&p.startedAt===void 0&&(p.startedAt=Date.now(),p.endedAt=void 0);const f=h.lastComponent??new G("",0,0);return f.setText(ct(a,e.prompt,h.expanded===!0)),f},renderResult(a,m,h,p){const f=p.state;f.startedAt!==void 0&&m.isPartial&&!f.interval&&(f.interval=setInterval(()=>p.invalidate(),1e3)),(!m.isPartial||p.isError)&&(f.endedAt??=Date.now(),f.interval&&(clearInterval(f.interval),f.interval=void 0));const O=p.lastComponent??new lt;return mt(O,a,m,p.showImages,f.startedAt,f.endedAt,p.isError,p.durationMs),O.invalidate(),O}}}r(ft,"createShellToolDefinition");const ht={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:he.snippet,promptGuidelines:he.guidelines,tempFilePrefix:"dal-bash",readOnlyCommand:Be,sandboxShell:r(t=>ae(t).shell,"sandboxShell")};function wt(t,e){return ft(t,ht,e)}r(wt,"createBashToolDefinition");function jt(t,e){const n=wt(t,e),o=Xe(n);return Object.assign(o,{promptSnippet:n.promptSnippet,promptGuidelines:n.promptGuidelines}),o}r(jt,"createBashTool");export{he as bashToolSystemPromptContribution,jt as createBashTool,wt as createBashToolDefinition,ot as createLocalBashOperations,nt as createLocalShellOperations,ft as createShellToolDefinition,Ut as registerShellExecutionGuard,Ze 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(h=>{t.off("finish",i),s(h)},"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,h=Buffer.alloc(n),l=Buffer.alloc(i);await e.read(h,0,n,0),await e.read(l,0,i,s-i);const u=new TextDecoder().decode(h,{stream:!0});let o=0;for(;o<l.length&&(l[o]&192)===128;)o++;const m=new TextDecoder().decode(l.subarray(o)),d=s-n-i;return{content:`${u}
|
|
2
2
|
|
|
3
3
|
[... ${d} bytes omitted ...]
|
|
4
4
|
|
|
5
|
-
${m}`,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(`
|
|
5
|
+
${m}`,truncated:!0}}finally{await e.close()}}handOff(){return this.tempFilePath?{earlierFile:this.tempFilePath}:{earlier:Buffer.concat(this.rawChunks)}}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{g as ERROR_LINE,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};
|
|
@@ -2,12 +2,11 @@ import { type Static, Type } from "typebox";
|
|
|
2
2
|
import type { BackgroundProcessInfo, BackgroundProcessManager } from "../background-processes.ts";
|
|
3
3
|
import type { ToolDefinition } from "../extensions/types.ts";
|
|
4
4
|
declare const processSchema: Type.TObject<{
|
|
5
|
-
action: Type.TUnion<[Type.TLiteral<"start">, Type.TLiteral<"
|
|
5
|
+
action: Type.TUnion<[Type.TLiteral<"start">, Type.TLiteral<"poll">, Type.TLiteral<"stdin">, Type.TLiteral<"kill">, Type.TLiteral<"list">]>;
|
|
6
6
|
command: Type.TOptional<Type.TString>;
|
|
7
|
-
name: Type.TOptional<Type.TString>;
|
|
8
7
|
id: Type.TOptional<Type.TString>;
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
input: Type.TOptional<Type.TString>;
|
|
9
|
+
wait: Type.TOptional<Type.TNumber>;
|
|
11
10
|
}>;
|
|
12
11
|
export type ProcessToolInput = Static<typeof processSchema>;
|
|
13
12
|
export interface ProcessToolDetails {
|
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}
|
|
3
|
-
${e
|
|
1
|
+
var _=Object.defineProperty;var m=(t,e)=>_(t,"name",{value:e,configurable:!0});import{ToolExecutionError as F}from"@earendil-works/pi-agent-core";import{Text as g}from"@earendil-works/pi-tui";import{Type as n}from"typebox";import{theme as w}from"../../modes/interactive/theme/theme.js";import{describeDenialForModel as S}from"../sandbox/denial.js";import{sandboxEscalationSchema as y}from"./bash.js";import{getTextOutput as k}from"./render-utils.js";import{SHELL_OUTPUT_MAX_CHARS as C,truncateHeadTail as U}from"./truncate.js";const T=n.Object({action:n.Union([n.Literal("start"),n.Literal("poll"),n.Literal("stdin"),n.Literal("kill"),n.Literal("list")],{description:'"start" a command in the background; "poll": new output and state; "stdin": send `input`; "kill"; "list"'}),command:n.Optional(n.String({description:'For "start"'})),id:n.Optional(n.String({description:'Process id (from bash or "start")'})),input:n.Optional(n.String({description:'For "stdin"; end with \\n to send a line'})),wait:n.Optional(n.Number({description:'Seconds to wait; "poll" returns early when it exits (default 30, max 300)'}))}),P=n.Object({...T.properties,sandbox_escalation:y}),j=30,D=300,E=2;function x(t){const e=[`${t.id}${t.name?` (${t.name})`:""}: ${t.state}`];t.pid&&e.push(`pid ${t.pid}`),t.state!=="running"&&t.exitCode!==void 0&&e.push(`exit code ${t.exitCode??"none"}`),t.signal&&e.push(`signal ${t.signal}`),t.ports.length>0&&e.push(`ports ${t.ports.join(", ")}`),t.urls.length>0&&e.push(`urls ${t.urls.join(" ")}`),t.sandboxed&&e.push("sandboxed");const o=[e.join(", "),`command: ${t.command}`,`log: ${t.logFile}`];return t.sandboxed&&!t.portsReachableFromHost&&t.ports.length>0&&o.push("note: on Linux the sandbox gives the process its own network namespace; these ports are not reachable from outside the sandbox."),o.join(`
|
|
2
|
+
`)}m(x,"describe");function O(t,e){return new Promise(o=>{if(t<=0||e?.aborted)return o();const d=setTimeout(o,t);e?.addEventListener("abort",()=>{clearTimeout(d),o()},{once:!0})})}m(O,"sleep");function $(t,e){const o=typeof t=="number"&&Number.isFinite(t)&&t>=0?t:e;return Math.min(o,D)*1e3}m($,"waitMs");function f(t,e){if(!t)return"(no new output)";const o=U(t,C);return o.truncated?`${o.content}
|
|
3
|
+
[Truncated; full output: ${e}]`:o.content}m(f,"limitOutput");function q(t,e,o={}){return{name:"process",label:"process",description:'Background processes: commands bash moved to the background at their timeout, or started here. "poll" waits for new output and returns it with the state (exit code, listening ports and URLs). Processes stop when the session ends.'+(o.sandboxed?' Under the sandbox only commands started here may listen on localhost: start dev servers with "start".':""),promptSnippet:"Poll, feed or stop background processes",parameters:o.sandboxed?P:T,async execute(d,i,u,h,l){const s=i.action;if(s==="list"){const r=e.list();return{content:[{type:"text",text:r.length>0?r.map(x).join(`
|
|
4
4
|
|
|
5
|
-
`):"No background processes."}],details:{processes:
|
|
5
|
+
`):"No background processes."}],details:{processes:r}}}if(s==="start"){const r=i.command?.trim();if(!r)throw new Error('action "start" needs a command');const b=await e.start({command:r,cwd:l?.cwd||t,toolCallId:d,escalation:i.sandbox_escalation,ctx:l});await O($(i.wait,E),u);const{text:c,info:a}=e.read(b.id);if(a.denial)throw new F(`${x(a)}
|
|
6
6
|
|
|
7
|
-
${f(
|
|
7
|
+
${f(c,a.logFile)}
|
|
8
8
|
|
|
9
|
-
${
|
|
10
|
-
${
|
|
9
|
+
${S(a.denial)}`,{process:a});return{content:[{type:"text",text:`Started.
|
|
10
|
+
${x(a)}
|
|
11
11
|
|
|
12
12
|
Output so far:
|
|
13
|
-
${f(
|
|
14
|
-
[earlier output is in ${c.logFile}]`:""
|
|
13
|
+
${f(c,a.logFile)}`}],details:{process:a}}}const p=i.id?.trim();if(!p)throw new Error(`action "${s}" needs the process id`);if(s==="poll"||s==="stdin"){if(s==="stdin"){if(typeof i.input!="string")throw new Error('action "stdin" needs input');e.write(p,i.input),await O($(i.wait,E),u)}else await e.waitForExit(p,$(i.wait,j),u);const{text:r,truncated:b}=e.read(p),c=e.status(p),a=b?`
|
|
14
|
+
[earlier output is in ${c.logFile}]`:"",L=c.denial?`
|
|
15
15
|
|
|
16
|
-
${
|
|
16
|
+
${S(c.denial)}`:"";return{content:[{type:"text",text:`${x(c)}
|
|
17
17
|
|
|
18
|
-
${
|
|
19
|
-
${
|
|
20
|
-
`);return
|
|
21
|
-
${
|
|
22
|
-
${
|
|
18
|
+
${f(r,c.logFile)}${a}${L}`}],details:{process:c}}}if(s==="kill"){const r=await e.stop(p);return{content:[{type:"text",text:`Stopped.
|
|
19
|
+
${x(r)}`}],details:{process:r}}}throw new Error(`Unknown action: ${String(s)}`)},renderCall(d,i,u){const h=u.lastComponent??new g("",0,0),l=d?.action??"\u2026",s=l==="start"?d?.command??"":d?.id??"";return h.setText(`${w.fg("toolTitle",w.bold(`process ${l}`))} ${w.fg("dim",String(s))}`),h},renderResult(d,i,u,h){const l=h.lastComponent??new g("",0,0),s=k(d,!1).trim(),p=s.split(`
|
|
20
|
+
`);return l.setText(i.expanded?`
|
|
21
|
+
${w.fg("toolOutput",s)}`:`
|
|
22
|
+
${w.fg("toolOutput",p[0]??"")}`),l}}}m(q,"createProcessToolDefinition");export{q as createProcessToolDefinition};
|