@kodax-ai/kodax 0.7.92 → 0.7.93

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +9 -0
  3. package/README_CN.md +9 -0
  4. package/dist/chunks/{agent-YHHFIH7N.js → agent-R7HVNARP.js} +1 -1
  5. package/dist/chunks/argument-completer-JHXUJWHC.js +2 -0
  6. package/dist/chunks/{chunk-PKPBII4F.js → chunk-3YOZIFSJ.js} +2 -2
  7. package/dist/chunks/{chunk-OSQIYUGD.js → chunk-4BY53JTF.js} +2 -2
  8. package/dist/chunks/{chunk-X75UGXP3.js → chunk-7QBWHCIZ.js} +1 -1
  9. package/dist/chunks/chunk-A3ZQE2BX.js +519 -0
  10. package/dist/chunks/{chunk-FBL7IVMK.js → chunk-BHE66SP3.js} +14 -14
  11. package/dist/chunks/chunk-D27EY4XC.js +383 -0
  12. package/dist/chunks/{chunk-5CIKWSCA.js → chunk-HLZWPB32.js} +2 -2
  13. package/dist/chunks/{chunk-RJIYXB62.js → chunk-JJ2YDBSN.js} +2 -2
  14. package/dist/chunks/{chunk-AGZNXFHZ.js → chunk-JTZKC4TV.js} +4 -4
  15. package/dist/chunks/{chunk-QPBN3J4E.js → chunk-PRASABCC.js} +2 -2
  16. package/dist/chunks/{chunk-QKLS4BYA.js → chunk-SMVC3Q3U.js} +4 -4
  17. package/dist/chunks/{chunk-THZVJ6R7.js → chunk-XTWIGVUL.js} +1 -1
  18. package/dist/chunks/{construction-bootstrap-QVLJPFTL.js → construction-bootstrap-474QPSYB.js} +1 -1
  19. package/dist/chunks/{dist-XC5M7UYX.js → dist-H4PT2QAV.js} +1 -1
  20. package/dist/chunks/{dist-WNMK42WE.js → dist-ITTXQHRJ.js} +1 -1
  21. package/dist/chunks/{host-B3TK2U43.js → host-OR3IO2A4.js} +1 -1
  22. package/dist/chunks/{run-manager-5AV3MR4W.js → run-manager-MNOTWIFX.js} +1 -1
  23. package/dist/chunks/{utils-HPVZCR2J.js → utils-5J4BHNBV.js} +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/kodax_bootstrap.js +1 -1
  26. package/dist/kodax_cli.js +1035 -1035
  27. package/dist/runtime-worker.js +1007 -1007
  28. package/dist/sandbox-workspace-session.js +1 -1
  29. package/dist/sdk-a2a.js +1 -1
  30. package/dist/sdk-coding.js +1 -1
  31. package/dist/sdk-llm.js +1 -1
  32. package/dist/sdk-repl.js +1 -1
  33. package/dist/sdk-runtime.js +1 -1
  34. package/dist/sdk-sandbox.js +1 -1
  35. package/dist/sdk-session.js +1 -1
  36. package/package.json +1 -1
  37. package/dist/chunks/argument-completer-6ZTRBNZM.js +0 -2
  38. package/dist/chunks/chunk-A6GNPNGB.js +0 -383
  39. package/dist/chunks/chunk-BV3SVH36.js +0 -519
