@nativestudio/cli 0.3.0-rc.14 → 0.3.0-rc.16

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 (147) hide show
  1. package/COMPATIBILITY.json +11 -11
  2. package/components/runtime.json +7 -7
  3. package/components/runtime.tgz +0 -0
  4. package/dist/_chunks/{chunk-C62JAWRQ.js → chunk-35XQP7RY.js} +1 -1
  5. package/dist/_chunks/{chunk-RDIMORUT.js → chunk-5LSB6HDP.js} +1 -1
  6. package/dist/_chunks/{chunk-W6C63ZN7.js → chunk-B7BQERMR.js} +1 -1
  7. package/dist/_chunks/{chunk-S74X4KIC.js → chunk-BGH3Y5UX.js} +1 -1
  8. package/dist/_chunks/chunk-CW67UB2I.js +1 -0
  9. package/dist/_chunks/chunk-EML7OS3I.js +1 -0
  10. package/dist/_chunks/{chunk-3AVC742O.js → chunk-FX5UVDTH.js} +1 -1
  11. package/dist/_chunks/{chunk-6UYY5KHI.js → chunk-HAOCQVMU.js} +1 -1
  12. package/dist/_chunks/{chunk-VD3OQ743.js → chunk-JLQCUXCT.js} +1 -1
  13. package/dist/_chunks/chunk-KOCUZ3AE.js +1 -0
  14. package/dist/_chunks/chunk-LOYAGAAN.js +1 -0
  15. package/dist/_chunks/chunk-MT5XZ67U.js +1 -0
  16. package/dist/_chunks/{chunk-VDNNFVTZ.js → chunk-OW6R4MAQ.js} +1 -1
  17. package/dist/_chunks/{chunk-6LY4JYSG.js → chunk-PYUYK3FV.js} +1 -1
  18. package/dist/_chunks/chunk-RT77PT3A.js +1 -0
  19. package/dist/_chunks/chunk-RUPH3HZ2.js +1 -0
  20. package/dist/_chunks/chunk-SKAVQ4UW.js +1 -0
  21. package/dist/_chunks/{chunk-ROBBF33U.js → chunk-SRB5ZFKO.js} +1 -1
  22. package/dist/_chunks/chunk-TQIJBUSP.js +1 -0
  23. package/dist/_chunks/chunk-TWC3NXFA.js +1 -0
  24. package/dist/_chunks/chunk-U5FT4VBR.js +1 -0
  25. package/dist/_chunks/chunk-U6ZG2G7W.js +1 -0
  26. package/dist/_chunks/chunk-UMCOLDHH.js +1 -0
  27. package/dist/_chunks/chunk-VLEWCWYF.js +1 -0
  28. package/dist/_chunks/chunk-WAADGZEV.js +1 -0
  29. package/dist/_chunks/{chunk-VKLS4QK5.js → chunk-XVQWVJWD.js} +1 -1
  30. package/dist/_chunks/{connect-6UH7ZFAC.js → connect-OY623MMA.js} +1 -1
  31. package/dist/_chunks/{device-management-H3NIDIPY.js → device-management-ELAPFWM2.js} +1 -1
  32. package/dist/_chunks/device-preflight-27RDJVBU.js +1 -0
  33. package/dist/_chunks/{devices-inventory-I2E3Q4DA.js → devices-inventory-2XEJPPO5.js} +1 -1
  34. package/dist/_chunks/{devices-main-VV2VYU4T.js → devices-main-UMF3ZBHA.js} +1 -1
  35. package/dist/_chunks/{files-TTIQ7LYJ.js → files-72BEXD7E.js} +1 -1
  36. package/dist/_chunks/{host-main-3JFGVU5P.js → host-main-WYTVTQ4Z.js} +1 -1
  37. package/dist/_chunks/http-profile-D65WSTZU.js +1 -0
  38. package/dist/_chunks/{library-main-CTBW7DAI.js → library-main-L7SY7V7L.js} +1 -1
  39. package/dist/_chunks/local-main-7FONRY6F.js +1 -0
  40. package/dist/_chunks/{local-mcp-XB6E3V2W.js → local-mcp-ELFJBJG6.js} +1 -1
  41. package/dist/_chunks/main-XWUYQQ32.js +2 -0
  42. package/dist/_chunks/mcp-ACNG635V.js +1 -0
  43. package/dist/_chunks/oauth-QBJ62PIA.js +1 -0
  44. package/dist/_chunks/observe-entry-3CHBX74Y.js +1 -0
  45. package/dist/_chunks/remote-client-WIZVKP3O.js +1 -0
  46. package/dist/_chunks/{render-main-VTM6WGFP.js → render-main-ZXYQ7EV5.js} +1 -1
  47. package/dist/_chunks/{source-import-KKV2UWJO.js → source-import-ZWR26CMU.js} +1 -1
  48. package/dist/_chunks/src-TR4JNPGI.js +1 -0
  49. package/dist/_chunks/{stdio-main-Y7N4NVKU.js → stdio-main-QQLYSRD4.js} +1 -1
  50. package/dist/_chunks/workspace-main-NYDAQGB4.js +1 -0
  51. package/dist/_types/cli/local/desktop-contract.d.ts +14 -14
  52. package/dist/_types/cli/local/desktop-device-contract.d.ts +5 -5
  53. package/dist/_types/cli/local/desktop-device-owner.d.ts +2 -2
  54. package/dist/_types/cli/local/desktop-device-state.d.ts +2 -2
  55. package/dist/_types/cli/local/desktop-library.d.ts +1 -1
  56. package/dist/_types/cli/local/desktop-owner.d.ts +4 -4
  57. package/dist/_types/cli/local/manager.d.ts +2 -2
  58. package/dist/_types/cli/local/mcp-tools.d.ts +2 -2
  59. package/dist/_types/cli/local-management.d.ts +1 -1
  60. package/dist/_types/contracts/agent-execution-lifecycle.d.ts +55 -43
  61. package/dist/_types/contracts/agent-execution-oauth.d.ts +2 -2
  62. package/dist/_types/contracts/agent-execution-registration.d.ts +59 -15
  63. package/dist/_types/contracts/agent-execution-selection.d.ts +7 -7
  64. package/dist/_types/contracts/agent-host-contract.d.ts +189 -0
  65. package/dist/_types/contracts/agent-host-execution.d.ts +92 -61
  66. package/dist/_types/contracts/agent-host-generic-transport.d.ts +4 -4
  67. package/dist/_types/contracts/agent-host-legacy-release.d.ts +31 -0
  68. package/dist/_types/contracts/agent-host-protocol.d.ts +71 -0
  69. package/dist/_types/contracts/agent-host-wire.d.ts +263 -0
  70. package/dist/_types/contracts/agent-host.d.ts +126 -65
  71. package/dist/_types/contracts/artifact-discovery.d.ts +16 -16
  72. package/dist/_types/contracts/composition-observation.d.ts +1 -1
  73. package/dist/_types/contracts/delivery-operations.d.ts +1 -1
  74. package/dist/_types/contracts/delivery-summary.d.ts +1 -1
  75. package/dist/_types/contracts/device-onboarding.d.ts +29 -0
  76. package/dist/_types/contracts/device-render.d.ts +26 -0
  77. package/dist/_types/contracts/exploration-recommendation.d.ts +2 -2
  78. package/dist/_types/contracts/federation-result.d.ts +239 -0
  79. package/dist/_types/contracts/final-ready.d.ts +2 -2
  80. package/dist/_types/contracts/final-render.d.ts +2 -2
  81. package/dist/_types/contracts/index.d.ts +6 -0
  82. package/dist/_types/contracts/interface/execution-output.d.ts +9 -6
  83. package/dist/_types/contracts/interface/production-snapshot.d.ts +5 -5
  84. package/dist/_types/contracts/keyframe-generation.d.ts +2 -2
  85. package/dist/_types/contracts/keyframe-review.d.ts +1 -1
  86. package/dist/_types/contracts/lifecycle-event-projections.d.ts +17 -2
  87. package/dist/_types/contracts/lifecycle-events.d.ts +54 -2
  88. package/dist/_types/contracts/local-execution/device-inventory.d.ts +28 -2
  89. package/dist/_types/contracts/local-execution/index.d.ts +1 -0
  90. package/dist/_types/contracts/local-execution/ipc.d.ts +6 -6
  91. package/dist/_types/contracts/local-execution/library.d.ts +2 -2
  92. package/dist/_types/contracts/local-execution/processor.d.ts +7 -7
  93. package/dist/_types/contracts/local-execution/workspace.d.ts +1 -1
  94. package/dist/_types/contracts/media-observation.d.ts +3 -3
  95. package/dist/_types/contracts/native-tool-authority.d.ts +25 -21
  96. package/dist/_types/contracts/native-tool-execution.d.ts +60 -39
  97. package/dist/_types/contracts/navigation-context.d.ts +4 -4
  98. package/dist/_types/contracts/navigation-groups.d.ts +1 -1
  99. package/dist/_types/contracts/navigation.d.ts +5 -5
  100. package/dist/_types/contracts/production-feedback.d.ts +452 -0
  101. package/dist/_types/contracts/repair-strategy.d.ts +1 -1
  102. package/dist/_types/contracts/review-intelligence-final-output.d.ts +1 -1
  103. package/dist/_types/contracts/rough-cut.d.ts +1 -1
  104. package/dist/_types/contracts/shares.d.ts +135 -0
  105. package/dist/_types/contracts/speech.d.ts +5 -5
  106. package/dist/_types/contracts/temporal-evidence-operation.d.ts +1 -1
  107. package/dist/_types/contracts/video-generation.d.ts +2 -2
  108. package/dist/_types/contracts/video-review.d.ts +1 -1
  109. package/dist/_types/contracts/visual-exploration.d.ts +2 -2
  110. package/dist/_types/contracts/voice-profile/contracts.d.ts +4 -4
  111. package/dist/_types/contracts/workspace.d.ts +21 -0
  112. package/dist/_types/sdk/local-runtime/workspace.d.ts +4 -4
  113. package/dist/_types/sdk/local-runtime-client.d.ts +3 -3
  114. package/dist/entry.js +1 -1
  115. package/dist/local-management.js +1 -1
  116. package/dist/local-navigation.js +1 -1
  117. package/dist/native/helper.exe +0 -0
  118. package/dist/native/helper.json +1 -0
  119. package/package.json +1 -1
  120. package/dist/_chunks/chunk-2AI3WF2O.js +0 -1
  121. package/dist/_chunks/chunk-5DY7LSZZ.js +0 -1
  122. package/dist/_chunks/chunk-6LU6GJKW.js +0 -1
  123. package/dist/_chunks/chunk-77IAHNM2.js +0 -1
  124. package/dist/_chunks/chunk-FU3524Z6.js +0 -1
  125. package/dist/_chunks/chunk-HY7NXJYX.js +0 -1
  126. package/dist/_chunks/chunk-KB2GVAN7.js +0 -1
  127. package/dist/_chunks/chunk-PDQYFIQQ.js +0 -1
  128. package/dist/_chunks/chunk-PUNG4ND7.js +0 -1
  129. package/dist/_chunks/chunk-RK2P3UVF.js +0 -1
  130. package/dist/_chunks/chunk-SV3NF7GO.js +0 -1
  131. package/dist/_chunks/chunk-TLPI6P7L.js +0 -1
  132. package/dist/_chunks/chunk-U7ECMITP.js +0 -1
  133. package/dist/_chunks/chunk-ZRSYOFMX.js +0 -1
  134. package/dist/_chunks/device-preflight-LHFLPVAB.js +0 -1
  135. package/dist/_chunks/http-profile-NIQDCFPU.js +0 -1
  136. package/dist/_chunks/local-main-227MNGEC.js +0 -1
  137. package/dist/_chunks/main-W6NNZFLK.js +0 -2
  138. package/dist/_chunks/mcp-EXQ5UAHB.js +0 -1
  139. package/dist/_chunks/oauth-HC6TI7HB.js +0 -1
  140. package/dist/_chunks/src-OIY5TBQT.js +0 -1
  141. package/dist/_chunks/workspace-main-Y7ZVBRJJ.js +0 -1
  142. package/dist/native/Bootstrap.ps1 +0 -90
  143. package/dist/native/JobNative.cs +0 -137
  144. package/dist/native/JobRunner.cs +0 -381
  145. package/dist/native/NativeMain.cs +0 -161
  146. package/dist/native/PipeBridge.cs +0 -260
  147. package/dist/native/PrivateAccess.cs +0 -152
