@kodax-ai/kodax 0.7.94 → 0.7.95
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 +64 -0
- package/README.md +36 -2
- package/README_CN.md +29 -0
- package/dist/chunks/agent-XXZMXKKA.js +2 -0
- package/dist/chunks/argument-completer-KCYDGTQW.js +2 -0
- package/dist/chunks/{chunk-BVV3IA5W.js → chunk-2PEDBGKN.js} +1 -1
- package/dist/chunks/{chunk-NGOPE4KK.js → chunk-2TM3W3GK.js} +1 -1
- package/dist/chunks/{chunk-ZKEXHAXA.js → chunk-6ABQJUK6.js} +219 -217
- package/dist/chunks/{chunk-ZGZLSKN6.js → chunk-7JXA3533.js} +223 -225
- package/dist/chunks/{chunk-UNRHTOT5.js → chunk-BNVSKIAB.js} +338 -141
- package/dist/chunks/chunk-BR2OSB2I.js +722 -0
- package/dist/chunks/{chunk-YMNFQ7SQ.js → chunk-C4DTUKTR.js} +2 -2
- package/dist/chunks/{chunk-ZMGATMXN.js → chunk-DSMONSVB.js} +1 -1
- package/dist/chunks/{chunk-6BATYA47.js → chunk-JS452J2F.js} +2 -2
- package/dist/chunks/chunk-O743AJ5V.js +323 -0
- package/dist/chunks/{chunk-IIIAUDGW.js → chunk-OK4AXDC5.js} +1 -1
- package/dist/chunks/chunk-Q5VRWSKG.js +418 -0
- package/dist/chunks/{chunk-N7HIJNJH.js → chunk-SRIJX5ZP.js} +1 -1
- package/dist/chunks/chunk-XWRPOGJN.js +4 -0
- package/dist/chunks/chunk-Y5VIQBT6.js +383 -0
- package/dist/chunks/{client-4IOUU4U3.js → client-JDOS3YJR.js} +1 -1
- package/dist/chunks/{compaction-config-2DTN3OHT.js → compaction-config-EGS4577X.js} +1 -1
- package/dist/chunks/{construction-bootstrap-BL56XTNW.js → construction-bootstrap-YCWHHUYO.js} +1 -1
- package/dist/chunks/dist-KFYN3OKD.js +2 -0
- package/dist/chunks/host-VAYADIPW.js +2 -0
- package/dist/chunks/run-manager-52IJZMZJ.js +2 -0
- package/dist/chunks/utils-P7PBSL3R.js +2 -0
- package/dist/index.d.ts +25 -25
- package/dist/index.js +1 -1
- package/dist/kodax_bootstrap.js +1 -1
- package/dist/kodax_cli.js +1680 -1442
- package/dist/kodax_resume.js +35 -35
- package/dist/runtime-worker.js +1543 -1305
- package/dist/sandbox-workspace-session.js +320 -646
- package/dist/sdk-a2a.d.ts +18 -18
- package/dist/sdk-a2a.js +1 -1
- package/dist/sdk-agent.d.ts +36 -26
- package/dist/sdk-agent.js +1 -1
- package/dist/sdk-coding.d.ts +30 -32
- package/dist/sdk-coding.js +1 -1
- package/dist/sdk-experimental-memory.d.ts +6 -6
- package/dist/sdk-experimental-memory.js +1 -1
- package/dist/sdk-llm.d.ts +8 -8
- package/dist/sdk-mcp.d.ts +4 -4
- package/dist/sdk-mcp.js +1 -1
- package/dist/sdk-media.d.ts +1 -1
- package/dist/sdk-repl.d.ts +21 -21
- package/dist/sdk-repl.js +1 -1
- package/dist/sdk-runtime.d.ts +28 -26
- package/dist/sdk-runtime.js +1 -1
- package/dist/sdk-sandbox.d.ts +3 -1
- package/dist/sdk-sandbox.js +1 -1
- package/dist/sdk-session.d.ts +10 -10
- package/dist/sdk-session.js +1 -1
- package/dist/sdk-skills.d.ts +2 -2
- package/dist/sdk-skills.js +1 -1
- package/dist/semantic-worker.js +278 -81
- package/dist/types-chunks/{base.d-JjF6aKsh.d.ts → base.d-vopO1rml.d.ts} +1 -1
- package/dist/types-chunks/{bash-prefix-extractor.d-AOJdvO4r.d.ts → bash-prefix-extractor.d-B2rxNI4L.d.ts} +20 -9
- package/dist/types-chunks/{capability-learning.d-BAxy0mfx.d.ts → capability-learning.d-CE1tm29C.d.ts} +1 -1
- package/dist/types-chunks/{capsule.d-nYbM4MNL.d.ts → capsule.d-Y7QRS4J2.d.ts} +5 -5
- package/dist/types-chunks/{config.d-CTPaqsD-.d.ts → config.d-CJy1WENT.d.ts} +1 -1
- package/dist/types-chunks/{controller.d-CTvvOy_V.d.ts → controller.d-BR-UVeUR.d.ts} +1 -1
- package/dist/types-chunks/{controller.d-Bm1i9RVj.d.ts → controller.d-C5noq5-w.d.ts} +4 -4
- package/dist/types-chunks/{cost-tracker.d-MTAt6N7b.d.ts → cost-tracker.d-BeaenODW.d.ts} +1 -1
- package/dist/types-chunks/{guardrail.d-D8RyuTrv.d.ts → guardrail.d-DqHD-61O.d.ts} +9 -9
- package/dist/types-chunks/{history-retrieval.d-D0LNyBED.d.ts → history-retrieval.d-CKU8zmt_.d.ts} +2 -2
- package/dist/types-chunks/{integration-config.d-BHoiz-WZ.d.ts → integration-config.d-BNowXE8k.d.ts} +3 -3
- package/dist/types-chunks/{manager.d-D_1fqveb.d.ts → manager.d-B67TmPO1.d.ts} +3 -3
- package/dist/types-chunks/{oauth-login.d-Cz9OpSmz.d.ts → oauth-login.d-6i-vidxv.d.ts} +3 -3
- package/dist/types-chunks/{public-api.d-BNmLxGnR.d.ts → public-api.d-D7fXaWW8.d.ts} +7 -6
- package/dist/types-chunks/{repl.d-Q6Z3lV2-.d.ts → repl.d-BYDb14s6.d.ts} +8 -8
- package/dist/types-chunks/{resolver.d-DparsV6Y.d.ts → resolver.d-CwHUwbdE.d.ts} +4 -4
- package/dist/types-chunks/{review-inbox.d-dAtGH3g2.d.ts → review-inbox.d-BSgFewyj.d.ts} +3 -3
- package/dist/types-chunks/{run-manager.d-BeSEc2OL.d.ts → run-manager.d-BVJSntpS.d.ts} +2 -2
- package/dist/types-chunks/{sdk-session-BwC_i6JB.d.ts → sdk-session-CqEG84oP.d.ts} +3 -3
- package/dist/types-chunks/{sdk-skills-Bg1yL4i4.d.ts → sdk-skills-DokfOoJF.d.ts} +1 -1
- package/dist/types-chunks/{shell-command-sets.d-hkYPr4Dy.d.ts → shell-command-sets.d-DqaaBwhU.d.ts} +1 -1
- package/dist/types-chunks/{side-query.d-DNes6rHA.d.ts → side-query.d-iH0P9ASy.d.ts} +3 -3
- package/dist/types-chunks/{types-D8OiIEwA.d.ts → types-PHjfwebT.d.ts} +1 -1
- package/dist/types-chunks/{types.d-CzrUifXB.d.ts → types.d-C5xQEFcj.d.ts} +6 -6
- package/dist/types-chunks/{types.d-Cv09EdJR.d.ts → types.d-CK9A9rpP.d.ts} +1 -1
- package/dist/types-chunks/{types.d-Bdv2JoiC.d.ts → types.d-CaTXAW_Q.d.ts} +3 -3
- package/dist/types-chunks/{types.d-ssh6zRaf.d.ts → types.d-Cb8RdrjU.d.ts} +1 -1
- package/dist/types-chunks/{types.d-EjZTEEVu.d.ts → types.d-rUOjXych.d.ts} +6 -2
- package/dist/types-chunks/{utils.d-Buv_Gxhi.d.ts → utils.d-CWUyLiXo.d.ts} +8 -8
- package/package.json +2 -2
- package/dist/chunks/agent-Q3FB3GNZ.js +0 -2
- package/dist/chunks/argument-completer-SS2Q2ZKT.js +0 -2
- package/dist/chunks/chunk-56CIZI5I.js +0 -418
- package/dist/chunks/chunk-7CKGNNTU.js +0 -383
- package/dist/chunks/chunk-EASGM7W7.js +0 -687
- package/dist/chunks/chunk-NK5AWGNW.js +0 -319
- package/dist/chunks/dist-B4CB7KHY.js +0 -2
- package/dist/chunks/host-7747QS3X.js +0 -2
- package/dist/chunks/run-manager-NLNMI3P2.js +0 -2
- package/dist/chunks/utils-CGGQLMJS.js +0 -2
|
@@ -1,687 +0,0 @@
|
|
|
1
|
-
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{k as Pn,l as Cn}from"./chunk-ZGZLSKN6.js";import{Ac as U,Ia as q,Wa as ft,Ya as pt,_a as Ne,db as Le,fb as nn,ib as De,mb as wt,t as T,zc as mt}from"./chunk-UNRHTOT5.js";import{a as s}from"./chunk-ONUPGMER.js";import{spawn as Jn,spawnSync as Ve}from"node:child_process";import{createHash as Ye,randomUUID as H}from"node:crypto";import{once as yt}from"node:events";import{closeSync as Pr,constants as Cr,existsSync as Tt,lstatSync as yn,mkdirSync as ht,openSync as Tr,readFileSync as Wt,readSync as Wr,readdirSync as Un,realpathSync as G,renameSync as Nn,rmSync as pe,statSync as Re,writeFileSync as St,writeSync as mi}from"node:fs";import{copyFile as $t,lstat as $r,mkdir as J,readFile as Pe,realpath as qe,rename as _r,rm as z,rmdir as Or,stat as dn,writeFile as Ce}from"node:fs/promises";import{createRequire as Ir}from"node:module";import{createServer as Nr}from"node:net";import ae from"node:os";import d from"node:path";import Lr from"node:readline";import{fileURLToPath as bt,pathToFileURL as _t}from"node:url";function gr(e){let t=e.code;return t==="ENOENT"||t==="ENOTDIR"}s(gr,"isMissingGitTrustPath");function yr(e,t,n){try{let r=t(e).replaceAll("\\","/").replace(/\/+$/,"");return r===""?void 0:/^[A-Za-z]:$/.test(r)?`${r}/`:r}catch(r){if(n(r))return;throw r}}s(yr,"normalizeGitSafeDirectoryRootImplementation");function hr(e,t,n,r){try{let i=t(n.join(e,".git"));if(i.isDirectory()||i.isFile())return!0}catch(i){if(!r(i))throw i}if(!(n.basename(e).toLowerCase()===".git"||/[/\\]\.git[/\\]modules[/\\]/i.test(e)))return!1;try{return t(n.join(e,"HEAD")).isFile()}catch(i){if(r(i))return!1;throw i}}s(hr,"isRepoBearingGitReadRootImplementation");function Sr(e,t,n,r,o){let i=[];typeof e=="string"&&e!==""&&i.push(e);for(let l of n??[])o(l)&&i.push(l);i.push(...t??[]);let c=[],a=new Set;for(let l of i){if(c.length>=8)break;let u=r(l);if(u===void 0)continue;let m=u.toLowerCase();a.has(m)||(a.add(m),c.push(u))}return c}s(Sr,"windowsGitTrustRootsImplementation");function br(e){if(e==="git_config_count")return"count";if(/^git_config_key_\d+$/.test(e))return"key";if(/^git_config_value_\d+$/.test(e))return"value"}s(br,"gitConfigEnvKind");function vr(e,t,n,r,o){let i=new Map,c=[],a,l=!1;for(let u=0;u<t;u+=1){if(e[u]!=="--env"||u+1>=t)continue;let m=e[u+1],w=m.indexOf("="),f=(w<0?m:m.slice(0,w)).toLowerCase(),p=n(f);if(p===void 0)continue;l=!0,c.push(u);let y=w<0?"":m.slice(w+1);if(p==="count"){let b=Number.parseInt(y,10);(a!==void 0||!Number.isSafeInteger(b)||b<0||String(b)!==y)&&r(),a=b;continue}let v=Number.parseInt(f.slice(`git_config_${p}_`.length),10),x=i.get(v)??{};(!Number.isSafeInteger(v)||v<0||x[p]!==void 0)&&r(),x[p]=y,i.set(v,x)}return o(i,c,a,l,r)}s(vr,"parseGitConfigEnvironmentImplementation");function xr(){throw new Error("ASRT GIT_CONFIG environment has an unexpected shape.")}s(xr,"throwUnexpectedGitConfigShape");function kr(e,t,n,r,o){!r||n!==void 0&&e.size===n&&[...e].every(([a,l])=>a<n&&l.key!==void 0&&l.value!==void 0)||o();let c=[...e].map(([a,l])=>({slot:a,key:l.key,value:l.value}));return{argumentIndices:t,pairs:c,sawAny:r}}s(kr,"finishParsedGitConfigEnvironment");function Ar(e,t){let n=[];for(let o of e)n.push({key:"safe.directory",value:o},{key:"safe.directory",value:`${o}/*`});n.push(...t);let r=n.flatMap((o,i)=>[`GIT_CONFIG_KEY_${i}=${o.key}`,`GIT_CONFIG_VALUE_${i}=${o.value}`]);return r.push(`GIT_CONFIG_COUNT=${n.length}`),r}s(Ar,"gitSafeDirectoryAssignments");function Er(e,t,n,r){let o=new Set(n.argumentIndices),i=[],c=!1;for(let a=0;a<e.length;a+=1)if(o.has(a)){if(!c){for(let l of r)i.push("--env",l);c=!0}a+=1}else i.push(e[a]);return n.sawAny||i.splice(t,0,...r.flatMap(a=>["--env",a])),i}s(Er,"replaceGitConfigEnvironment");function Rr(e,t,n,r,o){let i=e.lastIndexOf("--");if(i<0)throw new Error("ASRT Windows wrapper omitted its child separator.");let c=n(e,i),a=c.pairs.filter(u=>u.key.toLowerCase()!=="safe.directory").sort((u,m)=>u.slot-m.slot),l=r(t,a);return o(e,i,c,l)}s(Rr,"rewriteWindowsGitSafeDirectoryArgvImplementation");function gt(){return String.raw`
|
|
3
|
-
const isMissingGitTrustPath = ${gr.toString()};
|
|
4
|
-
const normalizeGitSafeDirectoryRootImplementation = ${yr.toString()};
|
|
5
|
-
const normalizeGitSafeDirectoryRoot = (root) => (
|
|
6
|
-
normalizeGitSafeDirectoryRootImplementation(root, realpathSync, isMissingGitTrustPath)
|
|
7
|
-
);
|
|
8
|
-
const isRepoBearingGitReadRootImplementation = ${hr.toString()};
|
|
9
|
-
const isRepoBearingGitReadRoot = (root) => (
|
|
10
|
-
isRepoBearingGitReadRootImplementation(root, statSync, path, isMissingGitTrustPath)
|
|
11
|
-
);
|
|
12
|
-
const windowsGitTrustRootsImplementation = ${Sr.toString()};
|
|
13
|
-
const windowsGitTrustRoots = (input) => {
|
|
14
|
-
const filesystem = (input.config && input.config.filesystem) || {};
|
|
15
|
-
return windowsGitTrustRootsImplementation(
|
|
16
|
-
input.cwd,
|
|
17
|
-
filesystem.allowWrite,
|
|
18
|
-
filesystem.allowRead,
|
|
19
|
-
normalizeGitSafeDirectoryRoot,
|
|
20
|
-
isRepoBearingGitReadRoot,
|
|
21
|
-
);
|
|
22
|
-
};
|
|
23
|
-
const gitConfigEnvKind = ${br.toString()};
|
|
24
|
-
const throwUnexpectedGitConfigShape = ${xr.toString()};
|
|
25
|
-
const finishParsedGitConfigEnvironment = ${kr.toString()};
|
|
26
|
-
const parseGitConfigEnvironmentImplementation = ${vr.toString()};
|
|
27
|
-
const parseGitConfigEnvironment = (argv, separator) => (
|
|
28
|
-
parseGitConfigEnvironmentImplementation(
|
|
29
|
-
argv,
|
|
30
|
-
separator,
|
|
31
|
-
gitConfigEnvKind,
|
|
32
|
-
throwUnexpectedGitConfigShape,
|
|
33
|
-
finishParsedGitConfigEnvironment,
|
|
34
|
-
)
|
|
35
|
-
);
|
|
36
|
-
const gitSafeDirectoryAssignments = ${Ar.toString()};
|
|
37
|
-
const replaceGitConfigEnvironment = ${Er.toString()};
|
|
38
|
-
const rewriteWindowsGitSafeDirectoryArgvImplementation = ${Rr.toString()};
|
|
39
|
-
const rewriteWindowsGitSafeDirectoryArgv = (argv, trustRoots) => (
|
|
40
|
-
rewriteWindowsGitSafeDirectoryArgvImplementation(
|
|
41
|
-
argv,
|
|
42
|
-
trustRoots,
|
|
43
|
-
parseGitConfigEnvironment,
|
|
44
|
-
gitSafeDirectoryAssignments,
|
|
45
|
-
replaceGitConfigEnvironment,
|
|
46
|
-
)
|
|
47
|
-
);
|
|
48
|
-
`}s(gt,"windowsGitBrokerHelpersSource");var ue="0.0.65",{DEFAULT_WINDOWS_PROXY_PORT_RANGE:Dr,SandboxManager:Tn,getSrtWinPath:Br,getWindowsSandboxUserStatus:Hn,grantWindowsAcl:Fr,installWindowsSandbox:Mr,resolveSrtWin:Gr,revokeWindowsAcl:Ot}=await import("@anthropic-ai/sandbox-runtime");function jr(){let e=process.platform==="win32"?"windows-restricted-user":process.platform==="darwin"?"macos-seatbelt":process.platform==="linux"?"linux-bubblewrap":"unsupported";return{version:4,asrtVersion:ue,platform:process.platform,backend:e,genericCommandExecution:!0,controls:["filesystem","network","environment","timeout","output"],ordinaryCallsTriggerSetup:!1,setupMayElevate:process.platform==="win32",unavailableBehavior:"structured-no-execution",permissionFallback:"normal-permission-policy",gitSafeDirectory:"authorized-repo-roots"}}s(jr,"sandboxRuntimeCapability");var zn=1048576,hn=12e4,Vn=Ir(import.meta.url),It=process.env.KODAX_BUNDLED==="true"?void 0:_t(Vn.resolve("@anthropic-ai/sandbox-runtime")).href,Kr=new Set([".ssh",".aws",".azure",".gnupg",".kodax",".agents",".codex",".claude",".gemini",".direnv",".terraform.d"]),qr=new Set([".env",".envrc",".pgpass",".npmrc",".pypirc","credentials","id_rsa","id_ed25519"]),Xr=[".ssh",".aws",".azure",".gnupg",".kube",".docker",".kodax",".agents",".codex",".claude",".gemini",".direnv",".terraform.d",d.join(".cargo","credentials.toml"),d.join(".config","gcloud"),d.join(".config","gh"),d.join(".config","openai"),d.join(".config","anthropic"),".gitconfig",d.join(".config","git","config"),".terraformrc",d.join(".config","pypoetry","auth.toml"),".condarc",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",d.join(".config","fish","config.fish"),d.join(".config","fish","fish_variables"),".bash_history",".zsh_history",d.join(".m2","settings.xml"),d.join(".m2","settings-security.xml"),d.join(".gradle","gradle.properties"),d.join(".nuget","NuGet","NuGet.Config"),d.join(".pip","pip.conf"),d.join(".config","pip","pip.conf"),d.join(".cache","huggingface","token"),d.join(".huggingface","token"),d.join(".config","rclone","rclone.conf"),d.join(".local","share","keyrings"),d.join("Library","Keychains"),d.join("AppData","Roaming","Microsoft","Protect"),d.join("AppData","Roaming","Microsoft","Credentials"),d.join("AppData","Roaming","Microsoft","Vault"),d.join("AppData","Local","Microsoft","Credentials"),d.join("AppData","Local","Microsoft","Protect"),d.join("AppData","Local","Microsoft","Vault"),".password-store",".env",".envrc",".pgpass",".env.local",".env.development",".env.production",".env.test",".env.staging",".npmrc",".pypirc",".netrc",".git-credentials","credentials","credentials.json","application_default_credentials.json","id_rsa","id_dsa","id_ecdsa","id_ed25519"],Jr=["runtime","mcp-tokens","mcp-clients","integrations","sandbox-runtime","processes","learned","config.json","auth.json","trusted-project-rules.json",".env",".envrc",".pgpass",".npmrc",".pypirc",".netrc",".git-credentials","credentials","credentials.json","application_default_credentials.json"],Yn=["runtime","processes","learned"],Ur=String.raw`
|
|
49
|
-
$ErrorActionPreference = 'Stop'
|
|
50
|
-
$payload = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
51
|
-
$mutex = [System.Threading.Mutex]::new($false, 'Local\KodaXAsrtAclGuard-v1')
|
|
52
|
-
$held = $false
|
|
53
|
-
$missing = [System.Collections.Generic.List[string]]::new()
|
|
54
|
-
function Test-KodaXAsrtAclRule($acl, $sidValue, $rights, $inheritance) {
|
|
55
|
-
foreach ($rule in $acl.Access) {
|
|
56
|
-
try {
|
|
57
|
-
$ruleSid = $rule.IdentityReference.Translate(
|
|
58
|
-
[System.Security.Principal.SecurityIdentifier]
|
|
59
|
-
).Value
|
|
60
|
-
} catch {
|
|
61
|
-
continue
|
|
62
|
-
}
|
|
63
|
-
if (
|
|
64
|
-
$ruleSid -eq $sidValue -and
|
|
65
|
-
$rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Deny -and
|
|
66
|
-
-not $rule.IsInherited -and
|
|
67
|
-
$rule.InheritanceFlags -eq $inheritance -and
|
|
68
|
-
$rule.PropagationFlags -eq [System.Security.AccessControl.PropagationFlags]::None -and
|
|
69
|
-
(([int]$rule.FileSystemRights -band [int]$rights) -eq [int]$rights)
|
|
70
|
-
) {
|
|
71
|
-
return $true
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
return $false
|
|
75
|
-
}
|
|
76
|
-
function Test-KodaXParentDeleteChildSafe($acl, $tokenSidValues) {
|
|
77
|
-
foreach ($rule in $acl.Access) {
|
|
78
|
-
try {
|
|
79
|
-
$ruleSid = $rule.IdentityReference.Translate(
|
|
80
|
-
[System.Security.Principal.SecurityIdentifier]
|
|
81
|
-
).Value
|
|
82
|
-
} catch {
|
|
83
|
-
continue
|
|
84
|
-
}
|
|
85
|
-
if (
|
|
86
|
-
$tokenSidValues -contains $ruleSid -and
|
|
87
|
-
$rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Deny -and
|
|
88
|
-
($rule.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -eq 0 -and
|
|
89
|
-
(([int]$rule.FileSystemRights -band [int][System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles) -ne 0)
|
|
90
|
-
) {
|
|
91
|
-
return $true
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
foreach ($rule in $acl.Access) {
|
|
95
|
-
try {
|
|
96
|
-
$ruleSid = $rule.IdentityReference.Translate(
|
|
97
|
-
[System.Security.Principal.SecurityIdentifier]
|
|
98
|
-
).Value
|
|
99
|
-
} catch {
|
|
100
|
-
continue
|
|
101
|
-
}
|
|
102
|
-
if (
|
|
103
|
-
$tokenSidValues -contains $ruleSid -and
|
|
104
|
-
$rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and
|
|
105
|
-
($rule.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -eq 0 -and
|
|
106
|
-
(([int]$rule.FileSystemRights -band [int][System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles) -ne 0)
|
|
107
|
-
) {
|
|
108
|
-
return $false
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
return $true
|
|
112
|
-
}
|
|
113
|
-
function Test-KodaXAsrtAclRuleReadsData($acl, $sidValue) {
|
|
114
|
-
foreach ($rule in $acl.Access) {
|
|
115
|
-
try {
|
|
116
|
-
$ruleSid = $rule.IdentityReference.Translate(
|
|
117
|
-
[System.Security.Principal.SecurityIdentifier]
|
|
118
|
-
).Value
|
|
119
|
-
} catch {
|
|
120
|
-
continue
|
|
121
|
-
}
|
|
122
|
-
if (
|
|
123
|
-
$ruleSid -eq $sidValue -and
|
|
124
|
-
$rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Deny -and
|
|
125
|
-
-not $rule.IsInherited -and
|
|
126
|
-
$rule.PropagationFlags -eq [System.Security.AccessControl.PropagationFlags]::None -and
|
|
127
|
-
(([int]$rule.FileSystemRights -band ([int][System.Security.AccessControl.FileSystemRights]::ReadAndExecute -bor [int][System.Security.AccessControl.FileSystemRights]::Synchronize)) -ne 0)
|
|
128
|
-
) {
|
|
129
|
-
return $true
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
return $false
|
|
133
|
-
}
|
|
134
|
-
function Add-KodaXAsrtAclRule($target, $sid, $rights, $inheritance, $ruleText) {
|
|
135
|
-
$acl = Get-Acl -LiteralPath $target
|
|
136
|
-
if (Test-KodaXAsrtAclRule $acl $sid.Value $rights $inheritance) {
|
|
137
|
-
return
|
|
138
|
-
}
|
|
139
|
-
$principal = '*' + $sid.Value
|
|
140
|
-
& "$env:SystemRoot\System32\icacls.exe" $target '/deny' "$($principal):$ruleText" | Out-Null
|
|
141
|
-
if ($LASTEXITCODE -ne 0) {
|
|
142
|
-
throw "icacls failed to install a KodaX sandbox guard on $target."
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
function Add-KodaXAsrtWriteAclRule($target, $sid, $rights, $inheritance) {
|
|
146
|
-
$acl = Get-Acl -LiteralPath $target
|
|
147
|
-
if (Test-KodaXAsrtAclRule $acl $sid.Value $rights $inheritance) {
|
|
148
|
-
return
|
|
149
|
-
}
|
|
150
|
-
$rule = [System.Security.AccessControl.FileSystemAccessRule]::new(
|
|
151
|
-
$sid,
|
|
152
|
-
$rights,
|
|
153
|
-
$inheritance,
|
|
154
|
-
[System.Security.AccessControl.PropagationFlags]::None,
|
|
155
|
-
[System.Security.AccessControl.AccessControlType]::Deny
|
|
156
|
-
)
|
|
157
|
-
[void]$acl.AddAccessRule($rule)
|
|
158
|
-
Set-Acl -LiteralPath $target -AclObject $acl
|
|
159
|
-
}
|
|
160
|
-
try {
|
|
161
|
-
try {
|
|
162
|
-
$held = $mutex.WaitOne(10000)
|
|
163
|
-
} catch [System.Threading.AbandonedMutexException] {
|
|
164
|
-
$held = $true
|
|
165
|
-
}
|
|
166
|
-
if (-not $held) {
|
|
167
|
-
throw 'Timed out waiting for the KodaX ASRT ACL guard mutex.'
|
|
168
|
-
}
|
|
169
|
-
$sid = [System.Security.Principal.SecurityIdentifier]::new([string]$payload.sid)
|
|
170
|
-
$tokenSidValues = @($payload.tokenSids | ForEach-Object { [string]$_ })
|
|
171
|
-
foreach ($entry in $payload.paths) {
|
|
172
|
-
$target = [System.IO.Path]::GetFullPath([string]$entry.path)
|
|
173
|
-
if (-not (Test-Path -LiteralPath $target)) {
|
|
174
|
-
throw "ACL guard target disappeared before it could be protected: $target"
|
|
175
|
-
}
|
|
176
|
-
$inheritance = if ([bool]$entry.directory) {
|
|
177
|
-
[System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor
|
|
178
|
-
[System.Security.AccessControl.InheritanceFlags]::ObjectInherit
|
|
179
|
-
} else {
|
|
180
|
-
[System.Security.AccessControl.InheritanceFlags]::None
|
|
181
|
-
}
|
|
182
|
-
$writeRights = [System.Security.AccessControl.FileSystemRights]::Write -bor
|
|
183
|
-
[System.Security.AccessControl.FileSystemRights]::Delete -bor
|
|
184
|
-
[System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor
|
|
185
|
-
[System.Security.AccessControl.FileSystemRights]::TakeOwnership
|
|
186
|
-
if ([bool]$entry.directory) {
|
|
187
|
-
$writeRights = $writeRights -bor [System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles
|
|
188
|
-
}
|
|
189
|
-
$targetRights = if ([string]$entry.mode -eq 'write') {
|
|
190
|
-
$writeRights
|
|
191
|
-
} else {
|
|
192
|
-
[System.Security.AccessControl.FileSystemRights]::FullControl
|
|
193
|
-
}
|
|
194
|
-
$parent = [System.IO.Path]::GetDirectoryName($target)
|
|
195
|
-
$targetAcl = Get-Acl -LiteralPath $target
|
|
196
|
-
$targetReady = Test-KodaXAsrtAclRule $targetAcl $sid.Value $targetRights $inheritance
|
|
197
|
-
$targetTooBroad = [string]$entry.mode -eq 'write' -and (Test-KodaXAsrtAclRuleReadsData $targetAcl $sid.Value)
|
|
198
|
-
if ($targetTooBroad) {
|
|
199
|
-
$targetReady = $false
|
|
200
|
-
}
|
|
201
|
-
$parentReady = -not $parent -or $parent -eq $target -or -not (Test-Path -LiteralPath $parent)
|
|
202
|
-
if (-not $parentReady) {
|
|
203
|
-
$parentAcl = Get-Acl -LiteralPath $parent
|
|
204
|
-
$parentReady = (Test-KodaXAsrtAclRule $parentAcl $sid.Value ([System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles) ([System.Security.AccessControl.InheritanceFlags]::None)) -or (Test-KodaXParentDeleteChildSafe $parentAcl $tokenSidValues)
|
|
205
|
-
}
|
|
206
|
-
if (-not [bool]$payload.install) {
|
|
207
|
-
if (-not $targetReady -or -not $parentReady) {
|
|
208
|
-
[void]$missing.Add($target)
|
|
209
|
-
}
|
|
210
|
-
continue
|
|
211
|
-
}
|
|
212
|
-
if ($targetTooBroad) {
|
|
213
|
-
$principal = '*' + $sid.Value
|
|
214
|
-
& "$env:SystemRoot\System32\icacls.exe" $target '/remove:d' $principal | Out-Null
|
|
215
|
-
if ($LASTEXITCODE -ne 0) {
|
|
216
|
-
throw "icacls failed to remove an obsolete KodaX sandbox guard from $target."
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
if (-not $targetReady) {
|
|
220
|
-
if ([string]$entry.mode -eq 'write') {
|
|
221
|
-
Add-KodaXAsrtWriteAclRule $target $sid $targetRights $inheritance
|
|
222
|
-
} else {
|
|
223
|
-
$targetRule = if ([bool]$entry.directory) { '(OI)(CI)(F)' } else { '(F)' }
|
|
224
|
-
Add-KodaXAsrtAclRule $target $sid $targetRights $inheritance $targetRule
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
if (-not $parentReady) {
|
|
228
|
-
Add-KodaXAsrtAclRule $parent $sid ([System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles) ([System.Security.AccessControl.InheritanceFlags]::None) '(DC)'
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
[Console]::Out.Write((@{ missing = @($missing) } | ConvertTo-Json -Compress))
|
|
232
|
-
} finally {
|
|
233
|
-
if ($held) {
|
|
234
|
-
[void]$mutex.ReleaseMutex()
|
|
235
|
-
}
|
|
236
|
-
$mutex.Dispose()
|
|
237
|
-
}
|
|
238
|
-
`,Ln=new Set,Nt=new Set,vt=JSON.stringify(pt),Wn=JSON.stringify(ft),Hr=String.raw`
|
|
239
|
-
const { spawn } = require('node:child_process');
|
|
240
|
-
const { writeSync } = require('node:fs');
|
|
241
|
-
const input = JSON.parse(Buffer.from(process.argv[2], 'base64').toString('utf8'));
|
|
242
|
-
const childEnv = { ...process.env };
|
|
243
|
-
for (const name of Object.keys(childEnv)) {
|
|
244
|
-
if (name.toLowerCase() === 'electron_run_as_node') delete childEnv[name];
|
|
245
|
-
}
|
|
246
|
-
if (input.electronRunAsNode === true) childEnv.ELECTRON_RUN_AS_NODE = '1';
|
|
247
|
-
const child = spawn(input.command, input.args, {
|
|
248
|
-
cwd: input.cwd,
|
|
249
|
-
env: childEnv,
|
|
250
|
-
shell: false,
|
|
251
|
-
stdio: ['inherit', 'inherit', 'pipe'],
|
|
252
|
-
windowsHide: true,
|
|
253
|
-
windowsVerbatimArguments: input.windowsVerbatimArguments === true,
|
|
254
|
-
});
|
|
255
|
-
const stop = (signal) => child.kill(signal);
|
|
256
|
-
process.once('SIGINT', () => stop('SIGINT'));
|
|
257
|
-
process.once('SIGTERM', () => stop('SIGTERM'));
|
|
258
|
-
child.once('spawn', () => {
|
|
259
|
-
writeSync(2, input.targetStartedMarker);
|
|
260
|
-
child.stderr.pipe(process.stderr);
|
|
261
|
-
});
|
|
262
|
-
child.once('error', (error) => {
|
|
263
|
-
process.stderr.write((error instanceof Error ? error.message : String(error)) + '\n');
|
|
264
|
-
process.exitCode = 1;
|
|
265
|
-
});
|
|
266
|
-
child.once('exit', (code, signal) => {
|
|
267
|
-
process.exitCode = signal ? 1 : code ?? 1;
|
|
268
|
-
});
|
|
269
|
-
`,zr="eval(Buffer.from(process.argv[1],'base64').toString('utf8'))",Vr=JSON.stringify(zr),Yr=Buffer.from(Hr,"utf8").toString("base64"),Zr=JSON.stringify(Yr),Qr=gt(),Lt=String.raw`
|
|
270
|
-
import { spawn } from 'node:child_process';
|
|
271
|
-
import { randomUUID } from 'node:crypto';
|
|
272
|
-
import { readFile, rm, writeFile } from 'node:fs/promises';
|
|
273
|
-
import { realpathSync, statSync } from 'node:fs';
|
|
274
|
-
import path from 'node:path';
|
|
275
|
-
let SandboxManager;
|
|
276
|
-
const request = JSON.parse(await readFile(process.argv[2], 'utf8'));
|
|
277
|
-
await rm(process.argv[2], { force: true });
|
|
278
|
-
const targetStartedMarker = request.targetStartedMarker
|
|
279
|
-
?? '\u0000KODAX_ASRT_TARGET_STARTED:' + randomUUID() + '\u0000\n';
|
|
280
|
-
const endpoints = new Set(request.endpoints.map((item) => item.host.toLowerCase() + ':' + item.port));
|
|
281
|
-
const callback = request.allowAllNetwork === true
|
|
282
|
-
? async () => true
|
|
283
|
-
: request.endpoints.length === 0
|
|
284
|
-
? undefined
|
|
285
|
-
: async ({ host, port }) => endpoints.has(host.toLowerCase() + ':' + port);
|
|
286
|
-
${Qr}
|
|
287
|
-
const withWindowsChildEnvironment = (argv, environment, gitTrustRoots) => {
|
|
288
|
-
const separator = argv.lastIndexOf('--');
|
|
289
|
-
if (separator < 0) throw new Error('ASRT Windows wrapper omitted its child separator.');
|
|
290
|
-
const requested = [];
|
|
291
|
-
const requestedNames = new Set();
|
|
292
|
-
for (const [name, value] of Object.entries(environment ?? {})) {
|
|
293
|
-
if (value === undefined) continue;
|
|
294
|
-
if (!name || name.includes('=') || name.includes('\0') || value.includes('\0')) {
|
|
295
|
-
throw new Error('Invalid environment entry for ASRT Windows child.');
|
|
296
|
-
}
|
|
297
|
-
const normalized = name.toLowerCase();
|
|
298
|
-
if (requestedNames.has(normalized)) {
|
|
299
|
-
throw new Error('Ambiguous Windows child environment variable: ' + name + '.');
|
|
300
|
-
}
|
|
301
|
-
requestedNames.add(normalized);
|
|
302
|
-
requested.push([name, value]);
|
|
303
|
-
}
|
|
304
|
-
const requestedOverrides = new Set(requested.flatMap(([name]) => (
|
|
305
|
-
['path', 'pathext'].includes(name.toLowerCase()) ? [name.toLowerCase()] : []
|
|
306
|
-
)));
|
|
307
|
-
const controlled = new Set();
|
|
308
|
-
const prefix = [];
|
|
309
|
-
for (let index = 0; index < separator; index += 1) {
|
|
310
|
-
if (argv[index] !== '--env' || index + 1 >= separator) {
|
|
311
|
-
prefix.push(argv[index]);
|
|
312
|
-
continue;
|
|
313
|
-
}
|
|
314
|
-
const assignment = argv[index + 1];
|
|
315
|
-
const name = assignment.split('=', 1)[0]?.toLowerCase();
|
|
316
|
-
if (name) controlled.add(name);
|
|
317
|
-
if (!name || !requestedOverrides.has(name)) prefix.push(argv[index], assignment);
|
|
318
|
-
index += 1;
|
|
319
|
-
}
|
|
320
|
-
const injected = [];
|
|
321
|
-
for (const [name, value] of requested) {
|
|
322
|
-
const normalized = name.toLowerCase();
|
|
323
|
-
if (controlled.has(normalized) && normalized !== 'path' && normalized !== 'pathext') continue;
|
|
324
|
-
injected.push('--env', name + '=' + value);
|
|
325
|
-
}
|
|
326
|
-
const result = [...prefix, ...injected, ...argv.slice(separator)];
|
|
327
|
-
const withGitTrust = rewriteWindowsGitSafeDirectoryArgv(result, gitTrustRoots);
|
|
328
|
-
const estimate = withGitTrust.reduce((size, value) => size + value.length + 3, 0);
|
|
329
|
-
if (estimate > 30000) throw new Error('ASRT Windows child environment exceeds the CreateProcess command-line limit.');
|
|
330
|
-
return withGitTrust;
|
|
331
|
-
};
|
|
332
|
-
const writeObservation = async (observation) => {
|
|
333
|
-
if (typeof request.observationFile !== 'string') return;
|
|
334
|
-
await writeFile(request.observationFile, JSON.stringify(observation), { mode: 0o600 });
|
|
335
|
-
};
|
|
336
|
-
const waitForTarget = (target, observation) => {
|
|
337
|
-
const marker = Buffer.from(targetStartedMarker, 'utf8');
|
|
338
|
-
let pending = Buffer.alloc(0);
|
|
339
|
-
let diagnostic = Buffer.alloc(0);
|
|
340
|
-
let processError;
|
|
341
|
-
let wrapperSpawned = false;
|
|
342
|
-
let targetStarted = false;
|
|
343
|
-
let observationWrite = Promise.resolve();
|
|
344
|
-
return new Promise((resolve, reject) => {
|
|
345
|
-
let settled = false;
|
|
346
|
-
target.once('spawn', () => {
|
|
347
|
-
wrapperSpawned = true;
|
|
348
|
-
});
|
|
349
|
-
const finish = (result) => {
|
|
350
|
-
if (settled) return;
|
|
351
|
-
settled = true;
|
|
352
|
-
void observationWrite.then(() => resolve(result), reject);
|
|
353
|
-
};
|
|
354
|
-
target.stderr.on('data', (chunk) => {
|
|
355
|
-
if (targetStarted) {
|
|
356
|
-
process.stderr.write(chunk);
|
|
357
|
-
return;
|
|
358
|
-
}
|
|
359
|
-
pending = Buffer.concat([pending, Buffer.from(chunk)]);
|
|
360
|
-
const markerOffset = pending.indexOf(marker);
|
|
361
|
-
if (markerOffset >= 0) {
|
|
362
|
-
targetStarted = true;
|
|
363
|
-
const suffix = pending.subarray(markerOffset + marker.length);
|
|
364
|
-
pending = Buffer.alloc(0);
|
|
365
|
-
diagnostic = Buffer.alloc(0);
|
|
366
|
-
observationWrite = writeObservation(observation).catch(() => undefined);
|
|
367
|
-
if (suffix.length > 0) process.stderr.write(suffix);
|
|
368
|
-
return;
|
|
369
|
-
}
|
|
370
|
-
const retained = Math.max(0, marker.length - 1);
|
|
371
|
-
if (pending.length > retained) {
|
|
372
|
-
diagnostic = Buffer.concat([
|
|
373
|
-
diagnostic,
|
|
374
|
-
pending.subarray(0, pending.length - retained),
|
|
375
|
-
]).subarray(-65536);
|
|
376
|
-
pending = pending.subarray(pending.length - retained);
|
|
377
|
-
}
|
|
378
|
-
});
|
|
379
|
-
target.once('error', (error) => {
|
|
380
|
-
processError = error instanceof Error ? error.message : String(error);
|
|
381
|
-
});
|
|
382
|
-
target.once('close', (exitCode, signal) => {
|
|
383
|
-
const preTarget = Buffer.concat([diagnostic, pending]).toString('utf8').trim();
|
|
384
|
-
finish({
|
|
385
|
-
exitCode: signal ? 1 : exitCode ?? 1,
|
|
386
|
-
targetStarted,
|
|
387
|
-
spawnFailedBeforeSpawn: processError !== undefined && !wrapperSpawned,
|
|
388
|
-
diagnostic: preTarget || processError || undefined,
|
|
389
|
-
});
|
|
390
|
-
});
|
|
391
|
-
});
|
|
392
|
-
};
|
|
393
|
-
let child;
|
|
394
|
-
let targetStarted = false;
|
|
395
|
-
let normalFallbackAttempted = false;
|
|
396
|
-
const runDirect = async () => {
|
|
397
|
-
const internalElectronNode = request.command === process.execPath && process.versions.electron !== undefined;
|
|
398
|
-
const directArgs = internalElectronNode
|
|
399
|
-
? ['--import', ${vt}, ...request.args]
|
|
400
|
-
: request.args;
|
|
401
|
-
const directEnv = internalElectronNode
|
|
402
|
-
? { ...request.env, [${Wn}]: '1' }
|
|
403
|
-
: request.env;
|
|
404
|
-
child = spawn(request.command, directArgs, {
|
|
405
|
-
cwd: request.cwd,
|
|
406
|
-
env: directEnv,
|
|
407
|
-
shell: false,
|
|
408
|
-
stdio: 'inherit',
|
|
409
|
-
windowsHide: true,
|
|
410
|
-
windowsVerbatimArguments: request.windowsVerbatimArguments === true,
|
|
411
|
-
});
|
|
412
|
-
return await new Promise((resolve, reject) => {
|
|
413
|
-
child.once('error', reject);
|
|
414
|
-
child.once('exit', (exitCode, signal) => resolve(signal ? 1 : exitCode ?? 1));
|
|
415
|
-
});
|
|
416
|
-
};
|
|
417
|
-
const runNormalFallback = async () => {
|
|
418
|
-
if (
|
|
419
|
-
request.fallbackToNormalExecution !== true
|
|
420
|
-
|| targetStarted
|
|
421
|
-
|| normalFallbackAttempted
|
|
422
|
-
) return false;
|
|
423
|
-
await writeObservation({
|
|
424
|
-
version: 1,
|
|
425
|
-
state: 'fallback',
|
|
426
|
-
reason: 'backend_failed',
|
|
427
|
-
execution: 'normal_permission_policy',
|
|
428
|
-
}).catch(() => undefined);
|
|
429
|
-
normalFallbackAttempted = true;
|
|
430
|
-
process.exitCode = await runDirect();
|
|
431
|
-
return true;
|
|
432
|
-
};
|
|
433
|
-
try {
|
|
434
|
-
if (request.wrappedInvocation) {
|
|
435
|
-
const wrapped = request.wrappedInvocation;
|
|
436
|
-
child = spawn(wrapped.executable, wrapped.args, {
|
|
437
|
-
cwd: request.cwd,
|
|
438
|
-
env: wrapped.env,
|
|
439
|
-
shell: wrapped.shell,
|
|
440
|
-
stdio: ['inherit', 'inherit', 'pipe'],
|
|
441
|
-
windowsHide: true,
|
|
442
|
-
});
|
|
443
|
-
const result = await waitForTarget(child, {
|
|
444
|
-
version: 1,
|
|
445
|
-
state: 'applied',
|
|
446
|
-
backend: request.observationBackend ?? 'unsupported',
|
|
447
|
-
policyId: 'kodax-workspace-shell-v1',
|
|
448
|
-
});
|
|
449
|
-
targetStarted = result.targetStarted;
|
|
450
|
-
const fellBack = result.spawnFailedBeforeSpawn
|
|
451
|
-
? await runNormalFallback()
|
|
452
|
-
: false;
|
|
453
|
-
if (!targetStarted && !fellBack) {
|
|
454
|
-
process.stderr.write((result.diagnostic || 'Sandbox target launch could not be attested.') + '\n');
|
|
455
|
-
}
|
|
456
|
-
if (!fellBack) process.exitCode = targetStarted ? result.exitCode : 1;
|
|
457
|
-
} else {
|
|
458
|
-
({ SandboxManager } = await import(process.argv[1]));
|
|
459
|
-
const bootstrap = request.bootstrapCommand ?? 'node';
|
|
460
|
-
const bootstrapIsAbsolute = /^(?:[A-Za-z]:[\\/]|\\\\)/.test(bootstrap);
|
|
461
|
-
const bootstrapIsElectronNode = bootstrap === process.execPath
|
|
462
|
-
&& process.versions.electron !== undefined;
|
|
463
|
-
const config = process.platform === 'win32' && bootstrapIsAbsolute
|
|
464
|
-
? {
|
|
465
|
-
...request.config,
|
|
466
|
-
filesystem: {
|
|
467
|
-
...request.config.filesystem,
|
|
468
|
-
allowRead: [...new Set([
|
|
469
|
-
...request.config.filesystem.allowRead,
|
|
470
|
-
bootstrap,
|
|
471
|
-
path.dirname(bootstrap),
|
|
472
|
-
])],
|
|
473
|
-
},
|
|
474
|
-
}
|
|
475
|
-
: request.config;
|
|
476
|
-
await SandboxManager.initialize(config, callback);
|
|
477
|
-
const quote = (value) => process.platform === 'win32'
|
|
478
|
-
? '"' + value.replaceAll('"', '""') + '"'
|
|
479
|
-
: "'" + value.replaceAll("'", "'\"'\"'") + "'";
|
|
480
|
-
const internalElectronNode = request.command === process.execPath && process.versions.electron !== undefined;
|
|
481
|
-
const childArgs = internalElectronNode
|
|
482
|
-
? ['--import', ${vt}, ...request.args]
|
|
483
|
-
: request.args;
|
|
484
|
-
const command = [
|
|
485
|
-
quote(bootstrap),
|
|
486
|
-
'-e',
|
|
487
|
-
quote(${Vr}),
|
|
488
|
-
${Zr},
|
|
489
|
-
Buffer.from(JSON.stringify({
|
|
490
|
-
command: request.command,
|
|
491
|
-
args: childArgs,
|
|
492
|
-
windowsVerbatimArguments: request.windowsVerbatimArguments === true,
|
|
493
|
-
cwd: request.cwd,
|
|
494
|
-
targetStartedMarker,
|
|
495
|
-
electronRunAsNode: internalElectronNode,
|
|
496
|
-
}), 'utf8').toString('base64'),
|
|
497
|
-
].join(' ');
|
|
498
|
-
if (process.platform === 'win32') {
|
|
499
|
-
const wrapped = await SandboxManager.wrapWithSandboxArgv(command, 'cmd', undefined, undefined, request.cwd);
|
|
500
|
-
const requestedEnv = internalElectronNode || bootstrapIsElectronNode
|
|
501
|
-
? { ...request.env, [${Wn}]: '1' }
|
|
502
|
-
: request.env;
|
|
503
|
-
const childArgv = withWindowsChildEnvironment(wrapped.argv, requestedEnv, windowsGitTrustRoots(request));
|
|
504
|
-
child = spawn(childArgv[0], childArgv.slice(1), {
|
|
505
|
-
cwd: request.cwd,
|
|
506
|
-
env: wrapped.env,
|
|
507
|
-
shell: false,
|
|
508
|
-
stdio: ['inherit', 'inherit', 'pipe'],
|
|
509
|
-
windowsHide: true,
|
|
510
|
-
});
|
|
511
|
-
} else {
|
|
512
|
-
const wrapped = await SandboxManager.wrapWithSandbox(command);
|
|
513
|
-
const childEnv = internalElectronNode || bootstrapIsElectronNode
|
|
514
|
-
? { ...request.env, [${Wn}]: '1' }
|
|
515
|
-
: request.env;
|
|
516
|
-
child = spawn(wrapped, {
|
|
517
|
-
cwd: request.cwd,
|
|
518
|
-
env: childEnv,
|
|
519
|
-
shell: true,
|
|
520
|
-
stdio: ['inherit', 'inherit', 'pipe'],
|
|
521
|
-
});
|
|
522
|
-
}
|
|
523
|
-
const stop = () => child?.kill('SIGTERM');
|
|
524
|
-
process.once('SIGINT', stop);
|
|
525
|
-
process.once('SIGTERM', stop);
|
|
526
|
-
const result = await waitForTarget(child, {
|
|
527
|
-
version: 1,
|
|
528
|
-
state: 'applied',
|
|
529
|
-
backend: request.observationBackend ?? 'unsupported',
|
|
530
|
-
policyId: 'kodax-workspace-shell-v1',
|
|
531
|
-
});
|
|
532
|
-
targetStarted = result.targetStarted;
|
|
533
|
-
try { SandboxManager.cleanupAfterCommand(); } catch {}
|
|
534
|
-
await SandboxManager.reset().catch(() => undefined);
|
|
535
|
-
const fellBack = result.spawnFailedBeforeSpawn
|
|
536
|
-
? await runNormalFallback()
|
|
537
|
-
: false;
|
|
538
|
-
if (!targetStarted && !fellBack) {
|
|
539
|
-
process.stderr.write((result.diagnostic || 'Sandbox target launch could not be attested.') + '\n');
|
|
540
|
-
}
|
|
541
|
-
if (!fellBack) process.exitCode = targetStarted ? result.exitCode : 1;
|
|
542
|
-
}
|
|
543
|
-
} catch (error) {
|
|
544
|
-
await SandboxManager?.reset().catch(() => undefined);
|
|
545
|
-
if (
|
|
546
|
-
request.fallbackToNormalExecution === true
|
|
547
|
-
&& !targetStarted
|
|
548
|
-
&& !normalFallbackAttempted
|
|
549
|
-
&& child === undefined
|
|
550
|
-
) {
|
|
551
|
-
try {
|
|
552
|
-
await runNormalFallback();
|
|
553
|
-
} catch (fallbackError) {
|
|
554
|
-
process.stderr.write((fallbackError instanceof Error ? fallbackError.message : String(fallbackError)) + '\n');
|
|
555
|
-
process.exitCode = 1;
|
|
556
|
-
}
|
|
557
|
-
} else {
|
|
558
|
-
process.stderr.write((error instanceof Error ? error.message : String(error)) + '\n');
|
|
559
|
-
process.exitCode = 1;
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
`,xe,tn=0,eo=3e4,Be,Xe,Dn=!1,le;function fe(e){return e instanceof Error?e.message:String(e)}s(fe,"errorText");function Je(e,...t){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}s(Je,"isFileSystemError");async function xt(e){try{return await Pe(e)}catch(t){if(Je(t,"ENOENT"))return;throw t}}s(xt,"readFileIfPresent");async function no(e,t){let n=await xt(t);if(n?.equals(e))return;if(n!==void 0)throw new Error(`Prepared Windows sandbox runner failed integrity verification: ${t}.`);let r=`${t}.${process.pid}.${H()}.tmp`;try{await Ce(r,e,{flag:"wx",mode:448});try{await _r(r,t)}catch(o){if(!(await xt(t))?.equals(e))throw o}}finally{await z(r,{force:!0})}}s(no,"installWindowsRunnerCopy");async function Ue(){if(Be===void 0){let e=(async()=>{let t=await Pe(Br()),n=Ye("sha256").update(t).digest("hex").slice(0,16),r=d.join(d.resolve(q()),"sandbox-runtime","runner",ue,process.arch,n),o=d.join(r,"srt-win.exe");await J(vn(),{recursive:!0,mode:448}),await J(r,{recursive:!0,mode:448}),await no(t,o);let i={path:o,directory:r,srtWin:Gr({path:o})};return Xe=i,i})();Be=e,e.catch(()=>{Be===e&&(Be=void 0,Xe=void 0)})}return Be}s(Ue,"prepareWindowsSandboxRunner");function We(){if(process.platform!=="win32")throw new Error("A prepared Windows sandbox runner was requested on a non-Windows platform.");if(Xe===void 0)throw new Error("Windows sandbox runner is not prepared; run the sandbox readiness check first.");return Xe}s(We,"requirePreparedWindowsRunner");var I=new Set,X=new Map,$n,Q=35e3,we="[acl_cleanup_unconfirmed]",B=class extends Error{static{s(this,"WindowsSandboxAclAdmissionError")}recoveryAction;constructor(t,n){super(t,n),this.name="WindowsSandboxAclAdmissionError",this.recoveryAction=n?.recoveryAction}};function Dt(e){return/^windows-boot-\d+$/.test(e)}s(Dt,"isCanonicalWindowsBootIdentity");function Sn(e){return e.diagnostics.some(t=>t.startsWith(we))}s(Sn,"doctorHasWindowsSandboxAclCleanupBlock");function bn(){let e=Object.entries(process.env).find(([t,n])=>t.toUpperCase()==="PROGRAMDATA"&&n!==void 0)?.[1]??"C:\\ProgramData";return d.join(d.resolve(e),"KodaX","sandbox-runtime","acl-poison")}s(bn,"windowsSandboxAclPoisonDirectory");function vn(){return d.dirname(bn())}s(vn,"windowsSandboxAclCoordinationDirectory");function Zn(e=q()){return d.join(d.resolve(e),"sandbox-runtime","acl-poison")}s(Zn,"legacyWindowsSandboxAclPoisonDirectory");function to(){return d.join(vn(),"acl-poison-staging")}s(to,"windowsSandboxAclPoisonStagingDirectory");function ro(e=q()){return d.join(d.resolve(e),"sandbox-runtime","acl-poison-staging")}s(ro,"legacyWindowsSandboxAclPoisonStagingDirectory");function ee(){return d.join(vn(),"acl-recovery.lock")}s(ee,"windowsSandboxAclRecoveryLockFile");function Bt(e){let t=JSON.parse(e);if(typeof t!="object"||t===null)throw new Error("Windows sandbox ACL poison marker is not an object.");let n=t;if(n.version!==1&&n.version!==2||n.state!==void 0&&n.state!=="active"&&n.state!=="unconfirmed"||n.policyKey!==void 0&&typeof n.policyKey!="string"||n.holderPid!==void 0&&(typeof n.holderPid!="number"||!Number.isSafeInteger(n.holderPid)||n.holderPid<=0)||n.holderProcessStartIdentity!==void 0&&typeof n.holderProcessStartIdentity!="string"||n.pid!==void 0&&(typeof n.pid!="number"||!Number.isSafeInteger(n.pid)||n.pid<=0)||n.processStartIdentity!==void 0&&typeof n.processStartIdentity!="string"||n.windowsBootIdentity!==void 0&&(typeof n.windowsBootIdentity!="string"||!Dt(n.windowsBootIdentity)))throw new Error("Windows sandbox ACL poison marker has an invalid owner identity.");return{version:n.version,...n.state==="active"||n.state==="unconfirmed"?{state:n.state}:{},...typeof n.policyKey=="string"?{policyKey:n.policyKey}:{},...typeof n.holderPid=="number"?{holderPid:n.holderPid}:{},...typeof n.holderProcessStartIdentity=="string"?{holderProcessStartIdentity:n.holderProcessStartIdentity}:{},...typeof n.pid=="number"?{pid:n.pid}:{},...typeof n.processStartIdentity=="string"?{processStartIdentity:n.processStartIdentity}:{},...typeof n.windowsBootIdentity=="string"?{windowsBootIdentity:n.windowsBootIdentity}:{}}}s(Bt,"parseWindowsSandboxAclPoisonOwner");function re(e=q()){return[...new Set([bn(),Zn(e)])].flatMap(n=>{let r;try{r=Un(n)}catch(o){if(Je(o,"ENOENT"))return[];throw o}return r.filter(o=>o.endsWith(".json")).map(o=>{let i=d.join(n,o);try{let c=yn(i);if(!c.isFile()||c.isSymbolicLink())throw new Error("Windows sandbox ACL poison marker is not a regular file.");let a=Bt(Wt(i,"utf8"));return{file:i,owner:d.basename(i).startsWith("unconfirmed-")?{...a,state:"unconfirmed"}:a}}catch(c){throw new B(`Windows sandbox ACL cleanup was not confirmed because its poison marker is unreadable: ${i}. `+Bn(),{cause:c,recoveryAction:"manual-recovery"})}})})}s(re,"readWindowsSandboxAclPoisonOwners");function de(){if(process.platform!=="win32")return;if($n!==void 0)return $n??void 0;let e=String.raw`
|
|
563
|
-
# KodaXWindowsBootIdentity-v1
|
|
564
|
-
$boot = (Get-CimInstance Win32_OperatingSystem -ErrorAction Stop).LastBootUpTime
|
|
565
|
-
[Console]::Out.Write($boot.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture))
|
|
566
|
-
`,t=Ve(rr(),["-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(e,"utf16le").toString("base64")],{encoding:"utf8",timeout:5e3,windowsHide:!0}),n=t.status===0?t.stdout.trim():"",r=/^\d+$/.test(n)?`windows-boot-${n}`:void 0;return $n=r??null,r}s(de,"readWindowsBootIdentity");function Oi(){return de()}s(Oi,"readWindowsSandboxBootIdentity");function Bn(){return`After stopping every KodaX and KodaX Space process, run "${Xe?.path??"srt-win.exe"}" acl recover --force --json, then delete "${bn()}" and "${Zn()}".`}s(Bn,"windowsSandboxAclManualRecoveryInstruction");function Ft(e,t=de()){if(e.find(({windowsBootIdentity:i})=>i===void 0||t===void 0)!==void 0)return new B("An unconfirmed Windows sandbox process tree has no verifiable Windows boot identity. "+Bn());let r=e[0],o=r?.pid===void 0?"":` (last root PID ${r.pid})`;return new B(`An unconfirmed Windows sandbox process tree${o} from the same Windows boot may still have live descendants; restart Windows before retrying. `+Bn())}s(Ft,"persistentWindowsSandboxAclPoisonError");function Fn(e,t,n="unconfirmed",r){if(process.platform!=="win32")return;let o=de(),i=Le(process.pid),c=H(),a=`${n==="unconfirmed"?"unconfirmed-":""}owner-${c}.json`,l=JSON.stringify({version:1,state:n,...r===void 0?{}:{policyKey:r},holderPid:process.pid,...i===void 0?{}:{holderProcessStartIdentity:i},...e===void 0?{}:{pid:e},...t===void 0?{}:{processStartIdentity:t},...o===void 0?{}:{windowsBootIdentity:o}}),u=s((w,f)=>{ht(w,{recursive:!0,mode:448});let p=d.join(w,a);if(n==="unconfirmed")return St(p,l,{flag:"wx",mode:384}),p;ht(f,{recursive:!0,mode:448});let y=d.join(f,`owner-${c}.tmp`);return St(y,l,{flag:"wx",mode:384}),Nn(y,p),p},"persist"),m=u(bn(),to());try{let w=u(Zn(),ro());X.set(m,w)}catch(w){if(n==="active")try{pe(m,{force:!0})}catch(f){throw new AggregateError([w,f],"Windows sandbox owner compatibility marker and primary rollback both failed.")}throw w}return m}s(Fn,"persistWindowsSandboxAclPoisonOwner");function oo(e){let t=Fn(void 0,void 0,"active",e);if(t!==void 0){I.add(t);let n=X.get(t);n!==void 0&&I.add(n)}return t}s(oo,"createWindowsSandboxAclOwnerMarker");function Me(e){if(e===void 0)return;let t=X.get(e);try{t!==void 0&&pe(t,{force:!0}),pe(e,{force:!0}),I.delete(e),t!==void 0&&I.delete(t),X.delete(e)}catch(n){throw I.delete(e),t!==void 0&&I.delete(t),me(n),new Error("Windows sandbox owner poison marker could not be cleared.",{cause:n})}}s(Me,"confirmWindowsSandboxAclOwnerStopped");async function rn(e,t){me(t);let n=await Qn(e,void 0,void 0,t);if(me(n),n!==t)throw n}s(rn,"retainWindowsSandboxAclOwnerPoison");function Mt(e,t,n){if(e===void 0)return Fn(t,n,"unconfirmed");let r=X.get(e),o=d.join(d.dirname(e),`unconfirmed-${d.basename(e)}`),i=r===void 0?void 0:d.join(d.dirname(r),`unconfirmed-${d.basename(r)}`);if(Tt(o))return I.delete(e),r!==void 0&&I.delete(r),i!==void 0&&X.set(o,i),X.delete(e),o;try{return Nn(e,o),r!==void 0&&i!==void 0&&Nn(r,i),I.delete(e),r!==void 0&&I.delete(r),i!==void 0&&X.set(o,i),X.delete(e),o}catch(c){try{let a=Fn(t,n,"unconfirmed");return I.delete(e),r!==void 0&&I.delete(r),X.delete(e),a}catch(a){throw I.delete(e),r!==void 0&&I.delete(r),X.delete(e),new AggregateError([c,a],"Windows sandbox ACL poison write-ahead failed.")}}}s(Mt,"writeAheadWindowsSandboxAclOwnerPoison");async function Qn(e,t,n,r){if(process.platform!=="win32")return r;let o;try{return o=Mt(e,t,n),await U(ee(),async()=>{},Q),r}catch(i){return new AggregateError([r,i],o===void 0?"Windows sandbox owner termination and durable ACL poison recording both failed.":"Windows sandbox owner termination was not confirmed and ACL poison serialization failed.")}}s(Qn,"transitionWindowsSandboxAclOwnerToPoison");function io(e,t){return I.has(e)}s(io,"isVerifiedActiveWindowsSandboxAclOwner");function et(e){if(e.state!=="active"||e.holderPid===void 0||e.holderProcessStartIdentity===void 0)return"stale";let t=Le(e.holderPid);if(t!==void 0)return t===e.holderProcessStartIdentity?"live":"stale";try{return process.kill(e.holderPid,0),"unknown"}catch(n){return Je(n,"ESRCH")?"stale":"unknown"}}s(et,"windowsSandboxAclOwnerLiveness");function nt(e,t,n){return t.state!=="active"?!1:I.has(e)?n===void 0||t.policyKey===n:n!==void 0&&t.policyKey===n&&et(t)==="live"}s(nt,"isCompatibleWindowsSandboxAclOwner");function tt(e){let t=re().filter(({file:n,owner:r})=>!nt(n,r,e));if(t.length!==0)throw Ft(t.map(({owner:n})=>n))}s(tt,"assertNoPersistentWindowsSandboxAclPoison");async function Gt(e,t,n,r){let o=new Error(n);if(process.platform==="win32"){let i=await Qn(r,e,t,o);return me(i),i instanceof Error?i:o}return me(o),o}s(Gt,"recordUnconfirmedWindowsSandboxOwner");function jt(e){return process.platform==="win32"?`${e} process-tree termination was not confirmed; restart Windows before retrying.`:`${e} process-tree termination was not confirmed; stop the retained process tree before retrying.`}s(jt,"unconfirmedSandboxProcessTreeMessage");function Te(e=3e4){let t=We(),n=Ve(t.srtWin.exe,[...t.srtWin.prependArgs,"acl","recover","--json"],{cwd:t.directory,encoding:"utf8",timeout:Math.max(1,Math.min(3e4,e)),windowsHide:!0}),r=(n.stderr??"").trim();if(n.error)throw new Error(`Windows sandbox ACL recovery failed to start: ${n.error.message}`,{cause:n.error});let o;try{o=JSON.parse((n.stdout??"").trim())}catch(c){throw new Error(`Windows sandbox ACL recovery failed with unparseable output (exit ${String(n.status)}): ${r||"(empty stderr)"}.`,{cause:c})}let i=typeof o=="object"&&o!==null?o:void 0;if(n.status!==0||typeof i?.deadBrokers!="number"||!Number.isSafeInteger(i.deadBrokers)||i.deadBrokers<0||typeof i.acesRevoked!="number"||!Number.isSafeInteger(i.acesRevoked)||i.acesRevoked<0)throw new Error(`Windows sandbox ACL recovery failed (exit ${String(n.status)}${n.signal?`, signal ${n.signal}`:""}): ${r||"(empty stderr)"}.`);Dn=!0}s(Te,"recoverWindowsSandboxAcls");async function Ii(e,t,n,r=7e4){if(process.platform!=="win32")return 0;if(t.processStartIdentity===void 0)throw new Error("Windows sandbox ACL recovery requires an exact daemon process identity.");let o=Date.now()+r;return U(ee(),async()=>{let i=re(e),c=i.filter(({owner:l})=>l.holderPid===t.pid&&l.holderProcessStartIdentity===t.processStartIdentity&&l.windowsBootIdentity===n);if(c.length!==i.length)throw new B("Windows sandbox ACL recovery found a foreign or unverifiable owner marker.");if(c.length===0)return 0;await qt(Ue(),Math.max(1,o-Date.now()));let a=o-Date.now();if(a<=0)throw new Error("Windows sandbox ACL recovery deadline expired before mutation.");return Te(a),c.length},Math.max(1,Math.min(Q,r)))}s(Ii,"recoverWindowsSandboxAclsForRuntimeOwner");async function Ni(e,t=7e4){if(process.platform!=="win32")return 0;let n=Date.now()+t;return U(ee(),async()=>{let r=re(e);if(r.length===0)return 0;Kt(r),await qt(Ue(),Math.max(1,n-Date.now()));let o=n-Date.now();if(o<=0)throw new Error("Windows sandbox ACL recovery deadline expired before mutation.");return Te(o),r.length},Math.max(1,Math.min(Q,t)))}s(Ni,"recoverPreviousBootWindowsSandboxAcls");function Kt(e){let t=de();if(t===void 0||!Dt(t))throw new B("Windows sandbox ACL recovery could not verify the current boot identity.",{recoveryAction:"restart-system"});if(e.some(({owner:n})=>n.windowsBootIdentity===void 0))throw new B("Windows sandbox ACL recovery found an unverifiable owner marker.",{recoveryAction:"manual-recovery"});if(e.some(({owner:n})=>n.windowsBootIdentity===t))throw new B("Windows sandbox ACL recovery found a current-boot owner marker.",{recoveryAction:"restart-system"})}s(Kt,"assertPreviousBootWindowsSandboxAclMarkers");async function qt(e,t){let n,r=new Promise((o,i)=>{n=setTimeout(()=>i(new Error("Windows sandbox runner preparation timed out.")),t)});try{return await Promise.race([e,r])}finally{n!==void 0&&clearTimeout(n)}}s(qt,"waitForWindowsSandboxRunnerPreparation");async function Li(e,t,n,r=4e4){if(process.platform!=="win32")return 0;if(t.processStartIdentity===void 0)throw new Error("Windows sandbox marker cleanup requires an exact daemon process identity.");return U(ee(),async()=>{let o=re(e),i=o.filter(({owner:c})=>c.holderPid===t.pid&&c.holderProcessStartIdentity===t.processStartIdentity&&c.windowsBootIdentity===n);if(i.length!==o.length)throw new B("Windows sandbox marker cleanup found a foreign or unverifiable owner marker.");for(let c of i)pe(c.file,{force:!0});return i.length},Math.max(1,Math.min(Q,r)))}s(Li,"clearWindowsSandboxAclMarkersForRuntimeOwner");async function Di(e,t=4e4){return process.platform!=="win32"?0:U(ee(),async()=>{let n=re(e);if(n.length===0)return 0;Kt(n);for(let r of n)pe(r.file,{force:!0});return n.length},Math.max(1,Math.min(Q,t)))}s(Di,"clearPreviousBootWindowsSandboxAclMarkers");function so(e){return e instanceof mt}s(so,"isWindowsSandboxAclRecoveryLockTimeout");var cn=class extends B{static{s(this,"ForeignWindowsSandboxAclOwnerContentionError")}constructor(t){super("Another Windows sandbox owner is active for the shared sandbox account; wait for it to close or stop the other KodaX/KodaX Space process, then retry.",{cause:t}),this.name="ForeignWindowsSandboxAclOwnerContentionError"}},ln=class extends B{static{s(this,"StaleWindowsSandboxAclOwnerContentionError")}constructor(t){super(t.message,{cause:t}),this.name="StaleWindowsSandboxAclOwnerContentionError"}};function Xt(e){!so(e)&&!(e instanceof cn)&&!(e instanceof ln)&&me(e)}s(Xt,"recordWindowsSandboxAclAdmissionFailure");function He(e,t=de()){let n=Ft(e.map(({owner:r})=>r),t);return e.every(({owner:r})=>r.state==="active")?e.some(({owner:r})=>et(r)==="stale")?new ln(n):new cn(n):n}s(He,"windowsSandboxAclPoisonSnapshotError");function ao(){let e=re();if(e.length===0)return;let t=de();if(t!==void 0&&e.every(({owner:r})=>r.windowsBootIdentity!==void 0&&r.windowsBootIdentity!==t)){Te();for(let r of e)pe(r.file,{force:!0});tt();return}return e.every(({owner:r})=>et(r)!=="stale")?new B("Windows sandbox setup cannot run while a sandbox owner is active for the shared Windows sandbox account; wait for sandboxed commands to finish and stop other KodaX or KodaX Space processes, then retry."):He(e,t)}s(ao,"windowsSandboxAclSetupBlockWithLock");function kt(e,t){return{...e,ready:!1,diagnostics:[...e.diagnostics.filter(n=>!n.startsWith(we)),`${we} ${t.message}`]}}s(kt,"withWindowsSandboxAclSetupBlock");function Jt(e){kn();let t=re(),n=t.filter(({file:r,owner:o})=>!nt(r,o,e));if(Dn){if(n.length>0)throw He(n);return}if(n.length>0){let r=de();if(!(r!==void 0&&n.every(({owner:i})=>i.windowsBootIdentity!==void 0&&i.windowsBootIdentity!==r)))throw He(n,r)}if(t.length>0){Dn=!0;return}Te();for(let r of n)pe(r.file,{force:!0});tt(e)}s(Jt,"ensureWindowsSandboxAclRecoveryWithLock");async function un(e){if(process.platform==="win32")try{await U(ee(),async()=>Jt(e),Q)}catch(t){throw Xt(t),t}}s(un,"ensureWindowsSandboxAclRecovery");async function Ut(e){if(process.platform!=="win32")return;let t;try{return await U(ee(),async()=>{try{Jt(e)}catch(n){throw Xt(n),n}return t=oo(e),t},Q)}catch(n){if(t===void 0)throw n;try{Me(t)}catch(r){throw new AggregateError([n,r],"Windows sandbox owner admission and marker cleanup both failed.")}throw n}}s(Ut,"admitWindowsSandboxAclOwner");async function Mn(e){if(process.platform!=="win32")return;let t;try{if(e===void 0||!I.has(e))return;if(t=Bt(Wt(e,"utf8")).policyKey,t!==void 0){await U(ee(),async()=>{let r=X.get(e),o=new Set([e,r].filter(a=>a!==void 0)),i=re().filter(({file:a})=>!o.has(a)),c=i.filter(({file:a,owner:l})=>!nt(a,l,t));if(c.length>0)throw He(c);if(i.length>0){Me(e);return}Te(),Me(e)},Q);return}let n=Mt(e,void 0,void 0);await U(ee(),async()=>{Te(),Me(n),e!==n&&Me(e)},Q)}catch(n){let r=t===void 0?n:await Qn(e,void 0,void 0,n);throw me(r),r}}s(Mn,"confirmWindowsSandboxAclRecovery");function _n(){le!==void 0&&(Ot({sandboxUserSid:le.sandboxUserSid,holderPid:process.pid,srtWin:le.runner.srtWin}),le=void 0)}s(_n,"releasePreparedWindowsRunnerGrant");function co(e,t){if(!(le?.runner.path===e.path&&le.sandboxUserSid===t)){process.removeListener("exit",_n),_n();try{Fr({read:[e.directory,e.path],write:[],sandboxUserSid:t,holderPid:process.pid,srtWin:e.srtWin})}catch(n){try{Ot({sandboxUserSid:t,holderPid:process.pid,srtWin:e.srtWin})}catch(r){throw new AggregateError([n,r],"Windows sandbox runner ACL grant failed and its partial grant could not be revoked.")}throw n}le={runner:e,sandboxUserSid:t},process.once("exit",_n)}}s(co,"retainPreparedWindowsRunnerGrant");async function lo(){let[e,t]=Dr;for(let n=0;n<5;n+=1){let r=Nr();r.listen(0,"127.0.0.1"),await yt(r,"listening");let o=r.address();if(typeof o=="object"&&o!==null&&(o.port<e||o.port>t))return{server:r,target:`127.0.0.1:${o.port}`};let i=yt(r,"close");r.close(),await i}throw new Error(`[wfp_probe_bind_failed] Could not bind a loopback listener outside the Windows sandbox proxy range [${e},${t}].`)}s(lo,"bindWindowsWfpProbe");function At(e){return/0x80070005|access (?:is )?denied|拒绝访问/i.test(e)?"runner_launch_access_denied":/seclogon|secondary logon/i.test(e)?"secondary_logon_unavailable":"wfp_probe_failed"}s(At,"windowsRunnerFailureCode");function uo(e){return Je(e,"ETIMEDOUT")?"wfp_probe_timeout":Je(e,"EACCES","EPERM")?"runner_launch_access_denied":"runner_spawn_failed"}s(uo,"windowsRunnerSpawnFailureCode");async function fo(e){let{server:t,target:n}=await lo();try{let r=Ve(e.srtWin.exe,[...e.srtWin.prependArgs,"wfp","verify","--target",n],{cwd:e.directory,encoding:"utf8",timeout:3e4,windowsHide:!0}),o=(r.stderr??"").trim();if(r.error)throw new Error(`[${uo(r.error)}] Windows sandbox runner failed to start: ${r.error.message}`);let i;try{i=JSON.parse((r.stdout??"").trim())}catch{let c=r.status===null?"wfp_probe_timeout":At(o);throw new Error(`[${c}] Windows sandbox WFP probe exited ${String(r.status)}${r.signal?` (signal ${r.signal})`:""} with unparseable output; stderr: ${o||"(empty)"}.`)}if(r.status===3)throw new Error(`[wfp_fence_inactive] Direct outbound access to ${String(i.target??n)} succeeded. Run "kodax sandbox setup" to reinstall the Windows network policy.`);if(r.status!==0||i.egress_probe!=="blocked")throw new Error(`[${At(o)}] Windows sandbox WFP probe to ${String(i.target??n)} was ${String(i.egress_probe)} (exit ${String(r.status)}): ${o||"(empty stderr)"}.`)}finally{t.close()}}s(fo,"verifyPreparedWindowsWfp");function Ht(e){let t=[];return e.provisioned||t.push("Windows sandbox account does not exist."),e.sid||t.push("Windows sandbox account SID is unavailable."),(!e.groupExists||!e.groupSid)&&t.push("Windows sandbox local group is unavailable."),e.inBuiltinUsers||t.push("Windows sandbox account is not in the built-in Users group."),e.inSandboxGroup||t.push("Windows sandbox account is not in the sandbox-runtime-users group."),e.hiddenFromLogon||t.push("Windows sandbox account is not hidden from interactive logon."),e.credPresent||t.push("Windows sandbox account credential is unavailable."),t}s(Ht,"windowsSandboxAccountDiagnostics");function po(e){let t=JSON.parse(e);if(typeof t!="object"||t===null)return;let n=t;if(n.version===1&&(n.state==="applied"&&n.policyId==="kodax-workspace-shell-v1"&&(n.backend==="windows-restricted-user"||n.backend==="macos-seatbelt"||n.backend==="linux-bubblewrap"||n.backend==="unsupported")||n.state==="fallback"&&n.reason==="backend_failed"&&n.execution==="normal_permission_policy"))return n}s(po,"parseBrokerObservation");function xn(){return process.env.KODAX_A2A_NODE!==void 0?process.env.KODAX_A2A_NODE:process.versions.electron!==void 0?process.execPath:process.env.KODAX_BUNDLED==="true"?"node":process.execPath}s(xn,"sandboxJavaScriptCommand");async function te(e={}){if(e.refresh||xe===void 0||Date.now()>=tn){let t=wo();xe=t,tn=Number.POSITIVE_INFINITY,t.then(n=>{xe===t&&(tn=n.ready?Number.POSITIVE_INFINITY:Date.now()+eo)},()=>{xe===t&&(xe=void 0,tn=0)})}return xe}s(te,"doctorSandboxRuntime");async function wo(){let e=[],t=!1;Tn.isSupportedPlatform()||e.push(`Unsupported platform: ${process.platform}.`);let n=process.platform==="win32"?{errors:[],warnings:[]}:Tn.checkDependencies();e.push(...n.warnings,...n.errors);let r=n.errors.length>0;if(process.env.KODAX_BUNDLED!=="true")try{let a=JSON.parse(await Pe(Vn.resolve("@anthropic-ai/sandbox-runtime/package.json"),"utf8"));a.version!==ue&&(r=!0,e.push(`ASRT package version mismatch: expected ${ue}, found ${String(a.version)}.`))}catch(a){r=!0,e.push(`ASRT package provenance check failed: ${fe(a)}`)}let o=xn(),i=Ne({args:["--version"],env:ge(),isElectron:o===process.execPath&&process.versions.electron!==void 0}),c=Ve(o,i.args,{env:i.env,shell:!1,encoding:"utf8",windowsHide:!0,timeout:5e3});if(c.status!==0){r=!0;let a=c.error?.message??(c.stderr.trim()||o);e.push(`JavaScript Skill interpreter is unavailable: ${a}.`)}if(process.platform==="win32"){try{let a=await Ue(),l=Hn({srtWin:a.srtWin}),u=Ht(l);if(u.length>0||!l.sid)r=!0,e.push(...u);else{co(a,l.sid);let m=tr(fn(),l.sid,l.groupSid,!1,"read");m.length>0&&(r=!0,e.push(`[acl_guards_missing] ${m.length} persistent Windows sandbox ACL guard(s) are missing. Run "kodax sandbox setup" once to install them outside the startup path.`)),await fo(a)}}catch(a){r=!0,e.push(fe(a))}try{let a=re().filter(({file:l,owner:u})=>!io(l,u));if(a.length>0){let l=de();l!==void 0&&a.every(({owner:m})=>m.windowsBootIdentity!==void 0&&m.windowsBootIdentity!==l)||(t=!0,e.push(`${we} `+He(a,l).message))}}catch(a){t=!0,e.push(`${we} ${fe(a)}`)}}return{ready:Tn.isSupportedPlatform()&&!r&&!t,platform:process.platform,version:ue,diagnostics:e,setupRequired:r}}s(wo,"inspectSandboxRuntime");async function mo(){let e=await te({refresh:!0});try{let r=ao();if(r!==void 0)return kt(e,r)}catch(r){let o=r instanceof Error?r:new Error(String(r));return kt(e,o)}if(e.ready||Sn(e)||!e.setupRequired)return e;let t=!1;try{let r=await Ue(),o=Hn({srtWin:r.srtWin});t=Ht(o).length===0&&o.sid!==void 0}catch{t=!1}if(t){jn(fn(),"read");let r=await te({refresh:!0});if(r.ready)return r}if(Mr().cancelled)throw new Error("Sandbox setup was cancelled.");return await Ue(),jn(fn(),"read"),te({refresh:!0})}s(mo,"setupWindowsSandboxRuntimeWithLock");async function go(){return process.platform!=="win32"?te({refresh:!0}):U(ee(),mo,Q)}s(go,"setupSandboxRuntime");function ke(e){if(e.ready)return[`KodaX sandbox is active (${e.platform}, ASRT ${e.version}).`];if(e.platform==="win32"){let t=e.diagnostics.find(n=>n.startsWith(we));return t!==void 0?[t.slice(we.length).trim()]:['Run "kodax sandbox setup". Windows will show a UAC prompt for the one-time sandbox account and network policy setup.',"The terminal itself does not need to be started as Administrator; approve the UAC prompt when it appears."]}return e.platform==="darwin"?['KodaX uses macOS Seatbelt through sandbox-exec. Install the missing dependency, then rerun "kodax sandbox doctor".',"Homebrew: brew install ripgrep"]:e.platform==="linux"?['KodaX uses bubblewrap on Linux. Install bubblewrap, socat, and ripgrep, then rerun "kodax sandbox doctor".',"Debian/Ubuntu: sudo apt install bubblewrap socat ripgrep","Fedora/RHEL: sudo dnf install bubblewrap socat ripgrep","Arch Linux: sudo pacman -S bubblewrap socat ripgrep"]:[`KodaX sandbox is not supported on ${e.platform}.`]}s(ke,"sandboxSetupGuidance");async function Bi(e={}){let t=await te({refresh:!0});if(t.ready)return{status:"ready",attempted:!1,doctor:t,guidance:ke(t)};if(Sn(t))return{status:"unavailable",attempted:!1,doctor:t,guidance:ke(t)};if(!t.setupRequired)return{status:"unavailable",attempted:!1,doctor:t,guidance:ke(t)};if(t.platform!=="win32"||e.allowElevation===!1)return{status:"unavailable",attempted:!1,doctor:t,guidance:ke(t)};try{let n=await go();return{status:n.ready?"ready":"unavailable",attempted:!0,doctor:n,guidance:ke(n)}}catch(n){let r=await te({refresh:!0}),o=fe(n);return{status:/cancelled/i.test(o)?"cancelled":"unavailable",attempted:!0,doctor:r,guidance:ke(r),error:o}}}s(Bi,"prepareSandboxRuntimeForSetup");function se(e,t){let n=e.replaceAll("\\","/").replace(/^\.\//,"");if(!n||d.posix.isAbsolute(n)||n.split("/").includes(".."))throw new Error(`${t} must be a safe relative path.`);return n}s(se,"canonicalRelative");function W(e,t){let n=d.relative(e,t);return n===""||!n.startsWith("..")&&!d.isAbsolute(n)}s(W,"isInside");function zt(e){let t=e.split(d.sep).map(n=>n.toLowerCase());return t.some(n=>Kr.has(n))||t.some(n=>qr.has(n)||n.startsWith(".env."))}s(zt,"isSensitiveRelative");async function yo(e,t){await J(t,{recursive:!0,mode:448});let n=[...(e.scripts??[]).map(r=>({folder:"scripts",file:r})),...(e.references??[]).map(r=>({folder:"references",file:r})),...(e.assets??[]).map(r=>({folder:"assets",file:r})),...(e.templates??[]).map(r=>({folder:"templates",file:r})),...(e.resources??[]).map(r=>({folder:"resources",file:r}))];await Ce(d.join(t,"SKILL.md"),await Pe(e.skillFilePath),{mode:384});for(let{folder:r,file:o}of n){let i=se(o.relativePath,`Skill ${e.name} support file`),c=d.join(t,r,...i.split("/"));await J(d.dirname(c),{recursive:!0,mode:448}),await Ce(c,await Pe(o.path),{mode:384})}}s(yo,"copySkillSnapshot");async function ho(e,t){let n=new Map;for(let[r,o]of Object.entries(e.admissions)){let i=await e.registry.loadFull(r),c=new Map((i.scripts??[]).map(l=>[`scripts/${se(l.relativePath,`Skill ${r} script`)}`,l])),a=d.join(t,r.replace(/[^A-Za-z0-9._-]/g,"_"));await yo(i,a);for(let l of o){let u=se(l,`toolPolicy.skillScripts.${r}`);if(!c.has(u))throw new Error(`Skill "${r}" has no script "${u}".`);n.set(`${r}\0${u}`,{skill:r,relativePath:u,snapshotPath:d.join(a,...u.split("/"))})}}return n}s(ho,"snapshotAdmissions");function So(e){return e.mode==="deny"?[]:e.origins.map(t=>{let n=new URL(t);return{host:n.hostname.toLowerCase(),port:n.port?Number(n.port):n.protocol==="https:"?443:80}})}s(So,"networkEndpoints");function ge(){let e=["PATH","Path","PATHEXT","SystemRoot","COMSPEC","TEMP","TMP","HOME","USERPROFILE","LOCALAPPDATA","LANG"],t={NO_COLOR:"1"};for(let n of e)process.env[n]!==void 0&&(t[n]=process.env[n]);for(let[n,r]of Object.entries(process.env))n.startsWith("LC_")&&r!==void 0&&(t[n]=r);return rt(t)}s(ge,"sanitizedEnvironment");function rt(e){if(process.platform!=="win32")return{...e};let t=new Map;for(let[n,r]of Object.entries(e))r!==void 0&&t.set(n.toLowerCase(),[n,r]);return Object.fromEntries(t.values())}s(rt,"normalizedSandboxEnvironment");function Vt(e,t){return rt({...e,...t})}s(Vt,"mergeSandboxEnvironment");function bo(e){let t=d.extname(e).toLowerCase();if([".js",".mjs",".cjs"].includes(t))return{command:process.env.KODAX_A2A_NODE??(process.env.KODAX_BUNDLED==="true"?"node":process.execPath),args:[e]};if(t===".py")return{command:process.env.KODAX_A2A_PYTHON??(process.platform==="win32"?"python.exe":"python3"),args:[e]};if(t===".ps1")return{command:process.env.KODAX_A2A_POWERSHELL??(process.platform==="win32"?d.join(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe"):"pwsh"),args:["-NoProfile","-NonInteractive","-File",e]};if(t===".sh"&&process.platform!=="win32")return{command:"/bin/sh",args:[e]};if([".cmd",".bat"].includes(t)&&process.platform==="win32")return{command:process.env.COMSPEC??d.join(process.env.SystemRoot??"C:\\Windows","System32","cmd.exe"),args:["/d","/s","/c",e]};throw new Error(`Unsupported admitted Skill script type: ${t||"<none>"}.`)}s(bo,"interpreterFor");var Et=250,vo=1500;async function Yt(e,t,n=hn,r=zn,o){let i=[],c=[],a=e.pid===void 0?void 0:Le(e.pid),l=0,u,m=s(()=>{},"reportStopRequested"),w,f,p=new Promise(h=>{m=h}),y=s(h=>{if(u!==void 0)return;u=h,m();let A=!1,E,$;w=new Promise((R,j)=>{E=R,$=j}),w.catch(()=>{});let P=s(async R=>{let j=await Gt(e.pid,a,jt("Sandbox broker"),o);return R===void 0?j:new AggregateError([j,R],"Sandbox broker termination failed and its process tree may still be alive.")},"unconfirmedTermination"),ne=s(R=>{A||(A=!0,f!==void 0&&clearTimeout(f),R===void 0?E():$(R))},"finish");f=setTimeout(()=>{try{e.kill("SIGKILL"),P().then(ne)}catch(R){P(R).then(ne)}},vo),De(e,{expectedProcessStartIdentity:a,forceMs:Et,taskkillMs:Et}).then(async R=>ne(R.status==="unknown"?await P():void 0),async R=>ne(await P(R)))},"requestStop"),v=s((h,A)=>{l+=A.byteLength,l>r?y(new Error(`Sandboxed command output exceeded ${r} bytes.`)):h.push(A)},"append");e.stdout?.on("data",h=>{v(i,h)}),e.stderr?.on("data",h=>{v(c,h)});let x=setTimeout(()=>{y(new Error(`Sandboxed command exceeded its ${n} ms timeout.`))},n),b=s(()=>{let h=t?.reason;y(h instanceof Error?h:new Error("Sandboxed command was cancelled."))},"abort");t?.addEventListener("abort",b,{once:!0}),t?.aborted&&b();try{let h=new Promise((E,$)=>{e.once("error",$),e.stdin?.once("error",$),e.once("close",P=>E(P??1))}),A=await Promise.race([h,p.then(()=>1)]);if(u!==void 0)throw await w,u;return{exitCode:A,stdout:Buffer.concat(i).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}}finally{clearTimeout(x),f!==void 0&&clearTimeout(f),t?.removeEventListener("abort",b)}}s(Yt,"collectProcess");async function Zt(e,t,n=hn,r=zn){let o=process.platform==="win32"?await En():ae.tmpdir(),i=d.join(o,`kodax-asrt-${process.pid}-${H()}.json`),c=process.platform==="win32"?at(e.config):{...e.config,filesystem:{...e.config.filesystem,denyRead:[...e.config.filesystem.denyRead,i]}},a={...e,bootstrapCommand:e.bootstrapCommand??xn(),config:c};await Ce(i,JSON.stringify(a),{mode:384});let l,u,m;try{if(process.platform==="win32"){await dt(),m=await Cn();let y=await ct(!0);if(y.length===1)throw y[0];if(y.length>1)throw new AggregateError(y,"Cached workspace sandbox reset was not confirmed before standalone execution.")}let w=process.env.KODAX_BUNDLED==="true"?["__asrt-broker",i]:["--input-type=module","-e",Lt,It,i],f=Ne({args:w,env:ge(),isElectron:process.versions.electron!==void 0});u=await Ut();let p=Jn(process.execPath,f.args,{cwd:process.platform==="win32"?We().directory:void 0,env:f.env,shell:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"});return nn(p),await Yt(p,t,n,r,u)}catch(w){throw l=w,w}finally{let w=[];try{await z(i,{force:!0})}catch(f){w.push(f)}try{await Mn(u)}catch(f){w.push(f)}if(m!==void 0)try{await m()}catch(f){w.push(f)}if(w.length>0)throw l!==void 0&&w.unshift(l),w.length===1?w[0]:new AggregateError(w,"Sandbox broker cleanup was not confirmed.")}}s(Zt,"runBrokerResult");async function xo(e,t){let n=await Zt(e,t);if(n.exitCode!==0){let r=n.stderr.trim()||n.stdout.trim();throw new Error(`Sandboxed Skill script failed (${n.exitCode}): ${r}`)}return n.stdout}s(xo,"runBroker");async function ko(e,t){let n=await qe(e),r=d.resolve(e,se(t,"Skill script input")),o=await qe(r);if(!W(n,o)||zt(d.relative(n,o)))throw new Error("Skill script input is outside the permitted workspace surface.");if(!(await dn(o)).isFile())throw new Error("Skill script inputs must be files.");return o}s(ko,"workspaceSource");async function Ao(e,t){let n=await qe(e),r=d.resolve(e,se(t,"Skill script output target"));if(!W(d.resolve(e),r)||zt(d.relative(d.resolve(e),r)))throw new Error("Skill script output target is outside the permitted workspace surface.");if(await J(d.dirname(r),{recursive:!0}),!W(n,await qe(d.dirname(r))))throw new Error("Skill script output target escapes through a symlink.");try{throw await dn(r),new Error("Skill script output target already exists.")}catch(o){if(o.code!=="ENOENT")throw o}return r}s(Ao,"workspaceTarget");async function Eo(e,t,n,r){if(n.inputs.length>0&&r==="none")throw new Error("Skill script inputs require workspace read access.");for(let o of n.inputs){let i=await ko(e,o.path),c=se(o.as??d.basename(i),"Skill script staged input"),a=d.resolve(t,"inputs",...c.split("/"));if(!W(d.join(t,"inputs"),a))throw new Error("Skill script staged input escapes staging.");await J(d.dirname(a),{recursive:!0,mode:448}),await $t(i,a)}}s(Eo,"stageInputFiles");async function Ro(e,t,n,r,o){if(n.outputs.length>0&&r!=="write")throw new Error("Skill script outputs require workspace write access.");let i=[];for(let c of n.outputs){let a=se(c.path,"Skill script staged output"),l=d.resolve(t,"outputs",...a.split("/")),u=await qe(l);if(!W(d.join(t,"outputs"),u)||(await $r(l)).isSymbolicLink()||!(await dn(l)).isFile())throw new Error(`Skill script did not produce output "${a}".`);let m=await Ao(e,c.target);if(o!==void 0&&Qt(e,!0)+(await dn(l)).size>o)throw new Error("Skill script outputs would exceed the remote workspace byte quota.");await $t(l,m,Cr.COPYFILE_EXCL),i.push(d.relative(e,m))}return i}s(Ro,"promoteOutputs");function Qt(e,t=!1){let n=0;for(let r of Un(e,{withFileTypes:!0})){if(t&&r.name===".kodax-a2a-script"||r.isSymbolicLink())continue;let o=d.join(e,r.name);r.isDirectory()?n+=Qt(o):r.isFile()&&(n+=Re(o).size)}return n}s(Qt,"directorySize");function ot(e){if(process.platform!=="win32")return e;let t=We();return{...e,windows:{...e.windows,srtWin:{path:t.path}},filesystem:{...e.filesystem,allowRead:[...new Set([...e.filesystem.allowRead,t.directory])],denyWrite:process.platform==="win32"?e.filesystem.denyWrite:[...new Set([...e.filesystem.denyWrite??[],t.directory])]}}}s(ot,"withPreparedWindowsRunner");function Po(e,t,n,r){let o=ae.homedir(),i=process.platform==="win32"?fn():[o],c=s(a=>d.isAbsolute(a)?process.platform==="win32"?[a,d.dirname(a)]:[a]:[],"executableReadScopes");return ot({network:{allowedDomains:[],deniedDomains:[],strictAllowlist:n.length===0,allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{denyRead:i,allowRead:[e,t,...new Set([...c(process.execPath),...c(r)])],allowWrite:[e],denyWrite:i}})}s(Po,"sandboxConfig");function Co(){let e=[ae.tmpdir(),process.env.TEMP,process.env.TMP,process.env.TMPDIR,...process.platform==="win32"?[]:["/tmp","/var/tmp"]];return[...new Set(e.filter(t=>typeof t=="string"&&d.isAbsolute(t)).map(t=>d.resolve(t)))]}s(Co,"canonicalTempDirectories");function er(e){return[d.join(e,".git","config"),d.join(e,".git","hooks")].filter(n=>{try{return Re(n),!0}catch{return!1}})}s(er,"existingWorkspaceDenyWrites");function it(e,t,n){let r=Xr.map(i=>d.resolve(e,i)).filter(i=>d.relative(i,t)!==""),o=process.platform==="win32"?[d.resolve(t),vn()]:[d.resolve(n),...Jr.map(i=>d.resolve(t,i))];return[...new Set([...o,...r])]}s(it,"workspaceShellSensitiveReadDenies");function st(e){let t=[...new Set(e.map(r=>d.resolve(r)))].filter(r=>Re(r,{throwIfNoEntry:!1})!==void 0).sort((r,o)=>r.length-o.length),n=[];for(let r of t)n.some(o=>W(o,r))||n.push(r);return n}s(st,"existingMinimalWindowsAclGuardRoots");function nr(e){return d.resolve(e).toLowerCase()}s(nr,"windowsAclGuardKey");function Gn(e,t){let n=nr(e),r=t==="read"?Ln:new Set([...Ln,...Nt]);for(let o of r)if(n===o||n.startsWith(o.endsWith(d.sep)?o:`${o}${d.sep}`))return!0;return!1}s(Gn,"windowsAclGuardCovers");function fn(){let e=d.resolve(ae.homedir()),t=d.resolve(q());return st(it(e,t,d.join(t,"sandbox-runtime")))}s(fn,"windowsPersistentAclGuardRoots");function tr(e,t,n,r,o){let i=st(e);if(i.length===0)return[];let c=JSON.stringify({sid:t,tokenSids:[t,n,"S-1-1-0","S-1-5-11","S-1-5-32-545"].filter(m=>m!==void 0),install:r,paths:i.map(m=>({path:m,directory:Re(m).isDirectory(),mode:o}))}),a=rr(),l=Ve(a,["-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(Ur,"utf16le").toString("base64")],{input:c,encoding:"utf8",timeout:r&&o==="read"?15*6e4:r?15e3:5e3,windowsHide:!0});if(l.error||l.status!==0){let m=(l.error?.message||l.stderr||l.stdout||"no diagnostics").trim().slice(-4096);throw new Error(`Windows sandbox ACL guard failed: ${m}`)}let u;try{let m=JSON.parse(l.stdout.trim());u=Array.isArray(m.missing)?m.missing.filter(w=>typeof w=="string"):[]}catch(m){throw new Error(`Windows sandbox ACL guard returned invalid output: ${fe(m)}`)}if(u.length===0){let m=o==="read"?Ln:Nt;for(let w of i)m.add(nr(w))}return u}s(tr,"runWindowsAclGuard");function rr(){let e=process.env.ProgramFiles??"C:\\Program Files",t=d.join(e,"PowerShell","7","pwsh.exe");return Tt(t)?t:d.join(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe")}s(rr,"windowsAclPowerShellExecutable");function jn(e,t){if(process.platform!=="win32"||e.length===0)return;let n=e.filter(c=>!Gn(c,t));if(n.length===0)return;let r=We(),o=Hn({srtWin:r.srtWin});if(!o.sid)throw new Error("Windows sandbox account SID is unavailable for ACL guards.");if(tr(n,o.sid,o.groupSid,!0,t).length>0)throw new Error("Windows sandbox ACL guards were not installed completely.")}s(jn,"installWindowsAclGuards");function at(e){return process.platform!=="win32"?e:{...e,filesystem:{...e.filesystem,denyRead:e.filesystem.denyRead.filter(t=>!Gn(t,"read")),denyWrite:e.filesystem.denyWrite?.filter(t=>!Gn(t,"write"))}}}s(at,"withoutWindowsAsrtDenyPropagation");function To(e,t){let n;try{n=G.native(t)}catch{return[]}let r=[];for(let o of e){let i;try{i=G.native(o)}catch{continue}if(!W(i,n))r.push(o);else if(i!==n){let c=d.relative(i,n).split(d.sep),a=i;try{for(let l of c){for(let u of Un(a,{withFileTypes:!0}))u.name!==l&&r.push(d.join(a,u.name));a=d.join(a,l)}}catch{}}}return process.platform!=="win32"&&r.push(t),[...new Set(r)]}s(To,"workspaceShellWriteRoots");function Wo(e,t){let n=process.platform==="win32"?t:d.resolve(e);return d.join(ae.tmpdir(),"kodax-sandbox",Ye("sha256").update(n).digest("hex").slice(0,16))}s(Wo,"workspaceShellTempRoot");function $o(e,t){return d.join(Wo(e,t),`${process.pid}-${H()}`)}s($o,"createWorkspaceShellTempDirectory");async function On(e){await z(e,{recursive:!0,force:!0}),await Or(d.dirname(e)).catch(t=>{if(t.code!=="ENOENT"&&t.code!=="ENOTEMPTY")throw t})}s(On,"removeWorkspaceShellTempDirectory");function _o(e){return process.platform==="win32"?e===void 0?[]:[d.dirname(e)]:Co()}s(_o,"workspaceShellTempWriteRoots");function Oo(e,t,n){try{let r=G.native(t),o=d.resolve(t),i=d.resolve(e);if(!W(o,i)||i===o)return;for(;i!==o;)try{let c=G.native(i);if(c===r||!W(r,c))return;let a=d.relative(r,c).split(d.sep)[0]?.toLowerCase();return a==="sandbox-runtime"||n&&Yn.some(l=>l===a)?void 0:c}catch(c){if(!n||c.code!=="ENOENT")return;try{yn(i);return}catch(l){if(l.code!=="ENOENT")return}let a=d.dirname(i);if(a===i)return;i=a}return}catch{return}}s(Oo,"windowsAgentHomeAccessRoot");function or(e,t){if(!t)return{read:[],write:[]};let n=s((r,o)=>[...new Set(r.flatMap(i=>{let c=Oo(i,e,o);return c?[c]:[]}))],"roots");return{read:n(t.read,!1),write:n(t.write,!0),...t.ephemeral===!0?{ephemeral:!0}:{}}}s(or,"windowsAgentHomeAccessRoots");function ze(e){return e??(process.platform==="win32"?process.env.COMSPEC??d.join(process.env.SystemRoot??"C:\\Windows","System32","cmd.exe"):"/bin/sh")}s(ze,"workspaceShellExecutable");function Io(e,t){return Object.entries(e).find(([n,r])=>n.toUpperCase()===t&&r!==void 0)?.[1]}s(Io,"shellEnvironmentValue");function No(e){let t=process.env.LOCALAPPDATA,n=[t===void 0?void 0:d.join(t,"Programs"),t,process.env.APPDATA,d.join(e,"AppData","Local","Programs"),d.join(e,"AppData","Local"),d.join(e,"AppData","Roaming"),e];return[...new Set(n.flatMap(r=>r===void 0?[]:[d.resolve(r)]))].filter(r=>W(e,r)).sort((r,o)=>o.length-r.length)}s(No,"workspaceShellUserDataBoundaries");function Lo(e,t,n){if(process.platform!=="win32"||e.toLowerCase()===t.toLowerCase())return[];try{if(!yn(e).isSymbolicLink())return[]}catch{return[]}let r=n.find(a=>a.toLowerCase()!==t.toLowerCase()&&W(a,t));if(r===void 0)return[];let[o]=d.relative(r,t).split(d.sep);if(!o)return[];let i=d.join(r,o),c=[];for(let a=d.dirname(t);a.toLowerCase()!==i.toLowerCase()&&W(i,a);a=d.dirname(a))c.push(a);return c}s(Lo,"workspaceShellLinkedTargetAncestors");function pn(e,t){let n=d.resolve(ae.homedir()),r=d.resolve(q()),o=it(n,r,d.join(r,"sandbox-runtime")),i=No(n),c=new Map,a=s(w=>{let f=d.resolve(w);if(!(f===d.parse(f).root||f.toLowerCase()===n.toLowerCase()||W(r,f)||W(f,r)||o.some(p=>W(p,f))))return f},"safe"),l=s((w,f)=>{let p=a(w);if(p===void 0)return;let y;try{y=G(p)}catch{return}if(a(y)===void 0)return;let v=f?[p,y].filter(x=>W(n,x)):[p,y];for(let x of v)c.set(process.platform==="win32"?x.toLowerCase():x,x);if(f&&v.includes(y))for(let x of Lo(p,y,i)){let b=a(x);b!==void 0&&W(n,b)&&c.set(b.toLowerCase(),b)}},"remember");for(let w of(Io(e,"PATH")??"").split(d.delimiter)){let f=w.trim().replace(/^"(.*)"$/,"$1");f&&d.isAbsolute(f)&&l(f,!0)}let u=ze(t);d.isAbsolute(u)&&l(d.dirname(u),!0);let m=xn();if(d.isAbsolute(m)){let w=a(m);w!==void 0&&c.set(process.platform==="win32"?w.toLowerCase():w,w),l(d.dirname(m),!1)}return[...c.values()].sort((w,f)=>w.toLowerCase().localeCompare(f.toLowerCase()))}s(pn,"workspaceShellRuntimeReadScopes");function Kn(e,t){return d.resolve(e).toLowerCase()===d.resolve(t).toLowerCase()}s(Kn,"sameWindowsPath");function wn(e,t){let n=Tr(e,"r");try{let r=Buffer.allocUnsafe(t+1),o=0;for(;o<r.length;){let i=Wr(n,r,o,r.length-o,o);if(i===0)break;o+=i}return o>t?void 0:r.toString("utf8",0,o)}finally{Pr(n)}}s(wn,"readBoundedUtf8File");function Do(e,t){let n=/^(.*)[/\\]worktrees[/\\][^/\\]+$/.exec(e);if(n===null)return;let r=wn(d.join(e,"commondir"),4096),o=wn(d.join(e,"gitdir"),4096);if(r===void 0||o===void 0)return;let i=G(n[1]),c=G(d.resolve(e,r.trim())),a=G(d.resolve(e,o.trim()));return Kn(c,i)&&Kn(a,t)?i:void 0}s(Do,"linkedWorktreeMainGitDirectory");function Bo(e){let t=wn(d.join(e,"config"),65536);if(t===void 0)return;let n=!1,r;for(let o of t.split(/\r?\n/)){let i=o.trim();if(i.startsWith("[")){n=/^\[\s*core\s*\]$/i.test(i);continue}if(!n)continue;let c=/^worktree\s*=\s*(.+?)\s*$/i.exec(i);if(c===null)continue;if(r!==void 0)return;let a=c[1];if(a.includes("\0")||a.startsWith('"')||a.endsWith('"'))return;r=a}return r===void 0?void 0:G(d.resolve(e,r))}s(Bo,"submoduleGitWorktree");function Fo(e,t){if(!/[/\\]\.git[/\\]modules[/\\]/i.test(e))return!1;let n=Bo(e);return n!==void 0&&Kn(n,t)}s(Fo,"isStructurallyBoundSubmoduleGitDirectory");function Mo(e){if(process.platform!=="win32")return{};let t=d.join(e,".git");try{if(!yn(t).isFile())return{};let n=wn(t,4096);if(n===void 0)return{};let r=/^gitdir:\s*(.+?)\s*$/m.exec(n);if(r===null)return{};let o=G(d.resolve(e,r[1])),i=Do(o,t),c=Fo(o,e);if(i===void 0&&!c)return{};let a=i??o;return Re(a).isDirectory()?Re(d.join(a,"HEAD")).isFile()?{mainGitDirectory:a,gitfile:t}:{}:{}}catch(n){let r=n.code;if(r==="ENOENT"||r==="ENOTDIR")return{};throw n}}s(Mo,"windowsLinkedWorktreeGitAccess");function ir(e,t,n,r,o=pn(process.env,ze())){let i=d.resolve(q()),c=d.join(i,"sandbox-runtime"),a=d.resolve(ae.homedir()),l=it(a,i,c),u=process.platform==="win32"?st(l):l.filter(p=>p!==i),m=process.platform==="win32"?or(i,n):{read:[],write:[]},w=To([e,..._o(t),...m.write,...r?.write??[]],i),f=Mo(e);return ot({network:{allowedDomains:[],deniedDomains:[],strictAllowlist:!1,allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{denyRead:u,allowRead:[...new Set([...o,...m.read,...r?.read??[],...f.mainGitDirectory!==void 0?[f.mainGitDirectory]:[]])],allowWrite:w,denyWrite:[c,...Yn.map(p=>d.join(i,p)),...er(e),...f.gitfile!==void 0?[f.gitfile]:[]]}})}s(ir,"workspaceShellSandboxConfig");function sr(e,t,n,r,o){let i=ir(e,t,n,r,o);return process.platform!=="win32"?i:ar(i)}s(sr,"workspaceShellSessionSandboxConfig");function ar(e){let t=e.filesystem.allowWrite;return{...e,filesystem:{...e.filesystem,denyRead:e.filesystem.denyRead,denyWrite:e.filesystem.denyWrite.filter(n=>t.some(r=>W(r,n)))}}}s(ar,"boundedWindowsWorkspaceDenies");function Go(e,t,n,r,o){let i=ir(e,t,n,r,o);return process.platform==="win32"?ar(i):i}s(Go,"workspaceShellCommandSandboxConfig");function on(e,t){return[...new Set((e??[]).map(n=>d.resolve(t,n)))]}s(on,"normalizedSandboxPaths");function jo(e){return e.mode!=="allowlist"?[]:e.origins.map(t=>{let n=new URL(t);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password||n.pathname!=="/"||n.search||n.hash)throw new Error(`Sandbox network origin must be an HTTP(S) origin: ${t}`);return{host:n.hostname.toLowerCase(),port:n.port?Number(n.port):n.protocol==="https:"?443:80}})}s(jo,"sdkSandboxEndpoints");async function Fi(e){if(!e.command.trim())throw new Error("Sandbox command must not be empty.");if(e.timeoutMs!==void 0&&(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0))throw new Error("Sandbox timeoutMs must be a positive finite number.");if(e.maxOutputBytes!==void 0&&(!Number.isSafeInteger(e.maxOutputBytes)||e.maxOutputBytes<=0))throw new Error("Sandbox maxOutputBytes must be a positive safe integer.");let t=d.resolve(e.cwd),n=e.network??{mode:"deny"},r=jo(n),o=await te();if(!o.ready){if(!Sn(o))return{status:"unavailable",sandboxed:!1,doctor:o};if(await un(),o.setupRequired)return{status:"unavailable",sandboxed:!1,doctor:o}}let i=Vt(e.inheritEnvironment===!0?process.env:ge(),e.env??{}),c={config:ot({network:{allowedDomains:[],deniedDomains:[],strictAllowlist:n.mode==="deny",allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{allowRead:on(e.filesystem.allowRead,t),allowWrite:on(e.filesystem.allowWrite,t),denyRead:on(e.filesystem.denyRead,t),denyWrite:on(e.filesystem.denyWrite,t)}}),command:e.command,args:e.args??[],cwd:t,env:i,endpoints:r,allowAllNetwork:n.mode==="allow"},a=await Zt(c,e.signal,e.timeoutMs??hn,e.maxOutputBytes??zn);return{status:"completed",sandboxed:!0,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}s(Fi,"runKodaXSandboxed");var Ko=5*6e4,qo=3e4,Xo=3e4,Fe=1500,dr=13e4,Jo=dr,Uo=Xo,Ho=Jo,zo=8,L=new Map,Ke=new Set,Ae=new Set,Ee=new Set,Ge,qn,mn=!1;function me(e){let t=e instanceof Error?e:new Error(String(e));if(process.platform!=="win32"){qn??=t;return}Ge??=t}s(me,"recordWindowsSandboxAclFailure");function kn(){if(process.platform!=="win32"&&qn!==void 0)throw new Error("Sandbox process cleanup was not confirmed; stop the retained process tree before more sandboxed commands.",{cause:qn});if(process.platform==="win32"&&Ge!==void 0)throw Ge instanceof B?Ge:new Error("Windows sandbox ACL cleanup was not confirmed; stop the retained owner or restart Windows before more sandboxed commands.",{cause:Ge})}s(kn,"assertWindowsSandboxAclProcessSafe");function An(e){kn(),process.platform==="win32"&&tt(e)}s(An,"assertWindowsSandboxAclSafe");function cr(e){Ae.add(e),e.then(()=>Ae.delete(e),()=>Ae.delete(e))}s(cr,"trackWorkspaceSessionReset");function Vo(e){Ee.add(e),e.then(()=>Ee.delete(e),t=>{Ee.delete(e),T({source:"sandbox:workspace-session",level:"error",message:"Workspace sandbox durable ACL poison transition failed.",detail:t})})}s(Vo,"trackWindowsSandboxAclTransition");async function Yo(){for(;Ee.size>0;)await Promise.allSettled([...Ee])}s(Yo,"waitForWindowsSandboxAclTransitions");async function dt(){for(;Ae.size>0;)await Promise.allSettled([...Ae]);await Yo(),kn()}s(dt,"waitForWorkspaceSessionResets");async function ct(e=!1){let t=[...L.values()];L.clear();let n=[];for(let r of t)try{await(await r).close(e)}catch(o){n.push(o),T({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox shutdown could not confirm ACL reset.",detail:o})}return n}s(ct,"closeCachedWorkspaceSessions");var lr=s(()=>{mn=!1,ct()},"closeWorkspaceSessionsBeforeExit");function Zo(){mn||(mn=!0,process.once("beforeExit",lr))}s(Zo,"registerWorkspaceSessionBeforeExit");async function Mi(){for(process.removeListener("beforeExit",lr),mn=!1;Ke.size>0;)await Promise.allSettled([...Ke]);let e=await ct();try{await dt()}catch(t){e.push(t)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"Workspace sandbox shutdown was not confirmed.")}s(Mi,"shutdownAsrtWorkspaceSessions");function ur(){let e=new Error("ASRT workspace session preparation timed out.");return e.name="TimeoutError",e}s(ur,"workspacePreparationTimeoutError");function gn(e,t){if(e?.aborted)throw new DOMException("Operation aborted","AbortError");if(t!==void 0&&Date.now()>=t)throw ur()}s(gn,"throwIfWorkspacePreparationStopped");function Xn(e,t,n){return gn(t,n),t===void 0&&n===void 0?e:new Promise((r,o)=>{let i=!1,c,a=s(u=>{i||(i=!0,c&&clearTimeout(c),t?.removeEventListener("abort",l),u())},"finish"),l=s(()=>{a(()=>o(new DOMException("Operation aborted","AbortError")))},"onAbort");t?.addEventListener("abort",l,{once:!0}),n!==void 0&&(c=setTimeout(()=>{a(()=>o(ur()))},Math.max(0,n-Date.now())),c.unref()),e.then(u=>a(()=>r(u)),u=>a(()=>o(u)))})}s(Xn,"waitForWorkspacePreparation");async function En(){let e=d.join(q(),"sandbox-runtime");return await J(e,{recursive:!0,mode:448}),e}s(En,"sandboxControlDirectory");function Qo(e){if(process.env.KODAX_BUNDLED==="true")return["__asrt-workspace-session",e];if(import.meta.url.endsWith(".ts"))return["--import",_t(Vn.resolve("tsx")).href,bt(new URL("./sandbox-workspace-session-entry.ts",import.meta.url)),e];let t=d.dirname(bt(import.meta.url)),n=d.basename(t)==="chunks"?d.dirname(t):t;return[d.join(n,"sandbox-workspace-session.js"),e]}s(Qo,"workspaceSessionEntryArgs");function sn(e,t){let n=t?"ref":"unref";e[n]();for(let r of e.stdio){if(!r)continue;r[n]?.()}}s(sn,"setWorkspaceSessionReferenced");async function fr(e,t,n){if(e)return t();let r=process.platform==="win32"?await Cn(n):await Pn(n);try{return await t()}finally{await r()}}s(fr,"withExclusiveFileSystemEffectFence");async function ei(e,t,n,r,o,i,c){let a=process.platform==="win32"?$o(e,o):void 0;a!==void 0&&await J(a,{recursive:!0,mode:448});let l=await En();process.platform==="win32"&&jn(er(e),"write");let u=d.join(l,`workspace-${process.pid}-${H()}.json`),m=at(sr(e,a,t,n,r));await Ce(u,JSON.stringify({config:m}),{mode:384});let w=Ne({args:Qo(u),env:ge(),isElectron:process.versions.electron!==void 0}),f;try{f=await Ut(o)}catch(S){let g=await Promise.allSettled([z(u,{force:!0}),...a===void 0?[]:[On(a)]]),k=[S,...g.flatMap(C=>C.status==="rejected"?[C.reason]:[])];throw k.length===1?S:new AggregateError(k,"Workspace sandbox owner admission and pre-launch cleanup both failed.")}let p;try{p=Jn(process.execPath,w.args,{cwd:process.platform==="win32"?We().directory:void 0,env:w.env,shell:!1,stdio:["pipe","pipe","pipe","pipe"],windowsHide:!0})}catch(S){let g=[S];try{await Mn(f)}catch(C){await rn(f,C),g.push(C)}let k=await Promise.allSettled([z(u,{force:!0}),...a===void 0?[]:[On(a)]]);throw g.push(...k.flatMap(C=>C.status==="rejected"?[C.reason]:[])),g.length===1?S:new AggregateError(g,"Workspace sandbox owner launch cleanup failed.")}nn(p);let y=p.pid===void 0?void 0:Le(p.pid),v=p.stdio[3];if(!v)throw new Error("ASRT workspace session control pipe was not created.");let x=Lr.createInterface({input:v}),b=new Map,h="",A=!1,E=!1,$=!1,P=!1,ne=0,R=0,j,K,ce,ye=new Promise(S=>{p.once("exit",(g,k)=>S({code:g,signal:k}))}),he=ye.then(async()=>{if(a!==void 0)try{await On(a)}catch(S){T({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox temp cleanup failed.",detail:S})}}),Ze=s(async(S=!1)=>{let g=await ye;await he;let k=[];if(!S&&(g.code!==0||g.signal!==null)){let C=g.signal===null?`code ${g.code??"unknown"}`:`signal ${g.signal}`;k.push(new Error(`ASRT workspace session ACL reset was not confirmed (${C}): ${h.trim()||"no diagnostics"}`))}try{await Mn(f)}catch(C){k.push(C)}if(k.length===1)throw k[0];if(k.length>1)throw new AggregateError(k,"Workspace sandbox cleanup was not confirmed.")},"confirmCleanReset"),F,V,M=new Promise((S,g)=>{F=S,V=g}),$e=s(()=>{P||(P=!0,c())},"evict"),Qe=s(async()=>{if(!E||!$||R!==0||p.exitCode!==null||p.signalCode!==null||!p.stdin.writable)return!1;try{p.stdin.end()}catch{return!1}let S;try{let g=await Promise.race([ye,new Promise(k=>{S=setTimeout(k,process.platform==="win32"?dr:Fe)})]);return g!==void 0&&g.code===0&&g.signal===null}finally{S!==void 0&&clearTimeout(S)}},"waitForOrderlyClose"),N,_e=!1,lt=!1,Rn=s(()=>N||(lt=!0,N=(async()=>{try{if(await Qe())return;if((await De(p,{gracefulStdinEnd:!1,gracefulMs:Fe,forceMs:Fe,taskkillMs:Fe})).status==="unknown")throw await Gt(p.pid,y,jt("ASRT workspace session"),f);_e=!0}finally{x.close(),v.destroy(),p.stdin.destroy()}})().finally($e),N),"terminate"),Se=s(S=>{Rn().catch(g=>{T({source:"runtime.sandbox.workspace-session",level:"error",message:`ASRT workspace session termination failed after ${S}.`,detail:g})})},"observeFailedTermination"),oe=s(S=>{if(!A){A=!0,V(S);for(let g of b.values())g.reject(S);b.clear()}},"fail");p.stderr.on("data",S=>{h=(h+S.toString("utf8")).slice(-16384)}),p.stdout.on("data",S=>{h=(h+S.toString("utf8")).slice(-16384)}),x.on("line",S=>{let g;try{g=JSON.parse(S)}catch{oe(new Error("ASRT workspace session returned malformed control data.")),Se("malformed control data");return}if(g.type==="ready"){g.ok?($=!0,F()):V(new Error(g.error??"ASRT workspace session failed."));return}if(g.type!=="result"||!g.id){oe(new Error("ASRT workspace session returned an invalid control response.")),Se("an invalid control response");return}let k=b.get(g.id);k&&(b.delete(g.id),k.resolve(g))}),p.once("error",S=>{oe(S),Se("a child-process error")}),x.once("close",()=>{E||A||(oe(new Error("ASRT workspace session control pipe closed unexpectedly.")),Se("an unexpected control-pipe close"))}),p.once("exit",(S,g)=>{K&&clearTimeout(K);let k=new Error(`ASRT workspace session exited ${g??S??1}: ${h.trim()||"no diagnostics"}`);!lt&&(S!==0||g!==null||!E)&&Vo(rn(f,k)),oe(k),$e()});let mr=setTimeout(()=>{oe(new Error("ASRT workspace session initialization timed out.")),Se("an initialization timeout")},qo);try{await M.finally(()=>clearTimeout(mr))}catch(S){E=!0;let g=[S],k=!1;try{await Rn(),k=!0}catch(C){g.push(C)}if(k)try{await Ze(_e)}catch(C){await rn(f,C),g.push(C)}throw await z(u,{force:!0}),g.length===1?S:new AggregateError(g,`Workspace sandbox startup cleanup failed: ${fe(g.at(-1))}`)}let en=s(async(S,g)=>{if(A||E&&S==="wrap")throw new Error("ASRT workspace session is unavailable.");let k=`workspace_${++ne}`,C=new Promise((D,ve)=>{b.set(k,{resolve:D,reject:ve})}),ie=setTimeout(()=>{oe(new Error(`ASRT workspace session ${S} request timed out.`)),be.close(i).catch(D=>{T({source:"sandbox:workspace-session",level:"warn",message:"Timed-out workspace sandbox request could not retire its session.",detail:D})})},S==="cleanup"?Ho:Uo);ie.unref();try{await new Promise((D,ve)=>{p.stdin.write(`${JSON.stringify({id:k,type:S,request:g})}
|
|
567
|
-
`,Oe=>Oe?ve(Oe):D())})}catch(D){throw b.delete(k),clearTimeout(ie),oe(D instanceof Error?D:new Error(String(D))),Se("a control request write failure"),D}return C.finally(()=>clearTimeout(ie))},"request"),ut=s(()=>{if(K&&clearTimeout(K),!(R>0||E||A)){if(process.platform==="win32"){sn(p,!1);return}K=setTimeout(()=>{be.close().catch(S=>{T({source:"sandbox:workspace-session",level:"warn",message:"Idle workspace sandbox session could not confirm ACL reset.",detail:S})})},Ko),K.unref(),sn(p,!1)}},"scheduleIdleClose"),be={policyKey:o,...a===void 0?{}:{tempDirectory:a},async acquire(S,g,k){if(An(o),gn(g,k),A||E)throw new Error("ASRT workspace session is unavailable.");K&&clearTimeout(K),sn(p,!0),R+=1;let C=!1,ie=s(()=>{if(C)return!1;C=!0,R-=1;let Y=R===0;return R===0&&(j?.(),j=void 0),ut(),Y},"finalize"),D=s(async()=>{ie()&&process.platform==="win32"&&await be.close(i)},"finalizeAndCloseIfIdle"),ve=s((Y,_)=>{T({source:"sandbox:workspace-session",level:"warn",message:Y,detail:_}),ie()&&be.close(i).catch(Z=>{T({source:"sandbox:workspace-session",level:"warn",message:"Failed workspace sandbox cleanup could not retire its session.",detail:Z})})},"retireAfterCleanupFailure"),Oe=en("wrap",S),Ie;try{Ie=await Xn(Oe,g,k)}catch(Y){throw Oe.then(async _=>{if(!_.ok||!_.invocation)return;let O=await en("cleanup");if(!O.ok)throw new Error(O.error??"ASRT command cleanup failed.")}).then(D,_=>ve("Late workspace sandbox preparation cleanup failed.",_)),Y}try{if(!Ie.ok||!Ie.invocation){ie();let _=new Error(Ie.error??"ASRT workspace wrapping failed.");try{await be.close(i)}catch(O){let Z=O instanceof Error?O.message:String(O);throw new Error(`${_.message} Workspace session reset failed: ${Z}`,{cause:_})}throw _}try{gn(g,k)}catch(_){try{let O=await en("cleanup");if(!O.ok)throw new Error(O.error??"ASRT command cleanup failed.")}catch(O){ve("Cancelled workspace sandbox preparation cleanup failed.",O)}throw await D(),_}let Y=!1;return{invocation:Ie.invocation,async release(){if(Y)return;Y=!0;let _;try{let Z=await en("cleanup");if(!Z.ok)throw new Error(Z.error??"ASRT command cleanup failed.")}catch(Z){_=Z}let O;try{await D()}catch(Z){O=Z}if(_!==void 0&&O!==void 0)throw new AggregateError([_,O],"Workspace sandbox command cleanup and policy-group reset both failed.");if(_!==void 0)throw _;if(O!==void 0)throw O}}}catch(Y){throw ie(),Y}},async close(S=!1){return ce||(E=!0,$e(),ce=(async()=>{K&&clearTimeout(K),sn(p,!0),R>0&&await new Promise(g=>{let k=setTimeout(g,Fe);k.unref?.(),j=s(()=>{clearTimeout(k),g()},"resolveDrained")}),await fr(i||S,async()=>{await Rn(),await Ze()},o)})().catch(async g=>{throw await rn(f,g),g}),cr(ce),ce)}};return ut(),be}s(ei,"startWorkspaceSessionClientWithFence");function Rt(e,t,n,r,o,i,c){return fr(i,async()=>{if(pr(e,t,n,r)!==o)throw new Error("Sandbox policy paths changed before ACL initialization.");return An(o),await un(o),ei(e,t,n,r,o,i,c)},o)}s(Rt,"startWorkspaceSessionClient");function In(e){return[...new Set(e.map(t=>{let n=d.resolve(t);return process.platform==="win32"?n.toLowerCase():n}))].sort()}s(In,"normalizedWorkspacePolicyPaths");function je(e){let t=s(r=>{let o=d.resolve(r);return process.platform==="win32"?o.toLowerCase():o},"normalize"),n=null;try{n=t(G.native(e))}catch{}return{lexical:t(e),canonical:n}}s(je,"workspacePolicyPathIdentity");function an(e){let t=new Map;for(let n of e){let r=je(n);t.set(`${r.lexical}\0${r.canonical??""}`,r)}return[...t.values()].sort((n,r)=>n.lexical.localeCompare(r.lexical)||(n.canonical??"").localeCompare(r.canonical??""))}s(an,"workspacePolicyPathIdentities");function pr(e,t,n,r){let o=sr(e,void 0,t,n,r);return Ye("sha256").update(JSON.stringify({workspace:je(e),agentHome:je(q()),tempBase:je(ae.tmpdir()),filesystem:{allowRead:an(o.filesystem.allowRead),allowWrite:an(o.filesystem.allowWrite),denyRead:an(o.filesystem.denyRead),denyWrite:an(o.filesystem.denyWrite)},network:o.network,windowsRunner:process.platform==="win32"?{version:ue,architecture:process.arch,path:je(We().path)}:null,ephemeral:t?.ephemeral===!0})).digest("hex")}s(pr,"workspaceShellPolicyKey");function ni(e){return process.platform!=="win32"?!0:(e?.write??[]).every(t=>{try{return G.native(t),!0}catch{return!1}})}s(ni,"workspaceShellFilesystemAccessIsRepresentable");async function Pt(e,t,n,r=pn(process.env,ze()),o=r,i=!1){if(process.platform==="win32"){if(Ae.size>0||Ee.size>0)return}else await dt();kn();let c=await te();if(!c.ready&&!Sn(c))return;if(process.platform!=="win32"){let b=q();await Promise.all([En(),...Yn.map(h=>J(d.join(b,h),{recursive:!0,mode:448}))])}let a=pr(e,process.platform==="win32"?t:void 0,n,r);if(!c.ready&&(await un(a),c.setupRequired))return;await un(a),An(a),Zo();let l=process.platform==="win32"?t:void 0,u=process.platform==="win32"?e.toLowerCase():e,m=In,w=m(r),f=JSON.stringify(w)===JSON.stringify(m(o)),p=(n?.read.length??0)>0||(n?.write.length??0)>0,y=l===void 0&&!p&&f?"workspace":Ye("sha256").update(JSON.stringify({read:[...l?.read??[]].map(b=>b.toLowerCase()).sort(),write:[...l?.write??[]].map(b=>b.toLowerCase()).sort(),additionalRead:In(n?.read??[]),additionalWrite:In(n?.write??[]),runtimeReadScopes:w})).digest("hex"),v=process.platform==="win32"?a:`${u}\0${y}`;if(process.platform==="win32"&&i){let b=l?.ephemeral===!0?void 0:v;for(let[h,A]of[...L])if(h!==b){L.delete(h);try{await(await A).close(!0)}catch(E){throw T({source:"sandbox:workspace-session",level:"warn",message:"Retiring the previous Windows workspace sandbox scope failed.",detail:E}),E}}}if(l?.ephemeral===!0)return Rt(e,l,n,r,a,i,()=>{});let x=L.get(v);if(x&&(L.delete(v),L.set(v,x)),!x){if(process.platform!=="win32"&&y!=="workspace"){let b=[...L.keys()].filter(h=>!h.endsWith("\0workspace"));if(b.length>=zo){let h=b[0],A=L.get(h);if(L.delete(h),A)try{await(await A).close()}catch(E){throw T({source:"sandbox:workspace-session",level:"warn",message:"Retiring an old scoped workspace sandbox failed.",detail:E}),E}}}x=Rt(e,l,n,r,a,i,()=>{L.get(v)===x&&L.delete(v)}),L.set(v,x),x.catch(()=>{L.get(v)===x&&L.delete(v)})}return x}s(Pt,"getWorkspaceSession");function ti(e){let t=d.resolve(e.workspaceRoot),n=pn(process.platform==="win32"?{}:process.env,ze()),r=process.platform==="win32"?void 0:Pt(t,void 0,void 0,n,n);return r!==void 0&&(Ke.add(r),r.then(()=>Ke.delete(r),()=>Ke.delete(r)),r.catch(o=>{T({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox warm-up failed; admitted commands will use normal permission fallback.",detail:o})})),{processTreeContainment:process.platform==="linux"?"root-exit-drains":void 0,async prepare(o){if(!o.toolCallId){o.reportObservation?.({version:1,state:"not_selected"});return}let i={id:o.toolCallId,name:"bash",input:{...o.toolInput}},c=await e.shouldSandbox(i);if(!c){o.reportObservation?.({version:1,state:"not_selected"});return}let a=typeof c=="object"?c.agentHomeAccess:void 0,l=process.platform==="win32"&&a!==void 0?or(d.resolve(q()),a):a,u=typeof c=="object"?c.filesystemAccess:void 0;if(!ni(u)){o.reportObservation?.({version:1,state:"fallback",reason:"not_ready",execution:"normal_permission_policy"});return}let m=process.platform==="win32"&&l?.ephemeral===!0,w=ze(o.executable),f=o.args??(process.platform==="win32"?["/d","/s","/c",o.command]:["-c",o.command]),p=rt(o.env),y=pn(p,w),v,x;try{r!==void 0&&(await Xn(r.then(()=>{},()=>{}),o.signal,o.deadlineAt),gn(o.signal,o.deadlineAt));let b=Pt(t,l,u,y,n),h;try{h=await Xn(b,o.signal,o.deadlineAt)}catch(F){if(process.platform==="win32"&&(o.signal?.aborted||o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt)){let V=b.then(async M=>{M&&await M.close()},async()=>{});cr(V),V.catch(M=>{T({source:"sandbox:workspace-session",level:"warn",message:"Late cancelled workspace session rollback failed.",detail:M})})}throw F}if(!h){o.reportObservation?.({version:1,state:"fallback",reason:"not_ready",execution:"normal_permission_policy"});return}let A=h.policyKey;x=h;let E=await En(),$=d.join(E,`kodax-asrt-shell-${process.pid}-${H()}.json`),P=d.join(E,`kodax-asrt-observation-${process.pid}-${H()}.json`),ne=p;if(process.platform==="win32"){let F=h.tempDirectory;if(F===void 0)throw new Error("Windows workspace sandbox temp directory is unavailable.");ne=Vt(p,{TEMP:F,TMP:F,TMPDIR:F,GIT_CONFIG_GLOBAL:"NUL",GIT_CONFIG_NOSYSTEM:"1"})}let R={config:at(Go(t,h.tempDirectory,l,u,y)),command:w,args:f,windowsVerbatimArguments:o.windowsVerbatimArguments===!0,cwd:o.cwd,env:ne,endpoints:[],allowAllNetwork:!0,bootstrapCommand:xn(),fallbackToNormalExecution:o.fallbackToNormalExecution!==!1,observationBackend:jr().backend,observationFile:P,targetStartedMarker:`\0KODAX_ASRT_TARGET_STARTED:${H()}\0
|
|
568
|
-
`},j=await h.acquire(R,o.signal,o.deadlineAt);v=j;let K={...R,wrappedInvocation:j.invocation},ce=process.env.KODAX_BUNDLED==="true"?["__asrt-broker",$]:["--input-type=module","-e",Lt,It,$],ye=Ne({args:ce,env:ge(),isElectron:process.versions.electron!==void 0});await Ce($,JSON.stringify(K),{mode:384});let he,Ze=s(async()=>{m||(he===void 0&&(he=x?.close(!1)??Promise.resolve(),he.catch(F=>{T({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox session retirement failed.",detail:F})})),process.platform==="win32"&&await he)},"retireWorkspaceSession");return{executable:process.execPath,args:ye.args,env:ye.env,fileSystemEffectPolicyKey:A,authorizeStart:s(()=>An(A),"authorizeStart"),async cleanup(F){let V,M=[];try{V=await Pe(P,"utf8").then(po).catch(N=>{if(N.code!=="ENOENT")throw N})}catch(N){M.push(N)}let $e=await Promise.allSettled([z($,{force:!0}),z(P,{force:!0})]);for(let N of $e)N.status==="rejected"&&M.push(N.reason);try{await j.release()}catch(N){M.push(N)}let Qe=F?.execution==="started_or_unknown"&&V===void 0;if(Qe&&M.push(new Error("Required OS sandbox execution could not be attested; the workspace session must be retired and the command was not retried")),M.length>0){let N=Qe?"Required OS sandbox execution could not be attested and request cleanup failed; the workspace session must be retired and the command was not retried.":"Required OS sandbox request cleanup failed; the workspace session must be retired.",_e=new AggregateError(M,N);throw T({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox command cleanup failed.",detail:_e}),_e}return V},retire:Ze}}catch(b){let h=[b],A=o.signal?.aborted||o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt,E=!1;if(v)try{await v.release()}catch(P){E=!0,h.push(P),T({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox lease release failed.",detail:P})}if(A&&process.platform==="win32"&&x&&v===void 0)throw x.close().catch(P=>{T({source:"sandbox:workspace-session",level:"warn",message:"Cancelled workspace preparation cleanup could not retire its session.",detail:P})}),b;if(process.platform==="win32"&&x)try{await x.close()}catch(P){h.push(P),T({source:"sandbox:workspace-session",level:"warn",message:"Failed workspace lease cleanup could not retire its session.",detail:P})}else E&&x&&x.close().catch(P=>{T({source:"sandbox:workspace-session",level:"warn",message:"Failed workspace lease cleanup could not retire its session.",detail:P})});if(A)throw b;let $=h.length===1?b:new AggregateError(h,`Workspace sandbox preparation failed and cleanup was incomplete: ${h.map(fe).join(" | ")}`);T({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox preparation failed; using normal permission fallback.",detail:$}),o.reportObservation?.({version:1,state:"fallback",reason:"prepare_failed",execution:"normal_permission_policy"});return}}}}s(ti,"createAsrtShellSandbox");var ri=String.raw`
|
|
569
|
-
const { createHash } = require('node:crypto');
|
|
570
|
-
const fs = require('node:fs/promises');
|
|
571
|
-
const path = require('node:path');
|
|
572
|
-
const chunks = [];
|
|
573
|
-
process.stdin.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
|
|
574
|
-
process.stdin.once('end', async () => {
|
|
575
|
-
const assertSingleLink = (stat) => {
|
|
576
|
-
if (stat.nlink !== 1n) throw new Error('Text mutation target must not be hard-linked.');
|
|
577
|
-
};
|
|
578
|
-
const revision = (content, stat) => 'present:' + createHash('sha256')
|
|
579
|
-
.update(stat.dev.toString())
|
|
580
|
-
.update(':')
|
|
581
|
-
.update(stat.ino.toString())
|
|
582
|
-
.update(':')
|
|
583
|
-
.update(stat.nlink.toString())
|
|
584
|
-
.update('\0')
|
|
585
|
-
.update(content)
|
|
586
|
-
.digest('hex');
|
|
587
|
-
const backupPath = async (target, openedStat) => {
|
|
588
|
-
const canonical = await fs.realpath(target);
|
|
589
|
-
let canonicalHandle;
|
|
590
|
-
try {
|
|
591
|
-
canonicalHandle = await fs.open(canonical, 'r');
|
|
592
|
-
const canonicalStat = await canonicalHandle.stat({ bigint: true });
|
|
593
|
-
assertSingleLink(canonicalStat);
|
|
594
|
-
if (canonicalStat.dev !== openedStat.dev || canonicalStat.ino !== openedStat.ino) {
|
|
595
|
-
throw new Error('Text mutation target identity changed while reading.');
|
|
596
|
-
}
|
|
597
|
-
return canonical;
|
|
598
|
-
} finally {
|
|
599
|
-
await canonicalHandle?.close();
|
|
600
|
-
}
|
|
601
|
-
};
|
|
602
|
-
const snapshot = async (target) => {
|
|
603
|
-
let handle;
|
|
604
|
-
try {
|
|
605
|
-
handle = await fs.open(target, 'r');
|
|
606
|
-
} catch (error) {
|
|
607
|
-
if (error && error.code === 'ENOENT') {
|
|
608
|
-
return { state: 'missing', content: '', revision: 'missing', backupPath: path.resolve(target) };
|
|
609
|
-
}
|
|
610
|
-
throw error;
|
|
611
|
-
}
|
|
612
|
-
try {
|
|
613
|
-
const [content, stat] = await Promise.all([
|
|
614
|
-
handle.readFile('utf8'),
|
|
615
|
-
handle.stat({ bigint: true }),
|
|
616
|
-
]);
|
|
617
|
-
assertSingleLink(stat);
|
|
618
|
-
return {
|
|
619
|
-
state: 'present',
|
|
620
|
-
content,
|
|
621
|
-
revision: revision(content, stat),
|
|
622
|
-
backupPath: await backupPath(target, stat),
|
|
623
|
-
};
|
|
624
|
-
} finally {
|
|
625
|
-
await handle?.close();
|
|
626
|
-
}
|
|
627
|
-
};
|
|
628
|
-
const writeFully = async (handle, content) => {
|
|
629
|
-
const encoded = Buffer.from(content, 'utf8');
|
|
630
|
-
let written = 0;
|
|
631
|
-
while (written < encoded.length) {
|
|
632
|
-
const result = await handle.write(encoded, written, encoded.length - written, written);
|
|
633
|
-
if (result.bytesWritten === 0) throw new Error('Text mutation write made no progress.');
|
|
634
|
-
written += result.bytesWritten;
|
|
635
|
-
}
|
|
636
|
-
await handle.truncate(encoded.length);
|
|
637
|
-
};
|
|
638
|
-
try {
|
|
639
|
-
const input = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
640
|
-
if (!input || typeof input.path !== 'string' || !path.isAbsolute(input.path)) {
|
|
641
|
-
throw new Error('Text mutation target must be an absolute path.');
|
|
642
|
-
}
|
|
643
|
-
if (input.action === 'read') {
|
|
644
|
-
process.stdout.write(JSON.stringify({ status: 'ok', snapshot: await snapshot(input.path) }));
|
|
645
|
-
return;
|
|
646
|
-
}
|
|
647
|
-
if (
|
|
648
|
-
input.action !== 'write'
|
|
649
|
-
|| typeof input.content !== 'string'
|
|
650
|
-
|| typeof input.expectedRevision !== 'string'
|
|
651
|
-
|| typeof input.createParentDirectories !== 'boolean'
|
|
652
|
-
) throw new Error('Invalid text mutation request.');
|
|
653
|
-
if (input.createParentDirectories) await fs.mkdir(path.dirname(input.path), { recursive: true });
|
|
654
|
-
let handle;
|
|
655
|
-
try {
|
|
656
|
-
if (input.expectedRevision === 'missing') {
|
|
657
|
-
handle = await fs.open(input.path, 'wx');
|
|
658
|
-
assertSingleLink(await handle.stat({ bigint: true }));
|
|
659
|
-
} else {
|
|
660
|
-
handle = await fs.open(input.path, 'r+');
|
|
661
|
-
const [content, stat] = await Promise.all([
|
|
662
|
-
handle.readFile('utf8'),
|
|
663
|
-
handle.stat({ bigint: true }),
|
|
664
|
-
]);
|
|
665
|
-
assertSingleLink(stat);
|
|
666
|
-
if (revision(content, stat) !== input.expectedRevision) {
|
|
667
|
-
process.stdout.write(JSON.stringify({ status: 'conflict' }));
|
|
668
|
-
return;
|
|
669
|
-
}
|
|
670
|
-
}
|
|
671
|
-
await writeFully(handle, input.content);
|
|
672
|
-
process.stdout.write(JSON.stringify({ status: 'written' }));
|
|
673
|
-
} catch (error) {
|
|
674
|
-
if (input.expectedRevision === 'missing' && error && error.code === 'EEXIST') {
|
|
675
|
-
process.stdout.write(JSON.stringify({ status: 'conflict' }));
|
|
676
|
-
return;
|
|
677
|
-
}
|
|
678
|
-
throw error;
|
|
679
|
-
} finally {
|
|
680
|
-
await handle?.close();
|
|
681
|
-
}
|
|
682
|
-
} catch (error) {
|
|
683
|
-
process.stderr.write((error instanceof Error ? error.message : String(error)) + '\n');
|
|
684
|
-
process.exitCode = 1;
|
|
685
|
-
}
|
|
686
|
-
});
|
|
687
|
-
`,oi=64*1024*1024,ii=128,wr="__kodaxTextFileMutationCall";function si(e){let t=e.input[wr];if(t===null||typeof t!="object")return;let n=t;if(!(typeof n.id!="string"||typeof n.name!="string"||typeof n.path!="string"||n.input===null||typeof n.input!="object"))return n}s(si,"encodedTextFileMutationCall");async function Ct(e,t,n,r){let o=n.toolCallId??`text-file-${H()}`,i=await e.prepare({toolCallId:o,toolInput:{[wr]:{id:o,name:n.toolName,input:n.toolInput,path:n.path}},command:"kodax-internal-text-file-mutation",executable:process.execPath,args:["-e",ri],cwd:t,env:ge(),fallbackToNormalExecution:!1,signal:n.signal});if(i===void 0)return;let c="not_started",a,l,u=!1,m=!1,w=!1,f,p;try{if(i.fileSystemEffectPolicyKey!==void 0&&(l=await Pn(i.fileSystemEffectPolicyKey)),f=Jn(i.executable,[...i.args],{cwd:t,detached:process.platform!=="win32",env:i.env,shell:!1,stdio:["pipe","pipe","pipe"],windowsHide:!0,windowsVerbatimArguments:i.windowsVerbatimArguments}),c="started_or_unknown",nn(f),l!==void 0){if(f.pid===void 0)throw new Error("Sandboxed text mutation process has no PID.");process.platform==="win32"&&(p=await wt(f.pid)),await l.bindEffectProcess(p?.supervisorPid??f.pid,p!==void 0),u=!0}i.authorizeStart?.();let y=f.stdin;if(y===null)throw new Error("Sandboxed text mutation process has no stdin gate.");let v=Yt(f,n.signal,hn,oi),x=new Promise((A,E)=>{y.end(JSON.stringify(r),$=>{$?E($):A()})}),[b]=await Promise.all([v,x]);if(p!==void 0)await p.drained;else if((await De(f)).status==="unknown")throw new Error("Sandboxed text mutation process tree could not be proven drained.");if(w=!0,l!==void 0&&(await l.finishEffectProcess(),m=!0),b.exitCode!==0)throw new Error(`Sandboxed text mutation failed (${b.exitCode}): ${b.stderr.trim()||"no diagnostics"}`);let h=JSON.parse(b.stdout);if(h===null||typeof h!="object"||Array.isArray(h))throw new Error("Sandboxed text mutation returned an invalid response.");return h}catch(y){throw a=y,y}finally{let y=[];if(f!==void 0&&!w)try{if((await De(f)).status==="unknown")throw new Error("Sandboxed text mutation process tree could not be proven drained.");await p?.drained,w=!0}catch(v){y.push(v)}if(u&&w&&!m)try{await l?.finishEffectProcess()}catch(v){y.push(v)}try{await i.cleanup({execution:c})}catch(v){y.push(v)}try{await l?.()}catch(v){y.push(v)}if(y.length>0)throw new AggregateError([...a===void 0?[]:[a],...y],a===void 0?"Sandboxed text mutation cleanup failed.":"Sandboxed text mutation and cleanup both failed.")}}s(Ct,"executePreparedTextFileMutation");function Gi(e){let t=d.resolve(e.workspaceRoot),n=G(t),r=s(c=>{let a=d.resolve(c);return W(t,a)||W(n,a)},"canHandlePath"),o=new Map,i=ti({workspaceRoot:e.workspaceRoot,shouldSandbox:s(async c=>{let a=si(c);if(a===void 0||!r(a.path))return!1;let l=Ye("sha256").update(a.name).update("\0").update(a.path).update("\0").update(JSON.stringify(a.input)).digest("hex"),u=o.get(a.id);if(u!==void 0&&u.fingerprint!==l)throw new Error(`Text mutation tool-call identity was reused with different input: ${a.id}`);if(u===void 0){let m=Promise.resolve(e.shouldSandbox({id:a.id,name:a.name,input:a.input})).catch(w=>{throw o.delete(a.id),w});u={fingerprint:l,selection:m},o.set(a.id,u),o.size>ii&&o.delete(o.keys().next().value)}return u.selection},"shouldSandbox")});return{canHandlePath:r,async read(c){let a=await Ct(i,t,c,{action:"read",path:c.path});if(a===void 0)return{status:"unavailable"};let l=a.snapshot;if(a.status!=="ok"||l===null||typeof l!="object")throw new Error("Sandboxed text read returned an invalid response.");let u=l;if(u.state!=="missing"&&u.state!=="present"||typeof u.content!="string"||typeof u.revision!="string"||typeof u.backupPath!="string"||!d.isAbsolute(u.backupPath)||!r(u.backupPath))throw new Error("Sandboxed text read returned an invalid snapshot.");return{status:"ok",snapshot:{state:u.state,content:u.content,revision:u.revision,backupPath:u.backupPath}}},async write(c){try{let a=await Ct(i,t,c,{action:"write",path:c.path,content:c.content,expectedRevision:c.expectedRevision,createParentDirectories:c.createParentDirectories});if(a===void 0)return{status:"unavailable"};if(a.status==="written")return{status:"written"};if(a.status==="conflict")return{status:"conflict"};throw new Error("Sandboxed text write returned an invalid response.")}finally{c.toolCallId!==void 0&&o.delete(c.toolCallId)}}}}s(Gi,"createAsrtTextFileMutationSandbox");async function ji(e){let t=await te();if(!t.ready)throw new Error(`ASRT ${ue} is not ready: ${t.diagnostics.join(" ")||"run kodax sandbox setup"}`);let n=d.join(e.snapshotRoot,H()),r=d.join(n,"skills");await J(r,{recursive:!0,mode:448});try{let o=await ho(e,r),i=So(e.network),c=Promise.resolve();return{async run(a,l){let u=c,m;if(c=new Promise(w=>{m=w}),await u,l.signal?.aborted)throw m?.(),l.signal.reason??new Error("Sandboxed Skill script was cancelled.");try{if(a.args.length>64||a.args.some(y=>y.length>8192))throw new Error("Skill script arguments exceed the bounded remote contract.");if(a.inputs.length>32||a.outputs.length>32)throw new Error("Skill script file mappings exceed the bounded remote contract.");let w=se(a.script,"Skill script"),f=o.get(`${a.skill}\0${w}`);if(!f)throw new Error("Skill script is not admitted by this Runtime binding.");if([".cmd",".bat"].includes(d.extname(f.snapshotPath).toLowerCase())&&a.args.some(y=>/[&|<>^]/.test(y)))throw new Error("Batch Skill script arguments cannot contain command operators.");let p=d.join(l.workspaceRoot,".kodax-a2a-script",H());try{await J(d.join(p,"inputs"),{recursive:!0,mode:448}),await J(d.join(p,"outputs"),{recursive:!0,mode:448}),await Eo(l.workspaceRoot,p,a,e.workspaceAccess);let y=bo(f.snapshotPath),v=await xo({config:Po(p,n,i,y.command),command:y.command,args:[...y.args,...a.args],cwd:p,env:ge(),endpoints:i},l.signal),x=await Ro(l.workspaceRoot,p,a,e.workspaceAccess,e.workspaceByteLimit);return JSON.stringify({stdout:v.trim(),outputs:x})}finally{await z(p,{recursive:!0,force:!0})}}finally{m?.()}},async dispose(){await c,await z(n,{recursive:!0,force:!0})}}}catch(o){throw await z(n,{recursive:!0,force:!0}),o}}s(ji,"createAsrtSkillScriptRunner");export{ue as a,jr as b,Oi as c,Ii as d,Ni as e,Li as f,Di as g,te as h,go as i,ke as j,Bi as k,Fi as l,Mi as m,ti as n,Gi as o,ji as p};
|