@kodax-ai/kodax 0.7.97-alpha.9 → 0.7.97-beta.2

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 (234) hide show
  1. package/CHANGELOG.md +393 -0
  2. package/README.md +170 -29
  3. package/README_CN.md +116 -17
  4. package/config-templates/config.example.jsonc +2 -3
  5. package/dist/artifacts/skills/artifact-review/SKILL.md +44 -7
  6. package/dist/builtin/code-review/SKILL.md +5 -17
  7. package/dist/builtin/git-workflow/SKILL.md +9 -8
  8. package/dist/builtin/skill-creator/SKILL.md +38 -108
  9. package/dist/builtin/skill-creator/references/evaluation.md +50 -0
  10. package/dist/builtin/skill-creator/scripts/analyze-benchmark.d.ts +2 -0
  11. package/dist/builtin/skill-creator/scripts/analyze-benchmark.js +6 -3
  12. package/dist/builtin/skill-creator/scripts/compare-runs.d.ts +2 -0
  13. package/dist/builtin/skill-creator/scripts/compare-runs.js +6 -3
  14. package/dist/builtin/skill-creator/scripts/grade-evals.d.ts +2 -0
  15. package/dist/builtin/skill-creator/scripts/grade-evals.js +6 -3
  16. package/dist/builtin/skill-creator/scripts/run-eval.js +3 -3
  17. package/dist/builtin/skill-creator/scripts/run-loop.js +2 -1
  18. package/dist/builtin/skill-creator/scripts/run-trigger-eval.d.ts +2 -0
  19. package/dist/builtin/skill-creator/scripts/run-trigger-eval.js +3 -1
  20. package/dist/builtin/skill-creator/scripts/utils.d.ts +1 -1
  21. package/dist/builtin/skill-creator/scripts/utils.js +8 -0
  22. package/dist/builtin/tdd/SKILL.md +24 -40
  23. package/dist/builtin/visual-review/SKILL.md +7 -3
  24. package/dist/chunks/agent-DS7M57WD.js +2 -0
  25. package/dist/chunks/agent-adapter-TLWGGK3V.js +2 -0
  26. package/dist/chunks/argument-completer-OGCXKTRQ.js +2 -0
  27. package/dist/chunks/bedrock-native-Z5VNWF5U.js +4 -0
  28. package/dist/chunks/cell-LV7MNPNQ.js +2 -0
  29. package/dist/chunks/chunk-2HH5AS7E.js +1157 -0
  30. package/dist/chunks/chunk-3CP7AUWY.js +2 -0
  31. package/dist/chunks/chunk-45ZP2YHG.js +2 -0
  32. package/dist/chunks/chunk-4Y6U7AH4.js +9 -0
  33. package/dist/chunks/chunk-52EN2777.js +2 -0
  34. package/dist/chunks/{chunk-HXCY52Z2.js → chunk-53CJDQS2.js} +1 -1
  35. package/dist/chunks/{chunk-JNB2FL6P.js → chunk-5MUVRFMU.js} +1 -1
  36. package/dist/chunks/chunk-65652LR4.js +2 -0
  37. package/dist/chunks/chunk-6TITQQAI.js +351 -0
  38. package/dist/chunks/chunk-AGUM5SWX.js +2 -0
  39. package/dist/chunks/chunk-BBZWF2EA.js +2 -0
  40. package/dist/chunks/chunk-C6JGLEYD.js +2 -0
  41. package/dist/chunks/chunk-D36OIMV7.js +142 -0
  42. package/dist/chunks/chunk-D425EZGC.js +2 -0
  43. package/dist/chunks/chunk-D5OW7UD5.js +2 -0
  44. package/dist/chunks/chunk-DCE7XQUG.js +2 -0
  45. package/dist/chunks/chunk-DV5YPYLW.js +10 -0
  46. package/dist/chunks/chunk-EISRVOBJ.js +4 -0
  47. package/dist/chunks/chunk-EPK6EWRI.js +12 -0
  48. package/dist/chunks/chunk-F6GJXQNA.js +29 -0
  49. package/dist/chunks/chunk-GJXOTOZB.js +465 -0
  50. package/dist/chunks/chunk-GZUWQZJD.js +2 -0
  51. package/dist/chunks/chunk-I325ER7D.js +2 -0
  52. package/dist/chunks/chunk-ISLK6R2P.js +2 -0
  53. package/dist/chunks/chunk-J2L2NK6E.js +366 -0
  54. package/dist/chunks/chunk-JAF2YLZO.js +14 -0
  55. package/dist/chunks/chunk-KDLOPBFZ.js +2 -0
  56. package/dist/chunks/chunk-KDSO7V4O.js +5 -0
  57. package/dist/chunks/chunk-KE2NBMAP.js +20 -0
  58. package/dist/chunks/chunk-MCDZNQWD.js +634 -0
  59. package/dist/chunks/chunk-NSR4RW2F.js +3 -0
  60. package/dist/chunks/chunk-OGTRDK4Q.js +359 -0
  61. package/dist/chunks/chunk-P55RJIOG.js +18 -0
  62. package/dist/chunks/chunk-P7OJRV5Z.js +2 -0
  63. package/dist/chunks/chunk-QP47JIWP.js +3 -0
  64. package/dist/chunks/chunk-QSZCR5GC.js +190 -0
  65. package/dist/chunks/chunk-R2HTPDI7.js +2 -0
  66. package/dist/chunks/chunk-R42S4BLA.js +2 -0
  67. package/dist/chunks/chunk-RYBUYHDL.js +5 -0
  68. package/dist/chunks/chunk-SDPZFH6M.js +4 -0
  69. package/dist/chunks/chunk-SK3RRGHJ.js +142 -0
  70. package/dist/chunks/chunk-TQ475LOI.js +2 -0
  71. package/dist/chunks/chunk-UF3GZ5PO.js +2 -0
  72. package/dist/chunks/chunk-UL6YIT4M.js +2 -0
  73. package/dist/chunks/chunk-V2XJSFFE.js +19 -0
  74. package/dist/chunks/chunk-V4WSBIXB.js +2 -0
  75. package/dist/chunks/chunk-V5RCDBKU.js +2 -0
  76. package/dist/chunks/{chunk-FX4R5PB3.js → chunk-W2CWO4PQ.js} +1 -1
  77. package/dist/chunks/chunk-W33QJA3M.js +2 -0
  78. package/dist/chunks/chunk-WMMESRP3.js +9 -0
  79. package/dist/chunks/chunk-WWPVEK6B.js +127 -0
  80. package/dist/chunks/chunk-X5M7TLJV.js +2 -0
  81. package/dist/chunks/chunk-XDMNJW6J.js +42 -0
  82. package/dist/chunks/{chunk-L22BDZGE.js → chunk-XZSFUGPN.js} +1 -1
  83. package/dist/chunks/client-LTIFNED5.js +2 -0
  84. package/dist/chunks/compaction-config-ECMOFP5H.js +2 -0
  85. package/dist/chunks/{construction-bootstrap-XBHM6NON.js → construction-bootstrap-OAZKGI5Y.js} +1 -1
  86. package/dist/chunks/devtools-MVOFT6N7.js +2 -0
  87. package/dist/chunks/devtools-TXYDDL2A.js +2 -0
  88. package/dist/chunks/dist-5J53DGAO.js +2 -0
  89. package/dist/chunks/errors-ER7ZRPWC.js +2 -0
  90. package/dist/chunks/google-native-WLL27OV7.js +2 -0
  91. package/dist/chunks/host-65E5NM5P.js +2 -0
  92. package/dist/chunks/mistral-native-JXPIDDYZ.js +5 -0
  93. package/dist/chunks/model-DZF6URW3.js +2 -0
  94. package/dist/chunks/permission-YVVMLQ5I.js +2 -0
  95. package/dist/chunks/pi-messages-5LLOZH57.js +16 -0
  96. package/dist/chunks/readline-helpers-UZXWBRXQ.js +2 -0
  97. package/dist/chunks/responses-websocket-Y4N5GXD3.js +2 -0
  98. package/dist/chunks/run-manager-ZFACIZM2.js +2 -0
  99. package/dist/chunks/running-session-Q5Y6A2QV.js +2 -0
  100. package/dist/chunks/skills-TJP6BLZJ.js +2 -0
  101. package/dist/chunks/tool-dispatch-MLM3QTSU.js +2 -0
  102. package/dist/chunks/utils-2QNMYRGA.js +2 -0
  103. package/dist/generated-config-templates.json +6 -0
  104. package/dist/index.d.ts +34 -32
  105. package/dist/index.js +6 -6
  106. package/dist/kodax_bootstrap.js +4 -2
  107. package/dist/kodax_cli.js +1755 -2979
  108. package/dist/kodax_doctor.js +3 -0
  109. package/dist/kodax_resume.js +30 -30
  110. package/dist/manual-topics.json +2211 -0
  111. package/dist/native/darwin-arm64/kodax-text-transaction.node +0 -0
  112. package/dist/native/darwin-arm64/manifest.json +1 -1
  113. package/dist/native/win32-x64/kodax-windows-sandbox.exe +0 -0
  114. package/dist/native/win32-x64/kodax-windows-text-transaction.node +0 -0
  115. package/dist/native/win32-x64/manifest.json +2 -2
  116. package/dist/one-shot-task.js +2 -0
  117. package/dist/provider-auth-cli.js +16 -0
  118. package/dist/provider-capabilities.json +560 -40
  119. package/dist/runtime-daemon-schema.json +1 -0
  120. package/dist/sandbox-network-broker.js +260 -795
  121. package/dist/script-cell.js +1 -0
  122. package/dist/script-worker.cjs +2189 -0
  123. package/dist/sdk-a2a.d.ts +23 -22
  124. package/dist/sdk-a2a.js +6 -8
  125. package/dist/sdk-agent.d.ts +125 -98
  126. package/dist/sdk-agent.js +1 -1
  127. package/dist/sdk-client.d.ts +16 -10
  128. package/dist/sdk-client.js +1 -1
  129. package/dist/sdk-coding.d.ts +109 -80
  130. package/dist/sdk-coding.js +1 -1
  131. package/dist/sdk-experimental-memory.d.ts +3 -3
  132. package/dist/sdk-experimental-memory.js +1 -1
  133. package/dist/sdk-llm.d.ts +265 -14
  134. package/dist/sdk-llm.js +1 -1
  135. package/dist/sdk-mcp.d.ts +3 -3
  136. package/dist/sdk-mcp.js +1 -1
  137. package/dist/sdk-media.d.ts +41 -166
  138. package/dist/sdk-media.js +1 -1
  139. package/dist/sdk-repl.d.ts +81 -51
  140. package/dist/sdk-repl.js +2 -2
  141. package/dist/sdk-runtime.d.ts +216 -2989
  142. package/dist/sdk-runtime.js +1 -1
  143. package/dist/sdk-sandbox.js +1 -1
  144. package/dist/sdk-session.d.ts +15 -14
  145. package/dist/sdk-session.js +1 -1
  146. package/dist/sdk-skills.d.ts +2 -2
  147. package/dist/sdk-skills.js +1 -1
  148. package/dist/semantic-worker.js +121 -75
  149. package/dist/static-text.json +371 -0
  150. package/dist/storage-repair-cli.js +3 -0
  151. package/dist/types-chunks/auth-file.d-ovsHEqD4.d.ts +178 -0
  152. package/dist/types-chunks/{bash-prefix-extractor.d-DFH463j2.d.ts → bash-prefix-extractor.d-CJliu5-D.d.ts} +326 -168
  153. package/dist/types-chunks/{capability-learning.d-B4pxKwP4.d.ts → capability-learning.d-BXDEOON2.d.ts} +4 -4
  154. package/dist/types-chunks/{capability.d-DOF3r0fJ.d.ts → capability.d-DapzKxy3.d.ts} +1 -1
  155. package/dist/types-chunks/{capsule.d-CwpmHGFB.d.ts → capsule.d-EMwSALqK.d.ts} +5 -5
  156. package/dist/types-chunks/{client-contract-CRm9ZpL2.d.ts → client-contract-B7q69yMA.d.ts} +265 -67
  157. package/dist/types-chunks/{controller.d-B4GyqWri.d.ts → controller.d-C0SAuNKu.d.ts} +1 -1
  158. package/dist/types-chunks/{controller.d-P3H97ddz.d.ts → controller.d-D-hPLKaA.d.ts} +71 -11
  159. package/dist/types-chunks/{cost-tracker.d-BeaenODW.d.ts → cost-tracker.d-D1CTx-IO.d.ts} +37 -7
  160. package/dist/types-chunks/{base.d-ZBOdjDUT.d.ts → errors.d-D73qdYbS.d.ts} +91 -74
  161. package/dist/types-chunks/{history-retrieval.d-BzKWDjzG.d.ts → history-retrieval.d-BwEUR9cb.d.ts} +2 -2
  162. package/dist/types-chunks/{manager.d-C8OlTe2J.d.ts → manager.d-BMH8Q6TV.d.ts} +1 -1
  163. package/dist/types-chunks/{manifest.d-COreAnXG.d.ts → manifest.d-YE3-AIeO.d.ts} +1 -1
  164. package/dist/types-chunks/{provider-credential-context.d-BH2OaB1b.d.ts → provider-credential-context.d-Dw-sWcnu.d.ts} +11 -2
  165. package/dist/types-chunks/{provider-request-observation.d-C_bEqr4m.d.ts → provider-request-observation.d-CNe9vse3.d.ts} +4 -2
  166. package/dist/types-chunks/{public-api.d-BLmqDi73.d.ts → public-api.d-BhDU643p.d.ts} +13 -10
  167. package/dist/types-chunks/queue-BxQhqhFM.d.ts +166 -0
  168. package/dist/types-chunks/{resolver.d-DLY01RHx.d.ts → resolver.d-DrkpD8wY.d.ts} +142 -103
  169. package/dist/types-chunks/{review-inbox.d-BTLDdpG2.d.ts → review-inbox.d-Bgt46S7L.d.ts} +16 -3
  170. package/dist/types-chunks/{review-packet.d-Crra1Q7t.d.ts → review-packet.d-ChOfJaNI.d.ts} +7 -7
  171. package/dist/types-chunks/{run-manager.d-DmS1edk4.d.ts → run-manager.d-ChzguipG.d.ts} +48 -12
  172. package/dist/types-chunks/{runtime-client-info-BBBxdU8V.d.ts → runtime-client-info-P_mRDG7j.d.ts} +93 -7
  173. package/dist/types-chunks/runtime-event-BW5Pla7a.d.ts +48 -0
  174. package/dist/types-chunks/sdk-runtime-cDe7qmN3.d.ts +2244 -0
  175. package/dist/types-chunks/{sdk-session-DipY_CCd.d.ts → sdk-session-D3pcSbnA.d.ts} +13 -4
  176. package/dist/types-chunks/{sdk-skills-DokfOoJF.d.ts → sdk-skills-C-UA1A6I.d.ts} +3 -1
  177. package/dist/types-chunks/{side-query.d-DTrhVd_r.d.ts → side-query.d-UFKdWSw7.d.ts} +4 -4
  178. package/dist/types-chunks/{types.d-Jxj49rqO.d.ts → skill-invocation-error.d-gsNNDnnt.d.ts} +24 -14
  179. package/dist/types-chunks/task-results.d-XMdWq0eA.d.ts +15 -0
  180. package/dist/types-chunks/{trusted-repl-entry-B1cb7lAn.d.ts → trusted-repl-entry-Bbkd2HlO.d.ts} +10 -10
  181. package/dist/types-chunks/{types.d-BjOq57-z.d.ts → types.d-Bi8iUd6x.d.ts} +248 -4
  182. package/dist/types-chunks/{types.d-NyCB6ztO.d.ts → types.d-BlXTogOo.d.ts} +24 -13
  183. package/dist/types-chunks/types.d-BvEGNdN-.d.ts +131 -0
  184. package/dist/types-chunks/{types.d-Cb8RdrjU.d.ts → types.d-D8qQjMeo.d.ts} +5 -1
  185. package/dist/types-chunks/{utils.d-Bt6USYa5.d.ts → utils.d-CxHyBvO6.d.ts} +11 -7
  186. package/dist/windows-native-scripts.json +5 -0
  187. package/docs/ARTIFACT_SDK.md +8 -0
  188. package/docs/CLIENT_CONTRACT.md +195 -9
  189. package/docs/SDK_MIGRATION.md +887 -2
  190. package/docs/SPACE_SDK_SEAMS.md +255 -2
  191. package/package.json +33 -6
  192. package/public_docs/README.md +27 -2
  193. package/public_docs/configuration/config-files.md +6 -0
  194. package/public_docs/configuration/custom-providers.md +62 -0
  195. package/public_docs/configuration/providers.md +238 -3
  196. package/public_docs/configuration/sandbox.md +30 -0
  197. package/public_docs/getting-started/quickstart.md +10 -1
  198. package/public_docs/sdk/embedder-guide.md +476 -206
  199. package/dist/chunks/agent-C7MMIRIH.js +0 -2
  200. package/dist/chunks/argument-completer-WIQAV5GP.js +0 -2
  201. package/dist/chunks/chunk-2AM3FRQ7.js +0 -137
  202. package/dist/chunks/chunk-2TBKGO2Q.js +0 -497
  203. package/dist/chunks/chunk-35P7QL2Q.js +0 -2
  204. package/dist/chunks/chunk-5DQTOU2E.js +0 -69
  205. package/dist/chunks/chunk-7NH5BGE4.js +0 -350
  206. package/dist/chunks/chunk-AWYO4MH3.js +0 -635
  207. package/dist/chunks/chunk-CIPS75XZ.js +0 -260
  208. package/dist/chunks/chunk-CRQWSDHV.js +0 -429
  209. package/dist/chunks/chunk-HD5BDOPC.js +0 -2
  210. package/dist/chunks/chunk-JXZMES45.js +0 -12
  211. package/dist/chunks/chunk-KJSZTP5N.js +0 -2
  212. package/dist/chunks/chunk-KYHMB6XR.js +0 -431
  213. package/dist/chunks/chunk-ONUPGMER.js +0 -2
  214. package/dist/chunks/chunk-P42PHZWC.js +0 -351
  215. package/dist/chunks/chunk-SHG3EIH5.js +0 -19
  216. package/dist/chunks/chunk-UH6VOCVP.js +0 -2
  217. package/dist/chunks/chunk-V26LAWJY.js +0 -2
  218. package/dist/chunks/chunk-WOHHMGEF.js +0 -394
  219. package/dist/chunks/chunk-WONYJBAA.js +0 -2
  220. package/dist/chunks/chunk-XJWNIFC2.js +0 -298
  221. package/dist/chunks/chunk-XMWTEVFZ.js +0 -1481
  222. package/dist/chunks/chunk-YJTIPSNW.js +0 -22
  223. package/dist/chunks/chunk-YVBBU6K5.js +0 -5
  224. package/dist/chunks/client-XFASU74S.js +0 -2
  225. package/dist/chunks/compaction-config-JZNGDKWW.js +0 -2
  226. package/dist/chunks/devtools-CD6KSIHE.js +0 -2
  227. package/dist/chunks/devtools-XR5F2C6T.js +0 -2
  228. package/dist/chunks/dist-M4HLQAX7.js +0 -2
  229. package/dist/chunks/dist-ZLR4OTDD.js +0 -2
  230. package/dist/chunks/host-EHVJWNGS.js +0 -2
  231. package/dist/chunks/readline-helpers-KIDMSK76.js +0 -2
  232. package/dist/chunks/run-manager-HNGIYMG7.js +0 -2
  233. package/dist/chunks/tool-dispatch-ON33NJR5.js +0 -2
  234. package/dist/chunks/utils-RHR6YHB2.js +0 -2
