@native-sdk/cli 0.5.3 → 0.6.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 (172) hide show
  1. package/build/app.zig +91 -2
  2. package/build.zig +756 -5
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +19 -1
  5. package/package.json +9 -9
  6. package/packages/core/package-lock.json +2 -2
  7. package/packages/core/package.json +1 -1
  8. package/packages/core/rt/rt.zig +416 -9
  9. package/packages/core/sdk/core.ts +706 -5
  10. package/packages/core/sdk/events.ts +17 -8
  11. package/packages/core/src/checker.ts +305 -2
  12. package/packages/core/src/diagnostics.ts +12 -0
  13. package/packages/core/src/emitter.ts +3187 -264
  14. package/packages/core/src/typed_ast.ts +51 -4
  15. package/packages/core/src/types.ts +34 -1
  16. package/skill-data/native-ui/SKILL.md +42 -4
  17. package/skill-data/ts-core/SKILL.md +13 -3
  18. package/src/app_runner/root.zig +112 -10
  19. package/src/app_runner/ts_core_main.zig +4 -0
  20. package/src/automation/layout_fingerprint.zig +160 -0
  21. package/src/automation/protocol.zig +82 -33
  22. package/src/automation/root.zig +1 -0
  23. package/src/automation/server.zig +1 -1
  24. package/src/automation/snapshot.zig +68 -9
  25. package/src/automation/watcher.zig +1 -1
  26. package/src/embed/host.zig +5 -0
  27. package/src/embed/tests.zig +119 -1
  28. package/src/embed/ui_host.zig +13 -0
  29. package/src/platform/linux/gtk_host.c +639 -16
  30. package/src/platform/linux/gtk_host.h +25 -0
  31. package/src/platform/linux/root.zig +351 -7
  32. package/src/platform/macos/appkit_host.h +152 -8
  33. package/src/platform/macos/appkit_host.m +1816 -100
  34. package/src/platform/macos/cef_host.mm +372 -11
  35. package/src/platform/macos/root.zig +379 -11
  36. package/src/platform/null_platform.zig +696 -9
  37. package/src/platform/null_platform_tests.zig +35 -0
  38. package/src/platform/root.zig +42 -0
  39. package/src/platform/types.zig +524 -18
  40. package/src/platform/windows/root.zig +432 -9
  41. package/src/platform/windows/webview2_host.cpp +482 -45
  42. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  43. package/src/primitives/app_manifest/root.zig +1 -0
  44. package/src/primitives/app_manifest/types.zig +32 -0
  45. package/src/primitives/app_manifest/validation.zig +18 -0
  46. package/src/primitives/canvas/a11y_audit.zig +33 -11
  47. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  48. package/src/primitives/canvas/drawing.zig +25 -0
  49. package/src/primitives/canvas/equality.zig +8 -0
  50. package/src/primitives/canvas/events.zig +103 -16
  51. package/src/primitives/canvas/frame.zig +125 -1
  52. package/src/primitives/canvas/layout_audit.zig +22 -5
  53. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  54. package/src/primitives/canvas/render_tests.zig +13 -10
  55. package/src/primitives/canvas/root.zig +48 -0
  56. package/src/primitives/canvas/terminal_box.zig +471 -0
  57. package/src/primitives/canvas/terminal_grid.zig +978 -0
  58. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  59. package/src/primitives/canvas/test_support.zig +1 -0
  60. package/src/primitives/canvas/tests.zig +2 -0
  61. package/src/primitives/canvas/text_tests.zig +39 -4
  62. package/src/primitives/canvas/tokens.zig +115 -12
  63. package/src/primitives/canvas/ui.zig +535 -12
  64. package/src/primitives/canvas/ui_markup.zig +253 -36
  65. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  66. package/src/primitives/canvas/ui_markup_compiled.zig +195 -9
  67. package/src/primitives/canvas/ui_markup_compiled_tests.zig +188 -8
  68. package/src/primitives/canvas/ui_markup_contract.zig +89 -6
  69. package/src/primitives/canvas/ui_markup_contract_tests.zig +65 -1
  70. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  71. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  72. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  73. package/src/primitives/canvas/ui_markup_tests.zig +178 -9
  74. package/src/primitives/canvas/ui_markup_view.zig +220 -11
  75. package/src/primitives/canvas/ui_markup_view_tests.zig +553 -28
  76. package/src/primitives/canvas/ui_schema.zig +110 -17
  77. package/src/primitives/canvas/ui_schema_tests.zig +18 -10
  78. package/src/primitives/canvas/ui_tests.zig +141 -9
  79. package/src/primitives/canvas/widget_access.zig +28 -2
  80. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  81. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  82. package/src/primitives/canvas/widget_layout.zig +59 -11
  83. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  84. package/src/primitives/canvas/widget_render.zig +272 -18
  85. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  86. package/src/primitives/canvas/widget_routing.zig +59 -7
  87. package/src/primitives/canvas/widget_runtime.zig +23 -0
  88. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  89. package/src/primitives/canvas/widget_semantics.zig +119 -11
  90. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  91. package/src/primitives/canvas/widget_tree.zig +17 -0
  92. package/src/primitives/canvas/widgets.zig +132 -0
  93. package/src/root.zig +23 -0
  94. package/src/runtime/api.zig +76 -5
  95. package/src/runtime/automation_commands.zig +20 -1
  96. package/src/runtime/automation_snapshot.zig +25 -1
  97. package/src/runtime/automation_widget_dispatch.zig +73 -8
  98. package/src/runtime/bridge_payload.zig +8 -0
  99. package/src/runtime/bridge_responses.zig +5 -0
  100. package/src/runtime/builtin_bridge.zig +9 -4
  101. package/src/runtime/canvas_font_tests.zig +439 -2
  102. package/src/runtime/canvas_fonts.zig +61 -6
  103. package/src/runtime/canvas_frame.zig +62 -7
  104. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  105. package/src/runtime/canvas_frame_helpers.zig +190 -1
  106. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  107. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  108. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  109. package/src/runtime/canvas_image_tests.zig +195 -0
  110. package/src/runtime/canvas_images.zig +45 -12
  111. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  112. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  113. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  114. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  115. package/src/runtime/canvas_widget_display.zig +1 -1
  116. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  117. package/src/runtime/canvas_widget_events.zig +240 -24
  118. package/src/runtime/canvas_widget_runtime.zig +213 -29
  119. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  120. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  121. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  122. package/src/runtime/canvas_widget_state.zig +6 -0
  123. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  124. package/src/runtime/core.zig +131 -13
  125. package/src/runtime/effects.zig +8136 -180
  126. package/src/runtime/effects_channel_tests.zig +3519 -0
  127. package/src/runtime/effects_fetch_tests.zig +89 -1
  128. package/src/runtime/effects_file_tests.zig +41 -1
  129. package/src/runtime/effects_image_tests.zig +1304 -0
  130. package/src/runtime/effects_pty_tests.zig +1362 -0
  131. package/src/runtime/effects_tests.zig +167 -9
  132. package/src/runtime/effects_video_tests.zig +3609 -0
  133. package/src/runtime/flow.zig +42 -4
  134. package/src/runtime/gpu_surface_events.zig +473 -13
  135. package/src/runtime/media_surface.zig +116 -11
  136. package/src/runtime/media_surface_tests.zig +61 -0
  137. package/src/runtime/pty.zig +1252 -0
  138. package/src/runtime/pty_windows.zig +1780 -0
  139. package/src/runtime/root.zig +36 -0
  140. package/src/runtime/runtime_event_tests.zig +20 -1
  141. package/src/runtime/session_blobs.zig +689 -0
  142. package/src/runtime/session_journal.zig +432 -62
  143. package/src/runtime/session_record.zig +43 -2
  144. package/src/runtime/session_replay.zig +556 -20
  145. package/src/runtime/session_tests.zig +2087 -1
  146. package/src/runtime/shell_layout.zig +7 -0
  147. package/src/runtime/terminal_session.zig +1569 -0
  148. package/src/runtime/terminal_session_tests.zig +450 -0
  149. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  150. package/src/runtime/terminal_vt_stub.zig +13 -0
  151. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  152. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  153. package/src/runtime/tests.zig +8 -0
  154. package/src/runtime/ts_core_host.zig +1320 -45
  155. package/src/runtime/ts_core_host_tests.zig +1100 -1
  156. package/src/runtime/ts_ui_app.zig +23 -5
  157. package/src/runtime/ui_app.zig +2444 -69
  158. package/src/runtime/ui_app_tests.zig +3171 -744
  159. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  160. package/src/runtime/ui_app_window_tests.zig +736 -0
  161. package/src/runtime/view.zig +190 -2
  162. package/src/runtime/view_widget_scroll.zig +218 -68
  163. package/src/runtime/view_widget_text.zig +11 -2
  164. package/src/runtime/view_widget_tree.zig +111 -3
  165. package/src/runtime/window_command_bridge_tests.zig +117 -0
  166. package/src/runtime/window_storage.zig +77 -2
  167. package/src/runtime/window_view_runtime.zig +34 -2
  168. package/src/runtime/window_views.zig +62 -1
  169. package/src/terminal_session_tests_root.zig +15 -0
  170. package/src/tooling/manifest.zig +75 -0
  171. package/src/tooling/raw_manifest.zig +2 -0
  172. package/src/tooling/templates.zig +244 -8
