@nativestudio/cli 0.0.0-stage → 0.3.0-rc.1

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 (206) hide show
  1. package/COMPATIBILITY.json +20 -0
  2. package/LICENSE +21 -0
  3. package/README.md +77 -2
  4. package/components/runtime.json +6 -0
  5. package/components/runtime.tgz +0 -0
  6. package/dist/BUNDLED_DEPENDENCIES.json +1 -0
  7. package/dist/_chunks/chunk-25EDDZQA.js +1 -0
  8. package/dist/_chunks/chunk-2UYKJ6YN.js +1 -0
  9. package/dist/_chunks/chunk-6NVIN2NI.js +1 -0
  10. package/dist/_chunks/chunk-E57YVMQ4.js +1 -0
  11. package/dist/_chunks/chunk-EAZKDCLD.js +1 -0
  12. package/dist/_chunks/chunk-G42IS5JF.js +1 -0
  13. package/dist/_chunks/chunk-GIEYSDCG.js +1 -0
  14. package/dist/_chunks/chunk-GJ7BZJLW.js +1 -0
  15. package/dist/_chunks/chunk-HLKERZIE.js +1 -0
  16. package/dist/_chunks/chunk-JFC6ZIGA.js +1 -0
  17. package/dist/_chunks/chunk-MSOMVWKN.js +1 -0
  18. package/dist/_chunks/chunk-PUNG4ND7.js +1 -0
  19. package/dist/_chunks/chunk-QC7RLTGU.js +1 -0
  20. package/dist/_chunks/chunk-RUMDDTON.js +1 -0
  21. package/dist/_chunks/chunk-U2UKGYGF.js +1 -0
  22. package/dist/_chunks/chunk-VDNNFVTZ.js +3 -0
  23. package/dist/_chunks/chunk-VPYAXWXY.js +1 -0
  24. package/dist/_chunks/files-TBJVDQWU.js +1 -0
  25. package/dist/_chunks/local-main-SOERK22D.js +1 -0
  26. package/dist/_chunks/local-mcp-JLPXXIDW.js +1 -0
  27. package/dist/_chunks/main-4SNF5EKE.js +2 -0
  28. package/dist/_chunks/mcp-EIMXNRH3.js +1 -0
  29. package/dist/_chunks/oauth-257CEUQH.js +1 -0
  30. package/dist/_chunks/project-connect-6MH2QG6G.js +1 -0
  31. package/dist/_chunks/src-7F6ZEU3U.js +1 -0
  32. package/dist/_chunks/stdio-main-JEADWO7U.js +1 -0
  33. package/dist/_types/cli/local/desktop-channel.d.ts +18 -0
  34. package/dist/_types/cli/local/desktop-contract.d.ts +208 -0
  35. package/dist/_types/cli/local/desktop-node.d.ts +1 -0
  36. package/dist/_types/cli/local/desktop-owner.d.ts +32 -0
  37. package/dist/_types/cli/local/ledger.d.ts +309 -0
  38. package/dist/_types/cli/local/manager.d.ts +592 -0
  39. package/dist/_types/cli/local/mcp-tools.d.ts +419 -0
  40. package/dist/_types/cli/local/releases.d.ts +100 -0
  41. package/dist/_types/cli/local-management.d.ts +11 -0
  42. package/dist/_types/cli/local-navigation.d.ts +3 -0
  43. package/dist/_types/contracts/accepted-shot.d.ts +27 -0
  44. package/dist/_types/contracts/accepted-visual-source.d.ts +120 -0
  45. package/dist/_types/contracts/agent-execution-lifecycle.d.ts +749 -0
  46. package/dist/_types/contracts/agent-execution-oauth.d.ts +71 -0
  47. package/dist/_types/contracts/agent-execution-registration.d.ts +240 -0
  48. package/dist/_types/contracts/agent-execution-selection.d.ts +107 -0
  49. package/dist/_types/contracts/agent-host-execution.d.ts +706 -0
  50. package/dist/_types/contracts/agent-host-generic-transport.d.ts +12 -0
  51. package/dist/_types/contracts/agent-host.d.ts +226 -0
  52. package/dist/_types/contracts/artifact-discovery.d.ts +170 -0
  53. package/dist/_types/contracts/artifact.d.ts +188 -0
  54. package/dist/_types/contracts/audio.d.ts +331 -0
  55. package/dist/_types/contracts/brief.d.ts +178 -0
  56. package/dist/_types/contracts/caption-render.d.ts +20 -0
  57. package/dist/_types/contracts/caption-transcript.d.ts +102 -0
  58. package/dist/_types/contracts/captions.d.ts +420 -0
  59. package/dist/_types/contracts/clip-framing.d.ts +14 -0
  60. package/dist/_types/contracts/clip-transition.d.ts +6 -0
  61. package/dist/_types/contracts/composition-authoring-guide.d.ts +160 -0
  62. package/dist/_types/contracts/composition-authoring.d.ts +744 -0
  63. package/dist/_types/contracts/composition-finding-locality.d.ts +24 -0
  64. package/dist/_types/contracts/composition-frame-render.d.ts +226 -0
  65. package/dist/_types/contracts/composition-making.d.ts +390 -0
  66. package/dist/_types/contracts/composition-observation.d.ts +239 -0
  67. package/dist/_types/contracts/composition-render-base.d.ts +292 -0
  68. package/dist/_types/contracts/composition-render-observation.d.ts +278 -0
  69. package/dist/_types/contracts/composition-render.d.ts +406 -0
  70. package/dist/_types/contracts/composition-repair.d.ts +451 -0
  71. package/dist/_types/contracts/composition-source-review.d.ts +1042 -0
  72. package/dist/_types/contracts/consistency-profile.d.ts +845 -0
  73. package/dist/_types/contracts/continuity-evaluation.d.ts +48 -0
  74. package/dist/_types/contracts/delivery-completion.d.ts +210 -0
  75. package/dist/_types/contracts/delivery-manifest.d.ts +11776 -0
  76. package/dist/_types/contracts/delivery-operations.d.ts +5009 -0
  77. package/dist/_types/contracts/delivery-output-profile.d.ts +12 -0
  78. package/dist/_types/contracts/delivery-summary.d.ts +220 -0
  79. package/dist/_types/contracts/delivery-validation.d.ts +183 -0
  80. package/dist/_types/contracts/director-proposal.d.ts +1067 -0
  81. package/dist/_types/contracts/editor-intelligence.d.ts +5751 -0
  82. package/dist/_types/contracts/exploration-recommendation.d.ts +11863 -0
  83. package/dist/_types/contracts/external-agent-access.d.ts +95 -0
  84. package/dist/_types/contracts/final-ready.d.ts +301 -0
  85. package/dist/_types/contracts/final-render-profile.d.ts +59 -0
  86. package/dist/_types/contracts/final-render.d.ts +8181 -0
  87. package/dist/_types/contracts/foundation.d.ts +1 -0
  88. package/dist/_types/contracts/generation-contract.d.ts +268 -0
  89. package/dist/_types/contracts/generation-cost.d.ts +70 -0
  90. package/dist/_types/contracts/health.d.ts +6 -0
  91. package/dist/_types/contracts/human-identity.d.ts +149 -0
  92. package/dist/_types/contracts/hyperframe-profile.d.ts +5 -0
  93. package/dist/_types/contracts/ids.d.ts +41 -0
  94. package/dist/_types/contracts/index.d.ts +122 -0
  95. package/dist/_types/contracts/interface/common.d.ts +56 -0
  96. package/dist/_types/contracts/interface/execution-output.d.ts +99 -0
  97. package/dist/_types/contracts/interface/index.d.ts +7 -0
  98. package/dist/_types/contracts/interface/media-output.d.ts +62 -0
  99. package/dist/_types/contracts/interface/operation.d.ts +61 -0
  100. package/dist/_types/contracts/interface/output.d.ts +15 -0
  101. package/dist/_types/contracts/interface/production-snapshot.d.ts +832 -0
  102. package/dist/_types/contracts/interface/query.d.ts +315 -0
  103. package/dist/_types/contracts/keyframe-generation.d.ts +349 -0
  104. package/dist/_types/contracts/keyframe-reference.d.ts +31 -0
  105. package/dist/_types/contracts/keyframe-review.d.ts +753 -0
  106. package/dist/_types/contracts/lifecycle-event-projections.d.ts +191 -0
  107. package/dist/_types/contracts/lifecycle-events.d.ts +156 -0
  108. package/dist/_types/contracts/listening-evidence.d.ts +37 -0
  109. package/dist/_types/contracts/local-execution/agent-review.d.ts +560 -0
  110. package/dist/_types/contracts/local-execution/canonical.d.ts +2 -0
  111. package/dist/_types/contracts/local-execution/common.d.ts +48 -0
  112. package/dist/_types/contracts/local-execution/completion.d.ts +128 -0
  113. package/dist/_types/contracts/local-execution/device.d.ts +134 -0
  114. package/dist/_types/contracts/local-execution/index.d.ts +11 -0
  115. package/dist/_types/contracts/local-execution/ipc.d.ts +1202 -0
  116. package/dist/_types/contracts/local-execution/lifecycle.d.ts +319 -0
  117. package/dist/_types/contracts/local-execution/local-navigation.d.ts +710 -0
  118. package/dist/_types/contracts/local-execution/preview.d.ts +3663 -0
  119. package/dist/_types/contracts/local-execution/tool-selection.d.ts +15 -0
  120. package/dist/_types/contracts/local-execution/work.d.ts +3441 -0
  121. package/dist/_types/contracts/matrix-parameter-rule.d.ts +23 -0
  122. package/dist/_types/contracts/media-export.d.ts +23 -0
  123. package/dist/_types/contracts/media-observation.d.ts +1159 -0
  124. package/dist/_types/contracts/model-capability-matrix.d.ts +118 -0
  125. package/dist/_types/contracts/native-tool-authority-failure.d.ts +38 -0
  126. package/dist/_types/contracts/native-tool-authority.d.ts +110 -0
  127. package/dist/_types/contracts/native-tool-execution.d.ts +287 -0
  128. package/dist/_types/contracts/native-tool-gateway.d.ts +41 -0
  129. package/dist/_types/contracts/native-video-audio.d.ts +62 -0
  130. package/dist/_types/contracts/navigation-context.d.ts +253 -0
  131. package/dist/_types/contracts/navigation-groups.d.ts +51 -0
  132. package/dist/_types/contracts/navigation.d.ts +238 -0
  133. package/dist/_types/contracts/observation-profile.d.ts +99 -0
  134. package/dist/_types/contracts/planning-input.d.ts +177 -0
  135. package/dist/_types/contracts/principal.d.ts +26 -0
  136. package/dist/_types/contracts/production-creation.d.ts +66 -0
  137. package/dist/_types/contracts/production-termination.d.ts +51 -0
  138. package/dist/_types/contracts/production.d.ts +111 -0
  139. package/dist/_types/contracts/programmatic-composition.d.ts +762 -0
  140. package/dist/_types/contracts/programmatic-exploration.d.ts +7459 -0
  141. package/dist/_types/contracts/programmatic-video-review.d.ts +894 -0
  142. package/dist/_types/contracts/project-library.d.ts +173 -0
  143. package/dist/_types/contracts/project.d.ts +93 -0
  144. package/dist/_types/contracts/provider-catalog.d.ts +421 -0
  145. package/dist/_types/contracts/provider-models.d.ts +3380 -0
  146. package/dist/_types/contracts/provider.d.ts +142 -0
  147. package/dist/_types/contracts/reference-preview.d.ts +36 -0
  148. package/dist/_types/contracts/repair-lifecycle.d.ts +2896 -0
  149. package/dist/_types/contracts/repair-plan.d.ts +728 -0
  150. package/dist/_types/contracts/repair-strategy.d.ts +5751 -0
  151. package/dist/_types/contracts/review-intelligence-evidence.d.ts +136 -0
  152. package/dist/_types/contracts/review-intelligence-final-output.d.ts +8705 -0
  153. package/dist/_types/contracts/review-intelligence.d.ts +11543 -0
  154. package/dist/_types/contracts/review1-repair-source.d.ts +452 -0
  155. package/dist/_types/contracts/review1-repair-strategy.d.ts +491 -0
  156. package/dist/_types/contracts/review1-repair.d.ts +36 -0
  157. package/dist/_types/contracts/rough-cut-manifest.d.ts +347 -0
  158. package/dist/_types/contracts/rough-cut-profile.d.ts +37 -0
  159. package/dist/_types/contracts/rough-cut-review.d.ts +12819 -0
  160. package/dist/_types/contracts/rough-cut.d.ts +5862 -0
  161. package/dist/_types/contracts/scene-shot-plan.d.ts +882 -0
  162. package/dist/_types/contracts/sdk-discovery.d.ts +66 -0
  163. package/dist/_types/contracts/shot-direction.d.ts +113 -0
  164. package/dist/_types/contracts/shot-preparation-basis.d.ts +356 -0
  165. package/dist/_types/contracts/shot-preparation.d.ts +2285 -0
  166. package/dist/_types/contracts/shot-sound-instruction.d.ts +58 -0
  167. package/dist/_types/contracts/sound-making-plan.d.ts +1585 -0
  168. package/dist/_types/contracts/source-sound-policy.d.ts +10 -0
  169. package/dist/_types/contracts/source-workspace.d.ts +62 -0
  170. package/dist/_types/contracts/speech.d.ts +424 -0
  171. package/dist/_types/contracts/story.d.ts +98 -0
  172. package/dist/_types/contracts/temporal-evidence-operation.d.ts +379 -0
  173. package/dist/_types/contracts/temporal-evidence-reference.d.ts +18 -0
  174. package/dist/_types/contracts/temporal-evidence.d.ts +248 -0
  175. package/dist/_types/contracts/tenant.d.ts +7 -0
  176. package/dist/_types/contracts/timeline-audio.d.ts +97 -0
  177. package/dist/_types/contracts/timeline-graphics.d.ts +80 -0
  178. package/dist/_types/contracts/timeline-manifest.d.ts +702 -0
  179. package/dist/_types/contracts/timeline-source-sound.d.ts +352 -0
  180. package/dist/_types/contracts/timeline-v2.d.ts +1263 -0
  181. package/dist/_types/contracts/timeline-version-reader.d.ts +2945 -0
  182. package/dist/_types/contracts/timeline-visual-layers.d.ts +1245 -0
  183. package/dist/_types/contracts/timeline.d.ts +4942 -0
  184. package/dist/_types/contracts/transcription.d.ts +80 -0
  185. package/dist/_types/contracts/video-generation.d.ts +643 -0
  186. package/dist/_types/contracts/video-review.d.ts +1871 -0
  187. package/dist/_types/contracts/visual-exploration.d.ts +1586 -0
  188. package/dist/_types/contracts/visual-layer-render.d.ts +2777 -0
  189. package/dist/_types/contracts/visual-layer.d.ts +112 -0
  190. package/dist/_types/contracts/visual-sequence.d.ts +121 -0
  191. package/dist/_types/contracts/writer-proposal.d.ts +268 -0
  192. package/dist/_types/sdk/errors.d.ts +9 -0
  193. package/dist/_types/sdk/local-runtime/device-client.d.ts +77 -0
  194. package/dist/_types/sdk/local-runtime-client.d.ts +932 -0
  195. package/dist/entry.js +2 -0
  196. package/dist/local-management.d.ts +1 -0
  197. package/dist/local-management.js +1 -0
  198. package/dist/local-navigation.d.ts +1 -0
  199. package/dist/local-navigation.js +1 -0
  200. package/dist/native/Bootstrap.ps1 +90 -0
  201. package/dist/native/JobNative.cs +127 -0
  202. package/dist/native/JobRunner.cs +360 -0
  203. package/dist/native/NativeMain.cs +146 -0
  204. package/dist/native/PipeBridge.cs +260 -0
  205. package/dist/native/PrivateAccess.cs +152 -0
  206. package/package.json +33 -3
