@native-sdk/cli 0.5.4 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/build/app.zig +50 -1
  2. package/build.zig +588 -32
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +3 -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 +280 -8
  9. package/packages/core/sdk/core.ts +481 -2
  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 +599 -3
  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 +39 -2
  17. package/skill-data/ts-core/SKILL.md +4 -2
  18. package/src/app_runner/root.zig +32 -10
  19. package/src/automation/layout_fingerprint.zig +160 -0
  20. package/src/automation/protocol.zig +82 -33
  21. package/src/automation/root.zig +1 -0
  22. package/src/automation/server.zig +1 -1
  23. package/src/automation/snapshot.zig +68 -9
  24. package/src/automation/watcher.zig +1 -1
  25. package/src/embed/host.zig +5 -0
  26. package/src/embed/ui_host.zig +13 -0
  27. package/src/platform/linux/gtk_host.c +527 -13
  28. package/src/platform/linux/gtk_host.h +25 -0
  29. package/src/platform/linux/root.zig +280 -7
  30. package/src/platform/macos/appkit_host.h +104 -6
  31. package/src/platform/macos/appkit_host.m +1368 -74
  32. package/src/platform/macos/cef_host.mm +110 -1
  33. package/src/platform/macos/root.zig +287 -7
  34. package/src/platform/null_platform.zig +398 -4
  35. package/src/platform/null_platform_tests.zig +35 -0
  36. package/src/platform/root.zig +9 -0
  37. package/src/platform/types.zig +386 -14
  38. package/src/platform/windows/root.zig +298 -9
  39. package/src/platform/windows/webview2_host.cpp +330 -5
  40. package/src/primitives/app_manifest/validation.zig +18 -0
  41. package/src/primitives/canvas/a11y_audit.zig +33 -11
  42. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  43. package/src/primitives/canvas/drawing.zig +25 -0
  44. package/src/primitives/canvas/equality.zig +8 -0
  45. package/src/primitives/canvas/events.zig +103 -16
  46. package/src/primitives/canvas/frame.zig +125 -1
  47. package/src/primitives/canvas/layout_audit.zig +22 -5
  48. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  49. package/src/primitives/canvas/render_tests.zig +13 -10
  50. package/src/primitives/canvas/root.zig +48 -0
  51. package/src/primitives/canvas/terminal_box.zig +471 -0
  52. package/src/primitives/canvas/terminal_grid.zig +978 -0
  53. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  54. package/src/primitives/canvas/test_support.zig +1 -0
  55. package/src/primitives/canvas/tests.zig +1 -0
  56. package/src/primitives/canvas/text_tests.zig +39 -4
  57. package/src/primitives/canvas/tokens.zig +115 -12
  58. package/src/primitives/canvas/ui.zig +524 -5
  59. package/src/primitives/canvas/ui_markup.zig +195 -2
  60. package/src/primitives/canvas/ui_markup_compiled.zig +172 -1
  61. package/src/primitives/canvas/ui_markup_compiled_tests.zig +133 -8
  62. package/src/primitives/canvas/ui_markup_contract.zig +88 -5
  63. package/src/primitives/canvas/ui_markup_contract_tests.zig +39 -1
  64. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  65. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  66. package/src/primitives/canvas/ui_markup_tests.zig +149 -0
  67. package/src/primitives/canvas/ui_markup_view.zig +191 -0
  68. package/src/primitives/canvas/ui_markup_view_tests.zig +403 -19
  69. package/src/primitives/canvas/ui_schema.zig +97 -17
  70. package/src/primitives/canvas/ui_schema_tests.zig +18 -11
  71. package/src/primitives/canvas/ui_tests.zig +141 -9
  72. package/src/primitives/canvas/widget_access.zig +28 -2
  73. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  74. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  75. package/src/primitives/canvas/widget_layout.zig +59 -11
  76. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  77. package/src/primitives/canvas/widget_render.zig +272 -18
  78. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  79. package/src/primitives/canvas/widget_routing.zig +59 -7
  80. package/src/primitives/canvas/widget_runtime.zig +23 -0
  81. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  82. package/src/primitives/canvas/widget_semantics.zig +119 -11
  83. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  84. package/src/primitives/canvas/widget_tree.zig +17 -0
  85. package/src/primitives/canvas/widgets.zig +132 -0
  86. package/src/root.zig +16 -0
  87. package/src/runtime/api.zig +76 -6
  88. package/src/runtime/automation_commands.zig +20 -1
  89. package/src/runtime/automation_snapshot.zig +25 -1
  90. package/src/runtime/automation_widget_dispatch.zig +73 -8
  91. package/src/runtime/bridge_payload.zig +1 -0
  92. package/src/runtime/canvas_frame.zig +62 -7
  93. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  94. package/src/runtime/canvas_frame_helpers.zig +190 -1
  95. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  96. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  97. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  98. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  99. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  100. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  101. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  102. package/src/runtime/canvas_widget_display.zig +1 -1
  103. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  104. package/src/runtime/canvas_widget_events.zig +268 -26
  105. package/src/runtime/canvas_widget_runtime.zig +213 -29
  106. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  107. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  108. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  109. package/src/runtime/canvas_widget_state.zig +6 -0
  110. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  111. package/src/runtime/core.zig +73 -2
  112. package/src/runtime/effects.zig +6389 -54
  113. package/src/runtime/effects_channel_tests.zig +3519 -0
  114. package/src/runtime/effects_pty_tests.zig +1362 -0
  115. package/src/runtime/effects_tests.zig +14 -9
  116. package/src/runtime/effects_video_tests.zig +3609 -0
  117. package/src/runtime/flow.zig +25 -4
  118. package/src/runtime/gpu_surface_events.zig +475 -15
  119. package/src/runtime/media_surface.zig +116 -11
  120. package/src/runtime/media_surface_tests.zig +61 -0
  121. package/src/runtime/pty.zig +1252 -0
  122. package/src/runtime/pty_windows.zig +1780 -0
  123. package/src/runtime/root.zig +25 -0
  124. package/src/runtime/runtime_event_tests.zig +20 -1
  125. package/src/runtime/session_journal.zig +367 -61
  126. package/src/runtime/session_record.zig +16 -0
  127. package/src/runtime/session_replay.zig +395 -11
  128. package/src/runtime/session_tests.zig +114 -19
  129. package/src/runtime/terminal_session.zig +1569 -0
  130. package/src/runtime/terminal_session_tests.zig +450 -0
  131. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  132. package/src/runtime/terminal_vt_stub.zig +13 -0
  133. package/src/runtime/tests.zig +6 -0
  134. package/src/runtime/ts_core_host.zig +980 -140
  135. package/src/runtime/ts_core_host_tests.zig +1059 -1
  136. package/src/runtime/ts_ui_app.zig +16 -5
  137. package/src/runtime/ui_app.zig +2338 -67
  138. package/src/runtime/ui_app_tests.zig +3171 -744
  139. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  140. package/src/runtime/ui_app_window_tests.zig +268 -0
  141. package/src/runtime/view.zig +190 -2
  142. package/src/runtime/view_widget_scroll.zig +218 -68
  143. package/src/runtime/view_widget_text.zig +11 -2
  144. package/src/runtime/view_widget_tree.zig +111 -3
  145. package/src/runtime/window_storage.zig +45 -2
  146. package/src/runtime/window_view_runtime.zig +34 -2
  147. package/src/runtime/window_views.zig +1 -0
  148. package/src/terminal_session_tests_root.zig +15 -0
  149. package/src/tooling/templates.zig +25 -7
@@ -145,7 +145,8 @@
145
145
  //! duplicate LIVE id rejects the new load (the spawn
146
146
  //! discipline: one load per id, never replaced
147
147
  //! implicitly), dispatching state "rejected" at the
148
- //! post-cycle boundary with the refused id echoed; ids
148
+ //! next drain, in command-stream order with the
149
+ //! engine's own refusals, the refused id echoed; ids
149
150
  //! the wire cannot carry exactly (0, non-integers,
150
151
  //! 2^53 and past — the SDK contract is BELOW 2^53)
151
152
  //! reject the same way echoing id 0, and so does a
@@ -171,6 +172,77 @@
171
172
  //! under the id keeps running and its terminal still
172
173
  //! registers the pixels — cancel the load first to
173
174
  //! keep the slot free.
175
+ //! channel_open-> `fx.openChannel` keyed by the app's own numeric key
176
+ //! (the image_load id convention: the raw key IS the
177
+ //! engine key, and the bridge holds a key->tag table).
178
+ //! The entry is non-retiring the spawn way: every
179
+ //! channel event routes the event arm — a five-field
180
+ //! record built by field NAME (key/state/bytes/
181
+ //! droppedPending/droppedTotal; `state`'s enum members
182
+ //! are matched by member name, exactly the
183
+ //! data/closed/rejected set) — until the one `closed`
184
+ //! (or a refused open's `rejected`) terminal retires
185
+ //! it. POSTING is not a TS-tier verb: transpiled cores
186
+ //! are single-threaded, so the thread-safe posting
187
+ //! handle is native-side API (`Effects.channelHandle`)
188
+ //! for embedders and platform-services extensions —
189
+ //! the TS tier opens, closes, and receives. A
190
+ //! duplicate LIVE key rejects the new open (one
191
+ //! channel per key, never replaced implicitly),
192
+ //! dispatching state "rejected" at the next drain, in
193
+ //! command-stream order with the engine's own
194
+ //! refusals, the refused key echoed; keys the wire
195
+ //! cannot carry exactly reject the same way echoing
196
+ //! key 0, and so does a full bridge table.
197
+ //! channel_close-> `fx.closeChannel(key)` on the live channel under
198
+ //! the key, if any: staged posts flush and the
199
+ //! engine's one `.closed` terminal routes the entry's
200
+ //! event arm and retires it. A key naming no live
201
+ //! channel (or one the wire cannot carry exactly) is
202
+ //! a no-op, audio_ctl's idle rule. Channels are keyed
203
+ //! numerically, so the string-keyed cancel never
204
+ //! touches them — this is their close.
205
+ //! pty_spawn -> `fx.ptySpawn` through the PTY table (`pty_key_base`
206
+ //! + index) — non-retiring the spawn way: coalesced
207
+ //! "output" batches route the event arm across
208
+ //! dispatches — a six-field record built by field NAME
209
+ //! (state/bytes/code/reason/signal/droppedWrites;
210
+ //! `state`'s and `reason`'s enum members are matched
211
+ //! by member name, so the app's declaration order is
212
+ //! free) — and the exactly-one "exit" terminal retires
213
+ //! the entry. An empty wire TERM opens with the
214
+ //! engine's default (the fetch-timeout convention);
215
+ //! grid dimensions ride the wire as f64 subset numbers
216
+ //! and a value the u16 transport cannot carry exactly
217
+ //! spawns with dimension 0, which the engine answers
218
+ //! with one "rejected" exit — loud, never a guess. A
219
+ //! duplicate LIVE wire key rejects the new spawn (the
220
+ //! spawn discipline: a running terminal's child is a
221
+ //! running subprocess, never killed implicitly),
222
+ //! dispatching one "exit" with reason "rejected" at
223
+ //! the next drain, in command-stream order with the
224
+ //! engine's own refusals; a full bridge table rejects
225
+ //! the same way.
226
+ //! pty_write -> `fx.ptyWrite` on the live session under the wire
227
+ //! key — fire-and-forget (keystrokes): a key naming no
228
+ //! open session is a no-op (the exit was already on
229
+ //! its way), and refused payloads count into the exit
230
+ //! event's droppedWrites, never silence.
231
+ //! pty_resize -> `fx.ptyResize` on the live session under the wire
232
+ //! key — fire-and-forget like pty_write; a key naming
233
+ //! no open session is a no-op, and a grid value the
234
+ //! u16 transport cannot carry exactly resizes nothing
235
+ //! (the no-op rule: there is no honest grid to push).
236
+ //! pty_kill -> `fx.ptyKill` on the live session under the wire key
237
+ //! — LOUD, the spawn cancel discipline: the engine
238
+ //! ends the child and the session's one "exit"
239
+ //! terminal routes its own event arm with reason
240
+ //! "cancelled", retiring the entry. A key naming no
241
+ //! open session is a no-op. Sessions are keyed by
242
+ //! their own family's verbs, so the string-keyed
243
+ //! `cancel` record never touches them — pty_kill is
244
+ //! their kill, the way audio_ctl stop is audio's
245
+ //! close.
174
246
  //! audio_ctl -> the engine's control verbs (`fx.pauseAudio`/
