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

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 (266) hide show
  1. package/COMPATIBILITY.json +45 -0
  2. package/LICENSE +201 -0
  3. package/components/runtime.json +31 -0
  4. package/components/runtime.tgz +0 -0
  5. package/dist/BUNDLED_DEPENDENCIES.json +1 -0
  6. package/dist/_chunks/chunk-2UYKJ6YN.js +1 -0
  7. package/dist/_chunks/chunk-37PAJCKA.js +1 -0
  8. package/dist/_chunks/chunk-3AVC742O.js +1 -0
  9. package/dist/_chunks/chunk-4U4Y2K73.js +1 -0
  10. package/dist/_chunks/chunk-65FQPXKC.js +1 -0
  11. package/dist/_chunks/chunk-6DVZBKNV.js +1 -0
  12. package/dist/_chunks/chunk-6LU6GJKW.js +1 -0
  13. package/dist/_chunks/chunk-6N433ZWR.js +1 -0
  14. package/dist/_chunks/chunk-EGUJ2YRX.js +1 -0
  15. package/dist/_chunks/chunk-FU3524Z6.js +1 -0
  16. package/dist/_chunks/chunk-GZBWA4YN.js +1 -0
  17. package/dist/_chunks/chunk-HR34UMPP.js +1 -0
  18. package/dist/_chunks/chunk-HTUTYIRU.js +1 -0
  19. package/dist/_chunks/chunk-JFC6ZIGA.js +1 -0
  20. package/dist/_chunks/chunk-KB2GVAN7.js +1 -0
  21. package/dist/_chunks/chunk-L543FEDK.js +1 -0
  22. package/dist/_chunks/chunk-LISB5W7B.js +1 -0
  23. package/dist/_chunks/chunk-LUAH3KAS.js +1 -0
  24. package/dist/_chunks/chunk-M2KVQQ4X.js +1 -0
  25. package/dist/_chunks/chunk-ODGPV7MM.js +1 -0
  26. package/dist/_chunks/chunk-PUBMDP4E.js +1 -0
  27. package/dist/_chunks/chunk-PUNG4ND7.js +1 -0
  28. package/dist/_chunks/chunk-Q57YFNK5.js +1 -0
  29. package/dist/_chunks/chunk-QAJH4RJQ.js +1 -0
  30. package/dist/_chunks/chunk-VDNNFVTZ.js +3 -0
  31. package/dist/_chunks/chunk-VPYAXWXY.js +1 -0
  32. package/dist/_chunks/chunk-WFRRNWO5.js +1 -0
  33. package/dist/_chunks/connect-5YMO6MAR.js +1 -0
  34. package/dist/_chunks/device-management-2OTGEBJQ.js +1 -0
  35. package/dist/_chunks/device-preflight-XPHFZGLO.js +1 -0
  36. package/dist/_chunks/devices-inventory-VWNTU5TE.js +1 -0
  37. package/dist/_chunks/devices-main-VQ4APRVS.js +1 -0
  38. package/dist/_chunks/files-TTIQ7LYJ.js +1 -0
  39. package/dist/_chunks/host-main-H7DPLV7B.js +1 -0
  40. package/dist/_chunks/http-profile-MNJX6OXO.js +1 -0
  41. package/dist/_chunks/library-main-SAC3V2ML.js +1 -0
  42. package/dist/_chunks/local-main-D6B3APK6.js +1 -0
  43. package/dist/_chunks/local-mcp-ONCANLPH.js +1 -0
  44. package/dist/_chunks/main-PW6HB3NC.js +2 -0
  45. package/dist/_chunks/mcp-ZIGBYFUW.js +1 -0
  46. package/dist/_chunks/oauth-HC6TI7HB.js +1 -0
  47. package/dist/_chunks/render-main-GYWKP72O.js +1 -0
  48. package/dist/_chunks/source-import-BC5GNCUZ.js +1 -0
  49. package/dist/_chunks/src-R6DNU336.js +1 -0
  50. package/dist/_chunks/stdio-main-RIJS5REB.js +1 -0
  51. package/dist/_chunks/workspace-main-GNSKHKBG.js +1 -0
  52. package/dist/_types/cli/local/desktop-channel.d.ts +18 -0
  53. package/dist/_types/cli/local/desktop-contract.d.ts +2176 -0
  54. package/dist/_types/cli/local/desktop-device-contract.d.ts +779 -0
  55. package/dist/_types/cli/local/desktop-device-navigation.d.ts +3 -0
  56. package/dist/_types/cli/local/desktop-device-owner.d.ts +244 -0
  57. package/dist/_types/cli/local/desktop-device-state.d.ts +397 -0
  58. package/dist/_types/cli/local/desktop-library.d.ts +853 -0
  59. package/dist/_types/cli/local/desktop-node.d.ts +1 -0
  60. package/dist/_types/cli/local/desktop-owner.d.ts +766 -0
  61. package/dist/_types/cli/local/ledger.d.ts +363 -0
  62. package/dist/_types/cli/local/manager.d.ts +1695 -0
  63. package/dist/_types/cli/local/mcp-tools.d.ts +660 -0
  64. package/dist/_types/cli/local/releases.d.ts +123 -0
  65. package/dist/_types/cli/local-management.d.ts +16 -0
  66. package/dist/_types/cli/local-navigation.d.ts +4 -0
  67. package/dist/_types/contracts/accepted-shot.d.ts +27 -0
  68. package/dist/_types/contracts/accepted-visual-source.d.ts +120 -0
  69. package/dist/_types/contracts/agent-execution-lifecycle.d.ts +749 -0
  70. package/dist/_types/contracts/agent-execution-oauth.d.ts +71 -0
  71. package/dist/_types/contracts/agent-execution-registration.d.ts +240 -0
  72. package/dist/_types/contracts/agent-execution-selection.d.ts +107 -0
  73. package/dist/_types/contracts/agent-host-execution.d.ts +706 -0
  74. package/dist/_types/contracts/agent-host-generic-transport.d.ts +12 -0
  75. package/dist/_types/contracts/agent-host.d.ts +226 -0
  76. package/dist/_types/contracts/artifact-discovery.d.ts +242 -0
  77. package/dist/_types/contracts/artifact.d.ts +188 -0
  78. package/dist/_types/contracts/audio.d.ts +335 -0
  79. package/dist/_types/contracts/brief.d.ts +178 -0
  80. package/dist/_types/contracts/caption-render.d.ts +20 -0
  81. package/dist/_types/contracts/caption-transcript.d.ts +102 -0
  82. package/dist/_types/contracts/captions.d.ts +420 -0
  83. package/dist/_types/contracts/clip-framing.d.ts +14 -0
  84. package/dist/_types/contracts/clip-transition.d.ts +6 -0
  85. package/dist/_types/contracts/composition-authoring-guide.d.ts +160 -0
  86. package/dist/_types/contracts/composition-authoring.d.ts +744 -0
  87. package/dist/_types/contracts/composition-finding-locality.d.ts +24 -0
  88. package/dist/_types/contracts/composition-frame-render.d.ts +226 -0
  89. package/dist/_types/contracts/composition-making.d.ts +390 -0
  90. package/dist/_types/contracts/composition-observation.d.ts +239 -0
  91. package/dist/_types/contracts/composition-render-base.d.ts +293 -0
  92. package/dist/_types/contracts/composition-render-observation.d.ts +278 -0
  93. package/dist/_types/contracts/composition-render.d.ts +406 -0
  94. package/dist/_types/contracts/composition-repair.d.ts +451 -0
  95. package/dist/_types/contracts/composition-source-review.d.ts +1042 -0
  96. package/dist/_types/contracts/consistency-profile.d.ts +845 -0
  97. package/dist/_types/contracts/continuity-evaluation.d.ts +48 -0
  98. package/dist/_types/contracts/delivery-completion.d.ts +210 -0
  99. package/dist/_types/contracts/delivery-manifest.d.ts +72 -0
  100. package/dist/_types/contracts/delivery-operations.d.ts +1151 -0
  101. package/dist/_types/contracts/delivery-output-profile.d.ts +12 -0
  102. package/dist/_types/contracts/delivery-summary.d.ts +220 -0
  103. package/dist/_types/contracts/delivery-validation.d.ts +206 -0
  104. package/dist/_types/contracts/device-render.d.ts +77 -0
  105. package/dist/_types/contracts/director-proposal.d.ts +1067 -0
  106. package/dist/_types/contracts/editor-intelligence.d.ts +3374 -0
  107. package/dist/_types/contracts/exploration-recommendation.d.ts +519 -0
  108. package/dist/_types/contracts/external-agent-access.d.ts +93 -0
  109. package/dist/_types/contracts/final-ready.d.ts +301 -0
  110. package/dist/_types/contracts/final-render-profile.d.ts +59 -0
  111. package/dist/_types/contracts/final-render.d.ts +2810 -0
  112. package/dist/_types/contracts/foundation.d.ts +1 -0
  113. package/dist/_types/contracts/generation-contract.d.ts +268 -0
  114. package/dist/_types/contracts/generation-cost.d.ts +70 -0
  115. package/dist/_types/contracts/health.d.ts +6 -0
  116. package/dist/_types/contracts/human-identity.d.ts +162 -0
  117. package/dist/_types/contracts/hyperframe-profile.d.ts +5 -0
  118. package/dist/_types/contracts/ids.d.ts +41 -0
  119. package/dist/_types/contracts/index.d.ts +126 -0
  120. package/dist/_types/contracts/interface/common.d.ts +56 -0
  121. package/dist/_types/contracts/interface/execution-output.d.ts +99 -0
  122. package/dist/_types/contracts/interface/index.d.ts +7 -0
  123. package/dist/_types/contracts/interface/media-output.d.ts +90 -0
  124. package/dist/_types/contracts/interface/operation.d.ts +61 -0
  125. package/dist/_types/contracts/interface/output.d.ts +15 -0
  126. package/dist/_types/contracts/interface/production-snapshot.d.ts +654 -0
  127. package/dist/_types/contracts/interface/query.d.ts +315 -0
  128. package/dist/_types/contracts/keyframe-generation.d.ts +378 -0
  129. package/dist/_types/contracts/keyframe-reference.d.ts +31 -0
  130. package/dist/_types/contracts/keyframe-review.d.ts +753 -0
  131. package/dist/_types/contracts/lifecycle-event-projections.d.ts +191 -0
  132. package/dist/_types/contracts/lifecycle-events.d.ts +156 -0
  133. package/dist/_types/contracts/listening-evidence.d.ts +37 -0
  134. package/dist/_types/contracts/local-execution/agent-context.d.ts +365 -0
  135. package/dist/_types/contracts/local-execution/agent-evidence.d.ts +79 -0
  136. package/dist/_types/contracts/local-execution/agent-grant.d.ts +31 -0
  137. package/dist/_types/contracts/local-execution/agent-review.d.ts +992 -0
  138. package/dist/_types/contracts/local-execution/canonical.d.ts +2 -0
  139. package/dist/_types/contracts/local-execution/common.d.ts +49 -0
  140. package/dist/_types/contracts/local-execution/completion.d.ts +124 -0
  141. package/dist/_types/contracts/local-execution/components.d.ts +45 -0
  142. package/dist/_types/contracts/local-execution/descriptor.d.ts +38 -0
  143. package/dist/_types/contracts/local-execution/device-authority.d.ts +31 -0
  144. package/dist/_types/contracts/local-execution/device-inventory.d.ts +76 -0
  145. package/dist/_types/contracts/local-execution/device-workspace.d.ts +11 -0
  146. package/dist/_types/contracts/local-execution/device.d.ts +102 -0
  147. package/dist/_types/contracts/local-execution/external-generation.d.ts +199 -0
  148. package/dist/_types/contracts/local-execution/index.d.ts +37 -0
  149. package/dist/_types/contracts/local-execution/ipc.d.ts +3730 -0
  150. package/dist/_types/contracts/local-execution/library-command.d.ts +620 -0
  151. package/dist/_types/contracts/local-execution/library-result.d.ts +408 -0
  152. package/dist/_types/contracts/local-execution/library.d.ts +873 -0
  153. package/dist/_types/contracts/local-execution/lifecycle.d.ts +519 -0
  154. package/dist/_types/contracts/local-execution/local-navigation.d.ts +929 -0
  155. package/dist/_types/contracts/local-execution/management.d.ts +400 -0
  156. package/dist/_types/contracts/local-execution/media-recipe.d.ts +207 -0
  157. package/dist/_types/contracts/local-execution/media-validation-request.d.ts +232 -0
  158. package/dist/_types/contracts/local-execution/media-validation.d.ts +262 -0
  159. package/dist/_types/contracts/local-execution/object-transfer.d.ts +155 -0
  160. package/dist/_types/contracts/local-execution/offline.d.ts +59 -0
  161. package/dist/_types/contracts/local-execution/preview.d.ts +243 -0
  162. package/dist/_types/contracts/local-execution/processor-capability.d.ts +39 -0
  163. package/dist/_types/contracts/local-execution/processor-direct.d.ts +290 -0
  164. package/dist/_types/contracts/local-execution/processor-recipes.d.ts +1122 -0
  165. package/dist/_types/contracts/local-execution/processor.d.ts +6173 -0
  166. package/dist/_types/contracts/local-execution/project-source-direct.d.ts +201 -0
  167. package/dist/_types/contracts/local-execution/qwen-tts.d.ts +31 -0
  168. package/dist/_types/contracts/local-execution/recognition.d.ts +170 -0
  169. package/dist/_types/contracts/local-execution/speech.d.ts +95 -0
  170. package/dist/_types/contracts/local-execution/tool-selection.d.ts +55 -0
  171. package/dist/_types/contracts/local-execution/whisper.d.ts +24 -0
  172. package/dist/_types/contracts/local-execution/work.d.ts +149 -0
  173. package/dist/_types/contracts/local-execution/workspace.d.ts +141 -0
  174. package/dist/_types/contracts/matrix-parameter-rule.d.ts +23 -0
  175. package/dist/_types/contracts/media-category.d.ts +11 -0
  176. package/dist/_types/contracts/media-export.d.ts +23 -0
  177. package/dist/_types/contracts/media-observation.d.ts +2080 -0
  178. package/dist/_types/contracts/model-capability-matrix.d.ts +118 -0
  179. package/dist/_types/contracts/native-tool-authority-failure.d.ts +38 -0
  180. package/dist/_types/contracts/native-tool-authority.d.ts +110 -0
  181. package/dist/_types/contracts/native-tool-execution.d.ts +287 -0
  182. package/dist/_types/contracts/native-tool-gateway.d.ts +41 -0
  183. package/dist/_types/contracts/native-video-audio.d.ts +62 -0
  184. package/dist/_types/contracts/navigation-context.d.ts +253 -0
  185. package/dist/_types/contracts/navigation-groups.d.ts +51 -0
  186. package/dist/_types/contracts/navigation.d.ts +248 -0
  187. package/dist/_types/contracts/observation-profile.d.ts +99 -0
  188. package/dist/_types/contracts/planning-input.d.ts +177 -0
  189. package/dist/_types/contracts/principal.d.ts +26 -0
  190. package/dist/_types/contracts/production-creation.d.ts +66 -0
  191. package/dist/_types/contracts/production-termination.d.ts +51 -0
  192. package/dist/_types/contracts/production.d.ts +111 -0
  193. package/dist/_types/contracts/programmatic-composition.d.ts +762 -0
  194. package/dist/_types/contracts/programmatic-exploration.d.ts +1822 -0
  195. package/dist/_types/contracts/programmatic-video-review.d.ts +894 -0
  196. package/dist/_types/contracts/project-library.d.ts +173 -0
  197. package/dist/_types/contracts/project.d.ts +93 -0
  198. package/dist/_types/contracts/provider-catalog.d.ts +421 -0
  199. package/dist/_types/contracts/provider-models.d.ts +3388 -0
  200. package/dist/_types/contracts/provider.d.ts +207 -0
  201. package/dist/_types/contracts/reference-preview.d.ts +55 -0
  202. package/dist/_types/contracts/repair-lifecycle.d.ts +2564 -0
  203. package/dist/_types/contracts/repair-plan.d.ts +646 -0
  204. package/dist/_types/contracts/repair-strategy.d.ts +1432 -0
  205. package/dist/_types/contracts/review-intelligence-evidence.d.ts +136 -0
  206. package/dist/_types/contracts/review-intelligence-final-output.d.ts +883 -0
  207. package/dist/_types/contracts/review-intelligence.d.ts +573 -0
  208. package/dist/_types/contracts/review1-repair-source.d.ts +452 -0
  209. package/dist/_types/contracts/review1-repair-strategy.d.ts +491 -0
  210. package/dist/_types/contracts/review1-repair.d.ts +36 -0
  211. package/dist/_types/contracts/rough-cut-manifest.d.ts +352 -0
  212. package/dist/_types/contracts/rough-cut-profile.d.ts +46 -0
  213. package/dist/_types/contracts/rough-cut-review.d.ts +459 -0
  214. package/dist/_types/contracts/rough-cut.d.ts +1260 -0
  215. package/dist/_types/contracts/scene-shot-plan.d.ts +882 -0
  216. package/dist/_types/contracts/sdk-discovery.d.ts +66 -0
  217. package/dist/_types/contracts/shot-direction.d.ts +113 -0
  218. package/dist/_types/contracts/shot-preparation-basis.d.ts +356 -0
  219. package/dist/_types/contracts/shot-preparation.d.ts +2285 -0
  220. package/dist/_types/contracts/shot-sound-instruction.d.ts +58 -0
  221. package/dist/_types/contracts/sound-making-plan.d.ts +1586 -0
  222. package/dist/_types/contracts/source-sound-policy.d.ts +10 -0
  223. package/dist/_types/contracts/source-workspace.d.ts +62 -0
  224. package/dist/_types/contracts/speech-cost.d.ts +81 -0
  225. package/dist/_types/contracts/speech.d.ts +573 -0
  226. package/dist/_types/contracts/story.d.ts +98 -0
  227. package/dist/_types/contracts/temporal-evidence-operation.d.ts +380 -0
  228. package/dist/_types/contracts/temporal-evidence-reference.d.ts +18 -0
  229. package/dist/_types/contracts/temporal-evidence.d.ts +248 -0
  230. package/dist/_types/contracts/tenant.d.ts +7 -0
  231. package/dist/_types/contracts/timeline-audio.d.ts +98 -0
  232. package/dist/_types/contracts/timeline-graphics.d.ts +80 -0
  233. package/dist/_types/contracts/timeline-manifest.d.ts +704 -0
  234. package/dist/_types/contracts/timeline-source-sound.d.ts +353 -0
  235. package/dist/_types/contracts/timeline-v2.d.ts +1267 -0
  236. package/dist/_types/contracts/timeline-version-reader.d.ts +2955 -0
  237. package/dist/_types/contracts/timeline-visual-layers.d.ts +1249 -0
  238. package/dist/_types/contracts/timeline.d.ts +142 -0
  239. package/dist/_types/contracts/transcription.d.ts +80 -0
  240. package/dist/_types/contracts/video-generation.d.ts +676 -0
  241. package/dist/_types/contracts/video-review.d.ts +1871 -0
  242. package/dist/_types/contracts/visual-exploration.d.ts +1586 -0
  243. package/dist/_types/contracts/visual-layer-render.d.ts +2820 -0
  244. package/dist/_types/contracts/visual-layer.d.ts +112 -0
  245. package/dist/_types/contracts/visual-sequence.d.ts +143 -0
  246. package/dist/_types/contracts/workspace.d.ts +32 -0
  247. package/dist/_types/contracts/writer-proposal.d.ts +268 -0
  248. package/dist/_types/sdk/errors.d.ts +14 -0
  249. package/dist/_types/sdk/local-runtime/components.d.ts +2 -0
  250. package/dist/_types/sdk/local-runtime/device-client.d.ts +187 -0
  251. package/dist/_types/sdk/local-runtime/library.d.ts +268 -0
  252. package/dist/_types/sdk/local-runtime/workspace.d.ts +186 -0
  253. package/dist/_types/sdk/local-runtime-client.d.ts +2616 -0
  254. package/dist/entry.js +2 -0
  255. package/dist/local-management.d.ts +1 -0
  256. package/dist/local-management.js +1 -0
  257. package/dist/local-navigation.d.ts +1 -0
  258. package/dist/local-navigation.js +1 -0
  259. package/dist/native/Bootstrap.ps1 +90 -0
  260. package/dist/native/JobNative.cs +137 -0
  261. package/dist/native/JobRunner.cs +381 -0
  262. package/dist/native/NativeMain.cs +161 -0
  263. package/dist/native/PipeBridge.cs +260 -0
  264. package/dist/native/PrivateAccess.cs +152 -0
  265. package/package.json +27 -3
  266. package/README.md +0 -3
