@native-sdk/cli 0.8.3 → 0.9.0

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 (188) hide show
  1. package/build/app.zig +905 -61
  2. package/build.zig +674 -373
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +6 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +455 -3
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  12. package/packages/core/scripts/run_external_core_compiler.mjs +77 -6
  13. package/packages/core/scripts/run_external_service_compiler.mjs +240 -0
  14. package/packages/core/scripts/stage_external_core.mjs +9 -1
  15. package/packages/core/scripts/stage_external_services.mjs +172 -0
  16. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  17. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  18. package/packages/core/sdk/core.d.ts +214 -2
  19. package/packages/core/sdk/core.ts +715 -42
  20. package/packages/core/sdk/events.d.ts +50 -0
  21. package/packages/core/sdk/events.ts +75 -0
  22. package/packages/core/src/checker.ts +528 -15
  23. package/packages/core/src/cli.ts +143 -3
  24. package/packages/core/src/contract.ts +26 -5
  25. package/packages/core/src/devhost.ts +1849 -18
  26. package/packages/core/src/devhost_journal.mjs +181 -0
  27. package/packages/core/src/devhost_resolver.mjs +17 -1
  28. package/packages/core/src/devhost_service_worker.mjs +90 -0
  29. package/packages/core/src/diagnostics.ts +84 -18
  30. package/packages/core/src/frontend.ts +204 -34
  31. package/packages/core/src/modules.ts +129 -80
  32. package/packages/core/src/service_contract.ts +597 -0
  33. package/packages/core/src/sqlite_cli.ts +93 -0
  34. package/packages/core/src/sqlite_codegen.ts +806 -0
  35. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  36. package/packages/core/src/typed_ast.ts +36 -8
  37. package/skill-data/core/SKILL.md +4 -2
  38. package/skill-data/core/references/project-anatomy.md +3 -2
  39. package/skill-data/core/references/web-engines-packaging-debugging.md +3 -1
  40. package/skill-data/native-ui/SKILL.md +55 -8
  41. package/skill-data/ts-core/SKILL.md +92 -40
  42. package/skill-data/ts-services/SKILL.md +126 -0
  43. package/skill-data/ts-services/references/service-surface.md +603 -0
  44. package/skill-data/zig/SKILL.md +1 -1
  45. package/skills/native-sdk/SKILL.md +1 -1
  46. package/src/app_runner/no_migrations.zig +3 -0
  47. package/src/app_runner/no_services.zig +20 -0
  48. package/src/app_runner/root.zig +104 -4
  49. package/src/app_runner/ts_core_main.zig +268 -4
  50. package/src/automation/snapshot.zig +23 -5
  51. package/src/embed/app_exports.zig +11 -1
  52. package/src/embed/c_api.zig +48 -2
  53. package/src/embed/conversions.zig +4 -5
  54. package/src/embed/host.zig +115 -1
  55. package/src/embed/root.zig +7 -0
  56. package/src/embed/tests.zig +213 -0
  57. package/src/embed/types.zig +51 -0
  58. package/src/embed/ui_host.zig +121 -5
  59. package/src/platform/android/NativeSdkActivity.java +131 -0
  60. package/src/platform/android/android_host.c +182 -1
  61. package/src/platform/android/native_sdk_app.h +17 -0
  62. package/src/platform/ios/native_sdk_app.h +17 -0
  63. package/src/platform/ios/uikit_host.m +115 -0
  64. package/src/platform/linux/cef_host.cpp +1 -1
  65. package/src/platform/linux/gtk_host.c +89 -17
  66. package/src/platform/linux/gtk_host.h +3 -0
  67. package/src/platform/linux/root.zig +41 -18
  68. package/src/platform/macos/appkit_host.h +26 -3
  69. package/src/platform/macos/appkit_host.m +1051 -129
  70. package/src/platform/macos/capture_info_plist.c +25 -0
  71. package/src/platform/macos/cef_host.mm +270 -36
  72. package/src/platform/macos/root.zig +312 -34
  73. package/src/platform/null_platform.zig +281 -19
  74. package/src/platform/null_platform_tests.zig +74 -0
  75. package/src/platform/root.zig +16 -0
  76. package/src/platform/types.zig +279 -15
  77. package/src/platform/windows/root.zig +243 -21
  78. package/src/platform/windows/webview2_host.cpp +464 -46
  79. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  80. package/src/primitives/app_manifest/root.zig +4 -0
  81. package/src/primitives/app_manifest/tests.zig +3 -0
  82. package/src/primitives/app_manifest/types.zig +34 -0
  83. package/src/primitives/app_manifest/validation.zig +19 -1
  84. package/src/primitives/canvas/code_tests.zig +9 -9
  85. package/src/primitives/canvas/events.zig +12 -11
  86. package/src/primitives/canvas/frame.zig +44 -9
  87. package/src/primitives/canvas/icons/mic.svg +1 -0
  88. package/src/primitives/canvas/icons.zig +2 -0
  89. package/src/primitives/canvas/root.zig +8 -0
  90. package/src/primitives/canvas/text_span_tests.zig +39 -0
  91. package/src/primitives/canvas/ui.zig +23 -4
  92. package/src/primitives/canvas/ui_markup.zig +15 -0
  93. package/src/primitives/canvas/ui_markup_compiled.zig +9 -0
  94. package/src/primitives/canvas/ui_markup_compiled_tests.zig +1 -1
  95. package/src/primitives/canvas/ui_markup_tests.zig +5 -0
  96. package/src/primitives/canvas/ui_markup_view.zig +9 -0
  97. package/src/primitives/canvas/ui_markup_view_tests.zig +9 -6
  98. package/src/primitives/canvas/ui_schema.zig +19 -10
  99. package/src/primitives/canvas/ui_schema_tests.zig +5 -3
  100. package/src/primitives/canvas/ui_tests.zig +18 -4
  101. package/src/primitives/canvas/widget_invalidation.zig +9 -2
  102. package/src/primitives/canvas/widget_render.zig +296 -114
  103. package/src/primitives/canvas/widget_runtime_tests.zig +133 -0
  104. package/src/primitives/canvas/widget_text_input.zig +10 -10
  105. package/src/primitives/canvas/widget_tree.zig +1 -1
  106. package/src/primitives/canvas/widgets.zig +29 -5
  107. package/src/root.zig +56 -0
  108. package/src/runtime/api.zig +11 -0
  109. package/src/runtime/automation_snapshot.zig +4 -0
  110. package/src/runtime/automation_widget_dispatch.zig +1 -0
  111. package/src/runtime/bridge_payload.zig +2 -0
  112. package/src/runtime/bridge_permission_tests.zig +23 -2
  113. package/src/runtime/bridge_responses.zig +3 -1
  114. package/src/runtime/canvas_frame.zig +31 -13
  115. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  116. package/src/runtime/canvas_frame_invalidation_tests.zig +35 -10
  117. package/src/runtime/canvas_widget_anchored_tests.zig +83 -0
  118. package/src/runtime/canvas_widget_events.zig +69 -24
  119. package/src/runtime/canvas_widget_runtime.zig +101 -6
  120. package/src/runtime/canvas_widget_scroll_driver_tests.zig +47 -4
  121. package/src/runtime/canvas_widget_scroll_drivers.zig +3 -3
  122. package/src/runtime/canvas_widget_semantics_tests.zig +2 -0
  123. package/src/runtime/canvas_widget_split_tree_tests.zig +228 -0
  124. package/src/runtime/canvas_widget_state.zig +6 -1
  125. package/src/runtime/canvas_widget_text_tests.zig +112 -3
  126. package/src/runtime/clock.zig +13 -1
  127. package/src/runtime/core.zig +133 -1
  128. package/src/runtime/credentials_store.zig +115 -0
  129. package/src/runtime/effects.zig +2568 -75
  130. package/src/runtime/effects_audio_capture_tests.zig +251 -0
  131. package/src/runtime/effects_credentials_tests.zig +332 -0
  132. package/src/runtime/effects_host_tests.zig +208 -1
  133. package/src/runtime/effects_relational_tests.zig +314 -0
  134. package/src/runtime/effects_store_tests.zig +211 -0
  135. package/src/runtime/flow.zig +14 -1
  136. package/src/runtime/gpu_surface_events.zig +6 -1
  137. package/src/runtime/native_command_event_tests.zig +42 -0
  138. package/src/runtime/persist_store.zig +666 -0
  139. package/src/runtime/record_store.zig +788 -0
  140. package/src/runtime/relational_store.zig +854 -0
  141. package/src/runtime/root.zig +52 -0
  142. package/src/runtime/runtime_event_tests.zig +70 -0
  143. package/src/runtime/service_host.zig +711 -0
  144. package/src/runtime/service_pool.zig +1314 -0
  145. package/src/runtime/session_blobs.zig +1 -1
  146. package/src/runtime/session_journal.zig +102 -0
  147. package/src/runtime/session_record.zig +177 -0
  148. package/src/runtime/session_replay.zig +109 -4
  149. package/src/runtime/shell_layout.zig +1 -0
  150. package/src/runtime/shell_layout_tests.zig +120 -0
  151. package/src/runtime/sqlite_engine.zig +474 -0
  152. package/src/runtime/state.zig +6 -0
  153. package/src/runtime/system_services.zig +49 -10
  154. package/src/runtime/tests.zig +5 -0
  155. package/src/runtime/ts_core_host.zig +1189 -118
  156. package/src/runtime/ts_core_host_tests.zig +638 -11
  157. package/src/runtime/ts_ui_app.zig +537 -1
  158. package/src/runtime/ui_app.zig +160 -19
  159. package/src/runtime/ui_app_tests.zig +203 -5
  160. package/src/runtime/validation.zig +22 -0
  161. package/src/runtime/view.zig +11 -0
  162. package/src/runtime/view_widget_scroll.zig +56 -5
  163. package/src/runtime/view_widget_text.zig +24 -5
  164. package/src/runtime/view_widget_tree.zig +1 -1
  165. package/src/runtime/window_storage.zig +1 -0
  166. package/src/runtime/window_view_runtime.zig +2 -3
  167. package/src/runtime/window_views.zig +19 -0
  168. package/src/tooling/android.zig +21 -16
  169. package/src/tooling/db.zig +160 -0
  170. package/src/tooling/ios.zig +7 -1
  171. package/src/tooling/manifest.zig +1248 -2
  172. package/src/tooling/package.zig +953 -6
  173. package/src/tooling/raw_manifest.zig +65 -0
  174. package/src/tooling/root.zig +1 -0
  175. package/src/tooling/templates.zig +216 -4
  176. package/src/tooling/ts_core.zig +283 -17
  177. package/src/tooling/verbs.zig +7 -0
  178. package/third_party/sqlite/README.md +13 -0
  179. package/third_party/sqlite/sqlite3.c +269649 -0
  180. package/third_party/sqlite/sqlite3.h +14349 -0
  181. package/tools/corewire/core_abi.zig +14 -2
  182. package/tools/corewire/emit.zig +98 -29
  183. package/tools/corewire/emit_facade.zig +414 -23
  184. package/tools/corewire/emit_profile.zig +6 -2
  185. package/tools/corewire/emit_service.zig +924 -0
  186. package/tools/corewire/main.zig +122 -0
  187. package/tools/corewire/service_contract.zig +250 -0
  188. package/tools/corewire/sidecar.zig +26 -15