175
247
  //! `resumeAudio`/`stopAudio`/`seekAudio`/
176
248
  //! `setAudioVolume`), gated by the wire key: a verb
@@ -178,6 +250,36 @@
178
250
  //! (the playback it aimed at is gone). `stop` also
179
251
  //! retires the bridge entry — no events for that key
180
252
  //! after it.
253
+ //! video_load -> `fx.loadVideo` on the bridge's single video entry.
254
+ //! The engine key is `videoKeyForTag` (the
255
+ //! `video_key_base` namespace with the load's event
256
+ //! tag in the low byte; the engine has ONE player, so
257
+ //! the bridge holds one stream), non-retiring the
258
+ //! audio way, gated by the wire key for verbs: every
259
+ //! `EffectVideo` event (loaded/position/completed/
260
+ //! failed/rejected) routes the arm of the load whose
261
+ //! key it echoes —
262
+ //! a seven-field record built by field NAME (state/
263
+ //! positionMs/durationMs/playing/buffering/width/
264
+ //! height; `state`'s enum members are matched by
265
+ //! member name, so the app's declaration order is
266
+ //! free) — until video_ctl `stop` (or a replacing
267
+ //! video_load, which re-keys and re-routes the same
268
+ //! entry) closes it. The record's surface is the
269
+ //! app's own media-surface id (decoded frames flow
270
+ //! platform-side into that texture channel, never
271
+ //! through this bridge); an id the wire cannot carry
272
+ //! exactly reaches the engine as 0, which it refuses
273
+ //! with one `.rejected` event — never silent.
274
+ //! `completed`/`failed`/`rejected` do NOT retire the
275
+ //! entry: stop is the explicit close, audio's rule.
276
+ //! video_ctl -> the engine's control verbs (`fx.playVideo`/
277
+ //! `pauseVideo`/`stopVideo`/`seekVideo`/
278
+ //! `setVideoVolume`/`setVideoMuted`/`setVideoLoop`),
279
+ //! gated by the wire key: a verb whose key does not
280
+ //! name the open stream is a no-op (the playback it
281
+ //! aimed at is gone). `stop` also retires the bridge
282
+ //! entry — no events for that key after it.
181
283
  //! window_show -> `fx.showWindow(label)` — fire-and-forget, label-
182
284
  //! addressed like the Zig tier's verb: un-hide +
183
285
  //! activate (the tray "Open" consequence of the
@@ -195,8 +297,8 @@
195
297
  //! the err arm with "cancelled"; killing a process IS
196
298
  //! an observable event, so spawn's cancel stays loud),
197
299
  //! the delay table (`fx.cancelTimer`, silent). The
198
- //! audio stream is not cancel's to end — audio_ctl
199
- //! `stop` is its close.
300
+ //! audio and video streams are not cancel's to end —
301
+ //! their ctl `stop` records are their closes.
200
302
  //!
201
303
  //! THE KEYED-EFFECT DISCIPLINE is ONE rule across request, read_file,
202
304
  //! write_file, fetch, clip_read, and delay: a keyed effect REPLACES its
@@ -206,12 +308,12 @@
206
308
  //! superseded entry dropped and cancelling its engine call; the
207
309
  //! engine's `.cancelled` terminal retires the entry and its Msg is
208
310
  //! swallowed before dispatch. The ONE exception is a live `Cmd.spawn`
209
- //! key: a duplicate REJECTS the new spawn — its err arm dispatches with
210
- //! "rejected" right after the issuing cycle (the same post-cycle
211
- //! boundary `now` dispatches use) — because a running subprocess is
212
- //! never killed implicitly; cancel it first. And spawn's explicit
213
- //! cancel stays loud (err arm "cancelled"), because killing a process
214
- //! is an observable event.
311
+ //! key: a duplicate REJECTS the new spawn — its err arm dispatches
312
+ //! with "rejected" on the next drain, at the refusal's command-stream
313
+ //! position (see the rejection-ordering paragraph below) — because a
314
+ //! running subprocess is never killed implicitly; cancel it first. And
315
+ //! spawn's explicit cancel stays loud (err arm "cancelled"), because
316
+ //! killing a process is an observable event.
215
317
  //! Sub timer -> `fx.startTimer` (repeating) with a fixed slot table
216
318
  //! reconciled by wire key: a new key arms the first
217
319
  //! free slot (slot order — deterministic, never hash
@@ -227,7 +329,18 @@
227
329
  //! `.effects_wake` and presented-frame drains), exactly like Zig-core
228
330
  //! fx results. The bridge adds no scheduler of its own; the one
229
331
  //! deliberate exception is `now` (above), which is synchronous the way
230
- //! `fx.wallMs` is.
332
+ //! `fx.wallMs` is. Bridge-refused rejections (spawn/image/channel)
333
+ //! stage into the ENGINE's loop-side pending order at refusal time
334
+ //! (`Effects.stageLoopMsg`) and dispatch at the next drain — the same
335
+ //! delivery moment as the engine's own refusals, so a `Cmd.batch`
336
+ //! whose records are refused by DIFFERENT layers (the bridge's table
337
+ //! validation, the engine's cross-family key gate) still dispatches
338
+ //! its rejections in COMMAND-STREAM order: one seq-ordered stream is
339
+ //! the ordering authority for every rejection, `Cmd.batch`'s
340
+ //! performed-in-order contract extended to refusals. A second
341
+ //! delivery moment is exactly how families fall out of stream order,
342
+ //! so a new refusing family joins by staging, never by dispatching
343
+ //! from its own boundary.
231
344
  //!
232
345
  //! Result payload lifetime: the engine's result bytes are drain
233
346
  //! scratch, but a routed result's bytes become a Msg payload the core
@@ -278,6 +391,25 @@ pub const spawn_key_base: u64 = 0x5453_5350_0000_0000;
278
391
  /// is the whole surface, so one constant key is the honest shape.
279
392
  pub const audio_key_base: u64 = 0x5453_4155_0000_0000;
280
393
 
394
+ /// The engine-key namespace of the bridge's single video playback
395
+ /// channel ("TSVI") — the audio key's twin, except the low byte
396
+ /// carries the issuing load's event-arm tag: every `EffectVideo` event
397
+ /// echoes the key of the playback that produced it, so a staged
398
+ /// synchronous `.failed` that delivers AFTER a replacing load re-keyed
399
+ /// the entry still routes the arm of the load it answers (the mutable
400
+ /// entry's tag would misroute it to the replacement's arm).
401
+ pub const video_key_base: u64 = 0x5453_5649_0000_0000;
402
+
403
+ /// The engine key for a video load routed to `event_tag`'s arm.
404
+ pub fn videoKeyForTag(event_tag: u8) u64 {
405
+ return video_key_base | event_tag;
406
+ }
407
+
408
+ /// Engine-key namespace for pty sessions ("TSPT"): `base + table
409
+ /// index`, deterministic in issue order. Ptys share the keyed
410
+ /// families' one engine key space without ever colliding on a key.
411
+ pub const pty_key_base: u64 = 0x5453_5054_0000_0000;
412
+
281
413
  /// The spawn wire record's "no line routing" tag sentinel (mirrors
282
414
  /// rt.zig's `spawn_no_line_tag`).
283
415
  pub const spawn_no_line_tag: u8 = 0xFF;
@@ -412,6 +544,28 @@ pub fn TsCoreHost(comptime core: type) type {
412
544
  }
413
545
  };
414
546
 
547
+ /// The single video stream entry — the audio entry's exact
548
+ /// shape (one player is the whole engine surface). Non-retiring:
549
+ /// video_ctl `stop` closes it, a new video_load re-keys and
550
+ /// re-routes it in place.
551
+ const VideoEntry = struct {
552
+ used: bool = false,
553
+ key_len: usize = 0,
554
+ key: [max_wire_key_bytes]u8 = undefined,
555
+ event_tag: u8 = 0,
556
+ /// The load identity this entry's own accepted load minted
557
+ /// (`Effects.videoMintedToken`): the proof that the
558
+ /// playback on the single engine channel is still THIS
559
+ /// stream — a load the bridge never issued (a declarative
560
+ /// element's) may have replaced it, and the entry's verbs
561
+ /// must not mutate or cancel someone else's playback.
562
+ token: u64 = 0,
563
+
564
+ fn wireKey(entry: *const VideoEntry) []const u8 {
565
+ return entry.key[0..entry.key_len];
566
+ }
567
+ };
568
+
415
569
  /// One in-flight image load, keyed by the app's own numeric
416
570
  /// ImageId (which IS the engine key — the registry id and the
417
571
  /// effect key are one value by design). Retires on its one
@@ -422,6 +576,35 @@ pub fn TsCoreHost(comptime core: type) type {
422
576
  event_tag: u8 = 0,
423
577
  };