@@ -1,2 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{F as x,G as C,a as p,b as u,f as v,m as h,n as y,o as m}from"./chunk-2TBKGO2Q.js";import{q as w}from"./chunk-CIPS75XZ.js";import{be as f}from"./chunk-XMWTEVFZ.js";import{a as t}from"./chunk-ONUPGMER.js";function g(s,c){let i=t(async e=>{let o=structuredClone(e.input);for(let r of["authorization","credential","hostTools","providerCredential","providerCredentialAccess","origin","trustedRunId","workflowHostPolicy"])delete o[r];let n=await c?.({...e,input:o},s);return{...o,...n===void 0?{}:{authorization:structuredClone(n)}}},"authorize");return{statistics:s.statistics??{read:t(async()=>{throw new Error("Execution facts require a compatible Host.")},"read"),readRequests:t(async()=>{throw new Error("Execution facts require a compatible Host.")},"readRequests"),readTools:t(async()=>{throw new Error("Execution facts require a compatible Host.")},"readTools")},lifecycle:s.lifecycle??{requestExit:t(async()=>{throw new Error("Client exit control requires a compatible daemon Host.")},"requestExit"),readExit:t(async()=>{throw new Error("Client exit control requires a compatible daemon Host.")},"readExit"),listPendingExits:t(async()=>{throw new Error("Client exit control requires a compatible daemon Host.")},"listPendingExits")},commands:{execute:t(async e=>s.invocations.executeCommand(await i({kind:"command",input:e})),"execute"),readPrompt:t(e=>s.invocations.readCommandPrompt(e),"readPrompt")},review:{start:t(async e=>s.invocations.startReview(await i({kind:"review",input:e})),"start")},host:{shutdown:t(()=>s.daemon!==void 0?s.daemon.shutdown():s.close().then(()=>({accepted:!0})),"shutdown")},sessions:{cancel:t(e=>s.sessions.cancel(e),"cancel"),create:t(e=>s.sessions.create(e),"create"),list:t(e=>s.sessions.list(e),"list"),read:t(e=>s.sessions.load(e),"read"),delete:t(e=>s.sessions.delete(e),"delete"),archive:t(e=>s.sessions.archive(e),"archive"),unarchive:t(e=>s.sessions.unarchive(e),"unarchive"),getAutoModeStats:t(async e=>await s.sessions.getAutoModeStats(e)??void 0,"getAutoModeStats"),getSettings:t(async e=>p(await s.sessions.getSettings(e)),"getSettings"),getSettingsVersioned:t(async e=>{let o=await s.sessions.getSettingsVersioned(e);return{revision:o.revision,value:p(o.value)}},"getSettingsVersioned"),updateSettingsVersioned:t(async(e,o,n)=>{let r=await s.sessions.updateSettingsVersioned(e,o,n);return{revision:r.revision,value:p(r.value)}},"updateSettingsVersioned"),updateSettings:t(async(e,o)=>p(await s.sessions.updateSettings(e,o)),"updateSettings"),observe:t((e,o,n)=>s.sessions.observeView(e,o,n),"observe"),readItem:t((e,o,n)=>s.sessions.readViewItem(e,o,n),"readItem"),readHistory:t((e,o)=>s.sessions.readHistory(e,o),"readHistory"),readHistoryEntry:t((e,o,n)=>s.sessions.readHistoryEntry(e,o,n),"readHistoryEntry"),searchHistory:t((e,o)=>s.sessions.searchHistory(e,o),"searchHistory"),readGoal:t(e=>s.sessions.readGoal(e),"readGoal"),createGoal:t((e,o)=>s.sessions.createGoal({sessionId:e,...o}),"createGoal"),pauseGoal:t(e=>s.sessions.pauseGoal(e),"pauseGoal"),resumeGoal:t(e=>s.sessions.resumeGoal(e),"resumeGoal"),clearGoal:t(e=>s.sessions.clearGoal(e),"clearGoal"),appendNotice:t(async(e,o)=>{if(!await s.sessions.appendNotice({sessionId:e,...o}))throw new Error("Host did not save the Session notice.")},"appendNotice"),readLineage:t(e=>s.sessions.readLineage(e),"readLineage"),labelEntry:t((e,o)=>s.sessions.labelEntry({sessionId:e,...o}),"labelEntry"),selectBranch:t((e,o,n)=>s.sessions.setActiveEntry({sessionId:e,entryId:o,...n}).then(r=>{if(r===null)throw Object.assign(new Error("No lineage entry matches the selector."),{code:"conflict"});return r}),"selectBranch"),rewindSession:t((e,o)=>s.sessions.rewind({sessionId:e,...o}).then(n=>{if(n===null)throw Object.assign(new Error("Rewind target no longer resolves."),{code:"conflict"});return n}),"rewindSession"),forkSession:t((e,o)=>s.sessions.fork({sessionId:e,...o??{}}).then(n=>{if(n===null)throw Object.assign(new Error("Fork boundary no longer resolves."),{code:"conflict"});return n}),"forkSession"),recoverSession:t((e,o)=>s.sessions.recover({sessionId:e,...o??{}}),"recoverSession"),compact:t(async(e,o)=>{let n=await i({kind:"compaction",input:{...o,sessionId:e}}),r=await s.sessions.compact({sessionId:n.sessionId,customInstructions:n.customInstructions,...n.authorization?.credential!==void 0?{credential:n.authorization.credential}:{}});return{compacted:r.compacted,messages:r.messages,tokensBefore:r.tokensBefore,tokensAfter:r.tokensAfter,...r.report!==void 0?{report:r.report}:{},...r.reason!==void 0?{reason:r.reason}:{}}},"compact")},learning:{list:t(e=>s.learning.list(e),"list"),get:t(e=>s.learning.get(e),"get"),getSnapshot:t(()=>s.learning.getSnapshot(),"getSnapshot"),events:t(e=>s.learning.events(e),"events"),subscribe:t(e=>s.learning.subscribe(e),"subscribe"),acknowledge:t(e=>s.learning.acknowledge(e),"acknowledge"),snooze:t((e,o)=>s.learning.snooze(e,o),"snooze"),reject:t(e=>s.learning.reject(e),"reject"),disable:t(e=>s.learning.disable(e),"disable"),rollback:t(e=>s.learning.rollback(e),"rollback"),promote:t((e,o)=>s.learning.promote(e,o),"promote"),review:t(e=>s.learning.review(e),"review"),trust:t(e=>s.learning.trust(e),"trust")},memory:{async forProject(e){let o=await s.memory.forProject(e);return{memoryRoot:o.memoryRoot,entrypointPath:o.entrypointPath,listReviews:t(()=>o.listReviews(),"listReviews"),reviewerProviderConfigured:t(()=>o.reviewerProviderConfigured(),"reviewerProviderConfigured"),rebuild:t(()=>o.rebuild(),"rebuild"),ensureOpenTarget:t(n=>o.ensureOpenTarget(n),"ensureOpenTarget"),controller:{listRefs:t(n=>o.controller.listRefs(n),"listRefs"),readRef:t(n=>o.controller.readRef(n),"readRef"),remember:t(n=>o.controller.remember(n),"remember"),forgetRef:t((n,r)=>o.controller.forgetRef(n,r),"forgetRef"),approveProposal:t((n,r,a)=>o.controller.approveProposal(n,r,a),"approveProposal"),rejectProposal:t((n,r,a)=>o.controller.rejectProposal(n,r,a),"rejectProposal"),listInbox:t(async()=>(await o.controller.listInbox()).map(n=>({...n,revision:f(n)})),"listInbox"),showProposal:t(async n=>{let r=await o.controller.showProposal(n);return r===void 0?void 0:{...r,revision:f(r)}},"showProposal")}}}},inputs:{submit:t(async e=>s.runs.acceptInput(await i({kind:"input",input:e})),"submit"),read:t((e,o)=>s.runs.getInput(e,o),"read"),withdraw:t((e,o)=>s.runs.withdrawInput(e,o),"withdraw")},runs:{startTool:t(async e=>{let o=await i({kind:"tool",input:e}),n=await s.runs.start({sessionId:o.sessionId,inputId:o.inputId,prompt:o.rawInput,options:{toolInvocation:{name:o.name,input:o.input}},...o.authorization!==void 0?{authorization:o.authorization}:{}});return{runId:n.runId,sessionId:n.sessionId}},"startTool"),read:t(e=>s.runs.get(e),"read"),stop:t(e=>s.runs.abort(e),"stop"),await:t(async e=>{let o=await s.runs.await(e);return{runId:o.runId,sessionId:o.sessionId,phase:o.phase,...o.result!==void 0?{result:o.result}:{},...o.error!==void 0?{error:o.error.message}:{},...o.terminal!==void 0?{terminal:o.terminal}:{},...o.stop!==void 0?{stop:o.stop}:{}}},"await")},interactions:{list:t(e=>s.interactions.list(e),"list"),respond:t((e,o)=>s.interactions.respond(e,o),"respond")},permissions:{listGrants:t(async()=>{let e=await s.permissions.listGrants();return{revision:e.revision,grants:e.value.map(o=>({id:o.id,...o.scope.sessionId!==void 0?{sessionId:o.scope.sessionId}:{},...o.label!==void 0?{label:o.label}:{},...o.persistence!==void 0?{persistence:o.persistence}:{}}))}},"listGrants"),revokeGrant:t((e,o)=>s.permissions.revokeGrant(e,o),"revokeGrant")},registrations:{list:t(()=>s.admin.agentRegistrations.list(),"list"),upsert:t((e,o)=>s.admin.agentRegistrations.upsert(e,o),"upsert"),setEnabled:t((e,o,n)=>s.admin.agentRegistrations.setEnabled(e,o,n),"setEnabled"),remove:t((e,o)=>s.admin.agentRegistrations.remove(e,o),"remove")},agents:{reviewLean:t(async e=>s.invocations.startAgentsLean(await i({kind:"agents_lean",input:e})),"reviewLean"),tree:t(e=>s.agents.tree(e),"tree"),detail:t((e,o)=>s.agents.detail(e,o),"detail"),spawn:t(async(e,o)=>{let n=await i({kind:"agent_spawn",input:{sessionId:e,agent:o}});return n.authorization===void 0?s.agents.spawn(e,n.agent):s.agents.spawn(e,n.agent,{authorization:n.authorization})},"spawn"),send:t((e,o,n,r)=>s.agents.send(e,o,n,r),"send"),followup:t(async(e,o,n,r)=>{let a=await i({kind:"agent_followup",input:{sessionId:e,actorPath:o,objective:n,...r?.expectedRevision===void 0?{}:{expectedRevision:r.expectedRevision}}});return s.agents.followup(e,o,n,{expectedRevision:a.expectedRevision,...a.authorization===void 0?{}:{authorization:a.authorization}})},"followup"),interrupt:t((e,o,n)=>s.agents.interrupt(e,o,n),"interrupt"),output:t((e,o,n)=>s.agents.output(e,o,n),"output"),wait:t((e,o,n,r)=>s.agents.wait(e,o,n,r?.signal===void 0?void 0:{signal:r.signal}),"wait")},config:{read:t(async()=>u(await s.config.read()),"read"),readEffective:t(async()=>{let{entries:e}=await s.config.readEffective(),o=t((r,a)=>({value:a,source:e[r]?.source??"unset",applied:e[r]?.applied===!0||e[r]?.present!==!0}),"project"),n=e.fallbackProviders?.value;return{stallLog:o("stallLog",e.stallLog?.value==="1"||e.stallLog?.value===!0),fallbackProviders:o("fallbackProviders",typeof n=="string"?n.split(",").map(r=>r.trim()).filter(Boolean):Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}},"readEffective"),patch:t(async e=>u(await s.config.patch(e)),"patch"),reload:t(async()=>({ok:!0,config:u((await s.config.reload()).config)}),"reload")},mcp:{status:t(()=>s.mcp.status(),"status"),listServers:t(()=>s.mcp.listServers(),"listServers"),getServer:t(e=>s.mcp.getServer(e),"getServer"),validateServer:t((e,o)=>s.mcp.validateServer(e,o),"validateServer"),upsertServer:t((e,o)=>s.mcp.upsertServer(e,o),"upsertServer"),deleteServer:t(e=>s.mcp.deleteServer(e),"deleteServer"),reloadServers:t(()=>s.mcp.reloadServers(),"reloadServers"),listTools:t(e=>s.mcp.listTools(e),"listTools")},workflows:{start:t(async e=>s.workflows.start({...await i({kind:"workflow",input:e}),settingsDefaults:"product"}),"start"),list:t(async e=>{let o=[];for(let n of await s.workflows.list(e??{})){let r=n.updatedAt===void 0?await s.workflows.get(n.runId):n;if(r?.updatedAt===void 0)throw new Error(`Workflow process is unavailable: ${n.runId}`);o.push({runId:n.runId,workflowName:n.workflow,status:n.status,totalSpawned:n.totalSpawned,eventCount:n.eventCount,runDir:n.runDir,...n.endedAt!==void 0?{endedAt:new Date(n.endedAt).toISOString()}:{},startedAt:new Date(n.startedAt).toISOString(),updatedAt:r.updatedAt,...r.displayName!==void 0?{displayName:r.displayName}:{},...n.resultText!==void 0?{resultSummary:n.resultText}:{},...n.error!==void 0?{error:n.error}:{}})}return o},"list"),get:t(e=>s.workflows.get(e),"get"),subscribe:t((e,o,n)=>{let r=s.workflows.subscribe(e,o,n);return{ready:r.ready??Promise.resolve(),close:t(()=>r.close(),"close")}},"subscribe"),pause:t(e=>s.workflows.pause(e),"pause"),resume:t(e=>s.workflows.resume(e),"resume"),stop:t((e,o)=>s.workflows.stop(e,o),"stop")},catalog:{extensions:t(async()=>{let e=await s.catalog.extensions(),o=t(({path:a,label:d,loadSource:l})=>({path:a,label:d,loadSource:l}),"loaded"),n=t(({kind:a,id:d,label:l})=>({kind:a,id:d,label:l}),"source"),r=e.diagnostics;return{active:e.active,extensions:e.extensions.map(o),diagnostics:r&&{loadedExtensions:r.loadedExtensions.map(o),capabilityProviders:r.capabilityProviders.map(({id:a,kinds:d,metadata:l})=>({id:a,kinds:d,metadata:l})),commands:r.commands.map(({name:a,aliases:d,description:l})=>({name:a,aliases:d,description:l})),tools:r.tools.map(a=>({name:a.name,source:n(a.source),shadowedSources:a.shadowedSources.map(n)})),hooks:r.hooks.map(a=>({hook:a.hook,order:a.order,source:n(a.source)})),failures:r.failures.map(a=>({stage:a.stage,target:a.target,message:a.message,source:n(a.source)})),defaults:{activeTools:r.defaults.activeTools,modelSelection:{...r.defaults.modelSelection},thinkingLevel:r.defaults.thinkingLevel}}}},"extensions"),providers:t(()=>s.catalog.providers(),"providers"),models:t(async e=>(await s.catalog.providers()).filter(o=>e?.provider===void 0||o.name===e.provider).map(o=>({provider:o.name,models:o.models})),"models"),reasoningEfforts:t(e=>s.catalog.reasoningEfforts(e),"reasoningEfforts"),probeReasoningEfforts:t(e=>s.catalog.probeReasoningEfforts(e),"probeReasoningEfforts"),forgetCapabilities:t(e=>s.catalog.forgetCapabilities(e),"forgetCapabilities"),commands:t(async e=>(await s.catalog.commands(e)).map(o=>({name:o.name,...o.aliases!==void 0?{aliases:o.aliases}:{},description:o.description,source:String(o.source),...o.userInvocable!==void 0?{userInvocable:o.userInvocable}:{}})),"commands"),skills:t(async e=>(await s.catalog.skills(e)).map(o=>({name:o.name,description:o.description,userInvocable:o.userInvocable,path:o.path,source:String(o.source)})),"skills")},disconnect:t(()=>s.close(),"disconnect")}}t(g,"toKodaXProductClient");import b from"node:path";async function H(s){let{instanceId:c,instanceSecret:i}=s.clientInfo;if(!c||!/^[A-Za-z0-9_.:-]{4,160}$/.test(c)||!i||i.length<32||i.length>512)throw new Error("Exit recovery requires the original stable client identity and secret.");let e=v(s.homeDir===void 0?w:b.resolve(s.homeDir,".kodax"),s.profile);return Promise.all(y(e,h(c,i)).map(o=>m(e,o)))}t(H,"readKodaXClientExits");async function q(s={}){return g(await C({...s,requirements:{productClient:1,productHistoryBoundaries:1,productExitControl:1,productExecutionFacts:1,...s.authorizeExecution?{productExecutionAuthorization:2,productActorAuthorization:1}:{}}}),s.authorizeExecution)}t(q,"ensureKodaXClient");async function j(s={}){let c=await x({homeDir:s.homeDir,profile:s.profile,endpoint:s.endpoint,daemonToken:s.token,autoStart:!1,onStartupProgress:s.onStartupProgress,clientInfo:s.clientInfo,requirements:{productClient:1,productHistoryBoundaries:1,productExitControl:1,productExecutionFacts:1,...s.authorizeExecution?{productExecutionAuthorization:2,productActorAuthorization:1}:{}}});return g(c,s.authorizeExecution)}t(j,"connectKodaXClient");export{g as a,H as b,q as c,j as d};
@@ -1,298 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Ka as v}from"./chunk-XMWTEVFZ.js";import{a}from"./chunk-ONUPGMER.js";import{spawnSync as O}from"node:child_process";import{createHash as F}from"node:crypto";import c from"node:fs";import q from"node:os";import i from"node:path";import{fileURLToPath as W}from"node:url";var z=64*1024*1024,Y="v2";function x(){{let e=JSON.parse('{"darwin-arm64":"{\\n \\"version\\": 1,\\n \\"platform\\": \\"darwin\\",\\n \\"arch\\": \\"arm64\\",\\n \\"textTransaction\\": {\\n \\"file\\": \\"kodax-text-transaction.node\\",\\n \\"protocol\\": 5,\\n \\"sha256\\": \\"3822f552af1c81ddc3df0de743f5bbd87c0588d9aa0f9617446f22b6b483a156\\"\\n },\\n \\"legal\\": [\\n {\\n \\"file\\": \\"LICENSE-APACHE.txt\\",\\n \\"sha256\\": \\"6bdadfab6d5d2b0d4e0ccea244f5e412d1597dc84c56db645556ce192b131e98\\"\\n }\\n ]\\n}\\n","darwin-x64":"{\\n \\"version\\": 1,\\n \\"platform\\": \\"darwin\\",\\n \\"arch\\": \\"x64\\",\\n \\"textTransaction\\": {\\n \\"file\\": \\"kodax-text-transaction.node\\",\\n \\"protocol\\": 5,\\n \\"sha256\\": \\"7c8ab6d7b687cc0a2ff3dd453921eb449f12b8481e1815793bbbccfd39911385\\"\\n },\\n \\"legal\\": [\\n {\\n \\"file\\": \\"LICENSE-APACHE.txt\\",\\n \\"sha256\\": \\"6bdadfab6d5d2b0d4e0ccea244f5e412d1597dc84c56db645556ce192b131e98\\"\\n }\\n ]\\n}\\n","linux-arm64":"{\\n \\"version\\": 1,\\n \\"platform\\": \\"linux\\",\\n \\"arch\\": \\"arm64\\",\\n \\"textTransaction\\": {\\n \\"file\\": \\"kodax-text-transaction.node\\",\\n \\"protocol\\": 5,\\n \\"sha256\\": \\"3f788f0fb2bd627c758fcfe5b171cfed20da8102fa31d56e41b3047e855c016e\\"\\n },\\n \\"legal\\": [\\n {\\n \\"file\\": \\"LICENSE-APACHE.txt\\",\\n \\"sha256\\": \\"6bdadfab6d5d2b0d4e0ccea244f5e412d1597dc84c56db645556ce192b131e98\\"\\n }\\n ]\\n}\\n","linux-x64":"{\\n \\"version\\": 1,\\n \\"platform\\": \\"linux\\",\\n \\"arch\\": \\"x64\\",\\n \\"textTransaction\\": {\\n \\"file\\": \\"kodax-text-transaction.node\\",\\n \\"protocol\\": 5,\\n \\"sha256\\": \\"a667ba689ef9b95118236496e60612ee4407dae02a67fdef30e6456ee4592a6a\\"\\n },\\n \\"legal\\": [\\n {\\n \\"file\\": \\"LICENSE-APACHE.txt\\",\\n \\"sha256\\": \\"6bdadfab6d5d2b0d4e0ccea244f5e412d1597dc84c56db645556ce192b131e98\\"\\n }\\n ]\\n}\\n","win32-x64":"{\\n \\"version\\": 1,\\n \\"platform\\": \\"win32\\",\\n \\"arch\\": \\"x64\\",\\n \\"textTransaction\\": {\\n \\"file\\": \\"kodax-windows-text-transaction.node\\",\\n \\"protocol\\": 5,\\n \\"sha256\\": \\"89843d5d060b4bd1b5db28e6959094ee643eafe6c3a673d8159eda37df4df55d\\"\\n },\\n \\"legal\\": [\\n {\\n \\"file\\": \\"LICENSE-APACHE.txt\\",\\n \\"sha256\\": \\"f8dd90eb71a7af4048bde3ff1d18b7d7280522e0a429ff71b7270a4189cf3568\\"\\n },\\n {\\n \\"file\\": \\"NOTICE-windows-sandbox.txt\\",\\n \\"sha256\\": \\"78723eb162f0782c5e27928f46c681996edc1907d552eba9d0f7f53e014c20c9\\"\\n }\\n ],\\n \\"shellSandbox\\": {\\n \\"file\\": \\"kodax-windows-sandbox.exe\\",\\n \\"protocol\\": 10,\\n \\"sha256\\": \\"52f08d685a24017f0527946e0ac7c0dbc28f37c03726736d912cf645f346f249\\"\\n },\\n \\"asrtRunner\\": {\\n \\"file\\": \\"srt-win.exe\\",\\n \\"version\\": \\"0.0.65\\",\\n \\"sha256\\": \\"777736e17d6cf9b4280f155f5cda731fdff0f789fa16e6cb3adc0006073e241a\\"\\n }\\n}\\n"}');if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("embedded native manifest map is invalid");let t=e[`${process.platform}-${process.arch}`];if(typeof t!="string"||t==="")throw new Error(`embedded native manifest is missing for ${process.platform}-${process.arch}`);return t}return process.platform==="win32",`{
3
- "version": 1,
4
- "platform": "linux",
5
- "arch": "x64",
6
- "textTransaction": {
7
- "file": "kodax-text-transaction.node",
8
- "protocol": 5,
9
- "sha256": "a667ba689ef9b95118236496e60612ee4407dae02a67fdef30e6456ee4592a6a"
10
- },
11
- "legal": [
12
- {
13
- "file": "LICENSE-APACHE.txt",
14
- "sha256": "6bdadfab6d5d2b0d4e0ccea244f5e412d1597dc84c56db645556ce192b131e98"
15
- }
16
- ]
17
- }
18
- `}a(x,"embeddedNativeManifestText");function E(e){let t=i.resolve(e),r=i.parse(t),n=t.slice(r.root.length).split(i.sep).filter(Boolean),o=n.findIndex(u=>u.toLowerCase()==="app.asar");if(o<0)return t;let s=[...n];s[o]=`${n[o]}.unpacked`;let d=i.join(r.root,...s);return c.existsSync(d)?d:t}a(E,"physicalElectronArtifactPath");function D(e,t=!1){let r=i.dirname(W(e)),n=`win32-${process.arch}`;return[...new Set([i.join(r,"native",n),i.join(r,"..","native",n),i.join(r,"..","dist","native",n),i.join(i.dirname(process.execPath),"vendor","kodax-native",n)].map(o=>{let s=i.resolve(o);return t?E(s):s}))]}a(D,"artifactDirectories");function L(e){let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("manifest root is not an object");return t}a(L,"manifestObject");function M(e){if(e.version!==1||e.platform!=="win32"||e.arch!==process.arch)throw new Error("manifest platform, architecture, or version is incompatible")}a(M,"assertManifestHeader");function k(e,t){let r=e[t];if(typeof r?.file!="string"||i.basename(r.file)!==r.file||!Number.isSafeInteger(r.protocol)||!/^[0-9a-f]{64}$/i.test(r.sha256??""))throw new Error(`manifest ${t} entry is invalid`);return r}a(k,"assertManifestEntry");function Q(e){let t=e.asrtRunner;if(t?.file!=="srt-win.exe"||typeof t.version!="string"||t.version===""||!/^[0-9a-f]{64}$/i.test(t.sha256??""))throw new Error("manifest asrtRunner entry is invalid");return t}a(Q,"assertManifestAsrtRunner");function Z(e){let t=L(e);M(t);for(let r of["textTransaction","shellSandbox"])k(t,r);return Q(t),t}a(Z,"parseManifestText");function ee(e,t){let r=L(e);M(r);let n=k(r,t);return{manifest:r,entry:n}}a(ee,"parseManifestEntryText");function h(e,t){let r=process.platform==="win32"?i.win32:i.posix,n=r.relative(r.resolve(e),r.resolve(t));return n===""||!n.startsWith("..")&&!r.isAbsolute(n)}a(h,"sameOrInside");function _(e,t){try{return c.realpathSync.native(e).toLowerCase()===c.realpathSync.native(t).toLowerCase()}catch{return!1}}a(_,"sameRealPath");function g(e,t){let r=$(e);if(t.map($).some(n=>h(n,r)||h(r,n)))throw new Error(`native artifact source overlaps a writable Runtime root: ${e}. Use a production bundle with an embedded native manifest.`)}a(g,"assertDevelopmentSourceIsOutsideWriteRoots");function R(e,t){return e.dev===t.dev&&e.ino===t.ino}a(R,"sameFileIdentity");function j(e,t){let r=c.lstatSync(e),n=a(s=>!s.isFile()||s.isSymbolicLink()||t&&s.nlink!==1||s.size>z,"invalid");if(n(r))throw new Error(`native artifact is not a bounded ordinary file: ${e}`);let o=c.openSync(e,c.constants.O_RDONLY);try{let s=c.fstatSync(o),d=c.lstatSync(e);if(n(s)||n(d)||!R(r,s)||!R(s,d))throw new Error(`native artifact is not a stable bounded ordinary file: ${e}`);let u=Buffer.allocUnsafe(s.size+1),l=0;for(;l<u.byteLength;){let y=c.readSync(o,u,l,u.byteLength-l,null);if(y===0)break;l+=y}let f=c.fstatSync(o);if(l!==s.size||n(f)||!R(s,f))throw new Error(`native artifact changed during bounded read: ${e}`);return u.subarray(0,l)}finally{c.closeSync(o)}}a(j,"readBoundedOrdinaryFile");function U(e,t,r){let n=j(e,r);if(F("sha256").update(n).digest("hex")!==t.toLowerCase())throw new Error(`native artifact hash mismatch: ${e}`);return n}a(U,"readHashPinnedArtifact");function m(e,t){return U(e,t,!0)}a(m,"readVerifiedArtifact");function V(e,t){m(e,t);let r=c.realpathSync.native(w()),n=c.realpathSync.native(e);if(!h(r,n))throw new Error("Protected native artifact escaped its physical cache root.");return n}a(V,"verifyProtectedWindowsNativeArtifactImage");function w(){let e=process.env.LOCALAPPDATA??i.join(q.homedir(),"AppData","Local");return i.join(i.resolve(e),"KodaXNativeArtifactsV3")}a(w,"windowsNativeArtifactCacheRoot");function te(){return i.join(w(),"control-v1")}a(te,"windowsSandboxControlDirectory");function Ae(e){let t=$(w()),r=e.allowRead.find(d=>{let u=$(d);return h(t,u)}),n=e.allowWrite.find(d=>{let u=$(d);return h(t,u)||h(u,t)}),o=r??n;if(o!==void 0)throw new Error(`Windows policy overlaps protected native shell control state: ${o}`);let s=[...e.denyRead,...e.denyWrite].find(d=>h(t,$(d)));if(s!==void 0)throw new Error(`Windows deny policy targets protected native shell control state: ${s}`)}a(Ae,"assertWindowsSandboxControlStateNotDirectlyAccessible");function K(e){let t=$(w()),r=e.find(n=>{let o=$(n);return h(t,o)||h(o,t)});if(r!==void 0)throw new Error(`Windows write policy targets protected native state: ${r}`)}a(K,"assertWindowsNativeArtifactStoreNotDirectlyWritable");function re(){return i.join(b(),"artifacts-v1")}a(re,"unixNativeArtifactCacheRoot");function b(){return i.join(i.resolve(v()),"native-text-state-v1")}a(b,"unixTrustedTextStateRoot");function G(){let e=process.geteuid?.();if(e===void 0)throw new Error("Unix trusted text coordination requires an effective user identity");let t=process.platform==="darwin"?"/private/tmp":"/tmp";return i.join(t,`kodax-native-text-coordination-v1-${e}`)}a(G,"unixTrustedTextCoordinationRoot");function ne(){return process.platform==="win32"?[w()]:[b(),G()]}a(ne,"trustedTextNativeArtifactStateRoots");function oe(e){X(e,"write")}a(oe,"assertTrustedTextNativeStateNotDirectlyWritable");function ve(e){X(e,"read")}a(ve,"assertTrustedTextNativeStateNotDirectlyReadable");function X(e,t){let r=(process.platform==="win32"?ne():[J(),ce()]).map($),n=e.map($);for(let o of r){let s=n.find(d=>h(o,d)||h(d,o));if(s!==void 0)throw new Error(`Runtime ${t} policy targets protected native text state: ${s}`)}}a(X,"assertTrustedTextNativeStateNotDirectlyAccessible");function $(e){let t=i.resolve(e),r=[];for(;;){try{c.lstatSync(t)}catch(n){let o=n instanceof Error&&"code"in n?n.code:void 0;if(o!=="ENOENT"&&o!=="ENOTDIR")throw new Error(`Unable to inspect Runtime filesystem policy root: ${e}`,{cause:n});let s=i.dirname(t);if(s===t)throw new Error(`Runtime filesystem policy root has no existing ancestor: ${e}`);r.unshift(i.basename(t)),t=s;continue}try{return i.resolve(c.realpathSync.native(t),...r)}catch(n){throw new Error(`Unable to canonicalize Runtime filesystem policy root: ${e}`,{cause:n})}}}a($,"canonicalExistingPath");function ie(e,t){let r=i.dirname(W(e)),n=`${process.platform}-${process.arch}`;return[...new Set([i.join(r,"native",n),i.join(r,"..","native",n),i.join(r,"..","dist","native",n),i.join(i.dirname(process.execPath),"vendor","kodax-native",n)].map(o=>{let s=i.resolve(o);return t?E(s):s}))]}a(ie,"portableTextArtifactDirectories");function se(e){let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("native text manifest root is not an object");let r=t,n=r.textTransaction;if(r.version!==1||r.platform!==process.platform||r.arch!==process.arch||typeof n?.file!="string"||i.basename(n.file)!==n.file||!Number.isSafeInteger(n.protocol)||!/^[0-9a-f]{64}$/i.test(n.sha256??""))throw new Error("native text manifest is incompatible");return r}a(se,"parsePortableTextManifest");function C(e){let t=c.lstatSync(e),r=process.geteuid?.();if(!t.isDirectory()||t.isSymbolicLink()||r!==void 0&&t.uid!==r||(t.mode&63)!==0)throw new Error(`native text state directory is not private and host-owned: ${e}`)}a(C,"assertPrivateUnixDirectory");function ae(e){let t=J(),r=i.relative(t,e);if(r.startsWith("..")||i.isAbsolute(r))throw new Error("native text artifact escaped its cache root");let n=t;for(let o of r.split(i.sep).filter(Boolean)){n=i.join(n,o);try{c.mkdirSync(n,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s}C(n)}}a(ae,"ensurePrivateUnixDirectory");function J(){let e=i.resolve(v());if(I(e),c.mkdirSync(e,{recursive:!0,mode:448}),I(e),c.realpathSync.native(e)!==e)throw new Error("Agent home must not resolve through a symbolic-link alias");let t=b();try{c.mkdirSync(t,{mode:448})}catch(r){if(r.code!=="EEXIST")throw r}return C(t),c.realpathSync.native(t)}a(J,"ensureUnixTrustedTextStateRoot");function ce(){let e=G();try{c.mkdirSync(e,{mode:448})}catch(t){if(t.code!=="EEXIST")throw t}return C(e),c.realpathSync.native(e)}a(ce,"ensureUnixTrustedTextCoordinationRoot");function I(e){let t=i.resolve(e),r=i.parse(t),n=r.root;for(let o of t.slice(r.root.length).split(i.sep).filter(Boolean)){n=i.join(n,o);try{if(c.lstatSync(n).isSymbolicLink())throw new Error(`Agent home path contains a symbolic-link ancestor: ${n}`)}catch(s){if(s.code==="ENOENT")return;throw s}}}a(I,"assertNoUnixSymlinkAncestor");function de(e,t){let r=i.join(re(),`${process.platform}-${process.arch}`,"textTransaction",e.sha256.toLowerCase());ae(r);let n=i.join(r,e.file);if(!c.existsSync(n)){let d=i.join(r,`.${process.pid}-${Date.now()}.tmp`),u;try{u=c.openSync(d,c.constants.O_CREAT|c.constants.O_EXCL|c.constants.O_WRONLY|c.constants.O_NOFOLLOW,320);let l=0;for(;l<t.length;){let f=c.writeSync(u,t,l,t.length-l,l);if(f===0)throw new Error("native text artifact write made no progress");l+=f}c.fsyncSync(u),c.closeSync(u),u=void 0;try{c.linkSync(d,n)}catch(f){if(f.code!=="EEXIST")throw f}}finally{u!==void 0&&c.closeSync(u),c.rmSync(d,{force:!0})}}let o=c.lstatSync(n),s=process.geteuid?.();if(!o.isFile()||o.isSymbolicLink()||o.nlink!==1||s!==void 0&&o.uid!==s||(o.mode&511)!==320)throw new Error("protected native text artifact has an unsafe identity or mode");return m(n,e.sha256),c.realpathSync.native(n)}a(de,"provisionUnixTextArtifact");function Re(e,t,r,n=r){if(oe(r),process.platform==="win32")return ye(e,"textTransaction",t,{untrustedWriteRoots:r,developmentWriteRoots:n}).path;if(process.platform!=="linux"&&process.platform!=="darwin")throw new Error(`Trusted text transactions are unavailable on ${process.platform}.`);let o=x(),s=[];for(let d of ie(e,o!==void 0)){let u=i.join(d,"manifest.json");try{g(d,o===void 0?n:r);let l=se(o??c.readFileSync(u,"utf8"));if(l.textTransaction.protocol!==t)throw new Error(`textTransaction protocol ${l.textTransaction.protocol} does not match ${t}`);let f=i.join(d,l.textTransaction.file),y=m(f,l.textTransaction.sha256);return de(l.textTransaction,y)}catch(l){s.push(`${u}: ${l instanceof Error?l.message:String(l)}`)}}throw new Error(`A compatible KodaX text transaction artifact is unavailable. ${s.join(" | ")}`)}a(Re,"resolveTrustedTextNativeArtifact");function N(e,t,r,n=!1){let o=n?"local-users":r===void 0?"host-only":`sandbox-${F("sha256").update(r.toUpperCase()).digest("hex").slice(0,16)}`;return i.join(w(),Y,`win32-${process.arch}`,e,o,t.toLowerCase())}a(N,"protectedArtifactDirectory");var le=String.raw`
19
- $ErrorActionPreference = 'Stop'
20
- $payloadText = [Console]::In.ReadToEnd()
21
- if ([Text.Encoding]::UTF8.GetByteCount($payloadText) -gt 90000000) { throw 'payload exceeds bound' }
22
- $payload = $payloadText | ConvertFrom-Json
23
- $hostSid = [Security.Principal.WindowsIdentity]::GetCurrent().User
24
- $systemSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
25
- $usersSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-545')
26
- $sandboxSid = if ([string]::IsNullOrEmpty([string]$payload.sandboxReadSid)) { $null } else { [Security.Principal.SecurityIdentifier]::new([string]$payload.sandboxReadSid) }
27
- $localUsersReadExecute = [bool]$payload.localUsersReadExecute
28
- $allowCreate = [bool]$payload.allowCreate
29
- $inherit = [Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit
30
- $none = [Security.AccessControl.PropagationFlags]::None
31
- $allow = [Security.AccessControl.AccessControlType]::Allow
32
- function New-DirectorySecurity {
33
- $security = [Security.AccessControl.DirectorySecurity]::new()
34
- $security.SetAccessRuleProtection($true, $false)
35
- $security.SetOwner($hostSid)
36
- [void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($hostSid, [Security.AccessControl.FileSystemRights]::FullControl, $inherit, $none, $allow))
37
- [void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($systemSid, [Security.AccessControl.FileSystemRights]::FullControl, $inherit, $none, $allow))
38
- [void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($usersSid, [Security.AccessControl.FileSystemRights]::ReadAndExecute, $inherit, $none, $allow))
39
- return $security
40
- }
41
- function New-FileSecurity {
42
- $security = [Security.AccessControl.FileSecurity]::new()
43
- $security.SetAccessRuleProtection($true, $false)
44
- $security.SetOwner($hostSid)
45
- [void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($hostSid, [Security.AccessControl.FileSystemRights]::FullControl, $allow))
46
- [void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($systemSid, [Security.AccessControl.FileSystemRights]::FullControl, $allow))
47
- if ($localUsersReadExecute) { [void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($usersSid, [Security.AccessControl.FileSystemRights]::ReadAndExecute, $allow)) }
48
- elseif ($null -ne $sandboxSid) { [void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sandboxSid, [Security.AccessControl.FileSystemRights]::ReadAndExecute, $allow)) }
49
- return $security
50
- }
51
- function Assert-NoReparse([string]$candidate) {
52
- $item = Get-Item -LiteralPath $candidate -Force
53
- if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw "reparse artifact path: $candidate" }
54
- }
55
- function Assert-AclShape($acl, [bool]$directory, [string]$candidate) {
56
- if (-not $acl.AreAccessRulesProtected -or $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $hostSid.Value) { throw 'artifact ACL is not protected and host-owned' }
57
- $expected = @{}
58
- $expected[$hostSid.Value] = [int][Security.AccessControl.FileSystemRights]::FullControl
59
- $expected[$systemSid.Value] = [int][Security.AccessControl.FileSystemRights]::FullControl
60
- $readExecuteMask = [int]([Security.AccessControl.FileSystemRights]::ReadAndExecute -bor [Security.AccessControl.FileSystemRights]::Synchronize)
61
- if ($directory) { $expected[$usersSid.Value] = $readExecuteMask }
62
- if (-not $directory -and $localUsersReadExecute) { $expected[$usersSid.Value] = $readExecuteMask }
63
- elseif (-not $directory -and $null -ne $sandboxSid) { $expected[$sandboxSid.Value] = $readExecuteMask }
64
- $observed = @{}
65
- foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {
66
- if ($rule.IsInherited) { throw 'artifact ACL contains an inherited rule' }
67
- # Existing DENY ACEs can be legacy KodaX state or administrator policy.
68
- # Shape alone cannot prove ownership, so never remove or rewrite them. A
69
- # DENY cannot widen access, and is safe to retain while the exact ALLOW
70
- # surface below remains closed and fully verified.
71
- if ($rule.AccessControlType -eq [Security.AccessControl.AccessControlType]::Deny) { continue }
72
- $sid = $rule.IdentityReference.Value
73
- if (-not $expected.ContainsKey($sid) -or $observed.ContainsKey($sid)) { throw "artifact ACL contains an unexpected allow rule for $sid at $candidate" }
74
- if ([int]$rule.FileSystemRights -ne $expected[$sid]) { throw "artifact ACL allow mask is invalid for $sid at $candidate" }
75
- if ($directory) {
76
- if ($rule.InheritanceFlags -ne $inherit -or $rule.PropagationFlags -ne $none) { throw 'artifact directory ACL inheritance is invalid' }
77
- } elseif ($rule.InheritanceFlags -ne [Security.AccessControl.InheritanceFlags]::None) {
78
- throw 'artifact file ACL inheritance is invalid'
79
- }
80
- $observed[$sid] = $true
81
- }
82
- foreach ($sid in $expected.Keys) { if (-not $observed.ContainsKey($sid)) { throw 'artifact ACL is missing a required allow rule' } }
83
- }
84
- function Ensure-ProtectedDirectory([string]$candidate) {
85
- if (Test-Path -LiteralPath $candidate) {
86
- Assert-NoReparse $candidate
87
- Assert-AclShape ([IO.Directory]::GetAccessControl($candidate)) $true $candidate
88
- return
89
- }
90
- if (-not $allowCreate) { throw "protected artifact directory is missing: $candidate" }
91
- [void][IO.Directory]::CreateDirectory($candidate, (New-DirectorySecurity))
92
- Assert-NoReparse $candidate
93
- Assert-AclShape ([IO.Directory]::GetAccessControl($candidate)) $true $candidate
94
- }
95
- $cacheRoot = [IO.Path]::GetFullPath([string]$payload.cacheRoot)
96
- $anchor = [IO.Path]::GetFullPath([string]$payload.anchor)
97
- $destinationDirectory = [IO.Path]::GetFullPath([string]$payload.destinationDirectory)
98
- if (-not $cacheRoot.StartsWith($anchor + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase)) { throw 'cache root escaped host LocalAppData' }
99
- if (-not $destinationDirectory.StartsWith($cacheRoot + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase)) { throw 'destination escaped cache root' }
100
- Assert-NoReparse $anchor
101
- $current = $anchor
102
- $relative = $destinationDirectory.Substring($anchor.Length).TrimStart([IO.Path]::DirectorySeparatorChar)
103
- foreach ($part in ($relative -split '[\\/]')) {
104
- if ([string]::IsNullOrEmpty($part)) { continue }
105
- $current = [IO.Path]::Combine($current, $part)
106
- Ensure-ProtectedDirectory $current
107
- }
108
- $bytes = [Convert]::FromBase64String([string]$payload.bytes)
109
- $hash = [Security.Cryptography.SHA256]::Create()
110
- try { $actual = ([BitConverter]::ToString($hash.ComputeHash($bytes))).Replace('-', '').ToLowerInvariant() } finally { $hash.Dispose() }
111
- if ($actual -ne ([string]$payload.sha256).ToLowerInvariant()) { throw 'provisioning payload hash mismatch' }
112
- $destination = [IO.Path]::Combine($destinationDirectory, [string]$payload.file)
113
- # Keep the CreateNew staging name short. PowerShell 5.1 FileStream still hits
114
- # MAX_PATH on otherwise valid LocalAppData roots before long-path policy is
115
- # enabled, while GetRandomFileName retains cross-process collision resistance.
116
- $temporary = [IO.Path]::Combine($destinationDirectory, '.' + [IO.Path]::GetRandomFileName() + '.tmp')
117
- try {
118
- if (-not (Test-Path -LiteralPath $destination)) {
119
- if (-not $allowCreate) { throw 'protected artifact is missing' }
120
- $stream = [IO.FileStream]::new($temporary, [IO.FileMode]::CreateNew, [Security.AccessControl.FileSystemRights]::FullControl, [IO.FileShare]::None, 65536, [IO.FileOptions]::WriteThrough, (New-FileSecurity))
121
- try { $stream.Write($bytes, 0, $bytes.Length); $stream.Flush($true) } finally { $stream.Dispose() }
122
- try { [IO.File]::Move($temporary, $destination) } catch { if (-not (Test-Path -LiteralPath $destination)) { throw } }
123
- }
124
- Assert-NoReparse $destination
125
- Assert-AclShape ([IO.File]::GetAccessControl($destination)) $false $destination
126
- # A sibling Runtime may already be executing this content-addressed image.
127
- # Verification must share an immutable published file for read/delete or
128
- # artifact provisioning itself becomes a cross-Runtime admission lock.
129
- $share = [IO.FileShare]::Read -bor [IO.FileShare]::Delete
130
- $stream = [IO.FileStream]::new($destination, [IO.FileMode]::Open, [IO.FileAccess]::Read, $share)
131
- try {
132
- $publishedHasher = [Security.Cryptography.SHA256]::Create()
133
- try { $publishedHash = ([BitConverter]::ToString($publishedHasher.ComputeHash($stream))).Replace('-', '').ToLowerInvariant() } finally { $publishedHasher.Dispose() }
134
- } finally { $stream.Dispose() }
135
- if ($publishedHash -ne $actual) { throw 'published artifact hash mismatch' }
136
- [Console]::Out.Write($destination)
137
- } finally {
138
- if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Force }
139
- }
140
- `,ue=String.raw`
141
- $ErrorActionPreference = 'Stop'
142
- $payload = ([Console]::In.ReadToEnd() | ConvertFrom-Json)
143
- $hostSid = [Security.Principal.WindowsIdentity]::GetCurrent().User
144
- $systemSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
145
- $inherit = [Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit
146
- $none = [Security.AccessControl.PropagationFlags]::None
147
- $allow = [Security.AccessControl.AccessControlType]::Allow
148
- function Assert-NoReparse([string]$candidate) {
149
- $item = Get-Item -LiteralPath $candidate -Force
150
- if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw "reparse control path: $candidate" }
151
- }
152
- function New-ControlSecurity {
153
- $security = [Security.AccessControl.DirectorySecurity]::new()
154
- $security.SetAccessRuleProtection($true, $false)
155
- $security.SetOwner($hostSid)
156
- [void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($hostSid, [Security.AccessControl.FileSystemRights]::FullControl, $inherit, $none, $allow))
157
- [void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($systemSid, [Security.AccessControl.FileSystemRights]::FullControl, $inherit, $none, $allow))
158
- return $security
159
- }
160
- function Assert-ControlSecurity([string]$candidate) {
161
- $acl = [IO.Directory]::GetAccessControl($candidate)
162
- if (-not $acl.AreAccessRulesProtected -or $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $hostSid.Value) {
163
- throw 'control directory ACL is not protected and host-owned'
164
- }
165
- $expected = @{}
166
- $expected[$hostSid.Value] = $true
167
- $expected[$systemSid.Value] = $true
168
- $observed = @{}
169
- foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {
170
- if ($rule.IsInherited -or $rule.AccessControlType -ne $allow) { throw 'control directory ACL contains an unexpected rule' }
171
- $sid = $rule.IdentityReference.Value
172
- if (-not $expected.ContainsKey($sid) -or $observed.ContainsKey($sid)) { throw 'control directory ACL contains an unexpected principal' }
173
- if ($rule.FileSystemRights -ne [Security.AccessControl.FileSystemRights]::FullControl -or $rule.InheritanceFlags -ne $inherit -or $rule.PropagationFlags -ne $none) {
174
- throw 'control directory ACL rule shape is invalid'
175
- }
176
- $observed[$sid] = $true
177
- }
178
- foreach ($sid in $expected.Keys) { if (-not $observed.ContainsKey($sid)) { throw 'control directory ACL is missing a required principal' } }
179
- }
180
- function Test-ControlOwnerProcessAlive([uint32]$processId) {
181
- if ($processId -gt [int]::MaxValue) { return $false }
182
- try {
183
- return $null -ne [Diagnostics.Process]::GetProcessById([int]$processId)
184
- } catch [ArgumentException] {
185
- return $false
186
- } catch {
187
- return $true
188
- }
189
- }
190
- function Remove-ProvenStaleControlEntries([string]$candidate) {
191
- $now = [DateTimeOffset]::UtcNow
192
- foreach ($entry in [IO.Directory]::EnumerateFiles($candidate)) {
193
- try {
194
- $item = Get-Item -LiteralPath $entry -Force
195
- } catch {
196
- if ($_.Exception -is [Management.Automation.ItemNotFoundException] -or
197
- $_.Exception -is [IO.FileNotFoundException] -or
198
- $_.Exception -is [IO.DirectoryNotFoundException]) {
199
- # Another setup/owner may retire a converged entry after enumeration.
200
- continue
201
- }
202
- throw
203
- }
204
- if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 -or $item.Length -gt 1048576) { continue }
205
- $warmupMatch = [regex]::Match($item.Name, '^windows-read-warmup-([0-9]+)-[0-9a-fA-F-]{36}\.log$')
206
- if ($warmupMatch.Success) {
207
- $warmupPid = 0L
208
- if ([long]::TryParse($warmupMatch.Groups[1].Value, [ref]$warmupPid) -and
209
- $warmupPid -gt 0 -and
210
- $warmupPid -le [uint32]::MaxValue -and
211
- -not (Test-ControlOwnerProcessAlive ([uint32]$warmupPid))) {
212
- # Protocol-9 alpha builds left an authority-free warmup diagnostic.
213
- # Its dead creator proves no process can append to it.
214
- [IO.File]::Delete($entry)
215
- }
216
- continue
217
- }
218
- $stagingMatch = [regex]::Match($item.Name, '^windows-(resume|started)-([0-9]+)-[0-9a-fA-F-]{36}\.([0-9]+)\.[0-9a-fA-F]{32}\.tmp$')
219
- $denyStagingMatch = [regex]::Match($item.Name, '^windows-deny-[0-9a-fA-F-]{36}\.([0-9]+)\.[0-9a-fA-F]{32}\.tmp$')
220
- if ($stagingMatch.Success -or $denyStagingMatch.Success) {
221
- $stagingPidText = if ($stagingMatch.Success) { $stagingMatch.Groups[3].Value } else { $denyStagingMatch.Groups[1].Value }
222
- $stagingPid = 0L
223
- if ([long]::TryParse($stagingPidText, [ref]$stagingPid) -and
224
- $stagingPid -gt 0 -and
225
- $stagingPid -le [uint32]::MaxValue -and
226
- -not (Test-ControlOwnerProcessAlive ([uint32]$stagingPid)) -and
227
- $item.LastWriteTimeUtc -lt $now.UtcDateTime.AddMinutes(-1)) {
228
- # Atomic publication staging files carry no authority. A dead creator
229
- # plus two launch budgets proves publication can no longer complete.
230
- [IO.File]::Delete($entry)
231
- }
232
- continue
233
- }
234
- $match = [regex]::Match($item.Name, '^windows-(shell|network|resume|started|terminal)-([0-9]+)-[0-9a-fA-F-]{36}\.json$')
235
- if (-not $match.Success) { continue }
236
- $ownerPid = 0L
237
- if (-not [long]::TryParse($match.Groups[2].Value, [ref]$ownerPid) -or $ownerPid -le 0 -or $ownerPid -gt [uint32]::MaxValue) { continue }
238
- if (Test-ControlOwnerProcessAlive ([uint32]$ownerPid)) { continue }
239
- $kind = $match.Groups[1].Value
240
- $retire = $false
241
- if ($kind -eq 'resume' -or $kind -eq 'started') {
242
- # Launch attestations carry no authority and have no consumer after their
243
- # creating Runtime exits.
244
- $retire = $true
245
- } elseif ($kind -eq 'network') {
246
- # A network request is deleted as soon as its broker reads it. A dead
247
- # creator plus two launch budgets proves this file was never admitted.
248
- $retire = $item.LastWriteTimeUtc -lt $now.UtcDateTime.AddMinutes(-1)
249
- } else {
250
- try { $record = ([IO.File]::ReadAllText($entry) | ConvertFrom-Json) } catch { continue }
251
- if ($kind -eq 'shell') {
252
- $deadline = 0L
253
- $retire = [long]::TryParse([string]$record.operationDeadlineUnixMs, [ref]$deadline) -and $deadline -lt $now.ToUnixTimeMilliseconds()
254
- } else {
255
- # A terminal record is disposable only after native Job drainage was
256
- # durably observed. Unknown or partial records remain fail-closed.
257
- $retire = $record.jobDrained -eq $true
258
- }
259
- }
260
- if ($retire) { [IO.File]::Delete($entry) }
261
- }
262
- }
263
- $cacheRoot = [IO.Path]::GetFullPath([string]$payload.cacheRoot)
264
- $controlRoot = [IO.Path]::GetFullPath([string]$payload.controlRoot)
265
- $action = [string]$payload.action
266
- if ([IO.Path]::GetDirectoryName($controlRoot) -ne $cacheRoot) { throw 'control directory escaped native cache root' }
267
- if (-not (Test-Path -LiteralPath $cacheRoot -PathType Container)) { throw 'protected native cache root is unavailable' }
268
- Assert-NoReparse $cacheRoot
269
- if ($action -eq 'verify') {
270
- if (-not (Test-Path -LiteralPath $controlRoot -PathType Container)) { throw 'protected native shell control state is not initialized; run kodax sandbox setup' }
271
- Assert-NoReparse $controlRoot
272
- } elseif ($action -eq 'ensure') {
273
- if (Test-Path -LiteralPath $controlRoot) {
274
- Assert-NoReparse $controlRoot
275
- } else {
276
- [void][IO.Directory]::CreateDirectory($controlRoot, (New-ControlSecurity))
277
- Assert-NoReparse $controlRoot
278
- }
279
- } elseif ($action -eq 'repair') {
280
- if (Test-Path -LiteralPath $controlRoot) {
281
- Assert-NoReparse $controlRoot
282
- $existing = [IO.Directory]::GetAccessControl($controlRoot)
283
- if ($existing.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $hostSid.Value) { throw 'refusing to repair native shell control state not owned by the host' }
284
- Remove-ProvenStaleControlEntries $controlRoot
285
- $entries = [IO.Directory]::EnumerateFileSystemEntries($controlRoot).GetEnumerator()
286
- try { $notEmpty = $entries.MoveNext() } finally { $entries.Dispose() }
287
- if ($notEmpty) { throw 'refusing to repair non-empty native shell control state; close KodaX and remove the directory manually' }
288
- [IO.Directory]::SetAccessControl($controlRoot, (New-ControlSecurity))
289
- } else {
290
- [void][IO.Directory]::CreateDirectory($controlRoot, (New-ControlSecurity))
291
- }
292
- Assert-NoReparse $controlRoot
293
- } else {
294
- throw 'invalid native shell control state action'
295
- }
296
- Assert-ControlSecurity $controlRoot
297
- [Console]::Out.Write($controlRoot)
298
- `;function T(e){if(process.platform!=="win32")throw new Error("KodaX Windows native shell control state is unavailable on this platform.");let t=w(),r=te(),n=i.join(process.env.SystemRoot??String.raw`C:\Windows`,"System32","WindowsPowerShell","v1.0","powershell.exe"),o=O(n,["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(ue,"utf16le").toString("base64")],{input:JSON.stringify({action:e,cacheRoot:t,controlRoot:r}),encoding:"utf8",env:process.env,shell:!1,windowsHide:!0,timeout:3e4,maxBuffer:1024*1024});if(o.error!==void 0||o.status!==0){let u=o.error?.message??(o.stderr.trim()||`exit ${String(o.status)}`);throw new Error(`Cannot ${e} protected KodaX native shell control state: ${u}`)}if(o.stdout.trim().toLowerCase()!==r.toLowerCase()&&!_(o.stdout.trim(),r))throw new Error("Native shell control verifier returned an unexpected path.");let s=c.realpathSync.native(t),d=c.realpathSync.native(r);if(!h(s,d))throw new Error("Native shell control state escaped its physical cache root.");return d}a(T,"runWindowsSandboxControlDirectoryAction");function xe(){return T("verify")}a(xe,"verifyWindowsSandboxControlDirectory");function Ee(){return T("ensure")}a(Ee,"ensureWindowsSandboxControlDirectory");function be(){return T("repair")}a(be,"repairWindowsSandboxControlDirectory");function fe(e){if(e.sandboxReadSid!==void 0&&!/^S-\d+(?:-\d+)+$/i.test(e.sandboxReadSid))throw new Error("Native artifact sandbox-read SID is invalid.");let t=w(),r=i.dirname(t),n=N(e.kind,e.entry.sha256,e.sandboxReadSid,e.localUsersReadExecute===!0),o=i.join(process.env.SystemRoot??String.raw`C:\Windows`,"System32","WindowsPowerShell","v1.0","powershell.exe"),s=O(o,["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(le,"utf16le").toString("base64")],{input:JSON.stringify({cacheRoot:t,anchor:r,destinationDirectory:n,file:e.entry.file,sha256:e.entry.sha256,bytes:e.bytes.toString("base64"),sandboxReadSid:e.sandboxReadSid??"",localUsersReadExecute:e.localUsersReadExecute===!0,allowCreate:e.allowCreate!==!1}),encoding:"utf8",env:process.env,shell:!1,windowsHide:!0,timeout:3e4,maxBuffer:1024*1024});if(s.error!==void 0||s.status!==0){let y=s.error?.message??(s.stderr.trim()||`exit ${String(s.status)}`);throw new Error(`Cannot provision protected KodaX native artifact: ${y}`)}let d=s.stdout.trim(),u=i.join(n,e.entry.file);if(d.toLowerCase()!==u.toLowerCase()&&!_(d,u))throw new Error("Native artifact provisioner returned an unexpected path.");m(d,e.entry.sha256);let l=c.realpathSync.native(t),f=c.realpathSync.native(d);if(!h(l,f))throw new Error("Protected native artifact escaped its physical cache root.");return f}a(fe,"provisionProtectedArtifact");function B(e){let t={kind:e.kind,entry:e.entry,...e.sandboxReadSid===void 0?{}:{sandboxReadSid:e.sandboxReadSid},...e.localUsersReadExecute===void 0?{}:{localUsersReadExecute:e.localUsersReadExecute}},r=i.join(N(e.kind,e.entry.sha256,e.sandboxReadSid,e.localUsersReadExecute===!0),e.entry.file);try{return V(r,e.entry.sha256)}catch(n){let o=n instanceof Error&&"code"in n?Reflect.get(n,"code"):void 0;if(!e.provision||o!=="ENOENT"&&o!=="ENOTDIR")throw n;return fe({...t,bytes:e.bytes,allowCreate:!0})}}a(B,"verifyOrProvisionProtectedArtifact");function H(e){let t=i.join(N(e.kind,e.entry.sha256,e.sandboxReadSid,e.localUsersReadExecute===!0),e.entry.file);try{return V(t,e.entry.sha256)}catch(r){let n=r instanceof Error&&"code"in r?Reflect.get(r,"code"):void 0;if(n==="ENOENT"||n==="ENOTDIR")return;throw r}}a(H,"resolveExistingProtectedArtifact");function Ce(e,t,r,n={}){if(process.platform!=="win32")throw new Error("The protected ASRT Windows runner is unavailable on this platform.");K(n.untrustedWriteRoots??[]);let o=x(),s=o===void 0?i.resolve(t):E(t),d=i.dirname(s),u=o===void 0?D(e).map(f=>({manifestPath:i.join(f,"manifest.json"),manifestText:void 0,developmentTrustRoots:[f,d]})):[{manifestPath:"<embedded native manifest>",manifestText:o,developmentTrustRoots:[]}],l=[];for(let f of u)try{for(let S of f.developmentTrustRoots)g(S,n.untrustedWriteRoots??[]);let y=f.manifestText!==void 0,p=Z(f.manifestText??j(f.manifestPath,!0).toString("utf8"));if(p.asrtRunner.version!==r)throw new Error(`asrtRunner version ${p.asrtRunner.version} does not match ${r}`);if(y){let S=H({kind:"asrtRunner",entry:p.asrtRunner,localUsersReadExecute:!0});if(S!==void 0)return{path:S,sha256:p.asrtRunner.sha256,developmentTrustRoots:[]}}let P=U(s,p.asrtRunner.sha256,!y);return{...{path:B({kind:"asrtRunner",entry:p.asrtRunner,bytes:P,provision:n.provision!==!1,localUsersReadExecute:!0}),sha256:p.asrtRunner.sha256},developmentTrustRoots:f.developmentTrustRoots}}catch(y){l.push(`${f.manifestPath}: ${y instanceof Error?y.message:String(y)}`)}throw new Error(`A trusted ASRT Windows runner is unavailable. ${l.join(" | ")}`)}a(Ce,"resolveWindowsAsrtRunnerArtifact");function Ne(e,t){for(let r of e)g(r,t)}a(Ne,"assertWindowsAsrtRunnerTrustOutsideWriteRoots");function ye(e,t,r,n={}){if(process.platform!=="win32")throw new Error("KodaX Windows native artifacts are unavailable on this platform.");K(n.untrustedWriteRoots??[]);let o=x(),s=[];for(let d of D(e,o!==void 0)){let u=i.join(d,"manifest.json");try{g(d,o===void 0?n.developmentWriteRoots??n.untrustedWriteRoots??[]:n.untrustedWriteRoots??[]);let{manifest:l,entry:f}=ee(o??c.readFileSync(u,"utf8"),t);if(f.protocol!==r)throw new Error(`${t} protocol ${f.protocol} does not match ${r}`);if(o!==void 0){let A=H({kind:t,entry:f,...n.sandboxReadSid===void 0?{}:{sandboxReadSid:n.sandboxReadSid}});if(A!==void 0)return{path:A,entry:f,manifest:l,developmentTrustRoots:[]}}let y=i.join(d,f.file),p=m(y,f.sha256);return{path:B({kind:t,entry:f,bytes:p,provision:n.provision!==!1,...n.sandboxReadSid===void 0?{}:{sandboxReadSid:n.sandboxReadSid}}),entry:f,manifest:l,developmentTrustRoots:o===void 0?[d]:[]}}catch(l){s.push(`${u}: ${l instanceof Error?l.message:String(l)}`)}}throw new Error(`A compatible KodaX ${t} native artifact is unavailable. ${s.join(" | ")}`)}a(ye,"resolveWindowsNativeArtifact");export{V as a,w as b,te as c,Ae as d,K as e,ne as f,oe as g,ve as h,ce as i,Re as j,xe as k,Ee as l,be as m,Ce as n,Ne as o,ye as p};