@@ -0,0 +1,381 @@
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 readonly Dictionary<string, double> Cpus = new Dictionary<string, double>();
19
+ static readonly Dictionary<string, ulong> Memories = new Dictionary<string, ulong>();
20
+ static readonly HashSet<string> Exceeded = new HashSet<string>();
21
+ static ulong memoryBudget = 4294967296UL;
22
+ static IntPtr aggregate;
23
+ static Process parent;
24
+ static bool closed;
25
+ public static void Parent(int id)
26
+ {
27
+ parent = Process.GetProcessById(id);
28
+ if (parent.Handle == IntPtr.Zero)
29
+ throw new Exception("PARENT");
30
+ }
31
+ public static bool Reserve(string id)
32
+ {
33
+ lock (Sync)
34
+ {
35
+ if (closed || Jobs.Count >= 16 || Jobs.ContainsKey(id))
36
+ return false;
37
+ Jobs.Add(id, IntPtr.Zero);
38
+ return true;
39
+ }
40
+ }
41
+ public static void Release(string id)
42
+ {
43
+ lock (Sync)
44
+ {
45
+ Jobs.Remove(id);
46
+ Cancelled.Remove(id);
47
+ Exceeded.Remove(id);
48
+ Cpus.Remove(id);
49
+ Memories.Remove(id);
50
+ ApplyBudget();
51
+ }
52
+ }
53
+ static void ApplyBudget()
54
+ {
55
+ memoryBudget = Memories.Count == 0 ? 4294967296UL : Memories.Values.Min();
56
+ if (aggregate != IntPtr.Zero && !closed)
57
+ JobNative.Budget(aggregate, Cpus.Count == 0 ? 2 : Cpus.Values.Min(), memoryBudget);
58
+ }
59
+ public static void Cancel(string id)
60
+ {
61
+ lock (Sync)
62
+ {
63
+ IntPtr job;
64
+ if (!Jobs.TryGetValue(id, out job))
65
+ return;
66
+ Cancelled.Add(id);
67
+ if (job != IntPtr.Zero)
68
+ JobNative.TerminateJobObject(job, 1); // Handle disposal uses the same lock.
69
+ }
70
+ }
71
+ public static void Close()
72
+ {
73
+ lock (Sync)
74
+ {
75
+ closed = true;
76
+ if (aggregate != IntPtr.Zero)
77
+ {
78
+ JobNative.CloseHandle(aggregate);
79
+ aggregate = IntPtr.Zero;
80
+ }
81
+ }
82
+ }
83
+ static IntPtr Aggregate()
84
+ {
85
+ lock (Sync)
86
+ {
87
+ if (closed)
88
+ throw new Exception("CLOSED");
89
+ if (aggregate == IntPtr.Zero)
90
+ {
91
+ aggregate = JobNative.Job(true);
92
+ var monitor = new Thread(delegate ()
93
+ {
94
+ try
95
+ {
96
+ while (!closed)
97
+ {
98
+ lock (Sync)
99
+ {
100
+ if (closed)
101
+ return;
102
+ long rss = Process.GetCurrentProcess().WorkingSet64;
103
+ if (parent != null)
104
+ {
105
+ if (parent.HasExited)
106
+ {
107
+ Close();
108
+ return;
109
+ }
110
+ parent.Refresh();
111
+ rss += parent.WorkingSet64;
112
+ }
113
+ foreach (uint id in JobNative.Processes(aggregate))
114
+ {
115
+ try
116
+ {
117
+ using (var p = Process.GetProcessById((int)id))
118
+ rss += p.WorkingSet64;
119
+ }
120
+ catch (ArgumentException) { } // A command already exited.
121
+ }
122
+ if ((ulong)rss > memoryBudget)
123
+ {
124
+ foreach (var id in Cpus.Keys) Exceeded.Add(id);
125
+ JobNative.TerminateJobObject(aggregate, 1);
126
+ }
127
+ }
128
+ Thread.Sleep(100);
129
+ }
130
+ }
131
+ catch { Close(); }
132
+ });
133
+ monitor.IsBackground = true;
134
+ monitor.Start();
135
+ }
136
+ return aggregate;
137
+ }
138
+ }
139
+ public static string Quote(string value)
140
+ {
141
+ if (value.IndexOf('\0') >= 0)
142
+ throw new Exception("ARGUMENT");
143
+ var b = new StringBuilder("\"");
144
+ int slashes = 0;
145
+ foreach (char c in value)
146
+ {
147
+ if (c == '\\')
148
+ {
149
+ slashes++;
150
+ continue;
151
+ }
152
+ if (c == '\"')
153
+ {
154
+ b.Append('\\', slashes * 2 + 1);
155
+ b.Append(c);
156
+ }
157
+ else
158
+ {
159
+ b.Append('\\', slashes);
160
+ b.Append(c);
161
+ }
162
+ slashes = 0;
163
+ }
164
+ b.Append('\\', slashes * 2);
165
+ b.Append('"');
166
+ return b.ToString();
167
+ }
168
+ static IntPtr EnvironmentBlock(IDictionary<string, object> r)
169
+ {
170
+ var values = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
171
+ values["SystemRoot"] = Environment.GetEnvironmentVariable("SystemRoot");
172
+ object supplied;
173
+ if (r.TryGetValue("environment", out supplied) && supplied != null)
174
+ {
175
+ var env = (IDictionary<string, object>)supplied;
176
+ if (env.Count > 24)
177
+ throw new Exception("ENVIRONMENT");
178
+ foreach (var entry in env)
179
+ {
180
+ string key = entry.Key.ToUpperInvariant(), value = entry.Value as string;
181
+ 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_"))
182
+ throw new Exception("ENVIRONMENT");
183
+ if (key != "SYSTEMROOT")
184
+ values[key] = value;
185
+ }
186
+ }
187
+ return Marshal.StringToHGlobalUni(String.Join("\0", values.Select(v => v.Key + "=" + v.Value).ToArray()) + "\0\0");
188
+ }
189
+ static FileStream Stream(IntPtr handle, FileAccess access)
190
+ {
191
+ return new FileStream(new SafeFileHandle(handle, true), access, 4096, false);
192
+ }
193
+ public static object Execute(string id, IDictionary<string, object> r)
194
+ {
195
+ string binary = PrivateAccess.PathOf(NativeMain.Text(r, "binary"));
196
+ if (!binary.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
197
+ throw new Exception("EXECUTABLE");
198
+ PrivateAccess.Check(binary, "file", false);
199
+ var args = (IList)r["args"];
200
+ if (args.Count > 512)
201
+ throw new Exception("ARGUMENT");
202
+ var command = new StringBuilder(Quote(binary));
203
+ foreach (object arg in args)
204
+ {
205
+ if (!(arg is string))
206
+ throw new Exception("ARGUMENT");
207
+ command.Append(' ').Append(Quote((string)arg));
208
+ }
209
+ if (command.Length > 30000)
210
+ throw new Exception("ARGUMENT_LIMIT");
211
+ string input = r.ContainsKey("input") ? NativeMain.Text(r, "input") : "";
212
+ if (Encoding.UTF8.GetByteCount(input) > 65536)
213
+ throw new Exception("INPUT_LIMIT");
214
+ int maximum = Convert.ToInt32(r["maxOutputBytes"]);
215
+ long expires = Convert.ToInt64(r["expiresAt"]);
216
+ var budget = r.ContainsKey("limits") ? (IDictionary<string, object>)r["limits"] : null;
217
+ double cpu = budget == null ? 2 : Convert.ToDouble(budget["cpuCores"]);
218
+ ulong memory = budget == null ? 4294967296UL : Convert.ToUInt64(budget["memoryBytes"]);
219
+ if (Double.IsNaN(cpu) || Double.IsInfinity(cpu) || cpu < 0.25 || cpu > 2 || memory < 1048576UL || memory > 4294967296UL)
220
+ throw new Exception("LIMIT");
221
+ if (maximum < 1 || maximum > 524288 || expires <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
222
+ throw new Exception("LIMIT");
223
+ string cwd = r.ContainsKey("cwd") && r["cwd"] != null ? PrivateAccess.PathOf(NativeMain.Text(r, "cwd")) : null;
224
+ 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;
225
+ SafeFileHandle ownedJob = null;
226
+ var info = new JobNative.ProcessInfo();
227
+ bool assigned = false;
228
+ try
229
+ {
230
+ var root = Aggregate();
231
+ lock (Sync) { Cpus[id] = cpu; Memories[id] = memory; ApplyBudget(); }
232
+ job = JobNative.Job(false);
233
+ ownedJob = new SafeFileHandle(job, true);
234
+ lock (Sync)
235
+ {
236
+ Jobs[id] = job;
237
+ if (Cancelled.Contains(id) || closed)
238
+ throw new Exception("CANCELLED");
239
+ }
240
+ var sa = new JobNative.SecurityAttributes { size = Marshal.SizeOf(typeof(JobNative.SecurityAttributes)), inherit = 1 };
241
+ 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))
242
+ throw new Exception("PIPE");
243
+ if (!JobNative.SetHandleInformation(inWrite, 1, 0) || !JobNative.SetHandleInformation(outRead, 1, 0) || !JobNative.SetHandleInformation(errRead, 1, 0))
244
+ throw new Exception("HANDLE");
245
+ var startup = new JobNative.StartupInfo { size = Marshal.SizeOf(typeof(JobNative.StartupInfo)), flags = 0x100, input = inRead, output = outWrite, error = errWrite };
246
+ environment = EnvironmentBlock(r);
247
+ if (!JobNative.CreateProcess(binary, command, IntPtr.Zero, IntPtr.Zero, true, 4 | 0x400 | 0x8000000, environment, cwd, ref startup, out info))
248
+ throw new Exception("SPAWN");
249
+ lock (Sync)
250
+ {
251
+ if (closed || Cancelled.Contains(id))
252
+ throw new Exception("CANCELLED");
253
+ if (!JobNative.AssignProcessToJobObject(root, info.process) || !JobNative.AssignProcessToJobObject(job, info.process))
254
+ throw new Exception("JOB_ASSIGN");
255
+ assigned = true;
256
+ }
257
+ JobNative.CloseHandle(inRead);
258
+ inRead = IntPtr.Zero;
259
+ JobNative.CloseHandle(outWrite);
260
+ outWrite = IntPtr.Zero;
261
+ JobNative.CloseHandle(errWrite);
262
+ errWrite = IntPtr.Zero;
263
+ using (var output = Stream(outRead, FileAccess.Read))
264
+ using (var errors = Stream(errRead, FileAccess.Read))
265
+ using (var stdin = Stream(inWrite, FileAccess.Write))
266
+ using (var bytes = new MemoryStream())
267
+ {
268
+ outRead = errRead = inWrite = IntPtr.Zero;
269
+ int failed = 0;
270
+ var reader = new Thread(delegate ()
271
+ {
272
+ try
273
+ {
274
+ var buffer = new byte[4096];
275
+ int count;
276
+ while ((count = output.Read(buffer, 0, buffer.Length)) > 0)
277
+ {
278
+ if (bytes.Length + count > maximum)
279
+ throw new Exception();
280
+ bytes.Write(buffer, 0, count);
281
+ }
282
+ }
283
+ catch { Interlocked.Exchange(ref failed, 1); JobNative.Kill(ownedJob); }
284
+ });
285
+ var diagnostics = new Thread(delegate ()
286
+ {
287
+ try
288
+ {
289
+ var buffer = new byte[4096];
290
+ int count, total = 0;
291
+ while ((count = errors.Read(buffer, 0, buffer.Length)) > 0)
292
+ {
293
+ total += count;
294
+ if (total > 65536)
295
+ throw new Exception();
296
+ }
297
+ }
298
+ catch { Interlocked.Exchange(ref failed, 1); JobNative.Kill(ownedJob); }
299
+ });
300
+ var writer = new Thread(delegate ()
301
+ {
302
+ try
303
+ {
304
+ var b = Encoding.UTF8.GetBytes(input);
305
+ stdin.Write(b, 0, b.Length);
306
+ stdin.Dispose();
307
+ }
308
+ catch { Interlocked.Exchange(ref failed, 1); JobNative.Kill(ownedJob); }
309
+ });
310
+ try
311
+ {
312
+ reader.IsBackground = diagnostics.IsBackground = writer.IsBackground = true;
313
+ reader.Start();
314
+ diagnostics.Start();
315
+ writer.Start();
316
+ lock (Sync)
317
+ {
318
+ if (closed || Cancelled.Contains(id) || JobNative.ResumeThread(info.thread) == 0xffffffff)
319
+ throw new Exception("CANCELLED");
320
+ }
321
+ while (JobNative.WaitForSingleObject(info.process, 50) == 258)
322
+ {
323
+ lock (Sync)
324
+ {
325
+ if (closed || Cancelled.Contains(id) || failed != 0 || expires <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
326
+ throw new Exception("CANCELLED");
327
+ }
328
+ }
329
+ uint code;
330
+ lock (Sync) { if (Exceeded.Contains(id)) throw new Exception("RESOURCE_BUDGET_EXCEEDED"); }
331
+ if (!JobNative.GetExitCodeProcess(info.process, out code))
332
+ throw new Exception("EXIT");
333
+ JobNative.Kill(ownedJob); // Dispose every descendant even if it closed its streams.
334
+ if (!reader.Join(2000) || !diagnostics.Join(2000) || !writer.Join(2000) || failed != 0 || code != 0)
335
+ throw new Exception("EXECUTION");
336
+ lock (Sync)
337
+ {
338
+ if (closed || Cancelled.Contains(id))
339
+ throw new Exception("CANCELLED");
340
+ }
341
+ return new
342
+ {
343
+ output = Convert.ToBase64String(bytes.ToArray())
344
+ };
345
+ }
346
+ finally
347
+ {
348
+ JobNative.Kill(ownedJob);
349
+ foreach (var worker in new[] { reader, diagnostics, writer })
350
+ if (worker.IsAlive)
351
+ worker.Join(2000);
352
+ }
353
+ }
354
+ }
355
+ finally
356
+ {
357
+ if (info.process != IntPtr.Zero)
358
+ {
359
+ if (!assigned)
360
+ JobNative.TerminateProcess(info.process, 1);
361
+ JobNative.CloseHandle(info.process);
362
+ }
363
+ if (info.thread != IntPtr.Zero)
364
+ JobNative.CloseHandle(info.thread);
365
+ lock (Sync)
366
+ {
367
+ Jobs[id] = IntPtr.Zero;
368
+ if (ownedJob != null)
369
+ ownedJob.Dispose();
370
+ else if (job != IntPtr.Zero)
371
+ JobNative.CloseHandle(job);
372
+ }
373
+ foreach (var handle in new[] { inRead, inWrite, outRead, outWrite, errRead, errWrite })
374
+ if (handle != IntPtr.Zero)
375
+ JobNative.CloseHandle(handle);
376
+ if (environment != IntPtr.Zero)
377
+ Marshal.FreeHGlobal(environment);
378
+ }
379
+ }
380
+ }
381
+ }
@@ -0,0 +1,161 @@
1
+ using System;
2
+ using System.Collections.Generic;
3
+ using System.Text;
4
+ using System.Threading;
5
+ using System.Web.Script.Serialization;
6
+ namespace NativeStudio.Platform
7
+ {
8
+ public static class NativeMain
9
+ {
10
+ [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
11
+ struct LastInput { public uint size; public uint tick; }
12
+ [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
13
+ static extern bool GetLastInputInfo(ref LastInput input);
14
+ static int IdleSeconds()
15
+ {
16
+ var input = new LastInput { size = 8 };
17
+ if (!GetLastInputInfo(ref input)) throw new Exception("IDLE_UNAVAILABLE");
18
+ return (int)Math.Min(86400U, unchecked((uint)Environment.TickCount - input.tick) / 1000U);
19
+ }
20
+ static readonly object Output = new object();
21
+ public static readonly JavaScriptSerializer Json = new JavaScriptSerializer { MaxJsonLength = 2097152, RecursionLimit = 32 };
22
+ public static string Text(IDictionary<string, object> r, string key)
23
+ {
24
+ object value;
25
+ if (!r.TryGetValue(key, out value) || !(value is string) || ((string)value).Length > 1048576)
26
+ throw new Exception("INPUT");
27
+ return (string)value;
28
+ }
29
+ public static string Line(int limit)
30
+ {
31
+ var value = new StringBuilder();
32
+ for (; ; )
33
+ {
34
+ int c = Console.In.Read();
35
+ if (c < 0)
36
+ return value.Length == 0 ? null : value.ToString();
37
+ if (c == 10)
38
+ return value.ToString();
39
+ if (c != 13)
40
+ value.Append((char)c);
41
+ if (value.Length > limit)
42
+ throw new Exception("INPUT_LIMIT");
43
+ }
44
+ }
45
+ public static void Send(object value)
46
+ {
47
+ string line;
48
+ lock (Json)
49
+ line = Json.Serialize(value);
50
+ lock (Output)
51
+ {
52
+ Console.WriteLine(line);
53
+ Console.Out.Flush();
54
+ }
55
+ }
56
+ static void Handle(IDictionary<string, object> r)
57
+ {
58
+ string id = Text(r, "id");
59
+ try
60
+ {
61
+ var operation = Text(r, "operation");
62
+ if (operation == "idle")
63
+ {
64
+ Send(new { id = id, ok = true, data = new { seconds = IdleSeconds() } });
65
+ return;
66
+ }
67
+ if (operation == "directory")
68
+ PrivateAccess.Directory(Text(r, "path"));
69
+ else if (operation == "check")
70
+ PrivateAccess.Check(Text(r, "path"), Text(r, "kind"), true);
71
+ else if (operation == "executable")
72
+ PrivateAccess.Check(Text(r, "path"), "file", false);
73
+ else if (operation == "move")
74
+ PrivateAccess.Move(Text(r, "source"), Text(r, "target"), r.ContainsKey("exclusive") && (bool)r["exclusive"]);
75
+ else if (operation == "execute")
76
+ {
77
+ Send(new
78
+ {
79
+ id = id,
80
+ ok = true,
81
+ data = JobRunner.Execute(id, r)
82
+ });
83
+ return;
84
+ }
85
+ else
86
+ throw new Exception("OPERATION");
87
+ Send(new
88
+ {
89
+ id = id,
90
+ ok = true,
91
+ data = true
92
+ });
93
+ }
94
+ catch (Exception e)
95
+ {
96
+ Send(new
97
+ {
98
+ id = id,
99
+ ok = false,
100
+ error = e.Message == "EXISTS" ? "EXISTS" : "DENIED"
101
+ });
102
+ }
103
+ }
104
+ public static int Main(string[] args)
105
+ {
106
+ Console.InputEncoding = new UTF8Encoding(false);
107
+ Console.OutputEncoding = new UTF8Encoding(false);
108
+ try
109
+ {
110
+ if (args.Length == 2 && args[0] == "pipe")
111
+ {
112
+ PipeBridge.Run(args[1]);
113
+ return 0;
114
+ }
115
+ if (args.Length != 2 || args[0] != "service")
116
+ return 1;
117
+ JobRunner.Parent(Int32.Parse(args[1]));
118
+ for (; ; )
119
+ {
120
+ var line = Line(1048576);
121
+ if (line == null)
122
+ break;
123
+ IDictionary<string, object> request;
124
+ lock (Json)
125
+ request = Json.Deserialize<Dictionary<string, object>>(line);
126
+ if (Text(request, "operation") == "cancel")
127
+ {
128
+ JobRunner.Cancel(Text(request, "target"));
129
+ continue;
130
+ }
131
+ if (Text(request, "operation") == "execute")
132
+ {
133
+ if (!JobRunner.Reserve(Text(request, "id")))
134
+ {
135
+ Send(new
136
+ {
137
+ id = Text(request, "id"),
138
+ ok = false,
139
+ error = "BUSY"
140
+ });
141
+ continue;
142
+ }
143
+ ThreadPool.QueueUserWorkItem(delegate
144
+ {
145
+ try
146
+ {
147
+ Handle(request);
148
+ }
149
+ finally { JobRunner.Release(Text(request, "id")); }
150
+ });
151
+ }
152
+ else
153
+ Handle(request);
154
+ }
155
+ return 0;
156
+ }
157
+ catch { return 1; }
158
+ finally { JobRunner.Close(); }
159
+ }
160
+ }
161
+ }