424
578
 
579
+ /// One open external-source channel, keyed by the app's own
580
+ /// numeric key (which IS the engine key, the image
581
+ /// convention). Non-retiring the spawn way: `data` events flow
582
+ /// through it across dispatches; the one `closed` (or a
583
+ /// refused open's `rejected`) terminal retires it. Sized to
584
+ /// the engine's channel table.
585
+ const ChannelEntry = struct {
586
+ used: bool = false,
587
+ key: u64 = 0,
588
+ event_tag: u8 = 0,
589
+ };
590
+
591
+ /// One live pty session — the stream entries' non-retiring
592
+ /// shape: "output" events route through it repeatedly across
593
+ /// dispatches, and only the one "exit" terminal retires it. The
594
+ /// table index IS the engine key (minus `pty_key_base`),
595
+ /// deterministic in issue order; sized to the engine's pty
596
+ /// table.
597
+ const PtyEntry = struct {
598
+ used: bool = false,
599
+ key_len: usize = 0,
600
+ key: [max_wire_key_bytes]u8 = undefined,
601
+ event_tag: u8 = 0,
602
+
603
+ fn wireKey(entry: *const PtyEntry) []const u8 {
604
+ return entry.key[0..entry.key_len];
605
+ }
606
+ };
607
+
425
608
  var model_root: *const Model = undefined;
426
609
  /// The platform caches directory for URL audio sources, set by
427
610
  /// the wiring (`TsUiApp`'s `audio_cache_dir`, or `setAudioCacheDir`
