@kodax-ai/kodax 0.7.78 → 0.7.80

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 (126) hide show
  1. package/CHANGELOG.md +3556 -3197
  2. package/README.md +371 -277
  3. package/README_CN.md +295 -215
  4. package/config-templates/config.example.jsonc +24 -2
  5. package/config-templates/integrations/a2a.example.jsonc +23 -7
  6. package/dist/builtin/skill-creator/scripts/aggregate-benchmark.js +2 -1
  7. package/dist/builtin/skill-creator/scripts/analyze-benchmark.d.ts +1 -0
  8. package/dist/builtin/skill-creator/scripts/analyze-benchmark.js +4 -3
  9. package/dist/builtin/skill-creator/scripts/compare-runs.d.ts +1 -0
  10. package/dist/builtin/skill-creator/scripts/compare-runs.js +4 -3
  11. package/dist/builtin/skill-creator/scripts/generate-review.js +2 -1
  12. package/dist/builtin/skill-creator/scripts/grade-evals.d.ts +1 -0
  13. package/dist/builtin/skill-creator/scripts/grade-evals.js +4 -3
  14. package/dist/builtin/skill-creator/scripts/improve-description.js +2 -1
  15. package/dist/builtin/skill-creator/scripts/init-skill.d.ts +1 -0
  16. package/dist/builtin/skill-creator/scripts/init-skill.js +4 -3
  17. package/dist/builtin/skill-creator/scripts/install-skill.d.ts +1 -0
  18. package/dist/builtin/skill-creator/scripts/install-skill.js +4 -3
  19. package/dist/builtin/skill-creator/scripts/package-skill.d.ts +1 -0
  20. package/dist/builtin/skill-creator/scripts/package-skill.js +4 -3
  21. package/dist/builtin/skill-creator/scripts/quick-validate.d.ts +1 -0
  22. package/dist/builtin/skill-creator/scripts/quick-validate.js +4 -3
  23. package/dist/builtin/skill-creator/scripts/run-eval.d.ts +1 -0
  24. package/dist/builtin/skill-creator/scripts/run-eval.js +4 -3
  25. package/dist/builtin/skill-creator/scripts/run-loop.js +2 -1
  26. package/dist/builtin/skill-creator/scripts/run-trigger-eval.js +2 -1
  27. package/dist/builtin/skill-creator/scripts/utils.d.ts +3 -0
  28. package/dist/builtin/skill-creator/scripts/utils.js +5 -1
  29. package/dist/chunks/agent-5PHGNFW3.js +2 -0
  30. package/dist/chunks/argument-completer-FXRZFMTC.js +2 -0
  31. package/dist/chunks/chunk-6UENDY33.js +89 -0
  32. package/dist/chunks/{chunk-6FOJVETH.js → chunk-BWX4YZX3.js} +7 -7
  33. package/dist/chunks/chunk-CDCCTM5I.js +278 -0
  34. package/dist/chunks/chunk-CEB5FDND.js +810 -0
  35. package/dist/chunks/{chunk-2CFHBKRE.js → chunk-E7C4DRD2.js} +2 -2
  36. package/dist/chunks/chunk-EVXIJPZ6.js +218 -0
  37. package/dist/chunks/chunk-FQ7NVMSU.js +319 -0
  38. package/dist/chunks/chunk-GC4JBMBS.js +385 -0
  39. package/dist/chunks/{chunk-Z3KFRTSB.js → chunk-HTVLCHWH.js} +1 -1
  40. package/dist/chunks/chunk-IHPH3444.js +655 -0
  41. package/dist/chunks/{chunk-YAZQTC2L.js → chunk-KHEFUT6O.js} +1 -1
  42. package/dist/chunks/{chunk-7OEBJGHK.js → chunk-PMKAG4SZ.js} +1 -1
  43. package/dist/chunks/chunk-RPF5RGWZ.js +479 -0
  44. package/dist/chunks/{chunk-UID7BLAB.js → chunk-RXXKDR6Y.js} +1 -1
  45. package/dist/chunks/chunk-T5U4OP2N.js +292 -0
  46. package/dist/chunks/chunk-TRNAWSXP.js +123 -0
  47. package/dist/chunks/chunk-UZSHBQER.js +30 -0
  48. package/dist/chunks/{chunk-TQDBTTIM.js → chunk-VECRQTSD.js} +44 -44
  49. package/dist/chunks/compaction-config-6J6XCBJS.js +2 -0
  50. package/dist/chunks/{construction-bootstrap-VQLQGWPY.js → construction-bootstrap-KPCAE3VN.js} +1 -1
  51. package/dist/chunks/dist-RWEVZOFK.js +2 -0
  52. package/dist/chunks/{dist-BFT5YIGU.js → dist-WWL2DNIJ.js} +1 -1
  53. package/dist/chunks/host-OGS2R5J4.js +2 -0
  54. package/dist/chunks/run-manager-2YMM3BOT.js +2 -0
  55. package/dist/chunks/{utils-SID4HW2Q.js → utils-2YHRUZYC.js} +1 -1
  56. package/dist/index.d.ts +21 -20
  57. package/dist/index.js +4 -4
  58. package/dist/kodax_bootstrap.js +2 -1
  59. package/dist/kodax_cli.js +1850 -1476
  60. package/dist/kodax_resume.js +570 -34
  61. package/dist/provider-capabilities.json +85 -50
  62. package/dist/runtime-worker.js +1737 -1369
  63. package/dist/sandbox-workspace-session.js +285 -19
  64. package/dist/sdk-a2a.d.ts +19 -13
  65. package/dist/sdk-a2a.js +8 -8
  66. package/dist/sdk-agent.d.ts +80 -150
  67. package/dist/sdk-agent.js +1 -1
  68. package/dist/sdk-coding.d.ts +186 -66
  69. package/dist/sdk-coding.js +1 -1
  70. package/dist/sdk-experimental-memory.d.ts +3 -3
  71. package/dist/sdk-experimental-memory.js +1 -1
  72. package/dist/sdk-llm.d.ts +7 -7
  73. package/dist/sdk-llm.js +1 -1
  74. package/dist/sdk-mcp.d.ts +1 -1
  75. package/dist/sdk-mcp.js +1 -1
  76. package/dist/sdk-media.d.ts +1 -1
  77. package/dist/sdk-media.js +1 -1
  78. package/dist/sdk-repl.d.ts +31 -213
  79. package/dist/sdk-repl.js +2 -2
  80. package/dist/sdk-runtime.d.ts +230 -31
  81. package/dist/sdk-runtime.js +1 -1
  82. package/dist/sdk-sandbox.js +1 -1
  83. package/dist/sdk-session.d.ts +8 -8
  84. package/dist/sdk-session.js +1 -1
  85. package/dist/sdk-skills.js +1 -1
  86. package/dist/semantic-worker.js +283 -18
  87. package/dist/types-chunks/{base.d-4e74xDdy.d.ts → base.d-DxG0m09Z.d.ts} +1 -1
  88. package/dist/types-chunks/{bash-prefix-extractor.d-uAe2Oqda.d.ts → bash-prefix-extractor.d-DStqKIlu.d.ts} +31 -8
  89. package/dist/types-chunks/{capability-learning.d-CVsdHw4j.d.ts → capability-learning.d-iPSiAmc_.d.ts} +1 -1
  90. package/dist/types-chunks/{capsule.d-BlSv9l3V.d.ts → capsule.d-BuFJaYxA.d.ts} +14 -21
  91. package/dist/types-chunks/{types.d-BA-Jwpfs.d.ts → controller.d-C2aHqzHj.d.ts} +344 -11
  92. package/dist/types-chunks/{guardrail.d-CXDYRgZ3.d.ts → guardrail.d-DM-OK0m3.d.ts} +187 -116
  93. package/dist/types-chunks/{history-retrieval.d-DtCy7x64.d.ts → history-retrieval.d-DImTKgO6.d.ts} +16 -3
  94. package/dist/types-chunks/{oauth-login.d-Bgb4rdLN.d.ts → oauth-login.d-6i-vidxv.d.ts} +6 -2
  95. package/dist/types-chunks/{public-api.d-B3AohsxN.d.ts → public-api.d-CewTvUKV.d.ts} +335 -38
  96. package/dist/types-chunks/{repl.d-Ie_ZXb_U.d.ts → repl.d-DvXQtgr7.d.ts} +5 -5
  97. package/dist/types-chunks/{resolver.d-iAQ9ocLB.d.ts → resolver.d-C9IW4fmU.d.ts} +5 -2
  98. package/dist/types-chunks/{run-manager.d-D1twIhF9.d.ts → run-manager.d-C6ahvZqK.d.ts} +1 -1
  99. package/dist/types-chunks/{sdk-session-DB9KksIx.d.ts → sdk-session-C59RUrri.d.ts} +3 -3
  100. package/dist/types-chunks/shell-command-sets.d-Dp4UvPLL.d.ts +297 -0
  101. package/dist/types-chunks/{side-query.d-DTuLPcC5.d.ts → side-query.d-CP1LiRiH.d.ts} +8 -2
  102. package/dist/types-chunks/{types-D3g6XUQr.d.ts → types-Bf3Y3mW-.d.ts} +1 -1
  103. package/dist/types-chunks/{types.d-BH0ZkTGf.d.ts → types.d-BzpPDBPV.d.ts} +2 -2
  104. package/dist/types-chunks/{types.d-DIpZJKUl.d.ts → types.d-CgrXrFrq.d.ts} +16 -2
  105. package/dist/types-chunks/{types.d-DVDTIfB_.d.ts → types.d-yuJzE82x.d.ts} +4 -4
  106. package/dist/types-chunks/{utils.d-CVp6bFl9.d.ts → utils.d-BpACJmzt.d.ts} +24 -6
  107. package/docs/SDK_EMBEDDER_GUIDE.md +1148 -598
  108. package/package.json +6 -3
  109. package/dist/chunks/agent-ASP4MS3X.js +0 -2
  110. package/dist/chunks/argument-completer-JYQ7FX3W.js +0 -2
  111. package/dist/chunks/chunk-35PPHOQ2.js +0 -292
  112. package/dist/chunks/chunk-43QNNDHR.js +0 -29
  113. package/dist/chunks/chunk-5GO6FH7L.js +0 -458
  114. package/dist/chunks/chunk-5NDCSFOP.js +0 -78
  115. package/dist/chunks/chunk-6XM4B6K2.js +0 -48
  116. package/dist/chunks/chunk-6YZUE6NC.js +0 -240
  117. package/dist/chunks/chunk-KQLQYHWU.js +0 -386
  118. package/dist/chunks/chunk-NXO6GWSY.js +0 -46
  119. package/dist/chunks/chunk-T2XZTLYE.js +0 -316
  120. package/dist/chunks/chunk-VAT2QYXM.js +0 -765
  121. package/dist/chunks/chunk-YVRYHC4C.js +0 -655
  122. package/dist/chunks/compaction-config-BQSSIWK5.js +0 -2
  123. package/dist/chunks/dist-PCFE24YP.js +0 -2
  124. package/dist/chunks/host-UTFXCYYM.js +0 -2
  125. package/dist/chunks/run-manager-PJU3WIFJ.js +0 -2
  126. package/dist/types-chunks/guardrail.d-BRE_ErEj.d.ts +0 -156
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kodax-ai/kodax",
3
- "version": "0.7.78",
3
+ "version": "0.7.80",
4
4
  "description": "KodaX lightweight coding agent - TypeScript implementation with 16 built-in LLM provider aliases, published as a Node-free single-file CLI and SDK",
