@kodax-ai/kodax 0.7.93 → 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 +162 -0
- package/README.md +88 -18
- package/README_CN.md +51 -0
- package/dist/builtin/skill-creator/SKILL.md +5 -0
- package/dist/builtin/skill-creator/scripts/init-skill.js +5 -4
- package/dist/chunks/agent-XXZMXKKA.js +2 -0
- package/dist/chunks/argument-completer-KCYDGTQW.js +2 -0
- package/dist/chunks/{chunk-YVG6OKN7.js → chunk-2PEDBGKN.js} +1 -1
- package/dist/chunks/{chunk-XTWIGVUL.js → chunk-2TM3W3GK.js} +10 -10
- package/dist/chunks/{chunk-3YOZIFSJ.js → chunk-6ABQJUK6.js} +252 -251
- package/dist/chunks/chunk-77PNP27P.js +92 -0
- package/dist/chunks/{chunk-JTZKC4TV.js → chunk-7JXA3533.js} +232 -233
- package/dist/chunks/{chunk-7XSZVOG7.js → chunk-BNVSKIAB.js} +340 -142
- package/dist/chunks/chunk-BR2OSB2I.js +722 -0
- package/dist/chunks/{chunk-HLZWPB32.js → chunk-C4DTUKTR.js} +2 -2
- package/dist/chunks/{chunk-4BY53JTF.js → chunk-DSMONSVB.js} +121 -122
- package/dist/chunks/{chunk-PRASABCC.js → chunk-JS452J2F.js} +2 -2
- package/dist/chunks/chunk-O743AJ5V.js +323 -0
- package/dist/chunks/{chunk-GRWUC6H7.js → chunk-OK4AXDC5.js} +1 -1
- package/dist/chunks/chunk-Q5VRWSKG.js +418 -0
- package/dist/chunks/{chunk-GH3KBC2H.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-OVYKC3ND.js → client-JDOS3YJR.js} +1 -1
- package/dist/chunks/compaction-config-EGS4577X.js +2 -0
- package/dist/chunks/{construction-bootstrap-474QPSYB.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 +26 -26
- package/dist/index.js +2 -2
- package/dist/kodax_bootstrap.js +1 -1
- package/dist/kodax_cli.js +1869 -1461
- package/dist/kodax_resume.js +35 -35
- package/dist/runtime-worker.js +1819 -1411
- package/dist/sandbox-workspace-session.js +481 -638
- package/dist/sdk-a2a.d.ts +18 -18
- package/dist/sdk-a2a.js +1 -1
- package/dist/sdk-agent.d.ts +47 -26
- package/dist/sdk-agent.js +1 -1
- package/dist/sdk-coding.d.ts +54 -39
- 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-media.js +1 -1
- package/dist/sdk-repl.d.ts +43 -25
- package/dist/sdk-repl.js +2 -2
- package/dist/sdk-runtime.d.ts +57 -32
- package/dist/sdk-runtime.js +1 -1
- package/dist/sdk-sandbox.d.ts +10 -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 -333
- package/dist/sdk-skills.js +1 -1
- package/dist/semantic-worker.js +279 -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-BMi_TJIY.d.ts → bash-prefix-extractor.d-B2rxNI4L.d.ts} +70 -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-CKkoea7y.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-BsZWOq3P.d.ts → public-api.d-D7fXaWW8.d.ts} +7 -6
- package/dist/types-chunks/{repl.d-DxD0Olm0.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-BTzblJTQ.d.ts → sdk-session-CqEG84oP.d.ts} +3 -3
- package/dist/types-chunks/sdk-skills-DokfOoJF.d.ts +335 -0
- package/dist/types-chunks/{shell-command-sets.d-C2cc9Hwi.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-DrtP1ceI.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-Dc3kwcjC.d.ts → types.d-CaTXAW_Q.d.ts} +14 -3
- package/dist/types-chunks/{types.d-BEMcUOng.d.ts → types.d-Cb8RdrjU.d.ts} +5 -4
- package/dist/types-chunks/{types.d-EjZTEEVu.d.ts → types.d-rUOjXych.d.ts} +6 -2
- package/dist/types-chunks/{utils.d-50Q24Few.d.ts → utils.d-CWUyLiXo.d.ts} +8 -8
- package/package.json +2 -2
- package/dist/chunks/agent-R7HVNARP.js +0 -2
- package/dist/chunks/argument-completer-JHXUJWHC.js +0 -2
- package/dist/chunks/chunk-A3ZQE2BX.js +0 -519
- package/dist/chunks/chunk-D27EY4XC.js +0 -383
- package/dist/chunks/chunk-JJ2YDBSN.js +0 -415
- package/dist/chunks/chunk-QFV6YCIH.js +0 -92
- package/dist/chunks/chunk-SMVC3Q3U.js +0 -320
- package/dist/chunks/compaction-config-2TVSYSB4.js +0 -2
- package/dist/chunks/dist-H4PT2QAV.js +0 -2
- package/dist/chunks/host-OR3IO2A4.js +0 -2
- package/dist/chunks/run-manager-MNOTWIFX.js +0 -2
- package/dist/chunks/utils-5J4BHNBV.js +0 -2
|
@@ -0,0 +1,722 @@
|
|
|
1
|
+
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
+
import{i as Qn,j as et,k as En,l as nn,m as tn,n as nt}from"./chunk-XWRPOGJN.js";import{$a as Kt,Cc as Ut,Dc as z,Ia as K,Wa as Gt,Ya as qt,_a as Ze,db as De,eb as Jt,fb as Qe,ib as ie,mb as en,nb as Se,pb as Xt,t as W}from"./chunk-BNVSKIAB.js";import{a as i}from"./chunk-ONUPGMER.js";import{spawn as Gn,spawnSync as qn}from"node:child_process";import{createHash as gn,randomUUID as F}from"node:crypto";import{once as zt}from"node:events";import{closeSync as mo,constants as go,existsSync as Tn,lstatSync as Kn,mkdirSync as $n,openSync as yo,readFileSync as Jn,readSync as So,readdirSync as yt,realpathSync as j,renameSync as St,rmSync as Y,statSync as Ke,writeFileSync as ht,writeSync as hs}from"node:fs";import{copyFile as ar,lstat as ho,mkdir as V,readFile as Je,realpath as cn,rename as bo,rm as L,rmdir as vo,stat as _n,writeFile as _e}from"node:fs/promises";import{createRequire as xo}from"node:module";import{createServer as ko}from"node:net";import ee from"node:os";import d from"node:path";import Ao from"node:readline";import{fileURLToPath as Vt,pathToFileURL as dr}from"node:url";function ro(e){let t=e.code;return t==="ENOENT"||t==="ENOTDIR"}i(ro,"isMissingGitTrustPath");function oo(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}}i(oo,"normalizeGitSafeDirectoryRootImplementation");function io(e,t,n,r){try{let s=t(n.join(e,".git"));if(s.isDirectory()||s.isFile())return!0}catch(s){if(!r(s))throw s}if(!(n.basename(e).toLowerCase()===".git"||/[/\\]\.git[/\\]modules[/\\]/i.test(e)))return!1;try{return t(n.join(e,"HEAD")).isFile()}catch(s){if(r(s))return!1;throw s}}i(io,"isRepoBearingGitReadRootImplementation");function so(e,t,n,r,o){let s=[];typeof e=="string"&&e!==""&&s.push(e);for(let c of n??[])o(c)&&s.push(c);s.push(...t??[]);let l=[],a=new Set;for(let c of s){if(l.length>=8)break;let f=r(c);if(f===void 0)continue;let u=f.toLowerCase();a.has(u)||(a.add(u),l.push(f))}return l}i(so,"windowsGitTrustRootsImplementation");function ao(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"}i(ao,"gitConfigEnvKind");function co(e,t,n,r,o){let s=new Map,l=[],a,c=!1;for(let f=0;f<t;f+=1){if(e[f]!=="--env"||f+1>=t)continue;let u=e[f+1],m=u.indexOf("="),p=(m<0?u:u.slice(0,m)).toLowerCase(),g=n(p);if(g===void 0)continue;c=!0,l.push(f);let w=m<0?"":u.slice(m+1);if(g==="count"){let y=Number.parseInt(w,10);(a!==void 0||!Number.isSafeInteger(y)||y<0||String(y)!==w)&&r(),a=y;continue}let x=Number.parseInt(p.slice(`git_config_${g}_`.length),10),b=s.get(x)??{};(!Number.isSafeInteger(x)||x<0||b[g]!==void 0)&&r(),b[g]=w,s.set(x,b)}return o(s,l,a,c,r)}i(co,"parseGitConfigEnvironmentImplementation");function lo(){throw new Error("ASRT GIT_CONFIG environment has an unexpected shape.")}i(lo,"throwUnexpectedGitConfigShape");function uo(e,t,n,r,o){!r||n!==void 0&&e.size===n&&[...e].every(([a,c])=>a<n&&c.key!==void 0&&c.value!==void 0)||o();let l=[...e].map(([a,c])=>({slot:a,key:c.key,value:c.value}));return{argumentIndices:t,pairs:l,sawAny:r}}i(uo,"finishParsedGitConfigEnvironment");function fo(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,s)=>[`GIT_CONFIG_KEY_${s}=${o.key}`,`GIT_CONFIG_VALUE_${s}=${o.value}`]);return r.push(`GIT_CONFIG_COUNT=${n.length}`),r}i(fo,"gitSafeDirectoryAssignments");function po(e,t,n,r){let o=new Set(n.argumentIndices),s=[],l=!1;for(let a=0;a<e.length;a+=1)if(o.has(a)){if(!l){for(let c of r)s.push("--env",c);l=!0}a+=1}else s.push(e[a]);return n.sawAny||s.splice(t,0,...r.flatMap(a=>["--env",a])),s}i(po,"replaceGitConfigEnvironment");function wo(e,t,n,r,o){let s=e.lastIndexOf("--");if(s<0)throw new Error("ASRT Windows wrapper omitted its child separator.");let l=n(e,s),a=l.pairs.filter(f=>f.key.toLowerCase()!=="safe.directory").sort((f,u)=>f.slot-u.slot),c=r(t,a);return o(e,s,l,c)}i(wo,"rewriteWindowsGitSafeDirectoryArgvImplementation");function Ht(){return String.raw`
|
|
3
|
+
const isMissingGitTrustPath = ${ro.toString()};
|
|
4
|
+
const normalizeGitSafeDirectoryRootImplementation = ${oo.toString()};
|
|
5
|
+
const normalizeGitSafeDirectoryRoot = (root) => (
|
|
6
|
+
normalizeGitSafeDirectoryRootImplementation(root, realpathSync, isMissingGitTrustPath)
|
|
7
|
+
);
|
|
8
|
+
const isRepoBearingGitReadRootImplementation = ${io.toString()};
|
|
9
|
+
const isRepoBearingGitReadRoot = (root) => (
|
|
10
|
+
isRepoBearingGitReadRootImplementation(root, statSync, path, isMissingGitTrustPath)
|
|
11
|
+
);
|
|
12
|
+
const windowsGitTrustRootsImplementation = ${so.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 = ${ao.toString()};
|
|
24
|
+
const throwUnexpectedGitConfigShape = ${lo.toString()};
|
|
25
|
+
const finishParsedGitConfigEnvironment = ${uo.toString()};
|
|
26
|
+
const parseGitConfigEnvironmentImplementation = ${co.toString()};
|
|
27
|
+
const parseGitConfigEnvironment = (argv, separator) => (
|
|
28
|
+
parseGitConfigEnvironmentImplementation(
|
|
29
|
+
argv,
|
|
30
|
+
separator,
|
|
31
|
+
gitConfigEnvKind,
|
|
32
|
+
throwUnexpectedGitConfigShape,
|
|
33
|
+
finishParsedGitConfigEnvironment,
|
|
34
|
+
)
|
|
35
|
+
);
|
|
36
|
+
const gitSafeDirectoryAssignments = ${fo.toString()};
|
|
37
|
+
const replaceGitConfigEnvironment = ${po.toString()};
|
|
38
|
+
const rewriteWindowsGitSafeDirectoryArgvImplementation = ${wo.toString()};
|
|
39
|
+
const rewriteWindowsGitSafeDirectoryArgv = (argv, trustRoots) => (
|
|
40
|
+
rewriteWindowsGitSafeDirectoryArgvImplementation(
|
|
41
|
+
argv,
|
|
42
|
+
trustRoots,
|
|
43
|
+
parseGitConfigEnvironment,
|
|
44
|
+
gitSafeDirectoryAssignments,
|
|
45
|
+
replaceGitConfigEnvironment,
|
|
46
|
+
)
|
|
47
|
+
);
|
|
48
|
+
`}i(Ht,"windowsGitBrokerHelpersSource");var $e="0.0.65",{DEFAULT_WINDOWS_PROXY_PORT_RANGE:Eo,SandboxManager:tt,getSrtWinPath:Ro,getWindowsSandboxUserStatus:yn,grantWindowsAcl:Po,installWindowsSandbox:Co,resolveSrtWin:Wo,revokeWindowsAcl:cr}=await import("@anthropic-ai/sandbox-runtime");function To(e,t){if(t.length===0)return e;let n=[...new Set(t.map(o=>d.resolve(o)))],r=typeof e=="object"?e.filesystemAccess:void 0;return{...typeof e=="object"&&e.agentHomeAccess!==void 0?{agentHomeAccess:e.agentHomeAccess}:{},filesystemAccess:{read:[...new Set([...r?.read??[],...n])],write:[...new Set([...r?.write??[],...n])]}}}i(To,"withAdditionalWorkspaceRoots");function $o(){let e=process.platform==="win32"?"windows-restricted-user":process.platform==="darwin"?"macos-seatbelt":process.platform==="linux"?"linux-bubblewrap":"unsupported";return{version:5,asrtVersion:$e,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",delayedEffectDrainRecovery:"automatic",sameBootAclRecovery:"sandbox-user-process-probe"}}i($o,"sandboxRuntimeCapability");var bt=1048576,Xn=12e4,vt=xo(import.meta.url),lr=process.env.KODAX_BUNDLED==="true"?void 0:dr(vt.resolve("@anthropic-ai/sandbox-runtime")).href,_o=new Set([".ssh",".aws",".azure",".gnupg",".kodax",".agents",".codex",".claude",".gemini",".direnv",".terraform.d"]),Oo=new Set([".env",".envrc",".pgpass",".npmrc",".pypirc","credentials","id_rsa","id_ed25519"]),No=[".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"],Io=["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"],xt=["runtime","processes","learned"],Lo=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
|
+
`,dt=new Set,ur=new Set,Yt=JSON.stringify(qt),rt=JSON.stringify(Gt),Fo=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
|
+
`,Do="eval(Buffer.from(process.argv[1],'base64').toString('utf8'))",Bo=JSON.stringify(Do),Mo=Buffer.from(Fo,"utf8").toString("base64"),jo=JSON.stringify(Mo),Go=Ht(),qo=String.raw`
|
|
270
|
+
const { spawn } = require('node:child_process');
|
|
271
|
+
const { createWriteStream } = require('node:fs');
|
|
272
|
+
const { readFile, rm } = require('node:fs/promises');
|
|
273
|
+
const readline = require('node:readline');
|
|
274
|
+
const input = readline.createInterface({ input: process.stdin, terminal: false });
|
|
275
|
+
input.once('line', async (gate) => {
|
|
276
|
+
input.close();
|
|
277
|
+
if (gate !== 'go') { process.exitCode = 125; return; }
|
|
278
|
+
const launchFile = process.argv[1];
|
|
279
|
+
const launch = JSON.parse(await readFile(launchFile, 'utf8'));
|
|
280
|
+
await rm(launchFile, { force: true });
|
|
281
|
+
const child = spawn(launch.command, launch.args, {
|
|
282
|
+
cwd: launch.cwd,
|
|
283
|
+
env: launch.env,
|
|
284
|
+
shell: false,
|
|
285
|
+
stdio: launch.controlPipe === true
|
|
286
|
+
? ['pipe', 'pipe', 'pipe', 'pipe']
|
|
287
|
+
: ['pipe', 'pipe', 'pipe'],
|
|
288
|
+
windowsHide: true,
|
|
289
|
+
});
|
|
290
|
+
process.stdin.pipe(child.stdin);
|
|
291
|
+
child.stdout.pipe(process.stdout);
|
|
292
|
+
child.stderr.pipe(process.stderr);
|
|
293
|
+
if (launch.controlPipe === true && child.stdio[3]) {
|
|
294
|
+
child.stdio[3].pipe(createWriteStream(null, { fd: 3, autoClose: false }));
|
|
295
|
+
}
|
|
296
|
+
child.once('error', (error) => {
|
|
297
|
+
process.stderr.write(String(error?.message ?? error));
|
|
298
|
+
process.exitCode = 1;
|
|
299
|
+
});
|
|
300
|
+
child.once('close', (code) => { process.exitCode = Number.isInteger(code) ? code : 1; });
|
|
301
|
+
});
|
|
302
|
+
`,fr=String.raw`
|
|
303
|
+
import { spawn } from 'node:child_process';
|
|
304
|
+
import { randomUUID } from 'node:crypto';
|
|
305
|
+
import { readFile, rm, writeFile } from 'node:fs/promises';
|
|
306
|
+
import { realpathSync, statSync } from 'node:fs';
|
|
307
|
+
import path from 'node:path';
|
|
308
|
+
let SandboxManager;
|
|
309
|
+
const request = JSON.parse(await readFile(process.argv[2], 'utf8'));
|
|
310
|
+
await rm(process.argv[2], { force: true });
|
|
311
|
+
const targetStartedMarker = request.targetStartedMarker
|
|
312
|
+
?? '\u0000KODAX_ASRT_TARGET_STARTED:' + randomUUID() + '\u0000\n';
|
|
313
|
+
const endpoints = new Set(request.endpoints.map((item) => item.host.toLowerCase() + ':' + item.port));
|
|
314
|
+
const callback = request.allowAllNetwork === true
|
|
315
|
+
? async () => true
|
|
316
|
+
: request.endpoints.length === 0
|
|
317
|
+
? undefined
|
|
318
|
+
: async ({ host, port }) => endpoints.has(host.toLowerCase() + ':' + port);
|
|
319
|
+
${Go}
|
|
320
|
+
const withWindowsChildEnvironment = (argv, environment, gitTrustRoots) => {
|
|
321
|
+
const separator = argv.lastIndexOf('--');
|
|
322
|
+
if (separator < 0) throw new Error('ASRT Windows wrapper omitted its child separator.');
|
|
323
|
+
const requested = [];
|
|
324
|
+
const requestedNames = new Set();
|
|
325
|
+
for (const [name, value] of Object.entries(environment ?? {})) {
|
|
326
|
+
if (value === undefined) continue;
|
|
327
|
+
if (!name || name.includes('=') || name.includes('\0') || value.includes('\0')) {
|
|
328
|
+
throw new Error('Invalid environment entry for ASRT Windows child.');
|
|
329
|
+
}
|
|
330
|
+
const normalized = name.toLowerCase();
|
|
331
|
+
if (requestedNames.has(normalized)) {
|
|
332
|
+
throw new Error('Ambiguous Windows child environment variable: ' + name + '.');
|
|
333
|
+
}
|
|
334
|
+
requestedNames.add(normalized);
|
|
335
|
+
requested.push([name, value]);
|
|
336
|
+
}
|
|
337
|
+
const requestedOverrides = new Set(requested.flatMap(([name]) => (
|
|
338
|
+
['path', 'pathext'].includes(name.toLowerCase()) ? [name.toLowerCase()] : []
|
|
339
|
+
)));
|
|
340
|
+
const controlled = new Set();
|
|
341
|
+
const prefix = [];
|
|
342
|
+
for (let index = 0; index < separator; index += 1) {
|
|
343
|
+
if (argv[index] !== '--env' || index + 1 >= separator) {
|
|
344
|
+
prefix.push(argv[index]);
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
const assignment = argv[index + 1];
|
|
348
|
+
const name = assignment.split('=', 1)[0]?.toLowerCase();
|
|
349
|
+
if (name) controlled.add(name);
|
|
350
|
+
if (!name || !requestedOverrides.has(name)) prefix.push(argv[index], assignment);
|
|
351
|
+
index += 1;
|
|
352
|
+
}
|
|
353
|
+
const injected = [];
|
|
354
|
+
for (const [name, value] of requested) {
|
|
355
|
+
const normalized = name.toLowerCase();
|
|
356
|
+
if (controlled.has(normalized) && normalized !== 'path' && normalized !== 'pathext') continue;
|
|
357
|
+
injected.push('--env', name + '=' + value);
|
|
358
|
+
}
|
|
359
|
+
const result = [...prefix, ...injected, ...argv.slice(separator)];
|
|
360
|
+
const withGitTrust = rewriteWindowsGitSafeDirectoryArgv(result, gitTrustRoots);
|
|
361
|
+
const estimate = withGitTrust.reduce((size, value) => size + value.length + 3, 0);
|
|
362
|
+
if (estimate > 30000) throw new Error('ASRT Windows child environment exceeds the CreateProcess command-line limit.');
|
|
363
|
+
return withGitTrust;
|
|
364
|
+
};
|
|
365
|
+
const writeObservation = async (observation) => {
|
|
366
|
+
if (typeof request.observationFile !== 'string') return;
|
|
367
|
+
await writeFile(request.observationFile, JSON.stringify(observation), { mode: 0o600 });
|
|
368
|
+
};
|
|
369
|
+
const waitForTarget = (target, observation) => {
|
|
370
|
+
const marker = Buffer.from(targetStartedMarker, 'utf8');
|
|
371
|
+
let pending = Buffer.alloc(0);
|
|
372
|
+
let diagnostic = Buffer.alloc(0);
|
|
373
|
+
let processError;
|
|
374
|
+
let wrapperSpawned = false;
|
|
375
|
+
let targetStarted = false;
|
|
376
|
+
let observationWrite = Promise.resolve();
|
|
377
|
+
return new Promise((resolve, reject) => {
|
|
378
|
+
let settled = false;
|
|
379
|
+
target.once('spawn', () => {
|
|
380
|
+
wrapperSpawned = true;
|
|
381
|
+
});
|
|
382
|
+
const finish = (result) => {
|
|
383
|
+
if (settled) return;
|
|
384
|
+
settled = true;
|
|
385
|
+
void observationWrite.then(() => resolve(result), reject);
|
|
386
|
+
};
|
|
387
|
+
target.stderr.on('data', (chunk) => {
|
|
388
|
+
if (targetStarted) {
|
|
389
|
+
process.stderr.write(chunk);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
pending = Buffer.concat([pending, Buffer.from(chunk)]);
|
|
393
|
+
const markerOffset = pending.indexOf(marker);
|
|
394
|
+
if (markerOffset >= 0) {
|
|
395
|
+
targetStarted = true;
|
|
396
|
+
const suffix = pending.subarray(markerOffset + marker.length);
|
|
397
|
+
pending = Buffer.alloc(0);
|
|
398
|
+
diagnostic = Buffer.alloc(0);
|
|
399
|
+
observationWrite = writeObservation(observation).catch(() => undefined);
|
|
400
|
+
if (suffix.length > 0) process.stderr.write(suffix);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
const retained = Math.max(0, marker.length - 1);
|
|
404
|
+
if (pending.length > retained) {
|
|
405
|
+
diagnostic = Buffer.concat([
|
|
406
|
+
diagnostic,
|
|
407
|
+
pending.subarray(0, pending.length - retained),
|
|
408
|
+
]).subarray(-65536);
|
|
409
|
+
pending = pending.subarray(pending.length - retained);
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
target.once('error', (error) => {
|
|
413
|
+
processError = error instanceof Error ? error.message : String(error);
|
|
414
|
+
});
|
|
415
|
+
target.once('close', (exitCode, signal) => {
|
|
416
|
+
const preTarget = Buffer.concat([diagnostic, pending]).toString('utf8').trim();
|
|
417
|
+
finish({
|
|
418
|
+
exitCode: signal ? 1 : exitCode ?? 1,
|
|
419
|
+
targetStarted,
|
|
420
|
+
spawnFailedBeforeSpawn: processError !== undefined && !wrapperSpawned,
|
|
421
|
+
diagnostic: preTarget || processError || undefined,
|
|
422
|
+
});
|
|
423
|
+
});
|
|
424
|
+
});
|
|
425
|
+
};
|
|
426
|
+
let child;
|
|
427
|
+
let targetStarted = false;
|
|
428
|
+
let normalFallbackAttempted = false;
|
|
429
|
+
const runDirect = async () => {
|
|
430
|
+
const internalElectronNode = request.command === process.execPath && process.versions.electron !== undefined;
|
|
431
|
+
const directArgs = internalElectronNode
|
|
432
|
+
? ['--import', ${Yt}, ...request.args]
|
|
433
|
+
: request.args;
|
|
434
|
+
const directEnv = internalElectronNode
|
|
435
|
+
? { ...request.env, [${rt}]: '1' }
|
|
436
|
+
: request.env;
|
|
437
|
+
child = spawn(request.command, directArgs, {
|
|
438
|
+
cwd: request.cwd,
|
|
439
|
+
env: directEnv,
|
|
440
|
+
shell: false,
|
|
441
|
+
stdio: 'inherit',
|
|
442
|
+
windowsHide: true,
|
|
443
|
+
windowsVerbatimArguments: request.windowsVerbatimArguments === true,
|
|
444
|
+
});
|
|
445
|
+
return await new Promise((resolve, reject) => {
|
|
446
|
+
child.once('error', reject);
|
|
447
|
+
child.once('exit', (exitCode, signal) => resolve(signal ? 1 : exitCode ?? 1));
|
|
448
|
+
});
|
|
449
|
+
};
|
|
450
|
+
const runNormalFallback = async () => {
|
|
451
|
+
if (
|
|
452
|
+
request.fallbackToNormalExecution !== true
|
|
453
|
+
|| targetStarted
|
|
454
|
+
|| normalFallbackAttempted
|
|
455
|
+
) return false;
|
|
456
|
+
await writeObservation({
|
|
457
|
+
version: 1,
|
|
458
|
+
state: 'fallback',
|
|
459
|
+
reason: 'backend_failed',
|
|
460
|
+
execution: 'normal_permission_policy',
|
|
461
|
+
}).catch(() => undefined);
|
|
462
|
+
normalFallbackAttempted = true;
|
|
463
|
+
process.exitCode = await runDirect();
|
|
464
|
+
return true;
|
|
465
|
+
};
|
|
466
|
+
try {
|
|
467
|
+
if (request.wrappedInvocation) {
|
|
468
|
+
const wrapped = request.wrappedInvocation;
|
|
469
|
+
child = spawn(wrapped.executable, wrapped.args, {
|
|
470
|
+
cwd: request.cwd,
|
|
471
|
+
env: wrapped.env,
|
|
472
|
+
shell: wrapped.shell,
|
|
473
|
+
stdio: ['inherit', 'inherit', 'pipe'],
|
|
474
|
+
windowsHide: true,
|
|
475
|
+
});
|
|
476
|
+
const result = await waitForTarget(child, {
|
|
477
|
+
version: 1,
|
|
478
|
+
state: 'applied',
|
|
479
|
+
backend: request.observationBackend ?? 'unsupported',
|
|
480
|
+
policyId: 'kodax-workspace-shell-v1',
|
|
481
|
+
});
|
|
482
|
+
targetStarted = result.targetStarted;
|
|
483
|
+
const fellBack = result.spawnFailedBeforeSpawn
|
|
484
|
+
? await runNormalFallback()
|
|
485
|
+
: false;
|
|
486
|
+
if (!targetStarted && !fellBack) {
|
|
487
|
+
process.stderr.write((result.diagnostic || 'Sandbox target launch could not be attested.') + '\n');
|
|
488
|
+
}
|
|
489
|
+
if (!fellBack) process.exitCode = targetStarted ? result.exitCode : 1;
|
|
490
|
+
} else {
|
|
491
|
+
({ SandboxManager } = await import(process.argv[1]));
|
|
492
|
+
const bootstrap = request.bootstrapCommand ?? 'node';
|
|
493
|
+
const bootstrapIsAbsolute = /^(?:[A-Za-z]:[\\/]|\\\\)/.test(bootstrap);
|
|
494
|
+
const bootstrapIsElectronNode = bootstrap === process.execPath
|
|
495
|
+
&& process.versions.electron !== undefined;
|
|
496
|
+
const config = process.platform === 'win32' && bootstrapIsAbsolute
|
|
497
|
+
? {
|
|
498
|
+
...request.config,
|
|
499
|
+
filesystem: {
|
|
500
|
+
...request.config.filesystem,
|
|
501
|
+
allowRead: [...new Set([
|
|
502
|
+
...request.config.filesystem.allowRead,
|
|
503
|
+
bootstrap,
|
|
504
|
+
path.dirname(bootstrap),
|
|
505
|
+
])],
|
|
506
|
+
},
|
|
507
|
+
}
|
|
508
|
+
: request.config;
|
|
509
|
+
await SandboxManager.initialize(config, callback);
|
|
510
|
+
const quote = (value) => process.platform === 'win32'
|
|
511
|
+
? '"' + value.replaceAll('"', '""') + '"'
|
|
512
|
+
: "'" + value.replaceAll("'", "'\"'\"'") + "'";
|
|
513
|
+
const internalElectronNode = request.command === process.execPath && process.versions.electron !== undefined;
|
|
514
|
+
const childArgs = internalElectronNode
|
|
515
|
+
? ['--import', ${Yt}, ...request.args]
|
|
516
|
+
: request.args;
|
|
517
|
+
const command = [
|
|
518
|
+
quote(bootstrap),
|
|
519
|
+
'-e',
|
|
520
|
+
quote(${Bo}),
|
|
521
|
+
${jo},
|
|
522
|
+
Buffer.from(JSON.stringify({
|
|
523
|
+
command: request.command,
|
|
524
|
+
args: childArgs,
|
|
525
|
+
windowsVerbatimArguments: request.windowsVerbatimArguments === true,
|
|
526
|
+
cwd: request.cwd,
|
|
527
|
+
targetStartedMarker,
|
|
528
|
+
electronRunAsNode: internalElectronNode,
|
|
529
|
+
}), 'utf8').toString('base64'),
|
|
530
|
+
].join(' ');
|
|
531
|
+
if (process.platform === 'win32') {
|
|
532
|
+
const wrapped = await SandboxManager.wrapWithSandboxArgv(command, 'cmd', undefined, undefined, request.cwd);
|
|
533
|
+
const requestedEnv = internalElectronNode || bootstrapIsElectronNode
|
|
534
|
+
? { ...request.env, [${rt}]: '1' }
|
|
535
|
+
: request.env;
|
|
536
|
+
const childArgv = withWindowsChildEnvironment(wrapped.argv, requestedEnv, windowsGitTrustRoots(request));
|
|
537
|
+
child = spawn(childArgv[0], childArgv.slice(1), {
|
|
538
|
+
cwd: request.cwd,
|
|
539
|
+
env: wrapped.env,
|
|
540
|
+
shell: false,
|
|
541
|
+
stdio: ['inherit', 'inherit', 'pipe'],
|
|
542
|
+
windowsHide: true,
|
|
543
|
+
});
|
|
544
|
+
} else {
|
|
545
|
+
const wrapped = await SandboxManager.wrapWithSandbox(command);
|
|
546
|
+
const childEnv = internalElectronNode || bootstrapIsElectronNode
|
|
547
|
+
? { ...request.env, [${rt}]: '1' }
|
|
548
|
+
: request.env;
|
|
549
|
+
child = spawn(wrapped, {
|
|
550
|
+
cwd: request.cwd,
|
|
551
|
+
env: childEnv,
|
|
552
|
+
shell: true,
|
|
553
|
+
stdio: ['inherit', 'inherit', 'pipe'],
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
const stop = () => child?.kill('SIGTERM');
|
|
557
|
+
process.once('SIGINT', stop);
|
|
558
|
+
process.once('SIGTERM', stop);
|
|
559
|
+
const result = await waitForTarget(child, {
|
|
560
|
+
version: 1,
|
|
561
|
+
state: 'applied',
|
|
562
|
+
backend: request.observationBackend ?? 'unsupported',
|
|
563
|
+
policyId: 'kodax-workspace-shell-v1',
|
|
564
|
+
});
|
|
565
|
+
targetStarted = result.targetStarted;
|
|
566
|
+
try { SandboxManager.cleanupAfterCommand(); } catch {}
|
|
567
|
+
await SandboxManager.reset().catch(() => undefined);
|
|
568
|
+
const fellBack = result.spawnFailedBeforeSpawn
|
|
569
|
+
? await runNormalFallback()
|
|
570
|
+
: false;
|
|
571
|
+
if (!targetStarted && !fellBack) {
|
|
572
|
+
process.stderr.write((result.diagnostic || 'Sandbox target launch could not be attested.') + '\n');
|
|
573
|
+
}
|
|
574
|
+
if (!fellBack) process.exitCode = targetStarted ? result.exitCode : 1;
|
|
575
|
+
}
|
|
576
|
+
} catch (error) {
|
|
577
|
+
await SandboxManager?.reset().catch(() => undefined);
|
|
578
|
+
if (
|
|
579
|
+
request.fallbackToNormalExecution === true
|
|
580
|
+
&& !targetStarted
|
|
581
|
+
&& !normalFallbackAttempted
|
|
582
|
+
&& child === undefined
|
|
583
|
+
) {
|
|
584
|
+
try {
|
|
585
|
+
await runNormalFallback();
|
|
586
|
+
} catch (fallbackError) {
|
|
587
|
+
process.stderr.write((fallbackError instanceof Error ? fallbackError.message : String(fallbackError)) + '\n');
|
|
588
|
+
process.exitCode = 1;
|
|
589
|
+
}
|
|
590
|
+
} else {
|
|
591
|
+
process.stderr.write((error instanceof Error ? error.message : String(error)) + '\n');
|
|
592
|
+
process.exitCode = 1;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
`,Be,Rn=0,Ko=3e4,rn,On,ln=!1,Ce;function be(e){return e instanceof Error?e.message:String(e)}i(be,"errorText");function un(e,...t){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}i(un,"isFileSystemError");async function Zt(e){try{return await Je(e)}catch(t){if(un(t,"ENOENT"))return;throw t}}i(Zt,"readFileIfPresent");async function Jo(e,t){let n=await Zt(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}.${F()}.tmp`;try{await _e(r,e,{flag:"wx",mode:448});try{await bo(r,t)}catch(o){if(!(await Zt(t))?.equals(e))throw o}}finally{await L(r,{force:!0})}}i(Jo,"installWindowsRunnerCopy");async function fn(){if(rn===void 0){let e=(async()=>{let t=await Je(Ro()),n=gn("sha256").update(t).digest("hex").slice(0,16),r=d.join(d.resolve(K()),"sandbox-runtime","runner",$e,process.arch,n),o=d.join(r,"srt-win.exe");await V(Hn(),{recursive:!0,mode:448}),await V(r,{recursive:!0,mode:448}),await Jo(t,o);let s={path:o,directory:r,srtWin:Wo({path:o})};return On=s,s})();rn=e,e.catch(()=>{rn===e&&(rn=void 0,On=void 0)})}return rn}i(fn,"prepareWindowsSandboxRunner");function le(){if(process.platform!=="win32")throw new Error("A prepared Windows sandbox runner was requested on a non-Windows platform.");if(On===void 0)throw new Error("Windows sandbox runner is not prepared; run the sandbox readiness check first.");return On}i(le,"requirePreparedWindowsRunner");var I=new Set,X=new Map,xe=new Map,ot,ne=35e3,Oe="[acl_cleanup_unconfirmed]",M=class extends Error{static{i(this,"WindowsSandboxAclAdmissionError")}recoveryAction;constructor(t,n){super(t,n),this.name="WindowsSandboxAclAdmissionError",this.recoveryAction=n?.recoveryAction}},pn=class extends M{static{i(this,"UnreadableWindowsSandboxAclRecoveryTicketError")}constructor(t,n){super(`Windows sandbox ACL recovery ticket is temporarily unreadable: ${t}. Sandbox admission will retry automatically; non-sandbox work remains available.`,{cause:n,recoveryAction:"automatic-retry"}),this.name="UnreadableWindowsSandboxAclRecoveryTicketError"}};function pr(e){return/^windows-boot-\d+$/.test(e)}i(pr,"isCanonicalWindowsBootIdentity");function Un(e){return e.diagnostics.some(t=>t.startsWith(Oe))}i(Un,"doctorHasWindowsSandboxAclCleanupBlock");function Sn(){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")}i(Sn,"windowsSandboxAclPoisonDirectory");function Hn(){return d.dirname(Sn())}i(Hn,"windowsSandboxAclCoordinationDirectory");function wr(e=K()){return d.join(d.resolve(e),"sandbox-runtime","acl-poison")}i(wr,"legacyWindowsSandboxAclPoisonDirectory");function kt(){return d.join(Hn(),"acl-poison-staging")}i(kt,"windowsSandboxAclPoisonStagingDirectory");function At(e=K()){return d.join(d.resolve(e),"sandbox-runtime","acl-poison-staging")}i(At,"legacyWindowsSandboxAclPoisonStagingDirectory");function te(){return d.join(Hn(),"acl-recovery.lock")}i(te,"windowsSandboxAclRecoveryLockFile");function zn(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.version!==3||n.state!==void 0&&n.state!=="active"&&n.state!=="unconfirmed"&&n.state!=="recovery_pending"||n.ticketId!==void 0&&(typeof n.ticketId!="string"||!/^[0-9a-f-]{36}$/i.test(n.ticketId))||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"||!pr(n.windowsBootIdentity))||n.containment!==void 0&&(typeof n.containment!="object"||n.containment===null||n.containment.kind!=="windows-job"||typeof n.containment.jobName!="string"||!/^(?:Global\\)?KodaXEffect-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(String(n.containment.jobName))||n.containment.sandboxSid!==void 0&&(typeof n.containment.sandboxSid!="string"||!/^S-1-(?:\d+-)+\d+$/i.test(String(n.containment.sandboxSid)))||typeof n.containment.supervisorPid!="number"||!Number.isSafeInteger(n.containment.supervisorPid)||Number(n.containment.supervisorPid)<=0||n.containment.supervisorProcessStartIdentity!==void 0&&typeof n.containment.supervisorProcessStartIdentity!="string"))throw new Error("Windows sandbox ACL poison marker has an invalid owner identity.");return{version:n.version,...n.state==="active"||n.state==="unconfirmed"||n.state==="recovery_pending"?{state:n.state}:{},...typeof n.ticketId=="string"?{ticketId:n.ticketId}:{},...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}:{},...n.containment===void 0?{}:{containment:{kind:"windows-job",jobName:String(n.containment.jobName),...typeof n.containment.sandboxSid=="string"?{sandboxSid:String(n.containment.sandboxSid)}:{},supervisorPid:Number(n.containment.supervisorPid),...typeof n.containment.supervisorProcessStartIdentity=="string"?{supervisorProcessStartIdentity:String(n.containment.supervisorProcessStartIdentity)}:{}}}}}i(zn,"parseWindowsSandboxAclPoisonOwner");function mr(e=K()){return[...new Set([Sn(),wr(e)])].flatMap(n=>{let r;try{r=yt(n)}catch(o){if(un(o,"ENOENT"))return[];throw o}return r.filter(o=>o.endsWith(".json")).map(o=>d.join(n,o))})}i(mr,"listWindowsSandboxAclPoisonFiles");function ue(e=K()){return mr(e).map(t=>{try{let n=Kn(t);if(!n.isFile()||n.isSymbolicLink())throw new Error("Windows sandbox ACL poison marker is not a regular file.");let r=zn(Jn(t,"utf8"));return{file:t,owner:d.basename(t).startsWith("unconfirmed-")?{...r,state:"unconfirmed"}:d.basename(t).startsWith("recovery-")?{...r,state:"recovery_pending"}:r}}catch(n){throw new pn(t,n)}})}i(ue,"readWindowsSandboxAclPoisonOwners");function Ee(){if(process.platform!=="win32")return;if(ot!==void 0)return ot??void 0;let e=String.raw`
|
|
596
|
+
# KodaXWindowsBootIdentity-v1
|
|
597
|
+
$boot = (Get-CimInstance Win32_OperatingSystem -ErrorAction Stop).LastBootUpTime
|
|
598
|
+
[Console]::Out.Write($boot.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture))
|
|
599
|
+
`,t=qn(jr(),["-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 ot=r??null,r}i(Ee,"readWindowsBootIdentity");function Ts(){return Ee()}i(Ts,"readWindowsSandboxBootIdentity");function gr(e,t=Ee()){if(e.find(({windowsBootIdentity:s})=>s===void 0||t===void 0)!==void 0)return new M("A legacy Windows sandbox recovery ticket has no verifiable boot identity. Sandbox admission will retry recovery automatically without blocking non-sandbox work.",{recoveryAction:"automatic-retry"});let r=e[0],o=r?.pid===void 0?"":` (last root PID ${r.pid})`;return new M(`A legacy Windows sandbox recovery ticket${o} from the current Windows boot does not contain safe process-containment proof. Sandbox admission will retry recovery automatically without blocking non-sandbox work.`,{recoveryAction:"automatic-retry"})}i(gr,"persistentWindowsSandboxAclPoisonError");function yr(e,t,n="recovery_pending",r){if(process.platform!=="win32")return;let o=Ee(),s=De(process.pid),l=F(),a=`${n==="active"?"":"recovery-"}owner-${l}.json`,c={version:3,state:n,ticketId:l,...r===void 0?{}:{policyKey:r},holderPid:process.pid,...s===void 0?{}:{holderProcessStartIdentity:s},...e===void 0?{}:{pid:e},...t===void 0?{}:{processStartIdentity:t},...o===void 0?{}:{windowsBootIdentity:o}};return Sr(c,a)}i(yr,"persistWindowsSandboxAclPoisonOwner");function Sr(e,t){let n=JSON.stringify(e),r=i((s,l)=>{$n(s,{recursive:!0,mode:448});let a=d.join(s,t);$n(l,{recursive:!0,mode:448});let c=d.join(l,`owner-${F()}.tmp`);ht(c,n,{flag:"wx",mode:384});try{St(c,a)}catch(f){throw Y(c,{force:!0}),f}return a},"persist"),o=r(Sn(),kt());try{let s=r(wr(),At());X.set(o,s)}catch(s){try{Y(o,{force:!0})}catch(l){throw new AggregateError([s,l],"Windows sandbox owner compatibility marker and primary rollback both failed.")}throw s}return o}i(Sr,"persistWindowsSandboxAclPoisonRecord");function Xo(e){let t=yr(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}i(Xo,"createWindowsSandboxAclOwnerMarker");function We(e){if(e===void 0)return;let t=X.get(e);try{t!==void 0&&Y(t,{force:!0}),Y(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),Ne(n),new Error("Windows sandbox owner poison marker could not be cleared.",{cause:n})}}i(We,"confirmWindowsSandboxAclOwnerStopped");async function Pe(e,t){Ne(t);let n=await Et(e,void 0,void 0,t);if(Ne(n),n!==t)throw n}i(Pe,"retainWindowsSandboxAclOwnerPoison");function hr(e,t,n){if(e===void 0)return yr(t,n,"recovery_pending");let r=X.get(e),o=d.join(d.dirname(e),`recovery-${d.basename(e)}`),s=r===void 0?void 0:d.join(d.dirname(r),`recovery-${d.basename(r)}`);if(!Tn(e)&&Tn(o))return I.delete(e),r!==void 0&&I.delete(r),s!==void 0&&Tn(s)&&X.set(o,s),X.delete(e),o;let a={...zn(Jn(e,"utf8")),version:3,state:"recovery_pending",...t===void 0?{}:{pid:t},...n===void 0?{}:{processStartIdentity:n}},c=i((f,u)=>{let m=d.dirname(u)===Sn()?kt():At();$n(m,{recursive:!0,mode:448});let p=d.join(m,`.recovery-${F()}.tmp`);try{ht(p,JSON.stringify(a),{flag:"wx",mode:384}),St(p,u),f!==u&&Y(f,{force:!0})}catch(g){throw Y(p,{force:!0}),g}},"rewrite");try{return c(e,o),r!==void 0&&s!==void 0&&c(r,s),I.delete(e),r!==void 0&&I.delete(r),s!==void 0&&X.set(o,s),X.delete(e),o}catch(f){try{let u=a.ticketId??F(),m=Sr({...a,ticketId:u},`recovery-owner-${u}.json`);return I.delete(e),r!==void 0&&I.delete(r),X.delete(e),m}catch(u){throw I.delete(e),r!==void 0&&I.delete(r),X.delete(e),new AggregateError([f,u],"Windows sandbox ACL poison write-ahead failed.")}}}i(hr,"writeAheadWindowsSandboxAclOwnerPoison");function br(e,t){if(process.platform!=="win32"||e===void 0)return;let n=X.get(e),r=De(t.supervisorPid),o=yn({srtWin:le().srtWin}).sid;if(o===void 0)throw new Error("Windows sandbox Job binding could not verify the sandbox account SID.");for(let s of[e,n]){if(s===void 0)continue;let l=zn(Jn(s,"utf8")),a=d.dirname(s)===Sn()?kt():At();$n(a,{recursive:!0,mode:448});let c=d.join(a,`.contained-${F()}.tmp`);try{ht(c,JSON.stringify({...l,version:3,state:"active",containment:{kind:"windows-job",jobName:t.jobName,sandboxSid:o,supervisorPid:t.supervisorPid,...r===void 0?{}:{supervisorProcessStartIdentity:r}}}),{flag:"wx",mode:384}),St(c,s)}catch(f){throw Y(c,{force:!0}),f}}}i(br,"bindWindowsSandboxAclOwnerToJob");async function Et(e,t,n,r){if(process.platform!=="win32")return r;let o;try{return o=hr(e,t,n),await z(te(),async()=>{},ne),r}catch(s){return new AggregateError([r,s],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.")}}i(Et,"transitionWindowsSandboxAclOwnerToPoison");function Uo(e,t){return I.has(e)}i(Uo,"isVerifiedActiveWindowsSandboxAclOwner");function hn(e){if(e.holderPid===void 0||e.holderProcessStartIdentity===void 0)return"stale";let t=De(e.holderPid);if(t!==void 0)return t===e.holderProcessStartIdentity?"live":"stale";try{return process.kill(e.holderPid,0),"unknown"}catch(n){return un(n,"ESRCH")?"stale":"unknown"}}i(hn,"windowsSandboxAclOwnerLiveness");async function Rt(e){try{let t=le(),n=yn({srtWin:t.srtWin}),r=e??n.sid;return r===void 0||n.sid!==void 0&&n.sid!==r?!1:!await Xt(r,{executable:t.srtWin.exe,prependArgs:t.srtWin.prependArgs})}catch(t){return W({source:"runtime:sandbox-acl-recovery",level:"warn",message:"Windows sandbox-user process inspection failed; ACL recovery remains fenced for automatic retry.",detail:t}),!1}}i(Rt,"windowsSandboxSidIsIdle");async function Ho(e){return e.length>0&&e.every(({owner:t})=>t.containment===void 0&&hn(t)==="stale")&&await Rt()}i(Ho,"canAutomaticallyRecoverUncontainedWindowsSandboxAclOwners");function Pt(e,t,n){return t.state!=="active"?!1:I.has(e)?n===void 0||t.policyKey===n:n!==void 0&&t.policyKey===n&&hn(t)==="live"}i(Pt,"isCompatibleWindowsSandboxAclOwner");function Xe(e){let t=ue().filter(({file:n,owner:r})=>!Pt(n,r,e));if(t.length!==0)throw gr(t.map(({owner:n})=>n))}i(Xe,"assertNoPersistentWindowsSandboxAclPoison");async function vr(e,t,n,r){let o=new Error(n);if(process.platform==="win32"){let s=await Et(r,e,t,o);return Ne(s),s instanceof Error?s:o}return Ne(o),o}i(vr,"recordUnconfirmedWindowsSandboxOwner");function ct(e){return process.platform==="win32"?`${e} process-tree termination was not confirmed; automatic Job recovery is pending.`:`${e} process-tree termination was not confirmed; stop the retained process tree before retrying.`}i(ct,"unconfirmedSandboxProcessTreeMessage");async function ke(e=3e4){let t=le(),n=await Tr({command:t.srtWin.exe,args:[...t.srtWin.prependArgs,"acl","recover","--json"],env:fe(),cwd:t.directory,controlPipe:!1},await bn()),r,o,s=!1,l;try{if(r=Gn(n.command,[...n.args],{cwd:t.directory,env:n.env,shell:!1,stdio:["pipe","pipe","pipe"],windowsHide:!0}),Qe(r),r.pid===void 0)throw new Error("Windows ACL recovery gate did not expose a PID.");let u=Wt(r,void 0,Math.max(1,Math.min(3e4,e)),1024*1024,void 0,!0);u.catch(()=>{}),o=await en(r.pid),s=!0,await Tt(r,!0),l=await u,await o.drained}catch(u){let m=[u];if(r!==void 0)try{s||await $t(r),o!==void 0?(await Se(o.jobName),await o.drained):await ie(r)}catch(p){m.push(p)}throw m.length===1?u:new AggregateError(m,"Windows sandbox ACL recovery helper cleanup failed.")}finally{await L(n.gateFile,{force:!0})}let a=l.stderr.trim(),c;try{c=JSON.parse(l.stdout.trim())}catch(u){throw new Error(`Windows sandbox ACL recovery failed with unparseable output (exit ${String(l.exitCode)}): ${a||"(empty stderr)"}.`,{cause:u})}let f=typeof c=="object"&&c!==null?c:void 0;if(l.exitCode!==0||typeof f?.deadBrokers!="number"||!Number.isSafeInteger(f.deadBrokers)||f.deadBrokers<0||typeof f.acesRevoked!="number"||!Number.isSafeInteger(f.acesRevoked)||f.acesRevoked<0)throw new Error(`Windows sandbox ACL recovery failed (exit ${String(l.exitCode)}): ${a||"(empty stderr)"}.`);ln=!0}i(ke,"recoverWindowsSandboxAcls");async function $s(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 z(te(),async()=>{let s=ue(e),l=s.filter(({owner:c})=>c.holderPid===t.pid&&c.holderProcessStartIdentity===t.processStartIdentity&&c.windowsBootIdentity===n);if(l.length!==s.length)throw new M("Windows sandbox ACL recovery found a foreign or unverifiable owner marker.");if(l.length===0)return 0;await kr(fn(),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 await ke(a),l.length},Math.max(1,Math.min(ne,r)))}i($s,"recoverWindowsSandboxAclsForRuntimeOwner");async function _s(e,t=7e4){if(process.platform!=="win32")return 0;let n=Date.now()+t;return z(te(),async()=>{let r=ue(e);if(r.length===0)return 0;xr(r),await kr(fn(),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 await ke(o),r.length},Math.max(1,Math.min(ne,t)))}i(_s,"recoverPreviousBootWindowsSandboxAcls");function xr(e){let t=Ee();if(t===void 0||!pr(t))throw new M("Windows sandbox ACL recovery could not verify the current boot identity.",{recoveryAction:"automatic-retry"});if(e.some(({owner:n})=>n.windowsBootIdentity===void 0))throw new M("Windows sandbox ACL recovery found an unverifiable owner marker.",{recoveryAction:"automatic-retry"});if(e.some(({owner:n})=>n.windowsBootIdentity===t))throw new M("Windows sandbox ACL recovery found a current-boot owner marker.",{recoveryAction:"automatic-retry"})}i(xr,"assertPreviousBootWindowsSandboxAclMarkers");async function kr(e,t){let n,r=new Promise((o,s)=>{n=setTimeout(()=>s(new Error("Windows sandbox runner preparation timed out.")),t)});try{return await Promise.race([e,r])}finally{n!==void 0&&clearTimeout(n)}}i(kr,"waitForWindowsSandboxRunnerPreparation");async function Os(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 z(te(),async()=>{let o=ue(e),s=o.filter(({owner:l})=>l.holderPid===t.pid&&l.holderProcessStartIdentity===t.processStartIdentity&&l.windowsBootIdentity===n);if(s.length!==o.length)throw new M("Windows sandbox marker cleanup found a foreign or unverifiable owner marker.");for(let l of s)Y(l.file,{force:!0});return s.length},Math.max(1,Math.min(ne,r)))}i(Os,"clearWindowsSandboxAclMarkersForRuntimeOwner");async function Ns(e,t=4e4){return process.platform!=="win32"?0:z(te(),async()=>{let n=ue(e);if(n.length===0)return 0;xr(n);for(let r of n)Y(r.file,{force:!0});return n.length},Math.max(1,Math.min(ne,t)))}i(Ns,"clearPreviousBootWindowsSandboxAclMarkers");function zo(e){return e instanceof Ut}i(zo,"isWindowsSandboxAclRecoveryLockTimeout");var Nn=class extends M{static{i(this,"ForeignWindowsSandboxAclOwnerContentionError")}constructor(t){super("Another Windows sandbox owner is active for the shared sandbox account; recovery is waiting and will retry automatically; non-sandbox work remains available.",{cause:t,recoveryAction:"automatic-retry"}),this.name="ForeignWindowsSandboxAclOwnerContentionError"}},In=class extends M{static{i(this,"StaleWindowsSandboxAclOwnerContentionError")}constructor(t){super(t.message,{cause:t}),this.name="StaleWindowsSandboxAclOwnerContentionError"}};function lt(e){if(zo(e)||e instanceof Nn||e instanceof In){Ft();return}Ne(e)}i(lt,"recordWindowsSandboxAclAdmissionFailure");function wn(e,t=Ee()){let n=gr(e.map(({owner:r})=>r),t);return e.every(({owner:r})=>r.state==="active")?e.some(({owner:r})=>hn(r)==="stale")?new In(n):new Nn(n):n}i(wn,"windowsSandboxAclPoisonSnapshotError");async function Vo(){let e=ue();if(e.length===0)return;let t=Ee();if(t!==void 0&&e.every(({owner:r})=>r.windowsBootIdentity!==void 0&&r.windowsBootIdentity!==t)){await ke();for(let r of e)Y(r.file,{force:!0});Xe();return}return e.every(({owner:r})=>hn(r)!=="stale")?new M("Windows sandbox setup cannot run while a sandbox owner is active for the shared Windows sandbox account; recovery is waiting and will retry automatically; non-sandbox work remains available.",{recoveryAction:"automatic-retry"}):wn(e,t)}i(Vo,"windowsSandboxAclSetupBlockWithLock");function Qt(e,t){return{...e,ready:!1,diagnostics:[...e.diagnostics.filter(n=>!n.startsWith(Oe)),`${Oe} ${t.message}`]}}i(Qt,"withWindowsSandboxAclSetupBlock");function Ar(e,t){let n=new Map;for(let r of e){let o=t(r);o!==void 0&&n.set(o,[...n.get(o)??[],r])}return n}i(Ar,"groupWindowsSandboxAclPoisonEntries");async function Yo(e,t){let n=e.filter(({owner:a})=>a.state==="active"&&hn(a)!=="stale"&&(a.containment===void 0||!xe.has(a.containment.jobName)));if(n.length>0)throw wn(n,t);if(t!==void 0&&e.every(({owner:a})=>a.windowsBootIdentity!==void 0&&a.windowsBootIdentity!==t))return;let o=Ar(e,a=>a.owner.ticketId??a.file),s=await Ho(e);if(![...o.values()].every(a=>a.some(({owner:c})=>c.containment!==void 0)||a.every(({owner:c})=>c.version===3&&c.state==="active"&&c.pid===void 0)||s))throw wn(e,t)}i(Yo,"assertWindowsSandboxAclPoisonIsRecoverable");async function Zo(e){for(let[t,n]of e){if(await Se(t)!=="not_found"||t.startsWith("Global\\"))continue;let o=new Set(n.flatMap(({owner:s})=>s.containment?.sandboxSid===void 0?[]:[s.containment.sandboxSid]));if(!(o.size===1&&await Rt([...o][0])))throw new M("Windows sandbox Job recovery is waiting for exact process-drain proof; recovery will retry automatically and non-sandbox work remains available.",{recoveryAction:"automatic-retry"})}}i(Zo,"drainWindowsSandboxAclRecoveryJobs");async function Qo(e,t,n,r){let o=new Set(t.map(({file:s})=>s));e.some(({file:s})=>!o.has(s))||await ke();for(let s of n.keys()){let l=xe.get(s);l!==void 0&&(await tn(l),xe.delete(s))}for(let s of t)Y(s.file,{force:!0});Mn(),ln=!0,Xe(r)}i(Qo,"completeWindowsSandboxAclRecovery");async function Er(e){let t=ue(),n=t.filter(({file:r,owner:o})=>!Pt(r,o,e));if(n.length>0){await Yo(n,Ee());let r=Ar(n,o=>o.owner.containment?.jobName);await Zo(r),await Qo(t,n,r,e);return}if(t.length>0||ln){Mn();return}await ke(),Mn(),ln=!0,Xe(e)}i(Er,"ensureWindowsSandboxAclRecoveryWithLock");async function er(e){await z(te(),async()=>{try{await Er(e)}catch(t){if(!(t instanceof pn)||!await Rt())throw t;await ke();for(let n of mr())Y(n,{force:!0});Mn(),ln=!0,Xe(e)}},ne)}i(er,"recoverUnreadableWindowsSandboxAclTicketsWithFence");async function Ue(e,t=!1){if(process.platform==="win32")try{await z(te(),async()=>Er(e),ne)}catch(n){if(n instanceof pn)try{if(t){await er(e);return}let r=await nn();try{await er(e)}finally{await r()}return}catch(r){throw lt(r),r}throw lt(n),n}}i(Ue,"ensureWindowsSandboxAclRecovery");async function Rr(e){if(process.platform!=="win32")return;await Ue(e,!0);let t;try{return await z(te(),async()=>(Xe(e),t=Xo(e),t),ne)}catch(n){if(t===void 0)throw lt(n),n;try{We(t)}catch(r){throw new AggregateError([n,r],"Windows sandbox owner admission and marker cleanup both failed.")}throw n}}i(Rr,"admitWindowsSandboxAclOwner");async function an(e){if(process.platform!=="win32")return;let t;try{if(e===void 0||!I.has(e))return;if(t=zn(Jn(e,"utf8")).policyKey,t!==void 0){await z(te(),async()=>{let r=X.get(e),o=new Set([e,r].filter(a=>a!==void 0)),s=ue().filter(({file:a})=>!o.has(a)),l=s.filter(({file:a,owner:c})=>!Pt(a,c,t));if(l.length>0)throw wn(l);if(s.length>0){We(e);return}await ke(),We(e)},ne);return}let n=hr(e,void 0,void 0);await z(te(),async()=>{await ke(),We(n),e!==n&&We(e)},ne)}catch(n){let r=t===void 0?n:await Et(e,void 0,void 0,n);throw Ne(r),r}}i(an,"confirmWindowsSandboxAclRecovery");function it(){Ce!==void 0&&(cr({sandboxUserSid:Ce.sandboxUserSid,holderPid:process.pid,srtWin:Ce.runner.srtWin}),Ce=void 0)}i(it,"releasePreparedWindowsRunnerGrant");function ei(e,t){if(!(Ce?.runner.path===e.path&&Ce.sandboxUserSid===t)){process.removeListener("exit",it),it();try{Po({read:[e.directory,e.path],write:[],sandboxUserSid:t,holderPid:process.pid,srtWin:e.srtWin})}catch(n){try{cr({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}Ce={runner:e,sandboxUserSid:t},process.once("exit",it)}}i(ei,"retainPreparedWindowsRunnerGrant");async function ni(){let[e,t]=Eo;for(let n=0;n<5;n+=1){let r=ko();r.listen(0,"127.0.0.1"),await zt(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 s=zt(r,"close");r.close(),await s}throw new Error(`[wfp_probe_bind_failed] Could not bind a loopback listener outside the Windows sandbox proxy range [${e},${t}].`)}i(ni,"bindWindowsWfpProbe");function nr(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"}i(nr,"windowsRunnerFailureCode");function ti(e){return un(e,"ETIMEDOUT")?"wfp_probe_timeout":un(e,"EACCES","EPERM")?"runner_launch_access_denied":"runner_spawn_failed"}i(ti,"windowsRunnerSpawnFailureCode");async function ri(e){let{server:t,target:n}=await ni();try{let r=qn(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(`[${ti(r.error)}] Windows sandbox runner failed to start: ${r.error.message}`);let s;try{s=JSON.parse((r.stdout??"").trim())}catch{let l=r.status===null?"wfp_probe_timeout":nr(o);throw new Error(`[${l}] 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(s.target??n)} succeeded. Run "kodax sandbox setup" to reinstall the Windows network policy.`);if(r.status!==0||s.egress_probe!=="blocked")throw new Error(`[${nr(o)}] Windows sandbox WFP probe to ${String(s.target??n)} was ${String(s.egress_probe)} (exit ${String(r.status)}): ${o||"(empty stderr)"}.`)}finally{t.close()}}i(ri,"verifyPreparedWindowsWfp");function Pr(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}i(Pr,"windowsSandboxAccountDiagnostics");function oi(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}i(oi,"parseBrokerObservation");function Vn(){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}i(Vn,"sandboxJavaScriptCommand");async function ce(e={}){if(e.refresh||Be===void 0||Date.now()>=Rn){let t=ii();Be=t,Rn=Number.POSITIVE_INFINITY,t.then(n=>{Be===t&&(Rn=n.ready?Number.POSITIVE_INFINITY:Date.now()+Ko)},()=>{Be===t&&(Be=void 0,Rn=0)})}return Be}i(ce,"doctorSandboxRuntime");async function ii(){let e=[],t=!1;tt.isSupportedPlatform()||e.push(`Unsupported platform: ${process.platform}.`);let n=process.platform==="win32"?{errors:[],warnings:[]}:tt.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 Je(vt.resolve("@anthropic-ai/sandbox-runtime/package.json"),"utf8"));a.version!==$e&&(r=!0,e.push(`ASRT package version mismatch: expected ${$e}, found ${String(a.version)}.`))}catch(a){r=!0,e.push(`ASRT package provenance check failed: ${be(a)}`)}let o=Vn(),s=Ze({args:["--version"],env:fe(),isElectron:o===process.execPath&&process.versions.electron!==void 0}),l=qn(o,s.args,{env:s.env,shell:!1,encoding:"utf8",windowsHide:!0,timeout:5e3});if(l.status!==0){r=!0;let a=l.error?.message??(l.stderr.trim()||o);e.push(`JavaScript Skill interpreter is unavailable: ${a}.`)}if(process.platform==="win32"){try{let a=await fn(),c=yn({srtWin:a.srtWin}),f=Pr(c);if(f.length>0||!c.sid)r=!0,e.push(...f);else{ei(a,c.sid);let u=Mr(Ln(),c.sid,c.groupSid,!1,"read");u.length>0&&(r=!0,e.push(`[acl_guards_missing] ${u.length} persistent Windows sandbox ACL guard(s) are missing. Run "kodax sandbox setup" once to install them outside the startup path.`)),await ri(a)}}catch(a){r=!0,e.push(be(a))}try{let a=ue().filter(({file:c,owner:f})=>!Uo(c,f));if(a.length>0){let c=Ee();c!==void 0&&a.every(({owner:u})=>u.windowsBootIdentity!==void 0&&u.windowsBootIdentity!==c)||(t=!0,e.push(`${Oe} `+wn(a,c).message))}}catch(a){t=!0,e.push(`${Oe} ${be(a)}`)}}return{ready:tt.isSupportedPlatform()&&!r&&!t,platform:process.platform,version:$e,diagnostics:e,setupRequired:r}}i(ii,"inspectSandboxRuntime");async function si(){let e=await ce({refresh:!0});try{let r=await Vo();if(r!==void 0)return Qt(e,r)}catch(r){let o=r instanceof Error?r:new Error(String(r));return Qt(e,o)}if(e.ready||Un(e)||!e.setupRequired)return e;let t=!1;try{let r=await fn(),o=yn({srtWin:r.srtWin});t=Pr(o).length===0&&o.sid!==void 0}catch{t=!1}if(t){ft(Ln(),"read");let r=await ce({refresh:!0});if(r.ready)return r}if(Co().cancelled)throw new Error("Sandbox setup was cancelled.");return await fn(),ft(Ln(),"read"),ce({refresh:!0})}i(si,"setupWindowsSandboxRuntimeWithLock");async function ai(){return process.platform!=="win32"?ce({refresh:!0}):z(te(),si,ne)}i(ai,"setupSandboxRuntime");function Me(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(Oe));return t!==void 0?[t.slice(Oe.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}.`]}i(Me,"sandboxSetupGuidance");async function Is(e={}){let t=await ce({refresh:!0});if(t.ready)return{status:"ready",attempted:!1,doctor:t,guidance:Me(t)};if(Un(t))return{status:"unavailable",attempted:!1,doctor:t,guidance:Me(t)};if(!t.setupRequired)return{status:"unavailable",attempted:!1,doctor:t,guidance:Me(t)};if(t.platform!=="win32"||e.allowElevation===!1)return{status:"unavailable",attempted:!1,doctor:t,guidance:Me(t)};try{let n=await ai();return{status:n.ready?"ready":"unavailable",attempted:!0,doctor:n,guidance:Me(n)}}catch(n){let r=await ce({refresh:!0}),o=be(n);return{status:/cancelled/i.test(o)?"cancelled":"unavailable",attempted:!0,doctor:r,guidance:Me(r),error:o}}}i(Is,"prepareSandboxRuntimeForSetup");function Ae(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}i(Ae,"canonicalRelative");function _(e,t){let n=d.relative(e,t);return n===""||!n.startsWith("..")&&!d.isAbsolute(n)}i(_,"isInside");function Cr(e){let t=e.split(d.sep).map(n=>n.toLowerCase());return t.some(n=>_o.has(n))||t.some(n=>Oo.has(n)||n.startsWith(".env."))}i(Cr,"isSensitiveRelative");async function di(e,t){await V(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 _e(d.join(t,"SKILL.md"),await Je(e.skillFilePath),{mode:384});for(let{folder:r,file:o}of n){let s=Ae(o.relativePath,`Skill ${e.name} support file`),l=d.join(t,r,...s.split("/"));await V(d.dirname(l),{recursive:!0,mode:448}),await _e(l,await Je(o.path),{mode:384})}}i(di,"copySkillSnapshot");async function ci(e,t){let n=new Map;for(let[r,o]of Object.entries(e.admissions)){let s=await e.registry.loadFull(r),l=new Map((s.scripts??[]).map(c=>[`scripts/${Ae(c.relativePath,`Skill ${r} script`)}`,c])),a=d.join(t,r.replace(/[^A-Za-z0-9._-]/g,"_"));await di(s,a);for(let c of o){let f=Ae(c,`toolPolicy.skillScripts.${r}`);if(!l.has(f))throw new Error(`Skill "${r}" has no script "${f}".`);n.set(`${r}\0${f}`,{skill:r,relativePath:f,snapshotPath:d.join(a,...f.split("/"))})}}return n}i(ci,"snapshotAdmissions");function li(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}})}i(li,"networkEndpoints");function fe(){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 Ct(t)}i(fe,"sanitizedEnvironment");function Ct(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())}i(Ct,"normalizedSandboxEnvironment");function Wr(e,t){return Ct({...e,...t})}i(Wr,"mergeSandboxEnvironment");function ui(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>"}.`)}i(ui,"interpreterFor");var tr=250,fi=1500;async function Wt(e,t,n=Xn,r=bt,o,s=!1){let l=[],a=[],c=e.pid===void 0?void 0:De(e.pid),f=0,u,m=i(()=>{},"reportStopRequested"),p,g,w=new Promise(A=>{m=A}),x=i(A=>{if(u!==void 0)return;u=A,m();let v=!1,T,$;p=new Promise((C,G)=>{T=C,$=G}),p.catch(()=>{});let R=i(async C=>{let G=s?new Error(ct("Sandbox broker")):await vr(e.pid,c,ct("Sandbox broker"),o);return C===void 0?G:new AggregateError([G,C],"Sandbox broker termination failed and its process tree may still be alive.")},"unconfirmedTermination"),O=i(C=>{v||(v=!0,g!==void 0&&clearTimeout(g),C===void 0?T():$(C))},"finish");g=setTimeout(()=>{try{e.kill("SIGKILL"),R().then(O)}catch(C){R(C).then(O)}},fi),ie(e,{expectedProcessStartIdentity:c,forceMs:tr,taskkillMs:tr}).then(async C=>O(C.status==="unknown"?await R():void 0),async C=>O(await R(C)))},"requestStop"),b=i((A,v)=>{f+=v.byteLength,f>r?x(new Error(`Sandboxed command output exceeded ${r} bytes.`)):A.push(v)},"append");e.stdout?.on("data",A=>{b(l,A)}),e.stderr?.on("data",A=>{b(a,A)});let y=setTimeout(()=>{x(new Error(`Sandboxed command exceeded its ${n} ms timeout.`))},n),P=i(()=>{let A=t?.reason;x(A instanceof Error?A:new Error("Sandboxed command was cancelled."))},"abort");t?.addEventListener("abort",P,{once:!0}),t?.aborted&&P();try{let A=new Promise((T,$)=>{e.once("error",$),e.stdin?.once("error",$),e.once("close",R=>T(R??1))}),v=await Promise.race([A,w.then(()=>1)]);if(u!==void 0)throw await p,u;return{exitCode:v,stdout:Buffer.concat(l).toString("utf8"),stderr:Buffer.concat(a).toString("utf8")}}finally{clearTimeout(y),g!==void 0&&clearTimeout(g),t?.removeEventListener("abort",P)}}i(Wt,"collectProcess");async function Tr(e,t){let n=d.join(t,`kodax-asrt-gate-${process.pid}-${F()}.json`);return await _e(n,JSON.stringify(e),{mode:384}),{...Kt({args:["-e",qo,n],env:fe(),isElectron:process.versions.electron!==void 0}),gateFile:n}}i(Tr,"prepareWindowsGatedLaunch");async function $r(e,t,n=!1){let r=Ze({args:e,env:fe(),isElectron:process.versions.electron!==void 0});return process.platform!=="win32"?{command:process.execPath,...r}:Tr({command:process.execPath,args:r.args,env:r.env,cwd:le().directory,controlPipe:n},t)}i($r,"prepareStandaloneBrokerLaunch");async function pi(e,t){if(t.pid===void 0||t.stdin===null)throw new Error("Standalone sandbox broker gate did not expose a PID and stdin.");return await e.bindEffectProcess(t.pid,!1),en(t.pid)}i(pi,"containStandaloneBrokerFence");function Tt(e,t){let n=e.stdin;return n===null?Promise.reject(new Error("Sandbox gate stdin is unavailable.")):new Promise((r,o)=>{let s=!1,l=i(()=>n.removeListener("error",c),"cleanup"),a=i(f=>{s||(s=!0,l(),f?o(f):r())},"settle"),c=i(f=>a(f),"onError");n.once("error",c),t?n.end(`go
|
|
600
|
+
`,a):n.write(`go
|
|
601
|
+
`,a)})}i(Tt,"writeSandboxGate");function $t(e){let t=e.stdin;return t===null||t.destroyed||t.writableEnded?Promise.resolve():new Promise((n,r)=>{let o=!1,s=i(()=>t.removeListener("error",a),"cleanup"),l=i(c=>{o||(o=!0,s(),c?r(c):n())},"settle"),a=i(c=>l(c),"onError");t.once("error",a),t.end(l)})}i($t,"closeSandboxGate");async function wi(e){let{child:t,effectJob:n,targetStartAttempted:r,terminateFirst:o}=e;if(!r){await $t(t).catch(()=>{}),n!==void 0?(await Se(n.jobName),await n.drained):await ie(t);return}if(o){if(n!==void 0)await Se(n.jobName);else if((await ie(t)).status==="unknown")throw new Error("Standalone sandbox broker process tree drain was not confirmed.")}if(n!==void 0)await n.drained;else if(!o&&(await ie(t)).status==="unknown")throw new Error("Standalone sandbox broker process tree drain was not confirmed.")}i(wi,"proveStandaloneBrokerDrained");function _t(e){W({source:"sandbox:standalone-broker",level:"warn",message:"Standalone sandbox broker cleanup remains durably fenced.",detail:e})}i(_t,"reportDeferredStandaloneBrokerSettlement");function st(e){if(e===null)return;let t=Reflect.get(e,"unref");typeof t=="function"&&t.call(e)}i(st,"unrefStandaloneBrokerResource");function _r(e){e.effectJob?.unref?.(),e.child.unref(),st(e.child.stdin),st(e.child.stdout),st(e.child.stderr)}i(_r,"detachDeferredStandaloneBroker");function mi(e){_r(e),Or(yi(e))}i(mi,"trackDeferredStandaloneBrokerSettlement");function gi(e){_r(e),Or(Ir(e))}i(gi,"trackDeferredStandaloneFenceRelease");function Or(e){qe.add(e),e.then(()=>qe.delete(e),t=>{qe.delete(e),_t(t)})}i(Or,"trackPendingStandaloneBrokerSettlement");async function Nr(e){try{await wi(e),e.targetStartAttempted?await an(e.marker):We(e.marker)}catch(t){throw await Pe(e.marker,t),t}}i(Nr,"confirmStandaloneBrokerOwnershipRecovered");async function Ir(e){let t=250;for(;;)try{await tn(e.fence),e.effectJob!==void 0&&xe.delete(e.effectJob.jobName);return}catch(n){_t(n),await Promise.race([e.fence.released,hi(t)]),t=Math.min(t*2,5e3)}}i(Ir,"releaseStandaloneBrokerFenceUntilRecovered");async function yi(e){await Nr(e),await Ir(e)}i(yi,"settleStandaloneBrokerOwnershipUntilRecovered");async function Si(e){await Nr(e);try{await tn(e.fence),e.effectJob!==void 0&&xe.delete(e.effectJob.jobName)}catch(t){_t(t),gi(e)}}i(Si,"settleStandaloneBrokerOwnershipInForeground");function hi(e){return new Promise(t=>{setTimeout(t,e).unref()})}i(hi,"waitForUnreferencedRetry");async function Lr(e,t,n=Xn,r=bt){let o=process.platform==="win32"?await bn():ee.tmpdir(),s=d.join(o,`kodax-asrt-${process.pid}-${F()}.json`),l=process.platform==="win32"?Lt(e.config):{...e.config,filesystem:{...e.config.filesystem,denyRead:[...e.config.filesystem.denyRead,s]}},a={...e,bootstrapCommand:e.bootstrapCommand??Vn(),config:l};await _e(s,JSON.stringify(a),{mode:384});let c,f,u,m,p,g,w=!1,x=!1;try{if(process.platform==="win32"){await zr();let v=await Bt();if(v.length===1)throw v[0];if(v.length>1)throw new AggregateError(v,"Cached workspace sandbox reset was not confirmed before standalone execution.");await Ue(),u=await nn()}let b=process.env.KODAX_BUNDLED==="true"?["__asrt-broker",s]:["--input-type=module","-e",fr,lr,s],y=await $r(b,o);g=y.gateFile,f=await Rr(),m=Gn(y.command,[...y.args],{cwd:process.platform==="win32"?le().directory:void 0,env:y.env,shell:!1,stdio:process.platform==="win32"?["pipe","pipe","pipe"]:["ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),Qe(m);let P=Wt(m,t,n,r,f,u!==void 0);P.catch(()=>{}),u!==void 0&&(p=await pi(u,m),br(f,p),xe.set(p.jobName,u),await u.bindEffectProcess(p.supervisorPid,!0),w=!0,await Tt(m,!0));let A=await P;if(u!==void 0){let v=u;u=void 0,x=!0,await Si({child:m,effectJob:p,fence:v,marker:f,targetStartAttempted:w,terminateFirst:!1})}return A}catch(b){if(c=b,u!==void 0&&m!==void 0){let y=u;u=void 0,x=!0,mi({child:m,effectJob:p,fence:y,marker:f,targetStartAttempted:w,terminateFirst:!0})}throw b}finally{let b=[];try{await L(s,{force:!0})}catch(y){b.push(y)}if(g!==void 0)try{await L(g,{force:!0})}catch(y){b.push(y)}if(!x)try{await an(f)}catch(y){b.push(y)}if(u!==void 0)try{await u()}catch(y){b.push(y)}if(b.length>0)throw c!==void 0&&b.unshift(c),b.length===1?b[0]:new AggregateError(b,"Sandbox broker cleanup was not confirmed.")}}i(Lr,"runBrokerResult");async function bi(e,t){let n=await Lr(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}i(bi,"runBroker");async function vi(e,t){let n=await cn(e),r=d.resolve(e,Ae(t,"Skill script input")),o=await cn(r);if(!_(n,o)||Cr(d.relative(n,o)))throw new Error("Skill script input is outside the permitted workspace surface.");if(!(await _n(o)).isFile())throw new Error("Skill script inputs must be files.");return o}i(vi,"workspaceSource");async function xi(e,t){let n=await cn(e),r=d.resolve(e,Ae(t,"Skill script output target"));if(!_(d.resolve(e),r)||Cr(d.relative(d.resolve(e),r)))throw new Error("Skill script output target is outside the permitted workspace surface.");if(await V(d.dirname(r),{recursive:!0}),!_(n,await cn(d.dirname(r))))throw new Error("Skill script output target escapes through a symlink.");try{throw await _n(r),new Error("Skill script output target already exists.")}catch(o){if(o.code!=="ENOENT")throw o}return r}i(xi,"workspaceTarget");async function ki(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 s=await vi(e,o.path),l=Ae(o.as??d.basename(s),"Skill script staged input"),a=d.resolve(t,"inputs",...l.split("/"));if(!_(d.join(t,"inputs"),a))throw new Error("Skill script staged input escapes staging.");await V(d.dirname(a),{recursive:!0,mode:448}),await ar(s,a)}}i(ki,"stageInputFiles");async function Ai(e,t,n,r,o){if(n.outputs.length>0&&r!=="write")throw new Error("Skill script outputs require workspace write access.");let s=[];for(let l of n.outputs){let a=Ae(l.path,"Skill script staged output"),c=d.resolve(t,"outputs",...a.split("/")),f=await cn(c);if(!_(d.join(t,"outputs"),f)||(await ho(c)).isSymbolicLink()||!(await _n(c)).isFile())throw new Error(`Skill script did not produce output "${a}".`);let u=await xi(e,l.target);if(o!==void 0&&Fr(e,!0)+(await _n(c)).size>o)throw new Error("Skill script outputs would exceed the remote workspace byte quota.");await ar(c,u,go.COPYFILE_EXCL),s.push(d.relative(e,u))}return s}i(Ai,"promoteOutputs");function Fr(e,t=!1){let n=0;for(let r of yt(e,{withFileTypes:!0})){if(t&&r.name===".kodax-a2a-script"||r.isSymbolicLink())continue;let o=d.join(e,r.name);r.isDirectory()?n+=Fr(o):r.isFile()&&(n+=Ke(o).size)}return n}i(Fr,"directorySize");function Ot(e){if(process.platform!=="win32")return e;let t=le();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])]}}}i(Ot,"withPreparedWindowsRunner");function Ei(e,t,n,r){let o=process.platform==="win32"?process.env.USERPROFILE??ee.homedir():ee.homedir(),s=process.platform==="win32"?Ln():[o],l=i(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:s,allowRead:[e,t,...new Set([...l(process.execPath),...l(r)])],allowWrite:[e],denyWrite:s}})}i(Ei,"sandboxConfig");function Ri(){let e=[ee.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)))]}i(Ri,"canonicalTempDirectories");function Dr(e){return[d.join(e,".git","config"),d.join(e,".git","hooks")].filter(n=>{try{return Ke(n),!0}catch{return!1}})}i(Dr,"existingWorkspaceDenyWrites");function Nt(e,t,n){let r=No.map(s=>d.resolve(e,s)).filter(s=>d.relative(s,t)!==""),o=process.platform==="win32"?[d.resolve(t),Hn()]:[d.resolve(n),...Io.map(s=>d.resolve(t,s))];return[...new Set([...o,...r])]}i(Nt,"workspaceShellSensitiveReadDenies");function It(e){let t=[...new Set(e.map(r=>d.resolve(r)))].filter(r=>Ke(r,{throwIfNoEntry:!1})!==void 0).sort((r,o)=>r.length-o.length),n=[];for(let r of t)n.some(o=>_(o,r))||n.push(r);return n}i(It,"existingMinimalWindowsAclGuardRoots");function Br(e){return d.resolve(e).toLowerCase()}i(Br,"windowsAclGuardKey");function ut(e,t){let n=Br(e),r=t==="read"?dt:new Set([...dt,...ur]);for(let o of r)if(n===o||n.startsWith(o.endsWith(d.sep)?o:`${o}${d.sep}`))return!0;return!1}i(ut,"windowsAclGuardCovers");function Ln(){let e=d.resolve(process.env.USERPROFILE??ee.homedir()),t=d.resolve(K());return It(Nt(e,t,d.join(t,"sandbox-runtime")))}i(Ln,"windowsPersistentAclGuardRoots");function Mr(e,t,n,r,o){let s=It(e);if(s.length===0)return[];let l=JSON.stringify({sid:t,tokenSids:[t,n,"S-1-1-0","S-1-5-11","S-1-5-32-545"].filter(u=>u!==void 0),install:r,paths:s.map(u=>({path:u,directory:Ke(u).isDirectory(),mode:o}))}),a=jr(),c=qn(a,["-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(Lo,"utf16le").toString("base64")],{input:l,encoding:"utf8",timeout:r&&o==="read"?15*6e4:r?15e3:5e3,windowsHide:!0});if(c.error||c.status!==0){let u=(c.error?.message||c.stderr||c.stdout||"no diagnostics").trim().slice(-4096);throw new Error(`Windows sandbox ACL guard failed: ${u}`)}let f;try{let u=JSON.parse(c.stdout.trim());f=Array.isArray(u.missing)?u.missing.filter(m=>typeof m=="string"):[]}catch(u){throw new Error(`Windows sandbox ACL guard returned invalid output: ${be(u)}`)}if(f.length===0){let u=o==="read"?dt:ur;for(let m of s)u.add(Br(m))}return f}i(Mr,"runWindowsAclGuard");function jr(){let e=process.env.ProgramFiles??"C:\\Program Files",t=d.join(e,"PowerShell","7","pwsh.exe");return Tn(t)?t:d.join(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe")}i(jr,"windowsAclPowerShellExecutable");function ft(e,t){if(process.platform!=="win32"||e.length===0)return;let n=e.filter(l=>!ut(l,t));if(n.length===0)return;let r=le(),o=yn({srtWin:r.srtWin});if(!o.sid)throw new Error("Windows sandbox account SID is unavailable for ACL guards.");if(Mr(n,o.sid,o.groupSid,!0,t).length>0)throw new Error("Windows sandbox ACL guards were not installed completely.")}i(ft,"installWindowsAclGuards");function Lt(e){return process.platform!=="win32"?e:{...e,filesystem:{...e.filesystem,denyRead:e.filesystem.denyRead.filter(t=>!ut(t,"read")),denyWrite:e.filesystem.denyWrite?.filter(t=>!ut(t,"write"))}}}i(Lt,"withoutWindowsAsrtDenyPropagation");function Pi(e,t){let n;try{n=j.native(t)}catch{return[]}let r=[];for(let o of e){let s;try{s=j.native(o)}catch{continue}if(!_(s,n))r.push(o);else if(s!==n){let l=d.relative(s,n).split(d.sep),a=s;try{for(let c of l){for(let f of yt(a,{withFileTypes:!0}))f.name!==c&&r.push(d.join(a,f.name));a=d.join(a,c)}}catch{}}}return process.platform!=="win32"&&r.push(t),[...new Set(r)]}i(Pi,"workspaceShellWriteRoots");function Ci(e,t){let n=process.platform==="win32"?t:d.resolve(e);return d.join(ee.tmpdir(),"kodax-sandbox",gn("sha256").update(n).digest("hex").slice(0,16))}i(Ci,"workspaceShellTempRoot");function Wi(e,t){return d.join(Ci(e,t),`${process.pid}-${F()}`)}i(Wi,"createWorkspaceShellTempDirectory");async function Pn(e){await L(e,{recursive:!0,force:!0}),await vo(d.dirname(e)).catch(t=>{if(t.code!=="ENOENT"&&t.code!=="ENOTEMPTY")throw t})}i(Pn,"removeWorkspaceShellTempDirectory");function Ti(e){return process.platform==="win32"?e===void 0?[]:[d.dirname(e)]:Ri()}i(Ti,"workspaceShellTempWriteRoots");function $i(e,t,n){try{let r=j.native(t),o=d.resolve(t),s=d.resolve(e);if(!_(o,s)||s===o)return;for(;s!==o;)try{let l=j.native(s);if(l===r||!_(r,l))return;let a=d.relative(r,l).split(d.sep)[0]?.toLowerCase();return a==="sandbox-runtime"||n&&xt.some(c=>c===a)?void 0:l}catch(l){if(!n||l.code!=="ENOENT")return;try{Kn(s);return}catch(c){if(c.code!=="ENOENT")return}let a=d.dirname(s);if(a===s)return;s=a}return}catch{return}}i($i,"windowsAgentHomeAccessRoot");function Gr(e,t){if(!t)return{read:[],write:[]};let n=i((r,o)=>[...new Set(r.flatMap(s=>{let l=$i(s,e,o);return l?[l]:[]}))],"roots");return{read:n(t.read,!1),write:n(t.write,!0),...t.ephemeral===!0?{ephemeral:!0}:{}}}i(Gr,"windowsAgentHomeAccessRoots");function mn(e){return e??(process.platform==="win32"?process.env.COMSPEC??d.join(process.env.SystemRoot??"C:\\Windows","System32","cmd.exe"):"/bin/sh")}i(mn,"workspaceShellExecutable");function _i(e,t){return Object.entries(e).find(([n,r])=>n.toUpperCase()===t&&r!==void 0)?.[1]}i(_i,"shellEnvironmentValue");function Oi(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=>_(e,r)).sort((r,o)=>o.length-r.length)}i(Oi,"workspaceShellUserDataBoundaries");function Ni(e,t,n){if(process.platform!=="win32"||e.toLowerCase()===t.toLowerCase())return[];try{if(!Kn(e).isSymbolicLink())return[]}catch{return[]}let r=n.find(a=>a.toLowerCase()!==t.toLowerCase()&&_(a,t));if(r===void 0)return[];let[o]=d.relative(r,t).split(d.sep);if(!o)return[];let s=d.join(r,o),l=[];for(let a=d.dirname(t);a.toLowerCase()!==s.toLowerCase()&&_(s,a);a=d.dirname(a))l.push(a);return l}i(Ni,"workspaceShellLinkedTargetAncestors");function Fn(e,t){let n=d.resolve(process.platform==="win32"?process.env.USERPROFILE??ee.homedir():ee.homedir()),r=d.resolve(K()),o=Nt(n,r,d.join(r,"sandbox-runtime")),s=Oi(n),l=new Map,a=i(m=>{let p=d.resolve(m);if(!(p===d.parse(p).root||p.toLowerCase()===n.toLowerCase()||_(r,p)||_(p,r)||o.some(g=>_(g,p))))return p},"safe"),c=i((m,p)=>{let g=a(m);if(g===void 0)return;let w;try{w=j(g)}catch{return}if(a(w)===void 0)return;let x=p?[g,w].filter(b=>_(n,b)):[g,w];for(let b of x)l.set(process.platform==="win32"?b.toLowerCase():b,b);if(p&&x.includes(w))for(let b of Ni(g,w,s)){let y=a(b);y!==void 0&&_(n,y)&&l.set(y.toLowerCase(),y)}},"remember");for(let m of(_i(e,"PATH")??"").split(d.delimiter)){let p=m.trim().replace(/^"(.*)"$/,"$1");p&&d.isAbsolute(p)&&c(p,!0)}let f=mn(t);d.isAbsolute(f)&&c(d.dirname(f),!0);let u=Vn();if(d.isAbsolute(u)){let m=a(u);m!==void 0&&l.set(process.platform==="win32"?m.toLowerCase():m,m),c(d.dirname(u),!1)}return[...l.values()].sort((m,p)=>m.toLowerCase().localeCompare(p.toLowerCase()))}i(Fn,"workspaceShellRuntimeReadScopes");function pt(e,t){return d.resolve(e).toLowerCase()===d.resolve(t).toLowerCase()}i(pt,"sameWindowsPath");function Dn(e,t){let n=yo(e,"r");try{let r=Buffer.allocUnsafe(t+1),o=0;for(;o<r.length;){let s=So(n,r,o,r.length-o,o);if(s===0)break;o+=s}return o>t?void 0:r.toString("utf8",0,o)}finally{mo(n)}}i(Dn,"readBoundedUtf8File");function Ii(e,t){let n=/^(.*)[/\\]worktrees[/\\][^/\\]+$/.exec(e);if(n===null)return;let r=Dn(d.join(e,"commondir"),4096),o=Dn(d.join(e,"gitdir"),4096);if(r===void 0||o===void 0)return;let s=j(n[1]),l=j(d.resolve(e,r.trim())),a=j(d.resolve(e,o.trim()));return pt(l,s)&&pt(a,t)?s:void 0}i(Ii,"linkedWorktreeMainGitDirectory");function Li(e){let t=Dn(d.join(e,"config"),65536);if(t===void 0)return;let n=!1,r;for(let o of t.split(/\r?\n/)){let s=o.trim();if(s.startsWith("[")){n=/^\[\s*core\s*\]$/i.test(s);continue}if(!n)continue;let l=/^worktree\s*=\s*(.+?)\s*$/i.exec(s);if(l===null)continue;if(r!==void 0)return;let a=l[1];if(a.includes("\0")||a.startsWith('"')||a.endsWith('"'))return;r=a}return r===void 0?void 0:j(d.resolve(e,r))}i(Li,"submoduleGitWorktree");function Fi(e,t){if(!/[/\\]\.git[/\\]modules[/\\]/i.test(e))return!1;let n=Li(e);return n!==void 0&&pt(n,t)}i(Fi,"isStructurallyBoundSubmoduleGitDirectory");function Di(e){if(process.platform!=="win32")return{};let t=d.join(e,".git");try{if(!Kn(t).isFile())return{};let n=Dn(t,4096);if(n===void 0)return{};let r=/^gitdir:\s*(.+?)\s*$/m.exec(n);if(r===null)return{};let o=j(d.resolve(e,r[1])),s=Ii(o,t),l=Fi(o,e);if(s===void 0&&!l)return{};let a=s??o;return Ke(a).isDirectory()?Ke(d.join(a,"HEAD")).isFile()?{mainGitDirectory:a,gitfile:t}:{}:{}}catch(n){let r=n.code;if(r==="ENOENT"||r==="ENOTDIR")return{};throw n}}i(Di,"windowsLinkedWorktreeGitAccess");function qr(e,t,n,r,o=Fn(process.env,mn())){let s=d.resolve(K()),l=d.join(s,"sandbox-runtime"),a=d.resolve(process.platform==="win32"?process.env.USERPROFILE??ee.homedir():ee.homedir()),c=Nt(a,s,l),f=process.platform==="win32"?It(c):c.filter(g=>g!==s),u=process.platform==="win32"?Gr(s,n):{read:[],write:[]},m=Pi([e,...Ti(t),...u.write,...r?.write??[]],s),p=Di(e);return Ot({network:{allowedDomains:[],deniedDomains:[],strictAllowlist:!1,allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{denyRead:f,allowRead:[...new Set([...o,...u.read,...r?.read??[],...p.mainGitDirectory!==void 0?[p.mainGitDirectory]:[]])],allowWrite:m,denyWrite:[l,...xt.map(g=>d.join(s,g)),...Dr(e),...p.gitfile!==void 0?[p.gitfile]:[]]}})}i(qr,"workspaceShellSandboxConfig");function Kr(e,t,n,r,o){let s=qr(e,t,n,r,o);return process.platform!=="win32"?s:Jr(s)}i(Kr,"workspaceShellSessionSandboxConfig");function Jr(e){let t=e.filesystem.allowWrite;return{...e,filesystem:{...e.filesystem,denyRead:e.filesystem.denyRead,denyWrite:e.filesystem.denyWrite.filter(n=>t.some(r=>_(r,n)))}}}i(Jr,"boundedWindowsWorkspaceDenies");function Bi(e,t,n,r,o){let s=qr(e,t,n,r,o);return process.platform==="win32"?Jr(s):s}i(Bi,"workspaceShellCommandSandboxConfig");function Cn(e,t){return[...new Set((e??[]).map(n=>d.resolve(t,n)))]}i(Cn,"normalizedSandboxPaths");function Mi(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}})}i(Mi,"sdkSandboxEndpoints");async function Ls(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=Mi(n),o=await ce();if(!o.ready){if(!Un(o))return{status:"unavailable",sandboxed:!1,doctor:o};if(await Ue(),o.setupRequired)return{status:"unavailable",sandboxed:!1,doctor:o}}let s=Wr(e.inheritEnvironment===!0?process.env:fe(),e.env??{}),l={config:Ot({network:{allowedDomains:[],deniedDomains:[],strictAllowlist:n.mode==="deny",allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{allowRead:Cn(e.filesystem.allowRead,t),allowWrite:Cn(e.filesystem.allowWrite,t),denyRead:Cn(e.filesystem.denyRead,t),denyWrite:Cn(e.filesystem.denyWrite,t)}}),command:e.command,args:e.args??[],cwd:t,env:s,endpoints:r,allowAllNetwork:n.mode==="allow"},a=await Lr(l,e.signal,e.timeoutMs??Xn,e.maxOutputBytes??bt);return{status:"completed",sandboxed:!0,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}i(Ls,"runKodaXSandboxed");var ji=5*6e4,Gi=3e4,qi=3e4,on=1500,Xr=13e4,Ki=Xr,Ji=5e3,Xi=qi,Ui=Ki,rr=Ji,Hi=8,J=new Map,dn=new Set,ve=new Set,Ge=new Set,qe=new Set,je,wt,Bn=!1,Te,mt=250;function Mn(){je=void 0,Te!==void 0&&(clearTimeout(Te),Te=void 0),mt=250}i(Mn,"clearWindowsSandboxAclRecoveryRetry");function Ft(){if(process.platform!=="win32"||Te!==void 0)return;let e=mt;mt=Math.min(e*2,3e5),Te=setTimeout(()=>{Te=void 0,Ue().catch(()=>{Ft()})},e),Te.unref()}i(Ft,"scheduleWindowsSandboxAclRecoveryRetry");function Ne(e){let t=e instanceof Error?e:new Error(String(e));if(process.platform!=="win32"){wt??=t;return}je??=t,Ft()}i(Ne,"recordWindowsSandboxAclFailure");function Dt(){if(process.platform!=="win32"&&wt!==void 0)throw new Error("Sandbox process cleanup was not confirmed; stop the retained process tree before more sandboxed commands.",{cause:wt});if(process.platform==="win32"&&je!==void 0)throw je instanceof M?je:new Error("Windows sandbox ACL cleanup is pending automatic recovery; non-sandbox work remains available.",{cause:je})}i(Dt,"assertWindowsSandboxAclProcessSafe");function Yn(e){Dt(),process.platform==="win32"&&Xe(e)}i(Yn,"assertWindowsSandboxAclSafe");function Ur(e){ve.add(e),e.then(()=>ve.delete(e),()=>ve.delete(e))}i(Ur,"trackWorkspaceSessionReset");function zi(e){Ge.add(e),e.then(()=>Ge.delete(e),t=>{Ge.delete(e),W({source:"sandbox:workspace-session",level:"error",message:"Workspace sandbox durable ACL poison transition failed.",detail:t})})}i(zi,"trackWindowsSandboxAclTransition");async function Hr(){for(;Ge.size>0;)await Promise.allSettled([...Ge])}i(Hr,"waitForWindowsSandboxAclTransitions");async function Vi(){for(;qe.size>0;)await Promise.allSettled([...qe])}i(Vi,"waitForStandaloneBrokerSettlements");function Yi(e){return new Error(`Standalone sandbox broker settlement did not finish within ${e} ms; automatic recovery remains in progress and process ownership stays durably fenced.`)}i(Yi,"standaloneBrokerShutdownTimeoutError");async function Zi(){if(qe.size===0)return;let e;try{await Promise.race([Vi(),new Promise((t,n)=>{e=setTimeout(()=>n(Yi(rr)),rr),e.unref()})])}finally{e!==void 0&&clearTimeout(e)}}i(Zi,"waitForStandaloneBrokerSettlementsBeforeShutdown");async function zr(){for(;ve.size>0;)await Promise.allSettled([...ve]);await Hr(),process.platform!=="win32"&&Dt()}i(zr,"waitForWorkspaceSessionResets");async function Bt(){let e=[...J.values()];J.clear();let t=[];for(let n of e)try{await(await n).close()}catch(r){t.push(r),W({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox shutdown could not confirm ACL reset.",detail:r})}return t}i(Bt,"closeCachedWorkspaceSessions");var Vr=i(()=>{Bn=!1,Bt()},"closeWorkspaceSessionsBeforeExit");function Qi(){Bn||(Bn=!0,process.once("beforeExit",Vr))}i(Qi,"registerWorkspaceSessionBeforeExit");async function Fs(){for(process.removeListener("beforeExit",Vr),Bn=!1;dn.size>0;)await Promise.allSettled([...dn]);let e=await Bt();try{for(;ve.size>0;)await Promise.allSettled([...ve]);await Zi(),await Hr(),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.")}i(Fs,"shutdownAsrtWorkspaceSessions");function Yr(){let e=new Error("ASRT workspace session preparation timed out.");return e.name="TimeoutError",e}i(Yr,"workspacePreparationTimeoutError");function jn(e,t){if(e?.aborted)throw new DOMException("Operation aborted","AbortError");if(t!==void 0&&Date.now()>=t)throw Yr()}i(jn,"throwIfWorkspacePreparationStopped");function gt(e,t,n){return jn(t,n),t===void 0&&n===void 0?e:new Promise((r,o)=>{let s=!1,l,a=i(f=>{s||(s=!0,l&&clearTimeout(l),t?.removeEventListener("abort",c),f())},"finish"),c=i(()=>{a(()=>o(new DOMException("Operation aborted","AbortError")))},"onAbort");t?.addEventListener("abort",c,{once:!0}),n!==void 0&&(l=setTimeout(()=>{a(()=>o(Yr()))},Math.max(0,n-Date.now())),l.unref()),e.then(f=>a(()=>r(f)),f=>a(()=>o(f)))})}i(gt,"waitForWorkspacePreparation");async function bn(){let e=d.join(K(),"sandbox-runtime");return await V(e,{recursive:!0,mode:448}),e}i(bn,"sandboxControlDirectory");function es(e){if(process.env.KODAX_BUNDLED==="true")return["__asrt-workspace-session",e];if(import.meta.url.endsWith(".ts"))return["--import",dr(vt.resolve("tsx")).href,Vt(new URL("./sandbox-workspace-session-entry.ts",import.meta.url)),e];let t=d.dirname(Vt(import.meta.url)),n=d.basename(t)==="chunks"?d.dirname(t):t;return[d.join(n,"sandbox-workspace-session.js"),e]}i(es,"workspaceSessionEntryArgs");function he(e,t){let n=t?"ref":"unref";e[n]();for(let r of e.stdio){if(!r)continue;r[n]?.()}}i(he,"setWorkspaceSessionReferenced");async function Zr(e,t,n){if(e)return t();let r=process.platform==="win32"?await nn(n):await En(n);try{return await t()}finally{await r()}}i(Zr,"withExclusiveFileSystemEffectFence");async function ns(e,t,n,r,o){if(process.platform!=="win32")return Zr(!1,e,t);let s=r?.supervisorPid??n.pid;if(s===void 0)throw new Error("Workspace cleanup process identity is unavailable.");return nt(t,{pid:s,windowsJobContained:r!==void 0||Jt()},e,o,l=>{r!==void 0&&xe.set(r.jobName,l)},()=>{r!==void 0&&xe.delete(r.jobName)})}i(ns,"withExclusiveFileSystemCleanupFence");async function ts(e,t,n,r,o,s){let l=process.platform==="win32"?Wi(e,o):void 0;l!==void 0&&await V(l,{recursive:!0,mode:448});let a=await bn();process.platform==="win32"&&ft(Dr(e),"write");let c=d.join(a,`workspace-${process.pid}-${F()}.json`),f=Lt(Kr(e,l,t,n,r));await _e(c,JSON.stringify({config:f}),{mode:384});let u=Ze({args:es(c),env:fe(),isElectron:process.versions.electron!==void 0}),m=process.platform==="win32"?await $r(u.args,a,!0):{command:process.execPath,...u},p=m.gateFile,g;try{g=await Rr(o)}catch(S){let h=await Promise.allSettled([L(c,{force:!0}),...p===void 0?[]:[L(p,{force:!0})],...l===void 0?[]:[Pn(l)]]),k=[S,...h.flatMap(E=>E.status==="rejected"?[E.reason]:[])];throw k.length===1?S:new AggregateError(k,"Workspace sandbox owner admission and pre-launch cleanup both failed.")}let w;try{w=Gn(m.command,[...m.args],{cwd:process.platform==="win32"?le().directory:void 0,env:m.env,shell:!1,stdio:["pipe","pipe","pipe","pipe"],windowsHide:!0})}catch(S){let h=[S];try{await an(g)}catch(E){await Pe(g,E),h.push(E)}let k=await Promise.allSettled([L(c,{force:!0}),...p===void 0?[]:[L(p,{force:!0})],...l===void 0?[]:[Pn(l)]]);throw h.push(...k.flatMap(E=>E.status==="rejected"?[E.reason]:[])),h.length===1?S:new AggregateError(h,"Workspace sandbox owner launch cleanup failed.")}Qe(w);let x=new Promise(S=>{let h=!1,k=i((E,ge)=>{h||(h=!0,S({code:E,signal:ge}))},"finish");w.once("exit",k),w.once("close",k)}),b=new Promise(S=>w.once("error",S)),y,P=!1;if(process.platform==="win32")try{if(w.pid===void 0)throw new Error("Workspace sandbox gate did not expose a PID.");y=await en(w.pid),br(g,y),P=!0,await Tt(w,!1)}catch(S){let h=[S];try{if(P||await $t(w).catch(()=>{}),y!==void 0)await Se(y.jobName),await y.drained;else{let E=await ie(w);if(P&&E.status==="unknown")throw new Error("Workspace sandbox gate termination was not confirmed.")}P?await an(g):We(g)}catch(E){await Pe(g,E),h.push(E)}let k=await Promise.allSettled([L(c,{force:!0}),...p===void 0?[]:[L(p,{force:!0})],...l===void 0?[]:[Pn(l)]]);throw h.push(...k.flatMap(E=>E.status==="rejected"?[E.reason]:[])),new AggregateError(h,"Workspace sandbox Job containment failed.")}let A=w.pid===void 0?void 0:De(w.pid),v=w.stdio[3];if(!v)throw new Error("ASRT workspace session control pipe was not created.");let T=Ao.createInterface({input:v}),$=new Map,R="",O=!1,C=!1,G=!1,Re=!1,Zn=0,re=0,pe,U,se,He=x.then(async()=>{if(l!==void 0)try{await Pn(l)}catch(S){W({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox temp cleanup failed.",detail:S})}}),we=i(async()=>{await x,y!==void 0&&await y.drained,await He,await an(g)},"confirmCleanReset"),q,oe,D=new Promise((S,h)=>{q=S,oe=h}),ze=i(()=>{Re||(Re=!0,s())},"evict"),vn=i(async()=>{if(!C||!G||re!==0||w.exitCode!==null||w.signalCode!==null||!w.stdin.writable)return!1;try{w.stdin.end()}catch{return!1}let S;try{let h=await Promise.race([x,new Promise(k=>{S=setTimeout(k,process.platform==="win32"?Xr:on)})]);return h!==void 0&&h.code===0&&h.signal===null}finally{S!==void 0&&clearTimeout(S)}},"waitForOrderlyClose"),N,xn=!1,Ie=i(()=>{if(N)return N;xn=!0;let S=(async()=>{try{if(await vn())return;if((await ie(w,{gracefulStdinEnd:!1,gracefulMs:on,forceMs:on,taskkillMs:on})).status==="unknown")if(y!==void 0)await Se(y.jobName);else throw await vr(w.pid,A,ct("ASRT workspace session"),g)}finally{T.close(),v.destroy(),w.stdin.destroy()}})().finally(ze);return N=S,S.catch(()=>{N===S&&(N=void 0)}),S},"terminate"),Le=i(S=>{Ie().catch(h=>{W({source:"runtime.sandbox.workspace-session",level:"error",message:`ASRT workspace session termination failed after ${S}.`,detail:h})})},"observeFailedTermination"),me=i(S=>{if(!O){O=!0,oe(S);for(let h of $.values())h.reject(S);$.clear()}},"fail");w.stderr.on("data",S=>{R=(R+S.toString("utf8")).slice(-16384)}),w.stdout.on("data",S=>{R=(R+S.toString("utf8")).slice(-16384)}),T.on("line",S=>{let h;try{h=JSON.parse(S)}catch{me(new Error("ASRT workspace session returned malformed control data.")),Le("malformed control data");return}if(h.type==="ready"){h.ok?(G=!0,q()):oe(new Error(h.error??"ASRT workspace session failed."));return}if(h.type!=="result"||!h.id){me(new Error("ASRT workspace session returned an invalid control response.")),Le("an invalid control response");return}let k=$.get(h.id);k&&($.delete(h.id),k.resolve(h))}),b.then(S=>{me(S),Le("a child-process error")}),T.once("close",()=>{C||O||(me(new Error("ASRT workspace session control pipe closed unexpectedly.")),Le("an unexpected control-pipe close"))}),x.then(({code:S,signal:h})=>{U&&clearTimeout(U);let k=new Error(`ASRT workspace session exited ${h??S??1}: ${R.trim()||"no diagnostics"}`);!xn&&(S!==0||h!==null||!C)&&zi(Pe(g,k)),me(k),ze()});let no=setTimeout(()=>{me(new Error("ASRT workspace session initialization timed out.")),Le("an initialization timeout")},Gi);try{await D.finally(()=>clearTimeout(no))}catch(S){C=!0;let h=[S],k=!1;try{await Ie(),k=!0}catch(E){h.push(E)}if(k)try{await we()}catch(E){await Pe(g,E),h.push(E)}throw await L(c,{force:!0}),h.length===1?S:new AggregateError(h,`Workspace sandbox startup cleanup failed: ${be(h.at(-1))}`)}let kn=i(async(S,h)=>{if(O||C&&S==="wrap")throw new Error("ASRT workspace session is unavailable.");let k=`workspace_${++Zn}`,E=new Promise((B,ye)=>{$.set(k,{resolve:B,reject:ye})}),ge=setTimeout(()=>{me(new Error(`ASRT workspace session ${S} request timed out.`)),Fe.close().catch(B=>{W({source:"sandbox:workspace-session",level:"warn",message:"Timed-out workspace sandbox request could not retire its session.",detail:B})})},S==="cleanup"?Ui:Xi);ge.unref();try{await new Promise((B,ye)=>{w.stdin.write(`${JSON.stringify({id:k,type:S,request:h})}
|
|
602
|
+
`,Ve=>Ve?ye(Ve):B())})}catch(B){throw $.delete(k),clearTimeout(ge),me(B instanceof Error?B:new Error(String(B))),Le("a control request write failure"),B}return E.finally(()=>clearTimeout(ge))},"request"),Mt=i(()=>{if(U&&clearTimeout(U),!(re>0||C||O)){if(process.platform==="win32"){he(w,!1);return}U=setTimeout(()=>{Fe.close().catch(S=>{W({source:"sandbox:workspace-session",level:"warn",message:"Idle workspace sandbox session could not confirm ACL reset.",detail:S})})},ji),U.unref(),he(w,!1)}},"scheduleIdleClose"),Fe={policyKey:o,...l===void 0?{}:{tempDirectory:l},async acquire(S,h,k){if(Yn(o),jn(h,k),O||C)throw new Error("ASRT workspace session is unavailable.");U&&clearTimeout(U),he(w,!0),re+=1;let E=!1,ge=!1,B=i(()=>{if(E)return!1;E=!0,re-=1;let Z=re===0;return re===0&&(pe?.(),pe=void 0),Mt(),Z},"finalize"),ye=i(async()=>{E||(ge=B()&&process.platform==="win32"),ge&&await Fe.close()},"finalizeAndCloseIfIdle"),Ve=i((Z,ae)=>{W({source:"sandbox:workspace-session",level:"warn",message:Z,detail:ae}),B()&&Fe.close().catch(Q=>{W({source:"sandbox:workspace-session",level:"warn",message:"Failed workspace sandbox cleanup could not retire its session.",detail:Q})})},"retireAfterCleanupFailure"),jt=kn("wrap",S),Ye;try{Ye=await gt(jt,h,k)}catch(Z){throw jt.then(async ae=>{if(!ae.ok||!ae.invocation)return;let de=await kn("cleanup");if(!de.ok)throw new Error(de.error??"ASRT command cleanup failed.")}).then(ye,ae=>Ve("Late workspace sandbox preparation cleanup failed.",ae)),Z}try{if(!Ye.ok||!Ye.invocation){B();let Q=new Error(Ye.error??"ASRT workspace wrapping failed.");try{await Fe.close()}catch(H){let An=H instanceof Error?H.message:String(H);throw new Error(`${Q.message} Workspace session reset failed: ${An}`,{cause:Q})}throw Q}try{jn(h,k)}catch(Q){try{let H=await kn("cleanup");if(!H.ok)throw new Error(H.error??"ASRT command cleanup failed.")}catch(H){Ve("Cancelled workspace sandbox preparation cleanup failed.",H)}throw await ye(),Q}let Z=!1,ae=!1,de;return{invocation:Ye.invocation,async release(){if(Z)return;if(de!==void 0)return de;let Q=(async()=>{if(!ae){let H;try{H=await kn("cleanup")}catch(An){try{await ye(),Z=!0}catch(to){throw new AggregateError([An,to],"Workspace sandbox command cleanup and policy-group reset both failed.")}throw An}if(!H.ok)throw new Error(H.error??"ASRT command cleanup failed.");ae=!0}await ye(),Z=!0})();de=Q;try{await Q}finally{de===Q&&(de=void 0)}}}}catch(Z){throw B(),Z}},async close(){if(se)return se;C=!0,ze();let S=!1,h=(async()=>{U&&clearTimeout(U),he(w,!0),re>0&&await new Promise(k=>{let E=setTimeout(k,on);E.unref?.(),pe=i(()=>{clearTimeout(E),k()},"resolveDrained")}),he(w,!1),await ns(async()=>{he(w,!0),await Ie(),await we(),S=!0},o,w,y,async k=>{he(w,!1),S||await Pe(g,k)})})().catch(async k=>{throw he(w,!1),!S&&!(k instanceof Qn)&&await Pe(g,k),k});se=h,Ur(h);try{await h}catch(k){throw se===h&&(se=void 0),k}}};return Mt(),Fe}i(ts,"startWorkspaceSessionClientWithFence");function or(e,t,n,r,o,s,l){return Zr(s,async()=>{if(Qr(e,t,n,r)!==o)throw new Error("Sandbox policy paths changed before ACL initialization.");return await Ue(o,!0),Yn(o),ts(e,t,n,r,o,l)},o)}i(or,"startWorkspaceSessionClient");function at(e){return[...new Set(e.map(t=>{let n=d.resolve(t);return process.platform==="win32"?n.toLowerCase():n}))].sort()}i(at,"normalizedWorkspacePolicyPaths");function sn(e){let t=i(r=>{let o=d.resolve(r);return process.platform==="win32"?o.toLowerCase():o},"normalize"),n=null;try{n=t(j.native(e))}catch{}return{lexical:t(e),canonical:n}}i(sn,"workspacePolicyPathIdentity");function Wn(e){let t=new Map;for(let n of e){let r=sn(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??""))}i(Wn,"workspacePolicyPathIdentities");function Qr(e,t,n,r){let o=Kr(e,void 0,t,n,r);return gn("sha256").update(JSON.stringify({workspace:sn(e),agentHome:sn(K()),tempBase:sn(ee.tmpdir()),filesystem:{allowRead:Wn(o.filesystem.allowRead),allowWrite:Wn(o.filesystem.allowWrite),denyRead:Wn(o.filesystem.denyRead),denyWrite:Wn(o.filesystem.denyWrite)},network:o.network,windowsRunner:process.platform==="win32"?{version:$e,architecture:process.arch,path:sn(le().path)}:null,ephemeral:t?.ephemeral===!0})).digest("hex")}i(Qr,"workspaceShellPolicyKey");function rs(e){return process.platform!=="win32"?!0:(e?.write??[]).every(t=>{try{return j.native(t),!0}catch{return!1}})}i(rs,"workspaceShellFilesystemAccessIsRepresentable");async function ir(e,t,n,r=Fn(process.env,mn()),o=r,s=!1){if(process.platform==="win32"){if(ve.size>0||Ge.size>0)return}else await zr();let l=await ce();if(!l.ready&&!Un(l))return;if(process.platform!=="win32"){let y=K();await Promise.all([bn(),...xt.map(P=>V(d.join(y,P),{recursive:!0,mode:448}))])}let a=Qr(e,process.platform==="win32"?t:void 0,n,r);if(!l.ready&&l.setupRequired)return;Qi();let c=process.platform==="win32"?t:void 0,f=process.platform==="win32"?e.toLowerCase():e,u=at,m=u(r),p=JSON.stringify(m)===JSON.stringify(u(o)),g=(n?.read.length??0)>0||(n?.write.length??0)>0,w=c===void 0&&!g&&p?"workspace":gn("sha256").update(JSON.stringify({read:[...c?.read??[]].map(y=>y.toLowerCase()).sort(),write:[...c?.write??[]].map(y=>y.toLowerCase()).sort(),additionalRead:at(n?.read??[]),additionalWrite:at(n?.write??[]),runtimeReadScopes:m})).digest("hex"),x=process.platform==="win32"?a:`${f}\0${w}`;if(c?.ephemeral===!0)return or(e,c,n,r,a,s,()=>{});let b=J.get(x);if(b&&(await Ue(a),Yn(a),J.delete(x),J.set(x,b)),!b){if(process.platform!=="win32"&&w!=="workspace"){let y=[...J.keys()].filter(P=>!P.endsWith("\0workspace"));if(y.length>=Hi){let P=y[0],A=J.get(P);if(J.delete(P),A)try{await(await A).close()}catch(v){throw W({source:"sandbox:workspace-session",level:"warn",message:"Retiring an old scoped workspace sandbox failed.",detail:v}),v}}}b=or(e,c,n,r,a,s,()=>{J.get(x)===b&&J.delete(x)}),J.set(x,b),b.catch(()=>{J.get(x)===b&&J.delete(x)})}return b}i(ir,"getWorkspaceSession");function os(e){let t=d.resolve(e.workspaceRoot),n=Fn(process.platform==="win32"?{}:process.env,mn()),r=process.platform==="win32"?void 0:ir(t,void 0,void 0,n,n);return r!==void 0&&(dn.add(r),r.then(()=>dn.delete(r),()=>dn.delete(r)),r.catch(o=>{W({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 s={id:o.toolCallId,name:"bash",input:{...o.toolInput}},l=await e.shouldSandbox(s),a=l?To(l,e.additionalWorkspaceRoots?.()??[]):!1;if(!a){o.reportObservation?.({version:1,state:"not_selected"});return}let c=typeof a=="object"?a.agentHomeAccess:void 0,f=process.platform==="win32"&&c!==void 0?Gr(d.resolve(K()),c):c,u=typeof a=="object"?a.filesystemAccess:void 0;if(!rs(u)){o.reportObservation?.({version:1,state:"fallback",reason:"not_ready",execution:"normal_permission_policy"});return}let m=process.platform==="win32"&&f?.ephemeral===!0,p=mn(o.executable),g=o.args??(process.platform==="win32"?["/d","/s","/c",o.command]:["-c",o.command]),w=Ct(o.env),x=Fn(w,p),b,y;try{r!==void 0&&(await gt(r.then(()=>{},()=>{}),o.signal,o.deadlineAt),jn(o.signal,o.deadlineAt));let P=ir(t,f,u,x,n),A;try{A=await gt(P,o.signal,o.deadlineAt)}catch(q){if(process.platform==="win32"&&(o.signal?.aborted||o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt)){let oe=P.then(async D=>{D&&await D.close()},async()=>{});Ur(oe),oe.catch(D=>{W({source:"sandbox:workspace-session",level:"warn",message:"Late cancelled workspace session rollback failed.",detail:D})})}throw q}if(!A){o.reportObservation?.({version:1,state:"fallback",reason:"not_ready",execution:"normal_permission_policy"});return}let v=A.policyKey;y=A;let T=await bn(),$=d.join(T,`kodax-asrt-shell-${process.pid}-${F()}.json`),R=d.join(T,`kodax-asrt-observation-${process.pid}-${F()}.json`),O=w;if(process.platform==="win32"){let q=A.tempDirectory;if(q===void 0)throw new Error("Windows workspace sandbox temp directory is unavailable.");O=Wr(w,{TEMP:q,TMP:q,TMPDIR:q,GIT_CONFIG_GLOBAL:"NUL",GIT_CONFIG_NOSYSTEM:"1"})}let C={config:Lt(Bi(t,A.tempDirectory,f,u,x)),command:p,args:g,windowsVerbatimArguments:o.windowsVerbatimArguments===!0,cwd:o.cwd,env:O,endpoints:[],allowAllNetwork:!0,bootstrapCommand:Vn(),fallbackToNormalExecution:o.fallbackToNormalExecution!==!1,observationBackend:$o().backend,observationFile:R,targetStartedMarker:`\0KODAX_ASRT_TARGET_STARTED:${F()}\0
|
|
603
|
+
`},G=await A.acquire(C,o.signal,o.deadlineAt);b=G;let Re={...C,wrappedInvocation:G.invocation},Zn=process.env.KODAX_BUNDLED==="true"?["__asrt-broker",$]:["--input-type=module","-e",fr,lr,$],re=Ze({args:Zn,env:fe(),isElectron:process.versions.electron!==void 0});await _e($,JSON.stringify(Re),{mode:384});let pe,U=i(async()=>{m||(pe===void 0&&(pe=y?.close()??Promise.resolve(),pe.catch(q=>{W({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox session retirement failed.",detail:q})})),process.platform==="win32"&&await pe)},"retireWorkspaceSession"),se=!1,He,we;return{executable:process.execPath,args:re.args,env:re.env,fileSystemEffectPolicyKey:v,authorizeStart:i(()=>Yn(v),"authorizeStart"),async cleanup(q){if(we!==void 0)return we;let oe=(async()=>{let D=[];if(!se)try{He=await Je(R,"utf8").then(oi).catch(N=>{if(N.code!=="ENOENT")throw N}),se=!0}catch(N){D.push(N)}let ze=await Promise.allSettled([L($,{force:!0}),...se?[L(R,{force:!0})]:[]]);for(let N of ze)N.status==="rejected"&&D.push(N.reason);try{await G.release()}catch(N){D.push(N)}let vn=q?.execution==="started_or_unknown"&&He===void 0;if(vn&&D.push(new Error("Required OS sandbox execution could not be attested; the workspace session must be retired and the command was not retried")),D.length>0){let N=vn?"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.",xn=D.length===1?`${N} Cause: ${be(D[0])}`:N,Ie=new AggregateError(D,xn);throw W({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox command cleanup failed.",detail:Ie}),Ie}return He})();we=oe;try{return await oe}finally{we===oe&&(we=void 0)}},retire:U}}catch(P){let A=[P],v=o.signal?.aborted||o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt,T=!1;if(b)try{await b.release()}catch(R){T=!0,A.push(R),W({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox lease release failed.",detail:R})}if(v&&process.platform==="win32"&&y&&b===void 0)throw y.close().catch(R=>{W({source:"sandbox:workspace-session",level:"warn",message:"Cancelled workspace preparation cleanup could not retire its session.",detail:R})}),P;if(process.platform==="win32"&&y)try{await y.close()}catch(R){A.push(R),W({source:"sandbox:workspace-session",level:"warn",message:"Failed workspace lease cleanup could not retire its session.",detail:R})}else T&&y&&y.close().catch(R=>{W({source:"sandbox:workspace-session",level:"warn",message:"Failed workspace lease cleanup could not retire its session.",detail:R})});if(v)throw P;let $=A.length===1?P:new AggregateError(A,`Workspace sandbox preparation failed and cleanup was incomplete: ${A.map(be).join(" | ")}`);W({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}}}}i(os,"createAsrtShellSandbox");var is=String.raw`
|
|
604
|
+
const { createHash } = require('node:crypto');
|
|
605
|
+
const fs = require('node:fs/promises');
|
|
606
|
+
const path = require('node:path');
|
|
607
|
+
const chunks = [];
|
|
608
|
+
process.stdin.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
|
|
609
|
+
process.stdin.once('end', async () => {
|
|
610
|
+
const assertSingleLink = (stat) => {
|
|
611
|
+
if (stat.nlink !== 1n) throw new Error('Text mutation target must not be hard-linked.');
|
|
612
|
+
};
|
|
613
|
+
const revision = (content, stat) => 'present:' + createHash('sha256')
|
|
614
|
+
.update(stat.dev.toString())
|
|
615
|
+
.update(':')
|
|
616
|
+
.update(stat.ino.toString())
|
|
617
|
+
.update(':')
|
|
618
|
+
.update(stat.nlink.toString())
|
|
619
|
+
.update('\0')
|
|
620
|
+
.update(content)
|
|
621
|
+
.digest('hex');
|
|
622
|
+
const backupPath = async (target, openedStat) => {
|
|
623
|
+
const canonical = await fs.realpath(target);
|
|
624
|
+
let canonicalHandle;
|
|
625
|
+
try {
|
|
626
|
+
canonicalHandle = await fs.open(canonical, 'r');
|
|
627
|
+
const canonicalStat = await canonicalHandle.stat({ bigint: true });
|
|
628
|
+
assertSingleLink(canonicalStat);
|
|
629
|
+
if (canonicalStat.dev !== openedStat.dev || canonicalStat.ino !== openedStat.ino) {
|
|
630
|
+
throw new Error('Text mutation target identity changed while reading.');
|
|
631
|
+
}
|
|
632
|
+
return canonical;
|
|
633
|
+
} finally {
|
|
634
|
+
await canonicalHandle?.close();
|
|
635
|
+
}
|
|
636
|
+
};
|
|
637
|
+
const snapshot = async (target) => {
|
|
638
|
+
let handle;
|
|
639
|
+
try {
|
|
640
|
+
handle = await fs.open(target, 'r');
|
|
641
|
+
} catch (error) {
|
|
642
|
+
if (error && error.code === 'ENOENT') {
|
|
643
|
+
return { state: 'missing', content: '', revision: 'missing', backupPath: path.resolve(target) };
|
|
644
|
+
}
|
|
645
|
+
throw error;
|
|
646
|
+
}
|
|
647
|
+
try {
|
|
648
|
+
const [content, stat] = await Promise.all([
|
|
649
|
+
handle.readFile('utf8'),
|
|
650
|
+
handle.stat({ bigint: true }),
|
|
651
|
+
]);
|
|
652
|
+
assertSingleLink(stat);
|
|
653
|
+
return {
|
|
654
|
+
state: 'present',
|
|
655
|
+
content,
|
|
656
|
+
revision: revision(content, stat),
|
|
657
|
+
backupPath: await backupPath(target, stat),
|
|
658
|
+
};
|
|
659
|
+
} finally {
|
|
660
|
+
await handle?.close();
|
|
661
|
+
}
|
|
662
|
+
};
|
|
663
|
+
const writeFully = async (handle, content) => {
|
|
664
|
+
const encoded = Buffer.from(content, 'utf8');
|
|
665
|
+
let written = 0;
|
|
666
|
+
while (written < encoded.length) {
|
|
667
|
+
const result = await handle.write(encoded, written, encoded.length - written, written);
|
|
668
|
+
if (result.bytesWritten === 0) throw new Error('Text mutation write made no progress.');
|
|
669
|
+
written += result.bytesWritten;
|
|
670
|
+
}
|
|
671
|
+
await handle.truncate(encoded.length);
|
|
672
|
+
};
|
|
673
|
+
try {
|
|
674
|
+
const input = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
675
|
+
if (!input || typeof input.path !== 'string' || !path.isAbsolute(input.path)) {
|
|
676
|
+
throw new Error('Text mutation target must be an absolute path.');
|
|
677
|
+
}
|
|
678
|
+
if (input.action === 'read') {
|
|
679
|
+
process.stdout.write(JSON.stringify({ status: 'ok', snapshot: await snapshot(input.path) }));
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
if (
|
|
683
|
+
input.action !== 'write'
|
|
684
|
+
|| typeof input.content !== 'string'
|
|
685
|
+
|| typeof input.expectedRevision !== 'string'
|
|
686
|
+
|| typeof input.createParentDirectories !== 'boolean'
|
|
687
|
+
) throw new Error('Invalid text mutation request.');
|
|
688
|
+
if (input.createParentDirectories) await fs.mkdir(path.dirname(input.path), { recursive: true });
|
|
689
|
+
let handle;
|
|
690
|
+
try {
|
|
691
|
+
if (input.expectedRevision === 'missing') {
|
|
692
|
+
handle = await fs.open(input.path, 'wx');
|
|
693
|
+
assertSingleLink(await handle.stat({ bigint: true }));
|
|
694
|
+
} else {
|
|
695
|
+
handle = await fs.open(input.path, 'r+');
|
|
696
|
+
const [content, stat] = await Promise.all([
|
|
697
|
+
handle.readFile('utf8'),
|
|
698
|
+
handle.stat({ bigint: true }),
|
|
699
|
+
]);
|
|
700
|
+
assertSingleLink(stat);
|
|
701
|
+
if (revision(content, stat) !== input.expectedRevision) {
|
|
702
|
+
process.stdout.write(JSON.stringify({ status: 'conflict' }));
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
await writeFully(handle, input.content);
|
|
707
|
+
process.stdout.write(JSON.stringify({ status: 'written' }));
|
|
708
|
+
} catch (error) {
|
|
709
|
+
if (input.expectedRevision === 'missing' && error && error.code === 'EEXIST') {
|
|
710
|
+
process.stdout.write(JSON.stringify({ status: 'conflict' }));
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
throw error;
|
|
714
|
+
} finally {
|
|
715
|
+
await handle?.close();
|
|
716
|
+
}
|
|
717
|
+
} catch (error) {
|
|
718
|
+
process.stderr.write((error instanceof Error ? error.message : String(error)) + '\n');
|
|
719
|
+
process.exitCode = 1;
|
|
720
|
+
}
|
|
721
|
+
});
|
|
722
|
+
`,ss=64*1024*1024,as=128,eo="__kodaxTextFileMutationCall";function ds(e){let t=e.input[eo];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}i(ds,"encodedTextFileMutationCall");async function sr(e,t,n,r){let o=n.toolCallId??`text-file-${F()}`,s=await e.prepare({toolCallId:o,toolInput:{[eo]:{id:o,name:n.toolName,input:n.toolInput,path:n.path}},command:"kodax-internal-text-file-mutation",executable:process.execPath,args:["-e",is],cwd:t,env:fe(),fallbackToNormalExecution:!1,signal:n.signal});if(s===void 0)return;let l="not_started",a,c,f=!1,u=!1,m=!1,p,g,w=!1,x=!1,b=!1,y=i(()=>(p===void 0||m)&&(c===void 0||u)&&w&&x,"cleanupRecovered"),P=i(async v=>{if(p!==void 0&&!m){if(v&&g!==void 0)await Se(g.jobName);else{if((await ie(p)).status==="unknown")throw new Error("Sandboxed text mutation process tree is still not proven drained.");await g?.drained}m=!0}if(c!==void 0&&!u&&(await c.finishEffectProcess(),u=!0),f){w||(await s.cleanup({execution:l}),w=!0),x||(await c?.(),x=!0);return}x||(await c?.(),x=!0),w||(await s.cleanup({execution:l}),w=!0)},"recoverTextMutationCleanup"),A=i(()=>{b||y()||(b=!0,et(()=>P(!0),()=>{},(v,T)=>{T%10===0&&W({source:"runtime:text-file-mutation",level:"warn",message:"Automatic text-mutation cleanup recovery is still pending; its sandbox owner and filesystem fence remain closed.",detail:v})}))},"scheduleCleanupRecovery");try{if(s.fileSystemEffectPolicyKey!==void 0&&(c=await En(s.fileSystemEffectPolicyKey)),p=Gn(s.executable,[...s.args],{cwd:t,detached:process.platform!=="win32",env:s.env,shell:!1,stdio:["pipe","pipe","pipe"],windowsHide:!0,windowsVerbatimArguments:s.windowsVerbatimArguments}),l="started_or_unknown",Qe(p),c!==void 0){if(p.pid===void 0)throw new Error("Sandboxed text mutation process has no PID.");process.platform==="win32"&&(g=await en(p.pid)),await c.bindEffectProcess(g?.supervisorPid??p.pid,g!==void 0),f=!0}s.authorizeStart?.();let v=p.stdin;if(v===null)throw new Error("Sandboxed text mutation process has no stdin gate.");let T=Wt(p,n.signal,Xn,ss),$=new Promise((C,G)=>{v.end(JSON.stringify(r),Re=>{Re?G(Re):C()})}),[R]=await Promise.all([T,$]);if(g!==void 0)await g.drained;else if((await ie(p)).status==="unknown")throw new Error("Sandboxed text mutation process tree could not be proven drained.");if(m=!0,c!==void 0&&(await c.finishEffectProcess(),u=!0),R.exitCode!==0)throw new Error(`Sandboxed text mutation failed (${R.exitCode}): ${R.stderr.trim()||"no diagnostics"}`);let O=JSON.parse(R.stdout);if(O===null||typeof O!="object"||Array.isArray(O))throw new Error("Sandboxed text mutation returned an invalid response.");return O}catch(v){throw a=v,v}finally{let v=[];try{await P(!1)}catch(T){v.push(T)}if(y()||A(),v.length>0)throw new AggregateError([...a===void 0?[]:[a],...v],a===void 0?"Sandboxed text mutation cleanup failed.":"Sandboxed text mutation and cleanup both failed.")}}i(sr,"executePreparedTextFileMutation");function Ds(e){let t=d.resolve(e.workspaceRoot),n=j(t),r=i(a=>{let c=d.resolve(a),f=[];for(;;)try{return d.join(j.native(c),...f)}catch{let u=d.dirname(c);if(u===c)return;f.unshift(d.basename(c)),c=u}},"canonicalCandidate"),o=i(a=>{let c=d.resolve(a),f=r(c);return _(t,c)||f!==void 0&&_(n,f)?!0:f===void 0?!1:(e.additionalWorkspaceRoots?.()??[]).some(u=>_(d.resolve(u),f))},"canHandlePath"),s=new Map,l=os({workspaceRoot:e.workspaceRoot,...e.additionalWorkspaceRoots===void 0?{}:{additionalWorkspaceRoots:e.additionalWorkspaceRoots},shouldSandbox:i(async a=>{let c=ds(a);if(c===void 0||!o(c.path))return!1;let f=gn("sha256").update(c.name).update("\0").update(c.path).update("\0").update(JSON.stringify(c.input)).digest("hex"),u=s.get(c.id);if(u!==void 0&&u.fingerprint!==f)throw new Error(`Text mutation tool-call identity was reused with different input: ${c.id}`);if(u===void 0){let m=Promise.resolve(e.shouldSandbox({id:c.id,name:c.name,input:c.input})).catch(p=>{throw s.delete(c.id),p});u={fingerprint:f,selection:m},s.set(c.id,u),s.size>as&&s.delete(s.keys().next().value)}return u.selection},"shouldSandbox")});return{canHandlePath:o,async read(a){let c=await sr(l,t,a,{action:"read",path:a.path});if(c===void 0)return{status:"unavailable"};let f=c.snapshot;if(c.status!=="ok"||f===null||typeof f!="object")throw new Error("Sandboxed text read returned an invalid response.");let u=f;if(u.state!=="missing"&&u.state!=="present"||typeof u.content!="string"||typeof u.revision!="string"||typeof u.backupPath!="string"||!d.isAbsolute(u.backupPath)||!o(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(a){try{let c=await sr(l,t,a,{action:"write",path:a.path,content:a.content,expectedRevision:a.expectedRevision,createParentDirectories:a.createParentDirectories});if(c===void 0)return{status:"unavailable"};if(c.status==="written")return{status:"written"};if(c.status==="conflict")return{status:"conflict"};throw new Error("Sandboxed text write returned an invalid response.")}finally{a.toolCallId!==void 0&&s.delete(a.toolCallId)}}}}i(Ds,"createAsrtTextFileMutationSandbox");async function Bs(e){let t=await ce();if(!t.ready)throw new Error(`ASRT ${$e} is not ready: ${t.diagnostics.join(" ")||"run kodax sandbox setup"}`);let n=d.join(e.snapshotRoot,F()),r=d.join(n,"skills");await V(r,{recursive:!0,mode:448});try{let o=await ci(e,r),s=li(e.network),l=Promise.resolve();return{async run(a,c){let f=l,u;if(l=new Promise(m=>{u=m}),await f,c.signal?.aborted)throw u?.(),c.signal.reason??new Error("Sandboxed Skill script was cancelled.");try{if(a.args.length>64||a.args.some(w=>w.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 m=Ae(a.script,"Skill script"),p=o.get(`${a.skill}\0${m}`);if(!p)throw new Error("Skill script is not admitted by this Runtime binding.");if([".cmd",".bat"].includes(d.extname(p.snapshotPath).toLowerCase())&&a.args.some(w=>/[&|<>^]/.test(w)))throw new Error("Batch Skill script arguments cannot contain command operators.");let g=d.join(c.workspaceRoot,".kodax-a2a-script",F());try{await V(d.join(g,"inputs"),{recursive:!0,mode:448}),await V(d.join(g,"outputs"),{recursive:!0,mode:448}),await ki(c.workspaceRoot,g,a,e.workspaceAccess);let w=ui(p.snapshotPath),x=await bi({config:Ei(g,n,s,w.command),command:w.command,args:[...w.args,...a.args],cwd:g,env:fe(),endpoints:s},c.signal),b=await Ai(c.workspaceRoot,g,a,e.workspaceAccess,e.workspaceByteLimit);return JSON.stringify({stdout:x.trim(),outputs:b})}finally{await L(g,{recursive:!0,force:!0})}}finally{u?.()}},async dispose(){await l,await L(n,{recursive:!0,force:!0})}}}catch(o){throw await L(n,{recursive:!0,force:!0}),o}}i(Bs,"createAsrtSkillScriptRunner");export{$e as a,$o as b,Ts as c,$s as d,_s as e,Os as f,Ns as g,ce as h,ai as i,Me as j,Is as k,Ls as l,Fs as m,os as n,Ds as o,Bs as p};
|