@@ -438,7 +621,10 @@ pub fn TsCoreHost(comptime core: type) type {
438
621
  var delays: [runtime_effects.max_effect_timers]DelayEntry = @splat(.{});
439
622
  var streams: [runtime_effects.max_effects]StreamEntry = @splat(.{});
440
623
  var audio_entry: AudioEntry = .{};
624
+ var video_entry: VideoEntry = .{};
441
625
  var images: [runtime_effects.max_effects]ImageEntry = @splat(.{});
626
+ var channels: [runtime_effects.max_effect_channels]ChannelEntry = @splat(.{});
627
+ var ptys: [runtime_effects.max_effect_ptys]PtyEntry = @splat(.{});
442
628
  /// The platform caches directory for URL image sources, the
443
629
  /// audio cache dir's twin (`setImageCacheDir` / `TsUiApp`'s
444
630
  /// `image_cache_dir`): bridge-side derivation of the
@@ -461,90 +647,25 @@ pub fn TsCoreHost(comptime core: type) type {
461
647
  /// after the issuing cycle's frame reset.
462
648
  const PendingNow = struct { tag: u8, ms: i64 };
463
649
 
464
- /// A spawn issue the bridge itself refused (duplicate live wire
465
- /// key — the one reject in the keyed-effect discipline),
466
- /// dispatched as the spawn's err arm with "rejected" after the
467
- /// issuing cycle's frame reset, at the same boundary `now`
468
- /// dispatches use.
469
- const max_rejects_per_cmd: usize = runtime_effects.max_effects;
470
-
471
- /// An image load the bridge itself refused (duplicate live id,
472
- /// an unrepresentable id, a full image table), dispatched as the
473
- /// load's event arm with state "rejected" at the same post-cycle
474
- /// boundary. `id` echoes the requested ImageId so concurrent
475
- /// rejections stay distinguishable — 0 when the wire value is
476
- /// not an exactly-carried positive integer, because there is no
477
- /// honest integer to echo for one.
478
- const ImageReject = struct { tag: u8, id: u64 };
479
-
480
- /// One cycle's staging for bridge-refused image loads. Unlike
481
- /// the spawn-reject buffer, the count here is the APP's to
482
- /// choose — a `Cmd.batch` of N loads against a full table must
483
- /// yield N rejected results, never a crash — so the stage never
484
- /// caps at the table size: the inline buffer covers everyday
485
- /// command values without touching an allocator, and the first
486
- /// overflow spills once into an engine-allocator block sized by
487
- /// the wire's own arithmetic bound. Staging exists because the
488
- /// command walk cannot dispatch (the wire bytes are frame-arena
489
- /// resident, and a nested cycle's frame reset would free them
490
- /// mid-walk): rejects are captured during the walk and
491
- /// delivered after the issuing cycle's frame reset, at the same
492
- /// boundary `now` dispatches use — stack and heap storage both
493
- /// survive the nested delivery cycles that boundary runs.
494
- const ImageRejectStage = struct {
495
- /// Every image_load record occupies at least this many wire
496
- /// bytes ([op][id f64][event_tag], three empty long-bytes
497
- /// fields, [expected f64]), so a command value of L bytes
498
- /// carries at most L / 30 of them — the spill bound needs
499
- /// no second record parser to stay in sync with.
500
- const min_image_load_record_bytes: usize = 1 + 8 + 1 + 3 * 4 + 8;
501
-
502
- inline_buf: [max_rejects_per_cmd]ImageReject = undefined,
503
- spill: []ImageReject = &.{},
504
- count: usize = 0,
505
- /// The arithmetic ceiling on this cycle's image_load record
506
- /// count (and therefore on its rejects).
507
- bound: usize,
508
- allocator: std.mem.Allocator,
509
-
510
- fn open(fx: *Fx, cmd_len: usize) ImageRejectStage {
511
- return .{
512
- .bound = cmd_len / min_image_load_record_bytes,
513
- .allocator = fx.allocator,
514
- };
515
- }
516
-
517
- fn push(self: *ImageRejectStage, tag: u8, id: u64) void {
518
- if (self.count < self.inline_buf.len) {
519
- self.inline_buf[self.count] = .{ .tag = tag, .id = id };
520
- self.count += 1;
521
- return;
522
- }
523
- if (self.spill.len == 0) {
524
- // First overflow: size by the wire bound once and
525
- // move the inline prefix over — one allocation for
526
- // the whole cycle, and only on cycles that earn it.
527
- self.spill = self.allocator.alloc(ImageReject, self.bound) catch
528
- @panic("ts core host: out of memory staging rejected image loads");
529
- @memcpy(self.spill[0..self.count], &self.inline_buf);
530
- }
531
- // The wire arithmetic sized the spill: rejects <= loads
532
- // <= bound, so the store below can never run past it.
533
- std.debug.assert(self.count < self.spill.len);
534
- self.spill[self.count] = .{ .tag = tag, .id = id };
535
- self.count += 1;
536
- }
537
-
538
- fn staged(self: *const ImageRejectStage) []const ImageReject {
539
- if (self.spill.len > 0) return self.spill[0..self.count];
540
- return self.inline_buf[0..self.count];
541
- }
542
-
543
- fn close(self: *ImageRejectStage) void {
544
- if (self.spill.len > 0) self.allocator.free(self.spill);
545
- self.spill = &.{};
546
- }
547
- };
650
+ // Bridge-refused dispatches (a spawn under a live wire key, an
651
+ // image load or channel open under a duplicate live id/key, an
652
+ // unrepresentable one, or a full bridge table) do NOT dispatch
653
+ // from the bridge's own boundary: each refusal builds its
654
+ // record's err/event arm Msg ("rejected", echoing the
655
+ // requested ImageId / channel key where the family has one —
656
+ // 0 when the wire value is not an exactly-carried positive
657
+ // integer, since there is no honest integer to echo) and
658
+ // stages it into the ENGINE's loop-side pending order at
659
+ // refusal time (`Effects.stageLoopMsg`). One seq-ordered
660
+ // stream is the ordering authority for every rejection, so a
661
+ // batch mixing bridge-refused and engine-refused records
662
+ // dispatches all of them in command-stream order at the next
663
+ // drain — see the result-ordering contract in the module doc.
664
+ // The staged Msgs are self-contained (static reason bytes and
665
+ // scalar echoes, never frame-arena slices) and regenerate
666
+ // deterministically under replay: the walk re-runs against the
667
+ // same table state, so record and replay stage identical
668
+ // sequences — `stageLoopMsg`'s two caller contracts.
548
669
 
549
670
  /// Install the core: reset the kernel and the bridge tables
550
671
  /// (deterministic re-init — the seam session replay relies on),
@@ -574,7 +695,10 @@ pub fn TsCoreHost(comptime core: type) type {
574
695
  delays = @splat(.{});
575
696
  streams = @splat(.{});
576
697
  audio_entry = .{};
698
+ video_entry = .{};
577
699
  images = @splat(.{});
700
+ channels = @splat(.{});
701
+ ptys = @splat(.{});
578
702
  clip_write_counter = 0;
579
703
  audio_cache_dir_len = 0;
580
704
  image_cache_dir_len = 0;
@@ -704,36 +828,22 @@ pub fn TsCoreHost(comptime core: type) type {
704
828
  }
705
829
  }
706
830
 
707
- /// The tail of every cycle: walk the command bytes, reconcile
831
+ /// The tail of every cycle: walk the command bytes (staging any
832
+ /// bridge-refused rejections into the engine's pending order as
833
+ /// it goes — see the rejection note above `init`), reconcile
708
834
  /// subscriptions against the NEW committed model, reset the
709
- /// frame arena, then run the cycle's `now` dispatches and
710
- /// bridge-refused spawn rejections (each a full cycle of its
711
- /// own, on the fresh frame — nows first, rejections after, in
712
- /// record order; deterministic under record and replay alike).
835
+ /// frame arena, then run the cycle's `now` dispatches (each a
836
+ /// full cycle of its own, on the fresh frame, in record order;
837
+ /// deterministic under record and replay alike).
713
838
  fn finishCycle(fx: *Fx, cmd: []const u8, depth: usize) void {
714
839
  var nows: [max_nows_per_cmd]PendingNow = undefined;
715
840
  var now_count: usize = 0;
716
- var rejects: [max_rejects_per_cmd]u8 = undefined;
717
- var reject_count: usize = 0;
718
- var image_rejects = ImageRejectStage.open(fx, cmd.len);
719
- defer image_rejects.close();
720
- runCmd(fx, cmd, &nows, &now_count, &rejects, &reject_count, &image_rejects);
841
+ runCmd(fx, cmd, &nows, &now_count);
721
842
  reconcileTimers(fx);
722
843
  core.rt.frameReset();
723
844
  for (nows[0..now_count]) |pending| {
724
845
  dispatchDepth(fx, msgFromTagNumber(pending.tag, @floatFromInt(pending.ms)), depth + 1);
725
846
  }
726
- for (rejects[0..reject_count]) |err_tag| {
727
- dispatchDepth(fx, msgFromTagBytes(err_tag, "rejected"), depth + 1);
728
- }
729
- // Bridge-refused image loads (duplicate live id, an
730
- // unrepresentable id, a full image table): the event arm's
731
- // "rejected" state echoing the refused id, regenerated
732
- // deterministically under replay like the spawn rejections
733
- // above.
734
- for (image_rejects.staged()) |reject| {
735
- dispatchDepth(fx, msgFromTagImage(reject.tag, .{ .id = reject.id, .outcome = .rejected }), depth + 1);
736
- }
737
847
  }
738
848
 
739
849
  // ------------------------------------------------- command walk
@@ -745,9 +855,6 @@ pub fn TsCoreHost(comptime core: type) type {
745
855
  cmd: []const u8,
746
856
  nows: *[max_nows_per_cmd]PendingNow,
747
857
  now_count: *usize,
748
- rejects: *[max_rejects_per_cmd]u8,
749
- reject_count: *usize,
750
- image_rejects: *ImageRejectStage,
751
858
  ) void {
752
859
  var at: usize = 0;
753
860
  while (at < cmd.len) {
@@ -904,7 +1011,7 @@ pub fn TsCoreHost(comptime core: type) type {
904
1011
  var argv: [runtime_effects.max_effect_argv][]const u8 = undefined;
905
1012
  for (0..argc) |i| argv[i] = takeLongBytes(cmd, &at);
906
1013
  const stdin = takeLongBytes(cmd, &at);
907
- issueSpawn(fx, .{ .key = key, .line_tag = line_tag, .exit_tag = exit_tag, .err_tag = err_tag }, mode == 1, argv[0..argc], stdin, rejects, reject_count);
1014
+ issueSpawn(fx, .{ .key = key, .line_tag = line_tag, .exit_tag = exit_tag, .err_tag = err_tag }, mode == 1, argv[0..argc], stdin);
908
1015
  },
909
1016
  // audio_play [op][key_len][key][event_tag]
910
1017
  // [path_len u32 LE][path][url_len u32 LE][url]
@@ -966,7 +1073,7 @@ pub fn TsCoreHost(comptime core: type) type {
966
1073
  const cache_path = takeLongBytes(cmd, &at);
967
1074
  const expected_bits = takeBytes(cmd, &at, 8);
968
1075
  const expected: f64 = @bitCast(std.mem.readInt(u64, expected_bits[0..8], .little));
969
- issueImageLoad(fx, id_value, event_tag, image_path, url, cache_path, expected, image_rejects);
1076
+ issueImageLoad(fx, id_value, event_tag, image_path, url, cache_path, expected);
970
1077
  },
971
1078
  // image_cancel [op][id f64 LE]
972
1079
  0x13 => {
@@ -980,6 +1087,136 @@ pub fn TsCoreHost(comptime core: type) type {
980
1087
  const id_value: f64 = @bitCast(std.mem.readInt(u64, id_bits[0..8], .little));
981
1088
  runImageUnregister(fx, id_value);
982
1089
  },
1090
+ // channel_open [op][key f64 LE][event_tag]
1091
+ 0x15 => {
1092
+ const key_bits = takeBytes(cmd, &at, 8);
1093
+ const key_value: f64 = @bitCast(std.mem.readInt(u64, key_bits[0..8], .little));
1094
+ const event_tag = takeByte(cmd, &at);
1095
+ issueChannelOpen(fx, key_value, event_tag);
1096
+ },
1097
+ // channel_close [op][key f64 LE]
1098
+ 0x16 => {
1099
+ const key_bits = takeBytes(cmd, &at, 8);
1100
+ const key_value: f64 = @bitCast(std.mem.readInt(u64, key_bits[0..8], .little));
1101
+ runChannelClose(fx, key_value);
1102
+ },
1103
+ // video_load [op][key_len][key][event_tag][surface f64 LE]
1104
+ // [path_len u32 LE][path][url_len u32 LE][url]
1105
+ // [flags u8]
1106
+ 0x17 => {
1107
+ const key = takeShortBytes(cmd, &at);
1108
+ const event_tag = takeByte(cmd, &at);
1109
+ const surface_bits = takeBytes(cmd, &at, 8);
1110
+ const surface: f64 = @bitCast(std.mem.readInt(u64, surface_bits[0..8], .little));
1111
+ const video_path = takeLongBytes(cmd, &at);
1112
+ const url = takeLongBytes(cmd, &at);
1113
+ const flags = takeByte(cmd, &at);
1114
+ const options: Fx.LoadVideoOptions = .{
1115
+ // The tag rides the key's low byte so every
1116
+ // event routes the arm of the load that
1117
+ // produced it (see `videoKeyForTag`).
1118
+ .key = videoKeyForTag(event_tag),
1119
+ // The wire carries the app's number; a surface
1120
+ // that is not an exactly-carried positive
1121
+ // integer (0, negatives, fractions, 2^53 and
1122
+ // past — the image id bound) reaches the engine
1123
+ // as 0, which the validation refuses with one
1124
+ // `.rejected` event — never silent.
1125
+ .surface = if (surface >= 1 and surface < 9007199254740992.0 and @floor(surface) == surface)
1126
+ @intFromFloat(surface)
1127
+ else
1128
+ 0,
1129
+ .path = video_path,
1130
+ .url = url,
1131
+ .autoplay = (flags & 0x01) != 0,
1132
+ .loop = (flags & 0x02) != 0,
1133
+ .muted = (flags & 0x04) != 0,
1134
+ .on_event = videoEventMsg,
1135
+ };
1136
+ // A load the engine's own deterministic gates
1137
+ // would refuse must not commit the routing
1138
+ // entry: the engine keeps the CURRENT playback
1139
+ // on a rejected load, so re-keying first would
1140
+ // route the surviving stream's events and verbs
1141
+ // through the refused load's key and arm. Stage
1142
+ // the rejection to the refused arm directly
1143
+ // (the channel-admission precedent) and leave
1144
+ // the entry — and the engine — untouched.
1145
+ if (Fx.videoLoadRejected(options)) {
1146
+ fx.stageLoopMsg(msgFromTagVideo(event_tag, .{
1147
+ .key = videoKeyForTag(event_tag),
1148
+ .kind = .rejected,
1149
+ }));
1150
+ } else {
1151
+ // One player is the whole surface: an
1152
+ // accepted load re-keys and re-routes the
1153
+ // single entry in place, exactly as the
1154
+ // engine replaces its channel.
1155
+ video_entry.used = true;
1156
+ video_entry.key_len = key.len;
1157
+ @memcpy(video_entry.key[0..key.len], key);
1158
+ video_entry.event_tag = event_tag;
1159
+ fx.loadVideo(options);
1160
+ // The identity this load minted (valid even
1161
+ // when a synchronous refusal already reset
1162
+ // the channel): the entry's verbs prove
1163
+ // ownership against it.
1164
+ video_entry.token = fx.videoMintedToken();
1165
+ }
1166
+ },
1167
+ // video_ctl [op][key_len][key][verb u8][value f64 LE]
1168
+ 0x18 => {
1169
+ const key = takeShortBytes(cmd, &at);
1170
+ const verb = takeByte(cmd, &at);
1171
+ const value_bits = takeBytes(cmd, &at, 8);
1172
+ const value: f64 = @bitCast(std.mem.readInt(u64, value_bits[0..8], .little));
1173
+ runVideoCtl(fx, key, verb, value);
1174
+ },
1175
+ // pty_spawn [op][key_len][key][event_tag]
1176
+ // [cols f64 LE][rows f64 LE][term_len][term]
1177
+ // [argc u8]([arg_len u32 LE][arg])*
1178
+ 0x19 => {
1179
+ const key = takeShortBytes(cmd, &at);
1180
+ const event_tag = takeByte(cmd, &at);
1181
+ const cols_bits = takeBytes(cmd, &at, 8);
1182
+ const cols: f64 = @bitCast(std.mem.readInt(u64, cols_bits[0..8], .little));
1183
+ const rows_bits = takeBytes(cmd, &at, 8);
1184
+ const rows: f64 = @bitCast(std.mem.readInt(u64, rows_bits[0..8], .little));
1185
+ const term = takeShortBytes(cmd, &at);
1186
+ const argc: usize = takeByte(cmd, &at);
1187
+ if (argc == 0 or argc > runtime_effects.max_effect_argv) {
1188
+ @panic("ts core host: a pty_spawn wire record carries more argv elements than the engine accepts - the transpiler's own bound should have stopped this build");
1189
+ }
1190
+ var argv: [runtime_effects.max_effect_argv][]const u8 = undefined;
1191
+ for (0..argc) |i| argv[i] = takeLongBytes(cmd, &at);
1192
+ issuePtySpawn(fx, key, event_tag, cols, rows, term, argv[0..argc]);
1193
+ },
1194
+ // pty_write [op][key_len][key][bytes_len u32 LE][bytes]
1195
+ 0x1A => {
1196
+ const key = takeShortBytes(cmd, &at);
1197
+ const bytes = takeLongBytes(cmd, &at);
1198
+ // TS `Cmd.ptyWrite` is fire-and-forget: a refusal
1199
+ // counts into the exit's dropped_writes, so the
1200
+ // acceptance result is ignored here.
1201
+ if (findPty(key)) |index| _ = fx.ptyWrite(pty_key_base + index, bytes);
1202
+ },
1203
+ // pty_resize [op][key_len][key][cols f64 LE][rows f64 LE]
1204
+ 0x1B => {
1205
+ const key = takeShortBytes(cmd, &at);
1206
+ const cols_bits = takeBytes(cmd, &at, 8);
1207
+ const cols: f64 = @bitCast(std.mem.readInt(u64, cols_bits[0..8], .little));
1208
+ const rows_bits = takeBytes(cmd, &at, 8);
1209
+ const rows: f64 = @bitCast(std.mem.readInt(u64, rows_bits[0..8], .little));
1210
+ runPtyResize(fx, key, cols, rows);
1211
+ },
1212
+ // pty_kill [op][key_len][key]
1213
+ 0x1C => {
1214
+ const key = takeShortBytes(cmd, &at);
1215
+ // LOUD: the engine ends the child and the session's
1216
+ // one "cancelled" exit routes its own event arm,
1217
+ // retiring the entry in ptyEventMsg.
1218
+ if (findPty(key)) |index| fx.ptyKill(pty_key_base + index);
1219
+ },
983
1220
  else => @panic("ts core host: unknown command wire record - the core and this runtime disagree on cmd_format_version"),
984
1221
  }
985
1222
  }
@@ -1112,15 +1349,9 @@ pub fn TsCoreHost(comptime core: type) type {
1112
1349
  collect: bool,
1113
1350
  argv: []const []const u8,
1114
1351
  stdin: []const u8,
1115
- rejects: *[max_rejects_per_cmd]u8,
1116
- reject_count: *usize,
1117
1352
  ) void {
1118
1353
  if (head.key.len > 0 and findStream(head.key) != null) {
1119
- if (reject_count.* >= max_rejects_per_cmd) {
1120
- @panic("ts core host: one command value carries more rejected named ops than the effect table holds");
1121
- }
1122
- rejects[reject_count.*] = head.err_tag;
1123
- reject_count.* += 1;
1354
+ fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1124
1355
  return;
1125
1356
  }
1126
1357
  const index = freeStreamIndex() orelse
@@ -1242,11 +1473,100 @@ pub fn TsCoreHost(comptime core: type) type {
1242
1473
  return msgFromTagAudio(audio_entry.event_tag, event);
1243
1474
  }
1244
1475
 
1476
+ // ------------------------------------------------- video stream
1477
+
1478
+ /// The video_ctl record: drive the single playback channel,
1479
+ /// gated by the wire key — a verb aimed at a key that is not
1480
+ /// the open stream no-ops (its playback is already gone), the
1481
+ /// same idle no-op the engine's own verbs keep. `stop` closes
1482
+ /// the stream: the entry retires and later platform stragglers
1483
+ /// are the engine's to swallow.
1484
+ fn runVideoCtl(fx: *Fx, key: []const u8, verb: u8, value: f64) void {
1485
+ if (!video_entry.used or !std.mem.eql(u8, video_entry.wireKey(), key)) return;
1486
+ if (verb == 2) {
1487
+ // `Cmd.videoStop` is the stream's CANCEL: the engine
1488
+ // drops THIS stream's staged answers (token-scoped —
1489
+ // even the synchronous terminal of a batch that
1490
+ // loaded, failed, and stopped in one dispatch, and
1491
+ // even when a later load reuses the same event tag),
1492
+ // and stops the player only while the channel still
1493
+ // plays this stream — a playback some other caller
1494
+ // loaded since (a declarative element) survives
1495
+ // untouched. A REPLACED predecessor sharing this arm
1496
+ // keeps its own owed terminal; only stop cancels.
1497
+ const token = video_entry.token;
1498
+ video_entry.used = false;
1499
+ fx.stopVideoCancel(token);
1500
+ return;
1501
+ }
1502
+ // The wire key names the bridge's entry, but the single
1503
+ // engine player may since have been replaced by a load the
1504
+ // bridge never issued (a declarative <video>): transport
1505
+ // verbs act only while the entry's own stream is the
1506
+ // playback on the channel — anything else is a stale key
1507
+ // and no-ops, the idle rule. VOLUME is the one exception
1508
+ // with the channel IDLE: it is a remembered preference the
1509
+ // next load re-applies (a failed load's handler routinely
1510
+ // sets it before retrying), and with nobody's playback on
1511
+ // the channel there is nothing to protect — a FOREIGN live
1512
+ // playback still gates it, its volume is not this key's to
1513
+ // move.
1514
+ if (fx.videoOwnerToken() != video_entry.token) {
1515
+ if (verb == 4 and fx.videoOwnerToken() == 0) {
1516
+ fx.setVideoVolume(@floatCast(value));
1517
+ }
1518
+ return;
1519
+ }
1520
+ switch (verb) {
1521
+ 0 => fx.playVideo(),
1522
+ 1 => fx.pauseVideo(),
1523
+ // The wire carries the app's f64. In-window offsets pass
1524
+ // through (the engine clamps to the duration itself); a
1525
+ // FINITE offset PAST the exact-integer window saturates
1526
+ // just below it — still beyond every real duration, so
1527
+ // the engine's clamp lands it at the end, exactly what
1528
+ // an oversized forward seek asks for. Non-finite values
1529
+ // and negatives are not millisecond offsets at all (the
1530
+ // literal validation rejects them) and seek to 0.
1531
+ 3 => fx.seekVideo(if (value >= 0 and value <= 9007199254740992.0)
1532
+ @intFromFloat(value)
1533
+ else if (value > 9007199254740992.0 and std.math.isFinite(value))
1534
+ runtime_effects.max_effect_video_scalar_exclusive - 1
1535
+ else
1536
+ 0),
1537
+ // The engine clamps volume to 0..1 (NaN clamps to the
1538
+ // bound arithmetic's result deterministically).
1539
+ 4 => fx.setVideoVolume(@floatCast(value)),
1540
+ 5 => fx.setVideoMuted(value != 0),
1541
+ 6 => fx.setVideoLoop(value != 0),
1542
+ else => @panic("ts core host: unknown video_ctl verb wire value - the core and this runtime disagree on cmd_format_version"),
1543
+ }
1544
+ }
1545
+
1546
+ /// `VideoMsgFn` for the video stream: every playback event
1547
+ /// routes by the TAG its own key carries (`videoKeyForTag`) —
1548
+ /// never the mutable entry's tag, which a replacing load in the
1549
+ /// same batch may already have re-pointed at another arm while
1550
+ /// the replaced playback's staged terminal was still awaiting
1551
+ /// its drain (a REPLACED stream still speaks its terminal).
1552
+ /// Stopped streams never reach here at all: video_ctl `stop`
1553
+ /// cancels the key's staged answers inside the engine
1554
+ /// (`stopVideoCancel`) and the engine swallows its own
1555
+ /// post-stop stragglers, so every event arriving carries a
1556
+ /// live stream's tag. The entry never retires here —
1557
+ /// `completed`/`failed` streams may still speak (the app often
1558
+ /// starts the next clip from `completed`), and video_ctl
1559
+ /// `stop` is the explicit close.
1560
+ fn videoEventMsg(event: runtime_effects.EffectVideo) Msg {
1561
+ return msgFromTagVideo(@intCast(event.key & 0xFF), event);
1562
+ }
1563
+
1245
1564
  /// Issue one image load. The keyed-effect discipline here is
1246
1565
  /// the SPAWN exception, by the same reasoning: one load per id
1247
1566
  /// at a time, never replaced implicitly — a duplicate LIVE id
1248
- /// rejects the new load (event arm, state "rejected", at the
1249
- /// post-cycle boundary), and so do an id the f64 wire cannot
1567
+ /// rejects the new load (event arm, state "rejected", staged
1568
+ /// into the engine's pending order and delivered at the next
1569
+ /// drain), and so do an id the f64 wire cannot
1250
1570
  /// honestly carry into the u64 registry (0, negatives,
1251
1571
  /// fractions, 2^53 and past) and a 17th in-flight load (the table
1252
1572
  /// mirrors the engine's max_effects slots, whose own exhaustion
@@ -1261,7 +1581,6 @@ pub fn TsCoreHost(comptime core: type) type {
1261
1581
  url: []const u8,
1262
1582
  cache_path: []const u8,
1263
1583
  expected: f64,
1264
- image_rejects: *ImageRejectStage,
1265
1584
  ) void {
1266
1585
  // Strictly BELOW 2^53 (the SDK contract): at 2^53 the f64
1267
1586
  // grid steps by 2, so 2^53 is the first value that aliases
@@ -1272,12 +1591,12 @@ pub fn TsCoreHost(comptime core: type) type {
1272
1591
  id_value >= 1 and id_value < 9007199254740992.0 and
1273
1592
  @floor(id_value) == id_value;
1274
1593
  if (!representable) {
1275
- image_rejects.push(event_tag, 0);
1594
+ fx.stageLoopMsg(msgFromTagImage(event_tag, .{ .id = 0, .outcome = .rejected }));
1276
1595
  return;
1277
1596
  }
1278
1597
  const id: u64 = @intFromFloat(id_value);
1279
1598
  if (findImage(id) != null) {
1280
- image_rejects.push(event_tag, id);
1599
+ fx.stageLoopMsg(msgFromTagImage(event_tag, .{ .id = id, .outcome = .rejected }));
1281
1600
  return;
1282
1601
  }
1283
1602
  const index = freeImageIndex() orelse {
@@ -1289,7 +1608,7 @@ pub fn TsCoreHost(comptime core: type) type {
1289
1608
  // vocabulary: exactly one rejected result through the
1290
1609
  // event arm, never a crash — however many loads one
1291
1610
  // batch stages against it.
1292
- image_rejects.push(event_tag, id);
1611
+ fx.stageLoopMsg(msgFromTagImage(event_tag, .{ .id = id, .outcome = .rejected }));
1293
1612
  return;
1294
1613
  };
1295
1614
  const entry = &images[index];
@@ -1390,6 +1709,224 @@ pub fn TsCoreHost(comptime core: type) type {
1390
1709
  return msgFromTagImage(entry.event_tag, result);
1391
1710
  }
1392
1711
 
1712
+ /// Open one external-source channel. The keyed-effect
1713
+ /// discipline here is the spawn/image exception, by the same
1714
+ /// reasoning: one channel per key at a time, never replaced
1715
+ /// implicitly — a duplicate LIVE key rejects the new open
1716
+ /// (event arm, state "rejected", staged into the engine's
1717
+ /// pending order and delivered at the next drain),
1718
+ /// and so do a key the f64 wire cannot honestly carry into the
1719
+ /// u64 engine (0, negatives, fractions, 2^53 and past — the
1720
+ /// image id gate) and a bridge table already holding
1721
+ /// `max_effect_channels` live channels. Everything else the
1722
+ /// engine refuses dynamically (a key occupied by another
1723
+ /// family, the engine's own table) comes back through the
1724
+ /// entry's event arm as its `.rejected` terminal — never
1725
+ /// silent. Posting is native-side API: embedders resolve
1726
+ /// `Effects.channelHandle(key)` and feed from their own
1727
+ /// threads; this bridge only opens, closes, and routes.
1728
+ fn issueChannelOpen(
1729
+ fx: *Fx,
1730
+ key_value: f64,
1731
+ event_tag: u8,
1732
+ ) void {
1733
+ const representable = std.math.isFinite(key_value) and
1734
+ key_value >= 1 and key_value < 9007199254740992.0 and
1735
+ @floor(key_value) == key_value;
1736
+ if (!representable) {
1737
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = 0, .kind = .rejected }));
1738
+ return;
1739
+ }
1740
+ const key: u64 = @intFromFloat(key_value);
1741
+ if (findChannel(key) != null) {
1742
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = key, .kind = .rejected }));
1743
+ return;
1744
+ }
1745
+ const index = freeChannelIndex() orelse {
1746
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = key, .kind = .rejected }));
1747
+ return;
1748
+ };
1749
+ const entry = &channels[index];
1750
+ entry.used = true;
1751
+ entry.key = key;
1752
+ entry.event_tag = event_tag;
1753
+ _ = fx.openChannel(.{
1754
+ .key = key,
1755
+ .on_event = channelEventMsg,
1756
+ });
1757
+ }
1758
+
1759
+ fn findChannel(key: u64) ?usize {
1760
+ for (&channels, 0..) |*entry, index| {
1761
+ if (entry.used and entry.key == key) return index;
1762
+ }
1763
+ return null;
1764
+ }
1765
+
1766
+ fn freeChannelIndex() ?usize {
1767
+ for (&channels, 0..) |*entry, index| {
1768
+ if (!entry.used) return index;
1769
+ }
1770
+ return null;
1771
+ }
1772
+
1773
+ /// The channel_close record: close the live channel under the
1774
+ /// key, if any — the engine flushes staged posts, delivers the
1775
+ /// one `.closed` terminal through `channelEventMsg` (which
1776
+ /// retires the entry), and frees the key. A key naming no live
1777
+ /// entry — or one the wire cannot carry exactly, which no
1778
+ /// channel could ever open under — is a no-op, audio_ctl's
1779
+ /// idle rule. The raw key IS the engine key (the image
1780
+ /// convention; every bridge key base sits above 2^53, so this
1781
+ /// can never reach another table's slot).
1782
+ fn runChannelClose(fx: *Fx, key_value: f64) void {
1783
+ const representable = std.math.isFinite(key_value) and
1784
+ key_value >= 1 and key_value < 9007199254740992.0 and
1785
+ @floor(key_value) == key_value;
1786
+ if (!representable) return;
1787
+ const key: u64 = @intFromFloat(key_value);
1788
+ if (findChannel(key) == null) return;
1789
+ fx.closeChannel(key);
1790
+ }
1791
+
1792
+ /// `ChannelMsgFn` for external-source channels: every event
1793
+ /// routes the entry's event arm; the `closed` and `rejected`
1794
+ /// terminals retire the entry (freeing the key for a fresh
1795
+ /// open), `data` events keep it live — the spawn stream shape.
1796
+ fn channelEventMsg(event: runtime_effects.EffectChannelEvent) Msg {
1797
+ const index = findChannel(event.key) orelse
1798
+ @panic("ts core host: a channel event arrived with no open bridge entry");
1799
+ const entry = &channels[index];
1800
+ if (event.kind != .data) entry.used = false;
1801
+ return msgFromTagChannel(entry.event_tag, event);
1802
+ }
1803
+
1804
+ // -------------------------------------------------- pty sessions
1805
+
1806
+ /// Open a pty session: claim a non-retiring entry (the spawn
1807
+ /// exception, by the same reasoning — a live wire key REJECTS
1808
+ /// the new spawn, because a running terminal's child is a
1809
+ /// running subprocess and is never killed implicitly; kill it
1810
+ /// first) and hand the request to the engine. Everything
1811
+ /// dynamic the engine refuses (argv over the block bound, a
1812
+ /// zero grid, a full engine table) comes back as one
1813
+ /// "rejected" exit through the entry's own event arm — never
1814
+ /// silent — and a transport that could not start as one
1815
+ /// "spawn_failed".
1816
+ fn issuePtySpawn(
1817
+ fx: *Fx,
1818
+ key: []const u8,
1819
+ event_tag: u8,
1820
+ cols: f64,
1821
+ rows: f64,
1822
+ term: []const u8,
1823
+ argv: []const []const u8,
1824
+ ) void {
1825
+ if (key.len > 0 and findPty(key) != null) {
1826
+ // The rejection is STAGED (delivered a later frame), so its
1827
+ // key must be self-contained: the wire key points into this
1828
+ // dispatch's command buffer, gone by delivery, so intern
1829
+ // it in the engine's instance-lived staged-key store and
1830
+ // reference that. The app's key rides the refusal,
1831
+ // correlating it with its command — and the interned
1832
+ // slice stays valid even committed into the model.
1833
+ fx.stageLoopMsg(msgFromTagPty(event_tag, fx.stageLoopKey(key), true, .{ .key = 0, .kind = .exit, .reason = .rejected }));
1834
+ return;
1835
+ }
1836
+ const index = freePtyIndex() orelse {
1837
+ // The bridge table mirrors the engine's pty table, whose
1838
+ // own exhaustion answer is the same rejected exit — one
1839
+ // vocabulary for every refusal, never a crash. Staged, so
1840
+ // the requested key rides the engine's interned
1841
+ // instance-lived staged-key store, not the frame arena.
1842
+ fx.stageLoopMsg(msgFromTagPty(event_tag, fx.stageLoopKey(key), true, .{ .key = 0, .kind = .exit, .reason = .rejected }));
1843
+ return;
1844
+ };
1845
+ const entry = &ptys[index];
1846
+ entry.used = true;
1847
+ entry.key_len = key.len;
1848
+ @memcpy(entry.key[0..key.len], key);
1849
+ entry.event_tag = event_tag;
1850
+ if (term.len == 0) {
1851
+ // Wire "" = "the engine's default TERM" — the record
1852
+ // never bakes the default in (the fetch-timeout rule).
1853
+ fx.ptySpawn(.{
1854
+ .key = pty_key_base + index,
1855
+ .argv = argv,
1856
+ .cols = ptyDimension(cols),
1857
+ .rows = ptyDimension(rows),
1858
+ .on_event = ptyEventMsg,
1859
+ });
1860
+ } else {
1861
+ fx.ptySpawn(.{
1862
+ .key = pty_key_base + index,
1863
+ .argv = argv,
1864
+ .cols = ptyDimension(cols),
1865
+ .rows = ptyDimension(rows),
1866
+ .term = term,
1867
+ .on_event = ptyEventMsg,
1868
+ });
1869
+ }
1870
+ }
1871
+
1872
+ /// The wire carries the app's f64; the transport's grid is u16.
1873
+ /// Anything that is not a whole dimension in 1..65535 maps to
1874
+ /// 0, which `ptySpawn` answers with one deterministic
1875
+ /// "rejected" exit — loud, never a truncated guess (the emitter
1876
+ /// already stops the literal spellings, NS1030).
1877
+ fn ptyDimension(value: f64) u16 {
1878
+ if (!(std.math.isFinite(value) and value >= 1 and value <= 65535 and @floor(value) == value)) return 0;
1879
+ return @intFromFloat(value);
1880
+ }
1881
+
1882
+ /// The pty_resize record: push a new grid to the live session
1883
+ /// under the wire key, if any — fire-and-forget. A key naming
1884
+ /// no session, or a grid value the u16 transport cannot carry
1885
+ /// exactly, is a no-op (there is no honest grid to push, and
1886
+ /// the engine's clamp would otherwise shrink the child to a
1887
+ /// 1x1 the app never asked for).
1888
+ fn runPtyResize(fx: *Fx, key: []const u8, cols: f64, rows: f64) void {
1889
+ const index = findPty(key) orelse return;
1890
+ const c = ptyDimension(cols);
1891
+ const r = ptyDimension(rows);
1892
+ if (c == 0 or r == 0) return;
1893
+ fx.ptyResize(pty_key_base + index, c, r);
1894
+ }
1895
+
1896
+ fn findPty(key: []const u8) ?usize {
1897
+ if (key.len == 0) return null;
1898
+ for (&ptys, 0..) |*entry, index| {
1899
+ if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
1900
+ }
1901
+ return null;
1902
+ }
1903
+
1904
+ fn freePtyIndex() ?usize {
1905
+ for (&ptys, 0..) |*entry, index| {
1906
+ if (!entry.used) return index;
1907
+ }
1908
+ return null;
1909
+ }
1910
+
1911
+ /// `PtyMsgFn` for pty sessions: every event routes the entry's
1912
+ /// event arm; the one "exit" terminal retires the entry
1913
+ /// (freeing the wire key for a fresh session), "output"
1914
+ /// batches keep it live — the spawn stream shape.
1915
+ fn ptyEventMsg(event: runtime_effects.EffectPtyEvent) Msg {
1916
+ if (event.key < pty_key_base) {
1917
+ @panic("ts core host: a pty event arrived outside the bridge's pty key namespace");
1918
+ }
1919
+ const index = event.key - pty_key_base;
1920
+ if (index >= ptys.len or !ptys[index].used) {
1921
+ @panic("ts core host: a pty event arrived for a session the bridge is not tracking");
1922
+ }
1923
+ const entry = &ptys[index];
1924
+ const wire_key = entry.wireKey();
1925
+ if (event.kind == .exit) entry.used = false;
1926
+ // Live delivery is same-frame, so the key rides the frame arena.
1927
+ return msgFromTagPty(entry.event_tag, wire_key, false, event);
1928
+ }
1929
+
1393
1930
  /// The wire `cancel` record: first match wins across the four
