@kodax-ai/kodax 0.7.83 → 0.7.85
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 +154 -4
- package/README.md +48 -26
- package/README_CN.md +26 -21
- package/dist/chunks/agent-OQ37XUWF.js +2 -0
- package/dist/chunks/argument-completer-IMRSIF2N.js +2 -0
- package/dist/chunks/chunk-2XJQNFVR.js +379 -0
- package/dist/chunks/chunk-3E4OSFP2.js +1279 -0
- package/dist/chunks/chunk-CDWYKVZC.js +482 -0
- package/dist/chunks/chunk-CZCEFGQG.js +412 -0
- package/dist/chunks/chunk-IA246OAN.js +679 -0
- package/dist/chunks/chunk-IWRNGH4M.js +319 -0
- package/dist/chunks/chunk-MJ4G5ZCW.js +2 -0
- package/dist/chunks/{chunk-RAQGGVIF.js → chunk-ODRLFQQH.js} +1 -1
- package/dist/chunks/chunk-RSOAHVUR.js +5 -0
- package/dist/chunks/chunk-RTFVMEF6.js +415 -0
- package/dist/chunks/{chunk-XB2JNLXH.js → chunk-SR4E5FQK.js} +2 -2
- package/dist/chunks/{chunk-HI6RCW5Y.js → chunk-TBBY2DKE.js} +2 -2
- package/dist/chunks/chunk-UH5WNJXF.js +92 -0
- package/dist/chunks/{chunk-6QILIBOU.js → chunk-ZVOXWLT6.js} +214 -201
- package/dist/chunks/compaction-config-3WLLNN57.js +2 -0
- package/dist/chunks/{construction-bootstrap-E4M3CY3N.js → construction-bootstrap-CZ6NWEWQ.js} +1 -1
- package/dist/chunks/dist-NFLLOZWF.js +2 -0
- package/dist/chunks/host-LWUSSCWH.js +2 -0
- package/dist/chunks/run-manager-PBMOVP7A.js +2 -0
- package/dist/chunks/utils-KFLK3EHJ.js +2 -0
- package/dist/index.d.ts +17 -15
- package/dist/index.js +2 -2
- package/dist/kodax_bootstrap.js +1 -1
- package/dist/kodax_cli.js +1975 -1564
- package/dist/kodax_resume.js +269 -90
- package/dist/runtime-worker.js +1824 -1419
- package/dist/sandbox-workspace-session.js +979 -66
- package/dist/sdk-a2a.d.ts +11 -10
- package/dist/sdk-a2a.js +9 -8
- package/dist/sdk-agent.d.ts +39 -299
- package/dist/sdk-agent.js +1 -1
- package/dist/sdk-coding.d.ts +103 -16
- package/dist/sdk-coding.js +1 -1
- package/dist/sdk-experimental-memory.d.ts +7 -20
- package/dist/sdk-experimental-memory.js +1 -1
- package/dist/sdk-mcp.js +1 -1
- package/dist/sdk-media.js +1 -1
- package/dist/sdk-repl.d.ts +14 -13
- package/dist/sdk-repl.js +2 -2
- package/dist/sdk-runtime.d.ts +64 -23
- package/dist/sdk-runtime.js +1 -1
- package/dist/sdk-sandbox.js +1 -1
- package/dist/sdk-session.d.ts +7 -6
- package/dist/sdk-session.js +1 -1
- package/dist/sdk-skills.d.ts +2 -2
- package/dist/sdk-skills.js +1 -1
- package/dist/semantic-worker.js +251 -64
- package/dist/types-chunks/{bash-prefix-extractor.d-CJM7OY-L.d.ts → bash-prefix-extractor.d-BnZQDirs.d.ts} +130 -13
- package/dist/types-chunks/{capsule.d-B7yoH4dM.d.ts → capsule.d-CN_iMqAS.d.ts} +2 -1
- package/dist/types-chunks/controller.d-A73Kf6tH.d.ts +105 -0
- package/dist/types-chunks/{controller.d-CYNuR2n9.d.ts → controller.d-Dzxz22X-.d.ts} +28 -1020
- package/dist/types-chunks/{guardrail.d-fM3mn4Op.d.ts → guardrail.d-BCkgaWT1.d.ts} +25 -19
- package/dist/types-chunks/{history-retrieval.d-BDI-ZMvY.d.ts → history-retrieval.d-Debbzn1z.d.ts} +1 -1
- package/dist/types-chunks/{public-api.d-i10kvYFs.d.ts → public-api.d-N6G6Jw8X.d.ts} +3 -2
- package/dist/types-chunks/{repl.d-Cs3eqGVT.d.ts → repl.d-BkTIOkJD.d.ts} +5 -5
- package/dist/types-chunks/review-inbox.d-DuZqFX-z.d.ts +221 -0
- package/dist/types-chunks/{run-manager.d-CodHf6rw.d.ts → run-manager.d-BS4lJfL3.d.ts} +1 -1
- package/dist/types-chunks/{sdk-session-CRXu5xNs.d.ts → sdk-session-DLkZTOc-.d.ts} +2 -2
- package/dist/types-chunks/{shell-command-sets.d-DfeSUjjM.d.ts → shell-command-sets.d-BrLw-WN9.d.ts} +3 -2
- package/dist/types-chunks/{types-Bf3Y3mW-.d.ts → types-PHjfwebT.d.ts} +62 -190
- package/dist/types-chunks/{types.d-BbtGlKZu.d.ts → types.d-BSPlmJqf.d.ts} +25 -6
- package/dist/types-chunks/{types.d-DIXZFauU.d.ts → types.d-Bo4fyMLu.d.ts} +1 -1
- package/dist/types-chunks/{types.d-DKs4tfSd.d.ts → types.d-Ch3BD97c.d.ts} +2 -2
- package/dist/types-chunks/types.d-DlLBRqZ9.d.ts +1057 -0
- package/dist/types-chunks/{utils.d-CgITiLyc.d.ts → utils.d-BI-kjuev.d.ts} +7 -4
- package/package.json +4 -2
- package/dist/chunks/agent-S7LMMTG7.js +0 -2
- package/dist/chunks/argument-completer-SQHG2LYE.js +0 -2
- package/dist/chunks/chunk-37RT45HT.js +0 -379
- package/dist/chunks/chunk-3DKQC7A2.js +0 -479
- package/dist/chunks/chunk-45E23YJI.js +0 -885
- package/dist/chunks/chunk-6UENDY33.js +0 -89
- package/dist/chunks/chunk-DSFHIUHZ.js +0 -655
- package/dist/chunks/chunk-DZUMH6GJ.js +0 -2
- package/dist/chunks/chunk-E7C4DRD2.js +0 -5
- package/dist/chunks/chunk-EVXIJPZ6.js +0 -218
- package/dist/chunks/chunk-KHEFUT6O.js +0 -5
- package/dist/chunks/chunk-LF2JBTBG.js +0 -319
- package/dist/chunks/chunk-TC2VHPG5.js +0 -348
- package/dist/chunks/chunk-URCS6CVP.js +0 -292
- package/dist/chunks/compaction-config-SSQ5NXUP.js +0 -2
- package/dist/chunks/dist-MIXP4ULB.js +0 -2
- package/dist/chunks/host-ZCPI7SMC.js +0 -2
- package/dist/chunks/run-manager-4RYG7HSP.js +0 -2
- package/dist/chunks/utils-7DKE2EKT.js +0 -2
- package/docs/SDK_EMBEDDER_GUIDE.md +0 -5735
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
+
import{k as Re}from"./chunk-ZVOXWLT6.js";import{Ia as U,Wa as ze,Ya as Ye,_a as oe,fb as ke,ib as Ae,t as E}from"./chunk-3E4OSFP2.js";import{a as i}from"./chunk-ONUPGMER.js";import{spawn as ir,spawnSync as Be}from"node:child_process";import{createHash as Fe,randomUUID as F}from"node:crypto";import{once as Ze}from"node:events";import{constants as $r,lstatSync as Tr,readdirSync as ar,realpathSync as me,statSync as he,writeSync as jt}from"node:fs";import{copyFile as cr,lstat as Cr,mkdir as W,readFile as z,realpath as ie,rename as Pr,rm as j,stat as we,writeFile as Y}from"node:fs/promises";import{createRequire as _r}from"node:module";import{createServer as Wr}from"node:net";import Z from"node:os";import o from"node:path";import Or from"node:readline";import{fileURLToPath as Qe,pathToFileURL as dr}from"node:url";import{DEFAULT_WINDOWS_PROXY_PORT_RANGE as Nr,SandboxManager as Ee,getSrtWinPath as Dr,getWindowsSandboxUserStatus as je,grantWindowsAcl as Lr,installWindowsSandbox as Ir,resolveSrtWin as Br,revokeWindowsAcl as lr}from"@anthropic-ai/sandbox-runtime";var V="0.0.65";function Fr(){let e=process.platform==="win32"?"windows-restricted-user":process.platform==="darwin"?"macos-seatbelt":process.platform==="linux"?"linux-bubblewrap":"unsupported";return{version:1,asrtVersion:V,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"}}i(Fr,"sandboxRuntimeCapability");var Me=1048576,qe=12e4,Ke=_r(import.meta.url),ur=process.env.KODAX_BUNDLED==="true"?void 0:dr(Ke.resolve("@anthropic-ai/sandbox-runtime")).href,jr=new Set([".ssh",".aws",".azure",".gnupg",".kodax",".agents",".codex",".claude",".gemini",".direnv",".terraform.d"]),Mr=new Set([".env",".envrc",".pgpass",".npmrc",".pypirc","credentials","id_rsa","id_ed25519"]),qr=[".ssh",".aws",".azure",".gnupg",".kube",".docker",".kodax",".agents",".codex",".claude",".gemini",".direnv",".terraform.d",o.join(".cargo","credentials.toml"),o.join(".config","gcloud"),o.join(".config","gh"),o.join(".config","openai"),o.join(".config","anthropic"),".gitconfig",o.join(".config","git","config"),".terraformrc",o.join(".config","pypoetry","auth.toml"),".condarc",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",o.join(".config","fish","config.fish"),o.join(".config","fish","fish_variables"),".bash_history",".zsh_history",o.join(".m2","settings.xml"),o.join(".m2","settings-security.xml"),o.join(".gradle","gradle.properties"),o.join(".nuget","NuGet","NuGet.Config"),o.join(".pip","pip.conf"),o.join(".config","pip","pip.conf"),o.join(".cache","huggingface","token"),o.join(".huggingface","token"),o.join(".config","rclone","rclone.conf"),o.join(".local","share","keyrings"),o.join("Library","Keychains"),o.join("AppData","Roaming","Microsoft","Protect"),o.join("AppData","Roaming","Microsoft","Credentials"),o.join("AppData","Roaming","Microsoft","Vault"),o.join("AppData","Local","Microsoft","Credentials"),o.join("AppData","Local","Microsoft","Protect"),o.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"],Kr=["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"],Xr=String.raw`
|
|
3
|
+
$ErrorActionPreference = 'Stop'
|
|
4
|
+
$payload = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
5
|
+
$mutex = [System.Threading.Mutex]::new($false, 'Local\KodaXAsrtAclGuard-v1')
|
|
6
|
+
$held = $false
|
|
7
|
+
$missing = [System.Collections.Generic.List[string]]::new()
|
|
8
|
+
function Test-KodaXAsrtAclRule($acl, $sidValue, $rights, $inheritance) {
|
|
9
|
+
foreach ($rule in $acl.Access) {
|
|
10
|
+
try {
|
|
11
|
+
$ruleSid = $rule.IdentityReference.Translate(
|
|
12
|
+
[System.Security.Principal.SecurityIdentifier]
|
|
13
|
+
).Value
|
|
14
|
+
} catch {
|
|
15
|
+
continue
|
|
16
|
+
}
|
|
17
|
+
if (
|
|
18
|
+
$ruleSid -eq $sidValue -and
|
|
19
|
+
$rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Deny -and
|
|
20
|
+
-not $rule.IsInherited -and
|
|
21
|
+
$rule.InheritanceFlags -eq $inheritance -and
|
|
22
|
+
$rule.PropagationFlags -eq [System.Security.AccessControl.PropagationFlags]::None -and
|
|
23
|
+
(([int]$rule.FileSystemRights -band [int]$rights) -eq [int]$rights)
|
|
24
|
+
) {
|
|
25
|
+
return $true
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return $false
|
|
29
|
+
}
|
|
30
|
+
function Test-KodaXParentDeleteChildSafe($acl, $tokenSidValues) {
|
|
31
|
+
foreach ($rule in $acl.Access) {
|
|
32
|
+
try {
|
|
33
|
+
$ruleSid = $rule.IdentityReference.Translate(
|
|
34
|
+
[System.Security.Principal.SecurityIdentifier]
|
|
35
|
+
).Value
|
|
36
|
+
} catch {
|
|
37
|
+
continue
|
|
38
|
+
}
|
|
39
|
+
if (
|
|
40
|
+
$tokenSidValues -contains $ruleSid -and
|
|
41
|
+
$rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Deny -and
|
|
42
|
+
($rule.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -eq 0 -and
|
|
43
|
+
(([int]$rule.FileSystemRights -band [int][System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles) -ne 0)
|
|
44
|
+
) {
|
|
45
|
+
return $true
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
foreach ($rule in $acl.Access) {
|
|
49
|
+
try {
|
|
50
|
+
$ruleSid = $rule.IdentityReference.Translate(
|
|
51
|
+
[System.Security.Principal.SecurityIdentifier]
|
|
52
|
+
).Value
|
|
53
|
+
} catch {
|
|
54
|
+
continue
|
|
55
|
+
}
|
|
56
|
+
if (
|
|
57
|
+
$tokenSidValues -contains $ruleSid -and
|
|
58
|
+
$rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and
|
|
59
|
+
($rule.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -eq 0 -and
|
|
60
|
+
(([int]$rule.FileSystemRights -band [int][System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles) -ne 0)
|
|
61
|
+
) {
|
|
62
|
+
return $false
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return $true
|
|
66
|
+
}
|
|
67
|
+
function Test-KodaXAsrtAclRuleReadsData($acl, $sidValue) {
|
|
68
|
+
foreach ($rule in $acl.Access) {
|
|
69
|
+
try {
|
|
70
|
+
$ruleSid = $rule.IdentityReference.Translate(
|
|
71
|
+
[System.Security.Principal.SecurityIdentifier]
|
|
72
|
+
).Value
|
|
73
|
+
} catch {
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
if (
|
|
77
|
+
$ruleSid -eq $sidValue -and
|
|
78
|
+
$rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Deny -and
|
|
79
|
+
-not $rule.IsInherited -and
|
|
80
|
+
$rule.PropagationFlags -eq [System.Security.AccessControl.PropagationFlags]::None -and
|
|
81
|
+
(([int]$rule.FileSystemRights -band ([int][System.Security.AccessControl.FileSystemRights]::ReadAndExecute -bor [int][System.Security.AccessControl.FileSystemRights]::Synchronize)) -ne 0)
|
|
82
|
+
) {
|
|
83
|
+
return $true
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return $false
|
|
87
|
+
}
|
|
88
|
+
function Add-KodaXAsrtAclRule($target, $sid, $rights, $inheritance, $ruleText) {
|
|
89
|
+
$acl = Get-Acl -LiteralPath $target
|
|
90
|
+
if (Test-KodaXAsrtAclRule $acl $sid.Value $rights $inheritance) {
|
|
91
|
+
return
|
|
92
|
+
}
|
|
93
|
+
$principal = '*' + $sid.Value
|
|
94
|
+
& "$env:SystemRoot\System32\icacls.exe" $target '/deny' "$($principal):$ruleText" | Out-Null
|
|
95
|
+
if ($LASTEXITCODE -ne 0) {
|
|
96
|
+
throw "icacls failed to install a KodaX sandbox guard on $target."
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function Add-KodaXAsrtWriteAclRule($target, $sid, $rights, $inheritance) {
|
|
100
|
+
$acl = Get-Acl -LiteralPath $target
|
|
101
|
+
if (Test-KodaXAsrtAclRule $acl $sid.Value $rights $inheritance) {
|
|
102
|
+
return
|
|
103
|
+
}
|
|
104
|
+
$rule = [System.Security.AccessControl.FileSystemAccessRule]::new(
|
|
105
|
+
$sid,
|
|
106
|
+
$rights,
|
|
107
|
+
$inheritance,
|
|
108
|
+
[System.Security.AccessControl.PropagationFlags]::None,
|
|
109
|
+
[System.Security.AccessControl.AccessControlType]::Deny
|
|
110
|
+
)
|
|
111
|
+
[void]$acl.AddAccessRule($rule)
|
|
112
|
+
Set-Acl -LiteralPath $target -AclObject $acl
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
try {
|
|
116
|
+
$held = $mutex.WaitOne(10000)
|
|
117
|
+
} catch [System.Threading.AbandonedMutexException] {
|
|
118
|
+
$held = $true
|
|
119
|
+
}
|
|
120
|
+
if (-not $held) {
|
|
121
|
+
throw 'Timed out waiting for the KodaX ASRT ACL guard mutex.'
|
|
122
|
+
}
|
|
123
|
+
$sid = [System.Security.Principal.SecurityIdentifier]::new([string]$payload.sid)
|
|
124
|
+
$tokenSidValues = @($payload.tokenSids | ForEach-Object { [string]$_ })
|
|
125
|
+
foreach ($entry in $payload.paths) {
|
|
126
|
+
$target = [System.IO.Path]::GetFullPath([string]$entry.path)
|
|
127
|
+
if (-not (Test-Path -LiteralPath $target)) {
|
|
128
|
+
throw "ACL guard target disappeared before it could be protected: $target"
|
|
129
|
+
}
|
|
130
|
+
$inheritance = if ([bool]$entry.directory) {
|
|
131
|
+
[System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor
|
|
132
|
+
[System.Security.AccessControl.InheritanceFlags]::ObjectInherit
|
|
133
|
+
} else {
|
|
134
|
+
[System.Security.AccessControl.InheritanceFlags]::None
|
|
135
|
+
}
|
|
136
|
+
$writeRights = [System.Security.AccessControl.FileSystemRights]::Write -bor
|
|
137
|
+
[System.Security.AccessControl.FileSystemRights]::Delete -bor
|
|
138
|
+
[System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor
|
|
139
|
+
[System.Security.AccessControl.FileSystemRights]::TakeOwnership
|
|
140
|
+
if ([bool]$entry.directory) {
|
|
141
|
+
$writeRights = $writeRights -bor [System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles
|
|
142
|
+
}
|
|
143
|
+
$targetRights = if ([string]$entry.mode -eq 'write') {
|
|
144
|
+
$writeRights
|
|
145
|
+
} else {
|
|
146
|
+
[System.Security.AccessControl.FileSystemRights]::FullControl
|
|
147
|
+
}
|
|
148
|
+
$parent = [System.IO.Path]::GetDirectoryName($target)
|
|
149
|
+
$targetAcl = Get-Acl -LiteralPath $target
|
|
150
|
+
$targetReady = Test-KodaXAsrtAclRule $targetAcl $sid.Value $targetRights $inheritance
|
|
151
|
+
$targetTooBroad = [string]$entry.mode -eq 'write' -and (Test-KodaXAsrtAclRuleReadsData $targetAcl $sid.Value)
|
|
152
|
+
if ($targetTooBroad) {
|
|
153
|
+
$targetReady = $false
|
|
154
|
+
}
|
|
155
|
+
$parentReady = -not $parent -or $parent -eq $target -or -not (Test-Path -LiteralPath $parent)
|
|
156
|
+
if (-not $parentReady) {
|
|
157
|
+
$parentAcl = Get-Acl -LiteralPath $parent
|
|
158
|
+
$parentReady = (Test-KodaXAsrtAclRule $parentAcl $sid.Value ([System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles) ([System.Security.AccessControl.InheritanceFlags]::None)) -or (Test-KodaXParentDeleteChildSafe $parentAcl $tokenSidValues)
|
|
159
|
+
}
|
|
160
|
+
if (-not [bool]$payload.install) {
|
|
161
|
+
if (-not $targetReady -or -not $parentReady) {
|
|
162
|
+
[void]$missing.Add($target)
|
|
163
|
+
}
|
|
164
|
+
continue
|
|
165
|
+
}
|
|
166
|
+
if ($targetTooBroad) {
|
|
167
|
+
$principal = '*' + $sid.Value
|
|
168
|
+
& "$env:SystemRoot\System32\icacls.exe" $target '/remove:d' $principal | Out-Null
|
|
169
|
+
if ($LASTEXITCODE -ne 0) {
|
|
170
|
+
throw "icacls failed to remove an obsolete KodaX sandbox guard from $target."
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (-not $targetReady) {
|
|
174
|
+
if ([string]$entry.mode -eq 'write') {
|
|
175
|
+
Add-KodaXAsrtWriteAclRule $target $sid $targetRights $inheritance
|
|
176
|
+
} else {
|
|
177
|
+
$targetRule = if ([bool]$entry.directory) { '(OI)(CI)(F)' } else { '(F)' }
|
|
178
|
+
Add-KodaXAsrtAclRule $target $sid $targetRights $inheritance $targetRule
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (-not $parentReady) {
|
|
182
|
+
Add-KodaXAsrtAclRule $parent $sid ([System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles) ([System.Security.AccessControl.InheritanceFlags]::None) '(DC)'
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
[Console]::Out.Write((@{ missing = @($missing) } | ConvertTo-Json -Compress))
|
|
186
|
+
} finally {
|
|
187
|
+
if ($held) {
|
|
188
|
+
[void]$mutex.ReleaseMutex()
|
|
189
|
+
}
|
|
190
|
+
$mutex.Dispose()
|
|
191
|
+
}
|
|
192
|
+
`,_e=new Set,pr=new Set,er=JSON.stringify(Ye),$e=JSON.stringify(ze),Gr=String.raw`
|
|
193
|
+
const { spawn } = require('node:child_process');
|
|
194
|
+
const { writeSync } = require('node:fs');
|
|
195
|
+
const input = JSON.parse(Buffer.from(process.argv[2], 'base64').toString('utf8'));
|
|
196
|
+
const child = spawn(input.command, input.args, {
|
|
197
|
+
cwd: input.cwd,
|
|
198
|
+
env: process.env,
|
|
199
|
+
shell: false,
|
|
200
|
+
stdio: ['inherit', 'inherit', 'pipe'],
|
|
201
|
+
windowsHide: true,
|
|
202
|
+
});
|
|
203
|
+
const stop = (signal) => child.kill(signal);
|
|
204
|
+
process.once('SIGINT', () => stop('SIGINT'));
|
|
205
|
+
process.once('SIGTERM', () => stop('SIGTERM'));
|
|
206
|
+
child.once('spawn', () => {
|
|
207
|
+
writeSync(2, input.targetStartedMarker);
|
|
208
|
+
child.stderr.pipe(process.stderr);
|
|
209
|
+
});
|
|
210
|
+
child.once('error', (error) => {
|
|
211
|
+
process.stderr.write((error instanceof Error ? error.message : String(error)) + '\n');
|
|
212
|
+
process.exitCode = 1;
|
|
213
|
+
});
|
|
214
|
+
child.once('exit', (code, signal) => {
|
|
215
|
+
process.exitCode = signal ? 1 : code ?? 1;
|
|
216
|
+
});
|
|
217
|
+
`,Hr="eval(Buffer.from(process.argv[1],'base64').toString('utf8'))",Ur=JSON.stringify(Hr),Jr=Buffer.from(Gr,"utf8").toString("base64"),Vr=JSON.stringify(Jr),fr=String.raw`
|
|
218
|
+
import { spawn } from 'node:child_process';
|
|
219
|
+
import { randomUUID } from 'node:crypto';
|
|
220
|
+
import { readFile, rm, writeFile } from 'node:fs/promises';
|
|
221
|
+
let SandboxManager;
|
|
222
|
+
const request = JSON.parse(await readFile(process.argv[2], 'utf8'));
|
|
223
|
+
await rm(process.argv[2], { force: true });
|
|
224
|
+
const targetStartedMarker = request.targetStartedMarker
|
|
225
|
+
?? '\u0000KODAX_ASRT_TARGET_STARTED:' + randomUUID() + '\u0000\n';
|
|
226
|
+
const endpoints = new Set(request.endpoints.map((item) => item.host.toLowerCase() + ':' + item.port));
|
|
227
|
+
const callback = request.allowAllNetwork === true
|
|
228
|
+
? async () => true
|
|
229
|
+
: request.endpoints.length === 0
|
|
230
|
+
? undefined
|
|
231
|
+
: async ({ host, port }) => endpoints.has(host.toLowerCase() + ':' + port);
|
|
232
|
+
const withWindowsChildEnvironment = (argv, environment) => {
|
|
233
|
+
const separator = argv.lastIndexOf('--');
|
|
234
|
+
if (separator < 0) throw new Error('ASRT Windows wrapper omitted its child separator.');
|
|
235
|
+
const controlled = new Set();
|
|
236
|
+
for (let index = 0; index < separator - 1; index += 1) {
|
|
237
|
+
if (argv[index] !== '--env') continue;
|
|
238
|
+
const name = argv[index + 1].split('=', 1)[0];
|
|
239
|
+
if (name) controlled.add(name.toLowerCase());
|
|
240
|
+
}
|
|
241
|
+
const injected = [];
|
|
242
|
+
for (const [name, value] of Object.entries(environment ?? {})) {
|
|
243
|
+
if (value === undefined) continue;
|
|
244
|
+
if (!name || name.includes('=') || name.includes('\0') || value.includes('\0')) {
|
|
245
|
+
throw new Error('Invalid environment entry for ASRT Windows child.');
|
|
246
|
+
}
|
|
247
|
+
const normalized = name.toLowerCase();
|
|
248
|
+
if (controlled.has(normalized) && normalized !== 'path' && normalized !== 'pathext') continue;
|
|
249
|
+
injected.push('--env', name + '=' + value);
|
|
250
|
+
}
|
|
251
|
+
const result = [...argv.slice(0, separator), ...injected, ...argv.slice(separator)];
|
|
252
|
+
const estimate = result.reduce((size, value) => size + value.length + 3, 0);
|
|
253
|
+
if (estimate > 30000) throw new Error('ASRT Windows child environment exceeds the CreateProcess command-line limit.');
|
|
254
|
+
return result;
|
|
255
|
+
};
|
|
256
|
+
const writeObservation = async (observation) => {
|
|
257
|
+
if (typeof request.observationFile !== 'string') return;
|
|
258
|
+
await writeFile(request.observationFile, JSON.stringify(observation), { mode: 0o600 });
|
|
259
|
+
};
|
|
260
|
+
const waitForTarget = (target, observation) => {
|
|
261
|
+
const marker = Buffer.from(targetStartedMarker, 'utf8');
|
|
262
|
+
let pending = Buffer.alloc(0);
|
|
263
|
+
let diagnostic = Buffer.alloc(0);
|
|
264
|
+
let processError;
|
|
265
|
+
let targetStarted = false;
|
|
266
|
+
let observationWrite = Promise.resolve();
|
|
267
|
+
return new Promise((resolve, reject) => {
|
|
268
|
+
let settled = false;
|
|
269
|
+
const finish = (result) => {
|
|
270
|
+
if (settled) return;
|
|
271
|
+
settled = true;
|
|
272
|
+
void observationWrite.then(() => resolve(result), reject);
|
|
273
|
+
};
|
|
274
|
+
target.stderr.on('data', (chunk) => {
|
|
275
|
+
if (targetStarted) {
|
|
276
|
+
process.stderr.write(chunk);
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
pending = Buffer.concat([pending, Buffer.from(chunk)]);
|
|
280
|
+
const markerOffset = pending.indexOf(marker);
|
|
281
|
+
if (markerOffset >= 0) {
|
|
282
|
+
targetStarted = true;
|
|
283
|
+
const suffix = pending.subarray(markerOffset + marker.length);
|
|
284
|
+
pending = Buffer.alloc(0);
|
|
285
|
+
diagnostic = Buffer.alloc(0);
|
|
286
|
+
observationWrite = writeObservation(observation).catch(() => undefined);
|
|
287
|
+
if (suffix.length > 0) process.stderr.write(suffix);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
const retained = Math.max(0, marker.length - 1);
|
|
291
|
+
if (pending.length > retained) {
|
|
292
|
+
diagnostic = Buffer.concat([
|
|
293
|
+
diagnostic,
|
|
294
|
+
pending.subarray(0, pending.length - retained),
|
|
295
|
+
]).subarray(-65536);
|
|
296
|
+
pending = pending.subarray(pending.length - retained);
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
target.once('error', (error) => {
|
|
300
|
+
processError = error instanceof Error ? error.message : String(error);
|
|
301
|
+
});
|
|
302
|
+
target.once('close', (exitCode, signal) => {
|
|
303
|
+
const preTarget = Buffer.concat([diagnostic, pending]).toString('utf8').trim();
|
|
304
|
+
finish({
|
|
305
|
+
exitCode: signal ? 1 : exitCode ?? 1,
|
|
306
|
+
targetStarted,
|
|
307
|
+
diagnostic: preTarget || processError || undefined,
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
});
|
|
311
|
+
};
|
|
312
|
+
let child;
|
|
313
|
+
let targetStarted = false;
|
|
314
|
+
let normalFallbackAttempted = false;
|
|
315
|
+
const runDirect = async () => {
|
|
316
|
+
const internalElectronNode = request.command === process.execPath && process.versions.electron !== undefined;
|
|
317
|
+
const directArgs = internalElectronNode
|
|
318
|
+
? ['--import', ${er}, ...request.args]
|
|
319
|
+
: request.args;
|
|
320
|
+
const directEnv = internalElectronNode
|
|
321
|
+
? { ...request.env, [${$e}]: '1' }
|
|
322
|
+
: request.env;
|
|
323
|
+
child = spawn(request.command, directArgs, {
|
|
324
|
+
cwd: request.cwd,
|
|
325
|
+
env: directEnv,
|
|
326
|
+
shell: false,
|
|
327
|
+
stdio: 'inherit',
|
|
328
|
+
windowsHide: true,
|
|
329
|
+
});
|
|
330
|
+
return await new Promise((resolve, reject) => {
|
|
331
|
+
child.once('error', reject);
|
|
332
|
+
child.once('exit', (exitCode, signal) => resolve(signal ? 1 : exitCode ?? 1));
|
|
333
|
+
});
|
|
334
|
+
};
|
|
335
|
+
try {
|
|
336
|
+
if (request.wrappedInvocation) {
|
|
337
|
+
const wrapped = request.wrappedInvocation;
|
|
338
|
+
child = spawn(wrapped.executable, wrapped.args, {
|
|
339
|
+
cwd: request.cwd,
|
|
340
|
+
env: wrapped.env,
|
|
341
|
+
shell: wrapped.shell,
|
|
342
|
+
stdio: ['inherit', 'inherit', 'pipe'],
|
|
343
|
+
windowsHide: true,
|
|
344
|
+
});
|
|
345
|
+
const result = await waitForTarget(child, {
|
|
346
|
+
version: 1,
|
|
347
|
+
state: 'applied',
|
|
348
|
+
backend: request.observationBackend ?? 'unsupported',
|
|
349
|
+
policyId: 'kodax-workspace-shell-v1',
|
|
350
|
+
});
|
|
351
|
+
targetStarted = result.targetStarted;
|
|
352
|
+
if (request.fallbackToNormalExecution === true && !targetStarted) {
|
|
353
|
+
await writeObservation({
|
|
354
|
+
version: 1,
|
|
355
|
+
state: 'fallback',
|
|
356
|
+
reason: 'backend_failed',
|
|
357
|
+
execution: 'normal_permission_policy',
|
|
358
|
+
}).catch(() => undefined);
|
|
359
|
+
normalFallbackAttempted = true;
|
|
360
|
+
process.exitCode = await runDirect();
|
|
361
|
+
} else {
|
|
362
|
+
if (!targetStarted && result.diagnostic) {
|
|
363
|
+
process.stderr.write(result.diagnostic + '\n');
|
|
364
|
+
}
|
|
365
|
+
process.exitCode = result.exitCode;
|
|
366
|
+
}
|
|
367
|
+
} else {
|
|
368
|
+
({ SandboxManager } = await import(process.argv[1]));
|
|
369
|
+
const bootstrap = request.bootstrapCommand ?? 'node';
|
|
370
|
+
const bootstrapIsAbsolute = /^(?:[A-Za-z]:[\\/]|\\\\)/.test(bootstrap);
|
|
371
|
+
const bootstrapIsElectronNode = bootstrap === process.execPath
|
|
372
|
+
&& process.versions.electron !== undefined;
|
|
373
|
+
const config = process.platform === 'win32' && bootstrapIsAbsolute
|
|
374
|
+
? {
|
|
375
|
+
...request.config,
|
|
376
|
+
filesystem: {
|
|
377
|
+
...request.config.filesystem,
|
|
378
|
+
allowRead: [...new Set([...request.config.filesystem.allowRead, bootstrap])],
|
|
379
|
+
},
|
|
380
|
+
}
|
|
381
|
+
: request.config;
|
|
382
|
+
await SandboxManager.initialize(config, callback);
|
|
383
|
+
const quote = (value) => process.platform === 'win32'
|
|
384
|
+
? '"' + value.replaceAll('"', '""') + '"'
|
|
385
|
+
: "'" + value.replaceAll("'", "'\"'\"'") + "'";
|
|
386
|
+
const internalElectronNode = request.command === process.execPath && process.versions.electron !== undefined;
|
|
387
|
+
const childArgs = internalElectronNode
|
|
388
|
+
? ['--import', ${er}, ...request.args]
|
|
389
|
+
: request.args;
|
|
390
|
+
const command = [
|
|
391
|
+
quote(bootstrap),
|
|
392
|
+
'-e',
|
|
393
|
+
quote(${Ur}),
|
|
394
|
+
${Vr},
|
|
395
|
+
Buffer.from(JSON.stringify({
|
|
396
|
+
command: request.command,
|
|
397
|
+
args: childArgs,
|
|
398
|
+
cwd: request.cwd,
|
|
399
|
+
targetStartedMarker,
|
|
400
|
+
}), 'utf8').toString('base64'),
|
|
401
|
+
].join(' ');
|
|
402
|
+
if (process.platform === 'win32') {
|
|
403
|
+
const wrapped = await SandboxManager.wrapWithSandboxArgv(command, 'cmd', undefined, undefined, request.cwd);
|
|
404
|
+
const requestedEnv = internalElectronNode || bootstrapIsElectronNode
|
|
405
|
+
? { ...request.env, [${$e}]: '1' }
|
|
406
|
+
: request.env;
|
|
407
|
+
const childArgv = withWindowsChildEnvironment(wrapped.argv, requestedEnv);
|
|
408
|
+
child = spawn(childArgv[0], childArgv.slice(1), {
|
|
409
|
+
cwd: request.cwd,
|
|
410
|
+
env: wrapped.env,
|
|
411
|
+
shell: false,
|
|
412
|
+
stdio: ['inherit', 'inherit', 'pipe'],
|
|
413
|
+
windowsHide: true,
|
|
414
|
+
});
|
|
415
|
+
} else {
|
|
416
|
+
const wrapped = await SandboxManager.wrapWithSandbox(command);
|
|
417
|
+
const childEnv = internalElectronNode || bootstrapIsElectronNode
|
|
418
|
+
? { ...request.env, [${$e}]: '1' }
|
|
419
|
+
: request.env;
|
|
420
|
+
child = spawn(wrapped, {
|
|
421
|
+
cwd: request.cwd,
|
|
422
|
+
env: childEnv,
|
|
423
|
+
shell: true,
|
|
424
|
+
stdio: ['inherit', 'inherit', 'pipe'],
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
const stop = () => child?.kill('SIGTERM');
|
|
428
|
+
process.once('SIGINT', stop);
|
|
429
|
+
process.once('SIGTERM', stop);
|
|
430
|
+
const result = await waitForTarget(child, {
|
|
431
|
+
version: 1,
|
|
432
|
+
state: 'applied',
|
|
433
|
+
backend: request.observationBackend ?? 'unsupported',
|
|
434
|
+
policyId: 'kodax-workspace-shell-v1',
|
|
435
|
+
});
|
|
436
|
+
targetStarted = result.targetStarted;
|
|
437
|
+
try { SandboxManager.cleanupAfterCommand(); } catch {}
|
|
438
|
+
await SandboxManager.reset().catch(() => undefined);
|
|
439
|
+
if (request.fallbackToNormalExecution === true && !targetStarted) {
|
|
440
|
+
await writeObservation({
|
|
441
|
+
version: 1,
|
|
442
|
+
state: 'fallback',
|
|
443
|
+
reason: 'backend_failed',
|
|
444
|
+
execution: 'normal_permission_policy',
|
|
445
|
+
}).catch(() => undefined);
|
|
446
|
+
normalFallbackAttempted = true;
|
|
447
|
+
process.exitCode = await runDirect();
|
|
448
|
+
} else {
|
|
449
|
+
if (!targetStarted && result.diagnostic) {
|
|
450
|
+
process.stderr.write(result.diagnostic + '\n');
|
|
451
|
+
}
|
|
452
|
+
process.exitCode = result.exitCode;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
} catch (error) {
|
|
456
|
+
await SandboxManager?.reset().catch(() => undefined);
|
|
457
|
+
if (
|
|
458
|
+
request.fallbackToNormalExecution === true
|
|
459
|
+
&& !targetStarted
|
|
460
|
+
&& !normalFallbackAttempted
|
|
461
|
+
) {
|
|
462
|
+
try {
|
|
463
|
+
await writeObservation({
|
|
464
|
+
version: 1,
|
|
465
|
+
state: 'fallback',
|
|
466
|
+
reason: 'backend_failed',
|
|
467
|
+
execution: 'normal_permission_policy',
|
|
468
|
+
}).catch(() => undefined);
|
|
469
|
+
normalFallbackAttempted = true;
|
|
470
|
+
process.exitCode = await runDirect();
|
|
471
|
+
} catch (fallbackError) {
|
|
472
|
+
process.stderr.write((fallbackError instanceof Error ? fallbackError.message : String(fallbackError)) + '\n');
|
|
473
|
+
process.exitCode = 1;
|
|
474
|
+
}
|
|
475
|
+
} else {
|
|
476
|
+
process.stderr.write((error instanceof Error ? error.message : String(error)) + '\n');
|
|
477
|
+
process.exitCode = 1;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
`,J,le=0,zr=3e4,se,ge,X;function ye(e){return e instanceof Error?e.message:String(e)}i(ye,"errorText");function We(e,...r){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&r.includes(e.code)}i(We,"isFileSystemError");async function rr(e){try{return await z(e)}catch(r){if(We(r,"ENOENT"))return;throw r}}i(rr,"readFileIfPresent");async function Yr(e,r){let t=await rr(r);if(t?.equals(e))return;if(t!==void 0)throw new Error(`Prepared Windows sandbox runner failed integrity verification: ${r}.`);let n=`${r}.${process.pid}.${F()}.tmp`;try{await Y(n,e,{flag:"wx",mode:448});try{await Pr(n,r)}catch(s){if(!(await rr(r))?.equals(e))throw s}}finally{await j(n,{force:!0})}}i(Yr,"installWindowsRunnerCopy");async function Oe(){if(se===void 0){let e=(async()=>{let r=await z(Dr()),t=Fe("sha256").update(r).digest("hex").slice(0,16),n=o.join(o.resolve(U()),"sandbox-runtime","runner",V,process.arch,t),s=o.join(n,"srt-win.exe");await W(n,{recursive:!0,mode:448}),await Yr(r,s);let a={path:s,directory:n,srtWin:Br({path:s})};return ge=a,a})();se=e,e.catch(()=>{se===e&&(se=void 0,ge=void 0)})}return se}i(Oe,"prepareWindowsSandboxRunner");function be(){if(process.platform!=="win32")throw new Error("A prepared Windows sandbox runner was requested on a non-Windows platform.");if(ge===void 0)throw new Error("Windows sandbox runner is not prepared; run the sandbox readiness check first.");return ge}i(be,"requirePreparedWindowsRunner");function Te(){X!==void 0&&(lr({sandboxUserSid:X.sandboxUserSid,holderPid:process.pid,srtWin:X.runner.srtWin}),X=void 0)}i(Te,"releasePreparedWindowsRunnerGrant");function Zr(e,r){if(!(X?.runner.path===e.path&&X.sandboxUserSid===r)){process.removeListener("exit",Te),Te();try{Lr({read:[e.directory,e.path],write:[],sandboxUserSid:r,holderPid:process.pid,srtWin:e.srtWin})}catch(t){try{lr({sandboxUserSid:r,holderPid:process.pid,srtWin:e.srtWin})}catch(n){throw new AggregateError([t,n],"Windows sandbox runner ACL grant failed and its partial grant could not be revoked.")}throw t}X={runner:e,sandboxUserSid:r},process.once("exit",Te)}}i(Zr,"retainPreparedWindowsRunnerGrant");async function Qr(){let[e,r]=Nr;for(let t=0;t<5;t+=1){let n=Wr();n.listen(0,"127.0.0.1"),await Ze(n,"listening");let s=n.address();if(typeof s=="object"&&s!==null&&(s.port<e||s.port>r))return{server:n,target:`127.0.0.1:${s.port}`};let a=Ze(n,"close");n.close(),await a}throw new Error(`[wfp_probe_bind_failed] Could not bind a loopback listener outside the Windows sandbox proxy range [${e},${r}].`)}i(Qr,"bindWindowsWfpProbe");function tr(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(tr,"windowsRunnerFailureCode");function et(e){return We(e,"ETIMEDOUT")?"wfp_probe_timeout":We(e,"EACCES","EPERM")?"runner_launch_access_denied":"runner_spawn_failed"}i(et,"windowsRunnerSpawnFailureCode");async function rt(e){let{server:r,target:t}=await Qr();try{let n=Be(e.srtWin.exe,[...e.srtWin.prependArgs,"wfp","verify","--target",t],{cwd:e.directory,encoding:"utf8",timeout:3e4,windowsHide:!0}),s=(n.stderr??"").trim();if(n.error)throw new Error(`[${et(n.error)}] Windows sandbox runner failed to start: ${n.error.message}`);let a;try{a=JSON.parse((n.stdout??"").trim())}catch{let d=n.status===null?"wfp_probe_timeout":tr(s);throw new Error(`[${d}] Windows sandbox WFP probe exited ${String(n.status)}${n.signal?` (signal ${n.signal})`:""} with unparseable output; stderr: ${s||"(empty)"}.`)}if(n.status===3)throw new Error(`[wfp_fence_inactive] Direct outbound access to ${String(a.target??t)} succeeded. Run "kodax sandbox setup" to reinstall the Windows network policy.`);if(n.status!==0||a.egress_probe!=="blocked")throw new Error(`[${tr(s)}] Windows sandbox WFP probe to ${String(a.target??t)} was ${String(a.egress_probe)} (exit ${String(n.status)}): ${s||"(empty stderr)"}.`)}finally{r.close()}}i(rt,"verifyPreparedWindowsWfp");function mr(e){let r=[];return e.provisioned||r.push("Windows sandbox account does not exist."),e.sid||r.push("Windows sandbox account SID is unavailable."),(!e.groupExists||!e.groupSid)&&r.push("Windows sandbox local group is unavailable."),e.inBuiltinUsers||r.push("Windows sandbox account is not in the built-in Users group."),e.inSandboxGroup||r.push("Windows sandbox account is not in the sandbox-runtime-users group."),e.hiddenFromLogon||r.push("Windows sandbox account is not hidden from interactive logon."),e.credPresent||r.push("Windows sandbox account credential is unavailable."),r}i(mr,"windowsSandboxAccountDiagnostics");function tt(e){let r=JSON.parse(e);if(typeof r!="object"||r===null)return;let t=r;if(t.version===1&&(t.state==="applied"&&t.policyId==="kodax-workspace-shell-v1"&&(t.backend==="windows-restricted-user"||t.backend==="macos-seatbelt"||t.backend==="linux-bubblewrap"||t.backend==="unsupported")||t.state==="fallback"&&t.reason==="backend_failed"&&t.execution==="normal_permission_policy"))return t}i(tt,"parseBrokerObservation");function ve(){return process.env.KODAX_A2A_NODE??(process.env.KODAX_BUNDLED==="true"?"node":process.execPath)}i(ve,"sandboxJavaScriptCommand");async function B(e={}){if(e.refresh||J===void 0||Date.now()>=le){let r=nt();J=r,le=Number.POSITIVE_INFINITY,r.then(t=>{J===r&&(le=t.ready?Number.POSITIVE_INFINITY:Date.now()+zr)},()=>{J===r&&(J=void 0,le=0)})}return J}i(B,"doctorSandboxRuntime");async function nt(){let e=[];Ee.isSupportedPlatform()||e.push(`Unsupported platform: ${process.platform}.`);let r=Ee.checkDependencies();e.push(...r.warnings,...r.errors);let t=r.errors.length>0;if(process.env.KODAX_BUNDLED!=="true")try{let d=JSON.parse(await z(Ke.resolve("@anthropic-ai/sandbox-runtime/package.json"),"utf8"));d.version!==V&&(t=!0,e.push(`ASRT package version mismatch: expected ${V}, found ${String(d.version)}.`))}catch(d){t=!0,e.push(`ASRT package provenance check failed: ${ye(d)}`)}let n=ve(),s=oe({args:["--version"],env:Q(),isElectron:n===process.execPath&&process.versions.electron!==void 0}),a=Be(n,s.args,{env:s.env,shell:!1,encoding:"utf8",windowsHide:!0,timeout:5e3});if(a.status!==0){t=!0;let d=a.error?.message??(a.stderr.trim()||n);e.push(`JavaScript Skill interpreter is unavailable: ${d}.`)}if(process.platform==="win32")try{let d=await Oe(),c=je({srtWin:d.srtWin}),u=mr(c);if(u.length>0||!c.sid)t=!0,e.push(...u);else{Zr(d,c.sid);let l=vr(Se(),c.sid,c.groupSid,!1,"read");l.length>0&&(t=!0,e.push(`[acl_guards_missing] ${l.length} persistent Windows sandbox ACL guard(s) are missing. Run "kodax sandbox setup" once to install them outside the startup path.`)),await rt(d)}}catch(d){t=!0,e.push(ye(d))}return{ready:Ee.isSupportedPlatform()&&!t,platform:process.platform,version:V,diagnostics:e,setupRequired:t}}i(nt,"inspectSandboxRuntime");async function ot(){if(process.platform!=="win32")return B({refresh:!0});let e=await B({refresh:!0});if(e.ready)return e;let r=!1;try{let n=await Oe(),s=je({srtWin:n.srtWin});r=mr(s).length===0&&s.sid!==void 0}catch{r=!1}if(r){De(Se(),"read");let n=await B({refresh:!0});if(n.ready)return n}if(Ir().cancelled)throw new Error("Sandbox setup was cancelled.");return await Oe(),De(Se(),"read"),B({refresh:!0})}i(ot,"setupSandboxRuntime");function ue(e){return e.ready?[`KodaX sandbox is active (${e.platform}, ASRT ${e.version}).`]:e.platform==="win32"?['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."]: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(ue,"sandboxSetupGuidance");async function tn(e={}){let r=await B({refresh:!0});if(r.ready)return{status:"ready",attempted:!1,doctor:r,guidance:ue(r)};if(r.platform!=="win32"||e.allowElevation===!1)return{status:"unavailable",attempted:!1,doctor:r,guidance:ue(r)};try{let t=await ot();return{status:t.ready?"ready":"unavailable",attempted:!0,doctor:t,guidance:ue(t)}}catch(t){let n=await B({refresh:!0}),s=ye(t);return{status:/cancelled/i.test(s)?"cancelled":"unavailable",attempted:!0,doctor:n,guidance:ue(n),error:s}}}i(tn,"prepareSandboxRuntimeForSetup");function M(e,r){let t=e.replaceAll("\\","/").replace(/^\.\//,"");if(!t||o.posix.isAbsolute(t)||t.split("/").includes(".."))throw new Error(`${r} must be a safe relative path.`);return t}i(M,"canonicalRelative");function _(e,r){let t=o.relative(e,r);return t===""||!t.startsWith("..")&&!o.isAbsolute(t)}i(_,"isInside");function wr(e){let r=e.split(o.sep).map(t=>t.toLowerCase());return r.some(t=>jr.has(t))||r.some(t=>Mr.has(t)||t.startsWith(".env."))}i(wr,"isSensitiveRelative");async function st(e,r){await W(r,{recursive:!0,mode:448});let t=[...(e.scripts??[]).map(n=>({folder:"scripts",file:n})),...(e.references??[]).map(n=>({folder:"references",file:n})),...(e.assets??[]).map(n=>({folder:"assets",file:n})),...(e.templates??[]).map(n=>({folder:"templates",file:n})),...(e.resources??[]).map(n=>({folder:"resources",file:n}))];await Y(o.join(r,"SKILL.md"),await z(e.skillFilePath),{mode:384});for(let{folder:n,file:s}of t){let a=M(s.relativePath,`Skill ${e.name} support file`),d=o.join(r,n,...a.split("/"));await W(o.dirname(d),{recursive:!0,mode:448}),await Y(d,await z(s.path),{mode:384})}}i(st,"copySkillSnapshot");async function it(e,r){let t=new Map;for(let[n,s]of Object.entries(e.admissions)){let a=await e.registry.loadFull(n),d=new Map((a.scripts??[]).map(u=>[`scripts/${M(u.relativePath,`Skill ${n} script`)}`,u])),c=o.join(r,n.replace(/[^A-Za-z0-9._-]/g,"_"));await st(a,c);for(let u of s){let l=M(u,`toolPolicy.skillScripts.${n}`);if(!d.has(l))throw new Error(`Skill "${n}" has no script "${l}".`);t.set(`${n}\0${l}`,{skill:n,relativePath:l,snapshotPath:o.join(c,...l.split("/"))})}}return t}i(it,"snapshotAdmissions");function at(e){return e.mode==="deny"?[]:e.origins.map(r=>{let t=new URL(r);return{host:t.hostname.toLowerCase(),port:t.port?Number(t.port):t.protocol==="https:"?443:80}})}i(at,"networkEndpoints");function Q(){let e=["PATH","Path","PATHEXT","SystemRoot","COMSPEC","TEMP","TMP","HOME","USERPROFILE","LOCALAPPDATA","LANG"],r={NO_COLOR:"1"};for(let t of e)process.env[t]!==void 0&&(r[t]=process.env[t]);for(let[t,n]of Object.entries(process.env))t.startsWith("LC_")&&n!==void 0&&(r[t]=n);return r}i(Q,"sanitizedEnvironment");function ct(e){let r=o.extname(e).toLowerCase();if([".js",".mjs",".cjs"].includes(r))return{command:process.env.KODAX_A2A_NODE??(process.env.KODAX_BUNDLED==="true"?"node":process.execPath),args:[e]};if(r===".py")return{command:process.env.KODAX_A2A_PYTHON??(process.platform==="win32"?"python.exe":"python3"),args:[e]};if(r===".ps1")return{command:process.env.KODAX_A2A_POWERSHELL??(process.platform==="win32"?o.join(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe"):"pwsh"),args:["-NoProfile","-NonInteractive","-File",e]};if(r===".sh"&&process.platform!=="win32")return{command:"/bin/sh",args:[e]};if([".cmd",".bat"].includes(r)&&process.platform==="win32")return{command:process.env.COMSPEC??o.join(process.env.SystemRoot??"C:\\Windows","System32","cmd.exe"),args:["/d","/s","/c",e]};throw new Error(`Unsupported admitted Skill script type: ${r||"<none>"}.`)}i(ct,"interpreterFor");var nr=250,dt=1500;async function lt(e,r,t=qe,n=Me){let s=[],a=[],d=0,c,u=i(()=>{},"rejectStopped"),l,p=new Promise((y,k)=>{u=k}),w=i(y=>{if(c!==void 0)return;c=y;let k=!1,v=i(()=>{k||(k=!0,l!==void 0&&clearTimeout(l),u(y))},"finish");l=setTimeout(()=>{try{e.kill("SIGKILL")}finally{v()}},dt),Ae(e,{forceMs:nr,taskkillMs:nr}).then(v,v)},"requestStop"),m=i((y,k)=>{d+=k.byteLength,d>n?w(new Error(`Sandboxed command output exceeded ${n} bytes.`)):y.push(k)},"append");e.stdout?.on("data",y=>{m(s,y)}),e.stderr?.on("data",y=>{m(a,y)});let S=setTimeout(()=>{w(new Error(`Sandboxed command exceeded its ${t} ms timeout.`))},t),g=i(()=>{let y=r?.reason;w(y instanceof Error?y:new Error("Sandboxed command was cancelled."))},"abort");r?.addEventListener("abort",g,{once:!0}),r?.aborted&&g();try{let y=new Promise((v,A)=>{e.once("error",A),e.once("close",q=>v(q??1))}),k=await Promise.race([y,p]);if(c!==void 0)throw c;return{exitCode:k,stdout:Buffer.concat(s).toString("utf8"),stderr:Buffer.concat(a).toString("utf8")}}finally{clearTimeout(S),l!==void 0&&clearTimeout(l),r?.removeEventListener("abort",g)}}i(lt,"collectProcess");async function gr(e,r,t=qe,n=Me){let s=process.platform==="win32"?await Ue():Z.tmpdir(),a=o.join(s,`kodax-asrt-${process.pid}-${F()}.json`),d=process.platform==="win32"?He(e.config):{...e.config,filesystem:{...e.config.filesystem,denyRead:[...e.config.filesystem.denyRead,a]}},c={...e,bootstrapCommand:e.bootstrapCommand??ve(),config:d};await Y(a,JSON.stringify(c),{mode:384});try{let u=process.env.KODAX_BUNDLED==="true"?["__asrt-broker",a]:["--input-type=module","-e",fr,ur,a],l=oe({args:u,env:Q(),isElectron:process.versions.electron!==void 0}),p=ir(process.execPath,l.args,{cwd:process.platform==="win32"?be().directory:void 0,env:l.env,shell:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"});return ke(p),await lt(p,r,t,n)}finally{await j(a,{force:!0})}}i(gr,"runBrokerResult");async function ut(e,r){let t=await gr(e,r);if(t.exitCode!==0){let n=t.stderr.trim()||t.stdout.trim();throw new Error(`Sandboxed Skill script failed (${t.exitCode}): ${n}`)}return t.stdout}i(ut,"runBroker");async function pt(e,r){let t=await ie(e),n=o.resolve(e,M(r,"Skill script input")),s=await ie(n);if(!_(t,s)||wr(o.relative(t,s)))throw new Error("Skill script input is outside the permitted workspace surface.");if(!(await we(s)).isFile())throw new Error("Skill script inputs must be files.");return s}i(pt,"workspaceSource");async function ft(e,r){let t=await ie(e),n=o.resolve(e,M(r,"Skill script output target"));if(!_(o.resolve(e),n)||wr(o.relative(o.resolve(e),n)))throw new Error("Skill script output target is outside the permitted workspace surface.");if(await W(o.dirname(n),{recursive:!0}),!_(t,await ie(o.dirname(n))))throw new Error("Skill script output target escapes through a symlink.");try{throw await we(n),new Error("Skill script output target already exists.")}catch(s){if(s.code!=="ENOENT")throw s}return n}i(ft,"workspaceTarget");async function mt(e,r,t,n){if(t.inputs.length>0&&n==="none")throw new Error("Skill script inputs require workspace read access.");for(let s of t.inputs){let a=await pt(e,s.path),d=M(s.as??o.basename(a),"Skill script staged input"),c=o.resolve(r,"inputs",...d.split("/"));if(!_(o.join(r,"inputs"),c))throw new Error("Skill script staged input escapes staging.");await W(o.dirname(c),{recursive:!0,mode:448}),await cr(a,c)}}i(mt,"stageInputFiles");async function wt(e,r,t,n,s){if(t.outputs.length>0&&n!=="write")throw new Error("Skill script outputs require workspace write access.");let a=[];for(let d of t.outputs){let c=M(d.path,"Skill script staged output"),u=o.resolve(r,"outputs",...c.split("/")),l=await ie(u);if(!_(o.join(r,"outputs"),l)||(await Cr(u)).isSymbolicLink()||!(await we(u)).isFile())throw new Error(`Skill script did not produce output "${c}".`);let p=await ft(e,d.target);if(s!==void 0&&yr(e,!0)+(await we(u)).size>s)throw new Error("Skill script outputs would exceed the remote workspace byte quota.");await cr(u,p,$r.COPYFILE_EXCL),a.push(o.relative(e,p))}return a}i(wt,"promoteOutputs");function yr(e,r=!1){let t=0;for(let n of ar(e,{withFileTypes:!0})){if(r&&n.name===".kodax-a2a-script"||n.isSymbolicLink())continue;let s=o.join(e,n.name);n.isDirectory()?t+=yr(s):n.isFile()&&(t+=he(s).size)}return t}i(yr,"directorySize");function Xe(e){if(process.platform!=="win32")return e;let r=be();return{...e,windows:{...e.windows,srtWin:{path:r.path}},filesystem:{...e.filesystem,allowRead:[...new Set([...e.filesystem.allowRead,r.directory])],denyWrite:process.platform==="win32"?e.filesystem.denyWrite:[...new Set([...e.filesystem.denyWrite??[],r.directory])]}}}i(Xe,"withPreparedWindowsRunner");function gt(e,r,t,n){let s=Z.homedir(),a=process.platform==="win32"?Se():[s],d=o.isAbsolute(n)?[n]:[];return Xe({network:{allowedDomains:[],deniedDomains:[],strictAllowlist:t.length===0,allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{denyRead:a,allowRead:[e,r,process.execPath,...d],allowWrite:[e],denyWrite:a}})}i(gt,"sandboxConfig");function yt(){let e=[Z.tmpdir(),process.env.TEMP,process.env.TMP,process.env.TMPDIR,...process.platform==="win32"?[]:["/tmp","/var/tmp"]];return[...new Set(e.filter(r=>typeof r=="string"&&o.isAbsolute(r)).map(r=>o.resolve(r)))]}i(yt,"canonicalTempDirectories");function Sr(e){return[o.join(e,".git","config"),o.join(e,".git","hooks")].filter(t=>{try{return he(t),!0}catch{return!1}})}i(Sr,"existingWorkspaceDenyWrites");function hr(e,r,t){let n=qr.map(a=>o.resolve(e,a)).filter(a=>o.relative(a,r)!==""),s=process.platform==="win32"?[o.resolve(r)]:[o.resolve(t),...Kr.map(a=>o.resolve(r,a))];return[...new Set([...s,...n])]}i(hr,"workspaceShellSensitiveReadDenies");function Ge(e){let r=[...new Set(e.map(n=>o.resolve(n)))].filter(n=>he(n,{throwIfNoEntry:!1})!==void 0).sort((n,s)=>n.length-s.length),t=[];for(let n of r)t.some(s=>_(s,n))||t.push(n);return t}i(Ge,"existingMinimalWindowsAclGuardRoots");function br(e){return o.resolve(e).toLowerCase()}i(br,"windowsAclGuardKey");function Ne(e,r){let t=br(e),n=r==="read"?_e:new Set([..._e,...pr]);for(let s of n)if(t===s||t.startsWith(s.endsWith(o.sep)?s:`${s}${o.sep}`))return!0;return!1}i(Ne,"windowsAclGuardCovers");function Se(){let e=o.resolve(Z.homedir()),r=o.resolve(U());return Ge(hr(e,r,o.join(r,"sandbox-runtime")))}i(Se,"windowsPersistentAclGuardRoots");function vr(e,r,t,n,s){let a=Ge(e);if(a.length===0)return[];let d=JSON.stringify({sid:r,tokenSids:[r,t,"S-1-1-0","S-1-5-11","S-1-5-32-545"].filter(p=>p!==void 0),install:n,paths:a.map(p=>({path:p,directory:he(p).isDirectory(),mode:s}))}),c=o.join(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe"),u=Be(c,["-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(Xr,"utf16le").toString("base64")],{input:d,encoding:"utf8",timeout:n&&s==="read"?15*6e4:n?15e3:5e3,windowsHide:!0});if(u.error||u.status!==0){let p=(u.error?.message||u.stderr||u.stdout||"no diagnostics").trim().slice(-4096);throw new Error(`Windows sandbox ACL guard failed: ${p}`)}let l;try{let p=JSON.parse(u.stdout.trim());l=Array.isArray(p.missing)?p.missing.filter(w=>typeof w=="string"):[]}catch(p){throw new Error(`Windows sandbox ACL guard returned invalid output: ${ye(p)}`)}if(l.length===0){let p=s==="read"?_e:pr;for(let w of a)p.add(br(w))}return l}i(vr,"runWindowsAclGuard");function De(e,r){if(process.platform!=="win32"||e.length===0)return;let t=e.filter(d=>!Ne(d,r));if(t.length===0)return;let n=be(),s=je({srtWin:n.srtWin});if(!s.sid)throw new Error("Windows sandbox account SID is unavailable for ACL guards.");if(vr(t,s.sid,s.groupSid,!0,r).length>0)throw new Error("Windows sandbox ACL guards were not installed completely.")}i(De,"installWindowsAclGuards");function He(e){return process.platform!=="win32"?e:{...e,filesystem:{...e.filesystem,denyRead:e.filesystem.denyRead.filter(r=>!Ne(r,"read")),denyWrite:e.filesystem.denyWrite?.filter(r=>!Ne(r,"write"))}}}i(He,"withoutWindowsAsrtDenyPropagation");function St(e,r){let t;try{t=me.native(r)}catch{return[]}let n=[];for(let s of e){let a;try{a=me.native(s)}catch{continue}if(!_(a,t))n.push(s);else if(a!==t){let d=o.relative(a,t).split(o.sep),c=a;try{for(let u of d){for(let l of ar(c,{withFileTypes:!0}))l.name!==u&&n.push(o.join(c,l.name));c=o.join(c,u)}}catch{}}}return process.platform!=="win32"&&n.push(r),[...new Set(n)]}i(St,"workspaceShellWriteRoots");function ht(e){let r=process.platform==="win32"?o.resolve(e).toLowerCase():o.resolve(e);return o.join(Z.tmpdir(),"kodax-sandbox",Fe("sha256").update(r).digest("hex").slice(0,16))}i(ht,"workspaceShellTempRoot");function bt(e){return o.join(ht(e),`${process.pid}-${F()}`)}i(bt,"createWorkspaceShellTempDirectory");function vt(e){return process.platform==="win32"?e===void 0?[]:[e]:yt()}i(vt,"workspaceShellTempWriteRoots");function xt(e,r,t){try{let n=me.native(r),s=o.resolve(r),a=o.resolve(e);if(!_(s,a)||a===s)return;for(;a!==s;)try{let d=me.native(a);if(d===n||!_(n,d))return;let c=o.relative(n,d).split(o.sep)[0]?.toLowerCase();return c==="sandbox-runtime"||t&&["runtime","processes","learned"].includes(c??"")?void 0:d}catch(d){if(!t||d.code!=="ENOENT")return;try{Tr(a);return}catch(u){if(u.code!=="ENOENT")return}let c=o.dirname(a);if(c===a)return;a=c}return}catch{return}}i(xt,"windowsAgentHomeAccessRoot");function xr(e,r){if(!r)return{read:[],write:[]};let t=i((n,s)=>[...new Set(n.flatMap(a=>{let d=xt(a,e,s);return d?[d]:[]}))],"roots");return{read:t(r.read,!1),write:t(r.write,!0),...r.ephemeral===!0?{ephemeral:!0}:{}}}i(xr,"windowsAgentHomeAccessRoots");function kr(e,r,t){let n=o.resolve(U()),s=o.join(n,"sandbox-runtime"),a=o.resolve(Z.homedir()),d=hr(a,n,s),c=process.platform==="win32"?Ge(d):d.filter(m=>m!==n),u=(process.env.PATH??process.env.Path??"").split(o.delimiter).map(m=>m.replace(/^"|"$/g,"")).filter(m=>o.isAbsolute(m)).map(m=>o.resolve(m)).filter(m=>{let S=o.relative(a,m);return S!==""&&!S.startsWith("..")&&!o.isAbsolute(S)&&!c.some(g=>_(g,m))}),l=ve(),p=process.platform==="win32"?xr(n,t):{read:[],write:[]},w=St([e,...vt(r),...p.write],n);return Xe({network:{allowedDomains:[],deniedDomains:[],strictAllowlist:!1,allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{denyRead:c,allowRead:[...new Set([...u,...p.read,...o.isAbsolute(l)?[l]:[]])],allowWrite:w,denyWrite:[s,o.join(n,"runtime"),o.join(n,"processes"),o.join(n,"learned"),...Sr(e)]}})}i(kr,"workspaceShellSandboxConfig");function kt(e,r,t){let n=kr(e,r,t);return process.platform!=="win32"?n:Ar(n)}i(kt,"workspaceShellSessionSandboxConfig");function Ar(e){let r=e.filesystem.allowWrite;return{...e,filesystem:{...e.filesystem,denyRead:e.filesystem.denyRead,denyWrite:e.filesystem.denyWrite.filter(t=>r.some(n=>_(n,t)))}}}i(Ar,"boundedWindowsWorkspaceDenies");function At(e,r,t){let n=kr(e,r,t);return process.platform==="win32"?Ar(n):n}i(At,"workspaceShellCommandSandboxConfig");function pe(e,r){return[...new Set((e??[]).map(t=>o.resolve(r,t)))]}i(pe,"normalizedSandboxPaths");function Rt(e){return e.mode!=="allowlist"?[]:e.origins.map(r=>{let t=new URL(r);if(t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password||t.pathname!=="/"||t.search||t.hash)throw new Error(`Sandbox network origin must be an HTTP(S) origin: ${r}`);return{host:t.hostname.toLowerCase(),port:t.port?Number(t.port):t.protocol==="https:"?443:80}})}i(Rt,"sdkSandboxEndpoints");async function nn(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 r=o.resolve(e.cwd),t=e.network??{mode:"deny"},n=Rt(t),s=await B();if(!s.ready)return{status:"unavailable",sandboxed:!1,doctor:s};let a={...e.inheritEnvironment===!0?process.env:Q(),...e.env},d={config:Xe({network:{allowedDomains:[],deniedDomains:[],strictAllowlist:t.mode==="deny",allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{allowRead:pe(e.filesystem.allowRead,r),allowWrite:pe(e.filesystem.allowWrite,r),denyRead:pe(e.filesystem.denyRead,r),denyWrite:pe(e.filesystem.denyWrite,r)}}),command:e.command,args:e.args??[],cwd:r,env:a,endpoints:n,allowAllNetwork:t.mode==="allow"},c=await gr(d,e.signal,e.timeoutMs??qe,e.maxOutputBytes??Me);return{status:"completed",sandboxed:!0,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr}}i(nn,"runKodaXSandboxed");var Et=5*6e4,$t=3e4,Tt=3e4,Ce=1500,Ct=15e3,Pt=8,$=new Map,Le=!1;async function _t(){let e=[...$.values()];$.clear();for(let r of e)try{await(await r).close()}catch(t){E({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox shutdown could not confirm ACL reset.",detail:t})}}i(_t,"closeCachedWorkspaceSessions");var Wt=i(()=>{Le=!1,_t()},"closeWorkspaceSessionsBeforeExit");function Ot(){Le||(Le=!0,process.once("beforeExit",Wt))}i(Ot,"registerWorkspaceSessionBeforeExit");function Rr(){let e=new Error("ASRT workspace session preparation timed out.");return e.name="TimeoutError",e}i(Rr,"workspacePreparationTimeoutError");function Ie(e,r){if(e?.aborted)throw new DOMException("Operation aborted","AbortError");if(r!==void 0&&Date.now()>=r)throw Rr()}i(Ie,"throwIfWorkspacePreparationStopped");function fe(e,r,t){return Ie(r,t),r===void 0&&t===void 0?e:new Promise((n,s)=>{let a=!1,d,c=i(l=>{a||(a=!0,d&&clearTimeout(d),r?.removeEventListener("abort",u),l())},"finish"),u=i(()=>{c(()=>s(new DOMException("Operation aborted","AbortError")))},"onAbort");r?.addEventListener("abort",u,{once:!0}),t!==void 0&&(d=setTimeout(()=>{c(()=>s(Rr()))},Math.max(0,t-Date.now())),d.unref()),e.then(l=>c(()=>n(l)),l=>c(()=>s(l)))})}i(fe,"waitForWorkspacePreparation");async function Ue(){let e=o.join(U(),"sandbox-runtime");return await W(e,{recursive:!0,mode:448}),e}i(Ue,"sandboxControlDirectory");function Nt(e){if(process.env.KODAX_BUNDLED==="true")return["__asrt-workspace-session",e];if(import.meta.url.endsWith(".ts"))return["--import",dr(Ke.resolve("tsx")).href,Qe(new URL("./sandbox-workspace-session-entry.ts",import.meta.url)),e];let r=o.dirname(Qe(import.meta.url)),t=o.basename(r)==="chunks"?o.dirname(r):r;return[o.join(t,"sandbox-workspace-session.js"),e]}i(Nt,"workspaceSessionEntryArgs");function Pe(e,r){let t=r?"ref":"unref";e[t]();for(let n of e.stdio){if(!n)continue;n[t]?.()}}i(Pe,"setWorkspaceSessionReferenced");async function Er(e,r){if(e)return r();let t=await Re();try{return await r()}finally{await t()}}i(Er,"withExclusiveFileSystemEffectFence");async function Dt(e,r,t,n){let s=process.platform==="win32"?bt(e):void 0;s!==void 0&&await W(s,{recursive:!0,mode:448});let a=await Ue();process.platform==="win32"&&De(Sr(e),"write");let d=o.join(a,`workspace-${process.pid}-${F()}.json`),c=He(kt(e,s,r));await Y(d,JSON.stringify({config:c}),{mode:384});let u=oe({args:Nt(d),env:Q(),isElectron:process.versions.electron!==void 0}),l=ir(process.execPath,u.args,{cwd:process.platform==="win32"?be().directory:void 0,env:u.env,shell:!1,stdio:["pipe","pipe","pipe","pipe"],windowsHide:!0});ke(l);let p=l.stdio[3];if(!p)throw new Error("ASRT workspace session control pipe was not created.");let w=Or.createInterface({input:p}),m=new Map,S="",g=!1,y=!1,k=!1,v=0,A=0,q,R,O,G=new Promise(f=>{l.once("exit",(h,T)=>f({code:h,signal:T}))}),C=G.then(async()=>{s!==void 0&&await j(s,{recursive:!0,force:!0})});C.catch(f=>{E({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox temp cleanup failed.",detail:f})});let ee=i(async()=>{let f=await G;if(await C,f.code===0&&f.signal===null)return;let h=f.signal===null?`code ${f.code??"unknown"}`:`signal ${f.signal}`;throw new Error(`ASRT workspace session ACL reset was not confirmed (${h}): ${S.trim()||"no diagnostics"}`)},"confirmCleanReset"),H,re,xe=new Promise((f,h)=>{H=f,re=h}),te=i(()=>{k||(k=!0,n())},"evict"),K,b=i(()=>K||(K=(async()=>{try{await Ae(l,{gracefulStdinEnd:!0,gracefulMs:process.platform==="win32"?Ct:Ce,forceMs:Ce,taskkillMs:Ce})}finally{w.close(),p.destroy(),l.stdin.destroy()}})().finally(te),K),"terminate"),x=i(f=>{if(!g){g=!0,re(f);for(let h of m.values())h.reject(f);m.clear()}},"fail");l.stderr.on("data",f=>{S=(S+f.toString("utf8")).slice(-16384)}),l.stdout.on("data",f=>{S=(S+f.toString("utf8")).slice(-16384)}),w.on("line",f=>{let h;try{h=JSON.parse(f)}catch{x(new Error("ASRT workspace session returned malformed control data.")),b();return}if(h.type==="ready"){h.ok?H():re(new Error(h.error??"ASRT workspace session failed."));return}if(h.type!=="result"||!h.id){x(new Error("ASRT workspace session returned an invalid control response.")),b();return}let T=m.get(h.id);T&&(m.delete(h.id),T.resolve(h))}),l.once("error",f=>{x(f),b()}),w.once("close",()=>{y||g||(x(new Error("ASRT workspace session control pipe closed unexpectedly.")),b())}),l.once("exit",f=>{R&&clearTimeout(R),x(new Error(`ASRT workspace session exited ${f??1}: ${S.trim()||"no diagnostics"}`)),te()});let ne=setTimeout(()=>{x(new Error("ASRT workspace session initialization timed out.")),b()},$t);try{await xe.finally(()=>clearTimeout(ne))}catch(f){throw await b(),await j(d,{force:!0}),f}let ae=i(async(f,h)=>{if(g||y&&f==="wrap")throw new Error("ASRT workspace session is unavailable.");let T=`workspace_${++v}`,ce=new Promise((P,D)=>{m.set(T,{resolve:P,reject:D})}),N=setTimeout(()=>{x(new Error(`ASRT workspace session ${f} request timed out.`)),b()},Tt);N.unref();try{await new Promise((P,D)=>{l.stdin.write(`${JSON.stringify({id:T,type:f,request:h})}
|
|
481
|
+
`,L=>L?D(L):P())})}catch(P){throw m.delete(T),clearTimeout(N),x(P instanceof Error?P:new Error(String(P))),b(),P}return ce.finally(()=>clearTimeout(N))},"request"),Je=i(()=>{R&&clearTimeout(R),!(A>0||y||g)&&(R=setTimeout(()=>{Ve.close()},Et),R.unref(),Pe(l,!1))},"scheduleIdleClose"),Ve={...s===void 0?{}:{tempDirectory:s},async acquire(f,h,T){if(Ie(h,T),g||y)throw new Error("ASRT workspace session is unavailable.");R&&clearTimeout(R),Pe(l,!0),A+=1;let ce=!1,N=i(()=>{ce||(ce=!0,A-=1,A===0&&(q?.(),q=void 0),Je())},"finalize"),P=ae("wrap",f),D;try{D=await fe(P,h,T)}catch(L){throw P.then(async I=>{if(!I.ok||!I.invocation)return;let de=await ae("cleanup");if(!de.ok)throw new Error(de.error??"ASRT command cleanup failed.")}).catch(I=>{E({source:"sandbox:workspace-session",level:"warn",message:"Late workspace sandbox preparation cleanup failed.",detail:I})}).finally(N),L}try{if(!D.ok||!D.invocation)throw N(),new Error(D.error??"ASRT workspace wrapping failed.");try{Ie(h,T)}catch(I){try{await ae("cleanup")}catch(de){E({source:"sandbox:workspace-session",level:"warn",message:"Cancelled workspace sandbox preparation cleanup failed.",detail:de})}throw N(),I}let L=!1;return{invocation:D.invocation,async release(){if(!L){L=!0;try{let I=await ae("cleanup");if(!I.ok)throw new Error(I.error??"ASRT command cleanup failed.")}finally{N()}}}}}catch(L){throw N(),L}},async close(){return O||(y=!0,O=Er(t,async()=>{if(R&&clearTimeout(R),g)return ee();Pe(l,!0),A>0&&await new Promise(f=>{q=f}),g||l.stdin.end(),await ee()}),O)}};return Je(),Ve}i(Dt,"startWorkspaceSessionClientWithFence");function or(e,r,t,n){return Er(t,()=>Dt(e,r,t,n))}i(or,"startWorkspaceSessionClient");async function sr(e,r,t=!1){if(!(await B()).ready)return;Ot();let s=process.platform==="win32"?r:void 0;if(s?.ephemeral===!0)return or(e,s,t,()=>{});let a=process.platform==="win32"?e.toLowerCase():e,d=s===void 0?"workspace":Fe("sha256").update(JSON.stringify({read:[...s.read].map(l=>l.toLowerCase()).sort(),write:[...s.write].map(l=>l.toLowerCase()).sort()})).digest("hex"),c=`${a}\0${d}`,u=$.get(c);if(u&&($.delete(c),$.set(c,u)),!u){if(s!==void 0){let l=[...$.keys()].filter(p=>!p.endsWith("\0workspace"));if(l.length>=Pt){let p=l[0],w=$.get(p);if($.delete(p),w)try{await(await w).close()}catch(m){throw E({source:"sandbox:workspace-session",level:"warn",message:"Retiring an old Agent Home sandbox scope failed.",detail:m}),m}}}u=or(e,s,!1,()=>{$.get(c)===u&&$.delete(c)}),$.set(c,u),u.catch(()=>{$.get(c)===u&&$.delete(c)})}return u}i(sr,"getWorkspaceSession");function on(e){let r=o.resolve(e.workspaceRoot),t=sr(r);return t.catch(n=>{E({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox warm-up failed; admitted commands remain fail-closed.",detail:n})}),{failClosed:e.failClosed===!0,processTreeContainment:e.failClosed===!0&&process.platform==="linux"?"root-exit-drains":void 0,async prepare(n){if(!n.toolCallId){n.reportObservation?.({version:1,state:"not_selected"});return}let s={id:n.toolCallId,name:"bash",input:{...n.toolInput}},a=await e.shouldSandbox(s);if(!a){n.reportObservation?.({version:1,state:"not_selected"});return}let d=typeof a=="object"?a.agentHomeAccess:void 0,c=process.platform==="win32"&&d!==void 0?xr(o.resolve(U()),d):d,u=process.platform==="win32"&&c?.ephemeral===!0,l,p,w,m=!1,S,g=i(async()=>{if(w){if(!m)throw new Error("Review-only Agent Home ACL reset is not confirmed.");S??=w(),await S}},"releaseExclusiveAfterReset"),y=i(()=>w===void 0?void 0:{bindEffectProcess:i((v,A)=>w.bindEffectProcess(v,A),"bindEffectProcess"),finishEffectProcess:i(()=>w.finishEffectProcess(),"finishEffectProcess"),release:g},"fileSystemEffectLease"),k=i(async()=>{!u||!p||(await p.close(),m=!0,await g())},"closeReviewSession");try{if(process.platform==="win32"&&c!==void 0&&await fe(t,n.signal,n.deadlineAt),u){let b=Re();try{w=await fe(b,n.signal,n.deadlineAt)}catch(x){throw b.then(ne=>ne()).catch(ne=>{E({source:"sandbox:workspace-session",level:"warn",message:"Late review-only filesystem fence cleanup failed.",detail:ne})}),x}}let v=await fe(sr(r,c,u),n.signal,n.deadlineAt);if(!v){w&&(m=!0,await g()),n.reportObservation?.({version:1,state:"fallback",reason:"not_ready",execution:"normal_permission_policy"});return}p=v;let A=n.executable??(process.platform==="win32"?process.env.COMSPEC??o.join(process.env.SystemRoot??"C:\\Windows","System32","cmd.exe"):"/bin/sh"),q=n.args??(process.platform==="win32"?["/d","/s","/c",n.command]:["-c",n.command]),R=await Ue(),O=o.join(R,`kodax-asrt-shell-${process.pid}-${F()}.json`),G=o.join(R,`kodax-asrt-observation-${process.pid}-${F()}.json`),C={...n.env};if(process.platform==="win32"){for(let x of Object.keys(C))["TEMP","TMP","TMPDIR"].includes(x.toUpperCase())&&delete C[x];let b=v.tempDirectory;if(b===void 0)throw new Error("Windows workspace sandbox temp directory is unavailable.");C.TEMP=b,C.TMP=b,C.TMPDIR=b,C.GIT_CONFIG_GLOBAL="NUL",C.GIT_CONFIG_NOSYSTEM="1"}let ee={config:He(At(r,v.tempDirectory,c)),command:A,args:q,cwd:n.cwd,env:C,endpoints:[],allowAllNetwork:!0,bootstrapCommand:ve(),fallbackToNormalExecution:e.failClosed!==!0,observationBackend:Fr().backend,observationFile:G,targetStartedMarker:`\0KODAX_ASRT_TARGET_STARTED:${F()}\0
|
|
482
|
+
`},H=await v.acquire(ee,n.signal,n.deadlineAt);l=H;let re={...ee,wrappedInvocation:H.invocation},xe=process.env.KODAX_BUNDLED==="true"?["__asrt-broker",O]:["--input-type=module","-e",fr,ur,O],te=oe({args:xe,env:Q(),isElectron:process.versions.electron!==void 0});await Y(O,JSON.stringify(re),{mode:384});let K=y();return{executable:process.execPath,args:te.args,env:te.env,...K===void 0?{}:{fileSystemEffectLease:K},async cleanup(){let b;try{b=await z(G,"utf8").then(tt).catch(x=>{if(x.code!=="ENOENT")throw x})}finally{await Promise.all([j(O,{force:!0}),j(G,{force:!0})]);try{await H.release()}catch(x){E({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox command cleanup failed.",detail:x})}finally{u&&await k()}}return b}}}catch(v){if(l&&await l.release().catch(A=>{E({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox lease release failed.",detail:A})}),u&&p?await k().catch(A=>{E({source:"sandbox:workspace-session",level:"warn",message:"Review-only Agent Home sandbox rollback failed.",detail:A})}):w&&(m=!0,await g().catch(A=>{E({source:"sandbox:workspace-session",level:"warn",message:"Unused review-only filesystem fence cleanup failed.",detail:A})})),n.signal?.aborted||n.deadlineAt!==void 0&&Date.now()>=n.deadlineAt)throw v;E({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox preparation failed; using normal permission fallback.",detail:v}),n.reportObservation?.({version:1,state:"fallback",reason:"prepare_failed",execution:"normal_permission_policy"});return}}}}i(on,"createAsrtShellSandbox");async function sn(e){let r=await B();if(!r.ready)throw new Error(`ASRT ${V} is not ready: ${r.diagnostics.join(" ")||"run kodax sandbox setup"}`);let t=o.join(e.snapshotRoot,F()),n=o.join(t,"skills");await W(n,{recursive:!0,mode:448});try{let s=await it(e,n),a=at(e.network),d=Promise.resolve();return{async run(c,u){let l=d,p;if(d=new Promise(w=>{p=w}),await l,u.signal?.aborted)throw p?.(),u.signal.reason??new Error("Sandboxed Skill script was cancelled.");try{if(c.args.length>64||c.args.some(g=>g.length>8192))throw new Error("Skill script arguments exceed the bounded remote contract.");if(c.inputs.length>32||c.outputs.length>32)throw new Error("Skill script file mappings exceed the bounded remote contract.");let w=M(c.script,"Skill script"),m=s.get(`${c.skill}\0${w}`);if(!m)throw new Error("Skill script is not admitted by this Runtime binding.");if([".cmd",".bat"].includes(o.extname(m.snapshotPath).toLowerCase())&&c.args.some(g=>/[&|<>^]/.test(g)))throw new Error("Batch Skill script arguments cannot contain command operators.");let S=o.join(u.workspaceRoot,".kodax-a2a-script",F());try{await W(o.join(S,"inputs"),{recursive:!0,mode:448}),await W(o.join(S,"outputs"),{recursive:!0,mode:448}),await mt(u.workspaceRoot,S,c,e.workspaceAccess);let g=ct(m.snapshotPath),y=await ut({config:gt(S,t,a,g.command),command:g.command,args:[...g.args,...c.args],cwd:S,env:Q(),endpoints:a},u.signal),k=await wt(u.workspaceRoot,S,c,e.workspaceAccess,e.workspaceByteLimit);return JSON.stringify({stdout:y.trim(),outputs:k})}finally{await j(S,{recursive:!0,force:!0})}}finally{p?.()}},async dispose(){await d,await j(t,{recursive:!0,force:!0})}}}catch(s){throw await j(t,{recursive:!0,force:!0}),s}}i(sn,"createAsrtSkillScriptRunner");export{V as a,Fr as b,B as c,ot as d,ue as e,tn as f,nn as g,on as h,sn as i};
|