package/dist/entry.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ if(process.argv[2]==="local"){if(process.argv[3]==="mcp"){const{runLocalMcp}=await import("./_chunks/local-mcp-JLPXXIDW.js");process.exitCode=await runLocalMcp(process.argv.slice(4))}else{const{runLocalCli}=await import("./_chunks/local-main-SOERK22D.js");const result=await runLocalCli(process.argv.slice(3));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}}else if(process.argv[2]==="mcp"){const{runMcpStdio}=await import("./_chunks/stdio-main-JEADWO7U.js");process.exitCode=await runMcpStdio(process.argv.slice(3),process.env)}else{const{runRemoteCli}=await import("./_chunks/main-4SNF5EKE.js");const result=await runRemoteCli(process.argv.slice(2));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}
@@ -0,0 +1 @@
1
+ export * from "./_types/cli/local-management.js";
@@ -0,0 +1 @@
1
+ import{LocalInstallationManager,socketAbsent}from"./_chunks/chunk-U2UKGYGF.js";import{LocalRuntimeDescriptorSchema,canonicalLocalJson,endpoint}from"./_chunks/chunk-EAZKDCLD.js";import"./_chunks/chunk-HLKERZIE.js";import"./_chunks/chunk-VPYAXWXY.js";import{LocalClientError,directory,fail,read,sha256,write}from"./_chunks/chunk-GIEYSDCG.js";import"./_chunks/chunk-6NVIN2NI.js";import{z}from"zod";var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z.string().url().max(4096),publicKey:z.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z.discriminatedUnion("operation",[z.strictObject({operation:z.enum(["status","start","stop","check","configuration","recovery"])}),z.strictObject({operation:z.enum(["prepare","reject"]),version}),z.strictObject({operation:z.literal("configure"),channelFingerprint:fingerprint}),z.strictObject({operation:z.enum(["apply","recover"]),planId:z.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z.string().regex(/^[A-Z_]{1,64}$/)});var DesktopUpdateCheckSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z.array(z.strictObject({version,rejected:z.boolean()})).max(128),notifications:z.boolean()});var DesktopOwnerPlanSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z.strictObject({kind:z.enum(["APPLY","RECOVER"]),planId:z.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z.iso.datetime(),phase:z.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z.strictObject({protocol:z.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z.boolean(),source:z.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};async function desktopRuntimeStatus(manager){const status=await manager.status();const stopped=!status.running&&status.activeVersion?await socketAbsent((await manager.configuration()).stateDirectory):false;return DesktopRuntimeStatusSchema.parse({protocol:"NVS_DESKTOP_RUNTIME_STATUS_V1",state:status.running?"RUNNING":stopped?"STOPPED":status.activeVersion?"UNAVAILABLE":"INSTALL_REQUIRED",activeVersion:status.activeVersion,phase:status.phase})}import{createPublicKey}from"node:crypto";import{join}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED"))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;const stateDirectory=join(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:true})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop")await manager.stop();result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"prepare":{const plan=await manager.prepare(request.version);result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"recovery":{const current=(await manager.ledger.current()).value,transition=current.transition;let plan=null;if(transition){const original=await manager.plan(transition.planId);if(original.fingerprint!==transition.fingerprint)fail("PLAN_CHANGED");plan={kind:"RECOVER",planId:original.planId,fingerprint:original.fingerprint,version:original.release.descriptor.version,previousVersion:transition.previous?.descriptor.version??null,expiresAt:original.expiresAt,phase:transition.phase}}result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan};break}case"apply":case"recover":if(request.operation==="apply")await manager.apply(request.planId,request.fingerprint);else await manager.reconcile(request.planId,request.fingerprint);result=await desktopRuntimeStatus(manager);break;case"reject":await manager.reject(request.version);result=await desktopRuntimeStatus(manager);break}return desktopOwnerResponses[request.operation].parse(result)}import{lstat,readFile,chmod}from"node:fs/promises";import{join as join2,isAbsolute,dirname}from"node:path";async function verifiedSource(source,expected,limit){if(!isAbsolute(source)||!/^[a-f0-9]{64}$/.test(expected))fail("DESKTOP_DISTRIBUTION_INVALID");const stat=await lstat(source);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>limit)fail("DESKTOP_DISTRIBUTION_INVALID");const bytes=await readFile(source);if(bytes.length>limit||sha256(bytes)!==expected)fail("DESKTOP_DISTRIBUTION_INVALID");return bytes}async function retain(target,bytes,expected,limit,mode){try{if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}catch(error){if(error.code!=="ENOENT")throw error;try{await write(target,bytes,true)}catch(error2){if(error2.code!=="EEXIST")throw error2}if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}await chmod(target,mode)}async function materializeDesktopNode(home,source,expected,licenseDigest){const bytes=await verifiedSource(source,expected,160*1024*1024);const license=licenseDigest?await verifiedSource(join2(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join2(await directory(home),"nodes",expected)),target=join2(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join2(base,"LICENSE.txt"),license,licenseDigest,2*1024*1024,256);await retain(target,bytes,expected,160*1024*1024,320);return target}async function runLocalManagement(home,operation){if(!["status","start","stop"].includes(operation))throw Error("INVALID_INPUT");const manager=await LocalInstallationManager.open(home);if(operation==="start")await manager.start();if(operation==="stop")await manager.stop();return desktopRuntimeStatus(manager)}export{DesktopOwnerRequestSchema,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,runDesktopOwnerRequest,runLocalManagement};
@@ -0,0 +1 @@
1
+ export * from "./_types/cli/local-navigation.js";
@@ -0,0 +1 @@
1
+ import{LocalMcpTools}from"./_chunks/chunk-QC7RLTGU.js";import"./_chunks/chunk-EAZKDCLD.js";import"./_chunks/chunk-HLKERZIE.js";import"./_chunks/chunk-VPYAXWXY.js";import"./_chunks/chunk-GIEYSDCG.js";import"./_chunks/chunk-6NVIN2NI.js";export{LocalMcpTools};
@@ -0,0 +1,90 @@
1
+ $ErrorActionPreference = 'Stop'
2
+ [Console]::InputEncoding = New-Object Text.UTF8Encoding($false)
3
+ [Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
4
+ try {
5
+ $raw = [Console]::In.ReadToEnd()
6
+ if ($raw.Length -gt 32768) { throw 'INPUT_LIMIT' }
7
+ $request = $raw | ConvertFrom-Json
8
+ $names = @('Bootstrap.ps1','NativeMain.cs','PrivateAccess.cs','PipeBridge.cs','JobNative.cs','JobRunner.cs')
9
+ $directory = [IO.Path]::GetFullPath($request.directory)
10
+ $hash = [Security.Cryptography.SHA256]::Create()
11
+ foreach ($name in $names) {
12
+ $file = Join-Path $directory $name
13
+ if (([IO.File]::GetAttributes($file) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'REPARSE' }
14
+ $prefix = [Text.Encoding]::UTF8.GetBytes($name + "`n")
15
+ [void]$hash.TransformBlock($prefix,0,$prefix.Length,$prefix,0)
16
+ $bytes = [IO.File]::ReadAllBytes($file)
17
+ if ($bytes.Length -gt 262144) { throw 'SOURCE_LIMIT' }
18
+ [void]$hash.TransformBlock($bytes,0,$bytes.Length,$bytes,0)
19
+ }
20
+ [void]$hash.TransformFinalBlock([byte[]]@(),0,0)
21
+ $digest = ([BitConverter]::ToString($hash.Hash)).Replace('-','').ToLowerInvariant()
22
+ if ($digest -ne $request.sourceDigest) { throw 'SOURCE_CHANGED' }
23
+ $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User
24
+ function Check-Private([string]$path) {
25
+ $item = Get-Item -LiteralPath $path -Force
26
+ if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'REPARSE' }
27
+ $acl = $item.GetAccessControl()
28
+ if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'OWNER' }
29
+ foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
30
+ if ($rule.AccessControlType -eq [Security.AccessControl.AccessControlType]::Allow -and
31
+ $rule.IdentityReference.Value -notin @($sid.Value,'S-1-5-18','S-1-5-32-544')) { throw 'ACL' }
32
+ }
33
+ }
34
+ function Private-Directory([string]$path) {
35
+ if ([IO.Directory]::Exists($path)) { Check-Private $path; return }
36
+ $acl = New-Object Security.AccessControl.DirectorySecurity
37
+ $acl.SetOwner($sid)
38
+ $acl.SetAccessRuleProtection($true,$false)
39
+ $rule = New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow')
40
+ $acl.AddAccessRule($rule)
41
+ [void][IO.Directory]::CreateDirectory($path,$acl)
42
+ Check-Private $path
43
+ }
44
+ $base = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'NativeStudio-platform'
45
+ Private-Directory $base
46
+ $cache = Join-Path $base $digest
47
+ Private-Directory $cache
48
+ $mutex = New-Object Threading.Mutex($false,('Local\NVS-compile-' + $sid.Value + '-' + $digest))
49
+ $locked = $false
50
+ try {
51
+ try { $locked = $mutex.WaitOne(10000) } catch [Threading.AbandonedMutexException] { $locked = $true }
52
+ if (-not $locked) { throw 'BUSY' }
53
+ $record = Join-Path $cache 'helper.json'
54
+ if ([IO.File]::Exists($record)) {
55
+ Check-Private $record
56
+ $value = [IO.File]::ReadAllText($record) | ConvertFrom-Json
57
+ if ($value.sourceDigest -ne $digest -or $value.file -notmatch '^helper-[0-9a-f-]{36}\.exe$') { throw 'CACHE' }
58
+ $executable = Join-Path $cache $value.file
59
+ Check-Private $executable
60
+ $actual = (Get-FileHash -LiteralPath $executable -Algorithm SHA256).Hash.ToLowerInvariant()
61
+ if ($actual -ne $value.sha256) { throw 'CACHE_CHANGED' }
62
+ } else {
63
+ $file = 'helper-' + [Guid]::NewGuid().ToString() + '.exe'
64
+ $executable = Join-Path $cache $file
65
+ $sources = @($names | Where-Object { $_.EndsWith('.cs') } | ForEach-Object { Join-Path $directory $_ })
66
+ $compiler = New-Object CodeDom.Compiler.CompilerParameters
67
+ $compiler.GenerateExecutable = $true
68
+ $compiler.OutputAssembly = $executable
69
+ $compiler.CompilerOptions = '/platform:x64 /optimize+ /langversion:5'
70
+ $compiler.ReferencedAssemblies.AddRange(@('System.dll','System.Core.dll','System.Web.dll','System.Web.Extensions.dll','System.Security.dll'))
71
+ Add-Type -Path $sources -CompilerParameters $compiler
72
+ Check-Private $executable
73
+ $actual = (Get-FileHash -LiteralPath $executable -Algorithm SHA256).Hash.ToLowerInvariant()
74
+ $value = @{ sourceDigest=$digest; file=$file; sha256=$actual }
75
+ $temporary = Join-Path $cache ([Guid]::NewGuid().ToString() + '.json')
76
+ $bytes = [Text.Encoding]::UTF8.GetBytes(($value | ConvertTo-Json -Compress))
77
+ $stream = New-Object IO.FileStream($temporary,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None)
78
+ try { $stream.Write($bytes,0,$bytes.Length); $stream.Flush($true) } finally { $stream.Dispose() }
79
+ [IO.File]::Move($temporary,$record)
80
+ Check-Private $record
81
+ }
82
+ @{ path=$executable; sha256=$actual; sourceDigest=$digest } | ConvertTo-Json -Compress
83
+ } finally {
84
+ if ($locked) { $mutex.ReleaseMutex() }
85
+ $mutex.Dispose()
86
+ }
87
+ } catch {
88
+ [Console]::Error.WriteLine('WINDOWS_HELPER_UNAVAILABLE')
89
+ exit 1
90
+ }
@@ -0,0 +1,127 @@
1
+ using System;
2
+ using System.Runtime.InteropServices;
3
+ using System.Text;
4
+ using Microsoft.Win32.SafeHandles;
5
+ namespace NativeStudio.Platform
6
+ {
7
+ public static class JobNative
8
+ {
9
+ [StructLayout(LayoutKind.Sequential)]
10
+ public struct SecurityAttributes
11
+ {
12
+ public int size; public IntPtr descriptor; public int inherit;
13
+ }
14
+ [StructLayout(LayoutKind.Sequential)]
15
+ public struct StartupInfo
16
+ {
17
+ public int size; public string reserved, desktop, title;
18
+ public uint x, y, xSize, ySize, xChars, yChars, fill, flags; public ushort show, reservedSize;
19
+ public IntPtr reservedBytes, input, output, error;
20
+ }
21
+ [StructLayout(LayoutKind.Sequential)]
22
+ public struct ProcessInfo
23
+ {
24
+ public IntPtr process, thread; public uint processId, threadId;
25
+ }
26
+ [StructLayout(LayoutKind.Sequential)]
27
+ public struct BasicLimits
28
+ {
29
+ public long processTime, jobTime; public uint flags; public UIntPtr minWorking, maxWorking;
30
+ public uint active; public UIntPtr affinity; public uint priority, scheduling;
31
+ }
32
+ [StructLayout(LayoutKind.Sequential)]
33
+ public struct Counters
34
+ {
35
+ public ulong readOps, writeOps, otherOps, readBytes, writeBytes, otherBytes;
36
+ }
37
+ [StructLayout(LayoutKind.Sequential)]
38
+ public struct ExtendedLimits
39
+ {
40
+ public BasicLimits basic; public Counters io; public UIntPtr processMemory, jobMemory, peakProcess, peakJob;
41
+ }
42
+ [StructLayout(LayoutKind.Sequential)]
43
+ public struct CpuLimits
44
+ {
45
+ public uint flags, rate;
46
+ }
47
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr CreateJobObject(IntPtr sa, string name);
48
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetInformationJobObject(IntPtr job, int type, IntPtr value, uint size);
49
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool QueryInformationJobObject(IntPtr job, int type, IntPtr value, uint size, out uint length);
50
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
51
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool TerminateJobObject(IntPtr job, uint code);
52
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool TerminateProcess(IntPtr process, uint code);
53
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CreateProcess(string application, StringBuilder command, IntPtr pa, IntPtr ta, bool inherit, uint flags, IntPtr environment, string directory, ref StartupInfo startup, out ProcessInfo info);
54
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool CreatePipe(out IntPtr read, out IntPtr write, ref SecurityAttributes sa, uint size);
55
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetHandleInformation(IntPtr handle, uint mask, uint flags);
56
+ [DllImport("kernel32.dll")] public static extern uint ResumeThread(IntPtr thread);
57
+ [DllImport("kernel32.dll")] public static extern uint WaitForSingleObject(IntPtr handle, uint ms);
58
+ [DllImport("kernel32.dll")] public static extern bool GetExitCodeProcess(IntPtr process, out uint code);
59
+ [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr handle);
60
+ [DllImport("kernel32.dll", EntryPoint = "TerminateJobObject", SetLastError = true)]
61
+ static extern bool TerminateOwnedJob(SafeFileHandle job, uint code);
62
+ public static void Kill(SafeFileHandle job)
63
+ {
64
+ if (job == null)
65
+ return;
66
+ try
67
+ {
68
+ TerminateOwnedJob(job, 1);
69
+ }
70
+ catch (ObjectDisposedException) { }
71
+ }
72
+ public static void Set<T>(IntPtr job, int kind, T data)
73
+ {
74
+ int size = Marshal.SizeOf(typeof(T));
75
+ IntPtr memory = Marshal.AllocHGlobal(size);
76
+ try
77
+ {
78
+ Marshal.StructureToPtr(data, memory, false);
79
+ if (!SetInformationJobObject(job, kind, memory, (uint)size))
80
+ throw new Exception("JOB_LIMIT");
81
+ }
82
+ finally { Marshal.FreeHGlobal(memory); }
83
+ }
84
+ public static IntPtr Job(bool aggregate)
85
+ {
86
+ var job = CreateJobObject(IntPtr.Zero, null);
87
+ if (job == IntPtr.Zero)
88
+ throw new Exception("JOB_CREATE");
89
+ try
90
+ {
91
+ var limits = new ExtendedLimits();
92
+ limits.basic.flags = 0x2000; // KILL_ON_JOB_CLOSE; no breakaway.
93
+ if (aggregate)
94
+ {
95
+ limits.basic.flags |= 0x200 | 8 | 0x20;
96
+ limits.jobMemory = new UIntPtr(4294967296UL);
97
+ limits.basic.active = 64;
98
+ limits.basic.priority = 0x4000;
99
+ }
100
+ Set(job, 9, limits);
101
+ if (aggregate)
102
+ Set(job, 15, new CpuLimits { flags = 5, rate = (uint)Math.Min(10000, Math.Max(1, 20000 / Environment.ProcessorCount)) });
103
+ return job;
104
+ }
105
+ catch { CloseHandle(job); throw; }
106
+ }
107
+ public static uint[] Processes(IntPtr job)
108
+ {
109
+ int size = 8 + 64 * IntPtr.Size;
110
+ IntPtr memory = Marshal.AllocHGlobal(size);
111
+ try
112
+ {
113
+ uint length;
114
+ if (!QueryInformationJobObject(job, 3, memory, (uint)size, out length))
115
+ throw new Exception("JOB_INSPECT");
116
+ int count = Marshal.ReadInt32(memory, 4);
117
+ if (count < 0 || count > 64)
118
+ throw new Exception("JOB_LIMIT");
119
+ var ids = new uint[count];
120
+ for (int i = 0; i < count; i++)
121
+ ids[i] = unchecked((uint)Marshal.ReadIntPtr(memory, 8 + i * IntPtr.Size).ToInt64());
122
+ return ids;
123
+ }
124
+ finally { Marshal.FreeHGlobal(memory); }
125
+ }
126
+ }
127
+ }
@@ -0,0 +1,360 @@
1
+ using System;
2
+ using System.IO;
3
+ using System.Text;
4
+ using System.Linq;
5
+ using System.Collections;
6
+ using System.Collections.Generic;
7
+ using System.Diagnostics;
8
+ using System.Runtime.InteropServices;
9
+ using System.Threading;
10
+ using Microsoft.Win32.SafeHandles;
11
+ namespace NativeStudio.Platform
12
+ {
13
+ public static class JobRunner
14
+ {
15
+ static readonly object Sync = new object();
16
+ static readonly Dictionary<string, IntPtr> Jobs = new Dictionary<string, IntPtr>();
17
+ static readonly HashSet<string> Cancelled = new HashSet<string>();
18
+ static IntPtr aggregate;
19
+ static Process parent;
20
+ static bool closed;
21
+ public static void Parent(int id)
22
+ {
23
+ parent = Process.GetProcessById(id);
24
+ if (parent.Handle == IntPtr.Zero)
25
+ throw new Exception("PARENT");
26
+ }
27
+ public static bool Reserve(string id)
28
+ {
29
+ lock (Sync)
30
+ {
31
+ if (closed || Jobs.Count >= 16 || Jobs.ContainsKey(id))
32
+ return false;
33
+ Jobs.Add(id, IntPtr.Zero);
34
+ return true;
35
+ }
36
+ }
37
+ public static void Release(string id)
38
+ {
39
+ lock (Sync)
40
+ {
41
+ Jobs.Remove(id);
42
+ Cancelled.Remove(id);
43
+ }
44
+ }
45
+ public static void Cancel(string id)
46
+ {
47
+ lock (Sync)
48
+ {
49
+ IntPtr job;
50
+ if (!Jobs.TryGetValue(id, out job))
51
+ return;
52
+ Cancelled.Add(id);
53
+ if (job != IntPtr.Zero)
54
+ JobNative.TerminateJobObject(job, 1); // Handle disposal uses the same lock.
55
+ }
56
+ }
57
+ public static void Close()
58
+ {
59
+ lock (Sync)
60
+ {
61
+ closed = true;
62
+ if (aggregate != IntPtr.Zero)
63
+ {
64
+ JobNative.CloseHandle(aggregate);
65
+ aggregate = IntPtr.Zero;
66
+ }
67
+ }
68
+ }
69
+ static IntPtr Aggregate()
70
+ {
71
+ lock (Sync)
72
+ {
73
+ if (closed)
74
+ throw new Exception("CLOSED");
75
+ if (aggregate == IntPtr.Zero)
76
+ {
77
+ aggregate = JobNative.Job(true);
78
+ var monitor = new Thread(delegate ()
79
+ {
80
+ try
81
+ {
82
+ while (!closed)
83
+ {
84
+ lock (Sync)
85
+ {
86
+ if (closed)
87
+ return;
88
+ long rss = Process.GetCurrentProcess().WorkingSet64;
89
+ if (parent != null)
90
+ {
91
+ if (parent.HasExited)
92
+ {
93
+ Close();
94
+ return;
95
+ }
96
+ parent.Refresh();
97
+ rss += parent.WorkingSet64;
98
+ }
99
+ foreach (uint id in JobNative.Processes(aggregate))
100
+ {
101
+ try
102
+ {
103
+ using (var p = Process.GetProcessById((int)id))
104
+ rss += p.WorkingSet64;
105
+ }
106
+ catch (ArgumentException) { } // A command already exited.
107
+ }
108
+ if (rss > 4294967296L)
109
+ {
110
+ Close();
111
+ return;
112
+ }
113
+ }
114
+ Thread.Sleep(100);
115
+ }
116
+ }
117
+ catch { Close(); }
118
+ });
119
+ monitor.IsBackground = true;
120
+ monitor.Start();
121
+ }
122
+ return aggregate;
123
+ }
124
+ }
125
+ public static string Quote(string value)
126
+ {
127
+ if (value.IndexOf('\0') >= 0)
128
+ throw new Exception("ARGUMENT");
129
+ var b = new StringBuilder("\"");
130
+ int slashes = 0;
131
+ foreach (char c in value)
132
+ {
133
+ if (c == '\\')
134
+ {
135
+ slashes++;
136
+ continue;
137
+ }
138
+ if (c == '\"')
139
+ {
140
+ b.Append('\\', slashes * 2 + 1);
141
+ b.Append(c);
142
+ }
143
+ else
144
+ {
145
+ b.Append('\\', slashes);
146
+ b.Append(c);
147
+ }
148
+ slashes = 0;
149
+ }
150
+ b.Append('\\', slashes * 2);
151
+ b.Append('"');
152
+ return b.ToString();
153
+ }
154
+ static IntPtr EnvironmentBlock(IDictionary<string, object> r)
155
+ {
156
+ var values = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
157
+ values["SystemRoot"] = Environment.GetEnvironmentVariable("SystemRoot");
158
+ object supplied;
159
+ if (r.TryGetValue("environment", out supplied) && supplied != null)
160
+ {
161
+ var env = (IDictionary<string, object>)supplied;
162
+ if (env.Count > 24)
163
+ throw new Exception("ENVIRONMENT");
164
+ foreach (var entry in env)
165
+ {
166
+ string key = entry.Key.ToUpperInvariant(), value = entry.Value as string;
167
+ if (value == null || value.Length > 4096 || value.IndexOf('\0') >= 0 || !System.Text.RegularExpressions.Regex.IsMatch(key, @"^[A-Z][A-Z0-9_]{0,60}$") || key == "NODE_OPTIONS" || key.StartsWith("LD_") || key.StartsWith("DYLD_"))
168
+ throw new Exception("ENVIRONMENT");
169
+ if (key != "SYSTEMROOT")
170
+ values[key] = value;
171
+ }
172
+ }
173
+ return Marshal.StringToHGlobalUni(String.Join("\0", values.Select(v => v.Key + "=" + v.Value).ToArray()) + "\0\0");
174
+ }
175
+ static FileStream Stream(IntPtr handle, FileAccess access)
176
+ {
177
+ return new FileStream(new SafeFileHandle(handle, true), access, 4096, false);
178
+ }
179
+ public static object Execute(string id, IDictionary<string, object> r)
180
+ {
181
+ string binary = PrivateAccess.PathOf(NativeMain.Text(r, "binary"));
182
+ if (!binary.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
183
+ throw new Exception("EXECUTABLE");
184
+ PrivateAccess.Check(binary, "file", false);
185
+ var args = (IList)r["args"];
186
+ if (args.Count > 512)
187
+ throw new Exception("ARGUMENT");
188
+ var command = new StringBuilder(Quote(binary));
189
+ foreach (object arg in args)
190
+ {
191
+ if (!(arg is string))
192
+ throw new Exception("ARGUMENT");
193
+ command.Append(' ').Append(Quote((string)arg));
194
+ }
195
+ if (command.Length > 30000)
196
+ throw new Exception("ARGUMENT_LIMIT");
197
+ string input = r.ContainsKey("input") ? NativeMain.Text(r, "input") : "";
198
+ if (Encoding.UTF8.GetByteCount(input) > 65536)
199
+ throw new Exception("INPUT_LIMIT");
200
+ int maximum = Convert.ToInt32(r["maxOutputBytes"]);
201
+ long expires = Convert.ToInt64(r["expiresAt"]);
202
+ if (maximum < 1 || maximum > 524288 || expires <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
203
+ throw new Exception("LIMIT");
204
+ string cwd = r.ContainsKey("cwd") && r["cwd"] != null ? PrivateAccess.PathOf(NativeMain.Text(r, "cwd")) : null;
205
+ IntPtr job = IntPtr.Zero, environment = IntPtr.Zero, inRead = IntPtr.Zero, inWrite = IntPtr.Zero, outRead = IntPtr.Zero, outWrite = IntPtr.Zero, errRead = IntPtr.Zero, errWrite = IntPtr.Zero;
206
+ SafeFileHandle ownedJob = null;
207
+ var info = new JobNative.ProcessInfo();
208
+ bool assigned = false;
209
+ try
210
+ {
211
+ var root = Aggregate();
212
+ job = JobNative.Job(false);
213
+ ownedJob = new SafeFileHandle(job, true);
214
+ lock (Sync)
215
+ {
216
+ Jobs[id] = job;
217
+ if (Cancelled.Contains(id) || closed)
218
+ throw new Exception("CANCELLED");
219
+ }
220
+ var sa = new JobNative.SecurityAttributes { size = Marshal.SizeOf(typeof(JobNative.SecurityAttributes)), inherit = 1 };
221
+ if (!JobNative.CreatePipe(out inRead, out inWrite, ref sa, 0) || !JobNative.CreatePipe(out outRead, out outWrite, ref sa, 0) || !JobNative.CreatePipe(out errRead, out errWrite, ref sa, 0))
222
+ throw new Exception("PIPE");
223
+ if (!JobNative.SetHandleInformation(inWrite, 1, 0) || !JobNative.SetHandleInformation(outRead, 1, 0) || !JobNative.SetHandleInformation(errRead, 1, 0))
224
+ throw new Exception("HANDLE");
225
+ var startup = new JobNative.StartupInfo { size = Marshal.SizeOf(typeof(JobNative.StartupInfo)), flags = 0x100, input = inRead, output = outWrite, error = errWrite };
226
+ environment = EnvironmentBlock(r);
227
+ if (!JobNative.CreateProcess(binary, command, IntPtr.Zero, IntPtr.Zero, true, 4 | 0x400 | 0x8000000, environment, cwd, ref startup, out info))
228
+ throw new Exception("SPAWN");
229
+ lock (Sync)
230
+ {
231
+ if (closed || Cancelled.Contains(id))
232
+ throw new Exception("CANCELLED");
233
+ if (!JobNative.AssignProcessToJobObject(root, info.process) || !JobNative.AssignProcessToJobObject(job, info.process))
234
+ throw new Exception("JOB_ASSIGN");
235
+ assigned = true;
236
+ }
237
+ JobNative.CloseHandle(inRead);
238
+ inRead = IntPtr.Zero;
239
+ JobNative.CloseHandle(outWrite);
240
+ outWrite = IntPtr.Zero;
241
+ JobNative.CloseHandle(errWrite);
242
+ errWrite = IntPtr.Zero;
243
+ using (var output = Stream(outRead, FileAccess.Read))
244
+ using (var errors = Stream(errRead, FileAccess.Read))
245
+ using (var stdin = Stream(inWrite, FileAccess.Write))
246
+ using (var bytes = new MemoryStream())
247
+ {
248
+ outRead = errRead = inWrite = IntPtr.Zero;
249
+ int failed = 0;
250
+ var reader = new Thread(delegate ()
251
+ {
252
+ try
253
+ {
254
+ var buffer = new byte[4096];
255
+ int count;
256
+ while ((count = output.Read(buffer, 0, buffer.Length)) > 0)
257
+ {
258
+ if (bytes.Length + count > maximum)
259
+ throw new Exception();
260
+ bytes.Write(buffer, 0, count);
261
+ }
262
+ }
263
+ catch { Interlocked.Exchange(ref failed, 1); JobNative.Kill(ownedJob); }
264
+ });
265
+ var diagnostics = new Thread(delegate ()
266
+ {
267
+ try
268
+ {
269
+ var buffer = new byte[4096];
270
+ int count, total = 0;
271
+ while ((count = errors.Read(buffer, 0, buffer.Length)) > 0)
272
+ {
273
+ total += count;
274
+ if (total > 65536)
275
+ throw new Exception();
276
+ }
277
+ }
278
+ catch { Interlocked.Exchange(ref failed, 1); JobNative.Kill(ownedJob); }
279
+ });
280
+ var writer = new Thread(delegate ()
281
+ {
282
+ try
283
+ {
284
+ var b = Encoding.UTF8.GetBytes(input);
285
+ stdin.Write(b, 0, b.Length);
286
+ stdin.Dispose();
287
+ }
288
+ catch { Interlocked.Exchange(ref failed, 1); JobNative.Kill(ownedJob); }
289
+ });
290
+ try
291
+ {
292
+ reader.IsBackground = diagnostics.IsBackground = writer.IsBackground = true;
293
+ reader.Start();
294
+ diagnostics.Start();
295
+ writer.Start();
296
+ lock (Sync)
297
+ {
298
+ if (closed || Cancelled.Contains(id) || JobNative.ResumeThread(info.thread) == 0xffffffff)
299
+ throw new Exception("CANCELLED");
300
+ }
301
+ while (JobNative.WaitForSingleObject(info.process, 50) == 258)
302
+ {
303
+ lock (Sync)
304
+ {
305
+ if (closed || Cancelled.Contains(id) || failed != 0 || expires <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
306
+ throw new Exception("CANCELLED");
307
+ }
308
+ }
309
+ uint code;
310
+ if (!JobNative.GetExitCodeProcess(info.process, out code))
311
+ throw new Exception("EXIT");
312
+ JobNative.Kill(ownedJob); // Dispose every descendant even if it closed its streams.
313
+ if (!reader.Join(2000) || !diagnostics.Join(2000) || !writer.Join(2000) || failed != 0 || code != 0)
314
+ throw new Exception("EXECUTION");
315
+ lock (Sync)
316
+ {
317
+ if (closed || Cancelled.Contains(id))
318
+ throw new Exception("CANCELLED");
319
+ }
320
+ return new
321
+ {
322
+ output = Convert.ToBase64String(bytes.ToArray())
323
+ };
324
+ }
325
+ finally
326
+ {
327
+ JobNative.Kill(ownedJob);
328
+ foreach (var worker in new[] { reader, diagnostics, writer })
329
+ if (worker.IsAlive)
330
+ worker.Join(2000);
331
+ }
332
+ }
333
+ }
334
+ finally
335
+ {
336
+ if (info.process != IntPtr.Zero)
337
+ {
338
+ if (!assigned)
339
+ JobNative.TerminateProcess(info.process, 1);
340
+ JobNative.CloseHandle(info.process);
341
+ }
342
+ if (info.thread != IntPtr.Zero)
343
+ JobNative.CloseHandle(info.thread);
344
+ lock (Sync)
345
+ {
346
+ Jobs[id] = IntPtr.Zero;
347
+ if (ownedJob != null)
348
+ ownedJob.Dispose();
349
+ else if (job != IntPtr.Zero)
350
+ JobNative.CloseHandle(job);
351
+ }
352
+ foreach (var handle in new[] { inRead, inWrite, outRead, outWrite, errRead, errWrite })
353
+ if (handle != IntPtr.Zero)
354
+ JobNative.CloseHandle(handle);
355
+ if (environment != IntPtr.Zero)
356
+ Marshal.FreeHGlobal(environment);
357
+ }
358
+ }
359
+ }
360
+ }