1394
1931
  /// keyed tables — requests (silent drop), named engine ops
1395
1932
  /// (silent drop: the entry is marked dropped, the engine's
@@ -1696,6 +2233,25 @@ pub fn TsCoreHost(comptime core: type) type {
1696
2233
  @panic("ts core host: a routed result names a Msg tag outside the union");
1697
2234
  }
1698
2235
 
2236
+ /// `msgFromTagBytes` for STATIC payloads (the staged rejection
2237
+ /// Msgs' "rejected"): no frame-arena copy, because a staged
2238
+ /// Msg outlives the issuing cycle's frame reset — it is held
2239
+ /// in the engine's pending order until the next drain, so its
2240
+ /// payload must be self-contained (`stageLoopMsg`'s contract).
2241
+ /// The commit walkers keep non-frame pointers as-is, and a
2242
+ /// static string's lifetime is the program's.
2243
+ fn msgFromTagStaticBytes(tag: u8, comptime bytes: []const u8) Msg {
2244
+ inline for (msg_arms, 0..) |arm, index| {
2245
+ if (tag == index) {
2246
+ if (comptime arm.type == []const u8) {
2247
+ return @unionInit(Msg, arm.name, bytes);
2248
+ }
2249
+ @panic("ts core host: a routed result targets Msg arm '" ++ arm.name ++ "', whose payload is not bytes");
2250
+ }
2251
+ }
2252
+ @panic("ts core host: a routed result names a Msg tag outside the union");
2253
+ }
2254
+
1699
2255
  /// Build the payload-less Msg arm at index `tag` (write_file's