@@ -0,0 +1,519 @@
1
+ // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
+ import{k as kn}from"./chunk-JTZKC4TV.js";import{Ac as J,Ia as K,Wa as ar,Ya as dr,_a as Ne,db as Ie,fb as vn,ib as xn,t as W,zc as cr}from"./chunk-7XSZVOG7.js";import{a as s}from"./chunk-ONUPGMER.js";import{spawn as vr,spawnSync as Ue}from"node:child_process";import{createHash as fn,randomUUID as Y}from"node:crypto";import{once as lr}from"node:events";import{constants as at,existsSync as xr,lstatSync as Fn,mkdirSync as ur,readFileSync as kr,readdirSync as jn,realpathSync as pe,renameSync as $n,rmSync as we,statSync as pn,writeFileSync as fr,writeSync as Oo}from"node:fs";import{copyFile as Ar,lstat as dt,mkdir as G,readFile as Ee,realpath as je,rename as ct,rm as U,rmdir as lt,stat as tn,writeFile as Re}from"node:fs/promises";import{createRequire as ut}from"node:module";import{createServer as ft}from"node:net";import ae from"node:os";import i from"node:path";import pt from"node:readline";import{fileURLToPath as pr,pathToFileURL as Er}from"node:url";var ue="0.0.65",{DEFAULT_WINDOWS_PROXY_PORT_RANGE:wt,SandboxManager:An,getSrtWinPath:mt,getWindowsSandboxUserStatus:qn,grantWindowsAcl:gt,installWindowsSandbox:yt,resolveSrtWin:St,revokeWindowsAcl:Rr}=await import("@anthropic-ai/sandbox-runtime");function ht(){let e=process.platform==="win32"?"windows-restricted-user":process.platform==="darwin"?"macos-seatbelt":process.platform==="linux"?"linux-bubblewrap":"unsupported";return{version:4,asrtVersion:ue,platform:process.platform,backend:e,genericCommandExecution:!0,controls:["filesystem","network","environment","timeout","output"],ordinaryCallsTriggerSetup:!1,setupMayElevate:process.platform==="win32",unavailableBehavior:"structured-no-execution",permissionFallback:"normal-permission-policy"}}s(ht,"sandboxRuntimeCapability");var Kn=1048576,Xn=12e4,Gn=ut(import.meta.url),Pr=process.env.KODAX_BUNDLED==="true"?void 0:Er(Gn.resolve("@anthropic-ai/sandbox-runtime")).href,bt=new Set([".ssh",".aws",".azure",".gnupg",".kodax",".agents",".codex",".claude",".gemini",".direnv",".terraform.d"]),vt=new Set([".env",".envrc",".pgpass",".npmrc",".pypirc","credentials","id_rsa","id_ed25519"]),xt=[".ssh",".aws",".azure",".gnupg",".kube",".docker",".kodax",".agents",".codex",".claude",".gemini",".direnv",".terraform.d",i.join(".cargo","credentials.toml"),i.join(".config","gcloud"),i.join(".config","gh"),i.join(".config","openai"),i.join(".config","anthropic"),".gitconfig",i.join(".config","git","config"),".terraformrc",i.join(".config","pypoetry","auth.toml"),".condarc",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",i.join(".config","fish","config.fish"),i.join(".config","fish","fish_variables"),".bash_history",".zsh_history",i.join(".m2","settings.xml"),i.join(".m2","settings-security.xml"),i.join(".gradle","gradle.properties"),i.join(".nuget","NuGet","NuGet.Config"),i.join(".pip","pip.conf"),i.join(".config","pip","pip.conf"),i.join(".cache","huggingface","token"),i.join(".huggingface","token"),i.join(".config","rclone","rclone.conf"),i.join(".local","share","keyrings"),i.join("Library","Keychains"),i.join("AppData","Roaming","Microsoft","Protect"),i.join("AppData","Roaming","Microsoft","Credentials"),i.join("AppData","Roaming","Microsoft","Vault"),i.join("AppData","Local","Microsoft","Credentials"),i.join("AppData","Local","Microsoft","Protect"),i.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"],kt=["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"],Jn=["runtime","processes","learned"],At=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
+ `,Tn=new Set,Cr=new Set,wr=JSON.stringify(dr),En=JSON.stringify(ar),Et=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 childEnv = { ...process.env };
197
+ for (const name of Object.keys(childEnv)) {
198
+ if (name.toLowerCase() === 'electron_run_as_node') delete childEnv[name];
199
+ }
200
+ if (input.electronRunAsNode === true) childEnv.ELECTRON_RUN_AS_NODE = '1';
201
+ const child = spawn(input.command, input.args, {
202
+ cwd: input.cwd,
203
+ env: childEnv,
204
+ shell: false,
205
+ stdio: ['inherit', 'inherit', 'pipe'],
206
+ windowsHide: true,
207
+ windowsVerbatimArguments: input.windowsVerbatimArguments === true,
208
+ });
209
+ const stop = (signal) => child.kill(signal);
210
+ process.once('SIGINT', () => stop('SIGINT'));
211
+ process.once('SIGTERM', () => stop('SIGTERM'));
212
+ child.once('spawn', () => {
213
+ writeSync(2, input.targetStartedMarker);
214
+ child.stderr.pipe(process.stderr);
215
+ });
216
+ child.once('error', (error) => {
217
+ process.stderr.write((error instanceof Error ? error.message : String(error)) + '\n');
218
+ process.exitCode = 1;
219
+ });
220
+ child.once('exit', (code, signal) => {
221
+ process.exitCode = signal ? 1 : code ?? 1;
222
+ });
223
+ `,Rt="eval(Buffer.from(process.argv[1],'base64').toString('utf8'))",Pt=JSON.stringify(Rt),Ct=Buffer.from(Et,"utf8").toString("base64"),Wt=JSON.stringify(Ct),Wr=String.raw`
224
+ import { spawn } from 'node:child_process';
225
+ import { randomUUID } from 'node:crypto';
226
+ import { readFile, rm, writeFile } from 'node:fs/promises';
227
+ import { dirname } from 'node:path';
228
+ let SandboxManager;
229
+ const request = JSON.parse(await readFile(process.argv[2], 'utf8'));
230
+ await rm(process.argv[2], { force: true });
231
+ const targetStartedMarker = request.targetStartedMarker
232
+ ?? '\u0000KODAX_ASRT_TARGET_STARTED:' + randomUUID() + '\u0000\n';
233
+ const endpoints = new Set(request.endpoints.map((item) => item.host.toLowerCase() + ':' + item.port));
234
+ const callback = request.allowAllNetwork === true
235
+ ? async () => true
236
+ : request.endpoints.length === 0
237
+ ? undefined
238
+ : async ({ host, port }) => endpoints.has(host.toLowerCase() + ':' + port);
239
+ const withWindowsChildEnvironment = (argv, environment) => {
240
+ const separator = argv.lastIndexOf('--');
241
+ if (separator < 0) throw new Error('ASRT Windows wrapper omitted its child separator.');
242
+ const requested = [];
243
+ const requestedNames = new Set();
244
+ for (const [name, value] of Object.entries(environment ?? {})) {
245
+ if (value === undefined) continue;
246
+ if (!name || name.includes('=') || name.includes('\0') || value.includes('\0')) {
247
+ throw new Error('Invalid environment entry for ASRT Windows child.');
248
+ }
249
+ const normalized = name.toLowerCase();
250
+ if (requestedNames.has(normalized)) {
251
+ throw new Error('Ambiguous Windows child environment variable: ' + name + '.');
252
+ }
253
+ requestedNames.add(normalized);
254
+ requested.push([name, value]);
255
+ }
256
+ const requestedOverrides = new Set(requested.flatMap(([name]) => (
257
+ ['path', 'pathext'].includes(name.toLowerCase()) ? [name.toLowerCase()] : []
258
+ )));
259
+ const controlled = new Set();
260
+ const prefix = [];
261
+ for (let index = 0; index < separator; index += 1) {
262
+ if (argv[index] !== '--env' || index + 1 >= separator) {
263
+ prefix.push(argv[index]);
264
+ continue;
265
+ }
266
+ const assignment = argv[index + 1];
267
+ const name = assignment.split('=', 1)[0]?.toLowerCase();
268
+ if (name) controlled.add(name);
269
+ if (!name || !requestedOverrides.has(name)) prefix.push(argv[index], assignment);
270
+ index += 1;
271
+ }
272
+ const injected = [];
273
+ for (const [name, value] of requested) {
274
+ const normalized = name.toLowerCase();
275
+ if (controlled.has(normalized) && normalized !== 'path' && normalized !== 'pathext') continue;
276
+ injected.push('--env', name + '=' + value);
277
+ }
278
+ const result = [...prefix, ...injected, ...argv.slice(separator)];
279
+ const estimate = result.reduce((size, value) => size + value.length + 3, 0);
280
+ if (estimate > 30000) throw new Error('ASRT Windows child environment exceeds the CreateProcess command-line limit.');
281
+ return result;
282
+ };
283
+ const writeObservation = async (observation) => {
284
+ if (typeof request.observationFile !== 'string') return;
285
+ await writeFile(request.observationFile, JSON.stringify(observation), { mode: 0o600 });
286
+ };
287
+ const waitForTarget = (target, observation) => {
288
+ const marker = Buffer.from(targetStartedMarker, 'utf8');
289
+ let pending = Buffer.alloc(0);
290
+ let diagnostic = Buffer.alloc(0);
291
+ let processError;
292
+ let wrapperSpawned = false;
293
+ let targetStarted = false;
294
+ let observationWrite = Promise.resolve();
295
+ return new Promise((resolve, reject) => {
296
+ let settled = false;
297
+ target.once('spawn', () => {
298
+ wrapperSpawned = true;
299
+ });
300
+ const finish = (result) => {
301
+ if (settled) return;
302
+ settled = true;
303
+ void observationWrite.then(() => resolve(result), reject);
304
+ };
305
+ target.stderr.on('data', (chunk) => {
306
+ if (targetStarted) {
307
+ process.stderr.write(chunk);
308
+ return;
309
+ }
310
+ pending = Buffer.concat([pending, Buffer.from(chunk)]);
311
+ const markerOffset = pending.indexOf(marker);
312
+ if (markerOffset >= 0) {
313
+ targetStarted = true;
314
+ const suffix = pending.subarray(markerOffset + marker.length);
315
+ pending = Buffer.alloc(0);
316
+ diagnostic = Buffer.alloc(0);
317
+ observationWrite = writeObservation(observation).catch(() => undefined);
318
+ if (suffix.length > 0) process.stderr.write(suffix);
319
+ return;
320
+ }
321
+ const retained = Math.max(0, marker.length - 1);
322
+ if (pending.length > retained) {
323
+ diagnostic = Buffer.concat([
324
+ diagnostic,
325
+ pending.subarray(0, pending.length - retained),
326
+ ]).subarray(-65536);
327
+ pending = pending.subarray(pending.length - retained);
328
+ }
329
+ });
330
+ target.once('error', (error) => {
331
+ processError = error instanceof Error ? error.message : String(error);
332
+ });
333
+ target.once('close', (exitCode, signal) => {
334
+ const preTarget = Buffer.concat([diagnostic, pending]).toString('utf8').trim();
335
+ finish({
336
+ exitCode: signal ? 1 : exitCode ?? 1,
337
+ targetStarted,
338
+ spawnFailedBeforeSpawn: processError !== undefined && !wrapperSpawned,
339
+ diagnostic: preTarget || processError || undefined,
340
+ });
341
+ });
342
+ });
343
+ };
344
+ let child;
345
+ let targetStarted = false;
346
+ let normalFallbackAttempted = false;
347
+ const runDirect = async () => {
348
+ const internalElectronNode = request.command === process.execPath && process.versions.electron !== undefined;
349
+ const directArgs = internalElectronNode
350
+ ? ['--import', ${wr}, ...request.args]
351
+ : request.args;
352
+ const directEnv = internalElectronNode
353
+ ? { ...request.env, [${En}]: '1' }
354
+ : request.env;
355
+ child = spawn(request.command, directArgs, {
356
+ cwd: request.cwd,
357
+ env: directEnv,
358
+ shell: false,
359
+ stdio: 'inherit',
360
+ windowsHide: true,
361
+ windowsVerbatimArguments: request.windowsVerbatimArguments === true,
362
+ });
363
+ return await new Promise((resolve, reject) => {
364
+ child.once('error', reject);
365
+ child.once('exit', (exitCode, signal) => resolve(signal ? 1 : exitCode ?? 1));
366
+ });
367
+ };
368
+ const runNormalFallback = async () => {
369
+ if (
370
+ request.fallbackToNormalExecution !== true
371
+ || targetStarted
372
+ || normalFallbackAttempted
373
+ ) return false;
374
+ await writeObservation({
375
+ version: 1,
376
+ state: 'fallback',
377
+ reason: 'backend_failed',
378
+ execution: 'normal_permission_policy',
379
+ }).catch(() => undefined);
380
+ normalFallbackAttempted = true;
381
+ process.exitCode = await runDirect();
382
+ return true;
383
+ };
384
+ try {
385
+ if (request.wrappedInvocation) {
386
+ const wrapped = request.wrappedInvocation;
387
+ child = spawn(wrapped.executable, wrapped.args, {
388
+ cwd: request.cwd,
389
+ env: wrapped.env,
390
+ shell: wrapped.shell,
391
+ stdio: ['inherit', 'inherit', 'pipe'],
392
+ windowsHide: true,
393
+ });
394
+ const result = await waitForTarget(child, {
395
+ version: 1,
396
+ state: 'applied',
397
+ backend: request.observationBackend ?? 'unsupported',
398
+ policyId: 'kodax-workspace-shell-v1',
399
+ });
400
+ targetStarted = result.targetStarted;
401
+ const fellBack = result.spawnFailedBeforeSpawn
402
+ ? await runNormalFallback()
403
+ : false;
404
+ if (!targetStarted && !fellBack) {
405
+ process.stderr.write((result.diagnostic || 'Sandbox target launch could not be attested.') + '\n');
406
+ }
407
+ if (!fellBack) process.exitCode = targetStarted ? result.exitCode : 1;
408
+ } else {
409
+ ({ SandboxManager } = await import(process.argv[1]));
410
+ const bootstrap = request.bootstrapCommand ?? 'node';
411
+ const bootstrapIsAbsolute = /^(?:[A-Za-z]:[\\/]|\\\\)/.test(bootstrap);
412
+ const bootstrapIsElectronNode = bootstrap === process.execPath
413
+ && process.versions.electron !== undefined;
414
+ const config = process.platform === 'win32' && bootstrapIsAbsolute
415
+ ? {
416
+ ...request.config,
417
+ filesystem: {
418
+ ...request.config.filesystem,
419
+ allowRead: [...new Set([
420
+ ...request.config.filesystem.allowRead,
421
+ bootstrap,
422
+ dirname(bootstrap),
423
+ ])],
424
+ },
425
+ }
426
+ : request.config;
427
+ await SandboxManager.initialize(config, callback);
428
+ const quote = (value) => process.platform === 'win32'
429
+ ? '"' + value.replaceAll('"', '""') + '"'
430
+ : "'" + value.replaceAll("'", "'\"'\"'") + "'";
431
+ const internalElectronNode = request.command === process.execPath && process.versions.electron !== undefined;
432
+ const childArgs = internalElectronNode
433
+ ? ['--import', ${wr}, ...request.args]
434
+ : request.args;
435
+ const command = [
436
+ quote(bootstrap),
437
+ '-e',
438
+ quote(${Pt}),
439
+ ${Wt},
440
+ Buffer.from(JSON.stringify({
441
+ command: request.command,
442
+ args: childArgs,
443
+ windowsVerbatimArguments: request.windowsVerbatimArguments === true,
444
+ cwd: request.cwd,
445
+ targetStartedMarker,
446
+ electronRunAsNode: internalElectronNode,
447
+ }), 'utf8').toString('base64'),
448
+ ].join(' ');
449
+ if (process.platform === 'win32') {
450
+ const wrapped = await SandboxManager.wrapWithSandboxArgv(command, 'cmd', undefined, undefined, request.cwd);
451
+ const requestedEnv = internalElectronNode || bootstrapIsElectronNode
452
+ ? { ...request.env, [${En}]: '1' }
453
+ : request.env;
454
+ const childArgv = withWindowsChildEnvironment(wrapped.argv, requestedEnv);
455
+ child = spawn(childArgv[0], childArgv.slice(1), {
456
+ cwd: request.cwd,
457
+ env: wrapped.env,
458
+ shell: false,
459
+ stdio: ['inherit', 'inherit', 'pipe'],
460
+ windowsHide: true,
461
+ });
462
+ } else {
463
+ const wrapped = await SandboxManager.wrapWithSandbox(command);
464
+ const childEnv = internalElectronNode || bootstrapIsElectronNode
465
+ ? { ...request.env, [${En}]: '1' }
466
+ : request.env;
467
+ child = spawn(wrapped, {
468
+ cwd: request.cwd,
469
+ env: childEnv,
470
+ shell: true,
471
+ stdio: ['inherit', 'inherit', 'pipe'],
472
+ });
473
+ }
474
+ const stop = () => child?.kill('SIGTERM');
475
+ process.once('SIGINT', stop);
476
+ process.once('SIGTERM', stop);
477
+ const result = await waitForTarget(child, {
478
+ version: 1,
479
+ state: 'applied',
480
+ backend: request.observationBackend ?? 'unsupported',
481
+ policyId: 'kodax-workspace-shell-v1',
482
+ });
483
+ targetStarted = result.targetStarted;
484
+ try { SandboxManager.cleanupAfterCommand(); } catch {}
485
+ await SandboxManager.reset().catch(() => undefined);
486
+ const fellBack = result.spawnFailedBeforeSpawn
487
+ ? await runNormalFallback()
488
+ : false;
489
+ if (!targetStarted && !fellBack) {
490
+ process.stderr.write((result.diagnostic || 'Sandbox target launch could not be attested.') + '\n');
491
+ }
492
+ if (!fellBack) process.exitCode = targetStarted ? result.exitCode : 1;
493
+ }
494
+ } catch (error) {
495
+ await SandboxManager?.reset().catch(() => undefined);
496
+ if (
497
+ request.fallbackToNormalExecution === true
498
+ && !targetStarted
499
+ && !normalFallbackAttempted
500
+ && child === undefined
501
+ ) {
502
+ try {
503
+ await runNormalFallback();
504
+ } catch (fallbackError) {
505
+ process.stderr.write((fallbackError instanceof Error ? fallbackError.message : String(fallbackError)) + '\n');
506
+ process.exitCode = 1;
507
+ }
508
+ } else {
509
+ process.stderr.write((error instanceof Error ? error.message : String(error)) + '\n');
510
+ process.exitCode = 1;
511
+ }
512
+ }
513
+ `,ve,Ye=0,$t=3e4,Le,qe,_n=!1,le;function fe(e){return e instanceof Error?e.message:String(e)}s(fe,"errorText");function Ke(e,...r){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&r.includes(e.code)}s(Ke,"isFileSystemError");async function mr(e){try{return await Ee(e)}catch(r){if(Ke(r,"ENOENT"))return;throw r}}s(mr,"readFileIfPresent");async function Tt(e,r){let n=await mr(r);if(n?.equals(e))return;if(n!==void 0)throw new Error(`Prepared Windows sandbox runner failed integrity verification: ${r}.`);let t=`${r}.${process.pid}.${Y()}.tmp`;try{await Re(t,e,{flag:"wx",mode:448});try{await ct(t,r)}catch(o){if(!(await mr(r))?.equals(e))throw o}}finally{await U(t,{force:!0})}}s(Tt,"installWindowsRunnerCopy");async function Xe(){if(Le===void 0){let e=(async()=>{let r=await Ee(mt()),n=fn("sha256").update(r).digest("hex").slice(0,16),t=i.join(i.resolve(K()),"sandbox-runtime","runner",ue,process.arch,n),o=i.join(t,"srt-win.exe");await G(gn(),{recursive:!0,mode:448}),await G(t,{recursive:!0,mode:448}),await Tt(r,o);let a={path:o,directory:t,srtWin:St({path:o})};return qe=a,a})();Le=e,e.catch(()=>{Le===e&&(Le=void 0,qe=void 0)})}return Le}s(Xe,"prepareWindowsSandboxRunner");function Ce(){if(process.platform!=="win32")throw new Error("A prepared Windows sandbox runner was requested on a non-Windows platform.");if(qe===void 0)throw new Error("Windows sandbox runner is not prepared; run the sandbox readiness check first.");return qe}s(Ce,"requirePreparedWindowsRunner");var O=new Set,X=new Map,Rn,Z=35e3,me="[acl_cleanup_unconfirmed]",B=class extends Error{static{s(this,"WindowsSandboxAclAdmissionError")}recoveryAction;constructor(r,n){super(r,n),this.name="WindowsSandboxAclAdmissionError",this.recoveryAction=n?.recoveryAction}};function $r(e){return/^windows-boot-\d+$/.test(e)}s($r,"isCanonicalWindowsBootIdentity");function wn(e){return e.diagnostics.some(r=>r.startsWith(me))}s(wn,"doctorHasWindowsSandboxAclCleanupBlock");function mn(){let e=Object.entries(process.env).find(([r,n])=>r.toUpperCase()==="PROGRAMDATA"&&n!==void 0)?.[1]??"C:\\ProgramData";return i.join(i.resolve(e),"KodaX","sandbox-runtime","acl-poison")}s(mn,"windowsSandboxAclPoisonDirectory");function gn(){return i.dirname(mn())}s(gn,"windowsSandboxAclCoordinationDirectory");function Un(e=K()){return i.join(i.resolve(e),"sandbox-runtime","acl-poison")}s(Un,"legacyWindowsSandboxAclPoisonDirectory");function _t(){return i.join(gn(),"acl-poison-staging")}s(_t,"windowsSandboxAclPoisonStagingDirectory");function Ot(e=K()){return i.join(i.resolve(e),"sandbox-runtime","acl-poison-staging")}s(Ot,"legacyWindowsSandboxAclPoisonStagingDirectory");function Q(){return i.join(gn(),"acl-recovery.lock")}s(Q,"windowsSandboxAclRecoveryLockFile");function Tr(e){let r=JSON.parse(e);if(typeof r!="object"||r===null)throw new Error("Windows sandbox ACL poison marker is not an object.");let n=r;if(n.version!==1&&n.version!==2||n.state!==void 0&&n.state!=="active"&&n.state!=="unconfirmed"||n.policyKey!==void 0&&typeof n.policyKey!="string"||n.holderPid!==void 0&&(typeof n.holderPid!="number"||!Number.isSafeInteger(n.holderPid)||n.holderPid<=0)||n.holderProcessStartIdentity!==void 0&&typeof n.holderProcessStartIdentity!="string"||n.pid!==void 0&&(typeof n.pid!="number"||!Number.isSafeInteger(n.pid)||n.pid<=0)||n.processStartIdentity!==void 0&&typeof n.processStartIdentity!="string"||n.windowsBootIdentity!==void 0&&(typeof n.windowsBootIdentity!="string"||!$r(n.windowsBootIdentity)))throw new Error("Windows sandbox ACL poison marker has an invalid owner identity.");return{version:n.version,...n.state==="active"||n.state==="unconfirmed"?{state:n.state}:{},...typeof n.policyKey=="string"?{policyKey:n.policyKey}:{},...typeof n.holderPid=="number"?{holderPid:n.holderPid}:{},...typeof n.holderProcessStartIdentity=="string"?{holderProcessStartIdentity:n.holderProcessStartIdentity}:{},...typeof n.pid=="number"?{pid:n.pid}:{},...typeof n.processStartIdentity=="string"?{processStartIdentity:n.processStartIdentity}:{},...typeof n.windowsBootIdentity=="string"?{windowsBootIdentity:n.windowsBootIdentity}:{}}}s(Tr,"parseWindowsSandboxAclPoisonOwner");function re(e=K()){return[...new Set([mn(),Un(e)])].flatMap(n=>{let t;try{t=jn(n)}catch(o){if(Ke(o,"ENOENT"))return[];throw o}return t.filter(o=>o.endsWith(".json")).map(o=>{let a=i.join(n,o);try{let c=Fn(a);if(!c.isFile()||c.isSymbolicLink())throw new Error("Windows sandbox ACL poison marker is not a regular file.");let d=Tr(kr(a,"utf8"));return{file:a,owner:i.basename(a).startsWith("unconfirmed-")?{...d,state:"unconfirmed"}:d}}catch(c){throw new B(`Windows sandbox ACL cleanup was not confirmed because its poison marker is unreadable: ${a}. `+On(),{cause:c,recoveryAction:"manual-recovery"})}})})}s(re,"readWindowsSandboxAclPoisonOwners");function de(){if(process.platform!=="win32")return;if(Rn!==void 0)return Rn??void 0;let e=String.raw`
514
+ # KodaXWindowsBootIdentity-v1
515
+ $boot = (Get-CimInstance Win32_OperatingSystem -ErrorAction Stop).LastBootUpTime
516
+ [Console]::Out.Write($boot.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture))
517
+ `,r=Ue(Hr(),["-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(e,"utf16le").toString("base64")],{encoding:"utf8",timeout:5e3,windowsHide:!0}),n=r.status===0?r.stdout.trim():"",t=/^\d+$/.test(n)?`windows-boot-${n}`:void 0;return Rn=t??null,t}s(de,"readWindowsBootIdentity");function Vo(){return de()}s(Vo,"readWindowsSandboxBootIdentity");function On(){return`After stopping every KodaX and KodaX Space process, run "${qe?.path??"srt-win.exe"}" acl recover --force --json, then delete "${mn()}" and "${Un()}".`}s(On,"windowsSandboxAclManualRecoveryInstruction");function _r(e,r=de()){if(e.find(({windowsBootIdentity:a})=>a===void 0||r===void 0)!==void 0)return new B("An unconfirmed Windows sandbox process tree has no verifiable Windows boot identity. "+On());let t=e[0],o=t?.pid===void 0?"":` (last root PID ${t.pid})`;return new B(`An unconfirmed Windows sandbox process tree${o} from the same Windows boot may still have live descendants; restart Windows before retrying. `+On())}s(_r,"persistentWindowsSandboxAclPoisonError");function Nn(e,r,n="unconfirmed",t){if(process.platform!=="win32")return;let o=de(),a=Ie(process.pid),c=Y(),d=`${n==="unconfirmed"?"unconfirmed-":""}owner-${c}.json`,l=JSON.stringify({version:1,state:n,...t===void 0?{}:{policyKey:t},holderPid:process.pid,...a===void 0?{}:{holderProcessStartIdentity:a},...e===void 0?{}:{pid:e},...r===void 0?{}:{processStartIdentity:r},...o===void 0?{}:{windowsBootIdentity:o}}),u=s((f,p)=>{ur(f,{recursive:!0,mode:448});let w=i.join(f,d);if(n==="unconfirmed")return fr(w,l,{flag:"wx",mode:384}),w;ur(p,{recursive:!0,mode:448});let h=i.join(p,`owner-${c}.tmp`);return fr(h,l,{flag:"wx",mode:384}),$n(h,w),w},"persist"),g=u(mn(),_t());try{let f=u(Un(),Ot());X.set(g,f)}catch(f){if(n==="active")try{we(g,{force:!0})}catch(p){throw new AggregateError([f,p],"Windows sandbox owner compatibility marker and primary rollback both failed.")}throw f}return g}s(Nn,"persistWindowsSandboxAclPoisonOwner");function Nt(e){let r=Nn(void 0,void 0,"active",e);if(r!==void 0){O.add(r);let n=X.get(r);n!==void 0&&O.add(n)}return r}s(Nt,"createWindowsSandboxAclOwnerMarker");function De(e){if(e===void 0)return;let r=X.get(e);try{r!==void 0&&we(r,{force:!0}),we(e,{force:!0}),O.delete(e),r!==void 0&&O.delete(r),X.delete(e)}catch(n){throw O.delete(e),r!==void 0&&O.delete(r),ge(n),new Error("Windows sandbox owner poison marker could not be cleared.",{cause:n})}}s(De,"confirmWindowsSandboxAclOwnerStopped");async function Ze(e,r){ge(r);let n=await Vn(e,void 0,void 0,r);if(ge(n),n!==r)throw n}s(Ze,"retainWindowsSandboxAclOwnerPoison");function Or(e,r,n){if(e===void 0)return Nn(r,n,"unconfirmed");let t=X.get(e),o=i.join(i.dirname(e),`unconfirmed-${i.basename(e)}`),a=t===void 0?void 0:i.join(i.dirname(t),`unconfirmed-${i.basename(t)}`);if(xr(o))return O.delete(e),t!==void 0&&O.delete(t),a!==void 0&&X.set(o,a),X.delete(e),o;try{return $n(e,o),t!==void 0&&a!==void 0&&$n(t,a),O.delete(e),t!==void 0&&O.delete(t),a!==void 0&&X.set(o,a),X.delete(e),o}catch(c){try{let d=Nn(r,n,"unconfirmed");return O.delete(e),t!==void 0&&O.delete(t),X.delete(e),d}catch(d){throw O.delete(e),t!==void 0&&O.delete(t),X.delete(e),new AggregateError([c,d],"Windows sandbox ACL poison write-ahead failed.")}}}s(Or,"writeAheadWindowsSandboxAclOwnerPoison");async function Vn(e,r,n,t){if(process.platform!=="win32")return t;let o;try{return o=Or(e,r,n),await J(Q(),async()=>{},Z),t}catch(a){return new AggregateError([t,a],o===void 0?"Windows sandbox owner termination and durable ACL poison recording both failed.":"Windows sandbox owner termination was not confirmed and ACL poison serialization failed.")}}s(Vn,"transitionWindowsSandboxAclOwnerToPoison");function It(e,r){return O.has(e)}s(It,"isVerifiedActiveWindowsSandboxAclOwner");function Hn(e){if(e.state!=="active"||e.holderPid===void 0||e.holderProcessStartIdentity===void 0)return"stale";let r=Ie(e.holderPid);if(r!==void 0)return r===e.holderProcessStartIdentity?"live":"stale";try{return process.kill(e.holderPid,0),"unknown"}catch(n){return Ke(n,"ESRCH")?"stale":"unknown"}}s(Hn,"windowsSandboxAclOwnerLiveness");function zn(e,r,n){return r.state!=="active"?!1:O.has(e)?n===void 0||r.policyKey===n:n!==void 0&&r.policyKey===n&&Hn(r)==="live"}s(zn,"isCompatibleWindowsSandboxAclOwner");function Yn(e){let r=re().filter(({file:n,owner:t})=>!zn(n,t,e));if(r.length!==0)throw _r(r.map(({owner:n})=>n))}s(Yn,"assertNoPersistentWindowsSandboxAclPoison");async function Nr(e,r,n,t){let o=new Error(n);if(process.platform==="win32"){let a=await Vn(t,e,r,o);return ge(a),a instanceof Error?a:o}return ge(o),o}s(Nr,"recordUnconfirmedWindowsSandboxOwner");function Ir(e){return process.platform==="win32"?`${e} process-tree termination was not confirmed; restart Windows before retrying.`:`${e} process-tree termination was not confirmed; stop the retained process tree before retrying.`}s(Ir,"unconfirmedSandboxProcessTreeMessage");function Pe(e=3e4){let r=Ce(),n=Ue(r.srtWin.exe,[...r.srtWin.prependArgs,"acl","recover","--json"],{cwd:r.directory,encoding:"utf8",timeout:Math.max(1,Math.min(3e4,e)),windowsHide:!0}),t=(n.stderr??"").trim();if(n.error)throw new Error(`Windows sandbox ACL recovery failed to start: ${n.error.message}`,{cause:n.error});let o;try{o=JSON.parse((n.stdout??"").trim())}catch(c){throw new Error(`Windows sandbox ACL recovery failed with unparseable output (exit ${String(n.status)}): ${t||"(empty stderr)"}.`,{cause:c})}let a=typeof o=="object"&&o!==null?o:void 0;if(n.status!==0||typeof a?.deadBrokers!="number"||!Number.isSafeInteger(a.deadBrokers)||a.deadBrokers<0||typeof a.acesRevoked!="number"||!Number.isSafeInteger(a.acesRevoked)||a.acesRevoked<0)throw new Error(`Windows sandbox ACL recovery failed (exit ${String(n.status)}${n.signal?`, signal ${n.signal}`:""}): ${t||"(empty stderr)"}.`);_n=!0}s(Pe,"recoverWindowsSandboxAcls");async function Ho(e,r,n,t=7e4){if(process.platform!=="win32")return 0;if(r.processStartIdentity===void 0)throw new Error("Windows sandbox ACL recovery requires an exact daemon process identity.");let o=Date.now()+t;return J(Q(),async()=>{let a=re(e),c=a.filter(({owner:l})=>l.holderPid===r.pid&&l.holderProcessStartIdentity===r.processStartIdentity&&l.windowsBootIdentity===n);if(c.length!==a.length)throw new B("Windows sandbox ACL recovery found a foreign or unverifiable owner marker.");if(c.length===0)return 0;await Dr(Xe(),Math.max(1,o-Date.now()));let d=o-Date.now();if(d<=0)throw new Error("Windows sandbox ACL recovery deadline expired before mutation.");return Pe(d),c.length},Math.max(1,Math.min(Z,t)))}s(Ho,"recoverWindowsSandboxAclsForRuntimeOwner");async function zo(e,r=7e4){if(process.platform!=="win32")return 0;let n=Date.now()+r;return J(Q(),async()=>{let t=re(e);if(t.length===0)return 0;Lr(t),await Dr(Xe(),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 Pe(o),t.length},Math.max(1,Math.min(Z,r)))}s(zo,"recoverPreviousBootWindowsSandboxAcls");function Lr(e){let r=de();if(r===void 0||!$r(r))throw new B("Windows sandbox ACL recovery could not verify the current boot identity.",{recoveryAction:"restart-system"});if(e.some(({owner:n})=>n.windowsBootIdentity===void 0))throw new B("Windows sandbox ACL recovery found an unverifiable owner marker.",{recoveryAction:"manual-recovery"});if(e.some(({owner:n})=>n.windowsBootIdentity===r))throw new B("Windows sandbox ACL recovery found a current-boot owner marker.",{recoveryAction:"restart-system"})}s(Lr,"assertPreviousBootWindowsSandboxAclMarkers");async function Dr(e,r){let n,t=new Promise((o,a)=>{n=setTimeout(()=>a(new Error("Windows sandbox runner preparation timed out.")),r)});try{return await Promise.race([e,t])}finally{n!==void 0&&clearTimeout(n)}}s(Dr,"waitForWindowsSandboxRunnerPreparation");async function Yo(e,r,n,t=4e4){if(process.platform!=="win32")return 0;if(r.processStartIdentity===void 0)throw new Error("Windows sandbox marker cleanup requires an exact daemon process identity.");return J(Q(),async()=>{let o=re(e),a=o.filter(({owner:c})=>c.holderPid===r.pid&&c.holderProcessStartIdentity===r.processStartIdentity&&c.windowsBootIdentity===n);if(a.length!==o.length)throw new B("Windows sandbox marker cleanup found a foreign or unverifiable owner marker.");for(let c of a)we(c.file,{force:!0});return a.length},Math.max(1,Math.min(Z,t)))}s(Yo,"clearWindowsSandboxAclMarkersForRuntimeOwner");async function Zo(e,r=4e4){return process.platform!=="win32"?0:J(Q(),async()=>{let n=re(e);if(n.length===0)return 0;Lr(n);for(let t of n)we(t.file,{force:!0});return n.length},Math.max(1,Math.min(Z,r)))}s(Zo,"clearPreviousBootWindowsSandboxAclMarkers");function Lt(e){return e instanceof cr}s(Lt,"isWindowsSandboxAclRecoveryLockTimeout");var on=class extends B{static{s(this,"ForeignWindowsSandboxAclOwnerContentionError")}constructor(r){super("Another Windows sandbox owner is active for the shared sandbox account; wait for it to close or stop the other KodaX/KodaX Space process, then retry.",{cause:r}),this.name="ForeignWindowsSandboxAclOwnerContentionError"}},sn=class extends B{static{s(this,"StaleWindowsSandboxAclOwnerContentionError")}constructor(r){super(r.message,{cause:r}),this.name="StaleWindowsSandboxAclOwnerContentionError"}};function Br(e){!Lt(e)&&!(e instanceof on)&&!(e instanceof sn)&&ge(e)}s(Br,"recordWindowsSandboxAclAdmissionFailure");function Ge(e,r=de()){let n=_r(e.map(({owner:t})=>t),r);return e.every(({owner:t})=>t.state==="active")?e.some(({owner:t})=>Hn(t)==="stale")?new sn(n):new on(n):n}s(Ge,"windowsSandboxAclPoisonSnapshotError");function Dt(){let e=re();if(e.length===0)return;let r=de();if(r!==void 0&&e.every(({owner:t})=>t.windowsBootIdentity!==void 0&&t.windowsBootIdentity!==r)){Pe();for(let t of e)we(t.file,{force:!0});Yn();return}return e.every(({owner:t})=>Hn(t)!=="stale")?new B("Windows sandbox setup cannot run while a sandbox owner is active for the shared Windows sandbox account; wait for sandboxed commands to finish and stop other KodaX or KodaX Space processes, then retry."):Ge(e,r)}s(Dt,"windowsSandboxAclSetupBlockWithLock");function gr(e,r){return{...e,ready:!1,diagnostics:[...e.diagnostics.filter(n=>!n.startsWith(me)),`${me} ${r.message}`]}}s(gr,"withWindowsSandboxAclSetupBlock");function Mr(e){Sn();let r=re(),n=r.filter(({file:t,owner:o})=>!zn(t,o,e));if(_n){if(n.length>0)throw Ge(n);return}if(n.length>0){let t=de();if(!(t!==void 0&&n.every(({owner:a})=>a.windowsBootIdentity!==void 0&&a.windowsBootIdentity!==t)))throw Ge(n,t)}if(r.length>0){_n=!0;return}Pe();for(let t of n)we(t.file,{force:!0});Yn(e)}s(Mr,"ensureWindowsSandboxAclRecoveryWithLock");async function an(e){if(process.platform==="win32")try{await J(Q(),async()=>Mr(e),Z)}catch(r){throw Br(r),r}}s(an,"ensureWindowsSandboxAclRecovery");async function Fr(e){if(process.platform!=="win32")return;let r;try{return await J(Q(),async()=>{try{Mr(e)}catch(n){throw Br(n),n}return r=Nt(e),r},Z)}catch(n){if(r===void 0)throw n;try{De(r)}catch(t){throw new AggregateError([n,t],"Windows sandbox owner admission and marker cleanup both failed.")}throw n}}s(Fr,"admitWindowsSandboxAclOwner");async function In(e){if(process.platform!=="win32")return;let r;try{if(e===void 0||!O.has(e))return;if(r=Tr(kr(e,"utf8")).policyKey,r!==void 0){await J(Q(),async()=>{let t=X.get(e),o=new Set([e,t].filter(d=>d!==void 0)),a=re().filter(({file:d})=>!o.has(d)),c=a.filter(({file:d,owner:l})=>!zn(d,l,r));if(c.length>0)throw Ge(c);if(a.length>0){De(e);return}Pe(),De(e)},Z);return}let n=Or(e,void 0,void 0);await J(Q(),async()=>{Pe(),De(n),e!==n&&De(e)},Z)}catch(n){let t=r===void 0?n:await Vn(e,void 0,void 0,n);throw ge(t),t}}s(In,"confirmWindowsSandboxAclRecovery");function Pn(){le!==void 0&&(Rr({sandboxUserSid:le.sandboxUserSid,holderPid:process.pid,srtWin:le.runner.srtWin}),le=void 0)}s(Pn,"releasePreparedWindowsRunnerGrant");function Bt(e,r){if(!(le?.runner.path===e.path&&le.sandboxUserSid===r)){process.removeListener("exit",Pn),Pn();try{gt({read:[e.directory,e.path],write:[],sandboxUserSid:r,holderPid:process.pid,srtWin:e.srtWin})}catch(n){try{Rr({sandboxUserSid:r,holderPid:process.pid,srtWin:e.srtWin})}catch(t){throw new AggregateError([n,t],"Windows sandbox runner ACL grant failed and its partial grant could not be revoked.")}throw n}le={runner:e,sandboxUserSid:r},process.once("exit",Pn)}}s(Bt,"retainPreparedWindowsRunnerGrant");async function Mt(){let[e,r]=wt;for(let n=0;n<5;n+=1){let t=ft();t.listen(0,"127.0.0.1"),await lr(t,"listening");let o=t.address();if(typeof o=="object"&&o!==null&&(o.port<e||o.port>r))return{server:t,target:`127.0.0.1:${o.port}`};let a=lr(t,"close");t.close(),await a}throw new Error(`[wfp_probe_bind_failed] Could not bind a loopback listener outside the Windows sandbox proxy range [${e},${r}].`)}s(Mt,"bindWindowsWfpProbe");function yr(e){return/0x80070005|access (?:is )?denied|拒绝访问/i.test(e)?"runner_launch_access_denied":/seclogon|secondary logon/i.test(e)?"secondary_logon_unavailable":"wfp_probe_failed"}s(yr,"windowsRunnerFailureCode");function Ft(e){return Ke(e,"ETIMEDOUT")?"wfp_probe_timeout":Ke(e,"EACCES","EPERM")?"runner_launch_access_denied":"runner_spawn_failed"}s(Ft,"windowsRunnerSpawnFailureCode");async function jt(e){let{server:r,target:n}=await Mt();try{let t=Ue(e.srtWin.exe,[...e.srtWin.prependArgs,"wfp","verify","--target",n],{cwd:e.directory,encoding:"utf8",timeout:3e4,windowsHide:!0}),o=(t.stderr??"").trim();if(t.error)throw new Error(`[${Ft(t.error)}] Windows sandbox runner failed to start: ${t.error.message}`);let a;try{a=JSON.parse((t.stdout??"").trim())}catch{let c=t.status===null?"wfp_probe_timeout":yr(o);throw new Error(`[${c}] Windows sandbox WFP probe exited ${String(t.status)}${t.signal?` (signal ${t.signal})`:""} with unparseable output; stderr: ${o||"(empty)"}.`)}if(t.status===3)throw new Error(`[wfp_fence_inactive] Direct outbound access to ${String(a.target??n)} succeeded. Run "kodax sandbox setup" to reinstall the Windows network policy.`);if(t.status!==0||a.egress_probe!=="blocked")throw new Error(`[${yr(o)}] Windows sandbox WFP probe to ${String(a.target??n)} was ${String(a.egress_probe)} (exit ${String(t.status)}): ${o||"(empty stderr)"}.`)}finally{r.close()}}s(jt,"verifyPreparedWindowsWfp");function jr(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}s(jr,"windowsSandboxAccountDiagnostics");function qt(e){let r=JSON.parse(e);if(typeof r!="object"||r===null)return;let n=r;if(n.version===1&&(n.state==="applied"&&n.policyId==="kodax-workspace-shell-v1"&&(n.backend==="windows-restricted-user"||n.backend==="macos-seatbelt"||n.backend==="linux-bubblewrap"||n.backend==="unsupported")||n.state==="fallback"&&n.reason==="backend_failed"&&n.execution==="normal_permission_policy"))return n}s(qt,"parseBrokerObservation");function yn(){return process.env.KODAX_A2A_NODE!==void 0?process.env.KODAX_A2A_NODE:process.versions.electron!==void 0?process.execPath:process.env.KODAX_BUNDLED==="true"?"node":process.execPath}s(yn,"sandboxJavaScriptCommand");async function ne(e={}){if(e.refresh||ve===void 0||Date.now()>=Ye){let r=Kt();ve=r,Ye=Number.POSITIVE_INFINITY,r.then(n=>{ve===r&&(Ye=n.ready?Number.POSITIVE_INFINITY:Date.now()+$t)},()=>{ve===r&&(ve=void 0,Ye=0)})}return ve}s(ne,"doctorSandboxRuntime");async function Kt(){let e=[],r=!1;An.isSupportedPlatform()||e.push(`Unsupported platform: ${process.platform}.`);let n=process.platform==="win32"?{errors:[],warnings:[]}:An.checkDependencies();e.push(...n.warnings,...n.errors);let t=n.errors.length>0;if(process.env.KODAX_BUNDLED!=="true")try{let d=JSON.parse(await Ee(Gn.resolve("@anthropic-ai/sandbox-runtime/package.json"),"utf8"));d.version!==ue&&(t=!0,e.push(`ASRT package version mismatch: expected ${ue}, found ${String(d.version)}.`))}catch(d){t=!0,e.push(`ASRT package provenance check failed: ${fe(d)}`)}let o=yn(),a=Ne({args:["--version"],env:We(),isElectron:o===process.execPath&&process.versions.electron!==void 0}),c=Ue(o,a.args,{env:a.env,shell:!1,encoding:"utf8",windowsHide:!0,timeout:5e3});if(c.status!==0){t=!0;let d=c.error?.message??(c.stderr.trim()||o);e.push(`JavaScript Skill interpreter is unavailable: ${d}.`)}if(process.platform==="win32"){try{let d=await Xe(),l=qn({srtWin:d.srtWin}),u=jr(l);if(u.length>0||!l.sid)t=!0,e.push(...u);else{Bt(d,l.sid);let g=Vr(dn(),l.sid,l.groupSid,!1,"read");g.length>0&&(t=!0,e.push(`[acl_guards_missing] ${g.length} persistent Windows sandbox ACL guard(s) are missing. Run "kodax sandbox setup" once to install them outside the startup path.`)),await jt(d)}}catch(d){t=!0,e.push(fe(d))}try{let d=re().filter(({file:l,owner:u})=>!It(l,u));if(d.length>0){let l=de();l!==void 0&&d.every(({owner:g})=>g.windowsBootIdentity!==void 0&&g.windowsBootIdentity!==l)||(r=!0,e.push(`${me} `+Ge(d,l).message))}}catch(d){r=!0,e.push(`${me} ${fe(d)}`)}}return{ready:An.isSupportedPlatform()&&!t&&!r,platform:process.platform,version:ue,diagnostics:e,setupRequired:t}}s(Kt,"inspectSandboxRuntime");async function Xt(){let e=await ne({refresh:!0});try{let t=Dt();if(t!==void 0)return gr(e,t)}catch(t){let o=t instanceof Error?t:new Error(String(t));return gr(e,o)}if(e.ready||wn(e)||!e.setupRequired)return e;let r=!1;try{let t=await Xe(),o=qn({srtWin:t.srtWin});r=jr(o).length===0&&o.sid!==void 0}catch{r=!1}if(r){Dn(dn(),"read");let t=await ne({refresh:!0});if(t.ready)return t}if(yt().cancelled)throw new Error("Sandbox setup was cancelled.");return await Xe(),Dn(dn(),"read"),ne({refresh:!0})}s(Xt,"setupWindowsSandboxRuntimeWithLock");async function Gt(){return process.platform!=="win32"?ne({refresh:!0}):J(Q(),Xt,Z)}s(Gt,"setupSandboxRuntime");function xe(e){if(e.ready)return[`KodaX sandbox is active (${e.platform}, ASRT ${e.version}).`];if(e.platform==="win32"){let r=e.diagnostics.find(n=>n.startsWith(me));return r!==void 0?[r.slice(me.length).trim()]:['Run "kodax sandbox setup". Windows will show a UAC prompt for the one-time sandbox account and network policy setup.',"The terminal itself does not need to be started as Administrator; approve the UAC prompt when it appears."]}return e.platform==="darwin"?['KodaX uses macOS Seatbelt through sandbox-exec. Install the missing dependency, then rerun "kodax sandbox doctor".',"Homebrew: brew install ripgrep"]:e.platform==="linux"?['KodaX uses bubblewrap on Linux. Install bubblewrap, socat, and ripgrep, then rerun "kodax sandbox doctor".',"Debian/Ubuntu: sudo apt install bubblewrap socat ripgrep","Fedora/RHEL: sudo dnf install bubblewrap socat ripgrep","Arch Linux: sudo pacman -S bubblewrap socat ripgrep"]:[`KodaX sandbox is not supported on ${e.platform}.`]}s(xe,"sandboxSetupGuidance");async function Qo(e={}){let r=await ne({refresh:!0});if(r.ready)return{status:"ready",attempted:!1,doctor:r,guidance:xe(r)};if(wn(r))return{status:"unavailable",attempted:!1,doctor:r,guidance:xe(r)};if(!r.setupRequired)return{status:"unavailable",attempted:!1,doctor:r,guidance:xe(r)};if(r.platform!=="win32"||e.allowElevation===!1)return{status:"unavailable",attempted:!1,doctor:r,guidance:xe(r)};try{let n=await Gt();return{status:n.ready?"ready":"unavailable",attempted:!0,doctor:n,guidance:xe(n)}}catch(n){let t=await ne({refresh:!0}),o=fe(n);return{status:/cancelled/i.test(o)?"cancelled":"unavailable",attempted:!0,doctor:t,guidance:xe(t),error:o}}}s(Qo,"prepareSandboxRuntimeForSetup");function ie(e,r){let n=e.replaceAll("\\","/").replace(/^\.\//,"");if(!n||i.posix.isAbsolute(n)||n.split("/").includes(".."))throw new Error(`${r} must be a safe relative path.`);return n}s(ie,"canonicalRelative");function _(e,r){let n=i.relative(e,r);return n===""||!n.startsWith("..")&&!i.isAbsolute(n)}s(_,"isInside");function qr(e){let r=e.split(i.sep).map(n=>n.toLowerCase());return r.some(n=>bt.has(n))||r.some(n=>vt.has(n)||n.startsWith(".env."))}s(qr,"isSensitiveRelative");async function Jt(e,r){await G(r,{recursive:!0,mode:448});let n=[...(e.scripts??[]).map(t=>({folder:"scripts",file:t})),...(e.references??[]).map(t=>({folder:"references",file:t})),...(e.assets??[]).map(t=>({folder:"assets",file:t})),...(e.templates??[]).map(t=>({folder:"templates",file:t})),...(e.resources??[]).map(t=>({folder:"resources",file:t}))];await Re(i.join(r,"SKILL.md"),await Ee(e.skillFilePath),{mode:384});for(let{folder:t,file:o}of n){let a=ie(o.relativePath,`Skill ${e.name} support file`),c=i.join(r,t,...a.split("/"));await G(i.dirname(c),{recursive:!0,mode:448}),await Re(c,await Ee(o.path),{mode:384})}}s(Jt,"copySkillSnapshot");async function Ut(e,r){let n=new Map;for(let[t,o]of Object.entries(e.admissions)){let a=await e.registry.loadFull(t),c=new Map((a.scripts??[]).map(l=>[`scripts/${ie(l.relativePath,`Skill ${t} script`)}`,l])),d=i.join(r,t.replace(/[^A-Za-z0-9._-]/g,"_"));await Jt(a,d);for(let l of o){let u=ie(l,`toolPolicy.skillScripts.${t}`);if(!c.has(u))throw new Error(`Skill "${t}" has no script "${u}".`);n.set(`${t}\0${u}`,{skill:t,relativePath:u,snapshotPath:i.join(d,...u.split("/"))})}}return n}s(Ut,"snapshotAdmissions");function Vt(e){return e.mode==="deny"?[]:e.origins.map(r=>{let n=new URL(r);return{host:n.hostname.toLowerCase(),port:n.port?Number(n.port):n.protocol==="https:"?443:80}})}s(Vt,"networkEndpoints");function We(){let e=["PATH","Path","PATHEXT","SystemRoot","COMSPEC","TEMP","TMP","HOME","USERPROFILE","LOCALAPPDATA","LANG"],r={NO_COLOR:"1"};for(let n of e)process.env[n]!==void 0&&(r[n]=process.env[n]);for(let[n,t]of Object.entries(process.env))n.startsWith("LC_")&&t!==void 0&&(r[n]=t);return Zn(r)}s(We,"sanitizedEnvironment");function Zn(e){if(process.platform!=="win32")return{...e};let r=new Map;for(let[n,t]of Object.entries(e))t!==void 0&&r.set(n.toLowerCase(),[n,t]);return Object.fromEntries(r.values())}s(Zn,"normalizedSandboxEnvironment");function Kr(e,r){return Zn({...e,...r})}s(Kr,"mergeSandboxEnvironment");function Ht(e){let r=i.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"?i.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??i.join(process.env.SystemRoot??"C:\\Windows","System32","cmd.exe"),args:["/d","/s","/c",e]};throw new Error(`Unsupported admitted Skill script type: ${r||"<none>"}.`)}s(Ht,"interpreterFor");var Sr=250,zt=1500;async function Yt(e,r,n=Xn,t=Kn,o){let a=[],c=[],d=e.pid===void 0?void 0:Ie(e.pid),l=0,u,g=s(()=>{},"reportStopRequested"),f,p,w=new Promise(S=>{g=S}),h=s(S=>{if(u!==void 0)return;u=S,g();let A=!1,E,L;f=new Promise((R,j)=>{E=R,L=j}),f.catch(()=>{});let P=s(async R=>{let j=await Nr(e.pid,d,Ir("Sandbox broker"),o);return R===void 0?j:new AggregateError([j,R],"Sandbox broker termination failed and its process tree may still be alive.")},"unconfirmedTermination"),ee=s(R=>{A||(A=!0,p!==void 0&&clearTimeout(p),R===void 0?E():L(R))},"finish");p=setTimeout(()=>{try{e.kill("SIGKILL"),P().then(ee)}catch(R){P(R).then(ee)}},zt),xn(e,{expectedProcessStartIdentity:d,forceMs:Sr,taskkillMs:Sr}).then(async R=>ee(R.status==="unknown"?await P():void 0),async R=>ee(await P(R)))},"requestStop"),k=s((S,A)=>{l+=A.byteLength,l>t?h(new Error(`Sandboxed command output exceeded ${t} bytes.`)):S.push(A)},"append");e.stdout?.on("data",S=>{k(a,S)}),e.stderr?.on("data",S=>{k(c,S)});let b=setTimeout(()=>{h(new Error(`Sandboxed command exceeded its ${n} ms timeout.`))},n),v=s(()=>{let S=r?.reason;h(S instanceof Error?S:new Error("Sandboxed command was cancelled."))},"abort");r?.addEventListener("abort",v,{once:!0}),r?.aborted&&v();try{let S=new Promise((E,L)=>{e.once("error",L),e.once("close",P=>E(P??1))}),A=await Promise.race([S,w.then(()=>1)]);if(u!==void 0)throw await f,u;return{exitCode:A,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}}finally{clearTimeout(b),p!==void 0&&clearTimeout(p),r?.removeEventListener("abort",v)}}s(Yt,"collectProcess");async function Xr(e,r,n=Xn,t=Kn){let o=process.platform==="win32"?await bn():ae.tmpdir(),a=i.join(o,`kodax-asrt-${process.pid}-${Y()}.json`),c=process.platform==="win32"?rr(e.config):{...e.config,filesystem:{...e.config.filesystem,denyRead:[...e.config.filesystem.denyRead,a]}},d={...e,bootstrapCommand:e.bootstrapCommand??yn(),config:c};await Re(a,JSON.stringify(d),{mode:384});let l,u,g;try{if(process.platform==="win32"){await tr(),g=await kn();let h=await or(!0);if(h.length===1)throw h[0];if(h.length>1)throw new AggregateError(h,"Cached workspace sandbox reset was not confirmed before standalone execution.")}let f=process.env.KODAX_BUNDLED==="true"?["__asrt-broker",a]:["--input-type=module","-e",Wr,Pr,a],p=Ne({args:f,env:We(),isElectron:process.versions.electron!==void 0});u=await Fr();let w=vr(process.execPath,p.args,{cwd:process.platform==="win32"?Ce().directory:void 0,env:p.env,shell:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"});return vn(w),await Yt(w,r,n,t,u)}catch(f){throw l=f,f}finally{let f=[];try{await U(a,{force:!0})}catch(p){f.push(p)}try{await In(u)}catch(p){f.push(p)}if(g!==void 0)try{await g()}catch(p){f.push(p)}if(f.length>0)throw l!==void 0&&f.unshift(l),f.length===1?f[0]:new AggregateError(f,"Sandbox broker cleanup was not confirmed.")}}s(Xr,"runBrokerResult");async function Zt(e,r){let n=await Xr(e,r);if(n.exitCode!==0){let t=n.stderr.trim()||n.stdout.trim();throw new Error(`Sandboxed Skill script failed (${n.exitCode}): ${t}`)}return n.stdout}s(Zt,"runBroker");async function Qt(e,r){let n=await je(e),t=i.resolve(e,ie(r,"Skill script input")),o=await je(t);if(!_(n,o)||qr(i.relative(n,o)))throw new Error("Skill script input is outside the permitted workspace surface.");if(!(await tn(o)).isFile())throw new Error("Skill script inputs must be files.");return o}s(Qt,"workspaceSource");async function eo(e,r){let n=await je(e),t=i.resolve(e,ie(r,"Skill script output target"));if(!_(i.resolve(e),t)||qr(i.relative(i.resolve(e),t)))throw new Error("Skill script output target is outside the permitted workspace surface.");if(await G(i.dirname(t),{recursive:!0}),!_(n,await je(i.dirname(t))))throw new Error("Skill script output target escapes through a symlink.");try{throw await tn(t),new Error("Skill script output target already exists.")}catch(o){if(o.code!=="ENOENT")throw o}return t}s(eo,"workspaceTarget");async function no(e,r,n,t){if(n.inputs.length>0&&t==="none")throw new Error("Skill script inputs require workspace read access.");for(let o of n.inputs){let a=await Qt(e,o.path),c=ie(o.as??i.basename(a),"Skill script staged input"),d=i.resolve(r,"inputs",...c.split("/"));if(!_(i.join(r,"inputs"),d))throw new Error("Skill script staged input escapes staging.");await G(i.dirname(d),{recursive:!0,mode:448}),await Ar(a,d)}}s(no,"stageInputFiles");async function ro(e,r,n,t,o){if(n.outputs.length>0&&t!=="write")throw new Error("Skill script outputs require workspace write access.");let a=[];for(let c of n.outputs){let d=ie(c.path,"Skill script staged output"),l=i.resolve(r,"outputs",...d.split("/")),u=await je(l);if(!_(i.join(r,"outputs"),u)||(await dt(l)).isSymbolicLink()||!(await tn(l)).isFile())throw new Error(`Skill script did not produce output "${d}".`);let g=await eo(e,c.target);if(o!==void 0&&Gr(e,!0)+(await tn(l)).size>o)throw new Error("Skill script outputs would exceed the remote workspace byte quota.");await Ar(l,g,at.COPYFILE_EXCL),a.push(i.relative(e,g))}return a}s(ro,"promoteOutputs");function Gr(e,r=!1){let n=0;for(let t of jn(e,{withFileTypes:!0})){if(r&&t.name===".kodax-a2a-script"||t.isSymbolicLink())continue;let o=i.join(e,t.name);t.isDirectory()?n+=Gr(o):t.isFile()&&(n+=pn(o).size)}return n}s(Gr,"directorySize");function Qn(e){if(process.platform!=="win32")return e;let r=Ce();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])]}}}s(Qn,"withPreparedWindowsRunner");function to(e,r,n,t){let o=ae.homedir(),a=process.platform==="win32"?dn():[o],c=s(d=>i.isAbsolute(d)?process.platform==="win32"?[d,i.dirname(d)]:[d]:[],"executableReadScopes");return Qn({network:{allowedDomains:[],deniedDomains:[],strictAllowlist:n.length===0,allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{denyRead:a,allowRead:[e,r,...new Set([...c(process.execPath),...c(t)])],allowWrite:[e],denyWrite:a}})}s(to,"sandboxConfig");function oo(){let e=[ae.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"&&i.isAbsolute(r)).map(r=>i.resolve(r)))]}s(oo,"canonicalTempDirectories");function Jr(e){return[i.join(e,".git","config"),i.join(e,".git","hooks")].filter(n=>{try{return pn(n),!0}catch{return!1}})}s(Jr,"existingWorkspaceDenyWrites");function er(e,r,n){let t=xt.map(a=>i.resolve(e,a)).filter(a=>i.relative(a,r)!==""),o=process.platform==="win32"?[i.resolve(r),gn()]:[i.resolve(n),...kt.map(a=>i.resolve(r,a))];return[...new Set([...o,...t])]}s(er,"workspaceShellSensitiveReadDenies");function nr(e){let r=[...new Set(e.map(t=>i.resolve(t)))].filter(t=>pn(t,{throwIfNoEntry:!1})!==void 0).sort((t,o)=>t.length-o.length),n=[];for(let t of r)n.some(o=>_(o,t))||n.push(t);return n}s(nr,"existingMinimalWindowsAclGuardRoots");function Ur(e){return i.resolve(e).toLowerCase()}s(Ur,"windowsAclGuardKey");function Ln(e,r){let n=Ur(e),t=r==="read"?Tn:new Set([...Tn,...Cr]);for(let o of t)if(n===o||n.startsWith(o.endsWith(i.sep)?o:`${o}${i.sep}`))return!0;return!1}s(Ln,"windowsAclGuardCovers");function dn(){let e=i.resolve(ae.homedir()),r=i.resolve(K());return nr(er(e,r,i.join(r,"sandbox-runtime")))}s(dn,"windowsPersistentAclGuardRoots");function Vr(e,r,n,t,o){let a=nr(e);if(a.length===0)return[];let c=JSON.stringify({sid:r,tokenSids:[r,n,"S-1-1-0","S-1-5-11","S-1-5-32-545"].filter(g=>g!==void 0),install:t,paths:a.map(g=>({path:g,directory:pn(g).isDirectory(),mode:o}))}),d=Hr(),l=Ue(d,["-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(At,"utf16le").toString("base64")],{input:c,encoding:"utf8",timeout:t&&o==="read"?15*6e4:t?15e3:5e3,windowsHide:!0});if(l.error||l.status!==0){let g=(l.error?.message||l.stderr||l.stdout||"no diagnostics").trim().slice(-4096);throw new Error(`Windows sandbox ACL guard failed: ${g}`)}let u;try{let g=JSON.parse(l.stdout.trim());u=Array.isArray(g.missing)?g.missing.filter(f=>typeof f=="string"):[]}catch(g){throw new Error(`Windows sandbox ACL guard returned invalid output: ${fe(g)}`)}if(u.length===0){let g=o==="read"?Tn:Cr;for(let f of a)g.add(Ur(f))}return u}s(Vr,"runWindowsAclGuard");function Hr(){let e=process.env.ProgramFiles??"C:\\Program Files",r=i.join(e,"PowerShell","7","pwsh.exe");return xr(r)?r:i.join(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe")}s(Hr,"windowsAclPowerShellExecutable");function Dn(e,r){if(process.platform!=="win32"||e.length===0)return;let n=e.filter(c=>!Ln(c,r));if(n.length===0)return;let t=Ce(),o=qn({srtWin:t.srtWin});if(!o.sid)throw new Error("Windows sandbox account SID is unavailable for ACL guards.");if(Vr(n,o.sid,o.groupSid,!0,r).length>0)throw new Error("Windows sandbox ACL guards were not installed completely.")}s(Dn,"installWindowsAclGuards");function rr(e){return process.platform!=="win32"?e:{...e,filesystem:{...e.filesystem,denyRead:e.filesystem.denyRead.filter(r=>!Ln(r,"read")),denyWrite:e.filesystem.denyWrite?.filter(r=>!Ln(r,"write"))}}}s(rr,"withoutWindowsAsrtDenyPropagation");function so(e,r){let n;try{n=pe.native(r)}catch{return[]}let t=[];for(let o of e){let a;try{a=pe.native(o)}catch{continue}if(!_(a,n))t.push(o);else if(a!==n){let c=i.relative(a,n).split(i.sep),d=a;try{for(let l of c){for(let u of jn(d,{withFileTypes:!0}))u.name!==l&&t.push(i.join(d,u.name));d=i.join(d,l)}}catch{}}}return process.platform!=="win32"&&t.push(r),[...new Set(t)]}s(so,"workspaceShellWriteRoots");function io(e,r){let n=process.platform==="win32"?r:i.resolve(e);return i.join(ae.tmpdir(),"kodax-sandbox",fn("sha256").update(n).digest("hex").slice(0,16))}s(io,"workspaceShellTempRoot");function ao(e,r){return i.join(io(e,r),`${process.pid}-${Y()}`)}s(ao,"createWorkspaceShellTempDirectory");async function Cn(e){await U(e,{recursive:!0,force:!0}),await lt(i.dirname(e)).catch(r=>{if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw r})}s(Cn,"removeWorkspaceShellTempDirectory");function co(e){return process.platform==="win32"?e===void 0?[]:[i.dirname(e)]:oo()}s(co,"workspaceShellTempWriteRoots");function lo(e,r,n){try{let t=pe.native(r),o=i.resolve(r),a=i.resolve(e);if(!_(o,a)||a===o)return;for(;a!==o;)try{let c=pe.native(a);if(c===t||!_(t,c))return;let d=i.relative(t,c).split(i.sep)[0]?.toLowerCase();return d==="sandbox-runtime"||n&&Jn.some(l=>l===d)?void 0:c}catch(c){if(!n||c.code!=="ENOENT")return;try{Fn(a);return}catch(l){if(l.code!=="ENOENT")return}let d=i.dirname(a);if(d===a)return;a=d}return}catch{return}}s(lo,"windowsAgentHomeAccessRoot");function zr(e,r){if(!r)return{read:[],write:[]};let n=s((t,o)=>[...new Set(t.flatMap(a=>{let c=lo(a,e,o);return c?[c]:[]}))],"roots");return{read:n(r.read,!1),write:n(r.write,!0),...r.ephemeral===!0?{ephemeral:!0}:{}}}s(zr,"windowsAgentHomeAccessRoots");function Je(e){return e??(process.platform==="win32"?process.env.COMSPEC??i.join(process.env.SystemRoot??"C:\\Windows","System32","cmd.exe"):"/bin/sh")}s(Je,"workspaceShellExecutable");function uo(e,r){return Object.entries(e).find(([n,t])=>n.toUpperCase()===r&&t!==void 0)?.[1]}s(uo,"shellEnvironmentValue");function fo(e){let r=process.env.LOCALAPPDATA,n=[r===void 0?void 0:i.join(r,"Programs"),r,process.env.APPDATA,i.join(e,"AppData","Local","Programs"),i.join(e,"AppData","Local"),i.join(e,"AppData","Roaming"),e];return[...new Set(n.flatMap(t=>t===void 0?[]:[i.resolve(t)]))].filter(t=>_(e,t)).sort((t,o)=>o.length-t.length)}s(fo,"workspaceShellUserDataBoundaries");function po(e,r,n){if(process.platform!=="win32"||e.toLowerCase()===r.toLowerCase())return[];try{if(!Fn(e).isSymbolicLink())return[]}catch{return[]}let t=n.find(d=>d.toLowerCase()!==r.toLowerCase()&&_(d,r));if(t===void 0)return[];let[o]=i.relative(t,r).split(i.sep);if(!o)return[];let a=i.join(t,o),c=[];for(let d=i.dirname(r);d.toLowerCase()!==a.toLowerCase()&&_(a,d);d=i.dirname(d))c.push(d);return c}s(po,"workspaceShellLinkedTargetAncestors");function cn(e,r){let n=i.resolve(ae.homedir()),t=i.resolve(K()),o=er(n,t,i.join(t,"sandbox-runtime")),a=fo(n),c=new Map,d=s(f=>{let p=i.resolve(f);if(!(p===i.parse(p).root||p.toLowerCase()===n.toLowerCase()||_(t,p)||_(p,t)||o.some(w=>_(w,p))))return p},"safe"),l=s((f,p)=>{let w=d(f);if(w===void 0)return;let h;try{h=pe(w)}catch{return}if(d(h)===void 0)return;let k=p?[w,h].filter(b=>_(n,b)):[w,h];for(let b of k)c.set(process.platform==="win32"?b.toLowerCase():b,b);if(p&&k.includes(h))for(let b of po(w,h,a)){let v=d(b);v!==void 0&&_(n,v)&&c.set(v.toLowerCase(),v)}},"remember");for(let f of(uo(e,"PATH")??"").split(i.delimiter)){let p=f.trim().replace(/^"(.*)"$/,"$1");p&&i.isAbsolute(p)&&l(p,!0)}let u=Je(r);i.isAbsolute(u)&&l(i.dirname(u),!0);let g=yn();if(i.isAbsolute(g)){let f=d(g);f!==void 0&&c.set(process.platform==="win32"?f.toLowerCase():f,f),l(i.dirname(g),!1)}return[...c.values()].sort((f,p)=>f.toLowerCase().localeCompare(p.toLowerCase()))}s(cn,"workspaceShellRuntimeReadScopes");function Yr(e,r,n,t,o=cn(process.env,Je())){let a=i.resolve(K()),c=i.join(a,"sandbox-runtime"),d=i.resolve(ae.homedir()),l=er(d,a,c),u=process.platform==="win32"?nr(l):l.filter(p=>p!==a),g=process.platform==="win32"?zr(a,n):{read:[],write:[]},f=so([e,...co(r),...g.write,...t?.write??[]],a);return Qn({network:{allowedDomains:[],deniedDomains:[],strictAllowlist:!1,allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{denyRead:u,allowRead:[...new Set([...o,...g.read,...t?.read??[]])],allowWrite:f,denyWrite:[c,...Jn.map(p=>i.join(a,p)),...Jr(e)]}})}s(Yr,"workspaceShellSandboxConfig");function Zr(e,r,n,t,o){let a=Yr(e,r,n,t,o);return process.platform!=="win32"?a:Qr(a)}s(Zr,"workspaceShellSessionSandboxConfig");function Qr(e){let r=e.filesystem.allowWrite;return{...e,filesystem:{...e.filesystem,denyRead:e.filesystem.denyRead,denyWrite:e.filesystem.denyWrite.filter(n=>r.some(t=>_(t,n)))}}}s(Qr,"boundedWindowsWorkspaceDenies");function wo(e,r,n,t,o){let a=Yr(e,r,n,t,o);return process.platform==="win32"?Qr(a):a}s(wo,"workspaceShellCommandSandboxConfig");function Qe(e,r){return[...new Set((e??[]).map(n=>i.resolve(r,n)))]}s(Qe,"normalizedSandboxPaths");function mo(e){return e.mode!=="allowlist"?[]:e.origins.map(r=>{let n=new URL(r);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: ${r}`);return{host:n.hostname.toLowerCase(),port:n.port?Number(n.port):n.protocol==="https:"?443:80}})}s(mo,"sdkSandboxEndpoints");async function es(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=i.resolve(e.cwd),n=e.network??{mode:"deny"},t=mo(n),o=await ne();if(!o.ready){if(!wn(o))return{status:"unavailable",sandboxed:!1,doctor:o};if(await an(),o.setupRequired)return{status:"unavailable",sandboxed:!1,doctor:o}}let a=Kr(e.inheritEnvironment===!0?process.env:We(),e.env??{}),c={config:Qn({network:{allowedDomains:[],deniedDomains:[],strictAllowlist:n.mode==="deny",allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{allowRead:Qe(e.filesystem.allowRead,r),allowWrite:Qe(e.filesystem.allowWrite,r),denyRead:Qe(e.filesystem.denyRead,r),denyWrite:Qe(e.filesystem.denyWrite,r)}}),command:e.command,args:e.args??[],cwd:r,env:a,endpoints:t,allowAllNetwork:n.mode==="allow"},d=await Xr(c,e.signal,e.timeoutMs??Xn,e.maxOutputBytes??Kn);return{status:"completed",sandboxed:!0,exitCode:d.exitCode,stdout:d.stdout,stderr:d.stderr}}s(es,"runKodaXSandboxed");var go=5*6e4,yo=3e4,So=3e4,en=1500,et=13e4,ho=et,bo=So,vo=ho,xo=8,I=new Map,Fe=new Set,ke=new Set,Ae=new Set,Be,Bn,ln=!1;function ge(e){let r=e instanceof Error?e:new Error(String(e));if(process.platform!=="win32"){Bn??=r;return}Be??=r}s(ge,"recordWindowsSandboxAclFailure");function Sn(){if(process.platform!=="win32"&&Bn!==void 0)throw new Error("Sandbox process cleanup was not confirmed; stop the retained process tree before more sandboxed commands.",{cause:Bn});if(process.platform==="win32"&&Be!==void 0)throw Be instanceof B?Be:new Error("Windows sandbox ACL cleanup was not confirmed; stop the retained owner or restart Windows before more sandboxed commands.",{cause:Be})}s(Sn,"assertWindowsSandboxAclProcessSafe");function hn(e){Sn(),process.platform==="win32"&&Yn(e)}s(hn,"assertWindowsSandboxAclSafe");function nt(e){ke.add(e),e.then(()=>ke.delete(e),()=>ke.delete(e))}s(nt,"trackWorkspaceSessionReset");function ko(e){Ae.add(e),e.then(()=>Ae.delete(e),r=>{Ae.delete(e),W({source:"sandbox:workspace-session",level:"error",message:"Workspace sandbox durable ACL poison transition failed.",detail:r})})}s(ko,"trackWindowsSandboxAclTransition");async function Ao(){for(;Ae.size>0;)await Promise.allSettled([...Ae])}s(Ao,"waitForWindowsSandboxAclTransitions");async function tr(){for(;ke.size>0;)await Promise.allSettled([...ke]);await Ao(),Sn()}s(tr,"waitForWorkspaceSessionResets");async function or(e=!1){let r=[...I.values()];I.clear();let n=[];for(let t of r)try{await(await t).close(e)}catch(o){n.push(o),W({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox shutdown could not confirm ACL reset.",detail:o})}return n}s(or,"closeCachedWorkspaceSessions");var rt=s(()=>{ln=!1,or()},"closeWorkspaceSessionsBeforeExit");function Eo(){ln||(ln=!0,process.once("beforeExit",rt))}s(Eo,"registerWorkspaceSessionBeforeExit");async function ns(){for(process.removeListener("beforeExit",rt),ln=!1;Fe.size>0;)await Promise.allSettled([...Fe]);let e=await or();try{await tr()}catch(r){e.push(r)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"Workspace sandbox shutdown was not confirmed.")}s(ns,"shutdownAsrtWorkspaceSessions");function tt(){let e=new Error("ASRT workspace session preparation timed out.");return e.name="TimeoutError",e}s(tt,"workspacePreparationTimeoutError");function un(e,r){if(e?.aborted)throw new DOMException("Operation aborted","AbortError");if(r!==void 0&&Date.now()>=r)throw tt()}s(un,"throwIfWorkspacePreparationStopped");function Mn(e,r,n){return un(r,n),r===void 0&&n===void 0?e:new Promise((t,o)=>{let a=!1,c,d=s(u=>{a||(a=!0,c&&clearTimeout(c),r?.removeEventListener("abort",l),u())},"finish"),l=s(()=>{d(()=>o(new DOMException("Operation aborted","AbortError")))},"onAbort");r?.addEventListener("abort",l,{once:!0}),n!==void 0&&(c=setTimeout(()=>{d(()=>o(tt()))},Math.max(0,n-Date.now())),c.unref()),e.then(u=>d(()=>t(u)),u=>d(()=>o(u)))})}s(Mn,"waitForWorkspacePreparation");async function bn(){let e=i.join(K(),"sandbox-runtime");return await G(e,{recursive:!0,mode:448}),e}s(bn,"sandboxControlDirectory");function Ro(e){if(process.env.KODAX_BUNDLED==="true")return["__asrt-workspace-session",e];if(import.meta.url.endsWith(".ts"))return["--import",Er(Gn.resolve("tsx")).href,pr(new URL("./sandbox-workspace-session-entry.ts",import.meta.url)),e];let r=i.dirname(pr(import.meta.url)),n=i.basename(r)==="chunks"?i.dirname(r):r;return[i.join(n,"sandbox-workspace-session.js"),e]}s(Ro,"workspaceSessionEntryArgs");function nn(e,r){let n=r?"ref":"unref";e[n]();for(let t of e.stdio){if(!t)continue;t[n]?.()}}s(nn,"setWorkspaceSessionReferenced");async function ot(e,r,n){if(e)return r();let t=await kn(n);try{return await r()}finally{await t()}}s(ot,"withExclusiveFileSystemEffectFence");async function Po(e,r,n,t,o,a,c){let d=process.platform==="win32"?ao(e,o):void 0;d!==void 0&&await G(d,{recursive:!0,mode:448});let l=await bn();process.platform==="win32"&&Dn(Jr(e),"write");let u=i.join(l,`workspace-${process.pid}-${Y()}.json`),g=rr(Zr(e,d,r,n,t));await Re(u,JSON.stringify({config:g}),{mode:384});let f=Ne({args:Ro(u),env:We(),isElectron:process.versions.electron!==void 0}),p;try{p=await Fr(o)}catch(y){let m=await Promise.allSettled([U(u,{force:!0}),...d===void 0?[]:[Cn(d)]]),x=[y,...m.flatMap(C=>C.status==="rejected"?[C.reason]:[])];throw x.length===1?y:new AggregateError(x,"Workspace sandbox owner admission and pre-launch cleanup both failed.")}let w;try{w=vr(process.execPath,f.args,{cwd:process.platform==="win32"?Ce().directory:void 0,env:f.env,shell:!1,stdio:["pipe","pipe","pipe","pipe"],windowsHide:!0})}catch(y){let m=[y];try{await In(p)}catch(C){await Ze(p,C),m.push(C)}let x=await Promise.allSettled([U(u,{force:!0}),...d===void 0?[]:[Cn(d)]]);throw m.push(...x.flatMap(C=>C.status==="rejected"?[C.reason]:[])),m.length===1?y:new AggregateError(m,"Workspace sandbox owner launch cleanup failed.")}vn(w);let h=w.pid===void 0?void 0:Ie(w.pid),k=w.stdio[3];if(!k)throw new Error("ASRT workspace session control pipe was not created.");let b=pt.createInterface({input:k}),v=new Map,S="",A=!1,E=!1,L=!1,P=!1,ee=0,R=0,j,q,ce,ye=new Promise(y=>{w.once("exit",(m,x)=>y({code:m,signal:x}))}),Se=ye.then(async()=>{if(d!==void 0)try{await Cn(d)}catch(y){W({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox temp cleanup failed.",detail:y})}}),Ve=s(async(y=!1)=>{let m=await ye;await Se;let x=[];if(!y&&(m.code!==0||m.signal!==null)){let C=m.signal===null?`code ${m.code??"unknown"}`:`signal ${m.signal}`;x.push(new Error(`ASRT workspace session ACL reset was not confirmed (${C}): ${S.trim()||"no diagnostics"}`))}try{await In(p)}catch(C){x.push(C)}if(x.length===1)throw x[0];if(x.length>1)throw new AggregateError(x,"Workspace sandbox cleanup was not confirmed.")},"confirmCleanReset"),M,V,F=new Promise((y,m)=>{M=y,V=m}),$e=s(()=>{P||(P=!0,c())},"evict"),He=s(async()=>{if(!E||!L||R!==0||w.exitCode!==null||w.signalCode!==null||!w.stdin.writable)return!1;try{w.stdin.end()}catch{return!1}let y;try{let m=await Promise.race([ye,new Promise(x=>{y=setTimeout(x,process.platform==="win32"?et:en)})]);return m!==void 0&&m.code===0&&m.signal===null}finally{y!==void 0&&clearTimeout(y)}},"waitForOrderlyClose"),N,Te=!1,sr=!1,te=s(()=>N||(sr=!0,N=(async()=>{try{if(await He())return;if((await xn(w,{gracefulStdinEnd:!1,gracefulMs:en,forceMs:en,taskkillMs:en})).status==="unknown")throw await Nr(w.pid,h,Ir("ASRT workspace session"),p);Te=!0}finally{b.close(),k.destroy(),w.stdin.destroy()}})().finally($e),N),"terminate"),oe=s(y=>{if(!A){A=!0,V(y);for(let m of v.values())m.reject(y);v.clear()}},"fail");w.stderr.on("data",y=>{S=(S+y.toString("utf8")).slice(-16384)}),w.stdout.on("data",y=>{S=(S+y.toString("utf8")).slice(-16384)}),b.on("line",y=>{let m;try{m=JSON.parse(y)}catch{oe(new Error("ASRT workspace session returned malformed control data.")),te();return}if(m.type==="ready"){m.ok?(L=!0,M()):V(new Error(m.error??"ASRT workspace session failed."));return}if(m.type!=="result"||!m.id){oe(new Error("ASRT workspace session returned an invalid control response.")),te();return}let x=v.get(m.id);x&&(v.delete(m.id),x.resolve(m))}),w.once("error",y=>{oe(y),te()}),b.once("close",()=>{E||A||(oe(new Error("ASRT workspace session control pipe closed unexpectedly.")),te())}),w.once("exit",(y,m)=>{q&&clearTimeout(q);let x=new Error(`ASRT workspace session exited ${m??y??1}: ${S.trim()||"no diagnostics"}`);!sr&&(y!==0||m!==null||!E)&&ko(Ze(p,x)),oe(x),$e()});let it=setTimeout(()=>{oe(new Error("ASRT workspace session initialization timed out.")),te()},yo);try{await F.finally(()=>clearTimeout(it))}catch(y){E=!0;let m=[y],x=!1;try{await te(),x=!0}catch(C){m.push(C)}if(x)try{await Ve(Te)}catch(C){await Ze(p,C),m.push(C)}throw await U(u,{force:!0}),m.length===1?y:new AggregateError(m,`Workspace sandbox startup cleanup failed: ${fe(m.at(-1))}`)}let ze=s(async(y,m)=>{if(A||E&&y==="wrap")throw new Error("ASRT workspace session is unavailable.");let x=`workspace_${++ee}`,C=new Promise((D,be)=>{v.set(x,{resolve:D,reject:be})}),se=setTimeout(()=>{oe(new Error(`ASRT workspace session ${y} request timed out.`)),he.close(a).catch(D=>{W({source:"sandbox:workspace-session",level:"warn",message:"Timed-out workspace sandbox request could not retire its session.",detail:D})})},y==="cleanup"?vo:bo);se.unref();try{await new Promise((D,be)=>{w.stdin.write(`${JSON.stringify({id:x,type:y,request:m})}
518
+ `,_e=>_e?be(_e):D())})}catch(D){throw v.delete(x),clearTimeout(se),oe(D instanceof Error?D:new Error(String(D))),te(),D}return C.finally(()=>clearTimeout(se))},"request"),ir=s(()=>{if(q&&clearTimeout(q),!(R>0||E||A)){if(process.platform==="win32"){nn(w,!1);return}q=setTimeout(()=>{he.close().catch(y=>{W({source:"sandbox:workspace-session",level:"warn",message:"Idle workspace sandbox session could not confirm ACL reset.",detail:y})})},go),q.unref(),nn(w,!1)}},"scheduleIdleClose"),he={policyKey:o,...d===void 0?{}:{tempDirectory:d},async acquire(y,m,x){if(hn(o),un(m,x),A||E)throw new Error("ASRT workspace session is unavailable.");q&&clearTimeout(q),nn(w,!0),R+=1;let C=!1,se=s(()=>{if(C)return!1;C=!0,R-=1;let H=R===0;return R===0&&(j?.(),j=void 0),ir(),H},"finalize"),D=s(async()=>{se()&&process.platform==="win32"&&await he.close(a)},"finalizeAndCloseIfIdle"),be=s((H,$)=>{W({source:"sandbox:workspace-session",level:"warn",message:H,detail:$}),se()&&he.close(a).catch(z=>{W({source:"sandbox:workspace-session",level:"warn",message:"Failed workspace sandbox cleanup could not retire its session.",detail:z})})},"retireAfterCleanupFailure"),_e=ze("wrap",y),Oe;try{Oe=await Mn(_e,m,x)}catch(H){throw _e.then(async $=>{if(!$.ok||!$.invocation)return;let T=await ze("cleanup");if(!T.ok)throw new Error(T.error??"ASRT command cleanup failed.")}).then(D,$=>be("Late workspace sandbox preparation cleanup failed.",$)),H}try{if(!Oe.ok||!Oe.invocation){se();let $=new Error(Oe.error??"ASRT workspace wrapping failed.");try{await he.close(a)}catch(T){let z=T instanceof Error?T.message:String(T);throw new Error(`${$.message} Workspace session reset failed: ${z}`,{cause:$})}throw $}try{un(m,x)}catch($){try{let T=await ze("cleanup");if(!T.ok)throw new Error(T.error??"ASRT command cleanup failed.")}catch(T){be("Cancelled workspace sandbox preparation cleanup failed.",T)}throw await D(),$}let H=!1;return{invocation:Oe.invocation,async release(){if(H)return;H=!0;let $;try{let z=await ze("cleanup");if(!z.ok)throw new Error(z.error??"ASRT command cleanup failed.")}catch(z){$=z}let T;try{await D()}catch(z){T=z}if($!==void 0&&T!==void 0)throw new AggregateError([$,T],"Workspace sandbox command cleanup and policy-group reset both failed.");if($!==void 0)throw $;if(T!==void 0)throw T}}}catch(H){throw se(),H}},async close(y=!1){return ce||(E=!0,$e(),ce=(async()=>{q&&clearTimeout(q),nn(w,!0),R>0&&await new Promise(m=>{j=m}),await ot(a||y,async()=>{await te(),await Ve()},o)})().catch(async m=>{throw await Ze(p,m),m}),nt(ce),ce)}};return ir(),he}s(Po,"startWorkspaceSessionClientWithFence");function hr(e,r,n,t,o,a,c){return ot(a,async()=>{if(st(e,r,n,t)!==o)throw new Error("Sandbox policy paths changed before ACL initialization.");return hn(o),await an(o),Po(e,r,n,t,o,a,c)},o)}s(hr,"startWorkspaceSessionClient");function Wn(e){return[...new Set(e.map(r=>{let n=i.resolve(r);return process.platform==="win32"?n.toLowerCase():n}))].sort()}s(Wn,"normalizedWorkspacePolicyPaths");function Me(e){let r=s(t=>{let o=i.resolve(t);return process.platform==="win32"?o.toLowerCase():o},"normalize"),n=null;try{n=r(pe.native(e))}catch{}return{lexical:r(e),canonical:n}}s(Me,"workspacePolicyPathIdentity");function rn(e){let r=new Map;for(let n of e){let t=Me(n);r.set(`${t.lexical}\0${t.canonical??""}`,t)}return[...r.values()].sort((n,t)=>n.lexical.localeCompare(t.lexical)||(n.canonical??"").localeCompare(t.canonical??""))}s(rn,"workspacePolicyPathIdentities");function st(e,r,n,t){let o=Zr(e,void 0,r,n,t);return fn("sha256").update(JSON.stringify({workspace:Me(e),agentHome:Me(K()),tempBase:Me(ae.tmpdir()),filesystem:{allowRead:rn(o.filesystem.allowRead),allowWrite:rn(o.filesystem.allowWrite),denyRead:rn(o.filesystem.denyRead),denyWrite:rn(o.filesystem.denyWrite)},network:o.network,windowsRunner:process.platform==="win32"?{version:ue,architecture:process.arch,path:Me(Ce().path)}:null,ephemeral:r?.ephemeral===!0})).digest("hex")}s(st,"workspaceShellPolicyKey");function Co(e){return process.platform!=="win32"?!0:(e?.write??[]).every(r=>{try{return pe.native(r),!0}catch{return!1}})}s(Co,"workspaceShellFilesystemAccessIsRepresentable");async function br(e,r,n,t=cn(process.env,Je()),o=t,a=!1){if(process.platform==="win32"){if(ke.size>0||Ae.size>0)return}else await tr();Sn();let c=await ne();if(!c.ready&&!wn(c))return;if(process.platform!=="win32"){let v=K();await Promise.all([bn(),...Jn.map(S=>G(i.join(v,S),{recursive:!0,mode:448}))])}let d=st(e,process.platform==="win32"?r:void 0,n,t);if(!c.ready&&(await an(d),c.setupRequired))return;await an(d),hn(d),Eo();let l=process.platform==="win32"?r:void 0,u=process.platform==="win32"?e.toLowerCase():e,g=Wn,f=g(t),p=JSON.stringify(f)===JSON.stringify(g(o)),w=(n?.read.length??0)>0||(n?.write.length??0)>0,h=l===void 0&&!w&&p?"workspace":fn("sha256").update(JSON.stringify({read:[...l?.read??[]].map(v=>v.toLowerCase()).sort(),write:[...l?.write??[]].map(v=>v.toLowerCase()).sort(),additionalRead:Wn(n?.read??[]),additionalWrite:Wn(n?.write??[]),runtimeReadScopes:f})).digest("hex"),k=process.platform==="win32"?d:`${u}\0${h}`;if(process.platform==="win32"&&a){let v=l?.ephemeral===!0?void 0:k;for(let[S,A]of[...I])if(S!==v){I.delete(S);try{await(await A).close(!0)}catch(E){throw W({source:"sandbox:workspace-session",level:"warn",message:"Retiring the previous Windows workspace sandbox scope failed.",detail:E}),E}}}if(l?.ephemeral===!0)return hr(e,l,n,t,d,a,()=>{});let b=I.get(k);if(b&&(I.delete(k),I.set(k,b)),!b){if(process.platform!=="win32"&&h!=="workspace"){let v=[...I.keys()].filter(S=>!S.endsWith("\0workspace"));if(v.length>=xo){let S=v[0],A=I.get(S);if(I.delete(S),A)try{await(await A).close()}catch(E){throw W({source:"sandbox:workspace-session",level:"warn",message:"Retiring an old scoped workspace sandbox failed.",detail:E}),E}}}b=hr(e,l,n,t,d,a,()=>{I.get(k)===b&&I.delete(k)}),I.set(k,b),b.catch(()=>{I.get(k)===b&&I.delete(k)})}return b}s(br,"getWorkspaceSession");function rs(e){let r=i.resolve(e.workspaceRoot),n=cn(process.platform==="win32"?{}:process.env,Je()),t=process.platform==="win32"?void 0:br(r,void 0,void 0,n,n);return t!==void 0&&(Fe.add(t),t.then(()=>Fe.delete(t),()=>Fe.delete(t)),t.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 a={id:o.toolCallId,name:"bash",input:{...o.toolInput}},c=await e.shouldSandbox(a);if(!c){o.reportObservation?.({version:1,state:"not_selected"});return}let d=typeof c=="object"?c.agentHomeAccess:void 0,l=process.platform==="win32"&&d!==void 0?zr(i.resolve(K()),d):d,u=typeof c=="object"?c.filesystemAccess:void 0;if(!Co(u)){o.reportObservation?.({version:1,state:"fallback",reason:"not_ready",execution:"normal_permission_policy"});return}let g=process.platform==="win32"&&l?.ephemeral===!0,f=Je(o.executable),p=o.args??(process.platform==="win32"?["/d","/s","/c",o.command]:["-c",o.command]),w=Zn(o.env),h=cn(w,f),k,b;try{t!==void 0&&(await Mn(t.then(()=>{},()=>{}),o.signal,o.deadlineAt),un(o.signal,o.deadlineAt));let v=br(r,l,u,h,n),S;try{S=await Mn(v,o.signal,o.deadlineAt)}catch(M){if(process.platform==="win32"&&(o.signal?.aborted||o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt)){let V=v.then(async F=>{F&&await F.close()},async()=>{});nt(V),V.catch(F=>{W({source:"sandbox:workspace-session",level:"warn",message:"Late cancelled workspace session rollback failed.",detail:F})})}throw M}if(!S){o.reportObservation?.({version:1,state:"fallback",reason:"not_ready",execution:"normal_permission_policy"});return}let A=S.policyKey;b=S;let E=await bn(),L=i.join(E,`kodax-asrt-shell-${process.pid}-${Y()}.json`),P=i.join(E,`kodax-asrt-observation-${process.pid}-${Y()}.json`),ee=w;if(process.platform==="win32"){let M=S.tempDirectory;if(M===void 0)throw new Error("Windows workspace sandbox temp directory is unavailable.");ee=Kr(w,{TEMP:M,TMP:M,TMPDIR:M,GIT_CONFIG_GLOBAL:"NUL",GIT_CONFIG_NOSYSTEM:"1"})}let R={config:rr(wo(r,S.tempDirectory,l,u,h)),command:f,args:p,windowsVerbatimArguments:o.windowsVerbatimArguments===!0,cwd:o.cwd,env:ee,endpoints:[],allowAllNetwork:!0,bootstrapCommand:yn(),fallbackToNormalExecution:!0,observationBackend:ht().backend,observationFile:P,targetStartedMarker:`\0KODAX_ASRT_TARGET_STARTED:${Y()}\0
519
+ `},j=await S.acquire(R,o.signal,o.deadlineAt);k=j;let q={...R,wrappedInvocation:j.invocation},ce=process.env.KODAX_BUNDLED==="true"?["__asrt-broker",L]:["--input-type=module","-e",Wr,Pr,L],ye=Ne({args:ce,env:We(),isElectron:process.versions.electron!==void 0});await Re(L,JSON.stringify(q),{mode:384});let Se,Ve=s(async()=>{g||(Se===void 0&&(Se=b?.close(!1)??Promise.resolve(),Se.catch(M=>{W({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox session retirement failed.",detail:M})})),process.platform==="win32"&&await Se)},"retireWorkspaceSession");return{executable:process.execPath,args:ye.args,env:ye.env,fileSystemEffectPolicyKey:A,authorizeStart:s(()=>hn(A),"authorizeStart"),async cleanup(M){let V,F=[];try{V=await Ee(P,"utf8").then(qt).catch(N=>{if(N.code!=="ENOENT")throw N})}catch(N){F.push(N)}let $e=await Promise.allSettled([U(L,{force:!0}),U(P,{force:!0})]);for(let N of $e)N.status==="rejected"&&F.push(N.reason);try{await j.release()}catch(N){F.push(N)}let He=M?.execution==="started_or_unknown"&&V===void 0;if(He&&F.push(new Error("Required OS sandbox execution could not be attested; the workspace session must be retired and the command was not retried")),F.length>0){let N=He?"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.",Te=new AggregateError(F,N);throw W({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox command cleanup failed.",detail:Te}),Te}return V},retire:Ve}}catch(v){let S=[v],A=o.signal?.aborted||o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt,E=!1;if(k)try{await k.release()}catch(P){E=!0,S.push(P),W({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox lease release failed.",detail:P})}if(A&&process.platform==="win32"&&b&&k===void 0)throw b.close().catch(P=>{W({source:"sandbox:workspace-session",level:"warn",message:"Cancelled workspace preparation cleanup could not retire its session.",detail:P})}),v;if(process.platform==="win32"&&b)try{await b.close()}catch(P){S.push(P),W({source:"sandbox:workspace-session",level:"warn",message:"Failed workspace lease cleanup could not retire its session.",detail:P})}else E&&b&&b.close().catch(P=>{W({source:"sandbox:workspace-session",level:"warn",message:"Failed workspace lease cleanup could not retire its session.",detail:P})});if(A)throw v;let L=S.length===1?v:new AggregateError(S,`Workspace sandbox preparation failed and cleanup was incomplete: ${S.map(fe).join(" | ")}`);W({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox preparation failed; using normal permission fallback.",detail:L}),o.reportObservation?.({version:1,state:"fallback",reason:"prepare_failed",execution:"normal_permission_policy"});return}}}}s(rs,"createAsrtShellSandbox");async function ts(e){let r=await ne();if(!r.ready)throw new Error(`ASRT ${ue} is not ready: ${r.diagnostics.join(" ")||"run kodax sandbox setup"}`);let n=i.join(e.snapshotRoot,Y()),t=i.join(n,"skills");await G(t,{recursive:!0,mode:448});try{let o=await Ut(e,t),a=Vt(e.network),c=Promise.resolve();return{async run(d,l){let u=c,g;if(c=new Promise(f=>{g=f}),await u,l.signal?.aborted)throw g?.(),l.signal.reason??new Error("Sandboxed Skill script was cancelled.");try{if(d.args.length>64||d.args.some(h=>h.length>8192))throw new Error("Skill script arguments exceed the bounded remote contract.");if(d.inputs.length>32||d.outputs.length>32)throw new Error("Skill script file mappings exceed the bounded remote contract.");let f=ie(d.script,"Skill script"),p=o.get(`${d.skill}\0${f}`);if(!p)throw new Error("Skill script is not admitted by this Runtime binding.");if([".cmd",".bat"].includes(i.extname(p.snapshotPath).toLowerCase())&&d.args.some(h=>/[&|<>^]/.test(h)))throw new Error("Batch Skill script arguments cannot contain command operators.");let w=i.join(l.workspaceRoot,".kodax-a2a-script",Y());try{await G(i.join(w,"inputs"),{recursive:!0,mode:448}),await G(i.join(w,"outputs"),{recursive:!0,mode:448}),await no(l.workspaceRoot,w,d,e.workspaceAccess);let h=Ht(p.snapshotPath),k=await Zt({config:to(w,n,a,h.command),command:h.command,args:[...h.args,...d.args],cwd:w,env:We(),endpoints:a},l.signal),b=await ro(l.workspaceRoot,w,d,e.workspaceAccess,e.workspaceByteLimit);return JSON.stringify({stdout:k.trim(),outputs:b})}finally{await U(w,{recursive:!0,force:!0})}}finally{g?.()}},async dispose(){await c,await U(n,{recursive:!0,force:!0})}}}catch(o){throw await U(n,{recursive:!0,force:!0}),o}}s(ts,"createAsrtSkillScriptRunner");export{ue as a,ht as b,Vo as c,Ho as d,zo as e,Yo as f,Zo as g,ne as h,Gt as i,xe as j,Qo as k,es as l,ns as m,rs as n,ts as o};