@@ -1,137 +0,0 @@
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 void Budget(IntPtr job, double cores, ulong memory)
108
- {
109
- var limits = new ExtendedLimits();
110
- limits.basic.flags = 0x2000 | 0x200 | 8 | 0x20;
111
- limits.jobMemory = new UIntPtr(memory);
112
- limits.basic.active = 64;
113
- limits.basic.priority = 0x4000;
114
- Set(job, 9, limits);
115
- Set(job, 15, new CpuLimits { flags = 5, rate = (uint)Math.Min(10000, Math.Max(1, cores * 10000 / Environment.ProcessorCount)) });
116
- }
117
- public static uint[] Processes(IntPtr job)
118
- {
119
- int size = 8 + 64 * IntPtr.Size;
120
- IntPtr memory = Marshal.AllocHGlobal(size);
121
- try
122
- {
123
- uint length;
124
- if (!QueryInformationJobObject(job, 3, memory, (uint)size, out length))
125
- throw new Exception("JOB_INSPECT");
126
- int count = Marshal.ReadInt32(memory, 4);
127
- if (count < 0 || count > 64)
128
- throw new Exception("JOB_LIMIT");
129
- var ids = new uint[count];
130
- for (int i = 0; i < count; i++)
131
- ids[i] = unchecked((uint)Marshal.ReadIntPtr(memory, 8 + i * IntPtr.Size).ToInt64());
132
- return ids;
133
- }
134
- finally { Marshal.FreeHGlobal(memory); }
135
- }
136
- }
137
- }
@@ -1,381 +0,0 @@
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
- }
@@ -1,161 +0,0 @@
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
- }