1700
2256
  /// ok route — success carries nothing).
1701
2257
  fn msgFromTagVoid(tag: u8) Msg {
@@ -1717,7 +2273,7 @@ pub fn TsCoreHost(comptime core: type) type {
1717
2273
  /// transpiler validates the shape, so field names stay the
1718
2274
  /// app's). The bytes copy into the core's frame arena like
1719
2275
  /// every routed payload; the number widens into its field the
1720
- /// way the subset's number model classes it (i64 or f64).
2276
+ /// way the subset's number model classes it (i64, u64, or f64).
1721
2277
  fn msgFromTagNumberBytes(comptime what: []const u8, comptime shape: []const u8, tag: u8, number: anytype, bytes: []const u8) Msg {
1722
2278
  inline for (msg_arms, 0..) |arm, index| {
1723
2279
  if (tag == index) {
@@ -1730,7 +2286,7 @@ pub fn TsCoreHost(comptime core: type) type {
1730
2286
  var number_fields = 0;
1731
2287
  for (fields) |f| {
1732
2288
  if (f.type == []const u8) bytes_fields += 1;
1733
- if (f.type == i64 or f.type == f64) number_fields += 1;
2289
+ if (f.type == i64 or f.type == u64 or f.type == f64) number_fields += 1;
1734
2290
  }
1735
2291
  break :blk bytes_fields == 1 and number_fields == 1;
1736
2292
  };
@@ -1744,6 +2300,17 @@ pub fn TsCoreHost(comptime core: type) type {
1744
2300
  } else if (comptime f.type == f64) {
1745
2301
  @field(payload, f.name) = @floatFromInt(number);
1746
2302
  } else {
2303
+ // Exit codes carry -1 sentinels by
2304
+ // contract: a negative host number
2305
+ // into an unsigned field has no
2306
+ // honest value, so the crossing
2307
+ // teaches instead of faulting in
2308
+ // the cast.
2309
+ if (comptime f.type == u64) {
2310
+ if (number < 0) {
2311
+ @panic("ts core host: a negative number reached the u64-classed field '" ++ f.name ++ "' of Msg arm '" ++ arm.name ++ "' — the unsigned class cannot carry it; declare the field i64 or f64");
2312
+ }
2313
+ }
1747
2314
  @field(payload, f.name) = @intCast(number);
1748
2315
  }
1749
2316
  }
@@ -1771,7 +2338,7 @@ pub fn TsCoreHost(comptime core: type) type {
1771
2338
  if (std.mem.eql(u8, f.name, "state")) {
1772
2339
  if (@typeInfo(f.type) != .@"enum") ok = false;
1773
2340
  } else if (std.mem.eql(u8, f.name, "positionMs") or std.mem.eql(u8, f.name, "durationMs")) {
1774
- if (f.type != i64 and f.type != f64) ok = false;
2341
+ if (f.type != i64 and f.type != u64 and f.type != f64) ok = false;
1775
2342
  } else if (std.mem.eql(u8, f.name, "playing") or std.mem.eql(u8, f.name, "buffering")) {
1776
2343
  if (f.type != bool) ok = false;
1777
2344
  } else if (std.mem.eql(u8, f.name, "bands")) {
@@ -1798,7 +2365,7 @@ pub fn TsCoreHost(comptime core: type) type {
1798
2365
  /// engine event, by field name. The band bytes copy into the
1799
2366
  /// core's frame arena like every routed bytes payload; the
1800
2367
  /// millisecond fields widen the way the subset's number model
1801
- /// classes them (i64 or f64).
2368
+ /// classes them (i64, u64, or f64).
1802
2369
  fn msgFromTagAudio(tag: u8, event: runtime_effects.EffectAudio) Msg {
1803
2370
  inline for (msg_arms, 0..) |arm, index| {
1804
2371
  if (tag == index) {
@@ -1830,6 +2397,78 @@ pub fn TsCoreHost(comptime core: type) type {
1830
2397
  @panic("ts core host: an audio event names a Msg tag outside the union");
1831
2398
  }
1832
2399
 
2400
+ /// Whether an arm payload struct is the video event record: the
2401
+ /// seven SDK-fixed fields, matched by NAME — `state` (any enum;
2402
+ /// its members are matched by member name at delivery),
2403
+ /// `positionMs`/`durationMs` (numbers), `playing`/`buffering`
2404
+ /// (booleans), `width`/`height` (numbers).
2405
+ fn videoArmShape(comptime T: type) bool {
2406
+ const info = @typeInfo(T);
2407
+ if (info != .@"struct") return false;
2408
+ const fields = info.@"struct".fields;
2409
+ if (fields.len != 7) return false;
2410
+ var ok = true;
2411
+ for (fields) |f| {
2412
+ if (std.mem.eql(u8, f.name, "state")) {
2413
+ if (@typeInfo(f.type) != .@"enum") ok = false;
2414
+ } else if (std.mem.eql(u8, f.name, "positionMs") or std.mem.eql(u8, f.name, "durationMs") or
2415
+ std.mem.eql(u8, f.name, "width") or std.mem.eql(u8, f.name, "height"))
2416
+ {
2417
+ if (f.type != i64 and f.type != u64 and f.type != f64) ok = false;
2418
+ } else if (std.mem.eql(u8, f.name, "playing") or std.mem.eql(u8, f.name, "buffering")) {
2419
+ if (f.type != bool) ok = false;
2420
+ } else {
2421
+ ok = false;
2422
+ }
2423
+ }
2424
+ return ok;
2425
+ }
2426
+
2427
+ /// The arm's `state` member for an engine event kind, matched
2428
+ /// by member NAME — `audioStateValue`'s twin.
2429
+ fn videoStateValue(comptime E: type, kind: runtime_effects.EffectVideoEventKind) E {
2430
+ const name = @tagName(kind);
2431
+ inline for (@typeInfo(E).@"enum".fields) |f| {
2432
+ if (std.mem.eql(u8, f.name, name)) return @enumFromInt(f.value);
2433
+ }
2434
+ @panic("ts core host: a video event kind has no member in the event arm's state union - the transpiler's own shape check should have stopped this build");
2435
+ }
2436
+
2437
+ /// Build the seven-field video event arm at index `tag` from an
2438
+ /// engine event, by field name. The millisecond and dimension
2439
+ /// fields widen the way the subset's number model classes them
2440
+ /// (i64, u64, or f64).
2441
+ fn msgFromTagVideo(tag: u8, event: runtime_effects.EffectVideo) Msg {
2442
+ inline for (msg_arms, 0..) |arm, index| {
2443
+ if (tag == index) {
2444
+ if (comptime videoArmShape(arm.type)) {
2445
+ const fields = @typeInfo(arm.type).@"struct".fields;
2446
+ var payload: arm.type = undefined;
2447
+ inline for (fields) |f| {
2448
+ if (comptime std.mem.eql(u8, f.name, "state")) {
2449
+ @field(payload, f.name) = videoStateValue(f.type, event.kind);
2450
+ } else if (comptime std.mem.eql(u8, f.name, "positionMs")) {
2451
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.position_ms) else @intCast(event.position_ms);
2452
+ } else if (comptime std.mem.eql(u8, f.name, "durationMs")) {
2453
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.duration_ms) else @intCast(event.duration_ms);
2454
+ } else if (comptime std.mem.eql(u8, f.name, "playing")) {
2455
+ @field(payload, f.name) = event.playing;
2456
+ } else if (comptime std.mem.eql(u8, f.name, "buffering")) {
2457
+ @field(payload, f.name) = event.buffering;
2458
+ } else if (comptime std.mem.eql(u8, f.name, "width")) {
2459
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.width) else @intCast(event.width);
2460
+ } else {
2461
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.height) else @intCast(event.height);
2462
+ }
2463
+ }
2464
+ return @unionInit(Msg, arm.name, payload);
2465
+ }
2466
+ @panic("ts core host: a video event targets Msg arm '" ++ arm.name ++ "', which is not the seven-field video event record");
2467
+ }
2468
+ }
2469
+ @panic("ts core host: a video event names a Msg tag outside the union");
2470
+ }
2471
+
1833
2472
  /// The five-field image result record, matched by field name —
1834
2473
  /// `audioArmShape`'s twin.
1835
2474
  fn imageArmShape(comptime T: type) bool {
@@ -1842,7 +2481,7 @@ pub fn TsCoreHost(comptime core: type) type {
1842
2481
  if (std.mem.eql(u8, f.name, "state")) {
1843
2482
  if (@typeInfo(f.type) != .@"enum") ok = false;
1844
2483
  } else if (std.mem.eql(u8, f.name, "id") or std.mem.eql(u8, f.name, "width") or std.mem.eql(u8, f.name, "height") or std.mem.eql(u8, f.name, "status")) {
1845
- if (f.type != i64 and f.type != f64) ok = false;
2484
+ if (f.type != i64 and f.type != u64 and f.type != f64) ok = false;
1846
2485
  } else {
1847
2486
  ok = false;
1848
2487
  }
@@ -1891,9 +2530,200 @@ pub fn TsCoreHost(comptime core: type) type {
1891
2530
  @panic("ts core host: an image result names a Msg tag outside the union");
1892
2531
  }
1893
2532
 
2533
+ /// The five-field channel event record, matched by field name —
2534
+ /// `imageArmShape`'s twin: `key` (number), `state` (any enum;
2535
+ /// members matched by name at delivery), `bytes` (bytes),
2536
+ /// `droppedPending`/`droppedTotal` (numbers).
2537
+ fn channelArmShape(comptime T: type) bool {
2538
+ const info = @typeInfo(T);
2539
+ if (info != .@"struct") return false;
2540
+ const fields = info.@"struct".fields;
2541
+ if (fields.len != 5) return false;
2542
+ var ok = true;
2543
+ for (fields) |f| {
2544
+ if (std.mem.eql(u8, f.name, "state")) {
2545
+ if (@typeInfo(f.type) != .@"enum") ok = false;
2546
+ } else if (std.mem.eql(u8, f.name, "bytes")) {
2547
+ if (f.type != []const u8) ok = false;
2548
+ } else if (std.mem.eql(u8, f.name, "key") or std.mem.eql(u8, f.name, "droppedPending") or std.mem.eql(u8, f.name, "droppedTotal")) {
2549
+ if (f.type != i64 and f.type != u64 and f.type != f64) ok = false;
2550
+ } else {
2551
+ ok = false;
2552
+ }
2553
+ }
2554
+ return ok;
2555
+ }
2556
+
2557
+ /// The arm's `state` member for an engine channel event kind,
2558
+ /// matched by member NAME — `imageStateValue`'s twin.
2559
+ fn channelStateValue(comptime E: type, kind: runtime_effects.EffectChannelEventKind) E {
2560
+ const name = @tagName(kind);
2561
+ inline for (@typeInfo(E).@"enum".fields) |f| {
2562
+ if (std.mem.eql(u8, f.name, name)) return @enumFromInt(f.value);
2563
+ }
2564
+ @panic("ts core host: a channel event kind has no member in the event arm's state union - the transpiler's own shape check should have stopped this build");
2565
+ }
2566
+
2567
+ /// Build the five-field channel event arm at index `tag` from
2568
+ /// an engine event, by field name. The bytes copy into the
2569
+ /// core's frame arena like every routed payload (the engine's
2570
+ /// slice is drain scratch); `key` is the channel key echoed
2571
+ /// verbatim (always below 2^53 — the bridge refused anything
2572
+ /// wider — so both number classes carry it exactly), and the
2573
+ /// drop counters widen the way the subset's number model
2574
+ /// classes them.
2575
+ fn msgFromTagChannel(tag: u8, event: runtime_effects.EffectChannelEvent) Msg {
2576
+ inline for (msg_arms, 0..) |arm, index| {
2577
+ if (tag == index) {
2578
+ if (comptime channelArmShape(arm.type)) {
2579
+ const fields = @typeInfo(arm.type).@"struct".fields;
2580
+ var payload: arm.type = undefined;
2581
+ inline for (fields) |f| {
2582
+ if (comptime std.mem.eql(u8, f.name, "state")) {
2583
+ @field(payload, f.name) = channelStateValue(f.type, event.kind);
2584
+ } else if (comptime std.mem.eql(u8, f.name, "key")) {
2585
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.key) else @intCast(event.key);
2586
+ } else if (comptime std.mem.eql(u8, f.name, "droppedPending")) {
2587
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.dropped_pending) else @intCast(event.dropped_pending);
2588
+ } else if (comptime std.mem.eql(u8, f.name, "droppedTotal")) {
2589
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.dropped_total) else @intCast(event.dropped_total);
2590
+ } else if (event.bytes.len == 0) {
2591
+ // Payload-free events (rejected/closed
2592
+ // terminals, and the staged rejection
2593
+ // Msgs that must be self-contained
2594
+ // across the frame reset) carry the
2595
+ // static empty slice, never a
2596
+ // zero-length frame pointer.
2597
+ @field(payload, f.name) = "";
2598
+ } else {
2599
+ const copy = core.rt.frameAlloc(u8, event.bytes.len);
2600
+ @memcpy(copy, event.bytes);
2601
+ @field(payload, f.name) = copy;
2602
+ }
2603
+ }
2604
+ return @unionInit(Msg, arm.name, payload);
2605
+ }
2606
+ @panic("ts core host: a channel event targets Msg arm '" ++ arm.name ++ "', which is not the five-field channel event record");
2607
+ }
2608
+ }
2609
+ @panic("ts core host: a channel event names a Msg tag outside the union");
2610
+ }
2611
+
2612
+ /// The six-field pty event record, matched by field name —
2613
+ /// `channelArmShape`'s twin: `state` and `reason` (any enums;
2614
+ /// members matched by name at delivery), `bytes` (bytes),
2615
+ /// `code`/`signal`/`droppedWrites` (numbers).
2616
+ fn ptyArmShape(comptime T: type) bool {
2617
+ const info = @typeInfo(T);
2618
+ if (info != .@"struct") return false;
2619
+ const fields = info.@"struct".fields;
2620
+ if (fields.len != 7) return false;
2621
+ var ok = true;
2622
+ for (fields) |f| {
2623
+ if (std.mem.eql(u8, f.name, "state") or std.mem.eql(u8, f.name, "reason")) {
2624
+ if (@typeInfo(f.type) != .@"enum") ok = false;
2625
+ } else if (std.mem.eql(u8, f.name, "bytes") or std.mem.eql(u8, f.name, "key")) {
2626
+ if (f.type != []const u8) ok = false;
2627
+ } else if (std.mem.eql(u8, f.name, "code")) {
2628
+ // Non-exited terminals deliver the -1 code sentinel:
2629
+ // signed by contract, so the unsigned class cannot
2630
+ // carry it. `signal` stays zero-or-positive (the
2631
+ // fatal signal number, else 0) and takes any class.
2632
+ if (f.type != i64 and f.type != f64) ok = false;
2633
+ } else if (std.mem.eql(u8, f.name, "signal") or std.mem.eql(u8, f.name, "droppedWrites")) {
2634
+ if (f.type != i64 and f.type != u64 and f.type != f64) ok = false;
2635
+ } else {
2636
+ ok = false;
2637
+ }
2638
+ }
2639
+ return ok;
2640
+ }
2641
+
2642
+ /// The arm's `state` member for an engine pty event kind,
2643
+ /// matched by member NAME — `channelStateValue`'s twin.
2644
+ fn ptyStateValue(comptime E: type, kind: runtime_effects.EffectPtyEventKind) E {
2645
+ const name = @tagName(kind);
2646
+ inline for (@typeInfo(E).@"enum".fields) |f| {
2647
+ if (std.mem.eql(u8, f.name, name)) return @enumFromInt(f.value);
2648
+ }
2649
+ @panic("ts core host: a pty event kind has no member in the event arm's state union - the transpiler's own shape check should have stopped this build");
2650
+ }
2651
+
2652
+ /// The arm's `reason` member for an engine exit reason, matched
2653
+ /// by member NAME — the state member's twin.
2654
+ fn ptyReasonValue(comptime E: type, reason: runtime_effects.EffectExitReason) E {
2655
+ const name = @tagName(reason);
2656
+ inline for (@typeInfo(E).@"enum".fields) |f| {
2657
+ if (std.mem.eql(u8, f.name, name)) return @enumFromInt(f.value);
2658
+ }
2659
+ @panic("ts core host: a pty exit reason has no member in the event arm's reason union - the transpiler's own shape check should have stopped this build");
2660
+ }
2661
+
2662
+ /// Build the six-field pty event arm at index `tag` from an
2663
+ /// engine event, by field name. The output bytes copy into the
2664
+ /// core's frame arena like every routed payload (the engine's
2665
+ /// slice is drain scratch); payload-free events — exits, and
2666
+ /// the staged rejection Msgs that must be self-contained across
2667
+ /// the frame reset — carry the static empty slice, the channel
2668
+ /// record's rule.
2669
+ fn msgFromTagPty(tag: u8, wire_key: []const u8, key_durable: bool, event: runtime_effects.EffectPtyEvent) Msg {
2670
+ inline for (msg_arms, 0..) |arm, index| {
2671
+ if (tag == index) {
2672
+ if (comptime ptyArmShape(arm.type)) {
2673
+ const fields = @typeInfo(arm.type).@"struct".fields;
2674
+ var payload: arm.type = undefined;
2675
+ inline for (fields) |f| {
2676
+ if (comptime std.mem.eql(u8, f.name, "state")) {
2677
+ @field(payload, f.name) = ptyStateValue(f.type, event.kind);
2678
+ } else if (comptime std.mem.eql(u8, f.name, "reason")) {
2679
+ @field(payload, f.name) = ptyReasonValue(f.type, event.reason);
2680
+ } else if (comptime std.mem.eql(u8, f.name, "code")) {
2681
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.code) else @intCast(event.code);
2682
+ } else if (comptime std.mem.eql(u8, f.name, "signal")) {
2683
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.signal) else @intCast(event.signal);
2684
+ } else if (comptime std.mem.eql(u8, f.name, "droppedWrites")) {
2685
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.dropped_writes) else @intCast(event.dropped_writes);
2686
+ } else if (comptime std.mem.eql(u8, f.name, "key")) {
2687
+ // The app's own session key, so two sessions
2688
+ // sharing one event arm are told apart by this
2689
+ // field (never the engine key). A LIVE event
2690
+ // routes and delivers within one frame, so its
2691
+ // key copies into the frame arena like every
2692
+ // routed payload. A STAGED rejection (issued
2693
+ // now, delivered a later frame, past a frame
2694
+ // reset) passes `key_durable = true` with a key
2695
+ // already in the durable reject ring, so it is
2696
+ // referenced directly — a frame-arena copy there
2697
+ // would dangle by delivery.
2698
+ if (wire_key.len == 0) {
2699
+ @field(payload, f.name) = "";
2700
+ } else if (key_durable) {
2701
+ @field(payload, f.name) = wire_key;
2702
+ } else {
2703
+ const copy = core.rt.frameAlloc(u8, wire_key.len);
2704
+ @memcpy(copy, wire_key);
2705
+ @field(payload, f.name) = copy;
2706
+ }
2707
+ } else if (event.bytes.len == 0) {
2708
+ @field(payload, f.name) = "";
2709
+ } else {
2710
+ const copy = core.rt.frameAlloc(u8, event.bytes.len);
2711
+ @memcpy(copy, event.bytes);
2712
+ @field(payload, f.name) = copy;
2713
+ }
2714
+ }
2715
+ return @unionInit(Msg, arm.name, payload);
2716
+ }
2717
+ @panic("ts core host: a pty event targets Msg arm '" ++ arm.name ++ "', which is not the seven-field pty event record");
2718
+ }
2719
+ }
2720
+ @panic("ts core host: a pty event names a Msg tag outside the union");
2721
+ }
2722
+
1894
2723
  /// Build the Msg arm at index `tag` carrying one number (`now`
1895
- /// timestamps and timer fires; an i64-classed arm truncates the
1896
- /// way the subset's number model does at index sites).
2724
+ /// timestamps and timer fires; an integer-classed arm — i64 or
2725
+ /// its unsigned twin — truncates the way the subset's number
2726
+ /// model does at index sites).
1897
2727
  fn msgFromTagNumber(tag: u8, value: f64) Msg {
1898
2728
  inline for (msg_arms, 0..) |arm, index| {
1899
2729
  if (tag == index) {
@@ -1901,6 +2731,16 @@ pub fn TsCoreHost(comptime core: type) type {
1901
2731
  return @unionInit(Msg, arm.name, value);
1902
2732
  } else if (comptime arm.type == i64) {
1903
2733
  return @unionInit(Msg, arm.name, @intFromFloat(value));
2734
+ } else if (comptime arm.type == u64) {
2735
+ // Clocks are signed by contract (a pre-epoch or
2736
+ // skewed wall clock is a legal reading): when
2737
+ // one reaches an unsigned arm there is no
2738
+ // honest value, so the crossing teaches instead
2739
+ // of faulting in the cast.
2740
+ if (value < 0) {
2741
+ @panic("ts core host: a negative number reached the u64-classed Msg arm '" ++ arm.name ++ "' — the unsigned class cannot carry it; declare the arm i64 or f64");
2742
+ }
2743
+ return @unionInit(Msg, arm.name, @intFromFloat(value));
1904
2744
  }
1905
2745
  @panic("ts core host: a timestamp targets Msg arm '" ++ arm.name ++ "', whose payload is not a number");
1906
2746
  }