dal-code 1.0.25 → 1.0.27
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 +37 -0
- package/NOTICE +7 -0
- package/dal-docs/README.md +13 -0
- package/dal-docs/settings.md +18 -2
- package/dist/cli/args.d.ts +3 -0
- package/dist/cli/args.js +14 -14
- package/dist/core/agent-session-services.d.ts +2 -0
- package/dist/core/agent-session-services.js +1 -1
- package/dist/core/agent-session.d.ts +27 -1
- package/dist/core/agent-session.js +9 -8
- package/dist/core/background-processes.d.ts +73 -0
- package/dist/core/background-processes.js +7 -0
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/permission-surface.js +1 -1
- package/dist/core/extensions/runner.js +1 -1
- package/dist/core/extensions/types.d.ts +6 -0
- package/dist/core/host-capabilities.d.ts +50 -0
- package/dist/core/host-capabilities.js +2 -0
- package/dist/core/permissions/rules.d.ts +45 -0
- package/dist/core/permissions/rules.js +1 -0
- package/dist/core/permissions/shell-words.js +2 -0
- package/dist/core/permissions/tool-policy.d.ts +46 -0
- package/dist/core/permissions/tool-policy.js +1 -0
- package/dist/core/sandbox/availability.d.ts +14 -0
- package/dist/core/sandbox/availability.js +1 -0
- package/dist/core/sandbox/denial.d.ts +25 -0
- package/dist/core/sandbox/denial.js +3 -0
- package/dist/core/sandbox/index.d.ts +5 -0
- package/dist/core/sandbox/index.js +1 -0
- package/dist/core/sandbox/policy.d.ts +66 -0
- package/dist/core/sandbox/policy.js +1 -0
- package/dist/core/sandbox/runtime.d.ts +41 -0
- package/dist/core/sandbox/runtime.js +1 -0
- package/dist/core/sandbox/shell-sandbox.d.ts +125 -0
- package/dist/core/sandbox/shell-sandbox.js +5 -0
- package/dist/core/sandbox/windows.d.ts +122 -0
- package/dist/core/sandbox/windows.js +5 -0
- package/dist/core/sdk.d.ts +3 -0
- package/dist/core/sdk.js +1 -1
- package/dist/core/settings-manager.d.ts +20 -0
- package/dist/core/settings-manager.js +1 -1
- package/dist/core/tools/bash.d.ts +16 -1
- package/dist/core/tools/bash.js +16 -14
- package/dist/core/tools/find.js +11 -11
- package/dist/core/tools/grep.js +10 -10
- package/dist/core/tools/index.d.ts +1 -0
- package/dist/core/tools/index.js +1 -1
- package/dist/core/tools/ls.js +6 -6
- package/dist/core/tools/powershell.d.ts +1 -1
- package/dist/core/tools/powershell.js +2 -2
- package/dist/core/tools/process.d.ts +26 -0
- package/dist/core/tools/process.js +22 -0
- package/dist/core/tools/read.js +15 -15
- package/dist/dal/builtins.js +2 -2
- package/dist/dal/child-env.js +1 -1
- package/dist/dal/manifest.d.ts +32 -0
- package/dist/dal/manifest.js +1 -0
- package/dist/index.d.ts +8 -3
- package/dist/index.js +1 -1
- package/dist/main.js +4 -4
- package/dist/modes/index.d.ts +2 -2
- package/dist/modes/print-mode.js +6 -4
- package/dist/modes/rpc/environment-update.js +1 -0
- package/dist/modes/rpc/rpc-client.d.ts +38 -1
- package/dist/modes/rpc/rpc-client.js +4 -1
- package/dist/modes/rpc/rpc-mode.d.ts +1 -0
- package/dist/modes/rpc/rpc-mode.js +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +95 -0
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- 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/LICENSE +21 -0
- package/dist/node_modules/@dalcode/dal-interactive/package.json +33 -0
- package/dist/node_modules/@dalcode/dal-interactive/src/handoff.js +28 -0
- package/dist/node_modules/@dalcode/dal-interactive/src/index.js +1 -0
- package/dist/node_modules/@dalcode/dal-interactive/src/interactive-shell.js +1 -0
- package/dist/node_modules/@dalcode/dal-interactive/src/questionnaire.js +3 -0
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-mcp/src/add-wizard.js +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/config.d.ts +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/config.js +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/index.js +18 -18
- package/dist/node_modules/@dalcode/dal-mcp/src/proxy.js +6 -6
- package/dist/node_modules/@dalcode/dal-mcp/src/report.js +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/types.d.ts +1 -1
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-plugins/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-review/LICENSE +21 -0
- package/dist/node_modules/@dalcode/dal-review/package.json +34 -0
- package/dist/node_modules/@dalcode/dal-review/src/args.d.ts +13 -0
- package/dist/node_modules/@dalcode/dal-review/src/args.js +1 -0
- package/dist/node_modules/@dalcode/dal-review/src/core.d.ts +6 -0
- package/dist/node_modules/@dalcode/dal-review/src/core.js +1 -0
- package/dist/node_modules/@dalcode/dal-review/src/findings.d.ts +23 -0
- package/dist/node_modules/@dalcode/dal-review/src/findings.js +4 -0
- package/dist/node_modules/@dalcode/dal-review/src/index.js +1 -0
- package/dist/node_modules/@dalcode/dal-review/src/prompt.d.ts +3 -0
- package/dist/node_modules/@dalcode/dal-review/src/prompt.js +29 -0
- package/dist/node_modules/@dalcode/dal-review/src/runner.d.ts +91 -0
- package/dist/node_modules/@dalcode/dal-review/src/runner.js +2 -0
- package/dist/node_modules/@dalcode/dal-review/src/targets.d.ts +33 -0
- package/dist/node_modules/@dalcode/dal-review/src/targets.js +17 -0
- package/dist/node_modules/@dalcode/dal-review/src/types.d.ts +94 -0
- package/dist/node_modules/@dalcode/dal-review/src/types.js +1 -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-skills/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-subagent/src/agents.js +2 -2
- package/dist/node_modules/@dalcode/dal-subagent/src/index.js +12 -12
- package/dist/node_modules/@dalcode/dal-subagent/src/process-runner.js +3 -3
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-terminal/LICENSE +21 -0
- package/dist/node_modules/@dalcode/dal-terminal/package.json +33 -0
- package/dist/node_modules/@dalcode/dal-terminal/src/contract.d.ts +60 -0
- package/dist/node_modules/@dalcode/dal-terminal/src/contract.js +7 -0
- package/dist/node_modules/@dalcode/dal-terminal/src/index.js +6 -0
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-web/src/config.js +2 -2
- package/dist/node_modules/@dalcode/dal-web/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-web/src/search.js +4 -4
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-workflow/src/plan-mode.js +13 -13
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/chord/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts +4 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +4 -4
- 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/amazon-bedrock.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/anthropic.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-coding-agent/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 +5 -5
- package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/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 +6 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/review.d.ts +1 -0
- package/dist/sdk/review.js +1 -0
- package/dist/sdk/subagents.d.ts +8 -0
- package/dist/sdk/subagents.js +1 -0
- 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/index.ts +6 -0
- 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 +83 -5
- package/package.json +14 -1
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import type { ExtensionContext } from "../extensions/types.ts";
|
|
2
|
+
import { type SandboxAvailability } from "./availability.ts";
|
|
3
|
+
import { type SandboxDenial } from "./denial.ts";
|
|
4
|
+
import { type ResolvedSandboxPolicy, type SandboxLevel, type SandboxOverride } from "./policy.ts";
|
|
5
|
+
import { type WindowsShellKind } from "./windows.ts";
|
|
6
|
+
export interface SandboxEscalationInput {
|
|
7
|
+
mode: "allow" | "unsandboxed";
|
|
8
|
+
justification: string;
|
|
9
|
+
allow_domains?: string[];
|
|
10
|
+
allow_write?: string[];
|
|
11
|
+
}
|
|
12
|
+
export interface SandboxEscalationRequest {
|
|
13
|
+
toolCallId: string;
|
|
14
|
+
toolName: string;
|
|
15
|
+
command: string;
|
|
16
|
+
cwd: string;
|
|
17
|
+
level: SandboxLevel;
|
|
18
|
+
mode: "allow" | "unsandboxed";
|
|
19
|
+
justification: string;
|
|
20
|
+
allowDomains: string[];
|
|
21
|
+
allowWrite: string[];
|
|
22
|
+
background: boolean;
|
|
23
|
+
}
|
|
24
|
+
export interface SandboxEscalationDecision {
|
|
25
|
+
approved: boolean;
|
|
26
|
+
scope?: "once" | "session";
|
|
27
|
+
message?: string;
|
|
28
|
+
}
|
|
29
|
+
export type SandboxEscalationHandler = (request: SandboxEscalationRequest, ctx: ExtensionContext | undefined) => Promise<SandboxEscalationDecision | undefined> | SandboxEscalationDecision | undefined;
|
|
30
|
+
export type SandboxEvent = {
|
|
31
|
+
type: "sandbox_denied";
|
|
32
|
+
toolCallId: string;
|
|
33
|
+
toolName: string;
|
|
34
|
+
denial: SandboxDenial;
|
|
35
|
+
} | {
|
|
36
|
+
type: "sandbox_escalation";
|
|
37
|
+
toolCallId: string;
|
|
38
|
+
toolName: string;
|
|
39
|
+
request: SandboxEscalationRequest;
|
|
40
|
+
decision: SandboxEscalationDecision;
|
|
41
|
+
decidedBy: "sdk" | "handler" | "ui" | "none";
|
|
42
|
+
};
|
|
43
|
+
export interface SandboxStatus {
|
|
44
|
+
level: SandboxLevel;
|
|
45
|
+
levelSource: ResolvedSandboxPolicy["levelSource"];
|
|
46
|
+
enforced: boolean;
|
|
47
|
+
platform: NodeJS.Platform;
|
|
48
|
+
mechanism?: SandboxAvailability["mechanism"];
|
|
49
|
+
unavailableReason?: string;
|
|
50
|
+
network: {
|
|
51
|
+
allowedDomains: string[];
|
|
52
|
+
deniedDomains: string[];
|
|
53
|
+
proxyError?: string;
|
|
54
|
+
};
|
|
55
|
+
sessionAllowances: {
|
|
56
|
+
domains: string[];
|
|
57
|
+
writablePaths: string[];
|
|
58
|
+
};
|
|
59
|
+
isolationTier?: string;
|
|
60
|
+
limitations?: string[];
|
|
61
|
+
}
|
|
62
|
+
export interface SandboxOptions extends SandboxOverride {
|
|
63
|
+
defaultLevel?: SandboxLevel;
|
|
64
|
+
onEscalation?: SandboxEscalationHandler;
|
|
65
|
+
}
|
|
66
|
+
export interface ShellSandboxOptions {
|
|
67
|
+
policy: ResolvedSandboxPolicy;
|
|
68
|
+
onEscalation?: SandboxEscalationHandler;
|
|
69
|
+
onEvent?: (event: SandboxEvent) => void;
|
|
70
|
+
availability?: SandboxAvailability;
|
|
71
|
+
scratchDir?: () => string;
|
|
72
|
+
}
|
|
73
|
+
export interface PreparedCommand {
|
|
74
|
+
command: string;
|
|
75
|
+
sandboxed: boolean;
|
|
76
|
+
details: SandboxRunDetails;
|
|
77
|
+
finish(exitCode: number | null, output: string): Promise<SandboxDenial | undefined>;
|
|
78
|
+
}
|
|
79
|
+
export interface SandboxRunDetails {
|
|
80
|
+
level: SandboxLevel;
|
|
81
|
+
sandboxed: boolean;
|
|
82
|
+
escalation?: {
|
|
83
|
+
request: SandboxEscalationRequest;
|
|
84
|
+
decision: SandboxEscalationDecision;
|
|
85
|
+
};
|
|
86
|
+
denial?: SandboxDenial;
|
|
87
|
+
}
|
|
88
|
+
export declare function registerSandboxEscalationHandler(handler: SandboxEscalationHandler): () => void;
|
|
89
|
+
export declare function setProcessShellSandbox(sandbox: ShellSandbox | undefined): void;
|
|
90
|
+
export declare function getProcessShellSandbox(): ShellSandbox | undefined;
|
|
91
|
+
export declare class ShellSandbox {
|
|
92
|
+
readonly policy: ResolvedSandboxPolicy;
|
|
93
|
+
private readonly onEscalation?;
|
|
94
|
+
private readonly onEvent?;
|
|
95
|
+
private readonly availabilityOverride?;
|
|
96
|
+
private readonly sessionDomains;
|
|
97
|
+
private readonly sessionWritable;
|
|
98
|
+
private holdsRuntime;
|
|
99
|
+
private readonly sharedScratch?;
|
|
100
|
+
private ownScratch;
|
|
101
|
+
constructor(options: ShellSandboxOptions);
|
|
102
|
+
scratchDir(): string;
|
|
103
|
+
dispose(): Promise<void>;
|
|
104
|
+
get level(): SandboxLevel;
|
|
105
|
+
get active(): boolean;
|
|
106
|
+
private availability;
|
|
107
|
+
status(): SandboxStatus;
|
|
108
|
+
describeForModel(): string | undefined;
|
|
109
|
+
unavailableRefusal(): string | undefined;
|
|
110
|
+
prepare(request: {
|
|
111
|
+
command: string;
|
|
112
|
+
cwd: string;
|
|
113
|
+
shell: string;
|
|
114
|
+
toolCallId: string;
|
|
115
|
+
toolName: string;
|
|
116
|
+
escalation?: SandboxEscalationInput;
|
|
117
|
+
background?: boolean;
|
|
118
|
+
ctx?: ExtensionContext;
|
|
119
|
+
env?: NodeJS.ProcessEnv;
|
|
120
|
+
shellKind?: WindowsShellKind;
|
|
121
|
+
}): Promise<PreparedCommand>;
|
|
122
|
+
private prepareWindows;
|
|
123
|
+
private approveEscalation;
|
|
124
|
+
}
|
|
125
|
+
export declare function createScratchDir(): string;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
var M=Object.defineProperty;var d=(n,o)=>M(n,"name",{value:o,configurable:!0});import{spawnSync as B}from"node:child_process";import{mkdtempSync as U,rmSync as H}from"node:fs";import{tmpdir as K}from"node:os";import{isAbsolute as R,join as F,relative as G,resolve as Q}from"node:path";import{fill as b,t as c}from"../../dal/i18n.js";import{detectSandboxAvailability as X}from"./availability.js";import{collectBlockedAccesses as I}from"./denial.js";import{expandPath as Y,filesystemRules as z}from"./policy.js";import{acquireSandboxRuntime as J,ensureFilteringProxy as V,proxyUnavailableReason as j,registerNetworkGrant as Z,releaseSandboxRuntime as q,violationsForCommand as oo,wrapCommand as eo}from"./runtime.js";import{prepareWindowsCommand as no}from"./windows.js";const k=Symbol.for("dal.sandbox.escalationHandlers"),E=globalThis;E[k]instanceof Set||(E[k]=new Set);const W=E[k];function xo(n){return W.add(n),()=>{W.delete(n)}}d(xo,"registerSandboxEscalationHandler");let P;function go(n){P=n}d(go,"setProcessShellSandbox");function So(){return P}d(So,"getProcessShellSandbox");const N=new Map;function io(n){const o=N.get(n);if(o)return o;const e=B("git",["rev-parse","--absolute-git-dir","--git-common-dir"],{cwd:n,encoding:"utf8",timeout:3e3}),s=[];if(e.status===0)for(const l of e.stdout.split(`
|
|
2
|
+
`)){const i=l.trim();if(!i)continue;const a=R(i)?i:Q(n,i),r=G(n,a);(r.startsWith("..")||R(r))&&s.push(a)}const t=[...new Set(s)];return N.set(n,t),t}d(io,"gitDirsOutside");function _(n){return Array.isArray(n)?n.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>o.trim()):[]}d(_,"cleanList");let to=0;class Do{static{d(this,"ShellSandbox")}policy;onEscalation;onEvent;availabilityOverride;sessionDomains=new Set;sessionWritable=new Set;holdsRuntime=!1;sharedScratch;ownScratch;constructor(o){this.policy=o.policy,this.onEscalation=o.onEscalation,this.onEvent=o.onEvent,this.availabilityOverride=o.availability,this.sharedScratch=o.scratchDir,this.active&&(J(),this.holdsRuntime=!0)}scratchDir(){return this.sharedScratch?this.sharedScratch():(this.ownScratch??=ao(),this.ownScratch)}async dispose(){this.ownScratch&&(H(this.ownScratch,{recursive:!0,force:!0}),this.ownScratch=void 0),this.holdsRuntime&&(this.holdsRuntime=!1,await q())}get level(){return this.policy.level}get active(){return this.policy.level!=="off"}availability(){return this.availabilityOverride??X()}status(){const o=this.availability(),e=j();return{level:this.policy.level,levelSource:this.policy.levelSource,enforced:this.active&&o.available,platform:o.platform,...o.mechanism?{mechanism:o.mechanism}:{},...this.active&&!o.available&&o.reason?{unavailableReason:o.reason}:{},...o.isolationTier?{isolationTier:o.isolationTier}:{},...o.limitations?.length?{limitations:[...o.limitations]}:{},network:{allowedDomains:[...this.policy.network.allowedDomains],deniedDomains:[...this.policy.network.deniedDomains],...e?{proxyError:e}:{}},sessionAllowances:{domains:[...this.sessionDomains],writablePaths:[...this.sessionWritable]}}}describeForModel(){if(!this.active)return;const o=this.policy.level==="read-only"?"nothing may be written except $TMPDIR (a scratch directory for this session)":"writes are limited to the working directory and $TMPDIR (a scratch directory for this session; agent/editor config, git hooks and .env files stay read-only)",e=this.policy.network.allowedDomains,s=e.length>0?`network is off except ${e.join(", ")}`:"network is off";return`Commands run inside an OS sandbox (${this.policy.level}): ${o}; ${s}; credential files such as ~/.ssh cannot be read. When the sandbox blocks something the result says what; only then, and only if the task needs it, retry with sandbox_escalation.`}unavailableRefusal(){if(!this.active)return;const o=this.availability();if(!o.available)return[`Command refused: the sandbox level is "${this.policy.level}", but ${o.reason??"the OS sandbox is unavailable."}`,"Commands are not run without the sandbox unless the user says so explicitly.",'The user can fix the sandbox, or opt out explicitly with `dal --sandbox off` or "sandbox": { "level": "off" } in ~/.dal/agent/settings.json.','A single command can still run if the user approves it: retry with sandbox_escalation {"mode":"unsandboxed","justification":"..."}.'].join(`
|
|
3
|
+
`)}async prepare(o){const e=this.policy.level;if(e==="off")return A(o.command,{level:e,sandboxed:!1});const s=this.unavailableRefusal();if(s&&o.escalation?.mode!=="unsandboxed")throw new Error(s);let t=[],l=[],i;if(o.escalation){const f=await this.approveEscalation(o,o.escalation);if(i=f,!f.decision.approved)throw new Error(`Sandbox escalation refused${f.decision.message?`: ${f.decision.message}`:"."} Do not retry the same escalation; continue without it or ask the user.`);if(f.request.mode==="unsandboxed")return A(o.command,{level:e,sandboxed:!1,escalation:i});t=f.request.allowDomains,l=f.request.allowWrite}const a=this.availability(),r=o.shellKind??"bash";if(r!=="bash"&&a.mechanism!=="mxc")throw new Error(`Command refused: ${r} commands cannot run inside the ${a.mechanism??"OS"} sandbox, and the sandbox level is "${e}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);const m=this.scratchDir(),w=z(this.policy,o.cwd,{gitDirs:this.policy.level==="workspace-write"?io(o.cwd):[],extraWrite:[...this.sessionWritable,...l],scratchDir:m}),u={allowedDomains:[...this.policy.network.allowedDomains,...this.sessionDomains,...t],deniedDomains:this.policy.network.deniedDomains,refusals:[]},y=`${process.pid}-${++to}`;if(a.mechanism==="mxc"&&a.mxc)return this.prepareWindows(o,{level:e,shellKind:r,scratch:m,rules:w,grant:u,runId:y,escalation:i,availability:a});const h=so(m),g=`export DAL_SANDBOX_RUN=${y} TMPDIR=${h} TMP=${h} TEMP=${h}
|
|
4
|
+
${o.command}`,v=Date.now(),p=await eo({command:g,shell:o.shell,allowWrite:w.allowWrite,denyWrite:w.denyWrite,denyRead:w.denyRead,allowLocalBinding:o.background===!0||this.policy.network.allowLocalBinding,...a.ripgrep?{ripgrep:a.ripgrep}:{}},u),x={level:e,sandboxed:!0,...i?{escalation:i}:{}};let $=!1;return{command:p.command,sandboxed:!0,details:x,finish:d(async(f,T)=>{if($)return x.denial;if($=!0,p.release(),f===0)return;const O=a.platform==="darwin"?await oo(g,v,400):[],S=I({refusals:u.refusals,violations:O,output:T});if(!S)return;const C=p.proxied?void 0:j(),D={level:e,platform:a.platform,command:o.command,cwd:o.cwd,blocked:S,...C&&S.some(L=>L.kind==="network")?{networkProxyError:C}:{}};return x.denial=D,this.onEvent?.({type:"sandbox_denied",toolCallId:o.toolCallId,toolName:o.toolName,denial:D}),D},"finish")}}async prepareWindows(o,e){const{level:s,grant:t,availability:l}=e,i=l.mxc;if(!i)throw new Error("Command refused: the Windows sandbox (mxc) is not loaded.");let a,r;if(t.allowedDomains.length>0){const h=await V();"port"in h?a=h.port:r=h.error}const m=no({runtime:i,kind:e.shellKind,shellPath:o.shell,command:o.command,cwd:o.cwd,level:s,rules:e.rules,env:o.env??process.env,scratchDir:e.scratch,runId:e.runId,...a!==void 0?{proxyPort:a}:{},allowLocalNetwork:o.background===!0||this.policy.network.allowLocalBinding}),w=Z(t),u={level:s,sandboxed:!0,...e.escalation?{escalation:e.escalation}:{}};let y=!1;return{command:m.command,sandboxed:!0,details:u,finish:d(async(h,g)=>{if(y)return u.denial;if(y=!0,w(),m.cleanup(),h===0)return;const v=I({refusals:t.refusals,violations:[],output:g});if(!v)return;const p={level:s,platform:l.platform,command:o.command,cwd:o.cwd,blocked:v,...r&&v.some(x=>x.kind==="network")?{networkProxyError:r}:{}};return u.denial=p,this.onEvent?.({type:"sandbox_denied",toolCallId:o.toolCallId,toolName:o.toolName,denial:p}),p},"finish")}}async approveEscalation(o,e){const s=e.mode==="unsandboxed"?"unsandboxed":"allow",t={toolCallId:o.toolCallId,toolName:o.toolName,command:o.command,cwd:o.cwd,level:this.policy.level,mode:s,justification:typeof e.justification=="string"?e.justification.trim():"",allowDomains:s==="allow"?_(e.allow_domains):[],allowWrite:s==="allow"?_(e.allow_write).map(i=>Y(i,o.cwd)):[],background:o.background===!0},l=d((i,a)=>{const r=i.approved&&i.scope==="session"&&s==="unsandboxed"?{...i,scope:"once"}:i;if(r.approved&&r.scope==="session"){for(const m of t.allowDomains)this.sessionDomains.add(m);for(const m of t.allowWrite)this.sessionWritable.add(m)}return this.onEvent?.({type:"sandbox_escalation",toolCallId:o.toolCallId,toolName:o.toolName,request:t,decision:r,decidedBy:a}),{request:t,decision:r}},"finish");if(!t.justification)return l({approved:!1,message:"an escalation needs a justification"},"none");if(s==="allow"&&t.allowDomains.length===0&&t.allowWrite.length===0)return l({approved:!1,message:'mode "allow" needs allow_domains or allow_write'},"none");if(this.onEscalation){const i=await this.onEscalation(t,o.ctx);if(i)return l(i,"sdk")}for(const i of W){const a=await i(t,o.ctx);if(a)return l(a,"handler")}return o.ctx?.hasUI?l(await ro(t,o.ctx),"ui"):l({approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"},"none")}}function A(n,o){return{command:n,sandboxed:!1,details:o,finish:d(async()=>{},"finish")}}d(A,"passthrough");function ao(){return U(F(K(),"dal-sandbox-"))}d(ao,"createScratchDir");function so(n){return`'${n.replace(/'/g,"'\\''")}'`}d(so,"shellQuote");async function ro(n,o){const e=c("\u4EC5\u672C\u6B21\u5141\u8BB8"),s=c("\u672C\u4F1A\u8BDD\u5185\u90FD\u5141\u8BB8"),t=c("\u62D2\u7EDD"),l=n.mode==="unsandboxed"?c("\u5728\u6C99\u7BB1\u4E4B\u5916\u8FD0\u884C\u547D\u4EE4\uFF08\u53EF\u8BBF\u95EE\u4F60\u7684\u5168\u90E8\u6587\u4EF6\u548C\u7F51\u7EDC\uFF09"):[n.allowDomains.length>0?b(c("\u8BBF\u95EE {domains}"),{domains:n.allowDomains.join(", ")}):"",n.allowWrite.length>0?b(c("\u5199\u5165 {paths}"),{paths:n.allowWrite.join(", ")}):""].filter(Boolean).join(c("\uFF0C\u5E76")),i=[b(c("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:l}),b(c("\u547D\u4EE4\uFF1A{command}"),{command:n.command}),b(c("\u76EE\u5F55\uFF1A{cwd}"),{cwd:n.cwd}),b(c("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:n.justification})].join(`
|
|
5
|
+
`),a=n.mode==="unsandboxed"?[e,t]:[e,s,t],r=await o.ui.select(i,a);return r===e?{approved:!0,scope:"once"}:r===s?{approved:!0,scope:"session"}:{approved:!1,message:"the user declined"}}d(ro,"askThroughUi");export{Do as ShellSandbox,ao as createScratchDir,So as getProcessShellSandbox,xo as registerSandboxEscalationHandler,go as setProcessShellSandbox};
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import type { CommandFilesystemRules, SandboxLevel } from "./policy.ts";
|
|
2
|
+
export declare const MXC_SDK_DIR_ENV = "DAL_MXC_SDK_DIR";
|
|
3
|
+
export declare const MXC_POLICY_VERSION = "0.6.0-alpha";
|
|
4
|
+
export declare const WINDOWS_SANDBOX_LIMITATIONS: readonly string[];
|
|
5
|
+
export interface MxcPlatformSupport {
|
|
6
|
+
isSupported: boolean;
|
|
7
|
+
reason?: string;
|
|
8
|
+
availableMethods: string[];
|
|
9
|
+
isolationTier?: string;
|
|
10
|
+
isolationWarnings?: string[];
|
|
11
|
+
}
|
|
12
|
+
export interface MxcFilesystemFragment {
|
|
13
|
+
readonlyPaths: string[];
|
|
14
|
+
readwritePaths: string[];
|
|
15
|
+
}
|
|
16
|
+
export interface MxcPolicy {
|
|
17
|
+
version: string;
|
|
18
|
+
filesystem: {
|
|
19
|
+
readwritePaths: string[];
|
|
20
|
+
readonlyPaths: string[];
|
|
21
|
+
deniedPaths: string[];
|
|
22
|
+
};
|
|
23
|
+
network: {
|
|
24
|
+
allowOutbound?: boolean;
|
|
25
|
+
allowLocalNetwork?: boolean;
|
|
26
|
+
proxy?: {
|
|
27
|
+
localhost: number;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
ui: {
|
|
31
|
+
allowWindows: boolean;
|
|
32
|
+
clipboard: "none";
|
|
33
|
+
allowInputInjection: boolean;
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
export interface MxcContainerConfig {
|
|
37
|
+
version: string;
|
|
38
|
+
process?: {
|
|
39
|
+
commandLine: string;
|
|
40
|
+
cwd?: string;
|
|
41
|
+
env?: string[];
|
|
42
|
+
timeout?: number;
|
|
43
|
+
};
|
|
44
|
+
[key: string]: unknown;
|
|
45
|
+
}
|
|
46
|
+
export interface MxcSdkApi {
|
|
47
|
+
getPlatformSupport(): MxcPlatformSupport;
|
|
48
|
+
createConfigFromPolicy(policy: MxcPolicy, containment?: string, containerName?: string): MxcContainerConfig;
|
|
49
|
+
getAvailableToolsPolicy(env?: Record<string, string | undefined>, options?: {
|
|
50
|
+
containerType?: "processcontainer";
|
|
51
|
+
}): MxcFilesystemFragment;
|
|
52
|
+
getUserProfilePolicy(): MxcFilesystemFragment;
|
|
53
|
+
}
|
|
54
|
+
export interface MxcRuntime {
|
|
55
|
+
sdkDir: string;
|
|
56
|
+
sdkVersion: string;
|
|
57
|
+
wxcExec: string;
|
|
58
|
+
api: MxcSdkApi;
|
|
59
|
+
}
|
|
60
|
+
export declare function setMxcRuntimeForTesting(value: MxcRuntime | {
|
|
61
|
+
error: string;
|
|
62
|
+
} | undefined): void;
|
|
63
|
+
export declare function loadMxcRuntime(options?: {
|
|
64
|
+
env?: NodeJS.ProcessEnv;
|
|
65
|
+
arch?: string;
|
|
66
|
+
}): MxcRuntime | {
|
|
67
|
+
error: string;
|
|
68
|
+
};
|
|
69
|
+
export declare function toWindowsPath(path: string): string;
|
|
70
|
+
export declare function quoteWindowsArgument(value: string): string;
|
|
71
|
+
export type WindowsShellKind = "bash" | "powershell";
|
|
72
|
+
export declare function shellInstallRoot(shellPath: string): string;
|
|
73
|
+
export declare function windowsSandboxPolicy(input: {
|
|
74
|
+
level: SandboxLevel;
|
|
75
|
+
cwd: string;
|
|
76
|
+
rules: CommandFilesystemRules;
|
|
77
|
+
tools: MxcFilesystemFragment;
|
|
78
|
+
shellRoot: string;
|
|
79
|
+
runDir: string;
|
|
80
|
+
proxyPort?: number;
|
|
81
|
+
allowLocalNetwork: boolean;
|
|
82
|
+
exists: (path: string) => boolean;
|
|
83
|
+
}): MxcPolicy;
|
|
84
|
+
export declare function windowsSandboxEnvironment(env: NodeJS.ProcessEnv, overrides: {
|
|
85
|
+
scratchDir: string;
|
|
86
|
+
runId: string;
|
|
87
|
+
proxyPort?: number;
|
|
88
|
+
}): string[];
|
|
89
|
+
export declare function windowsInnerCommand(kind: WindowsShellKind, shellPath: string, command: string, scriptPath: string): {
|
|
90
|
+
script: string;
|
|
91
|
+
commandLine: string;
|
|
92
|
+
};
|
|
93
|
+
export declare function windowsOuterCommand(kind: WindowsShellKind, wxcExec: string, configPath: string): string;
|
|
94
|
+
export declare function createRunDirectory(): string;
|
|
95
|
+
export declare function prepareWindowsCommand(input: {
|
|
96
|
+
runtime: MxcRuntime;
|
|
97
|
+
kind: WindowsShellKind;
|
|
98
|
+
shellPath: string;
|
|
99
|
+
command: string;
|
|
100
|
+
cwd: string;
|
|
101
|
+
level: SandboxLevel;
|
|
102
|
+
rules: CommandFilesystemRules;
|
|
103
|
+
env: NodeJS.ProcessEnv;
|
|
104
|
+
scratchDir: string;
|
|
105
|
+
runId: string;
|
|
106
|
+
proxyPort?: number;
|
|
107
|
+
allowLocalNetwork: boolean;
|
|
108
|
+
runDir?: string;
|
|
109
|
+
exists?: (path: string) => boolean;
|
|
110
|
+
}): {
|
|
111
|
+
command: string;
|
|
112
|
+
configPath: string;
|
|
113
|
+
config: MxcContainerConfig;
|
|
114
|
+
cleanup: () => void;
|
|
115
|
+
};
|
|
116
|
+
export declare function probeWindowsSandbox(runtime: MxcRuntime): {
|
|
117
|
+
ok: true;
|
|
118
|
+
support: MxcPlatformSupport;
|
|
119
|
+
} | {
|
|
120
|
+
ok: false;
|
|
121
|
+
reason: string;
|
|
122
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
var S=Object.defineProperty;var c=(e,r)=>S(e,"name",{value:r,configurable:!0});import{spawnSync as D}from"node:child_process";import{existsSync as u,mkdtempSync as I,readFileSync as v,rmSync as w,writeFileSync as p}from"node:fs";import{createRequire as y}from"node:module";import{tmpdir as L}from"node:os";import{join as d,win32 as m}from"node:path";const x="DAL_MXC_SDK_DIR",P="0.6.0-alpha",O=/^0\.6\.\d+$/,H=["Allowlisted domains are reached through dal's filtering proxy, handed to mxc as its network proxy; mxc does not enforce per-host allow or block lists on Windows.","A background process that may listen locally gets mxc's local-network access, which also reaches other machines on the private network, not only localhost.","Protected names inside a writable folder (.env, .git/hooks, .vscode, .dal, \u2026) are protected only if they already exist when the command starts; creating a missing one is not blocked.","Protected credential files (~/.ssh, cloud credentials, \u2026) are denied only if they exist when the command starts."];let h;function V(e){h=e}c(V,"setMxcRuntimeForTesting");function E(e){const r=e[x]?.trim();if(r)return u(d(r,"package.json"))?{dir:r}:{error:`${x} is set to ${r}, but there is no package there.`};try{const o=y(import.meta.url);return{dir:d(o.resolve("@microsoft/mxc-sdk/package.json"),"..")}}catch{return{error:`Microsoft eXecution Containers (mxc) is not installed. Install it with \`npm install -g @microsoft/mxc-sdk@0.6.0\`, or set ${x} to an @microsoft/mxc-sdk 0.6 package directory.`}}}c(E,"sdkDirectory");function B(e={}){if(h)return h;const r=e.env??process.env,o=E(r);if("error"in o)return o;let t;try{t=JSON.parse(v(d(o.dir,"package.json"),"utf8")).version??""}catch(n){return{error:`cannot read the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}if(!O.test(t))return{error:`dal supports @microsoft/mxc-sdk 0.6.x, but ${o.dir} is version ${t||"(unknown)"}. Install @microsoft/mxc-sdk@0.6.0.`};const a=(e.arch??process.arch)==="arm64"?"arm64":"x64",s=d(o.dir,"bin",a,"wxc-exec.exe");if(!u(s))return{error:`the mxc SDK at ${o.dir} has no ${a} wxc-exec.exe.`};let i;try{i=y(import.meta.url)(d(o.dir,"dist","index.js"))}catch(n){return{error:`cannot load the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}return{sdkDir:o.dir,sdkVersion:t,wxcExec:s,api:i}}c(B,"loadMxcRuntime");function l(e){return e.replace(/\//g,"\\")}c(l,"toWindowsPath");function f(e){return e.length>0&&!/[\s"]/.test(e)?e:`"${e.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/,"$1$1")}"`}c(f,"quoteWindowsArgument");function g(e){return`'${e.replace(/'/g,"''")}'`}c(g,"powershellQuote");function $(e){return`'${e.replace(/'/g,"'\\''")}'`}c($,"bashQuote");function T(e){const r=m.dirname(e),o=m.dirname(r);return m.basename(r).toLowerCase()==="bin"&&m.basename(o).toLowerCase()==="usr"?m.dirname(o):m.basename(r).toLowerCase()==="bin"?o:r}c(T,"shellInstallRoot");function _(e,r){const o=m.relative(r,e);return o===""||!o.startsWith("..")&&!m.isAbsolute(o)}c(_,"isWithinWindows");function C(e){const r=c(n=>[...new Set(n.map(l))],"unique"),o=r([...e.rules.allowWrite,...e.tools.readwritePaths]),t=e.rules.denyWrite.filter(n=>!/[*?]/.test(n)&&e.exists(n)&&o.some(b=>_(l(n),b))),a=r([...e.tools.readonlyPaths,e.shellRoot,e.runDir,...e.level==="read-only"?[e.cwd]:[],...t]).filter(n=>!o.includes(n)),s=r(e.rules.denyRead.filter(n=>!/[*?]/.test(n)&&e.exists(n))),i=e.proxyPort!==void 0?{proxy:{localhost:e.proxyPort}}:{allowOutbound:!1,allowLocalNetwork:e.allowLocalNetwork};return{version:P,filesystem:{readwritePaths:o,readonlyPaths:a,deniedPaths:s},network:i,ui:{allowWindows:!0,clipboard:"none",allowInputInjection:!1}}}c(C,"windowsSandboxPolicy");function R(e,r){const o={};for(const[s,i]of Object.entries(e))typeof i=="string"&&(o[s]=i);const t=c((s,i)=>{for(const n of Object.keys(o))n.toLowerCase()===s.toLowerCase()&&delete o[n];o[s]=i},"set"),a=l(r.scratchDir);if(t("TMP",a),t("TEMP",a),t("TMPDIR",a),t("DAL_SANDBOX_RUN",r.runId),r.proxyPort!==void 0){const s=`http://127.0.0.1:${r.proxyPort}`;t("HTTP_PROXY",s),t("HTTPS_PROXY",s),o.http_proxy=s,o.https_proxy=s}return Object.entries(o).map(([s,i])=>`${s}=${i}`)}c(R,"windowsSandboxEnvironment");const N="try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}";function W(e,r,o,t){return e==="powershell"?{script:`${N}
|
|
2
|
+
${o}
|
|
3
|
+
if (-not $?) { if ($LASTEXITCODE) { exit $LASTEXITCODE } else { exit 1 } }
|
|
4
|
+
`,commandLine:[f(r),"-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",f(t)].join(" ")}:{script:`${o}
|
|
5
|
+
`,commandLine:[f(r),"--noprofile","--norc",f(t)].join(" ")}}c(W,"windowsInnerCommand");function j(e,r,o){if(e==="powershell")return`& ${g(l(r))} ${g(l(o))}; exit $LASTEXITCODE`;const t=c(a=>a.replace(/\\/g,"/"),"forward");return`${$(t(r))} ${$(t(o))}`}c(j,"windowsOuterCommand");function k(){return I(d(L(),"dal-mxc-"))}c(k,"createRunDirectory");function J(e){const r=e.runDir??k(),o=c(()=>w(r,{recursive:!0,force:!0}),"cleanup");try{const t=d(r,e.kind==="powershell"?"command.ps1":"command.sh"),a=d(r,"config.json"),s=W(e.kind,l(e.shellPath),e.command,l(t)),i=C({level:e.level,cwd:e.cwd,rules:e.rules,tools:M(e.runtime.api.getAvailableToolsPolicy(e.env,{containerType:"processcontainer"}),e.runtime.api.getUserProfilePolicy()),shellRoot:T(l(e.shellPath)),runDir:l(r),...e.proxyPort!==void 0?{proxyPort:e.proxyPort}:{},allowLocalNetwork:e.allowLocalNetwork,exists:e.exists??u}),n=e.runtime.api.createConfigFromPolicy(i,"process",`dal-${e.runId}`);return n.process={...n.process??{commandLine:""},commandLine:s.commandLine,cwd:l(e.cwd),env:R(e.env,{scratchDir:e.scratchDir,runId:e.runId,...e.proxyPort!==void 0?{proxyPort:e.proxyPort}:{}})},p(t,s.script,{mode:384}),p(a,JSON.stringify(n),{mode:384}),{command:j(e.kind,e.runtime.wxcExec,a),configPath:a,config:n,cleanup:o}}catch(t){throw o(),t}}c(J,"prepareWindowsCommand");function M(...e){return{readonlyPaths:e.flatMap(r=>r.readonlyPaths??[]),readwritePaths:e.flatMap(r=>r.readwritePaths??[])}}c(M,"mergeFragments");function Y(e){let r;try{r=e.api.getPlatformSupport()}catch(t){return{ok:!1,reason:`mxc could not check this machine: ${t instanceof Error?t.message:t}`}}if(!r.isSupported)return{ok:!1,reason:`mxc does not support this Windows installation: ${r.reason||"no reason given"}.`};if(!r.availableMethods.includes("processcontainer"))return{ok:!1,reason:`mxc's process container is not available here (available: ${r.availableMethods.join(", ")||"none"}).`};const o=k();try{const t=e.api.createConfigFromPolicy({version:P,filesystem:{readwritePaths:[],readonlyPaths:[],deniedPaths:[]},network:{allowOutbound:!1},ui:{allowWindows:!1,clipboard:"none",allowInputInjection:!1}},"process",`dal-probe-${process.pid}`);t.process={...t.process??{commandLine:""},commandLine:"cmd.exe /d /c exit 0"};const a=d(o,"config.json");p(a,JSON.stringify(t),{mode:384});const s=D(e.wxcExec,[a],{encoding:"utf8",timeout:3e4,windowsHide:!0});return s.status!==0?{ok:!1,reason:`mxc could not start a sandboxed process (${`${s.stderr??""}${s.stdout??""}`.trim()||s.error?.message||`exit code ${s.status}`}).`}:{ok:!0,support:r}}finally{w(o,{recursive:!0,force:!0})}}c(Y,"probeWindowsSandbox");export{P as MXC_POLICY_VERSION,x as MXC_SDK_DIR_ENV,H as WINDOWS_SANDBOX_LIMITATIONS,k as createRunDirectory,B as loadMxcRuntime,J as prepareWindowsCommand,Y as probeWindowsSandbox,f as quoteWindowsArgument,V as setMxcRuntimeForTesting,T as shellInstallRoot,l as toWindowsPath,W as windowsInnerCommand,j as windowsOuterCommand,R as windowsSandboxEnvironment,C as windowsSandboxPolicy};
|
package/dist/core/sdk.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { AgentSession } from "./agent-session.ts";
|
|
|
4
4
|
import type { LoadExtensionsResult, SessionStartEvent, ToolDefinition } from "./extensions/index.ts";
|
|
5
5
|
import { ModelRuntime } from "./model-runtime.ts";
|
|
6
6
|
import type { ResourceLoader } from "./resource-loader.ts";
|
|
7
|
+
import type { SandboxOptions } from "./sandbox/shell-sandbox.ts";
|
|
7
8
|
import { SessionManager } from "./session-manager.ts";
|
|
8
9
|
import { SettingsManager } from "./settings-manager.ts";
|
|
9
10
|
import { createBashTool, createCodingTools, createEditTool, createFindTool, createGrepTool, createLsTool, createPowerShellTool, createReadOnlyTools, createReadTool, createWriteTool, withFileMutationQueue } from "./tools/index.ts";
|
|
@@ -25,6 +26,8 @@ export interface CreateAgentSessionOptions {
|
|
|
25
26
|
sessionManager?: SessionManager;
|
|
26
27
|
settingsManager?: SettingsManager;
|
|
27
28
|
sessionStartEvent?: SessionStartEvent;
|
|
29
|
+
sandbox?: SandboxOptions;
|
|
30
|
+
defaultActiveTools?: string[];
|
|
28
31
|
}
|
|
29
32
|
export interface CreateAgentSessionResult {
|
|
30
33
|
session: AgentSession;
|
package/dist/core/sdk.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var q=Object.defineProperty;var d=(r,u)=>q(r,"name",{value:u,configurable:!0});import{join as w}from"node:path";import{Agent as K,setDefaultStreamFn as Q}from"@earendil-works/pi-agent-core";import{clampThinkingLevel as V,streamSimple as z}from"@earendil-works/pi-ai/compat";import{getAgentDir as J}from"../config.js";import{resolvePath as C}from"../utils/paths.js";import{AgentSession as X}from"./agent-session.js";import{formatNoModelsAvailableMessage as Y}from"./auth-guidance.js";import{CacheWarmer as Z}from"./cache-warmer.js";import{DEFAULT_THINKING_LEVEL as
|
|
1
|
+
var q=Object.defineProperty;var d=(r,u)=>q(r,"name",{value:u,configurable:!0});import{join as w}from"node:path";import{Agent as K,setDefaultStreamFn as Q}from"@earendil-works/pi-agent-core";import{clampThinkingLevel as V,streamSimple as z}from"@earendil-works/pi-ai/compat";import{getAgentDir as J}from"../config.js";import{resolvePath as C}from"../utils/paths.js";import{AgentSession as X}from"./agent-session.js";import{formatNoModelsAvailableMessage as Y}from"./auth-guidance.js";import{CacheWarmer as Z}from"./cache-warmer.js";import{DEFAULT_THINKING_LEVEL as b}from"./defaults.js";import{convertToLlm as ee}from"./messages.js";import{findInitialModel as te}from"./model-resolver.js";import{ModelRuntime as re}from"./model-runtime.js";import{mergeProviderAttributionHeaders as oe}from"./provider-attribution.js";import{DefaultResourceLoader as ne}from"./resource-loader.js";import{getDefaultSessionDir as se,SessionManager as ie}from"./session-manager.js";import{SettingsManager as ae}from"./settings-manager.js";import{time as de}from"./timings.js";import{createBashTool as le,createCodingTools as me,createEditTool as ce,createFindTool as ge,createGrepTool as ue,createLsTool as fe,createPowerShellTool as he,createReadOnlyTools as ve,createReadTool as Te,createWriteTool as pe,withFileMutationQueue as Me}from"./tools/index.js";Q(z);export*from"./agent-session-runtime.js";function xe(){return J()}d(xe,"getDefaultAgentDir");async function Oe(r={}){const u=C(r.cwd??r.sessionManager?.getCwd()??process.cwd()),v=r.agentDir?C(r.agentDir):xe();let T=r.resourceLoader;const P=r.agentDir?w(v,"auth.json"):void 0,A=r.agentDir?w(v,"models.json"):void 0,f=r.modelRuntime??await re.create({authPath:P,modelsPath:A}),o=r.settingsManager??ae.create(u,v),m=r.sessionManager??ie.create(u,se(u,v));T||(T=new ne({cwd:u,agentDir:v,settingsManager:o}),await T.reload(),de("resourceLoader.reload"));const l=m.buildSessionContext(),y=l.messages.length>0,I=m.getBranch().some(e=>e.type==="thinking_level_change");let n=r.model,p,L;if(!n&&y&&l.model){const e=f.getModel(l.model.provider,l.model.modelId);e&&f.hasConfiguredAuth(e.provider)&&(n=e),n||(p=`Could not restore model ${l.model.provider}/${l.model.modelId}`,L={provider:l.model.provider,modelId:l.model.modelId})}if(!n){const e=o.getDefaultProvider(),t=o.getDefaultModel();n=(await te({scopedModels:[],isContinuing:y,defaultProvider:e,defaultModelId:t,defaultThinkingLevel:o.getDefaultThinkingLevel(),modelThinkingLevels:o.getAllModelThinkingLevels(),modelRuntime:f})).model,n?p&&(p+=`. Using ${n.provider}/${n.id}`):p=Y(),e&&t&&(!n||n.provider!==e||n.id!==t)&&(L={provider:e,modelId:t})}let i=r.thinkingLevel;if(i===void 0&&y&&(i=I?l.thinkingLevel:o.getDefaultThinkingLevel()??b),i===void 0&&n){const e=o.getModelThinkingLevel(n.provider,n.id);e&&(i=e)}i===void 0&&(i=o.getDefaultThinkingLevel()??b),n?i=V(n,i):i="off";const _=["read","bash","edit","write"],E=o.getDefaultTools(),N=r.tools??(r.noTools==="all"?[]:void 0),R=r.excludeTools,B=R?new Set(R):void 0,H=(r.tools??(r.noTools?[]:E??r.defaultActiveTools??_)).filter(e=>!B?.has(e)),F=d(e=>{const t=ee(e);return o.getBlockImages()?t.map(s=>{if(s.role==="user"||s.role==="toolResult"){const a=s.content;if(Array.isArray(a)&&a.some(c=>c.type==="image")){const c=a.map(g=>g.type==="image"?{type:"text",text:"Image reading is disabled."}:g).filter((g,M,x)=>!(g.type==="text"&&g.text==="Image reading is disabled."&&M>0&&x[M-1].type==="text"&&x[M-1].text==="Image reading is disabled."));return{...s,content:c}}}return s}):t},"convertToLlmWithBlockImages"),h={},S=new Z(f,m,()=>o.getCacheWarmingMode(),async e=>h.current?.emitCacheWarmingDecision(e)??e.action),W=d((e,t={})=>{const s=o.getProviderRetrySettings(),a=o.getHttpIdleTimeoutMs(),D=a===0?2147483647:a,c=h.current,g=o.getOutputTokenLimit(e.maxTokens);return{...t,maxTokens:t.maxTokens??(g!==e.maxTokens?g:void 0),timeoutMs:t.timeoutMs??s.timeoutMs??D,websocketConnectTimeoutMs:t.websocketConnectTimeoutMs??o.getWebSocketConnectTimeoutMs(),maxRetries:t.maxRetries??s.maxRetries,maxRetryDelayMs:t.maxRetryDelayMs??s.maxRetryDelayMs,transformHeaders:d(async M=>{const x=oe(e,o,t.sessionId,M);return c?.hasHandlers("before_provider_headers")?c.emitBeforeProviderHeaders(x??{}):x??{}},"transformHeaders")}},"buildRequestOptions"),O=d(e=>{const t=k.state.messages;return()=>{const s=k.state.model,a=k.state.messages;return s.provider===e.provider&&s.id===e.id&&t.length<=a.length&&t.every((D,c)=>a[c]===D)}},"cacheContextIsCurrent"),U=d(async e=>{const t=h.current;return t?.hasHandlers("before_provider_request")?t.emitBeforeProviderRequest(e):e},"transformProviderPayload"),$=d(async e=>{const t=h.current;t?.hasHandlers("after_provider_response")&&await t.emit({type:"after_provider_response",status:e.status,headers:e.headers})},"handleProviderResponse"),k=new K({initialState:{systemPrompt:"",model:n,thinkingLevel:i,tools:[],messages:l.messages},convertToLlm:F,streamFn:d(async(e,t,s)=>{const a=W(e,s);return s?.sessionId===m.getSessionId()&&S.start({model:e,context:t,options:a},O(e)),f.streamSimple(e,t,a)},"streamFn"),onPayload:U,onResponse:$,sessionId:m.getSessionId(),transformContext:d(async e=>{const t=h.current;return t?t.emitContext(e):e},"transformContext"),steeringMode:o.getSteeringMode(),followUpMode:o.getFollowUpMode(),transport:o.getTransport(),thinkingBudgets:o.getThinkingBudgets(),maxRetryDelayMs:o.getProviderRetrySettings().maxRetryDelayMs});y?I||m.appendThinkingLevelChange(i):(n&&m.appendModelChange(n.provider,n.id),m.appendThinkingLevelChange(i));const j=new X({agent:k,sessionManager:m,settingsManager:o,cwd:u,scopedModels:r.scopedModels,resourceLoader:T,customTools:r.customTools,modelRuntime:f,cacheWarmer:S,initialActiveToolNames:H,allowedToolNames:N,excludedToolNames:R,extensionRunnerRef:h,sessionStartEvent:r.sessionStartEvent,desiredModel:L,sandbox:r.sandbox}),G=T.getExtensions();return{session:j,extensionsResult:G,modelFallbackMessage:p}}d(Oe,"createAgentSession");export{Oe as createAgentSession,le as createBashTool,me as createCodingTools,ce as createEditTool,ge as createFindTool,ue as createGrepTool,fe as createLsTool,he as createPowerShellTool,ve as createReadOnlyTools,Te as createReadTool,pe as createWriteTool,Me as withFileMutationQueue};
|
|
@@ -2,6 +2,7 @@ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
|
|
2
2
|
import { type Model, type Transport } from "@earendil-works/pi-ai";
|
|
3
3
|
import type { TuiMode as RendererTuiMode, ScrollViewScrollbar, TerminalCapabilities } from "@earendil-works/pi-tui";
|
|
4
4
|
import type { ShellEnvironmentPolicy } from "../dal/child-env.ts";
|
|
5
|
+
import type { SandboxSettings, SandboxSettingsSources } from "./sandbox/policy.ts";
|
|
5
6
|
export interface CompactionModelOverride {
|
|
6
7
|
reserveTokens?: number;
|
|
7
8
|
keepRecentTokens?: number;
|
|
@@ -99,6 +100,12 @@ export interface Settings {
|
|
|
99
100
|
defaultProjectTrust?: DefaultProjectTrust;
|
|
100
101
|
shellCommandPrefix?: string;
|
|
101
102
|
shellEnvironment?: ShellEnvironmentPolicy;
|
|
103
|
+
sandbox?: SandboxSettings;
|
|
104
|
+
permissions?: {
|
|
105
|
+
allow?: string[];
|
|
106
|
+
deny?: string[];
|
|
107
|
+
ask?: string[];
|
|
108
|
+
};
|
|
102
109
|
npmCommand?: string[];
|
|
103
110
|
collapseChangelog?: boolean;
|
|
104
111
|
enableInstallTelemetry?: boolean;
|
|
@@ -274,6 +281,19 @@ export declare class SettingsManager {
|
|
|
274
281
|
setDefaultProjectTrust(defaultProjectTrust: DefaultProjectTrust): void;
|
|
275
282
|
getShellCommandPrefix(): string | undefined;
|
|
276
283
|
getShellEnvironmentPolicy(): ShellEnvironmentPolicy;
|
|
284
|
+
getPermissionRuleSources(): {
|
|
285
|
+
user?: {
|
|
286
|
+
allow?: unknown;
|
|
287
|
+
deny?: unknown;
|
|
288
|
+
ask?: unknown;
|
|
289
|
+
};
|
|
290
|
+
project?: {
|
|
291
|
+
allow?: unknown;
|
|
292
|
+
deny?: unknown;
|
|
293
|
+
ask?: unknown;
|
|
294
|
+
};
|
|
295
|
+
};
|
|
296
|
+
getSandboxSettingsSources(): SandboxSettingsSources;
|
|
277
297
|
setShellCommandPrefix(prefix: string | undefined): void;
|
|
278
298
|
getNpmCommand(): string[] | undefined;
|
|
279
299
|
setNpmCommand(command: string[] | undefined): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var w=Object.defineProperty;var g=(l,e)=>w(l,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as x}from"@earendil-works/pi-ai";import{randomUUID as F}from"crypto";import{existsSync as k,mkdirSync as L,readFileSync as I,writeFileSync as A}from"fs";import{dirname as N,join as u}from"path";import O from"proper-lockfile";import{CONFIG_DIR_NAME as M,getAgentDir as D}from"../config.js";import{normalizePath as v,resolvePath as m}from"../utils/paths.js";import{stripBom as y}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as R,parseHttpIdleTimeoutMs as W}from"./http-dispatcher.js";const $={reserveTokens:16384,keepRecentTokens:2e4},_=128e3,U=32e3,B=5,H=["off","streaming","idle"];function f(l){return typeof l=="object"&&l!==null&&!Array.isArray(l)}g(f,"isMergeableObject");function T(l,e){const t={...l};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const r=l[s];t[s]=f(r)&&f(i)?T(r,i):i}return t}g(T,"deepMergeObjects");function h(l,e){return T(l,e)}g(h,"deepMergeSettings");function P(l,e){const t=W(l);if(t!==void 0)return t;if(l!==void 0)throw new Error(`Invalid ${e} setting: ${String(l)}`)}g(P,"parseTimeoutSetting");function p(l,e,t){return{scope:l,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}g(p,"toSettingsError");class q{static{g(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=m(e),i=m(t);this.globalSettingsPath=u(i,"settings.json"),this.projectSettingsPath=u(s,M,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let r=1;r<=10;r++)try{return O.lockSync(e,{realpath:!1})}catch(o){if((typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0)!=="ELOCKED"||r===10)throw o;i=o;const d=Date.now();for(;Date.now()-d<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 r;try{const o=k(s);o&&(r=this.acquireLockSyncWithRetry(s));const n=o?I(s,"utf-8"):void 0,d=t(n);d!==void 0&&(k(i)||L(i,{recursive:!0}),r||(r=this.acquireLockSyncWithRetry(s)),A(s,d,"utf-8"))}finally{r&&r()}}}class V{static{g(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 a{static{g(this,"SettingsManager")}storage;globalSettings;projectSettings;settings;projectTrusted;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(e,t,s,i=null,r=null,o=[],n=!0,d={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=n,this.globalSettingsLoadError=i,this.projectSettingsLoadError=r,this.errors=[...o],this.settingsPaths=d,this.settings=h(this.globalSettings,this.projectSettings)}static create(e,t=D(),s={}){const i=m(e),r=m(t),o=new q(i,r);return a.fromStorageWithPaths(o,s,{global:u(r,"settings.json"),project:u(i,M,"settings.json")})}static fromStorage(e,t={}){return a.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,r=a.tryLoadFromStorage(e,"global"),o=a.tryLoadFromStorage(e,"project",i),n=[];return r.error&&n.push(p("global",r.error,s.global)),o.error&&n.push(p("project",o.error,s.project)),new a(e,r.settings,o.settings,r.error,o.error,n,i,s)}static inMemory(e={},t={}){const s=new V,i=a.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),a.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 r=JSON.parse(y(i));return a.migrateSettings(r)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:a.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}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=a.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=a.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=a.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(p(e,t,this.settingsPaths[e]))}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,t){this.writeQueue=this.writeQueue.then(()=>{e==="project"&&this.assertProjectTrustedForWrite(),t(),this.clearModifiedScope(e)}).catch(s=>{this.recordError(e,s)})}cloneModifiedNestedFields(e){const t=new Map;for(const[s,i]of e.entries())t.set(s,new Set(i));return t}persistScopedSettings(e,t,s,i){this.storage.withLock(e,r=>{const o=r?a.migrateSettings(JSON.parse(y(r))):{},n={...o};for(const d of s){const c=t[d];if(i.has(d)&&typeof c=="object"&&c!==null){const j=i.get(d),E=o[d]??{},C=c,S={...E};for(const b of j)S[b]=C[b];n[d]=S}else n[d]=c}return JSON.stringify(n,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 r=t?`${t.provider}/${t.id}`:void 0,o=r!==void 0?s?.modelOverrides?.[r]:void 0;if(o!==void 0&&!f(o))throw new Error(`Invalid compaction.modelOverrides["${r}"] setting: ${String(o)}. Expected an object.`);const n=o?.[e];if(n!==void 0&&(typeof n!="number"||!Number.isSafeInteger(n)||n<0))throw new Error(`Invalid compaction.modelOverrides["${r}"].${e} setting: ${String(n)}. Expected a non-negative safe integer.`);return n??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 _;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??B,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??x}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return U;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 P(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??R}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&&H.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 P(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(){return this.settings.quietStartup??!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}}:{}}}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=F(),this.markModified("trackingId")),this.save()}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()}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;return e?[...e]:void 0}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{H as CACHE_WARMING_MODES,_ as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,U as DEFAULT_MAX_OUTPUT_TOKENS,B as DEFAULT_MAX_RETRIES,q as FileSettingsStorage,V as InMemorySettingsStorage,a as SettingsManager};
|
|
1
|
+
var w=Object.defineProperty;var g=(l,e)=>w(l,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as x}from"@earendil-works/pi-ai";import{randomUUID as F}from"crypto";import{existsSync as k,mkdirSync as L,readFileSync as I,writeFileSync as A}from"fs";import{dirname as N,join as u}from"path";import O from"proper-lockfile";import{CONFIG_DIR_NAME as M,getAgentDir as D}from"../config.js";import{normalizePath as v,resolvePath as m}from"../utils/paths.js";import{stripBom as y}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as R,parseHttpIdleTimeoutMs as W}from"./http-dispatcher.js";const $={reserveTokens:16384,keepRecentTokens:2e4},_=128e3,U=32e3,B=5,H=["off","streaming","idle"];function f(l){return typeof l=="object"&&l!==null&&!Array.isArray(l)}g(f,"isMergeableObject");function T(l,e){const t={...l};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const r=l[s];t[s]=f(r)&&f(i)?T(r,i):i}return t}g(T,"deepMergeObjects");function h(l,e){return T(l,e)}g(h,"deepMergeSettings");function P(l,e){const t=W(l);if(t!==void 0)return t;if(l!==void 0)throw new Error(`Invalid ${e} setting: ${String(l)}`)}g(P,"parseTimeoutSetting");function S(l,e,t){return{scope:l,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}g(S,"toSettingsError");class q{static{g(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=m(e),i=m(t);this.globalSettingsPath=u(i,"settings.json"),this.projectSettingsPath=u(s,M,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let r=1;r<=10;r++)try{return O.lockSync(e,{realpath:!1})}catch(o){if((typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0)!=="ELOCKED"||r===10)throw o;i=o;const d=Date.now();for(;Date.now()-d<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 r;try{const o=k(s);o&&(r=this.acquireLockSyncWithRetry(s));const n=o?I(s,"utf-8"):void 0,d=t(n);d!==void 0&&(k(i)||L(i,{recursive:!0}),r||(r=this.acquireLockSyncWithRetry(s)),A(s,d,"utf-8"))}finally{r&&r()}}}class V{static{g(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 a{static{g(this,"SettingsManager")}storage;globalSettings;projectSettings;settings;projectTrusted;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(e,t,s,i=null,r=null,o=[],n=!0,d={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=n,this.globalSettingsLoadError=i,this.projectSettingsLoadError=r,this.errors=[...o],this.settingsPaths=d,this.settings=h(this.globalSettings,this.projectSettings)}static create(e,t=D(),s={}){const i=m(e),r=m(t),o=new q(i,r);return a.fromStorageWithPaths(o,s,{global:u(r,"settings.json"),project:u(i,M,"settings.json")})}static fromStorage(e,t={}){return a.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,r=a.tryLoadFromStorage(e,"global"),o=a.tryLoadFromStorage(e,"project",i),n=[];return r.error&&n.push(S("global",r.error,s.global)),o.error&&n.push(S("project",o.error,s.project)),new a(e,r.settings,o.settings,r.error,o.error,n,i,s)}static inMemory(e={},t={}){const s=new V,i=a.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),a.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 r=JSON.parse(y(i));return a.migrateSettings(r)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:a.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}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=a.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=a.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=a.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,r=>{const o=r?a.migrateSettings(JSON.parse(y(r))):{},n={...o};for(const d of s){const c=t[d];if(i.has(d)&&typeof c=="object"&&c!==null){const j=i.get(d),C=o[d]??{},E=c,p={...C};for(const b of j)p[b]=E[b];n[d]=p}else n[d]=c}return JSON.stringify(n,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 r=t?`${t.provider}/${t.id}`:void 0,o=r!==void 0?s?.modelOverrides?.[r]:void 0;if(o!==void 0&&!f(o))throw new Error(`Invalid compaction.modelOverrides["${r}"] setting: ${String(o)}. Expected an object.`);const n=o?.[e];if(n!==void 0&&(typeof n!="number"||!Number.isSafeInteger(n)||n<0))throw new Error(`Invalid compaction.modelOverrides["${r}"].${e} setting: ${String(n)}. Expected a non-negative safe integer.`);return n??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 _;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??B,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??x}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return U;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 P(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??R}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&&H.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 P(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(){return this.settings.quietStartup??!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=F(),this.markModified("trackingId")),this.save()}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()}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;return e?[...e]:void 0}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{H as CACHE_WARMING_MODES,_ as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,U as DEFAULT_MAX_OUTPUT_TOKENS,B as DEFAULT_MAX_RETRIES,q as FileSettingsStorage,V as InMemorySettingsStorage,a as SettingsManager};
|
|
@@ -1,13 +1,23 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import { type Static, Type } from "typebox";
|
|
3
3
|
import { type ShellConfig } from "../../utils/shell.ts";
|
|
4
4
|
import type { ToolDefinition } from "../extensions/types.ts";
|
|
5
|
+
import { type SandboxRunDetails, type ShellSandbox } from "../sandbox/shell-sandbox.ts";
|
|
5
6
|
import { type TruncationResult } from "./truncate.ts";
|
|
6
7
|
declare const bashSchema: Type.TObject<{
|
|
7
8
|
command: Type.TString;
|
|
8
9
|
description: Type.TString;
|
|
9
10
|
timeout: Type.TOptional<Type.TNumber>;
|
|
10
11
|
}>;
|
|
12
|
+
export declare const sandboxEscalationSchema: Type.TOptional<Type.TObject<{
|
|
13
|
+
mode: Type.TUnion<[
|
|
14
|
+
Type.TLiteral<"allow">,
|
|
15
|
+
Type.TLiteral<"unsandboxed">
|
|
16
|
+
]>;
|
|
17
|
+
justification: Type.TString;
|
|
18
|
+
allow_domains: Type.TOptional<Type.TArray<Type.TString>>;
|
|
19
|
+
allow_write: Type.TOptional<Type.TArray<Type.TString>>;
|
|
20
|
+
}>>;
|
|
11
21
|
export declare const bashToolSystemPromptContribution: {
|
|
12
22
|
readonly snippet: "Execute bash commands (ls, grep, find, etc.)";
|
|
13
23
|
readonly guidelines: readonly [
|
|
@@ -18,6 +28,7 @@ export type BashToolInput = Static<typeof bashSchema>;
|
|
|
18
28
|
export interface BashToolDetails {
|
|
19
29
|
truncation?: TruncationResult;
|
|
20
30
|
fullOutputPath?: string;
|
|
31
|
+
sandbox?: SandboxRunDetails;
|
|
21
32
|
}
|
|
22
33
|
export interface BashOperations {
|
|
23
34
|
exec: (command: string, cwd: string, options: {
|
|
@@ -53,6 +64,7 @@ export interface BashToolOptions {
|
|
|
53
64
|
shellPath?: string;
|
|
54
65
|
exposeSessionEnvironment?: boolean;
|
|
55
66
|
spawnHook?: BashSpawnHook;
|
|
67
|
+
sandbox?: ShellSandbox;
|
|
56
68
|
}
|
|
57
69
|
export type BashRenderState = {
|
|
58
70
|
startedAt: number | undefined;
|
|
@@ -68,6 +80,9 @@ export interface ShellToolConfig {
|
|
|
68
80
|
promptGuidelines?: readonly string[];
|
|
69
81
|
tempFilePrefix: string;
|
|
70
82
|
readOnlyCommand?: (command: unknown) => boolean;
|
|
83
|
+
sandboxShell?: (shellPath: string | undefined) => string;
|
|
84
|
+
sandboxShellKind?: "bash" | "powershell";
|
|
85
|
+
defaultOperations?: () => BashOperations;
|
|
71
86
|
}
|
|
72
87
|
export declare function createShellToolDefinition(cwd: string, config: ShellToolConfig, options?: BashToolOptions): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState>;
|
|
73
88
|
export declare function createBashToolDefinition(cwd: string, options?: BashToolOptions): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState>;
|