@@ -0,0 +1,1780 @@
1
+ //! Windows pseudo-terminal primitive: a ConPTY (`CreatePseudoConsole`)
2
+ //! wired to an overlapped named-pipe pair, presenting the SAME transport
3
+ //! surface the POSIX half of `pty.zig` presents — `spawn`, the
4
+ //! read/write/resize/kill/reap methods, the nudge pair, and `wait` — so
5
+ //! the effects io loop drives both backends through one vocabulary and
6
+ //! the null platform's scriptable fake stays the one observable
7
+ //! contract.
8
+ //!
9
+ //! Encoding honesty at the ConPTY boundary: the pseudoconsole's pipe
10
+ //! contract IS UTF-8 with VT sequences, both directions — conhost
11
+ //! decodes input bytes as UTF-8 (VT input sequences included) and emits
12
+ //! its output as UTF-8-encoded VT. There is no console-mode call for
13
+ //! the toolkit to make: this host process has no console, and the modes
14
+ //! that make the child's world VT-native
15
+ //! (`ENABLE_VIRTUAL_TERMINAL_PROCESSING` on output,
16
+ //! `ENABLE_VIRTUAL_TERMINAL_INPUT` on input) are owned by the
17
+ //! pseudoconsole's conhost, which installs them for its clients. The
18
+ //! one configuration the toolkit does choose is `CreatePseudoConsole`'s
19
+ //! flags = 0: `PSEUDOCONSOLE_INHERIT_CURSOR` would make conhost open by
20
+ //! emitting a cursor-position request (DSR) and WAIT for the terminal's
21
+ //! answer — a handshake the effects reader deliberately never plays.
22
+ //!
23
+ //! Two documented behavioral differences from the POSIX backends:
24
+ //!
25
+ //! - RENDERED STREAM, NOT RAW BYTES. ConPTY output is conhost's VT
26
+ //! rendering of the child's screen (cursor moves, clears, repaints),
27
+ //! not the child's literal write() stream. A terminal emulator
28
+ //! consumes it identically; byte-exact assertions against child
29
+ //! output do not transfer.
30
+ //! - EXIT CODES ONLY. Windows has no signals: every ending carries a
31
+ //! process exit code (`Exit.signal` is always 0), so endings POSIX
32
+ //! reports as `.signaled` surface here as `.exited` with the
33
+ //! terminator's chosen code (a crash shows the NTSTATUS, e.g.
34
+ //! 0xC0000005, bit-cast to i32). The toolkit's own kill reports
35
+ //! `.cancelled` through the shared io-loop rule either way.
36
+ //!
37
+ //! EOF is MANUFACTURED here, deliberately: conhost holds the output
38
+ //! pipe open past the child's death, so the pipe alone never EOFs. The
39
+ //! `wait` loop watches the process handle; once the child has exited
40
+ //! and the pipe has gone quiet behind the armed read, it closes the
41
+ //! pseudoconsole — conhost flushes its tail, tears down anything still
42
+ //! attached (the POSIX group-kill's analog: a descendant that detached
43
+ //! from the console escapes, mirroring the setsid escape), and exits,
44
+ //! which breaks the pipe and delivers the EOF the io loop's shared
45
+ //! reap path expects. Closing only at a QUIET moment matters: older
46
+ //! conhosts block `ClosePseudoConsole` while their output pipe is full,
47
+ //! and an empty pipe (ours is 128 KiB) cannot be full.
48
+ //!
49
+ //! Reaping discipline, Windows-shaped: process objects self-release
50
+ //! when the last handle closes — there are no zombies to guard against
51
+ //! — so the POSIX surrendered-pid table has no work here. What remains
52
+ //! is HANDLE discipline (every spawn's process handle, pipe pair, and
53
+ //! events close exactly once, at `close`) and exit-code capture
54
+ //! (`GetExitCodeProcess` after the process handle signals).
55
+
56
+ const std = @import("std");
57
+ const builtin = @import("builtin");
58
+ const pty = @import("pty.zig");
59
+ const clock = @import("clock.zig");
60
+
61
+ const is_windows = builtin.os.tag == .windows;
62
+
63
+ const Error = pty.Error;
64
+ const Exit = pty.Exit;
65
+ const SpawnOptions = pty.SpawnOptions;
66
+ const EnvVar = pty.EnvVar;
67
+ const Ready = pty.Ready;
68
+
69
+ /// The parent-side pipe buffer, both directions. Generous on purpose:
70
+ /// the quiet-moment console close (see the file doc) relies on "empty
71
+ /// pipe means conhost is not blocked writing", and a bigger buffer
72
+ /// makes the window where conhost could refill it between the peek and
73
+ /// the close irrelevant — a just-emptied 128 KiB pipe cannot be full
74
+ /// again before `ClosePseudoConsole` returns.
75
+ const pipe_buffer_bytes: u32 = 128 * 1024;
76
+ /// Matches the io loop's 16 KiB local read chunk: the overlapped read
77
+ /// lands here and `read` hands it out in caller-sized bites.
78
+ const read_buffer_bytes: usize = 16 * 1024;
79
+ /// Matches the flush path's 4 KiB write chunk (one staged overlapped
80
+ /// write in flight; a second write while it pends answers WouldBlock,
81
+ /// the POSIX EAGAIN shape).
82
+ const write_buffer_bytes: usize = 4096;
83
+
84
+ /// Everything one live ConPTY session owns, heap-allocated because the
85
+ /// transport value is COPIED (into the io thread and the slot) and the
86
+ /// overlapped state must be shared, not forked. Threading contract:
87
+ /// the io thread owns all read/write/wait state; the loop thread
88
+ /// touches only `resize` (pseudoconsole handle, under `hpc_lock`),
89
+ /// `kill` (process handle, immutable), and — strictly after the io
90
+ /// thread has finished — `close`.
91
+ ///
92
+ /// Allocated from `state_allocator` (process-lifetime backing), NEVER
93
+ /// the caller's allocator: teardown may ABANDON an io thread past its
94
+ /// join deadline, and everything that thread can still reach must
95
+ /// outlive the caller's allocator — the effects layer's abandoned-
96
+ /// worker invariant, applied to the transport. The block is freed at
97
+ /// `close` (which only runs after the io thread finished); an abandon
98
+ /// leaks it with the thread, deliberately.
99
+ const State = struct {
100
+ /// The pseudoconsole. Guarded by `hpc_lock` against the one real
101
+ /// race: a loop-thread `resize` landing while the io thread closes
102
+ /// the console after child exit (`ClosePseudoConsole` frees the
103
+ /// object; a resize against it would touch freed kernel-side
104
+ /// plumbing).
105
+ hpc: win.HPCON,
106
+ hpc_lock: SpinLock = .{},
107
+ console_closed: bool = false,
108
+ /// The child process handle (identity is stable for the handle's
109
+ /// life — no pid-reuse hazard, unlike POSIX pids).
110
+ process: win.HANDLE,
111
+ /// Parent end of the output pipe (conhost writes, we read).
112
+ out_read: win.HANDLE,
113
+ /// Parent end of the input pipe (we write, conhost reads).
114
+ in_write: win.HANDLE,
115
+ /// Manual-reset events backing the two overlapped channels
116
+ /// (manual-reset, the documented-safe kind for
117
+ /// WaitForMultipleObjects + GetOverlappedResult).
118
+ read_event: win.HANDLE,
119
+ write_event: win.HANDLE,
120
+ read_overlapped: win.OVERLAPPED = std.mem.zeroes(win.OVERLAPPED),
121
+ write_overlapped: win.OVERLAPPED = std.mem.zeroes(win.OVERLAPPED),
122
+ read_buf: [read_buffer_bytes]u8 = undefined,
123
+ read_off: usize = 0,
124
+ read_len: usize = 0,
125
+ read_pending: bool = false,
126
+ read_eof: bool = false,
127
+ read_failed: bool = false,
128
+ write_buf: [write_buffer_bytes]u8 = undefined,
129
+ write_pending: bool = false,
130
+ write_failed: bool = false,
131
+ /// Set by `wait` when the process handle signals; from then on the
132
+ /// wait loop steers toward the console close and the manufactured
133
+ /// EOF instead of re-polling an already-signaled handle.
134
+ child_exited: bool = false,
135
+ /// Monotonic stamp of that observation: the console close waits
136
+ /// out a QUIET GRACE past it, because conhost renders the dead
137
+ /// client's final frame asynchronously — a close racing that
138
+ /// render would cut the session's last output off. Bounded (see
139
+ /// `exit_grace_ns`); 0 means the clock was unavailable and the
140
+ /// grace degrades to the quiet-pipe checks alone.
141
+ child_exited_at_ns: u64 = 0,
142
+ /// Monotonic stamp of the last completed read that carried bytes:
143
+ /// the quiet grace measures from the LATER of exit and last
144
+ /// output, so a conhost still emitting (an attached descendant, a
145
+ /// slow final render) keeps pushing the close out instead of being
146
+ /// cut mid-stream at a fixed offset from the exit.
147
+ last_output_at_ns: u64 = 0,
148
+ };
149
+
150
+ /// Process-lifetime backing for `State` (see its doc): the page
151
+ /// allocator is thread-safe, never torn down, and each session's block
152
+ /// is a handful of pages.
153
+ const state_allocator = std.heap.page_allocator;
154
+
155
+ /// How long past the child's exit — and past the LAST OUTPUT, whichever
156
+ /// is later — the console close waits for the output pipe to stay
157
+ /// quiet. Not a liveness cost in the common case (the close fires at
158
+ /// the first quiet observation past the grace), and bounded either way;
159
+ /// the post-close drain still collects anything conhost flushes while
160
+ /// tearing down. The residual is stated plainly: a conhost that stays
161
+ /// SILENT this long while still holding an unrendered final frame
162
+ /// would lose it — the alternative (never closing) strands the session
163
+ /// forever, because the pipe never breaks on its own (measured: it
164
+ /// stays open indefinitely even after every attached client exited).
165
+ const exit_grace_ns: u64 = 100 * std.time.ns_per_ms;
166
+
167
+ const SpinLock = struct {
168
+ locked: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
169
+ fn lock(self: *SpinLock) void {
170
+ while (self.locked.swap(true, .acquire)) std.atomic.spinLoopHint();
171
+ }
172
+ fn unlock(self: *SpinLock) void {
173
+ self.locked.store(false, .release);
174
+ }
175
+ };
176
+
177
+ /// A live ConPTY session. Same method surface as the POSIX `Pty`;
178
+ /// `state` is the shared heap block both copies (io thread, slot)
179
+ /// point at, freed by `close`.
180
+ pub const Pty = struct {
181
+ state: *State,
182
+
183
+ /// Hand out bytes the overlapped read already landed. Returns 0 at
184
+ /// EOF (the manufactured broken-pipe end), WouldBlock while the
185
+ /// armed read is still in flight — the io loop only calls this
186
+ /// after `wait` reported readable, so the common case is a copy.
187
+ pub fn read(self: Pty, buf: []u8) error{ ReadFailed, WouldBlock }!usize {
188
+ const st = self.state;
189
+ if (st.read_len > st.read_off) {
190
+ const take = @min(buf.len, st.read_len - st.read_off);
191
+ @memcpy(buf[0..take], st.read_buf[st.read_off .. st.read_off + take]);
192
+ st.read_off += take;
193
+ return take;
194
+ }
195
+ if (st.read_eof) return 0;
196
+ if (st.read_failed) return error.ReadFailed;
197
+ return error.WouldBlock;
198
+ }
199
+
200
+ /// Stage bytes toward the child, one overlapped write in flight.
201
+ /// Accepted bytes are COPIED into the state buffer before the write
202
+ /// arms, so the caller's chunk may be reused immediately; a write
203
+ /// arriving while one pends answers WouldBlock (the POSIX
204
+ /// full-input-buffer EAGAIN) and the caller retries on the next
205
+ /// writable wake.
206
+ pub fn write(self: Pty, bytes: []const u8) error{ WriteFailed, WouldBlock }!usize {
207
+ const st = self.state;
208
+ if (st.write_failed) return error.WriteFailed;
209
+ if (st.write_pending) {
210
+ if (!completeWrite(st)) return error.WouldBlock;
211
+ if (st.write_failed) return error.WriteFailed;
212
+ }
213
+ const take = @min(bytes.len, st.write_buf.len);
214
+ if (take == 0) return 0;
215
+ @memcpy(st.write_buf[0..take], bytes[0..take]);
216
+ _ = win.ResetEvent(st.write_event);
217
+ st.write_overlapped = std.mem.zeroes(win.OVERLAPPED);
218
+ st.write_overlapped.hEvent = st.write_event;
219
+ const ok = win.WriteFile(st.in_write, &st.write_buf, @intCast(take), null, &st.write_overlapped);
220
+ if (ok != 0) return take; // completed synchronously (byte pipes write whole)
221
+ switch (lastError()) {
222
+ win.ERROR_IO_PENDING => {
223
+ st.write_pending = true;
224
+ return take;
225
+ },
226
+ else => {
227
+ st.write_failed = true;
228
+ return error.WriteFailed;
229
+ },
230
+ }
231
+ }
232
+
233
+ /// Push a new grid size through `ResizePseudoConsole`; conhost
234
+ /// forwards it to the client as a window-size change (the child
235
+ /// re-queries via the console APIs — Windows' SIGWINCH analog).
236
+ /// Serialized against the io thread's console close: a resize after
237
+ /// the pseudoconsole closed is a silent no-op, exactly like a POSIX
238
+ /// TIOCSWINSZ on a hung-up pty.
239
+ pub fn resize(self: Pty, cols: u16, rows: u16) void {
240
+ const st = self.state;
241
+ const size: win.COORD = .{
242
+ .X = @intCast(@min(@as(u16, if (cols == 0) 1 else cols), 32767)),
243
+ .Y = @intCast(@min(@as(u16, if (rows == 0) 1 else rows), 32767)),
244
+ };
245
+ st.hpc_lock.lock();
246
+ defer st.hpc_lock.unlock();
247
+ if (!st.console_closed) _ = win.ResizePseudoConsole(st.hpc, size);
248
+ }
249
+
250
+ /// Terminate the child. Windows has no graceful signal for an
251
+ /// arbitrary console client from outside its console, so both
252
+ /// flavors map to `TerminateProcess` (exit code 1); descendants
253
+ /// still attached to the pseudoconsole fall when the io thread's
254
+ /// reap closes it — the POSIX group-kill's reach, by another
255
+ /// mechanism. `graceful` is accepted for surface parity and
256
+ /// documented as hard here. Safe from any thread (handle identity
257
+ /// is stable; terminating an already-dead process fails
258
+ /// harmlessly).
259
+ pub fn kill(self: Pty, graceful: bool) void {
260
+ _ = graceful;
261
+ _ = win.TerminateProcess(self.state.process, 1);
262
+ }
263
+
264
+ /// Reap the child if it has exited: non-blocking process-handle
265
+ /// poll plus exit-code capture. A failed wait or code read reports
266
+ /// the gone-child sentinel (`code -1`), the POSIX ECHILD shape —
267
+ /// never "still running", so the shared kill fences stay exact.
268
+ pub fn reap(self: Pty) ?Exit {
269
+ return switch (win.WaitForSingleObject(self.state.process, 0)) {
270
+ win.WAIT_OBJECT_0 => self.exitCode(),
271
+ win.WAIT_TIMEOUT => null,
272
+ else => .{ .code = -1, .signal = 0 },
273
+ };
274
+ }
275
+
276
+ /// Reap the child, blocking until it exits.
277
+ pub fn reapBlocking(self: Pty) Exit {
278
+ if (win.WaitForSingleObject(self.state.process, win.INFINITE) == win.WAIT_OBJECT_0) {
279
+ return self.exitCode();
280
+ }
281
+ return .{ .code = -1, .signal = 0 };
282
+ }
283
+
284
+ /// Reap after the output stream ended, never blocking indefinitely
285
+ /// — the shared escalate-then-bound discipline with Windows verbs:
286
+ /// the fast path is the normal case (the manufactured EOF only
287
+ /// arrives after the process handle signaled, so the child is
288
+ /// already reapable); a child still alive is hung up by closing the
289
+ /// pseudoconsole (conhost tears its clients down — the SIGHUP
290
+ /// analog), escalated to `TerminateProcess` within the same bounded
291
+ /// window the POSIX backend uses, and a process the kernel will not
292
+ /// release within the surrender bound is reported ended with the
293
+ /// unknown-code sentinel — its handle still closes at `close`, and
294
+ /// the object self-releases when the process finally dies, so
295
+ /// nothing lingers (no surrendered table on Windows: there is no
296
+ /// zombie to re-poll for).
297
+ pub fn reapEnding(self: Pty) Exit {
298
+ const st = self.state;
299
+ // Every ending tears the console down HERE — on the kill and
300
+ // shutdown paths (where the loop broke before any EOF) this is
301
+ // what fells the descendants still attached to it, at the reap
302
+ // rather than a later retire the host might never drain to. A
303
+ // no-op on the normal path, whose EOF only exists because the
304
+ // console already closed.
305
+ defer drainAndCloseConsole(st);
306
+ if (self.reap()) |exit| return exit;
307
+ // Still running: hang it up like a real terminal closing (the
308
+ // drain keeps the close away from a full pipe).
309
+ drainAndCloseConsole(st);
310
+ const start_ns = clock.monotonicNanoseconds();
311
+ const clock_ok = start_ns != 0;
312
+ var iterations: usize = 0;
313
+ var killed = false;
314
+ while (true) : (iterations += 1) {
315
+ const elapsed_ns = if (clock_ok) clock.monotonicNanoseconds() -% start_ns else iterations * 10 * std.time.ns_per_ms;
316
+ if (elapsed_ns >= 500 * std.time.ns_per_ms) break;
317
+ if (win.WaitForSingleObject(st.process, 10) == win.WAIT_OBJECT_0) return self.exitCode();
318
+ if (!killed and elapsed_ns >= 200 * std.time.ns_per_ms) {
319
+ killed = true;
320
+ _ = win.TerminateProcess(st.process, 1);
321
+ }
322
+ }
323
+ if (!killed) _ = win.TerminateProcess(st.process, 1);
324
+ // The surrender bound: TerminateProcess is asynchronous, and a
325
+ // process wedged in a kernel call dies only when that call
326
+ // returns — the exit event must reach the app regardless.
327
+ if (win.WaitForSingleObject(st.process, 5000) == win.WAIT_OBJECT_0) return self.exitCode();
328
+ return .{ .code = -1, .signal = 0 };
329
+ }
330
+
331
+ /// Close every handle the session owns and free the shared state.
332
+ /// The io thread must be done (the retire path's `io_done` proof):
333
+ /// a still-armed overlapped read or write is cancelled and REAPED
334
+ /// here before the buffers it targets are freed — freeing state
335
+ /// under in-flight kernel I/O would hand the kernel a dangling
336
+ /// buffer.
337
+ pub fn close(self: Pty) void {
338
+ const st = self.state;
339
+ if (st.read_pending) {
340
+ _ = win.CancelIoEx(st.out_read, &st.read_overlapped);
341
+ var n: win.DWORD = 0;
342
+ _ = win.GetOverlappedResult(st.out_read, &st.read_overlapped, &n, 1);
343
+ st.read_pending = false;
344
+ }
345
+ if (st.write_pending) {
346
+ _ = win.CancelIoEx(st.in_write, &st.write_overlapped);
347
+ var n: win.DWORD = 0;
348
+ _ = win.GetOverlappedResult(st.in_write, &st.write_overlapped, &n, 1);
349
+ st.write_pending = false;
350
+ }
351
+ closeConsole(st);
352
+ // The close fallback may already have broken the read end (its
353
+ // INVALID sentinel); everything else closes exactly once here.
354
+ if (st.out_read != win.INVALID_HANDLE_VALUE) _ = win.CloseHandle(st.out_read);
355
+ _ = win.CloseHandle(st.in_write);
356
+ _ = win.CloseHandle(st.read_event);
357
+ _ = win.CloseHandle(st.write_event);
358
+ _ = win.CloseHandle(st.process);
359
+ state_allocator.destroy(st);
360
+ }
361
+
362
+ /// Windows has no exec self-pipe: `CreateProcessW`'s verdict is
363
+ /// synchronous, so a spawn that returned can never surface a late
364
+ /// exec failure.
365
+ pub fn lateExecFailure(self: Pty) bool {
366
+ _ = self;
367
+ return false;
368
+ }
369
+
370
+ fn exitCode(self: Pty) Exit {
371
+ var code: win.DWORD = 0;
372
+ if (win.GetExitCodeProcess(self.state.process, &code) == 0) {
373
+ return .{ .code = -1, .signal = 0 };
374
+ }
375
+ // The DWORD bit-cast keeps NTSTATUS endings honest (a crash's
376
+ // 0xC0000005 arrives as its negative i32 self, never a
377
+ // truncated small number). Signals do not exist here: 0 always.
378
+ return .{ .code = @bitCast(code), .signal = 0 };
379
+ }
380
+ };
381
+
382
+ /// Initiate the console close, then discard-drain the output pipe
383
+ /// (bounded) so a conhost blocked mid-write — its own teardown flush,
384
+ /// or a client's CTRL_CLOSE handler emitting past the pipe capacity —
385
+ /// always finds a reader and finishes closing. Used on the paths where
386
+ /// the io loop stopped reading before any EOF (kill, shutdown,
387
+ /// spawn-failure wind-down); the bound keeps a still-writing attached
388
+ /// descendant from stranding the reap forever (the detached closer
389
+ /// finishes whenever conhost does). Discarding is the shared teardown
390
+ /// discipline: these paths already deliver no further output.
391
+ /// io-thread only (it owns the read machinery).
392
+ fn drainAndCloseConsole(st: *State) void {
393
+ // Drain to a quiet moment FIRST: if the detached closer cannot
394
+ // spawn, `closeConsole`'s inline fallback runs on this reader
395
+ // thread, and it must never meet a full pipe (the documented
396
+ // ClosePseudoConsole wait). With the pipe just emptied, only a
397
+ // writer refilling 128 KiB inside the fallback's window could
398
+ // block it — the OOM-corner residual the closeConsole doc names.
399
+ drainDiscard(st, true);
400
+ closeConsole(st);
401
+ // Then keep draining while conhost tears down — its final flush,
402
+ // or CTRL_CLOSE writers among surviving descendants — until the
403
+ // broken pipe or the bound (the detached closer finishes whenever
404
+ // conhost does).
405
+ drainDiscard(st, false);
406
+ st.read_off = 0;
407
+ st.read_len = 0;
408
+ }
409
+
410
+ /// Bounded discard-drain of the output pipe. `stop_on_quiet` stops at
411
+ /// the first observation of an idle armed read over an empty pipe;
412
+ /// otherwise only EOF, a read failure, or the bound ends it.
413
+ fn drainDiscard(st: *State, stop_on_quiet: bool) void {
414
+ const start_ns = clock.monotonicNanoseconds();
415
+ const clock_ok = start_ns != 0;
416
+ var iterations: usize = 0;
417
+ while (!st.read_eof and !st.read_failed) : (iterations += 1) {
418
+ const elapsed_ns = if (clock_ok) clock.monotonicNanoseconds() -% start_ns else iterations * 10 * std.time.ns_per_ms;
419
+ if (elapsed_ns >= 400 * std.time.ns_per_ms) break;
420
+ // Discard whatever the last completion or a sync arm landed.
421
+ st.read_off = 0;
422
+ st.read_len = 0;
423
+ armRead(st);
424
+ if (st.read_len > 0) continue; // sync data: keep draining
425
+ if (!st.read_pending) continue; // spurious: re-arm next round
426
+ if (win.WaitForSingleObject(st.read_event, 10) == win.WAIT_OBJECT_0) {
427
+ completeRead(st);
428
+ continue;
429
+ }
430
+ if (!stop_on_quiet) continue;
431
+ var avail: win.DWORD = 0;
432
+ if (win.PeekNamedPipe(st.out_read, null, 0, null, &avail, null) == 0 or avail == 0) return;
433
+ }
434
+ }
435
+
436
+ /// Close the pseudoconsole exactly once (idempotent, lock-guarded
437
+ /// against `resize`). The blocking call itself runs on a DETACHED
438
+ /// helper thread: `ClosePseudoConsole` waits for conhost, and conhost
439
+ /// may be blocked writing into the output pipe (a client's CTRL_CLOSE
440
+ /// handler can emit more than the pipe holds), so the reader thread
441
+ /// must stay free to keep draining — closing inline on the reader is
442
+ /// the documented ClosePseudoConsole deadlock. The helper captures
443
+ /// only the HPCON VALUE (the object the call consumes; `resize` is
444
+ /// fenced off by `console_closed` under the lock), never the session
445
+ /// state, so it needs no join and cannot dangle.
446
+ ///
447
+ /// If the thread cannot spawn (resource exhaustion), the fallback
448
+ /// BREAKS THE OUTPUT PIPE first — cancel and reap the armed read so
449
+ /// its buffer is quiescent, mark the manufactured EOF, close the read
450
+ /// handle — and only then closes inline: with the pipe broken,
451
+ /// conhost's writes fail fast instead of filling it, so the inline
452
+ /// call cannot meet the deadlock (the cost is any unflushed tail,
453
+ /// which the thread-exhausted process was about to lose anyway).
454
+ /// io-thread only (the fallback owns the read machinery).
455
+ fn closeConsole(st: *State) void {
456
+ st.hpc_lock.lock();
457
+ defer st.hpc_lock.unlock();
458
+ if (st.console_closed) return;
459
+ st.console_closed = true;
460
+ const thread = std.Thread.spawn(.{}, closeConsoleThreadMain, .{st.hpc}) catch {
461
+ if (st.read_pending) {
462
+ _ = win.CancelIoEx(st.out_read, &st.read_overlapped);
463
+ var n: win.DWORD = 0;
464
+ _ = win.GetOverlappedResult(st.out_read, &st.read_overlapped, &n, 1);
465
+ st.read_pending = false;
466
+ }
467
+ st.read_eof = true;
468
+ _ = win.CloseHandle(st.out_read);
469
+ st.out_read = win.INVALID_HANDLE_VALUE;
470
+ win.ClosePseudoConsole(st.hpc);
471
+ return;
472
+ };
473
+ thread.detach();
474
+ }
475
+
476
+ fn closeConsoleThreadMain(hpc: win.HPCON) void {
477
+ win.ClosePseudoConsole(hpc);
478
+ }
479
+
480
+ /// Reap a completed overlapped write (non-blocking). True when the
481
+ /// write is no longer pending (completed or failed — `write_failed`
482
+ /// carries which).
483
+ fn completeWrite(st: *State) bool {
484
+ var n: win.DWORD = 0;
485
+ if (win.GetOverlappedResult(st.in_write, &st.write_overlapped, &n, 0) != 0) {
486
+ st.write_pending = false;
487
+ return true;
488
+ }
489
+ if (lastError() == win.ERROR_IO_INCOMPLETE) return false;
490
+ st.write_pending = false;
491
+ st.write_failed = true;
492
+ return true;
493
+ }
494
+
495
+ /// Reap a completed overlapped read (non-blocking): data lands in the
496
+ /// state buffer, a broken pipe becomes the EOF flag (the POSIX
497
+ /// EIO-after-hangup normalization), anything else marks the stream
498
+ /// failed.
499
+ fn completeRead(st: *State) void {
500
+ var n: win.DWORD = 0;
501
+ if (win.GetOverlappedResult(st.out_read, &st.read_overlapped, &n, 0) != 0) {
502
+ st.read_pending = false;
503
+ st.read_off = 0;
504
+ st.read_len = n;
505
+ if (n > 0) st.last_output_at_ns = clock.monotonicNanoseconds();
506
+ return;
507
+ }
508
+ switch (lastError()) {
509
+ win.ERROR_IO_INCOMPLETE => {},
510
+ win.ERROR_BROKEN_PIPE, win.ERROR_PIPE_NOT_CONNECTED, win.ERROR_HANDLE_EOF => {
511
+ st.read_pending = false;
512
+ st.read_eof = true;
513
+ },
514
+ else => {
515
+ st.read_pending = false;
516
+ st.read_failed = true;
517
+ },
518
+ }
519
+ }
520
+
521
+ /// Arm the overlapped read if nothing is buffered, pending, or
522
+ /// terminal. A synchronous completion lands its bytes immediately.
523
+ fn armRead(st: *State) void {
524
+ if (st.read_pending or st.read_eof or st.read_failed) return;
525
+ if (st.read_len > st.read_off) return;
526
+ st.read_off = 0;
527
+ st.read_len = 0;
528
+ _ = win.ResetEvent(st.read_event);
529
+ st.read_overlapped = std.mem.zeroes(win.OVERLAPPED);
530
+ st.read_overlapped.hEvent = st.read_event;
531
+ const ok = win.ReadFile(st.out_read, &st.read_buf, @intCast(read_buffer_bytes), null, &st.read_overlapped);
532
+ if (ok != 0) {
533
+ var n: win.DWORD = 0;
534
+ if (win.GetOverlappedResult(st.out_read, &st.read_overlapped, &n, 0) != 0) {
535
+ st.read_off = 0;
536
+ st.read_len = n;
537
+ // Synchronous completions push the exit quiet grace out
538
+ // exactly like event-delivered ones.
539
+ if (n > 0) st.last_output_at_ns = clock.monotonicNanoseconds();
540
+ }
541
+ return;
542
+ }
543
+ switch (lastError()) {
544
+ win.ERROR_IO_PENDING => st.read_pending = true,
545
+ win.ERROR_BROKEN_PIPE, win.ERROR_PIPE_NOT_CONNECTED, win.ERROR_HANDLE_EOF => st.read_eof = true,
546
+ else => st.read_failed = true,
547
+ }
548
+ }
549
+
550
+ /// The quiet-moment console close after child exit (see the file doc):
551
+ /// only behind an ARMED, still-silent read (a completed read means data
552
+ /// to deliver first; a visible backlog means conhost is mid-burst), so
553
+ /// `ClosePseudoConsole` can never meet the full pipe that wedges older
554
+ /// conhosts.
555
+ fn maybeCloseConsole(st: *State) void {
556
+ if (st.console_closed or !st.read_pending) return;
557
+ // The quiet grace: give conhost its beat to render the dead
558
+ // client's final frame — measured from the LATER of the exit and
559
+ // the last delivered output — before manufacturing EOF.
560
+ const quiet_since = @max(st.child_exited_at_ns, st.last_output_at_ns);
561
+ if (quiet_since != 0) {
562
+ const now = clock.monotonicNanoseconds();
563
+ if (now != 0 and now -% quiet_since < exit_grace_ns) return;
564
+ }
565
+ if (win.WaitForSingleObject(st.read_event, 0) == win.WAIT_OBJECT_0) return;
566
+ var avail: win.DWORD = 0;
567
+ if (win.PeekNamedPipe(st.out_read, null, 0, null, &avail, null) != 0 and avail != 0) return;
568
+ // Re-probe the read event AFTER the peek: a completion landing
569
+ // between the two hands its bytes to the armed read — the pipe
570
+ // peeks empty exactly then — and means conhost just started
571
+ // emitting, so the grace must restart rather than the console
572
+ // close. (The residual sliver between this probe and the close is
573
+ // covered by conhost's flush-on-close plus the post-close drain.)
574
+ if (win.WaitForSingleObject(st.read_event, 0) == win.WAIT_OBJECT_0) return;
575
+ closeConsole(st);
576
+ }
577
+
578
+ /// Block until the session is readable, writable, or nudged — the
579
+ /// POSIX `poll` loop restated over WaitForMultipleObjects. The process
580
+ /// handle rides the wait set until the child exits; from then on the
581
+ /// loop steers the console close that manufactures EOF. A caller
582
+ /// wanting neither direction (a parked reader) waits on the nudge
583
+ /// event alone, the shared parked-reader contract.
584
+ pub fn wait(transport: Pty, nudge_fd: c_int, want_read: bool, want_write: bool) Ready {
585
+ const st = transport.state;
586
+ const nudge_handle = fdToHandle(nudge_fd);
587
+ while (true) {
588
+ var ready: Ready = .{};
589
+ if (want_write) {
590
+ if (st.write_pending) _ = completeWrite(st);
591
+ if (!st.write_pending) ready.writable = true;
592
+ }
593
+ if (want_read) {
594
+ if (st.read_pending) completeRead(st);
595
+ armRead(st);
596
+ if (st.read_len > st.read_off or st.read_eof or st.read_failed) {
597
+ ready.readable = true;
598
+ } else if (st.child_exited) {
599
+ maybeCloseConsole(st);
600
+ }
601
+ }
602
+ if (ready.readable or ready.writable) {
603
+ // Collect a pending nudge without blocking (the POSIX poll
604
+ // reports all readiness at once; auto-reset consumes it).
605
+ if (win.WaitForSingleObject(nudge_handle, 0) == win.WAIT_OBJECT_0) ready.nudged = true;
606
+ return ready;
607
+ }
608
+ var handles: [4]win.HANDLE = undefined;
609
+ var count: win.DWORD = 1;
610
+ handles[0] = nudge_handle;
611
+ var read_index: win.DWORD = 0;
612
+ var process_index: win.DWORD = 0;
613
+ var write_index: win.DWORD = 0;
614
+ if (want_read and st.read_pending) {
615
+ handles[count] = st.read_event;
616
+ read_index = count;
617
+ count += 1;
618
+ }
619
+ if (want_read and !st.child_exited) {
620
+ handles[count] = st.process;
621
+ process_index = count;
622
+ count += 1;
623
+ }
624
+ if (want_write and st.write_pending) {
625
+ handles[count] = st.write_event;
626
+ write_index = count;
627
+ count += 1;
628
+ }
629
+ // Between the child's exit and the console close the loop polls
630
+ // on a short beat instead of blocking: the quiet grace has no
631
+ // waitable handle of its own, and conhost's final render is
632
+ // what the beat is listening for.
633
+ const timeout: win.DWORD = if (want_read and st.child_exited and !st.console_closed)
634
+ 10
635
+ else
636
+ win.INFINITE;
637
+ const r = win.WaitForMultipleObjects(count, &handles, 0, timeout);
638
+ if (r == win.WAIT_TIMEOUT) continue;
639
+ if (r == win.WAIT_FAILED or r >= win.WAIT_OBJECT_0 + count) return .{};
640
+ const index = r - win.WAIT_OBJECT_0;
641
+ if (index == 0) return .{ .nudged = true };
642
+ if (index == process_index) {
643
+ // Already-signaled handles return immediately, so the exit
644
+ // flag must stick before the next iteration rebuilds the
645
+ // wait set without it.
646
+ st.child_exited = true;
647
+ st.child_exited_at_ns = clock.monotonicNanoseconds();
648
+ continue;
649
+ }
650
+ // A read or write completion: fold it in and let the top of
651
+ // the loop report the resulting readiness.
652
+ if (index == read_index) {
653
+ completeRead(st);
654
+ continue;
655
+ }
656
+ if (index == write_index) {
657
+ _ = completeWrite(st);
658
+ continue;
659
+ }
660
+ return .{};
661
+ }
662
+ }
663
+
664
+ /// One spawn: resolve argv[0] through the caller's PATH policy, build
665
+ /// the UTF-16 command line and environment block, open the overlapped
666
+ /// pipe pair, create the pseudoconsole, and launch the child attached
667
+ /// to it. Synchronous verdicts throughout — `CreateProcessW` is the
668
+ /// exec, so there is no self-pipe and no late-failure carry.
669
+ pub fn spawn(gpa: std.mem.Allocator, options: SpawnOptions) Error!Pty {
670
+ if (comptime !is_windows) return error.PtyUnsupported;
671
+ if (options.argv.len == 0 or options.argv.len > pty.max_argv) return error.PtyArgvInvalid;
672
+ for (options.argv) |arg| {
673
+ if (std.mem.indexOfScalar(u8, arg, 0) != null) return error.PtyArgvInvalid;
674
+ }
675
+
676
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
677
+ defer arena_state.deinit();
678
+ const arena = arena_state.allocator();
679
+
680
+ const resolved = resolveExecutable(arena, options.argv[0], options.env) orelse
681
+ return error.PtyCommandNotFound;
682
+ const is_batch = endsWithIgnoreCase(resolved, ".cmd") or endsWithIgnoreCase(resolved, ".bat");
683
+ var interpreter: []const u8 = resolved;
684
+ if (is_batch) {
685
+ // A batch target's command line is REPARSED by cmd.exe with
686
+ // its own metacharacter grammar, which no quoting scheme can
687
+ // neutralize losslessly (`%` expands inside and outside quotes,
688
+ // `^` escapes outside them, `!` follows the child's own
689
+ // delayed-expansion setting) — `safe&whoami` as one argument
690
+ // would splice a second command, and a `%X%` in the SCRIPT
691
+ // PATH itself would expand before cmd resolves it. Bytes the
692
+ // cmd grammar can reinterpret refuse the spawn whole (the
693
+ // argv-NUL teaching applied, and the mainstream standard-
694
+ // library answer to batch argument injection): mutating them
695
+ // would run a different command line than the caller declared.
696
+ // The restriction is part of the documented Windows semantics.
697
+ if (std.mem.indexOfAny(u8, resolved, batch_hostile_bytes) != null) return error.PtyArgvInvalid;
698
+ for (options.argv[1..]) |arg| {
699
+ if (std.mem.indexOfAny(u8, arg, batch_hostile_bytes) != null) return error.PtyArgvInvalid;
700
+ }
701
+ // The command processor is EXPLICIT and PINNED to the OS's own
702
+ // System32 — never the caller's PATH (a PATH-planted cmd.exe
703
+ // must not answer for a trusted script, and a PATH without
704
+ // System32 must not break batch spawns) and never COMSPEC (the
705
+ // same caller-owned trust class) — and invoked with /d, so a
706
+ // machine's AutoRun registry entries cannot splice commands
707
+ // around (or in place of) the requested script the way they
708
+ // would under CreateProcess's implicit batch rewrite.
709
+ interpreter = batchInterpreterPath(arena, options.env) orelse
710
+ return error.PtyCommandNotFound;
711
+ }
712
+ const command_line_w = buildCommandLineW(arena, interpreter, resolved, options.argv, is_batch) catch |err| switch (err) {
713
+ error.InvalidWtf8 => return error.PtyArgvInvalid,
714
+ error.OutOfMemory => return error.PtyEnvironTooLarge,
715
+ };
716
+ // The application name always rides its own argument (never the
717
+ // command line's MAX_PATH-bound module token, so a long-path .exe
718
+ // still starts; cmd itself imposes the MAX_PATH bound on scripts):
719
+ // the resolved executable directly, or the explicit interpreter
720
+ // for a batch target.
721
+ const app_name_w: [*:0]const u16 = app: {
722
+ const len = std.unicode.calcWtf16LeLen(interpreter) catch return error.PtyArgvInvalid;
723
+ const wide = arena.allocSentinel(u16, len, 0) catch return error.PtyEnvironTooLarge;
724
+ _ = std.unicode.wtf8ToWtf16Le(wide, interpreter) catch return error.PtyArgvInvalid;
725
+ break :app wide.ptr;
726
+ };
727
+ const env_block_w = buildEnvironmentBlockW(arena, options.env, options.term) catch |err| switch (err) {
728
+ error.InvalidWtf8 => return error.PtyEnvironTooLarge,
729
+ error.OutOfMemory => return error.PtyEnvironTooLarge,
730
+ };
731
+
732
+ // The pipe pair. Parent ends are overlapped named-pipe servers (the
733
+ // one Windows pipe flavor that can join an event wait); the conhost
734
+ // ends are plain synchronous clients, non-inheritable —
735
+ // CreatePseudoConsole duplicates them into conhost, so nothing here
736
+ // rides handle inheritance and the POSIX CLOEXEC choreography has
737
+ // no analog to need.
738
+ const out_pipe = createOverlappedPipe(.inbound) catch return error.PtyOpenFailed;
739
+ const in_pipe = createOverlappedPipe(.outbound) catch {
740
+ _ = win.CloseHandle(out_pipe.server);
741
+ _ = win.CloseHandle(out_pipe.client);
742
+ return error.PtyOpenFailed;
743
+ };
744
+
745
+ const size: win.COORD = .{
746
+ .X = @intCast(@min(@as(u16, if (options.cols == 0) 80 else options.cols), 32767)),
747
+ .Y = @intCast(@min(@as(u16, if (options.rows == 0) 24 else options.rows), 32767)),
748
+ };
749
+ var hpc: win.HPCON = undefined;
750
+ // flags = 0 on purpose: no PSEUDOCONSOLE_INHERIT_CURSOR (see the
751
+ // file doc — inheriting would make conhost await a DSR answer).
752
+ const hr = win.CreatePseudoConsole(size, in_pipe.client, out_pipe.client, 0, &hpc);
753
+ // The conhost ends are duplicated by CreatePseudoConsole; the
754
+ // originals close now either way.
755
+ _ = win.CloseHandle(in_pipe.client);
756
+ _ = win.CloseHandle(out_pipe.client);
757
+ if (hr < 0) {
758
+ _ = win.CloseHandle(out_pipe.server);
759
+ _ = win.CloseHandle(in_pipe.server);
760
+ return error.PtyOpenFailed;
761
+ }
762
+
763
+ // Attribute list carrying exactly the pseudoconsole attribute.
764
+ var attr_size: usize = 0;
765
+ _ = win.InitializeProcThreadAttributeList(null, 1, 0, &attr_size);
766
+ const attr_buf = arena.alignedAlloc(u8, .of(usize), attr_size) catch {
767
+ failSpawnCleanup(hpc, out_pipe.server, in_pipe.server);
768
+ return error.PtyEnvironTooLarge;
769
+ };
770
+ if (win.InitializeProcThreadAttributeList(attr_buf.ptr, 1, 0, &attr_size) == 0) {
771
+ failSpawnCleanup(hpc, out_pipe.server, in_pipe.server);
772
+ return error.PtyOpenFailed;
773
+ }
774
+ defer win.DeleteProcThreadAttributeList(attr_buf.ptr);
775
+ if (win.UpdateProcThreadAttribute(
776
+ attr_buf.ptr,
777
+ 0,
778
+ win.PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
779
+ hpc,
780
+ @sizeOf(win.HPCON),
781
+ null,
782
+ null,
783
+ ) == 0) {
784
+ failSpawnCleanup(hpc, out_pipe.server, in_pipe.server);
785
+ return error.PtyOpenFailed;
786
+ }
787
+
788
+ var siex = std.mem.zeroes(win.STARTUPINFOEXW);
789
+ siex.StartupInfo.cb = @sizeOf(win.STARTUPINFOEXW);
790
+ siex.lpAttributeList = attr_buf.ptr;
791
+ // STARTF_USESTDHANDLES with NULL handles, deliberately: without
792
+ // it, CreateProcess DUPLICATES the parent's std handles into a
793
+ // console child whenever they do not reference a console (a parent
794
+ // under sshd or CI holds pipes there), and the child's stdio then
795
+ // bypasses the pseudoconsole entirely — output lands on the
796
+ // parent's pipes, not in this transport. Explicit null std handles
797
+ // block that duplication, and console initialization in the child
798
+ // binds the empty slots to its console: the pseudoconsole. (The
799
+ // same choice every ConPTY-hosting terminal makes.)
800
+ siex.StartupInfo.dwFlags = win.STARTF_USESTDHANDLES;
801
+ var pi = std.mem.zeroes(win.PROCESS_INFORMATION);
802
+ // bInheritHandles = FALSE: the child's stdio comes from the
803
+ // pseudoconsole, not from inherited handles — the recommended
804
+ // ConPTY shape, and the reason no parent-side descriptor can leak
805
+ // into the child at all.
806
+ if (win.CreateProcessW(
807
+ app_name_w,
808
+ command_line_w.ptr,
809
+ null,
810
+ null,
811
+ 0,
812
+ win.EXTENDED_STARTUPINFO_PRESENT | win.CREATE_UNICODE_ENVIRONMENT,
813
+ env_block_w.ptr,
814
+ null,
815
+ &siex.StartupInfo,
816
+ &pi,
817
+ ) == 0) {
818
+ const code = lastError();
819
+ failSpawnCleanup(hpc, out_pipe.server, in_pipe.server);
820
+ return switch (code) {
821
+ win.ERROR_FILE_NOT_FOUND,
822
+ win.ERROR_PATH_NOT_FOUND,
823
+ win.ERROR_ACCESS_DENIED,
824
+ win.ERROR_BAD_EXE_FORMAT,
825
+ win.ERROR_INVALID_NAME,
826
+ win.ERROR_DIRECTORY,
827
+ => error.PtyCommandNotFound,
828
+ else => error.PtyForkFailed,
829
+ };
830
+ }
831
+ _ = win.CloseHandle(pi.hThread);
832
+
833
+ const read_event = win.CreateEventW(null, 1, 0, null) orelse {
834
+ _ = win.TerminateProcess(pi.hProcess, 1);
835
+ _ = win.CloseHandle(pi.hProcess);
836
+ failSpawnCleanup(hpc, out_pipe.server, in_pipe.server);
837
+ return error.PtyOpenFailed;
838
+ };
839
+ const write_event = win.CreateEventW(null, 1, 0, null) orelse {
840
+ _ = win.CloseHandle(read_event);
841
+ _ = win.TerminateProcess(pi.hProcess, 1);
842
+ _ = win.CloseHandle(pi.hProcess);
843
+ failSpawnCleanup(hpc, out_pipe.server, in_pipe.server);
844
+ return error.PtyOpenFailed;
845
+ };
846
+ const state = state_allocator.create(State) catch {
847
+ _ = win.CloseHandle(read_event);
848
+ _ = win.CloseHandle(write_event);
849
+ _ = win.TerminateProcess(pi.hProcess, 1);
850
+ _ = win.CloseHandle(pi.hProcess);
851
+ failSpawnCleanup(hpc, out_pipe.server, in_pipe.server);
852
+ return error.PtyEnvironTooLarge;
853
+ };
854
+ state.* = .{
855
+ .hpc = hpc,
856
+ .process = pi.hProcess,
857
+ .out_read = out_pipe.server,
858
+ .in_write = in_pipe.server,
859
+ .read_event = read_event,
860
+ .write_event = write_event,
861
+ };
862
+ return .{ .state = state };
863
+ }
864
+
865
+ /// Spawn-failure cleanup. The pipe ends close BEFORE the
866
+ /// pseudoconsole, deliberately: a fast child (already terminated by
867
+ /// the failing branch) may have filled the output pipe, and a conhost
868
+ /// blocked mid-write would block `ClosePseudoConsole` behind it —
869
+ /// breaking the pipe first turns those writes into immediate failures.
870
+ /// The close itself still rides a detached helper: conhost's own
871
+ /// client shutdown can take its OS-bounded beat (a terminated-but-
872
+ /// wedged child), and a spawn failure must deliver its verdict to the
873
+ /// loop thread now, not after that beat. Inline on helper-spawn
874
+ /// failure — with the pipes already broken, the inline call waits only
875
+ /// on that same OS-bounded shutdown, never a full pipe.
876
+ fn failSpawnCleanup(hpc: win.HPCON, out_server: win.HANDLE, in_server: win.HANDLE) void {
877
+ _ = win.CloseHandle(out_server);
878
+ _ = win.CloseHandle(in_server);
879
+ const thread = std.Thread.spawn(.{}, closeConsoleThreadMain, .{hpc}) catch {
880
+ win.ClosePseudoConsole(hpc);
881
+ return;
882
+ };
883
+ thread.detach();
884
+ }
885
+
886
+ /// Windows process objects self-release; there is no zombie table to
887
+ /// re-poll (see the file doc). Kept for seam parity.
888
+ pub fn reapSurrendered() void {}
889
+
890
+ /// The io thread's nudge, event-shaped: one auto-reset event stands in
891
+ /// for the POSIX self-pipe (SetEvent coalesces exactly like a full
892
+ /// pipe's dropped byte; the wait's wake consumes it, so `drainNudges`
893
+ /// has nothing to drain). Two distinct handles to the one object are
894
+ /// returned so the caller's [read end, write end] close discipline
895
+ /// stays symmetrical.
896
+ pub fn pipePair() Error![2]c_int {
897
+ if (comptime !is_windows) return error.PtyUnsupported;
898
+ const event = win.CreateEventW(null, 0, 0, null) orelse return error.PtyOpenFailed;
899
+ const me = win.GetCurrentProcess();
900
+ var dup: win.HANDLE = undefined;
901
+ if (win.DuplicateHandle(me, event, me, &dup, 0, 0, win.DUPLICATE_SAME_ACCESS) == 0) {
902
+ _ = win.CloseHandle(event);
903
+ return error.PtyOpenFailed;
904
+ }
905
+ return .{ handleToFd(dup), handleToFd(event) };
906
+ }
907
+
908
+ pub fn nudge(fd: c_int) void {
909
+ if (fd == -1) return;
910
+ _ = win.SetEvent(fdToHandle(fd));
911
+ }
912
+
913
+ pub fn drainNudges(fd: c_int) void {
914
+ // Auto-reset: the wait that reported the nudge already consumed it.
915
+ _ = fd;
916
+ }
917
+
918
+ pub fn closeFd(fd: c_int) void {
919
+ if (fd == -1 or fd == 0) return;
920
+ _ = win.CloseHandle(fdToHandle(fd));
921
+ }
922
+
923
+ /// Snapshot the LIVE process environment into the transport's env-list
924
+ /// shape — the Windows half of the effects layer's inherit-the-host
925
+ /// policy (`GetEnvironmentStringsW` is the atomic snapshot; reading the
926
+ /// PEB block raw would race concurrent SetEnvironmentVariable calls).
927
+ /// WTF-16 entries decode to WTF-8 into `bytes`; `TERM` is skipped (the
928
+ /// transport injects its own, and Windows env names are
929
+ /// case-insensitive, so the skip is too). The hidden `=X:=...`
930
+ /// per-drive-directory entries CreateProcess plumbs around ride along
931
+ /// verbatim (name `=X:`, and they sort ahead of every letter, the
932
+ /// block position Windows expects) so a child's drive-relative path
933
+ /// state matches its parent's. Over-bound environments return null —
934
+ /// the same loud whole-or-nothing refusal the POSIX flatten teaches.
935
+ pub fn captureGlobalEnviron(buffer: []EnvVar, bytes: []u8) ?[]const EnvVar {
936
+ if (comptime !is_windows) return null;
937
+ const block = win.GetEnvironmentStringsW() orelse return null;
938
+ defer _ = win.FreeEnvironmentStringsW(block);
939
+ var count: usize = 0;
940
+ var used: usize = 0;
941
+ var index: usize = 0;
942
+ while (block[index] != 0) {
943
+ const start = index;
944
+ while (block[index] != 0) : (index += 1) {}
945
+ const entry_w = block[start..index];
946
+ index += 1; // past the terminator, onto the next entry
947
+ // Decode into the byte pool (WTF-16 -> WTF-8 is at most 3 bytes
948
+ // per code unit; check before converting so a long tail entry
949
+ // cannot overrun).
950
+ if (used + entry_w.len * 3 > bytes.len) {
951
+ if (used + std.unicode.calcWtf8Len(entry_w) > bytes.len) return null;
952
+ }
953
+ const len = std.unicode.wtf16LeToWtf8(bytes[used..], entry_w);
954
+ const entry = bytes[used .. used + len];
955
+ // A leading '=' names the hidden per-drive-directory entries
956
+ // ("=C:=C:\dir"): their name is everything through the drive
957
+ // ("=C:"), so the split looks past the first byte for them.
958
+ const search_from: usize = if (entry.len > 0 and entry[0] == '=') 1 else 0;
959
+ const eq = search_from + (std.mem.indexOfScalar(u8, entry[search_from..], '=') orelse continue);
960
+ const name = entry[0..eq];
961
+ if (asciiEqlIgnoreCase(name, "TERM")) continue;
962
+ if (count == buffer.len) return null;
963
+ if (used + len > pty.max_env_bytes) return null;
964
+ buffer[count] = .{ .name = name, .value = entry[eq + 1 ..] };
965
+ count += 1;
966
+ used += len;
967
+ }
968
+ return buffer[0..count];
969
+ }
970
+
971
+ fn asciiEqlIgnoreCase(a: []const u8, b: []const u8) bool {
972
+ if (a.len != b.len) return false;
973
+ for (a, b) |x, y| {
974
+ if (std.ascii.toUpper(x) != std.ascii.toUpper(y)) return false;
975
+ }
976
+ return true;
977
+ }
978
+
979
+ /// Resolve argv[0] to an executable path, the POSIX resolver's policy
980
+ /// with Windows spelling: a name carrying any path separator (or a
981
+ /// drive) is probed as given; a bare name walks the CALLER-SUPPLIED
982
+ /// env's PATH (`;`-separated, quoted components unwrapped) — never the
983
+ /// process's own PATH, and never the current directory (the classic
984
+ /// Windows CWD-first search is a planted-binary hazard; an app that
985
+ /// wants it says `.\name`). Each candidate is tried as spelled and
986
+ /// with the conventional executable extensions appended — the PATHEXT
987
+ /// idea reduced to the four kinds `CreateProcessW` itself can start.
988
+ fn resolveExecutable(arena: std.mem.Allocator, arg0: []const u8, env: ?[]const EnvVar) ?[]const u8 {
989
+ const has_separator = std.mem.indexOfAny(u8, arg0, "/\\") != null or
990
+ (arg0.len >= 2 and arg0[1] == ':');
991
+ if (has_separator) {
992
+ return probeWithExtensions(arena, "", arg0);
993
+ }
994
+ // Sized for two Windows-directory roots (MAX_PATH each, 3-byte
995
+ // WTF-8 worst case) plus the joining literal.
996
+ var fallback_path_buf: [2 * 260 * 3 + 16]u8 = undefined;
997
+ const path = lookupEnvIgnoreCase(env, "PATH") orelse systemPathFallback(env, &fallback_path_buf);
998
+ var it = std.mem.splitScalar(u8, path, ';');
999
+ while (it.next()) |raw_component| {
1000
+ // Quoted PATH components are a Windows convention; the quotes
1001
+ // are wrapper, not path. Empty components are SKIPPED, never
1002
+ // "the current directory" (the deliberate no-CWD policy above).
1003
+ const component = std.mem.trim(u8, raw_component, "\"");
1004
+ if (component.len == 0) continue;
1005
+ if (probeWithExtensions(arena, component, arg0)) |found| return found;
1006
+ }
1007
+ return null;
1008
+ }
1009
+
1010
+ /// The PATH stand-in when the caller's env carries none: the system
1011
+ /// directories under the real Windows root — the env's own
1012
+ /// `SystemRoot`/`windir` first, then the OS's answer
1013
+ /// (`GetWindowsDirectoryW`, so an install under D:\Windows still
1014
+ /// resolves bare names), and the conventional literal only when both
1015
+ /// fail.
1016
+ fn systemPathFallback(env: ?[]const EnvVar, buf: []u8) []const u8 {
1017
+ var root_buf: [windows_root_bytes]u8 = undefined;
1018
+ const root = windowsRoot(env, &root_buf);
1019
+ return std.fmt.bufPrint(buf, "{s}\\System32;{s}", .{ root, root }) catch "C:\\Windows\\System32;C:\\Windows";
1020
+ }
1021
+
1022
+ /// The Windows directory is bounded at MAX_PATH (260) UTF-16 units;
1023
+ /// WTF-8 needs at most 3 bytes per unit.
1024
+ const windows_root_bytes = 260 * 3;
1025
+
1026
+ /// The real Windows root, OS truth first: `GetWindowsDirectoryW` is
1027
+ /// what an install under D:\Windows answers regardless of what the
1028
+ /// caller's env claims; the env's `SystemRoot`/`windir` and the
1029
+ /// conventional literal are the fallbacks for the corner where the
1030
+ /// call itself fails.
1031
+ fn windowsRoot(env: ?[]const EnvVar, buf: *[windows_root_bytes]u8) []const u8 {
1032
+ if (comptime is_windows) {
1033
+ var wide: [260]u16 = undefined;
1034
+ const len = win.GetWindowsDirectoryW(&wide, @intCast(wide.len));
1035
+ if (len > 0 and len < wide.len) {
1036
+ const decoded_len = std.unicode.wtf16LeToWtf8(buf, wide[0..len]);
1037
+ return buf[0..decoded_len];
1038
+ }
1039
+ }
1040
+ if (lookupEnvIgnoreCase(env, "SystemRoot")) |value| return value;
1041
+ if (lookupEnvIgnoreCase(env, "windir")) |value| return value;
1042
+ return "C:\\Windows";
1043
+ }
1044
+
1045
+ /// The pinned batch interpreter: `<windows root>\System32\cmd.exe`,
1046
+ /// probed for existence — a missing system cmd.exe reports the spawn
1047
+ /// as command-not-found rather than falling back to anything the
1048
+ /// caller could plant.
1049
+ fn batchInterpreterPath(arena: std.mem.Allocator, env: ?[]const EnvVar) ?[]const u8 {
1050
+ var root_buf: [windows_root_bytes]u8 = undefined;
1051
+ const root = windowsRoot(env, &root_buf);
1052
+ const candidate = std.fmt.allocPrint(arena, "{s}\\System32\\cmd.exe", .{root}) catch return null;
1053
+ if (!executableAt(arena, candidate)) return null;
1054
+ return candidate;
1055
+ }
1056
+
1057
+ /// The executable-extension allowlist for EXTENSION-LESS names: the
1058
+ /// runnable suffixes first (`.exe`, `.cmd`, `.bat`, `.com` — the
1059
+ /// shapes the spawn can start; `.cmd`/`.bat` route through the
1060
+ /// explicit `cmd.exe /d /s /c` form), the bare spelling LAST — so a
1061
+ /// same-named plain file next to a real `tool.exe` or `tool.cmd`
1062
+ /// cannot mask them (the CreateProcess/PATHEXT ordering, where an
1063
+ /// extension-less name means its runnable suffixes before itself).
1064
+ const executable_extensions = [_][]const u8{ ".exe", ".cmd", ".bat", ".com", "" };
1065
+
1066
+ fn probeWithExtensions(arena: std.mem.Allocator, dir: []const u8, name: []const u8) ?[]const u8 {
1067
+ // A name that already carries an extension is probed AS SPELLED
1068
+ // only: appending further suffixes would let a co-located
1069
+ // `tool.cmd.exe` answer for a missing `tool.cmd` — the
1070
+ // CreateProcess convention (.exe joins extension-less names only),
1071
+ // kept for the whole allowlist.
1072
+ const extensions: []const []const u8 = if (hasExtension(name)) &.{""} else &executable_extensions;
1073
+ for (extensions) |ext| {
1074
+ const candidate = if (dir.len == 0)
1075
+ std.fmt.allocPrint(arena, "{s}{s}", .{ name, ext }) catch return null
1076
+ else
1077
+ std.fmt.allocPrint(arena, "{s}\\{s}{s}", .{ dir, name, ext }) catch return null;
1078
+ if (executableAt(arena, candidate)) return candidate;
1079
+ }
1080
+ return null;
1081
+ }
1082
+
1083
+ /// Existence-and-not-a-directory probe (Windows has no X_OK; being a
1084
+ /// readable file is the closest honest analog, and `CreateProcessW`
1085
+ /// delivers the final verdict synchronously either way). The wide
1086
+ /// copy sizes to the CANDIDATE — a PATH component can outgrow any
1087
+ /// fixed stack buffer (`\\?\` prefixed directories), and the arena
1088
+ /// already owns the spawn's transient conversions.
1089
+ fn executableAt(arena: std.mem.Allocator, path: []const u8) bool {
1090
+ if (comptime !is_windows) return false;
1091
+ const len = std.unicode.calcWtf16LeLen(path) catch return false;
1092
+ const wide = arena.allocSentinel(u16, len, 0) catch return false;
1093
+ _ = std.unicode.wtf8ToWtf16Le(wide, path) catch return false;
1094
+ const attrs = win.GetFileAttributesW(wide.ptr);
1095
+ if (attrs == win.INVALID_FILE_ATTRIBUTES) return false;
1096
+ return attrs & win.FILE_ATTRIBUTE_DIRECTORY == 0;
1097
+ }
1098
+
1099
+ /// Whether the LAST PATH COMPONENT carries an extension (a leading dot
1100
+ /// alone names a hidden-style file, not an extension).
1101
+ fn hasExtension(name: []const u8) bool {
1102
+ const base_start = if (std.mem.lastIndexOfAny(u8, name, "/\\:")) |index| index + 1 else 0;
1103
+ const base = name[base_start..];
1104
+ const dot = std.mem.lastIndexOfScalar(u8, base, '.') orelse return false;
1105
+ return dot != 0;
1106
+ }
1107
+
1108
+ fn endsWithIgnoreCase(text: []const u8, suffix: []const u8) bool {
1109
+ if (text.len < suffix.len) return false;
1110
+ return asciiEqlIgnoreCase(text[text.len - suffix.len ..], suffix);
1111
+ }
1112
+
1113
+ fn lookupEnvIgnoreCase(env: ?[]const EnvVar, name: []const u8) ?[]const u8 {
1114
+ const list = env orelse return null;
1115
+ for (list) |entry| {
1116
+ if (asciiEqlIgnoreCase(entry.name, name)) return entry.value;
1117
+ }
1118
+ return null;
1119
+ }
1120
+
1121
+ /// Bytes cmd.exe's reparse can reinterpret inside a batch command
1122
+ /// line: command splicers, redirections, escapes, variable expansion,
1123
+ /// quotes (cmd's quote rules differ from the CRT's), and line breaks.
1124
+ const batch_hostile_bytes = "&|<>^%!\"\r\n";
1125
+
1126
+ /// Build the mutable UTF-16 command line `CreateProcessW` parses.
1127
+ ///
1128
+ /// Direct executables: the first token is the CALLER's argv[0]
1129
+ /// spelling (the module comes from `lpApplicationName`, so a multicall
1130
+ /// binary observes the name it was invoked by — POSIX argv[0] parity),
1131
+ /// and arguments use the standard CommandLineToArgvW-inverse quoting,
1132
+ /// so a conforming child recovers each byte-exactly.
1133
+ ///
1134
+ /// Batch targets: `"<cmd.exe>" /d /s /c ""<script>" "arg"..."` — the
1135
+ /// explicit, AutoRun-disabled interpreter form (/s pins the standard
1136
+ /// quote treatment; the outer quote pair is what /s strips). Every
1137
+ /// argument is ALWAYS quoted — a bare `foo)` token could close a block
1138
+ /// in cmd's reparse, and quotes make delimiters and grouping bytes
1139
+ /// literal — with NO backslash doubling: cmd reads backslashes
1140
+ /// literally, so the CRT's trailing-run doubling would hand a script
1141
+ /// `\\` where the caller said `\`. (The bytes quoting cannot make
1142
+ /// literal were refused at admission.)
1143
+ fn buildCommandLineW(
1144
+ arena: std.mem.Allocator,
1145
+ interpreter: []const u8,
1146
+ resolved: []const u8,
1147
+ argv: []const []const u8,
1148
+ is_batch: bool,
1149
+ ) (error{ InvalidWtf8, OutOfMemory })![:0]u16 {
1150
+ var line: std.ArrayList(u8) = .empty;
1151
+ try line.append(arena, '"');
1152
+ try line.appendSlice(arena, if (is_batch) interpreter else argv[0]);
1153
+ try line.append(arena, '"');
1154
+ if (is_batch) {
1155
+ try line.appendSlice(arena, " /d /s /c \"\"");
1156
+ try line.appendSlice(arena, resolved);
1157
+ try line.append(arena, '"');
1158
+ }
1159
+ for (argv[1..]) |arg| {
1160
+ try line.append(arena, ' ');
1161
+ if (is_batch) {
1162
+ try line.append(arena, '"');
1163
+ try line.appendSlice(arena, arg);
1164
+ try line.append(arena, '"');
1165
+ continue;
1166
+ }
1167
+ try appendQuotedArg(arena, &line, arg);
1168
+ }
1169
+ if (is_batch) try line.append(arena, '"');
1170
+ const wide_len = std.unicode.calcWtf16LeLen(line.items) catch return error.InvalidWtf8;
1171
+ const wide = try arena.allocSentinel(u16, wide_len, 0);
1172
+ _ = try std.unicode.wtf8ToWtf16Le(wide, line.items);
1173
+ return wide;
1174
+ }
1175
+
1176
+ /// The CommandLineToArgvW inverse: quote when the argument is empty or
1177
+ /// carries a space, tab, or quote; inside quotes, N backslashes before
1178
+ /// a quote double to 2N (+1 with the escaped quote), and a trailing
1179
+ /// run doubles before the closing quote.
1180
+ fn appendQuotedArg(arena: std.mem.Allocator, line: *std.ArrayList(u8), arg: []const u8) error{OutOfMemory}!void {
1181
+ const needs_quotes = arg.len == 0 or std.mem.indexOfAny(u8, arg, " \t\"") != null;
1182
+ if (!needs_quotes) {
1183
+ try line.appendSlice(arena, arg);
1184
+ return;
1185
+ }
1186
+ try line.append(arena, '"');
1187
+ var backslashes: usize = 0;
1188
+ for (arg) |byte| {
1189
+ if (byte == '\\') {
1190
+ backslashes += 1;
1191
+ continue;
1192
+ }
1193
+ if (byte == '"') {
1194
+ try line.appendNTimes(arena, '\\', backslashes * 2 + 1);
1195
+ try line.append(arena, '"');
1196
+ } else {
1197
+ try line.appendNTimes(arena, '\\', backslashes);
1198
+ try line.append(arena, byte);
1199
+ }
1200
+ backslashes = 0;
1201
+ }
1202
+ try line.appendNTimes(arena, '\\', backslashes * 2);
1203
+ try line.append(arena, '"');
1204
+ }
1205
+
1206
+ /// Build the UTF-16 `name=value\0...\0\0` environment block: the
1207
+ /// caller's env (or nothing) plus the injected/replacing `TERM` — the
1208
+ /// exact POSIX `buildEnvpZ` policy — sorted with the case-insensitive
1209
+ /// ordinal order the CreateProcessW documentation requires of Unicode
1210
+ /// blocks. `TERM` matching is case-insensitive here because Windows
1211
+ /// environment names are.
1212
+ fn buildEnvironmentBlockW(
1213
+ arena: std.mem.Allocator,
1214
+ env: ?[]const EnvVar,
1215
+ term: []const u8,
1216
+ ) (error{ InvalidWtf8, OutOfMemory })![:0]u16 {
1217
+ const list = env orelse &[_]EnvVar{};
1218
+ if (list.len > pty.max_env_entries) return error.OutOfMemory;
1219
+ var entries: [pty.max_env_entries + 1]EnvVar = undefined;
1220
+ var count: usize = 0;
1221
+ var total_bytes: usize = 0;
1222
+ var has_term = false;
1223
+ for (list) |entry| {
1224
+ // NUL-bearing names or values would silently terminate the
1225
+ // block early at the UTF-16 boundary: reject via the
1226
+ // whole-or-nothing env error, the argv-NUL teaching applied.
1227
+ if (std.mem.indexOfScalar(u8, entry.name, 0) != null or
1228
+ std.mem.indexOfScalar(u8, entry.value, 0) != null)
1229
+ {
1230
+ return error.InvalidWtf8;
1231
+ }
1232
+ if (asciiEqlIgnoreCase(entry.name, "TERM")) {
1233
+ // The requested TERM REPLACES an inherited one, the shared
1234
+ // rule: the spawn declared what terminal the child is
1235
+ // attached to.
1236
+ entries[count] = .{ .name = "TERM", .value = term };
1237
+ has_term = true;
1238
+ } else {
1239
+ entries[count] = entry;
1240
+ }
1241
+ total_bytes += entry.name.len + entry.value.len;
1242
+ if (total_bytes > pty.max_env_bytes) return error.OutOfMemory;
1243
+ count += 1;
1244
+ }
1245
+ if (!has_term) {
1246
+ entries[count] = .{ .name = "TERM", .value = term };
1247
+ count += 1;
1248
+ }
1249
+ std.mem.sort(EnvVar, entries[0..count], {}, envNameLessThan);
1250
+
1251
+ var flat: std.ArrayList(u8) = .empty;
1252
+ for (entries[0..count]) |entry| {
1253
+ try flat.appendSlice(arena, entry.name);
1254
+ try flat.append(arena, '=');
1255
+ try flat.appendSlice(arena, entry.value);
1256
+ try flat.append(arena, 0);
1257
+ }
1258
+ // An empty environment still needs one terminating NUL entry ahead
1259
+ // of the block terminator.
1260
+ if (count == 0) try flat.append(arena, 0);
1261
+ const wide_len = std.unicode.calcWtf16LeLen(flat.items) catch return error.InvalidWtf8;
1262
+ const wide = try arena.allocSentinel(u16, wide_len, 0);
1263
+ _ = try std.unicode.wtf8ToWtf16Le(wide, flat.items);
1264
+ return wide;
1265
+ }
1266
+
1267
+ /// The environment-block contract's order: name comparison is
1268
+ /// case-insensitive in the order the OS itself compares environment
1269
+ /// names — UTF-16 CODE UNITS (a supplementary-plane name sorts by its
1270
+ /// surrogate halves, BELOW the private-use BMP range, exactly as
1271
+ /// `RtlCompareUnicodeString` would), each unit folded through the OS's
1272
+ /// own BMP uppercase table (`toUpperWtf16`, the same fold std's
1273
+ /// Windows env-name hashing uses) — never WTF-8 bytes or code points.
1274
+ /// A name that is not valid WTF-8 falls back to byte order; the block
1275
+ /// build refuses such an environment moments later with the
1276
+ /// whole-or-nothing env error, so the fallback never reaches a child.
1277
+ fn envNameLessThan(_: void, a: EnvVar, b: EnvVar) bool {
1278
+ const view_a = std.unicode.Wtf8View.init(a.name) catch return std.mem.lessThan(u8, a.name, b.name);
1279
+ const view_b = std.unicode.Wtf8View.init(b.name) catch return std.mem.lessThan(u8, a.name, b.name);
1280
+ var it_a: Wtf16UnitIterator = .{ .inner = view_a.iterator() };
1281
+ var it_b: Wtf16UnitIterator = .{ .inner = view_b.iterator() };
1282
+ while (true) {
1283
+ const unit_a = it_a.next() orelse return it_b.next() != null;
1284
+ const unit_b = it_b.next() orelse return false;
1285
+ const upper_a = std.os.windows.toUpperWtf16(unit_a);
1286
+ const upper_b = std.os.windows.toUpperWtf16(unit_b);
1287
+ if (upper_a != upper_b) return upper_a < upper_b;
1288
+ }
1289
+ }
1290
+
1291
+ /// WTF-8 code points re-emitted as WTF-16 code units (supplementary
1292
+ /// planes as their surrogate pair; WTF-8's unpaired surrogates pass
1293
+ /// through as themselves).
1294
+ const Wtf16UnitIterator = struct {
1295
+ inner: std.unicode.Wtf8Iterator,
1296
+ pending_low: ?u16 = null,
1297
+
1298
+ fn next(self: *Wtf16UnitIterator) ?u16 {
1299
+ if (self.pending_low) |low| {
1300
+ self.pending_low = null;
1301
+ return low;
1302
+ }
1303
+ const cp = self.inner.nextCodepoint() orelse return null;
1304
+ if (cp < 0x10000) return @intCast(cp);
1305
+ const offset = cp - 0x10000;
1306
+ self.pending_low = @intCast(0xDC00 + (offset & 0x3FF));
1307
+ return @intCast(0xD800 + (offset >> 10));
1308
+ }
1309
+ };
1310
+
1311
+ /// Monotonic counter distinguishing concurrent spawns' pipe names
1312
+ /// (pipe names are a global namespace; the pid alone is not unique
1313
+ /// across two runtime instances' simultaneous spawns in one process).
1314
+ var pipe_counter = std.atomic.Value(u64).init(0);
1315
+
1316
+ const PipeDirection = enum { inbound, outbound };
1317
+
1318
+ const PipeEnds = struct {
1319
+ server: win.HANDLE,
1320
+ client: win.HANDLE,
1321
+ };
1322
+
1323
+ /// One overlapped byte pipe: the parent keeps the overlapped server
1324
+ /// end; the synchronous client end goes to `CreatePseudoConsole`.
1325
+ /// FIRST_PIPE_INSTANCE + REJECT_REMOTE_CLIENTS keep the name squat
1326
+ /// window honest: a squatter holding the name fails the create rather
1327
+ /// than intercepting the console stream.
1328
+ fn createOverlappedPipe(direction: PipeDirection) error{PipeFailed}!PipeEnds {
1329
+ if (comptime !is_windows) return error.PipeFailed;
1330
+ const serial = pipe_counter.fetchAdd(1, .monotonic);
1331
+ var name_buf: [128]u8 = undefined;
1332
+ const name = std.fmt.bufPrint(&name_buf, "\\\\.\\pipe\\native-sdk-conpty-{d}-{d}", .{
1333
+ win.GetCurrentProcessId(),
1334
+ serial,
1335
+ }) catch return error.PipeFailed;
1336
+ var name_w: [160]u16 = undefined;
1337
+ const name_len = std.unicode.wtf8ToWtf16Le(name_w[0 .. name_w.len - 1], name) catch return error.PipeFailed;
1338
+ name_w[name_len] = 0;
1339
+ const name_z = name_w[0..name_len :0];
1340
+
1341
+ const open_mode: win.DWORD = win.FILE_FLAG_OVERLAPPED | win.FILE_FLAG_FIRST_PIPE_INSTANCE |
1342
+ (if (direction == .inbound) win.PIPE_ACCESS_INBOUND else win.PIPE_ACCESS_OUTBOUND);
1343
+ const server = win.CreateNamedPipeW(
1344
+ name_z.ptr,
1345
+ open_mode,
1346
+ win.PIPE_TYPE_BYTE | win.PIPE_READMODE_BYTE | win.PIPE_WAIT | win.PIPE_REJECT_REMOTE_CLIENTS,
1347
+ 1,
1348
+ pipe_buffer_bytes,
1349
+ pipe_buffer_bytes,
1350
+ 0,
1351
+ null,
1352
+ );
1353
+ if (server == win.INVALID_HANDLE_VALUE) return error.PipeFailed;
1354
+ const client_access: win.DWORD = if (direction == .inbound) win.GENERIC_WRITE else win.GENERIC_READ;
1355
+ const client = win.CreateFileW(
1356
+ name_z.ptr,
1357
+ client_access,
1358
+ 0,
1359
+ null,
1360
+ win.OPEN_EXISTING,
1361
+ 0,
1362
+ null,
1363
+ );
1364
+ if (client == win.INVALID_HANDLE_VALUE) {
1365
+ _ = win.CloseHandle(server);
1366
+ return error.PipeFailed;
1367
+ }
1368
+ return .{ .server = server, .client = client };
1369
+ }
1370
+
1371
+ /// Kernel handles are 32-bit significant by contract (the WOW64
1372
+ /// interoperability guarantee: only the low 32 bits carry identity,
1373
+ /// sign-extended to 64) — so a HANDLE rides the seam's c_int the way a
1374
+ /// POSIX fd does, and -1 stays the shared closed sentinel
1375
+ /// (INVALID_HANDLE_VALUE maps to -1 and is never a live event).
1376
+ fn handleToFd(handle: win.HANDLE) c_int {
1377
+ return @bitCast(@as(u32, @truncate(@intFromPtr(handle))));
1378
+ }
1379
+
1380
+ fn fdToHandle(fd: c_int) win.HANDLE {
1381
+ const wide: isize = fd; // sign-extend, the documented widening
1382
+ return @ptrFromInt(@as(usize, @bitCast(wide)));
1383
+ }
1384
+
1385
+ fn lastError() u32 {
1386
+ return @intFromEnum(std.os.windows.GetLastError());
1387
+ }
1388
+
1389
+ /// Self-contained Win32 surface, the file's `extern "c"` analog: only
1390
+ /// what the transport calls, declared here so the runtime keeps zero
1391
+ /// dependence on the platform layer's bindings. Everything below is a
1392
+ /// documented kernel32 export on the supported Windows floor (ConPTY:
1393
+ /// Windows 10 1809+).
1394
+ const win = struct {
1395
+ const HANDLE = std.os.windows.HANDLE;
1396
+ const HPCON = *anyopaque;
1397
+ const DWORD = u32;
1398
+ const BOOL = i32;
1399
+ const HRESULT = i32;
1400
+ const COORD = extern struct { X: i16, Y: i16 };
1401
+ const OVERLAPPED = extern struct {
1402
+ Internal: usize = 0,
1403
+ InternalHigh: usize = 0,
1404
+ Offset: DWORD = 0,
1405
+ OffsetHigh: DWORD = 0,
1406
+ hEvent: ?HANDLE = null,
1407
+ };
1408
+ const SECURITY_ATTRIBUTES = std.os.windows.SECURITY_ATTRIBUTES;
1409
+ const STARTUPINFOW = std.os.windows.STARTUPINFOW;
1410
+ const STARTUPINFOEXW = extern struct {
1411
+ StartupInfo: STARTUPINFOW,
1412
+ lpAttributeList: ?*anyopaque,
1413
+ };
1414
+ const PROCESS_INFORMATION = extern struct {
1415
+ hProcess: HANDLE,
1416
+ hThread: HANDLE,
1417
+ dwProcessId: DWORD,
1418
+ dwThreadId: DWORD,
1419
+ };
1420
+
1421
+ const INVALID_HANDLE_VALUE = std.os.windows.INVALID_HANDLE_VALUE;
1422
+ const INVALID_FILE_ATTRIBUTES: DWORD = 0xFFFF_FFFF;
1423
+ const FILE_ATTRIBUTE_DIRECTORY: DWORD = 0x10;
1424
+ const GENERIC_READ: DWORD = 0x8000_0000;
1425
+ const GENERIC_WRITE: DWORD = 0x4000_0000;
1426
+ const OPEN_EXISTING: DWORD = 3;
1427
+ const PIPE_ACCESS_INBOUND: DWORD = 0x1;
1428
+ const PIPE_ACCESS_OUTBOUND: DWORD = 0x2;
1429
+ const FILE_FLAG_FIRST_PIPE_INSTANCE: DWORD = 0x0008_0000;
1430
+ const FILE_FLAG_OVERLAPPED: DWORD = 0x4000_0000;
1431
+ const PIPE_TYPE_BYTE: DWORD = 0x0;
1432
+ const PIPE_READMODE_BYTE: DWORD = 0x0;
1433
+ const PIPE_WAIT: DWORD = 0x0;
1434
+ const PIPE_REJECT_REMOTE_CLIENTS: DWORD = 0x8;
1435
+ const EXTENDED_STARTUPINFO_PRESENT: DWORD = 0x0008_0000;
1436
+ const CREATE_UNICODE_ENVIRONMENT: DWORD = 0x0000_0400;
1437
+ const PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE: usize = 0x0002_0016;
1438
+ const DUPLICATE_SAME_ACCESS: DWORD = 0x2;
1439
+ const STARTF_USESTDHANDLES: DWORD = 0x100;
1440
+ const INFINITE: DWORD = 0xFFFF_FFFF;
1441
+ const WAIT_OBJECT_0: DWORD = 0;
1442
+ const WAIT_TIMEOUT: DWORD = 0x102;
1443
+ const WAIT_FAILED: DWORD = 0xFFFF_FFFF;
1444
+ const ERROR_FILE_NOT_FOUND: u32 = 2;
1445
+ const ERROR_PATH_NOT_FOUND: u32 = 3;
1446
+ const ERROR_ACCESS_DENIED: u32 = 5;
1447
+ const ERROR_HANDLE_EOF: u32 = 38;
1448
+ const ERROR_BROKEN_PIPE: u32 = 109;
1449
+ const ERROR_INVALID_NAME: u32 = 123;
1450
+ const ERROR_BAD_EXE_FORMAT: u32 = 193;
1451
+ const ERROR_PIPE_NOT_CONNECTED: u32 = 233;
1452
+ const ERROR_DIRECTORY: u32 = 267;
1453
+ const ERROR_IO_INCOMPLETE: u32 = 996;
1454
+ const ERROR_IO_PENDING: u32 = 997;
1455
+
1456
+ extern "kernel32" fn CreateNamedPipeW(
1457
+ lpName: [*:0]const u16,
1458
+ dwOpenMode: DWORD,
1459
+ dwPipeMode: DWORD,
1460
+ nMaxInstances: DWORD,
1461
+ nOutBufferSize: DWORD,
1462
+ nInBufferSize: DWORD,
1463
+ nDefaultTimeOut: DWORD,
1464
+ lpSecurityAttributes: ?*SECURITY_ATTRIBUTES,
1465
+ ) callconv(.winapi) HANDLE;
1466
+ extern "kernel32" fn CreateFileW(
1467
+ lpFileName: [*:0]const u16,
1468
+ dwDesiredAccess: DWORD,
1469
+ dwShareMode: DWORD,
1470
+ lpSecurityAttributes: ?*SECURITY_ATTRIBUTES,
1471
+ dwCreationDisposition: DWORD,
1472
+ dwFlagsAndAttributes: DWORD,
1473
+ hTemplateFile: ?HANDLE,
1474
+ ) callconv(.winapi) HANDLE;
1475
+ extern "kernel32" fn CreateEventW(
1476
+ lpEventAttributes: ?*SECURITY_ATTRIBUTES,
1477
+ bManualReset: BOOL,
1478
+ bInitialState: BOOL,
1479
+ lpName: ?[*:0]const u16,
1480
+ ) callconv(.winapi) ?HANDLE;
1481
+ extern "kernel32" fn SetEvent(hEvent: HANDLE) callconv(.winapi) BOOL;
1482
+ extern "kernel32" fn ResetEvent(hEvent: HANDLE) callconv(.winapi) BOOL;
1483
+ extern "kernel32" fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) callconv(.winapi) DWORD;
1484
+ extern "kernel32" fn WaitForMultipleObjects(
1485
+ nCount: DWORD,
1486
+ lpHandles: [*]const HANDLE,
1487
+ bWaitAll: BOOL,
1488
+ dwMilliseconds: DWORD,
1489
+ ) callconv(.winapi) DWORD;
1490
+ extern "kernel32" fn ReadFile(
1491
+ hFile: HANDLE,
1492
+ lpBuffer: [*]u8,
1493
+ nNumberOfBytesToRead: DWORD,
1494
+ lpNumberOfBytesRead: ?*DWORD,
1495
+ lpOverlapped: ?*OVERLAPPED,
1496
+ ) callconv(.winapi) BOOL;
1497
+ extern "kernel32" fn WriteFile(
1498
+ hFile: HANDLE,
1499
+ lpBuffer: [*]const u8,
1500
+ nNumberOfBytesToWrite: DWORD,
1501
+ lpNumberOfBytesWritten: ?*DWORD,
1502
+ lpOverlapped: ?*OVERLAPPED,
1503
+ ) callconv(.winapi) BOOL;
1504
+ extern "kernel32" fn GetOverlappedResult(
1505
+ hFile: HANDLE,
1506
+ lpOverlapped: *OVERLAPPED,
1507
+ lpNumberOfBytesTransferred: *DWORD,
1508
+ bWait: BOOL,
1509
+ ) callconv(.winapi) BOOL;
1510
+ extern "kernel32" fn PeekNamedPipe(
1511
+ hNamedPipe: HANDLE,
1512
+ lpBuffer: ?[*]u8,
1513
+ nBufferSize: DWORD,
1514
+ lpBytesRead: ?*DWORD,
1515
+ lpTotalBytesAvail: ?*DWORD,
1516
+ lpBytesLeftThisMessage: ?*DWORD,
1517
+ ) callconv(.winapi) BOOL;
1518
+ extern "kernel32" fn CancelIoEx(hFile: HANDLE, lpOverlapped: ?*OVERLAPPED) callconv(.winapi) BOOL;
1519
+ extern "kernel32" fn CloseHandle(hObject: HANDLE) callconv(.winapi) BOOL;
1520
+ extern "kernel32" fn CreateProcessW(
1521
+ lpApplicationName: ?[*:0]const u16,
1522
+ lpCommandLine: ?[*:0]u16,
1523
+ lpProcessAttributes: ?*SECURITY_ATTRIBUTES,
1524
+ lpThreadAttributes: ?*SECURITY_ATTRIBUTES,
1525
+ bInheritHandles: BOOL,
1526
+ dwCreationFlags: DWORD,
1527
+ lpEnvironment: ?[*:0]const u16,
1528
+ lpCurrentDirectory: ?[*:0]const u16,
1529
+ lpStartupInfo: *STARTUPINFOW,
1530
+ lpProcessInformation: *PROCESS_INFORMATION,
1531
+ ) callconv(.winapi) BOOL;
1532
+ extern "kernel32" fn TerminateProcess(hProcess: HANDLE, uExitCode: DWORD) callconv(.winapi) BOOL;
1533
+ extern "kernel32" fn GetExitCodeProcess(hProcess: HANDLE, lpExitCode: *DWORD) callconv(.winapi) BOOL;
1534
+ extern "kernel32" fn InitializeProcThreadAttributeList(
1535
+ lpAttributeList: ?*anyopaque,
1536
+ dwAttributeCount: DWORD,
1537
+ dwFlags: DWORD,
1538
+ lpSize: *usize,
1539
+ ) callconv(.winapi) BOOL;
1540
+ extern "kernel32" fn UpdateProcThreadAttribute(
1541
+ lpAttributeList: *anyopaque,
1542
+ dwFlags: DWORD,
1543
+ Attribute: usize,
1544
+ lpValue: ?*anyopaque,
1545
+ cbSize: usize,
1546
+ lpPreviousValue: ?*anyopaque,
1547
+ lpReturnSize: ?*usize,
1548
+ ) callconv(.winapi) BOOL;
1549
+ extern "kernel32" fn DeleteProcThreadAttributeList(lpAttributeList: *anyopaque) callconv(.winapi) void;
1550
+ extern "kernel32" fn CreatePseudoConsole(
1551
+ size: COORD,
1552
+ hInput: HANDLE,
1553
+ hOutput: HANDLE,
1554
+ dwFlags: DWORD,
1555
+ phPC: *HPCON,
1556
+ ) callconv(.winapi) HRESULT;
1557
+ extern "kernel32" fn ResizePseudoConsole(hPC: HPCON, size: COORD) callconv(.winapi) HRESULT;
1558
+ extern "kernel32" fn ClosePseudoConsole(hPC: HPCON) callconv(.winapi) void;
1559
+ extern "kernel32" fn GetFileAttributesW(lpFileName: [*:0]const u16) callconv(.winapi) DWORD;
1560
+ extern "kernel32" fn GetWindowsDirectoryW(lpBuffer: [*]u16, uSize: u32) callconv(.winapi) u32;
1561
+ extern "kernel32" fn GetEnvironmentStringsW() callconv(.winapi) ?[*:0]u16;
1562
+ extern "kernel32" fn FreeEnvironmentStringsW(penv: [*:0]u16) callconv(.winapi) BOOL;
1563
+ extern "kernel32" fn GetCurrentProcess() callconv(.winapi) HANDLE;
1564
+ extern "kernel32" fn GetCurrentProcessId() callconv(.winapi) DWORD;
1565
+ extern "kernel32" fn DuplicateHandle(
1566
+ hSourceProcessHandle: HANDLE,
1567
+ hSourceHandle: HANDLE,
1568
+ hTargetProcessHandle: HANDLE,
1569
+ lpTargetHandle: *HANDLE,
1570
+ dwDesiredAccess: DWORD,
1571
+ bInheritHandle: BOOL,
1572
+ dwOptions: DWORD,
1573
+ ) callconv(.winapi) BOOL;
1574
+ };
1575
+
1576
+ // ------------------------------------------------------------------ tests
1577
+
1578
+ /// The io loop's poll discipline condensed for in-file tests, the
1579
+ /// POSIX `testReadAll`'s Windows twin: a real nudge pair joins the
1580
+ /// wait so the loop shape matches the effects thread exactly.
1581
+ fn testReadAll(p: Pty, nudge_fd: c_int, buf: []u8) usize {
1582
+ var total: usize = 0;
1583
+ while (total < buf.len) {
1584
+ const ready = wait(p, nudge_fd, true, false);
1585
+ if (!ready.readable) continue;
1586
+ const n = p.read(buf[total..]) catch |err| switch (err) {
1587
+ error.WouldBlock => continue,
1588
+ error.ReadFailed => return total,
1589
+ };
1590
+ if (n == 0) return total;
1591
+ total += n;
1592
+ }
1593
+ return total;
1594
+ }
1595
+
1596
+ /// cmd.exe needs SystemRoot to start (it resolves its own DLL world
1597
+ /// through it), so the clean-environment tests carry the one variable
1598
+ /// the OS itself requires — the POSIX tests' /bin/sh needed nothing,
1599
+ /// but the policy under test (nothing leaks in but what the caller
1600
+ /// listed, plus TERM) is identical.
1601
+ const system_root_env: EnvVar = .{ .name = "SystemRoot", .value = "C:\\Windows" };
1602
+
1603
+ test "windows spawn rejects an empty argv and a missing command" {
1604
+ if (comptime !is_windows) return;
1605
+ try std.testing.expectError(error.PtyArgvInvalid, spawn(std.testing.allocator, .{ .argv = &.{} }));
1606
+ try std.testing.expectError(error.PtyCommandNotFound, spawn(std.testing.allocator, .{
1607
+ .argv = &.{"never-a-command-native-sdk"},
1608
+ }));
1609
+ try std.testing.expectError(error.PtyCommandNotFound, spawn(std.testing.allocator, .{
1610
+ .argv = &.{"C:\\nonexistent\\never-a-command.exe"},
1611
+ }));
1612
+ }
1613
+
1614
+ test "windows live conpty round trip: output, exit code, no signal channel" {
1615
+ if (comptime !is_windows) return;
1616
+ const p = try spawn(std.testing.allocator, .{
1617
+ .argv = &.{ "cmd.exe", "/d", "/c", "echo pty-win-live-marker& exit 7" },
1618
+ .env = &.{system_root_env},
1619
+ .cols = 60,
1620
+ .rows = 16,
1621
+ });
1622
+ defer p.close();
1623
+ try std.testing.expect(!p.lateExecFailure());
1624
+ const nudge_pair = try pipePair();
1625
+ defer closeFd(nudge_pair[0]);
1626
+ defer closeFd(nudge_pair[1]);
1627
+ var buf: [64 * 1024]u8 = undefined;
1628
+ const total = testReadAll(p, nudge_pair[0], &buf);
1629
+ // ConPTY output is conhost's VT rendering, so the marker rides
1630
+ // among escape sequences: containment is the honest assertion.
1631
+ try std.testing.expect(std.mem.indexOf(u8, buf[0..total], "pty-win-live-marker") != null);
1632
+ const exit = p.reapBlocking();
1633
+ try std.testing.expectEqual(@as(i32, 7), exit.code);
1634
+ try std.testing.expectEqual(@as(i32, 0), exit.signal);
1635
+ }
1636
+
1637
+ test "windows kill reports an exit code, never a signal" {
1638
+ if (comptime !is_windows) return;
1639
+ // A bare interactive cmd stays alive until killed.
1640
+ const p = try spawn(std.testing.allocator, .{
1641
+ .argv = &.{"cmd.exe"},
1642
+ .env = &.{system_root_env},
1643
+ });
1644
+ defer p.close();
1645
+ p.resize(100, 30);
1646
+ p.kill(false);
1647
+ const exit = p.reapBlocking();
1648
+ // TerminateProcess carries exit code 1; Windows has no signal
1649
+ // channel, so `signal` is always 0 — the documented mapping.
1650
+ try std.testing.expectEqual(@as(i32, 1), exit.code);
1651
+ try std.testing.expectEqual(@as(i32, 0), exit.signal);
1652
+ }
1653
+
1654
+ test "windows child environment is exactly env plus TERM" {
1655
+ if (comptime !is_windows) return;
1656
+ const p = try spawn(std.testing.allocator, .{
1657
+ .argv = &.{ "cmd.exe", "/d", "/c", "echo %PTY_MARKER%_%TERM%_%PTY_ABSENT%" },
1658
+ .env = &.{ system_root_env, .{ .name = "PTY_MARKER", .value = "pty-proof" } },
1659
+ });
1660
+ defer p.close();
1661
+ const nudge_pair = try pipePair();
1662
+ defer closeFd(nudge_pair[0]);
1663
+ defer closeFd(nudge_pair[1]);
1664
+ var buf: [64 * 1024]u8 = undefined;
1665
+ const total = testReadAll(p, nudge_pair[0], &buf);
1666
+ _ = p.reapBlocking();
1667
+ const out = buf[0..total];
1668
+ // MARKER passed through, TERM injected; an absent variable stays
1669
+ // an unexpanded literal in cmd — the clean-environment proof.
1670
+ try std.testing.expect(std.mem.indexOf(u8, out, "pty-proof_" ++ pty.default_term ++ "_%PTY_ABSENT%") != null);
1671
+
1672
+ // An inherited TERM is replaced, never preserved (case-insensitive,
1673
+ // the Windows env-name rule).
1674
+ const q = try spawn(std.testing.allocator, .{
1675
+ .argv = &.{ "cmd.exe", "/d", "/c", "echo term=%TERM%=" },
1676
+ .env = &.{ system_root_env, .{ .name = "Term", .value = "dumb" } },
1677
+ .term = "xterm-256color",
1678
+ });
1679
+ defer q.close();
1680
+ const q_nudge = try pipePair();
1681
+ defer closeFd(q_nudge[0]);
1682
+ defer closeFd(q_nudge[1]);
1683
+ var term_buf: [64 * 1024]u8 = undefined;
1684
+ const term_total = testReadAll(q, q_nudge[0], &term_buf);
1685
+ _ = q.reapBlocking();
1686
+ try std.testing.expect(std.mem.indexOf(u8, term_buf[0..term_total], "term=xterm-256color=") != null);
1687
+ try std.testing.expect(std.mem.indexOf(u8, term_buf[0..term_total], "dumb") == null);
1688
+ }
1689
+
1690
+ test "windows utf-8 honesty: non-ascii argv survives the utf-16 boundary and returns as utf-8" {
1691
+ if (comptime !is_windows) return;
1692
+ const p = try spawn(std.testing.allocator, .{
1693
+ .argv = &.{ "cmd.exe", "/d", "/c", "echo pty-你好-héllo" },
1694
+ .env = &.{system_root_env},
1695
+ });
1696
+ defer p.close();
1697
+ const nudge_pair = try pipePair();
1698
+ defer closeFd(nudge_pair[0]);
1699
+ defer closeFd(nudge_pair[1]);
1700
+ var buf: [64 * 1024]u8 = undefined;
1701
+ const total = testReadAll(p, nudge_pair[0], &buf);
1702
+ _ = p.reapBlocking();
1703
+ // The argument crossed WTF-8 -> UTF-16 into cmd, conhost rendered
1704
+ // it, and ConPTY delivered it back as UTF-8 bytes.
1705
+ try std.testing.expect(std.mem.indexOf(u8, buf[0..total], "pty-你好-héllo") != null);
1706
+ }
1707
+
1708
+ test "windows initial grid size reaches the child console" {
1709
+ if (comptime !is_windows) return;
1710
+ const p = try spawn(std.testing.allocator, .{
1711
+ // Full path: the test env carries no PATH for cmd to search.
1712
+ .argv = &.{ "cmd.exe", "/d", "/c", "C:\\Windows\\System32\\mode.com con" },
1713
+ .env = &.{system_root_env},
1714
+ .cols = 97,
1715
+ .rows = 41,
1716
+ });
1717
+ defer p.close();
1718
+ const nudge_pair = try pipePair();
1719
+ defer closeFd(nudge_pair[0]);
1720
+ defer closeFd(nudge_pair[1]);
1721
+ var buf: [64 * 1024]u8 = undefined;
1722
+ const total = testReadAll(p, nudge_pair[0], &buf);
1723
+ _ = p.reapBlocking();
1724
+ // `mode con` reports the console geometry; the labels are
1725
+ // localized, the numbers are not.
1726
+ try std.testing.expect(std.mem.indexOf(u8, buf[0..total], "97") != null);
1727
+ try std.testing.expect(std.mem.indexOf(u8, buf[0..total], "41") != null);
1728
+ }
1729
+
1730
+ test "windows env-block order folds case beyond ascii" {
1731
+ // é (U+00E9) uppercases to É (U+00C9), which orders BEFORE Ê
1732
+ // (U+00CA); raw WTF-8 bytes would order them the other way.
1733
+ const e_acute: EnvVar = .{ .name = "é", .value = "1" };
1734
+ const e_circ: EnvVar = .{ .name = "Ê", .value = "2" };
1735
+ try std.testing.expect(envNameLessThan({}, e_acute, e_circ));
1736
+ try std.testing.expect(!envNameLessThan({}, e_circ, e_acute));
1737
+ // The ASCII fold still holds, and a name that is a strict prefix
1738
+ // of another orders first.
1739
+ try std.testing.expect(envNameLessThan({}, .{ .name = "path", .value = "" }, .{ .name = "PATHEXT", .value = "" }));
1740
+ try std.testing.expect(!envNameLessThan({}, .{ .name = "TERM", .value = "" }, .{ .name = "term", .value = "" }));
1741
+ // UTF-16 code-unit order, the OS's own: a supplementary-plane name
1742
+ // (U+10000, surrogate halves 0xD800/0xDC00) sorts BELOW a
1743
+ // private-use BMP name (U+E000) even though its code point is
1744
+ // larger.
1745
+ try std.testing.expect(envNameLessThan({}, .{ .name = "\u{10000}", .value = "" }, .{ .name = "\u{E000}", .value = "" }));
1746
+ try std.testing.expect(!envNameLessThan({}, .{ .name = "\u{E000}", .value = "" }, .{ .name = "\u{10000}", .value = "" }));
1747
+ }
1748
+
1749
+ test "windows executable probing appends extensions only to extension-less names" {
1750
+ try std.testing.expect(hasExtension("tool.cmd"));
1751
+ try std.testing.expect(hasExtension("C:\\dir.d\\tool.exe"));
1752
+ try std.testing.expect(!hasExtension("cmd"));
1753
+ try std.testing.expect(!hasExtension("C:\\dir.d\\tool"));
1754
+ try std.testing.expect(!hasExtension(".hidden"));
1755
+ }
1756
+
1757
+ test "windows command-line quoting round-trips the argv inverse" {
1758
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
1759
+ defer arena_state.deinit();
1760
+ const arena = arena_state.allocator();
1761
+ var line: std.ArrayList(u8) = .empty;
1762
+ try appendQuotedArg(arena, &line, "plain");
1763
+ try line.append(arena, ' ');
1764
+ try appendQuotedArg(arena, &line, "has space");
1765
+ try line.append(arena, ' ');
1766
+ try appendQuotedArg(arena, &line, "quote\"inside");
1767
+ try line.append(arena, ' ');
1768
+ try appendQuotedArg(arena, &line, "trail\\");
1769
+ try line.append(arena, ' ');
1770
+ try appendQuotedArg(arena, &line, "back\\slash here\\");
1771
+ try line.append(arena, ' ');
1772
+ try appendQuotedArg(arena, &line, "");
1773
+ // A lone backslash needs no quoting (CommandLineToArgvW reads
1774
+ // backslashes literally outside a quote context); a quoted
1775
+ // trailing run doubles ahead of the closing quote.
1776
+ try std.testing.expectEqualStrings(
1777
+ "plain \"has space\" \"quote\\\"inside\" trail\\ \"back\\slash here\\\\\" \"\"",
1778
+ line.items,
1779
+ );
1780
+ }