5
5
  "type": "module",
6
6
  "private": false,
@@ -8,7 +8,8 @@
8
8
  "access": "public"
9
9
  },
10
10
  "kodaxRuntimeContracts": {
11
- "integrationConfigResilience": 1
11
+ "integrationConfigResilience": 1,
12
+ "managedRunDurability": 1
12
13
  },
13
14
  "workspaces": [
14
15
  "packages/*"
@@ -105,6 +106,9 @@
105
106
  "bench:perf": "tsx benchmark/perf/repl-render-perf.bench.ts",
106
107
  "bench:perf:e2e": "tsx benchmark/perf/repl-render-engine-e2e.bench.ts",
107
108
  "bench:repo-intel": "tsx benchmark/perf/repo-intelligence-index.bench.ts",
109
+ "bench:cli-first-ready": "tsx benchmark/perf/bare-cli-first-ready.bench.ts",
110
+ "bench:session-cold-open": "vite-node benchmark/perf/runtime-tiny-session-cold-open.bench.ts",
111
+ "bench:conversation-page-cold-open": "tsx benchmark/perf/runtime-conversation-page-cold-open.bench.ts",
108
112
  "clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
109
113
  "clean:packages": "npm run clean --workspaces"
110
114
  },
@@ -142,7 +146,6 @@
142
146
  "ink-text-input": "^6.0.0",
143
147
  "is-in-ci": "^2.0.0",
144
148
  "jimp": "^1.6.0",
145
- "js-tiktoken": "^1.0.12",
146
149
  "oauth4webapi": "3.8.6",
147
150
  "openai": "^6.32.0",
148
151
  "partial-json": "^0.1.7",