@@ -0,0 +1,711 @@
1
+ //! Out-of-process TypeScript service carrier.
2
+ //!
3
+ //! One worker thread owns one plain-scriptc child and the framed stdio
4
+ //! protocol. HostCallBinding callbacks only copy/enqueue on the loop thread;
5
+ //! completions are polled back onto that thread by Effects and therefore keep
6
+ //! its journaling/replay boundary unchanged. The child starts lazily on the
7
+ //! first real request, so replay never needs or starts it.
8
+
9
+ const std = @import("std");
10
+ const builtin = @import("builtin");
11
+ const effects = @import("effects.zig");
12
+ const platform = @import("../platform/root.zig");
13
+
14
+ const max_frame_bytes: usize = 16 * 1024 * 1024;
15
+ const transport_error = "{\"kind\":\"service_host\",\"message\":\"service host exited or rejected the request\"}";
16
+ const timeout_error = "{\"kind\":\"timeout\",\"message\":\"service request timed out\"}";
17
+
18
+ /// A service operation is synchronous inside the child. Bound the whole
19
+ /// request from admission through queueing, lazy spawn, hello, exchange, and
20
+ /// response; otherwise one hung operation would strand every request behind it.
21
+ pub const default_request_timeout_ms: u32 = 30_000;
22
+ pub const cooperative_cancel_grace_ms: u32 = 100;
23
+
24
+ /// The generated runner and tests share this one authority allowlist. Keeping
25
+ /// it beside the carrier prevents a generated-main copy from silently gaining
26
+ /// an ambient variable when the runtime policy changes.
27
+ pub fn environmentVariableAllowed(name: []const u8) bool {
28
+ return environmentVariableAllowedForOs(name, builtin.os.tag);
29
+ }
30
+
31
+ fn environmentVariableAllowedForOs(name: []const u8, os_tag: std.Target.Os.Tag) bool {
32
+ const portable = [_][]const u8{
33
+ "PATH", "HOME", "USER", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "LC_CTYPE", "TZ",
34
+ "SSL_CERT_FILE", "SSL_CERT_DIR", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY",
35
+ };
36
+ for (portable) |candidate| {
37
+ if (if (os_tag == .windows) std.ascii.eqlIgnoreCase(name, candidate) else std.mem.eql(u8, name, candidate)) return true;
38
+ }
39
+ if (os_tag == .windows) {
40
+ const windows = [_][]const u8{ "USERPROFILE", "USERNAME", "SystemRoot", "COMSPEC", "PATHEXT" };
41
+ for (windows) |candidate| if (std.ascii.eqlIgnoreCase(name, candidate)) return true;
42
+ }
43
+ return false;
44
+ }
45
+
46
+ pub fn ServiceHost(comptime Registry: type) type {
47
+ return struct {
48
+ const Self = @This();
49
+
50
+ const Request = struct {
51
+ key: u64,
52
+ request_id: u32,
53
+ operation: u16,
54
+ payload: []u8,
55
+ answer: bool,
56
+ deadline: std.Io.Clock.Timestamp,
57
+ channel: ?effects.ChannelHandle,
58
+ };
59
+ const Result = struct { key: u64, ok: bool, bytes: []u8 };
60
+
61
+ allocator: std.mem.Allocator,
62
+ io: std.Io,
63
+ executable: []const u8,
64
+ cwd: []const u8,
65
+ environ: ?*const std.process.Environ.Map,
66
+ mutex: std.Io.Mutex = .init,
67
+ condition: std.Io.Condition = .init,
68
+ requests: std.ArrayList(Request) = .empty,
69
+ results: std.ArrayList(Result) = .empty,
70
+ last_polled: ?[]u8 = null,
71
+ services: ?platform.PlatformServices = null,
72
+ channels: ?effects.HostChannelBinding = null,
73
+ worker_thread: ?std.Thread = null,
74
+ shutting_down: bool = false,
75
+ next_request_id: u32 = 1,
76
+ active_key: ?u64 = null,
77
+ child_id: ?std.process.Child.Id = null,
78
+ child_reaping: bool = false,
79
+ request_timeout_ms: u32 = default_request_timeout_ms,
80
+ active_request_id: ?u32 = null,
81
+ active_cancelled: bool = false,
82
+ active_cancel_path: ?[]const u8 = null,
83
+ active_cancel_signal: ?*std.Io.Event = null,
84
+
85
+ pub fn init(
86
+ allocator: std.mem.Allocator,
87
+ io: std.Io,
88
+ executable: []const u8,
89
+ cwd: []const u8,
90
+ environ: ?*const std.process.Environ.Map,
91
+ ) Self {
92
+ return .{ .allocator = allocator, .io = io, .executable = executable, .cwd = cwd, .environ = environ };
93
+ }
94
+
95
+ pub fn binding(self: *Self) effects.HostCallBinding {
96
+ return .{
97
+ .context = self,
98
+ .send_fn = send,
99
+ .request_fn = request,
100
+ .cancel_fn = cancel,
101
+ .reject_duplicate_keys = true,
102
+ .poll_fn = poll,
103
+ .pending_fn = pending,
104
+ .bind_services_fn = bindServices,
105
+ .bind_channels_fn = bindChannels,
106
+ .shutdown_fn = shutdown,
107
+ };
108
+ }
109
+
110
+ /// Configure the carrier while no exchange is active. Primarily
111
+ /// useful to keep deterministic timeout tests fast; production uses
112
+ /// the conservative default above.
113
+ pub fn setRequestTimeoutMs(self: *Self, timeout_ms: u32) void {
114
+ std.debug.assert(timeout_ms > 0);
115
+ self.mutex.lockUncancelable(self.io);
116
+ defer self.mutex.unlock(self.io);
117
+ std.debug.assert(self.active_request_id == null);
118
+ self.request_timeout_ms = timeout_ms;
119
+ }
120
+
121
+ /// Supervision/diagnostic visibility. The handle is only a snapshot;
122
+ /// callers must tolerate the child exiting immediately after return.
123
+ pub fn processId(self: *Self) ?std.process.Child.Id {
124
+ self.mutex.lockUncancelable(self.io);
125
+ defer self.mutex.unlock(self.io);
126
+ return self.child_id;
127
+ }
128
+
129
+ /// Safe to call after Effects shutdown; repeated shutdown is inert.
130
+ pub fn deinit(self: *Self) void {
131
+ shutdown(self);
132
+ self.mutex.lockUncancelable(self.io);
133
+ defer self.mutex.unlock(self.io);
134
+ for (self.requests.items) |entry| self.allocator.free(entry.payload);
135
+ self.requests.deinit(self.allocator);
136
+ for (self.results.items) |entry| self.allocator.free(entry.bytes);
137
+ self.results.deinit(self.allocator);
138
+ if (self.last_polled) |bytes| self.allocator.free(bytes);
139
+ self.last_polled = null;
140
+ }
141
+
142
+ fn send(context: *anyopaque, name: []const u8, payload: []const u8) void {
143
+ const self: *Self = @ptrCast(@alignCast(context));
144
+ const operation_index = Registry.indexOf(name) orelse return;
145
+ const operation = Registry.operationAt(operation_index) orelse return;
146
+ self.enqueue(0, operation.index, payload, false, operation.deadline_ms orelse self.request_timeout_ms, null);
147
+ }
148
+
149
+ fn request(context: *anyopaque, name: []const u8, key: u64, payload: []const u8) void {
150
+ const self: *Self = @ptrCast(@alignCast(context));
151
+ const operation_index = Registry.indexOf(name) orelse {
152
+ self.stageStatic(key, false, transport_error);
153
+ return;
154
+ };
155
+ const operation = Registry.operationAt(operation_index) orelse {
156
+ self.stageStatic(key, false, transport_error);
157
+ return;
158
+ };
159
+ var request_payload = payload;
160
+ var channel: ?effects.ChannelHandle = null;
161
+ if (operation.streaming) {
162
+ if (payload.len < 8) {
163
+ self.stageStatic(key, false, transport_error);
164
+ return;
165
+ }
166
+ const channel_number = @as(f64, @bitCast(readU64(payload, 0)));
167
+ if (!std.math.isFinite(channel_number) or channel_number < 1 or channel_number >= 9_007_199_254_740_992 or @floor(channel_number) != channel_number) {
168
+ self.stageStatic(key, false, transport_error);
169
+ return;
170
+ }
171
+ const channel_key: u64 = @intFromFloat(channel_number);
172
+ const channel_binding = self.channels orelse {
173
+ self.stageStatic(key, false, transport_error);
174
+ return;
175
+ };
176
+ channel = channel_binding.acquire_fn(channel_binding.context, channel_key) orelse {
177
+ self.stageStatic(key, false, transport_error);
178
+ return;
179
+ };
180
+ request_payload = payload[8..];
181
+ }
182
+ self.enqueue(key, operation.index, request_payload, true, operation.deadline_ms orelse self.request_timeout_ms, channel);
183
+ }
184
+
185
+ fn cancel(context: *anyopaque, key: u64) void {
186
+ const self: *Self = @ptrCast(@alignCast(context));
187
+ self.mutex.lockUncancelable(self.io);
188
+ var index: usize = 0;
189
+ while (index < self.requests.items.len) {
190
+ if (self.requests.items[index].answer and self.requests.items[index].key == key) {
191
+ const removed = self.requests.orderedRemove(index);
192
+ self.allocator.free(removed.payload);
193
+ } else index += 1;
194
+ }
195
+ index = 0;
196
+ while (index < self.results.items.len) {
197
+ if (self.results.items[index].key == key) {
198
+ const removed = self.results.orderedRemove(index);
199
+ self.allocator.free(removed.bytes);
200
+ } else index += 1;
201
+ }
202
+ const kill = self.active_key != null and self.active_key.? == key;
203
+ if (kill) {
204
+ self.active_cancelled = true;
205
+ self.publishCancellationLocked();
206
+ }
207
+ self.mutex.unlock(self.io);
208
+ }
209
+
210
+ fn bindServices(context: *anyopaque, services: *const platform.PlatformServices) void {
211
+ const self: *Self = @ptrCast(@alignCast(context));
212
+ self.mutex.lockUncancelable(self.io);
213
+ self.services = services.*;
214
+ self.mutex.unlock(self.io);
215
+ }
216
+
217
+ fn bindChannels(context: *anyopaque, channels: effects.HostChannelBinding) void {
218
+ const self: *Self = @ptrCast(@alignCast(context));
219
+ self.channels = channels;
220
+ }
221
+
222
+ fn pending(context: *anyopaque) bool {
223
+ const self: *Self = @ptrCast(@alignCast(context));
224
+ self.mutex.lockUncancelable(self.io);
225
+ defer self.mutex.unlock(self.io);
226
+ return self.results.items.len > 0;
227
+ }
228
+
229
+ fn poll(context: *anyopaque) ?effects.HostCallCompletion {
230
+ const self: *Self = @ptrCast(@alignCast(context));
231
+ self.mutex.lockUncancelable(self.io);
232
+ defer self.mutex.unlock(self.io);
233
+ if (self.last_polled) |bytes| self.allocator.free(bytes);
234
+ self.last_polled = null;
235
+ if (self.results.items.len == 0) return null;
236
+ const result = self.results.orderedRemove(0);
237
+ self.last_polled = result.bytes;
238
+ return .{ .key = result.key, .ok = result.ok, .bytes = result.bytes };
239
+ }
240
+
241
+ fn shutdown(context: *anyopaque) void {
242
+ const self: *Self = @ptrCast(@alignCast(context));
243
+ self.mutex.lockUncancelable(self.io);
244
+ if (self.shutting_down) {
245
+ const thread = self.worker_thread;
246
+ self.mutex.unlock(self.io);
247
+ if (thread) |value| value.join();
248
+ self.mutex.lockUncancelable(self.io);
249
+ self.worker_thread = null;
250
+ self.mutex.unlock(self.io);
251
+ return;
252
+ }
253
+ self.shutting_down = true;
254
+ self.killPublishedChildLocked();
255
+ self.condition.broadcast(self.io);
256
+ const thread = self.worker_thread;
257
+ self.mutex.unlock(self.io);
258
+ if (thread) |value| value.join();
259
+ self.mutex.lockUncancelable(self.io);
260
+ self.worker_thread = null;
261
+ self.services = null;
262
+ self.mutex.unlock(self.io);
263
+ }
264
+
265
+ fn enqueue(self: *Self, key: u64, operation: u16, payload: []const u8, answer: bool, timeout_ms: u32, channel: ?effects.ChannelHandle) void {
266
+ const copy = self.allocator.dupe(u8, payload) catch {
267
+ if (answer) self.stageStatic(key, false, transport_error);
268
+ return;
269
+ };
270
+ const deadline = std.Io.Clock.Timestamp.fromNow(self.io, .{
271
+ .raw = std.Io.Duration.fromMilliseconds(timeout_ms),
272
+ .clock = .awake,
273
+ });
274
+ self.mutex.lockUncancelable(self.io);
275
+ if (self.shutting_down) {
276
+ self.mutex.unlock(self.io);
277
+ self.allocator.free(copy);
278
+ if (answer) self.stageStatic(key, false, transport_error);
279
+ return;
280
+ }
281
+ const request_id = self.next_request_id;
282
+ self.next_request_id +%= 1;
283
+ if (self.next_request_id == 0) self.next_request_id = 1;
284
+ self.requests.append(self.allocator, .{
285
+ .key = key,
286
+ .request_id = request_id,
287
+ .operation = operation,
288
+ .payload = copy,
289
+ .answer = answer,
290
+ .deadline = deadline,
291
+ .channel = channel,
292
+ }) catch {
293
+ self.mutex.unlock(self.io);
294
+ self.allocator.free(copy);
295
+ if (answer) self.stageStatic(key, false, transport_error);
296
+ return;
297
+ };
298
+ if (self.worker_thread == null) {
299
+ self.worker_thread = std.Thread.spawn(.{}, workerMain, .{self}) catch null;
300
+ if (self.worker_thread == null) {
301
+ const removed = self.requests.pop().?;
302
+ self.mutex.unlock(self.io);
303
+ self.allocator.free(removed.payload);
304
+ if (answer) self.stageStatic(key, false, transport_error);
305
+ return;
306
+ }
307
+ }
308
+ self.condition.signal(self.io);
309
+ self.mutex.unlock(self.io);
310
+ }
311
+
312
+ fn stageStatic(self: *Self, key: u64, ok: bool, bytes: []const u8) void {
313
+ const copy = self.allocator.dupe(u8, bytes) catch return;
314
+ self.stageOwned(.{ .key = key, .ok = ok, .bytes = copy });
315
+ }
316
+
317
+ fn stageOwned(self: *Self, result: Result) void {
318
+ self.mutex.lockUncancelable(self.io);
319
+ if (self.shutting_down) {
320
+ self.mutex.unlock(self.io);
321
+ self.allocator.free(result.bytes);
322
+ return;
323
+ }
324
+ self.results.append(self.allocator, result) catch {
325
+ self.mutex.unlock(self.io);
326
+ self.allocator.free(result.bytes);
327
+ return;
328
+ };
329
+ const services = self.services;
330
+ self.mutex.unlock(self.io);
331
+ if (services) |bound| bound.wake() catch {};
332
+ }
333
+
334
+ fn workerMain(self: *Self) void {
335
+ var child: ?std.process.Child = null;
336
+ defer self.retireChild(&child);
337
+ while (true) {
338
+ self.mutex.lockUncancelable(self.io);
339
+ while (!self.shutting_down and self.requests.items.len == 0) self.condition.waitUncancelable(self.io, &self.mutex);
340
+ if (self.shutting_down) {
341
+ self.mutex.unlock(self.io);
342
+ return;
343
+ }
344
+ const work = self.requests.orderedRemove(0);
345
+ self.active_key = if (work.answer) work.key else null;
346
+ self.active_request_id = work.request_id;
347
+ self.active_cancelled = false;
348
+ self.mutex.unlock(self.io);
349
+
350
+ var completion: ?Result = null;
351
+ var preserve_child = false;
352
+ const response = self.exchange(&child, work) catch |err| response: {
353
+ preserve_child = err == error.ServiceTimedOutCooperative or err == error.ServiceDeadlineExpired;
354
+ if (work.answer) {
355
+ const bytes = if (err == error.ServiceTimedOut or err == error.ServiceTimedOutCooperative or err == error.ServiceDeadlineExpired) timeout_error else transport_error;
356
+ if (self.allocator.dupe(u8, bytes)) |copy| {
357
+ completion = .{ .key = work.key, .ok = false, .bytes = copy };
358
+ } else |_| {}
359
+ }
360
+ break :response null;
361
+ };
362
+ if (work.answer) {
363
+ if (response) |result| completion = .{ .key = work.key, .ok = result.ok, .bytes = result.bytes };
364
+ } else if (response) |result| {
365
+ self.allocator.free(result.bytes);
366
+ }
367
+ self.allocator.free(work.payload);
368
+ self.mutex.lockUncancelable(self.io);
369
+ const cancelled = self.active_request_id == work.request_id and self.active_cancelled;
370
+ self.active_key = null;
371
+ self.active_request_id = null;
372
+ self.active_cancelled = false;
373
+ self.active_cancel_path = null;
374
+ self.active_cancel_signal = null;
375
+ var services: ?platform.PlatformServices = null;
376
+ if (completion) |result| {
377
+ if (cancelled or self.shutting_down) {
378
+ self.allocator.free(result.bytes);
379
+ } else if (self.results.append(self.allocator, result)) |_| {
380
+ services = self.services;
381
+ } else |_| {
382
+ self.allocator.free(result.bytes);
383
+ }
384
+ }
385
+ self.mutex.unlock(self.io);
386
+ if (services) |bound| bound.wake() catch {};
387
+ if (response == null and !preserve_child) self.retireChild(&child);
388
+ }
389
+ }
390
+
391
+ const ExchangeResult = struct { ok: bool, bytes: []u8 };
392
+
393
+ const DeadlineWatch = struct {
394
+ host: *Self,
395
+ request_id: u32,
396
+ done: *std.Io.Event,
397
+ cancel_signal: *std.Io.Event,
398
+ deadline: std.Io.Clock.Timestamp,
399
+ timed_out: bool = false,
400
+ hard_killed: bool = false,
401
+
402
+ fn run(watch: *DeadlineWatch) void {
403
+ while (!watch.done.isSet()) {
404
+ watch.cancel_signal.waitTimeout(watch.host.io, .{ .deadline = watch.deadline }) catch |err| switch (err) {
405
+ error.Canceled => return,
406
+ error.Timeout => {
407
+ // Futex waits may wake spuriously. Only the actual
408
+ // monotonic deadline is authority to kill a child.
409
+ const now = std.Io.Clock.Timestamp.now(watch.host.io, .awake);
410
+ if (!std.Io.Clock.Timestamp.compare(now, .gte, watch.deadline)) continue;
411
+ watch.host.mutex.lockUncancelable(watch.host.io);
412
+ if (watch.host.active_request_id == watch.request_id and !watch.done.isSet()) {
413
+ watch.timed_out = true;
414
+ watch.host.publishCancellationLocked();
415
+ }
416
+ watch.host.mutex.unlock(watch.host.io);
417
+ watch.hardKillAfterGrace();
418
+ return;
419
+ },
420
+ };
421
+ if (!watch.done.isSet()) watch.hardKillAfterGrace();
422
+ return;
423
+ }
424
+ }
425
+
426
+ fn hardKillAfterGrace(watch: *DeadlineWatch) void {
427
+ const grace: std.Io.Clock.Duration = .{
428
+ .raw = std.Io.Duration.fromMilliseconds(cooperative_cancel_grace_ms),
429
+ .clock = .awake,
430
+ };
431
+ const deadline = std.Io.Clock.Timestamp.fromNow(watch.host.io, grace);
432
+ while (!watch.done.isSet()) {
433
+ watch.done.waitTimeout(watch.host.io, .{ .deadline = deadline }) catch |err| switch (err) {
434
+ error.Canceled => return,
435
+ error.Timeout => {
436
+ const now = std.Io.Clock.Timestamp.now(watch.host.io, .awake);
437
+ if (!std.Io.Clock.Timestamp.compare(now, .gte, deadline)) continue;
438
+ watch.host.mutex.lockUncancelable(watch.host.io);
439
+ if (watch.host.active_request_id == watch.request_id and !watch.done.isSet()) {
440
+ watch.hard_killed = true;
441
+ watch.host.killPublishedChildLocked();
442
+ }
443
+ watch.host.mutex.unlock(watch.host.io);
444
+ return;
445
+ },
446
+ };
447
+ }
448
+ }
449
+ };
450
+
451
+ fn exchange(self: *Self, child: *?std.process.Child, request_entry: Request) !ExchangeResult {
452
+ const now = std.Io.Clock.Timestamp.now(self.io, .awake);
453
+ if (std.Io.Clock.Timestamp.compare(now, .gte, request_entry.deadline)) return error.ServiceDeadlineExpired;
454
+ var done: std.Io.Event = .unset;
455
+ var cancel_signal: std.Io.Event = .unset;
456
+ const cancel_path = try self.cancellationPath(request_entry.request_id);
457
+ defer self.allocator.free(cancel_path);
458
+ defer std.Io.Dir.cwd().deleteFile(self.io, cancel_path) catch {};
459
+ self.mutex.lockUncancelable(self.io);
460
+ self.active_cancel_path = cancel_path;
461
+ self.active_cancel_signal = &cancel_signal;
462
+ if (self.active_cancelled) self.publishCancellationLocked();
463
+ self.mutex.unlock(self.io);
464
+ defer {
465
+ self.mutex.lockUncancelable(self.io);
466
+ if (self.active_request_id == request_entry.request_id) {
467
+ self.active_cancel_path = null;
468
+ self.active_cancel_signal = null;
469
+ }
470
+ self.mutex.unlock(self.io);
471
+ }
472
+ var watch: DeadlineWatch = .{
473
+ .host = self,
474
+ .request_id = request_entry.request_id,
475
+ .done = &done,
476
+ .cancel_signal = &cancel_signal,
477
+ .deadline = request_entry.deadline,
478
+ };
479
+ const watchdog = try std.Thread.spawn(.{}, DeadlineWatch.run, .{&watch});
480
+ const result = self.exchangeUnbounded(child, request_entry, cancel_path) catch |err| {
481
+ done.set(self.io);
482
+ cancel_signal.set(self.io);
483
+ watchdog.join();
484
+ if (watch.timed_out) return if (watch.hard_killed) error.ServiceTimedOut else error.ServiceTimedOutCooperative;
485
+ return err;
486
+ };
487
+ done.set(self.io);
488
+ cancel_signal.set(self.io);
489
+ watchdog.join();
490
+ if (watch.timed_out) {
491
+ self.allocator.free(result.bytes);
492
+ return if (watch.hard_killed) error.ServiceTimedOut else error.ServiceTimedOutCooperative;
493
+ }
494
+ return result;
495
+ }
496
+
497
+ fn exchangeUnbounded(self: *Self, child: *?std.process.Child, request_entry: Request, cancel_path: []const u8) !ExchangeResult {
498
+ if (child.* == null) try self.startChild(child);
499
+ if (cancel_path.len > std.math.maxInt(u16)) return error.CancellationPathTooLong;
500
+ var frame = try self.allocator.alloc(u8, 12 + cancel_path.len + request_entry.payload.len);
501
+ defer self.allocator.free(frame);
502
+ putU32(frame, 0, @intCast(8 + cancel_path.len + request_entry.payload.len));
503
+ putU32(frame, 4, request_entry.request_id);
504
+ putU16(frame, 8, request_entry.operation);
505
+ putU16(frame, 10, @intCast(cancel_path.len));
506
+ @memcpy(frame[12 .. 12 + cancel_path.len], cancel_path);
507
+ @memcpy(frame[12 + cancel_path.len ..], request_entry.payload);
508
+ const stdin = child.*.?.stdin orelse return error.NoServiceStdin;
509
+ try stdin.writeStreamingAll(self.io, frame);
510
+
511
+ const stdout = child.*.?.stdout orelse return error.NoServiceStdout;
512
+ while (true) {
513
+ var header: [4]u8 = undefined;
514
+ try readExact(self.io, stdout, &header);
515
+ const length = readU32(&header, 0);
516
+ if (length < 5 or length > max_frame_bytes) return error.BadServiceFrame;
517
+ const body = try self.allocator.alloc(u8, length);
518
+ errdefer self.allocator.free(body);
519
+ try readExact(self.io, stdout, body);
520
+ if (readU32(body, 0) != request_entry.request_id) return error.BadServiceRequestId;
521
+ const status = body[4];
522
+ if (status == 2) {
523
+ const channel = request_entry.channel orelse return error.BadServiceStatus;
524
+ _ = channel.post(body[5..]);
525
+ self.allocator.free(body);
526
+ continue;
527
+ }
528
+ if (status > 1) return error.BadServiceStatus;
529
+ const bytes = try self.allocator.dupe(u8, body[5..]);
530
+ self.allocator.free(body);
531
+ return .{ .ok = status == 0, .bytes = bytes };
532
+ }
533
+ }
534
+
535
+ fn startChild(self: *Self, child: *?std.process.Child) !void {
536
+ const child_cwd: std.process.Child.Cwd = if (self.cwd.len > 0) .{ .path = self.cwd } else .inherit;
537
+ child.* = try std.process.spawn(self.io, .{
538
+ .argv = &.{self.executable},
539
+ .cwd = child_cwd,
540
+ .environ_map = self.environ,
541
+ .stdin = .pipe,
542
+ .stdout = .pipe,
543
+ .stderr = .inherit,
544
+ .create_no_window = builtin.os.tag == .windows,
545
+ .pgid = if (builtin.os.tag == .windows) null else 0,
546
+ });
547
+ self.mutex.lockUncancelable(self.io);
548
+ self.child_id = child.*.?.id;
549
+ self.child_reaping = false;
550
+ self.mutex.unlock(self.io);
551
+ const stdout = child.*.?.stdout orelse return error.NoServiceStdout;
552
+ var hello: [5]u8 = undefined;
553
+ try readExact(self.io, stdout, &hello);
554
+ if (readU32(&hello, 0) != @as(u32, @intCast(1 + Registry.contract_fingerprint.len)) or
555
+ hello[4] != Registry.protocol_version) return error.ServiceProtocolSkew;
556
+ var fingerprint: [Registry.contract_fingerprint.len]u8 = undefined;
557
+ try readExact(self.io, stdout, &fingerprint);
558
+ if (!std.mem.eql(u8, &fingerprint, &Registry.contract_fingerprint)) return error.ServiceProtocolSkew;
559
+ }
560
+
561
+ fn retireChild(self: *Self, child: *?std.process.Child) void {
562
+ if (child.*) |*value| {
563
+ self.mutex.lockUncancelable(self.io);
564
+ self.child_reaping = true;
565
+ self.mutex.unlock(self.io);
566
+ if (value.stdin) |file| file.close(self.io);
567
+ value.stdin = null;
568
+ _ = value.wait(self.io) catch {};
569
+ child.* = null;
570
+ self.mutex.lockUncancelable(self.io);
571
+ self.child_id = null;
572
+ self.child_reaping = false;
573
+ self.mutex.unlock(self.io);
574
+ }
575
+ }
576
+
577
+ fn killPublishedChildLocked(self: *Self) void {
578
+ if (self.child_reaping) return;
579
+ const id = self.child_id orelse return;
580
+ if (builtin.os.tag == .windows) {
581
+ _ = std.os.windows.ntdll.NtTerminateProcess(id, @enumFromInt(1));
582
+ } else {
583
+ std.posix.kill(-id, .KILL) catch std.posix.kill(id, .KILL) catch {};
584
+ }
585
+ }
586
+
587
+ fn publishCancellationLocked(self: *Self) void {
588
+ if (self.active_cancel_path) |path| {
589
+ if (std.Io.Dir.cwd().createFile(self.io, path, .{ .truncate = true })) |file| {
590
+ file.close(self.io);
591
+ } else |_| {}
592
+ }
593
+ if (self.active_cancel_signal) |signal| signal.set(self.io);
594
+ }
595
+
596
+ fn cancellationPath(self: *Self, request_id: u32) ![]u8 {
597
+ const root = if (self.cwd.len > 0) self.cwd else ".";
598
+ const absolute_root = if (std.fs.path.isAbsolute(root))
599
+ null
600
+ else
601
+ try std.Io.Dir.cwd().realPathFileAlloc(self.io, root, self.allocator);
602
+ defer if (absolute_root) |path| self.allocator.free(path);
603
+ const resolved_root = absolute_root orelse root;
604
+ const pid: u32 = switch (builtin.os.tag) {
605
+ .windows => std.os.windows.GetCurrentProcessId(),
606
+ .wasi, .freestanding, .emscripten => 0,
607
+ else => @intCast(@max(0, std.posix.system.getpid())),
608
+ };
609
+ return std.fmt.allocPrint(
610
+ self.allocator,
611
+ "{s}{c}.native-service-cancel-{d}-{x}-{d}",
612
+ .{ resolved_root, std.fs.path.sep, pid, @intFromPtr(self), request_id },
613
+ );
614
+ }
615
+ };
616
+ }
617
+
618
+ fn readExact(io: std.Io, file: std.Io.File, bytes: []u8) !void {
619
+ var offset: usize = 0;
620
+ while (offset < bytes.len) {
621
+ const slices: [1][]u8 = .{bytes[offset..]};
622
+ const count = try file.readStreaming(io, &slices);
623
+ if (count == 0) return error.EndOfStream;
624
+ offset += count;
625
+ }
626
+ }
627
+
628
+ fn putU16(bytes: []u8, at: usize, value: u16) void {
629
+ bytes[at] = @truncate(value);
630
+ bytes[at + 1] = @truncate(value >> 8);
631
+ }
632
+ fn putU32(bytes: []u8, at: usize, value: u32) void {
633
+ bytes[at] = @truncate(value);
634
+ bytes[at + 1] = @truncate(value >> 8);
635
+ bytes[at + 2] = @truncate(value >> 16);
636
+ bytes[at + 3] = @truncate(value >> 24);
637
+ }
638
+ fn readU32(bytes: []const u8, at: usize) u32 {
639
+ return @as(u32, bytes[at]) |
640
+ (@as(u32, bytes[at + 1]) << 8) |
641
+ (@as(u32, bytes[at + 2]) << 16) |
642
+ (@as(u32, bytes[at + 3]) << 24);
643
+ }
644
+
645
+ fn readU64(bytes: []const u8, at: usize) u64 {
646
+ return @as(u64, readU32(bytes, at)) | (@as(u64, readU32(bytes, at + 4)) << 32);
647
+ }
648
+
649
+ test "service host binding is lazy and shuts down without spawning" {
650
+ const Registry = struct {
651
+ pub const protocol_version: u8 = 3;
652
+ pub const contract_fingerprint = [_]u8{0} ** 32;
653
+ pub const Operation = struct { name: []const u8, index: u16, deadline_ms: ?u32, cancellable: bool, streaming: bool, in_flight: u8 };
654
+ pub fn indexOf(name: []const u8) ?u16 {
655
+ return if (std.mem.eql(u8, name, "fixture.echo")) 0 else null;
656
+ }
657
+ pub fn operationAt(index: u16) ?Operation {
658
+ return if (index == 0) .{ .name = "fixture.echo", .index = 0, .deadline_ms = null, .cancellable = false, .streaming = false, .in_flight = 0 } else null;
659
+ }
660
+ };
661
+ const Host = ServiceHost(Registry);
662
+ var host = Host.init(std.testing.allocator, std.testing.io, "missing-service-host", "", null);
663
+ defer host.deinit();
664
+ const bound = host.binding();
665
+ try std.testing.expect(bound.poll_fn != null);
666
+ try std.testing.expect(bound.shutdown_fn != null);
667
+ try std.testing.expect(bound.reject_duplicate_keys);
668
+ }
669
+
670
+ test "service cancellation markers live under the writable service cwd" {
671
+ const Registry = struct {
672
+ pub const protocol_version: u8 = 3;
673
+ pub const contract_fingerprint = [_]u8{0} ** 32;
674
+ pub const Operation = struct { name: []const u8, index: u16, deadline_ms: ?u32, cancellable: bool, streaming: bool, in_flight: u8 };
675
+ pub fn indexOf(_: []const u8) ?u16 {
676
+ return null;
677
+ }
678
+ pub fn operationAt(_: u16) ?Operation {
679
+ return null;
680
+ }
681
+ };
682
+ const Host = ServiceHost(Registry);
683
+ const writable_root = try std.Io.Dir.cwd().realPathFileAlloc(std.testing.io, ".", std.testing.allocator);
684
+ defer std.testing.allocator.free(writable_root);
685
+ var host = Host.init(std.testing.allocator, std.testing.io, "read-only-package/app_services", ".", null);
686
+ const path = try host.cancellationPath(7);
687
+ defer std.testing.allocator.free(path);
688
+ try std.testing.expect(std.fs.path.isAbsolute(path));
689
+ try std.testing.expect(std.mem.startsWith(u8, path, writable_root));
690
+ try std.testing.expectEqual(std.fs.path.sep, path[writable_root.len]);
691
+ }
692
+
693
+ test "service environment allowlist exposes authority without SDK internals" {
694
+ try std.testing.expect(environmentVariableAllowed("PATH"));
695
+ try std.testing.expect(environmentVariableAllowed("SSL_CERT_FILE"));
696
+ try std.testing.expect(environmentVariableAllowed("HTTPS_PROXY"));
697
+ try std.testing.expect(!environmentVariableAllowed("NATIVE_SDK_PATH"));
698
+ try std.testing.expect(!environmentVariableAllowed("NATIVE_SDK_CORE_COMPILER"));
699
+ try std.testing.expect(!environmentVariableAllowed("AWS_SECRET_ACCESS_KEY"));
700
+ }
701
+
702
+ test "service environment allowlist honors Windows names and casing" {
703
+ try std.testing.expect(environmentVariableAllowedForOs("Path", .windows));
704
+ try std.testing.expect(environmentVariableAllowedForOs("USERPROFILE", .windows));
705
+ try std.testing.expect(environmentVariableAllowedForOs("username", .windows));
706
+ try std.testing.expect(environmentVariableAllowedForOs("SystemRoot", .windows));
707
+ try std.testing.expect(environmentVariableAllowedForOs("ComSpec", .windows));
708
+ try std.testing.expect(environmentVariableAllowedForOs("PATHEXT", .windows));
709
+ try std.testing.expect(!environmentVariableAllowedForOs("USERPROFILE", .linux));
710
+ try std.testing.expect(!environmentVariableAllowedForOs("NATIVE_SDK_PATH", .windows));
711
+ }