@@ -1,2 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Ja as g,La as h,Ya as i,a as c,cb as j,ra as d,sa as e,ta as f}from"./chunk-TQDBTTIM.js";import"./chunk-Z3KFRTSB.js";import"./chunk-KQLQYHWU.js";import"./chunk-YAZQTC2L.js";import"./chunk-5NDCSFOP.js";import{qb as a,rb as b}from"./chunk-VAT2QYXM.js";import"./chunk-6XM4B6K2.js";import"./chunk-2CFHBKRE.js";import"./chunk-NXO6GWSY.js";import"./chunk-ONUPGMER.js";export{e as bucketProviderPayloadSize,g as buildAutoRepoIntelligenceContext,f as checkPromiseSignal,b as cleanupIncompleteToolCalls,h as describeTransientProviderRetry,c as emitResilienceDebug,d as estimateProviderPayloadBytes,j as runKodaX,i as saveSessionSnapshot,a as validateAndFixToolHistory};
@@ -1,2 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Ua as a,Va as b}from"./chunk-YVRYHC4C.js";import"./chunk-6YZUE6NC.js";import"./chunk-7OEBJGHK.js";import"./chunk-5GO6FH7L.js";import"./chunk-TQDBTTIM.js";import"./chunk-UID7BLAB.js";import"./chunk-Z3KFRTSB.js";import"./chunk-6FOJVETH.js";import"./chunk-KQLQYHWU.js";import"./chunk-YAZQTC2L.js";import"./chunk-5NDCSFOP.js";import"./chunk-VAT2QYXM.js";import"./chunk-6XM4B6K2.js";import"./chunk-2CFHBKRE.js";import"./chunk-NXO6GWSY.js";import"./chunk-ONUPGMER.js";export{a as ArgumentCompleter,b as createArgumentCompleter};
@@ -1,292 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Ja as ge,Ka as be,Ma as K,Sa as se}from"./chunk-VAT2QYXM.js";import{d as B,g as V}from"./chunk-6XM4B6K2.js";import{a}from"./chunk-ONUPGMER.js";import{spawn as xe,spawnSync as Me}from"node:child_process";import{randomUUID as D}from"node:crypto";import{constants as qe,readdirSync as $e,statSync as Ee,writeSync as Br}from"node:fs";import{copyFile as Re,lstat as Ke,mkdir as O,readFile as ee,realpath as X,rm as I,stat as re,writeFile as F}from"node:fs/promises";import{createRequire as je}from"node:module";import te from"node:os";import n from"node:path";import Xe from"node:readline";import{fileURLToPath as ye,pathToFileURL as Fe}from"node:url";import{SandboxManager as ae,getWindowsSandboxUserStatus as Ue,installWindowsSandbox as Je,verifyWindowsWfpEgress as Ge}from"@anthropic-ai/sandbox-runtime";var j="0.0.65";function He(){let e=process.platform==="win32"?"windows-restricted-user":process.platform==="darwin"?"macos-seatbelt":process.platform==="linux"?"linux-bubblewrap":"unsupported";return{version:1,asrtVersion:j,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"}}a(He,"sandboxRuntimeCapability");var pe=1048576,fe=12e4,Ae=je(import.meta.url),Te=process.env.KODAX_BUNDLED==="true"?void 0:Fe(Ae.resolve("@anthropic-ai/sandbox-runtime")).href,ze=new Set([".ssh",".aws",".azure",".gnupg",".kodax",".agents"]),Ve=new Set([".env",".npmrc",".pypirc","credentials","id_rsa","id_ed25519"]),Ye=[".ssh",".aws",".azure",".gnupg",".kube",".docker",".kodax",".agents",n.join(".config","gcloud"),n.join(".config","gh"),".env",".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"],ve=JSON.stringify(be),ie=JSON.stringify(ge),Ze=String.raw`
3
- const { spawn } = require('node:child_process');
4
- const { writeSync } = require('node:fs');
5
- const input = JSON.parse(Buffer.from(process.argv[2], 'base64').toString('utf8'));
6
- const child = spawn(input.command, input.args, {
7
- cwd: input.cwd,
8
- env: process.env,
9
- shell: false,
10
- stdio: ['inherit', 'inherit', 'pipe'],
11
- windowsHide: true,
12
- });
13
- const stop = (signal) => child.kill(signal);
14
- process.once('SIGINT', () => stop('SIGINT'));
15
- process.once('SIGTERM', () => stop('SIGTERM'));
16
- child.once('spawn', () => {
17
- writeSync(2, input.targetStartedMarker);
18
- child.stderr.pipe(process.stderr);
19
- });
20
- child.once('error', (error) => {
21
- process.stderr.write((error instanceof Error ? error.message : String(error)) + '\n');
22
- process.exitCode = 1;
23
- });
24
- child.once('exit', (code, signal) => {
25
- process.exitCode = signal ? 1 : code ?? 1;
26
- });
27
- `,Qe="eval(Buffer.from(process.argv[1],'base64').toString('utf8'))",er=JSON.stringify(Qe),rr=Buffer.from(Ze,"utf8").toString("base64"),tr=JSON.stringify(rr),_e=String.raw`
28
- import { spawn } from 'node:child_process';
29
- import { randomUUID } from 'node:crypto';
30
- import { readFile, rm, writeFile } from 'node:fs/promises';
31
- let SandboxManager;
32
- const request = JSON.parse(await readFile(process.argv[2], 'utf8'));
33
- await rm(process.argv[2], { force: true });
34
- const targetStartedMarker = request.targetStartedMarker
35
- ?? '\u0000KODAX_ASRT_TARGET_STARTED:' + randomUUID() + '\u0000\n';
36
- const endpoints = new Set(request.endpoints.map((item) => item.host.toLowerCase() + ':' + item.port));
37
- const callback = request.allowAllNetwork === true
38
- ? async () => true
39
- : request.endpoints.length === 0
40
- ? undefined
41
- : async ({ host, port }) => endpoints.has(host.toLowerCase() + ':' + port);
42
- const withWindowsChildEnvironment = (argv, environment) => {
43
- const separator = argv.lastIndexOf('--');
44
- if (separator < 0) throw new Error('ASRT Windows wrapper omitted its child separator.');
45
- const controlled = new Set();
46
- for (let index = 0; index < separator - 1; index += 1) {
47
- if (argv[index] !== '--env') continue;
48
- const name = argv[index + 1].split('=', 1)[0];
49
- if (name) controlled.add(name.toLowerCase());
50
- }
51
- const injected = [];
52
- for (const [name, value] of Object.entries(environment ?? {})) {
53
- if (value === undefined) continue;
54
- if (!name || name.includes('=') || name.includes('\0') || value.includes('\0')) {
55
- throw new Error('Invalid environment entry for ASRT Windows child.');
56
- }
57
- const normalized = name.toLowerCase();
58
- if (controlled.has(normalized) && normalized !== 'path' && normalized !== 'pathext') continue;
59
- injected.push('--env', name + '=' + value);
60
- }
61
- const result = [...argv.slice(0, separator), ...injected, ...argv.slice(separator)];
62
- const estimate = result.reduce((size, value) => size + value.length + 3, 0);
63
- if (estimate > 30000) throw new Error('ASRT Windows child environment exceeds the CreateProcess command-line limit.');
64
- return result;
65
- };
66
- const writeObservation = async (observation) => {
67
- if (typeof request.observationFile !== 'string') return;
68
- await writeFile(request.observationFile, JSON.stringify(observation), { mode: 0o600 });
69
- };
70
- const waitForTarget = (target, observation) => {
71
- const marker = Buffer.from(targetStartedMarker, 'utf8');
72
- let pending = Buffer.alloc(0);
73
- let diagnostic = Buffer.alloc(0);
74
- let processError;
75
- let targetStarted = false;
76
- let observationWrite = Promise.resolve();
77
- return new Promise((resolve, reject) => {
78
- let settled = false;
79
- const finish = (result) => {
80
- if (settled) return;
81
- settled = true;
82
- void observationWrite.then(() => resolve(result), reject);
83
- };
84
- target.stderr.on('data', (chunk) => {
85
- if (targetStarted) {
86
- process.stderr.write(chunk);
87
- return;
88
- }
89
- pending = Buffer.concat([pending, Buffer.from(chunk)]);
90
- const markerOffset = pending.indexOf(marker);
91
- if (markerOffset >= 0) {
92
- targetStarted = true;
93
- const suffix = pending.subarray(markerOffset + marker.length);
94
- pending = Buffer.alloc(0);
95
- diagnostic = Buffer.alloc(0);
96
- observationWrite = writeObservation(observation).catch(() => undefined);
97
- if (suffix.length > 0) process.stderr.write(suffix);
98
- return;
99
- }
100
- const retained = Math.max(0, marker.length - 1);
101
- if (pending.length > retained) {
102
- diagnostic = Buffer.concat([
103
- diagnostic,
104
- pending.subarray(0, pending.length - retained),
105
- ]).subarray(-65536);
106
- pending = pending.subarray(pending.length - retained);
107
- }
108
- });
109
- target.once('error', (error) => {
110
- processError = error instanceof Error ? error.message : String(error);
111
- });
112
- target.once('close', (exitCode, signal) => {
113
- const preTarget = Buffer.concat([diagnostic, pending]).toString('utf8').trim();
114
- finish({
115
- exitCode: signal ? 1 : exitCode ?? 1,
116
- targetStarted,
117
- diagnostic: preTarget || processError || undefined,
118
- });
119
- });
120
- });
121
- };
122
- let child;
123
- let targetStarted = false;
124
- let normalFallbackAttempted = false;
125
- const runDirect = async () => {
126
- const internalElectronNode = request.command === process.execPath && process.versions.electron !== undefined;
127
- const directArgs = internalElectronNode
128
- ? ['--import', ${ve}, ...request.args]
129
- : request.args;
130
- const directEnv = internalElectronNode
131
- ? { ...request.env, [${ie}]: '1' }
132
- : request.env;
133
- child = spawn(request.command, directArgs, {
134
- cwd: request.cwd,
135
- env: directEnv,
136
- shell: false,
137
- stdio: 'inherit',
138
- windowsHide: true,
139
- });
140
- return await new Promise((resolve, reject) => {
141
- child.once('error', reject);
142
- child.once('exit', (exitCode, signal) => resolve(signal ? 1 : exitCode ?? 1));
143
- });
144
- };
145
- try {
146
- if (request.wrappedInvocation) {
147
- const wrapped = request.wrappedInvocation;
148
- child = spawn(wrapped.executable, wrapped.args, {
149
- cwd: request.cwd,
150
- env: wrapped.env,
151
- shell: wrapped.shell,
152
- stdio: ['inherit', 'inherit', 'pipe'],
153
- windowsHide: true,
154
- });
155
- const result = await waitForTarget(child, {
156
- version: 1,
157
- state: 'applied',
158
- backend: request.observationBackend ?? 'unsupported',
159
- policyId: 'kodax-workspace-shell-v1',
160
- });
161
- targetStarted = result.targetStarted;
162
- if (request.fallbackToNormalExecution === true && !targetStarted) {
163
- await writeObservation({
164
- version: 1,
165
- state: 'fallback',
166
- reason: 'backend_failed',
167
- execution: 'normal_permission_policy',
168
- }).catch(() => undefined);
169
- normalFallbackAttempted = true;
170
- process.exitCode = await runDirect();
171
- } else {
172
- if (!targetStarted && result.diagnostic) {
173
- process.stderr.write(result.diagnostic + '\n');
174
- }
175
- process.exitCode = result.exitCode;
176
- }
177
- } else {
178
- ({ SandboxManager } = await import(process.argv[1]));
179
- const bootstrap = request.bootstrapCommand ?? 'node';
180
- const bootstrapIsAbsolute = /^(?:[A-Za-z]:[\\/]|\\\\)/.test(bootstrap);
181
- const bootstrapIsElectronNode = bootstrap === process.execPath
182
- && process.versions.electron !== undefined;
183
- const config = process.platform === 'win32' && bootstrapIsAbsolute
184
- ? {
185
- ...request.config,
186
- filesystem: {
187
- ...request.config.filesystem,
188
- allowRead: [...new Set([...request.config.filesystem.allowRead, bootstrap])],
189
- },
190
- }
191
- : request.config;
192
- await SandboxManager.initialize(config, callback);
193
- const quote = (value) => process.platform === 'win32'
194
- ? '"' + value.replaceAll('"', '""') + '"'
195
- : "'" + value.replaceAll("'", "'\"'\"'") + "'";
196
- const internalElectronNode = request.command === process.execPath && process.versions.electron !== undefined;
197
- const childArgs = internalElectronNode
198
- ? ['--import', ${ve}, ...request.args]
199
- : request.args;
200
- const command = [
201
- quote(bootstrap),
202
- '-e',
203
- quote(${er}),
204
- ${tr},
205
- Buffer.from(JSON.stringify({
206
- command: request.command,
207
- args: childArgs,
208
- cwd: request.cwd,
209
- targetStartedMarker,
210
- }), 'utf8').toString('base64'),
211
- ].join(' ');
212
- if (process.platform === 'win32') {
213
- const wrapped = await SandboxManager.wrapWithSandboxArgv(command, 'cmd', undefined, undefined, request.cwd);
214
- const requestedEnv = internalElectronNode || bootstrapIsElectronNode
215
- ? { ...request.env, [${ie}]: '1' }
216
- : request.env;
217
- const childArgv = withWindowsChildEnvironment(wrapped.argv, requestedEnv);
218
- child = spawn(childArgv[0], childArgv.slice(1), {
219
- cwd: request.cwd,
220
- env: wrapped.env,
221
- shell: false,
222
- stdio: ['inherit', 'inherit', 'pipe'],
223
- windowsHide: true,
224
- });
225
- } else {
226
- const wrapped = await SandboxManager.wrapWithSandbox(command);
227
- const childEnv = internalElectronNode || bootstrapIsElectronNode
228
- ? { ...request.env, [${ie}]: '1' }
229
- : request.env;
230
- child = spawn(wrapped, {
231
- cwd: request.cwd,
232
- env: childEnv,
233
- shell: true,
234
- stdio: ['inherit', 'inherit', 'pipe'],
235
- });
236
- }
237
- const stop = () => child?.kill('SIGTERM');
238
- process.once('SIGINT', stop);
239
- process.once('SIGTERM', stop);
240
- const result = await waitForTarget(child, {
241
- version: 1,
242
- state: 'applied',
243
- backend: request.observationBackend ?? 'unsupported',
244
- policyId: 'kodax-workspace-shell-v1',
245
- });
246
- targetStarted = result.targetStarted;
247
- try { SandboxManager.cleanupAfterCommand(); } catch {}
248
- await SandboxManager.reset().catch(() => undefined);
249
- if (request.fallbackToNormalExecution === true && !targetStarted) {
250
- await writeObservation({
251
- version: 1,
252
- state: 'fallback',
253
- reason: 'backend_failed',
254
- execution: 'normal_permission_policy',
255
- }).catch(() => undefined);
256
- normalFallbackAttempted = true;
257
- process.exitCode = await runDirect();
258
- } else {
259
- if (!targetStarted && result.diagnostic) {
260
- process.stderr.write(result.diagnostic + '\n');
261
- }
262
- process.exitCode = result.exitCode;
263
- }
264
- }
265
- } catch (error) {
266
- await SandboxManager?.reset().catch(() => undefined);
267
- if (
268
- request.fallbackToNormalExecution === true
269
- && !targetStarted
270
- && !normalFallbackAttempted
271
- ) {
272
- try {
273
- await writeObservation({
274
- version: 1,
275
- state: 'fallback',
276
- reason: 'backend_failed',
277
- execution: 'normal_permission_policy',
278
- }).catch(() => undefined);
279
- normalFallbackAttempted = true;
280
- process.exitCode = await runDirect();
281
- } catch (fallbackError) {
282
- process.stderr.write((fallbackError instanceof Error ? fallbackError.message : String(fallbackError)) + '\n');
283
- process.exitCode = 1;
284
- }
285
- } else {
286
- process.stderr.write((error instanceof Error ? error.message : String(error)) + '\n');
287
- process.exitCode = 1;
288
- }
289
- }
290
- `,L,Y=0,or=3e4;function le(e){return e instanceof Error?e.message:String(e)}a(le,"errorText");function nr(e){let t=JSON.parse(e);if(typeof t!="object"||t===null)return;let r=t;if(r.version===1&&(r.state==="applied"&&r.policyId==="kodax-workspace-shell-v1"&&(r.backend==="windows-restricted-user"||r.backend==="macos-seatbelt"||r.backend==="linux-bubblewrap"||r.backend==="unsupported")||r.state==="fallback"&&r.reason==="backend_failed"&&r.execution==="normal_permission_policy"))return r}a(nr,"parseBrokerObservation");function oe(){return process.env.KODAX_A2A_NODE??(process.env.KODAX_BUNDLED==="true"?"node":process.execPath)}a(oe,"sandboxJavaScriptCommand");async function W(e={}){if(e.refresh||L===void 0||Date.now()>=Y){let t=sr();L=t,Y=Number.POSITIVE_INFINITY,t.then(r=>{L===t&&(Y=r.ready?Number.POSITIVE_INFINITY:Date.now()+or)},()=>{L===t&&(L=void 0,Y=0)})}return L}a(W,"doctorSandboxRuntime");async function sr(){let e=[];ae.isSupportedPlatform()||e.push(`Unsupported platform: ${process.platform}.`);let t=ae.checkDependencies();e.push(...t.warnings,...t.errors);let r=t.errors.length>0;if(process.env.KODAX_BUNDLED!=="true")try{let d=JSON.parse(await ee(Ae.resolve("@anthropic-ai/sandbox-runtime/package.json"),"utf8"));d.version!==j&&(r=!0,e.push(`ASRT package version mismatch: expected ${j}, found ${String(d.version)}.`))}catch(d){r=!0,e.push(`ASRT package provenance check failed: ${le(d)}`)}let o=oe(),s=K({args:["--version"],env:$(),isElectron:o===process.execPath&&process.versions.electron!==void 0}),c=Me(o,s.args,{env:s.env,shell:!1,encoding:"utf8",windowsHide:!0,timeout:5e3});if(c.status!==0){r=!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=Ue();!d.provisioned||!d.credPresent||!d.inSandboxGroup?(r=!0,e.push("Windows sandbox account is not fully provisioned.")):await Ge()}catch(d){r=!0,e.push(le(d))}return{ready:ae.isSupportedPlatform()&&!r,platform:process.platform,version:j,diagnostics:e,setupRequired:r}}a(sr,"inspectSandboxRuntime");async function ar(){if(process.platform!=="win32")return W({refresh:!0});if(Je().cancelled)throw new Error("Sandbox setup was cancelled.");return W({refresh:!0})}a(ar,"setupSandboxRuntime");function Z(e){return e.ready?[`KodaX sandbox is active (${e.platform}, ASRT ${e.version}).`]:e.platform==="win32"?['Run "kodax sandbox setup". Windows will show a UAC prompt for the one-time sandbox account and network policy setup.',"The terminal itself does not need to be started as Administrator; approve the UAC prompt when it appears."]:e.platform==="darwin"?['KodaX uses macOS Seatbelt through sandbox-exec. Install the missing dependency, then rerun "kodax sandbox doctor".',"Homebrew: brew install ripgrep"]:e.platform==="linux"?['KodaX uses bubblewrap on Linux. Install bubblewrap, socat, and ripgrep, then rerun "kodax sandbox doctor".',"Debian/Ubuntu: sudo apt install bubblewrap socat ripgrep","Fedora/RHEL: sudo dnf install bubblewrap socat ripgrep","Arch Linux: sudo pacman -S bubblewrap socat ripgrep"]:[`KodaX sandbox is not supported on ${e.platform}.`]}a(Z,"sandboxSetupGuidance");async function jr(e={}){let t=await W({refresh:!0});if(t.ready)return{status:"ready",attempted:!1,doctor:t,guidance:Z(t)};if(t.platform!=="win32"||e.allowElevation===!1)return{status:"unavailable",attempted:!1,doctor:t,guidance:Z(t)};try{let r=await ar();return{status:r.ready?"ready":"unavailable",attempted:!0,doctor:r,guidance:Z(r)}}catch(r){let o=await W({refresh:!0}),s=le(r);return{status:/cancelled/i.test(s)?"cancelled":"unavailable",attempted:!0,doctor:o,guidance:Z(o),error:s}}}a(jr,"prepareSandboxRuntimeForSetup");function N(e,t){let r=e.replaceAll("\\","/").replace(/^\.\//,"");if(!r||n.posix.isAbsolute(r)||r.split("/").includes(".."))throw new Error(`${t} must be a safe relative path.`);return r}a(N,"canonicalRelative");function q(e,t){let r=n.relative(e,t);return r===""||!r.startsWith("..")&&!n.isAbsolute(r)}a(q,"isInside");function Pe(e){let t=e.split(n.sep).map(r=>r.toLowerCase());return t.some(r=>ze.has(r))||t.some(r=>Ve.has(r)||r.startsWith(".env."))}a(Pe,"isSensitiveRelative");async function ir(e,t){await O(t,{recursive:!0,mode:448});let r=[...(e.scripts??[]).map(o=>({folder:"scripts",file:o})),...(e.references??[]).map(o=>({folder:"references",file:o})),...(e.assets??[]).map(o=>({folder:"assets",file:o})),...(e.templates??[]).map(o=>({folder:"templates",file:o})),...(e.resources??[]).map(o=>({folder:"resources",file:o}))];await F(n.join(t,"SKILL.md"),await ee(e.skillFilePath),{mode:384});for(let{folder:o,file:s}of r){let c=N(s.relativePath,`Skill ${e.name} support file`),d=n.join(t,o,...c.split("/"));await O(n.dirname(d),{recursive:!0,mode:448}),await F(d,await ee(s.path),{mode:384})}}a(ir,"copySkillSnapshot");async function cr(e,t){let r=new Map;for(let[o,s]of Object.entries(e.admissions)){let c=await e.registry.loadFull(o),d=new Map((c.scripts??[]).map(l=>[`scripts/${N(l.relativePath,`Skill ${o} script`)}`,l])),i=n.join(t,o.replace(/[^A-Za-z0-9._-]/g,"_"));await ir(c,i);for(let l of s){let u=N(l,`toolPolicy.skillScripts.${o}`);if(!d.has(u))throw new Error(`Skill "${o}" has no script "${u}".`);r.set(`${o}\0${u}`,{skill:o,relativePath:u,snapshotPath:n.join(i,...u.split("/"))})}}return r}a(cr,"snapshotAdmissions");function dr(e){return e.mode==="deny"?[]:e.origins.map(t=>{let r=new URL(t);return{host:r.hostname.toLowerCase(),port:r.port?Number(r.port):r.protocol==="https:"?443:80}})}a(dr,"networkEndpoints");function $(){let e=["PATH","Path","PATHEXT","SystemRoot","COMSPEC","TEMP","TMP","HOME","USERPROFILE","LOCALAPPDATA","LANG"],t={NO_COLOR:"1"};for(let r of e)process.env[r]!==void 0&&(t[r]=process.env[r]);for(let[r,o]of Object.entries(process.env))r.startsWith("LC_")&&o!==void 0&&(t[r]=o);return t}a($,"sanitizedEnvironment");function lr(e){let t=n.extname(e).toLowerCase();if([".js",".mjs",".cjs"].includes(t))return{command:process.env.KODAX_A2A_NODE??(process.env.KODAX_BUNDLED==="true"?"node":process.execPath),args:[e]};if(t===".py")return{command:process.env.KODAX_A2A_PYTHON??(process.platform==="win32"?"python.exe":"python3"),args:[e]};if(t===".ps1")return{command:process.env.KODAX_A2A_POWERSHELL??(process.platform==="win32"?n.join(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe"):"pwsh"),args:["-NoProfile","-NonInteractive","-File",e]};if(t===".sh"&&process.platform!=="win32")return{command:"/bin/sh",args:[e]};if([".cmd",".bat"].includes(t)&&process.platform==="win32")return{command:process.env.COMSPEC??n.join(process.env.SystemRoot??"C:\\Windows","System32","cmd.exe"),args:["/d","/s","/c",e]};throw new Error(`Unsupported admitted Skill script type: ${t||"<none>"}.`)}a(lr,"interpreterFor");var he=250,ur=1500;async function pr(e,t,r=fe,o=pe){let s=[],c=[],d=0,i,l=a(()=>{},"rejectStopped"),u,w=new Promise((m,f)=>{l=f}),b=a(m=>{if(i!==void 0)return;i=m;let f=!1,v=a(()=>{f||(f=!0,u!==void 0&&clearTimeout(u),l(m))},"finish");u=setTimeout(()=>{try{e.kill("SIGKILL")}finally{v()}},ur),se(e,{forceMs:he,taskkillMs:he}).then(v,v)},"requestStop"),h=a((m,f)=>{d+=f.byteLength,d>o?b(new Error(`Sandboxed command output exceeded ${o} bytes.`)):m.push(f)},"append");e.stdout?.on("data",m=>{h(s,m)}),e.stderr?.on("data",m=>{h(c,m)});let y=setTimeout(()=>{b(new Error(`Sandboxed command exceeded its ${r} ms timeout.`))},r),S=a(()=>{let m=t?.reason;b(m instanceof Error?m:new Error("Sandboxed command was cancelled."))},"abort");t?.addEventListener("abort",S,{once:!0}),t?.aborted&&S();try{let m=new Promise((v,_)=>{e.once("error",_),e.once("close",U=>v(U??1))}),f=await Promise.race([m,w]);if(i!==void 0)throw i;return{exitCode:f,stdout:Buffer.concat(s).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}}finally{clearTimeout(y),u!==void 0&&clearTimeout(u),t?.removeEventListener("abort",S)}}a(pr,"collectProcess");async function Ce(e,t,r=fe,o=pe){let s=n.join(te.tmpdir(),`kodax-asrt-${process.pid}-${D()}.json`),c={...e,bootstrapCommand:e.bootstrapCommand??oe(),config:{...e.config,filesystem:{...e.config.filesystem,denyRead:[...e.config.filesystem.denyRead,s]}}};await F(s,JSON.stringify(c),{mode:384});try{let d=process.env.KODAX_BUNDLED==="true"?["__asrt-broker",s]:["--input-type=module","-e",_e,Te,s],i=K({args:d,env:$(),isElectron:process.versions.electron!==void 0}),l=xe(process.execPath,i.args,{env:i.env,shell:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"});return await pr(l,t,r,o)}finally{await I(s,{force:!0})}}a(Ce,"runBrokerResult");async function fr(e,t){let r=await Ce(e,t);if(r.exitCode!==0){let o=r.stderr.trim()||r.stdout.trim();throw new Error(`Sandboxed Skill script failed (${r.exitCode}): ${o}`)}return r.stdout}a(fr,"runBroker");async function mr(e,t){let r=await X(e),o=n.resolve(e,N(t,"Skill script input")),s=await X(o);if(!q(r,s)||Pe(n.relative(r,s)))throw new Error("Skill script input is outside the permitted workspace surface.");if(!(await re(s)).isFile())throw new Error("Skill script inputs must be files.");return s}a(mr,"workspaceSource");async function wr(e,t){let r=await X(e),o=n.resolve(e,N(t,"Skill script output target"));if(!q(n.resolve(e),o)||Pe(n.relative(n.resolve(e),o)))throw new Error("Skill script output target is outside the permitted workspace surface.");if(await O(n.dirname(o),{recursive:!0}),!q(r,await X(n.dirname(o))))throw new Error("Skill script output target escapes through a symlink.");try{throw await re(o),new Error("Skill script output target already exists.")}catch(s){if(s.code!=="ENOENT")throw s}return o}a(wr,"workspaceTarget");async function Sr(e,t,r,o){if(r.inputs.length>0&&o==="none")throw new Error("Skill script inputs require workspace read access.");for(let s of r.inputs){let c=await mr(e,s.path),d=N(s.as??n.basename(c),"Skill script staged input"),i=n.resolve(t,"inputs",...d.split("/"));if(!q(n.join(t,"inputs"),i))throw new Error("Skill script staged input escapes staging.");await O(n.dirname(i),{recursive:!0,mode:448}),await Re(c,i)}}a(Sr,"stageInputFiles");async function gr(e,t,r,o,s){if(r.outputs.length>0&&o!=="write")throw new Error("Skill script outputs require workspace write access.");let c=[];for(let d of r.outputs){let i=N(d.path,"Skill script staged output"),l=n.resolve(t,"outputs",...i.split("/")),u=await X(l);if(!q(n.join(t,"outputs"),u)||(await Ke(l)).isSymbolicLink()||!(await re(l)).isFile())throw new Error(`Skill script did not produce output "${i}".`);let w=await wr(e,d.target);if(s!==void 0&&Oe(e,!0)+(await re(l)).size>s)throw new Error("Skill script outputs would exceed the remote workspace byte quota.");await Re(l,w,qe.COPYFILE_EXCL),c.push(n.relative(e,w))}return c}a(gr,"promoteOutputs");function Oe(e,t=!1){let r=0;for(let o of $e(e,{withFileTypes:!0})){if(t&&o.name===".kodax-a2a-script"||o.isSymbolicLink())continue;let s=n.join(e,o.name);o.isDirectory()?r+=Oe(s):o.isFile()&&(r+=Ee(s).size)}return r}a(Oe,"directorySize");function br(e,t,r,o){let s=te.homedir(),c=n.isAbsolute(o)?[o]:[];return{network:{allowedDomains:[],deniedDomains:[],strictAllowlist:r.length===0,allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{denyRead:[s],allowRead:[e,t,process.execPath,...c],allowWrite:[e],denyWrite:[s]}}}a(br,"sandboxConfig");function yr(){let e=[te.tmpdir(),process.env.TEMP,process.env.TMP,process.env.TMPDIR,...process.platform==="win32"?[]:["/tmp","/var/tmp"]];return[...new Set(e.filter(t=>typeof t=="string"&&n.isAbsolute(t)).map(t=>n.resolve(t)))]}a(yr,"canonicalTempDirectories");function vr(e){return[n.join(e,".git","config"),n.join(e,".git","hooks")].filter(r=>{try{return Ee(r),!0}catch{return!1}})}a(vr,"existingWorkspaceDenyWrites");function hr(e,t,r){return[...new Set([n.resolve(r),n.resolve(t),...Ye.map(o=>n.resolve(e,o))])]}a(hr,"workspaceShellSensitiveReadDenies");function Ne(e){let t=n.resolve(V()),r=n.join(t,"sandbox-runtime"),o=n.resolve(te.homedir()),s=hr(o,t,r),c=(process.env.PATH??process.env.Path??"").split(n.delimiter).map(i=>i.replace(/^"|"$/g,"")).filter(i=>n.isAbsolute(i)).map(i=>n.resolve(i)).filter(i=>{let l=n.relative(o,i);return l!==""&&!l.startsWith("..")&&!n.isAbsolute(l)&&!s.some(u=>q(u,i))}),d=oe();return{network:{allowedDomains:[],deniedDomains:[],strictAllowlist:!1,allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{denyRead:s,allowRead:[...new Set([...c,...n.isAbsolute(d)?[d]:[]])],allowWrite:[e,...yr()],denyWrite:[r,...vr(e)]}}}a(Ne,"workspaceShellSandboxConfig");function kr(e){let t=Ne(e);return process.platform!=="win32"?t:{...t,filesystem:{...t.filesystem,denyRead:[n.resolve(V(),"sandbox-runtime")]}}}a(kr,"workspaceShellSessionSandboxConfig");function Q(e,t){return[...new Set((e??[]).map(r=>n.resolve(t,r)))]}a(Q,"normalizedSandboxPaths");function xr(e){return e.mode!=="allowlist"?[]:e.origins.map(t=>{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.username||r.password||r.pathname!=="/"||r.search||r.hash)throw new Error(`Sandbox network origin must be an HTTP(S) origin: ${t}`);return{host:r.hostname.toLowerCase(),port:r.port?Number(r.port):r.protocol==="https:"?443:80}})}a(xr,"sdkSandboxEndpoints");async function Xr(e){if(!e.command.trim())throw new Error("Sandbox command must not be empty.");if(e.timeoutMs!==void 0&&(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0))throw new Error("Sandbox timeoutMs must be a positive finite number.");if(e.maxOutputBytes!==void 0&&(!Number.isSafeInteger(e.maxOutputBytes)||e.maxOutputBytes<=0))throw new Error("Sandbox maxOutputBytes must be a positive safe integer.");let t=n.resolve(e.cwd),r=e.network??{mode:"deny"},o=xr(r),s=await W();if(!s.ready)return{status:"unavailable",sandboxed:!1,doctor:s};let c={...e.inheritEnvironment===!0?process.env:$(),...e.env},d={config:{network:{allowedDomains:[],deniedDomains:[],strictAllowlist:r.mode==="deny",allowUnixSockets:[],allowAllUnixSockets:!1,allowLocalBinding:!1},filesystem:{allowRead:Q(e.filesystem.allowRead,t),allowWrite:Q(e.filesystem.allowWrite,t),denyRead:Q(e.filesystem.denyRead,t),denyWrite:Q(e.filesystem.denyWrite,t)}},command:e.command,args:e.args??[],cwd:t,env:c,endpoints:o,allowAllNetwork:r.mode==="allow"},i=await Ce(d,e.signal,e.timeoutMs??fe,e.maxOutputBytes??pe);return{status:"completed",sandboxed:!0,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}a(Xr,"runKodaXSandboxed");var Er=5*6e4,Rr=18e4,Ar=3e4,ce=1500,Tr=13e4,M=new Map;function Be(){let e=new Error("ASRT workspace session preparation timed out.");return e.name="TimeoutError",e}a(Be,"workspacePreparationTimeoutError");function ue(e,t){if(e?.aborted)throw new DOMException("Operation aborted","AbortError");if(t!==void 0&&Date.now()>=t)throw Be()}a(ue,"throwIfWorkspacePreparationStopped");function De(e,t,r){return ue(t,r),t===void 0&&r===void 0?e:new Promise((o,s)=>{let c=!1,d,i=a(u=>{c||(c=!0,d&&clearTimeout(d),t?.removeEventListener("abort",l),u())},"finish"),l=a(()=>{i(()=>s(new DOMException("Operation aborted","AbortError")))},"onAbort");t?.addEventListener("abort",l,{once:!0}),r!==void 0&&(d=setTimeout(()=>{i(()=>s(Be()))},Math.max(0,r-Date.now())),d.unref()),e.then(u=>i(()=>o(u)),u=>i(()=>s(u)))})}a(De,"waitForWorkspacePreparation");async function Ie(){let e=n.join(V(),"sandbox-runtime");return await O(e,{recursive:!0,mode:448}),e}a(Ie,"sandboxControlDirectory");function _r(e){if(process.env.KODAX_BUNDLED==="true")return["__asrt-workspace-session",e];if(import.meta.url.endsWith(".ts"))return["--import","tsx",ye(new URL("./sandbox-workspace-session-entry.ts",import.meta.url)),e];let t=n.dirname(ye(import.meta.url)),r=n.basename(t)==="chunks"?n.dirname(t):t;return[n.join(r,"sandbox-workspace-session.js"),e]}a(_r,"workspaceSessionEntryArgs");function de(e,t){let r=t?"ref":"unref";e[r]();for(let o of e.stdio){if(!o)continue;o[r]?.()}}a(de,"setWorkspaceSessionReferenced");async function Pr(e,t){let r=await Ie(),o=n.join(r,`workspace-${process.pid}-${D()}.json`);await F(o,JSON.stringify({config:kr(e)}),{mode:384});let s=K({args:_r(o),env:$(),isElectron:process.versions.electron!==void 0}),c=xe(process.execPath,s.args,{env:s.env,shell:!1,stdio:["pipe","pipe","pipe","pipe"],windowsHide:!0}),d=c.stdio[3];if(!d)throw new Error("ASRT workspace session control pipe was not created.");let i=Xe.createInterface({input:d}),l=new Map,u="",w=!1,b=!1,h=!1,y=0,S=0,m,f,v,_=new Promise(p=>{c.once("exit",()=>p())}),U,ne,We=new Promise((p,g)=>{U=p,ne=g}),me=a(()=>{h||(h=!0,t())},"evict"),J,P=a(()=>J||(J=(async()=>{try{await se(c,{gracefulStdinEnd:!0,gracefulMs:process.platform==="win32"?Tr:ce,forceMs:ce,taskkillMs:ce})}finally{i.close(),d.destroy(),c.stdin.destroy()}})().finally(me),J),"terminate"),C=a(p=>{if(!w){w=!0,ne(p);for(let g of l.values())g.reject(p);l.clear()}},"fail");c.stderr.on("data",p=>{u=(u+p.toString("utf8")).slice(-16384)}),c.stdout.on("data",p=>{u=(u+p.toString("utf8")).slice(-16384)}),i.on("line",p=>{let g;try{g=JSON.parse(p)}catch{C(new Error("ASRT workspace session returned malformed control data.")),P();return}if(g.type==="ready"){g.ok?U():ne(new Error(g.error??"ASRT workspace session failed."));return}if(g.type!=="result"||!g.id){C(new Error("ASRT workspace session returned an invalid control response.")),P();return}let x=l.get(g.id);x&&(l.delete(g.id),x.resolve(g))}),c.once("error",p=>{C(p),P()}),i.once("close",()=>{b||w||(C(new Error("ASRT workspace session control pipe closed unexpectedly.")),P())}),c.once("exit",p=>{f&&clearTimeout(f),C(new Error(`ASRT workspace session exited ${p??1}: ${u.trim()||"no diagnostics"}`)),me()});let Le=setTimeout(()=>{C(new Error("ASRT workspace session initialization timed out.")),P()},Rr);try{await We.finally(()=>clearTimeout(Le))}catch(p){throw await P(),await I(o,{force:!0}),p}let G=a(async(p,g)=>{if(w||b&&p==="wrap")throw new Error("ASRT workspace session is unavailable.");let x=`workspace_${++y}`,H=new Promise((k,R)=>{l.set(x,{resolve:k,reject:R})}),E=setTimeout(()=>{C(new Error(`ASRT workspace session ${p} request timed out.`)),P()},Ar);E.unref();try{await new Promise((k,R)=>{c.stdin.write(`${JSON.stringify({id:x,type:p,request:g})}
291
- `,A=>A?R(A):k())})}catch(k){throw l.delete(x),clearTimeout(E),C(k instanceof Error?k:new Error(String(k))),P(),k}return H.finally(()=>clearTimeout(E))},"request"),we=a(()=>{f&&clearTimeout(f),!(S>0||b||w)&&(f=setTimeout(()=>{Se.close()},Er),f.unref(),de(c,!1))},"scheduleIdleClose"),Se={async acquire(p,g,x){if(ue(g,x),w||b)throw new Error("ASRT workspace session is unavailable.");f&&clearTimeout(f),de(c,!0),S+=1;let H=!1,E=a(()=>{H||(H=!0,S-=1,S===0&&(m?.(),m=void 0),we())},"finalize"),k=G("wrap",p),R;try{R=await De(k,g,x)}catch(A){throw k.then(async T=>{if(!T.ok||!T.invocation)return;let z=await G("cleanup");if(!z.ok)throw new Error(z.error??"ASRT command cleanup failed.")}).catch(T=>{B({source:"sandbox:workspace-session",level:"warn",message:"Late workspace sandbox preparation cleanup failed.",detail:T})}).finally(E),A}try{if(!R.ok||!R.invocation)throw E(),new Error(R.error??"ASRT workspace wrapping failed.");try{ue(g,x)}catch(T){try{await G("cleanup")}catch(z){B({source:"sandbox:workspace-session",level:"warn",message:"Cancelled workspace sandbox preparation cleanup failed.",detail:z})}throw E(),T}let A=!1;return{invocation:R.invocation,async release(){if(!A){A=!0;try{let T=await G("cleanup");if(!T.ok)throw new Error(T.error??"ASRT command cleanup failed.")}finally{E()}}}}}catch(A){throw E(),A}},async close(){return v||(b=!0,v=(async()=>{f&&clearTimeout(f),!w&&(de(c,!0),S>0&&await new Promise(p=>{m=p}),!w&&(c.stdin.end(),await _))})(),v)}};return we(),Se}a(Pr,"startWorkspaceSessionClient");async function ke(e){if(!(await W()).ready)return;let r=process.platform==="win32"?e.toLowerCase():e,o=M.get(r);return o||(o=Pr(e,()=>{M.get(r)===o&&M.delete(r)}),M.set(r,o),o.catch(()=>{M.get(r)===o&&M.delete(r)})),o}a(ke,"getWorkspaceSession");function Fr(e){let t=n.resolve(e.workspaceRoot);return ke(t).catch(r=>{B({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox warm-up failed; commands will use normal permission fallback.",detail:r})}),{async prepare(r){if(!r.toolCallId){r.reportObservation?.({version:1,state:"not_selected"});return}let o={id:r.toolCallId,name:"bash",input:{...r.toolInput}};if(!e.shouldSandbox(o)){r.reportObservation?.({version:1,state:"not_selected"});return}let s;try{let c=await De(ke(t),r.signal,r.deadlineAt);if(!c){r.reportObservation?.({version:1,state:"fallback",reason:"not_ready",execution:"normal_permission_policy"});return}let d=r.executable??(process.platform==="win32"?process.env.COMSPEC??n.join(process.env.SystemRoot??"C:\\Windows","System32","cmd.exe"):"/bin/sh"),i=r.args??(process.platform==="win32"?["/d","/s","/c",r.command]:["-c",r.command]),l=await Ie(),u=n.join(l,`kodax-asrt-shell-${process.pid}-${D()}.json`),w=n.join(l,`kodax-asrt-observation-${process.pid}-${D()}.json`),b={...r.env},h={config:Ne(t),command:d,args:i,cwd:r.cwd,env:b,endpoints:[],allowAllNetwork:!0,bootstrapCommand:oe(),fallbackToNormalExecution:!0,observationBackend:He().backend,observationFile:w,targetStartedMarker:`\0KODAX_ASRT_TARGET_STARTED:${D()}\0
292
- `},y=await c.acquire(h,r.signal,r.deadlineAt);s=y;let S={...h,wrappedInvocation:y.invocation},m=process.env.KODAX_BUNDLED==="true"?["__asrt-broker",u]:["--input-type=module","-e",_e,Te,u],f=K({args:m,env:$(),isElectron:process.versions.electron!==void 0});return await F(u,JSON.stringify(S),{mode:384}),{executable:process.execPath,args:f.args,env:f.env,async cleanup(){let v;try{v=await ee(w,"utf8").then(nr).catch(_=>{if(_.code!=="ENOENT")throw _})}finally{await Promise.all([I(u,{force:!0}),I(w,{force:!0})]);try{await y.release()}catch(_){B({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox command cleanup failed.",detail:_})}}return v}}}catch(c){if(s&&await s.release().catch(d=>{B({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox lease release failed.",detail:d})}),r.signal?.aborted||r.deadlineAt!==void 0&&Date.now()>=r.deadlineAt)throw c;B({source:"sandbox:workspace-session",level:"warn",message:"Workspace sandbox preparation failed; using normal permission fallback.",detail:c}),r.reportObservation?.({version:1,state:"fallback",reason:"prepare_failed",execution:"normal_permission_policy"});return}}}}a(Fr,"createAsrtShellSandbox");async function Ur(e){let t=await W();if(!t.ready)throw new Error(`ASRT ${j} is not ready: ${t.diagnostics.join(" ")||"run kodax sandbox setup"}`);let r=n.join(e.snapshotRoot,D()),o=n.join(r,"skills");await O(o,{recursive:!0,mode:448});try{let s=await cr(e,o),c=dr(e.network),d=Promise.resolve();return{async run(i,l){let u=d,w;if(d=new Promise(b=>{w=b}),await u,l.signal?.aborted)throw w?.(),l.signal.reason??new Error("Sandboxed Skill script was cancelled.");try{if(i.args.length>64||i.args.some(S=>S.length>8192))throw new Error("Skill script arguments exceed the bounded remote contract.");if(i.inputs.length>32||i.outputs.length>32)throw new Error("Skill script file mappings exceed the bounded remote contract.");let b=N(i.script,"Skill script"),h=s.get(`${i.skill}\0${b}`);if(!h)throw new Error("Skill script is not admitted by this Runtime binding.");if([".cmd",".bat"].includes(n.extname(h.snapshotPath).toLowerCase())&&i.args.some(S=>/[&|<>^]/.test(S)))throw new Error("Batch Skill script arguments cannot contain command operators.");let y=n.join(l.workspaceRoot,".kodax-a2a-script",D());try{await O(n.join(y,"inputs"),{recursive:!0,mode:448}),await O(n.join(y,"outputs"),{recursive:!0,mode:448}),await Sr(l.workspaceRoot,y,i,e.workspaceAccess);let S=lr(h.snapshotPath),m=await fr({config:br(y,r,c,S.command),command:S.command,args:[...S.args,...i.args],cwd:y,env:$(),endpoints:c},l.signal),f=await gr(l.workspaceRoot,y,i,e.workspaceAccess,e.workspaceByteLimit);return JSON.stringify({stdout:m.trim(),outputs:f})}finally{await I(y,{recursive:!0,force:!0})}}finally{w?.()}},async dispose(){await d,await I(r,{recursive:!0,force:!0})}}}catch(s){throw await I(r,{recursive:!0,force:!0}),s}}a(Ur,"createAsrtSkillScriptRunner");export{j as a,He as b,W as c,ar as d,Z as e,jr as f,Xr as g,Fr as h,Ur as i};