@native-sdk/cli 0.4.3 → 0.5.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 (100) hide show
  1. package/build/app.zig +308 -72
  2. package/build/ts_run.mjs +63 -0
  3. package/build.zig +336 -7
  4. package/build.zig.zon +1 -0
  5. package/package.json +15 -10
  6. package/packages/core/package-lock.json +43 -0
  7. package/packages/core/package.json +37 -0
  8. package/packages/core/rt/rt.zig +1579 -0
  9. package/packages/core/sdk/bytes_text_methods.d.ts +88 -0
  10. package/packages/core/sdk/core.ts +694 -0
  11. package/packages/core/sdk/events.ts +137 -0
  12. package/packages/core/sdk/text.ts +519 -0
  13. package/packages/core/src/checker.ts +1869 -0
  14. package/packages/core/src/cli.ts +68 -0
  15. package/packages/core/src/devhost.ts +291 -0
  16. package/packages/core/src/devhost_resolver.mjs +22 -0
  17. package/packages/core/src/diagnostics.ts +417 -0
  18. package/packages/core/src/emitter.ts +8815 -0
  19. package/packages/core/src/infer.ts +1515 -0
  20. package/packages/core/src/modules.ts +173 -0
  21. package/packages/core/src/ownership.ts +740 -0
  22. package/packages/core/src/text_polyfill.ts +337 -0
  23. package/packages/core/src/text_tables.ts +408 -0
  24. package/packages/core/src/transpile.ts +146 -0
  25. package/packages/core/src/typed_ast.ts +536 -0
  26. package/packages/core/src/types.ts +815 -0
  27. package/skill-data/core/SKILL.md +3 -0
  28. package/skill-data/native-ui/SKILL.md +30 -0
  29. package/skill-data/ts-core/SKILL.md +493 -0
  30. package/skill-data/zig/SKILL.md +208 -0
  31. package/skills/native-sdk/SKILL.md +1 -1
  32. package/src/app_runner/root.zig +75 -9
  33. package/src/app_runner/ts_core_main.zig +231 -0
  34. package/src/platform/linux/gtk_host.c +226 -21
  35. package/src/platform/windows/webview2_host.cpp +16 -10
  36. package/src/primitives/app_manifest/comptime_scene.zig +341 -0
  37. package/src/primitives/app_manifest/root.zig +13 -0
  38. package/src/primitives/app_manifest/types.zig +14 -0
  39. package/src/primitives/app_manifest/validation.zig +18 -0
  40. package/src/primitives/app_manifest/web_layer.zig +366 -0
  41. package/src/primitives/canvas/commands.zig +14 -7
  42. package/src/primitives/canvas/lazy_tls.zig +73 -0
  43. package/src/primitives/canvas/render_generic_resources.zig +22 -15
  44. package/src/primitives/canvas/root.zig +6 -0
  45. package/src/primitives/canvas/tests.zig +1 -0
  46. package/src/primitives/canvas/text_atlas.zig +40 -32
  47. package/src/primitives/canvas/text_layout_cache.zig +29 -22
  48. package/src/primitives/canvas/text_measure_cache.zig +56 -41
  49. package/src/primitives/canvas/text_spans.zig +39 -26
  50. package/src/primitives/canvas/tokens.zig +54 -0
  51. package/src/primitives/canvas/ui.zig +125 -0
  52. package/src/primitives/canvas/ui_markup.zig +22 -3
  53. package/src/primitives/canvas/ui_markup_compiled.zig +97 -7
  54. package/src/primitives/canvas/ui_markup_compiled_tests.zig +275 -0
  55. package/src/primitives/canvas/ui_markup_contract.zig +68 -14
  56. package/src/primitives/canvas/ui_markup_contract_tests.zig +257 -2
  57. package/src/primitives/canvas/ui_markup_reflect.zig +214 -0
  58. package/src/primitives/canvas/ui_markup_view.zig +105 -1
  59. package/src/primitives/canvas/ui_markup_view_tests.zig +336 -0
  60. package/src/primitives/canvas/ui_schema.zig +8 -0
  61. package/src/primitives/canvas/ui_schema_tests.zig +5 -4
  62. package/src/primitives/canvas/widget_invalidation.zig +14 -7
  63. package/src/primitives/canvas/widget_render.zig +25 -15
  64. package/src/primitives/canvas/widget_render_controls.zig +15 -9
  65. package/src/primitives/canvas/widget_runtime_tests.zig +44 -0
  66. package/src/root.zig +7 -0
  67. package/src/runtime/api.zig +7 -0
  68. package/src/runtime/bridge_responses.zig +2 -0
  69. package/src/runtime/builtin_bridge.zig +6 -0
  70. package/src/runtime/canvas_frame.zig +57 -36
  71. package/src/runtime/canvas_images.zig +9 -3
  72. package/src/runtime/canvas_widget_control_tests.zig +5 -6
  73. package/src/runtime/canvas_widget_runtime.zig +7 -4
  74. package/src/runtime/effects.zig +490 -2
  75. package/src/runtime/effects_host_tests.zig +594 -0
  76. package/src/runtime/flow.zig +8 -0
  77. package/src/runtime/platform_bridge_tests.zig +1 -0
  78. package/src/runtime/root.zig +18 -0
  79. package/src/runtime/session_replay.zig +7 -1
  80. package/src/runtime/session_tests.zig +35 -8
  81. package/src/runtime/tests.zig +2 -0
  82. package/src/runtime/ts_core_host.zig +1505 -0
  83. package/src/runtime/ts_core_host_tests.zig +1408 -0
  84. package/src/runtime/ts_ui_app.zig +469 -0
  85. package/src/runtime/ui_app.zig +58 -0
  86. package/src/runtime/view_canvas.zig +24 -17
  87. package/src/runtime/view_widget_tree.zig +2 -2
  88. package/src/runtime/web_layer_gate_tests.zig +242 -0
  89. package/src/runtime/window_storage.zig +5 -0
  90. package/src/runtime/window_view_runtime.zig +1 -0
  91. package/src/tooling/buildgraph.zig +7 -1
  92. package/src/tooling/codesign.zig +212 -105
  93. package/src/tooling/doctor.zig +78 -0
  94. package/src/tooling/manifest.zig +314 -1
  95. package/src/tooling/package.zig +722 -18
  96. package/src/tooling/raw_manifest.zig +16 -0
  97. package/src/tooling/root.zig +1 -0
  98. package/src/tooling/templates.zig +911 -88
  99. package/src/tooling/ts_core.zig +486 -0
  100. package/src/tooling/verbs.zig +22 -0
@@ -0,0 +1,1505 @@
1
+ //! The native host consumer for transpiled app cores: bridges the
2
+ //! versioned command/subscription wire format a transpiled core emits
3
+ //! (`packages/core/rt/rt.zig`, `cmd_format_version` 2) onto the
4
+ //! real effect engine (`effects.zig`). The transpiler's output is a
5
+ //! pure Model/Msg/update core whose effects are INERT BYTES — this
6
+ //! module is the one place those bytes become engine calls, so the
7
+ //! entire existing effects machinery (executors, keyed slots, the
8
+ //! completion queue, the session journal, replay) carries transpiled
9
+ //! cores without a parallel engine.
10
+ //!
11
+ //! `TsCoreHost(core)` is comptime-generic over the emitted core module
12
+ //! and expects the emitted ABI:
13
+ //!
14
+ //! core.rt the core's rt kernel: `frameAlloc`,
15
+ //! `frameReset`, `resetAll`
16
+ //! core.Model the committed model struct
17
+ //! core.Msg the app Msg `union(enum)` (wire tags are the
18
+ //! arms' declaration-order indices)
19
+ //! core.initialModel() `*const Model`, or `InitResult{ model, cmd }`
20
+ //! for a boot command
21
+ //! core.update(m, msg) `*const Model`, or `UpdateResult{ model, cmd }`
22
+ //! core.commitModelRoot the frame-end commit walker
23
+ //! core.subscriptions optional: `fn (*const Model) []const u8`
24
+ //!
25
+ //! Like the rt kernel it drives, a host instance is container-level
26
+ //! state — the v1 contract is ONE LIVE APP PER CORE MODULE: two apps
27
+ //! over the same emitted core in one process would share a committed
28
+ //! root and one set of bridge tables. Two DIFFERENT core modules
29
+ //! coexist fine (each staged core carries its own rt.zig module
30
+ //! instance, so kernels never alias; distinct core types get distinct
31
+ //! hosts) — the e2e suite drives two live cores side by side to pin
32
+ //! exactly that.
33
+ //!
34
+ //! THE DISPATCH CYCLE — every Msg runs update → commit → command walk →
35
+ //! subscription reconcile → frame reset, in that order, because the
36
+ //! command and subscription bytes are frame-arena resident and must be
37
+ //! consumed before the reset. Wire records map onto the engine as:
38
+ //!
39
+ //! persist -> `fx.hostSend("core.persist", "")` — the host-
40
+ //! snapshot verb is a named host service like any
41
+ //! other; hosts that implement persistence bind it.
42
+ //! now -> `fx.wallMs()` (the journaled clock read) captured
43
+ //! during the walk; the named arm dispatches with that
44
+ //! time SYNCHRONOUSLY — immediately after the issuing
45
+ //! cycle completes, depth-first, before control
46
+ //! returns to the drain. This mirrors `fx.wallMs`'s
47
+ //! same-dispatch semantics for Zig cores and replays
48
+ //! deterministically through the `.clock` journal.
49
+ //! host -> `fx.hostSend(name, args)` — fire-and-forget; the
50
+ //! payload is the record's own arg block (`argc` f64
51
+ //! little-endian values, no count byte), decoded by
52
+ //! the named service per its build-time contract.
53
+ //! host_bytes -> `fx.hostSend(name, payload)` — fire-and-forget.
54
+ //! request -> `fx.hostRequest` with a bridge-assigned engine key
55
+ //! (`request_key_base` + table index, deterministic in
56
+ //! issue order). Completion routes the ok/err arm with
57
+ //! the result bytes; re-issuing a live wire key
58
+ //! replaces the pending request (the engine drops the
59
+ //! old result silently) and `cancel` drops it.
60
+ //! read_file -> `fx.readFile`; the terminal routes the ok arm with
61
+ //! the content bytes, or the err arm with the outcome
62
+ //! name as bytes ("not_found", "io_failed",
63
+ //! "truncated", "rejected").
64
+ //! write_file -> `fx.writeFile`; the ok arm carries no payload (a
65
+ //! void Msg arm), the err arm the outcome name.
66
+ //! fetch -> `fx.fetch` (buffered); an `.ok` un-truncated
67
+ //! response routes the ok arm as a two-field record —
68
+ //! the number field gets the real HTTP status (non-2xx
69
+ //! included), the bytes field the whole body, matched
70
+ //! by FIELD TYPE, so arm field names are the app's.
71
+ //! Every other outcome routes the err arm with the
72
+ //! outcome name; a truncated body routes err
73
+ //! ("truncated") rather than passing a silently cut
74
+ //! body as ok. Wire timeout 0 means the engine
75
+ //! default.
76
+ //! clip_write -> `fx.writeClipboard` fire-and-forget (`on_result`
77
+ //! null): a refused or over-bound write is dropped by
78
+ //! design — there is no route to report on. Engine
79
+ //! keys rotate through `clip_write_key_base` +
80
+ //! issue counter so back-to-back writes never collide.
81
+ //! clip_read -> `fx.readClipboard`; ok arm gets the text bytes,
82
+ //! err arm the outcome name ("failed", "rejected").
83
+ //! delay -> `fx.startTimer` (`.one_shot`) in its own slot table
84
+ //! (`delay_key_base` + index). Fires once, dispatching
85
+ //! the named arm with the fire time in fractional ms;
86
+ //! re-issuing a live delay key re-arms the same slot
87
+ //! from now (the debounce discipline) and `cancel`
88
+ //! drops it silently (a cancelled delay just never
89
+ //! fires).
90
+ //! spawn -> `fx.spawn` through the STREAM table (`spawn_key_base`
91
+ //! + index) — the one NON-RETIRING entry kind: unlike a
92
+ //! named op, whose entry retires on its first (only)
93
+ //! terminal, a stream entry stays live across
94
+ //! dispatches while `.lines`-mode stdout lines route
95
+ //! the line arm (line tag 0xFF = no line routing), and
96
+ //! retires only when the ONE exit terminal delivers —
97
+ //! a clean `.exited` end routes the exit arm (line
98
+ //! mode: the code as its single number payload;
99
+ //! collect mode: a code/output two-field record
100
+ //! matched by field TYPE, exactly the fetch record
101
+ //! mechanism), every other end (`signaled`,
102
+ //! `cancelled`, `rejected`, `spawn_failed`, and a
103
+ //! collect stdout over the engine bound, reason
104
+ //! "truncated") routes the err arm with the reason
105
+ //! bytes. Line/drop truncation flags are not surfaced
106
+ //! in v1: an over-bound line arrives cut to the
107
+ //! engine's 4 KiB line bound.
108
+ //! audio_play -> `fx.playAudio` on the bridge's single audio entry;
109
+ //! a URL record carrying no cache path plays under the
110
+ //! engine's conventional content-addressed cache path
111
+ //! when the wiring configured a caches directory
112
+ //! (`setAudioCacheDir` / `TsUiApp`'s `audio_cache_dir`)
113
+ //! — derived bridge-side from the URL alone, so update
114
+ //! stays pure and replay re-derives identically. The
115
+ //! entry itself is `audio_key_base` (the engine has
116
+ //! ONE player, so the bridge holds one stream),
117
+ //! non-retiring the spawn way, keyed by the wire key:
118
+ //! every `EffectAudio` event (loaded/position/
119
+ //! completed/failed/rejected/spectrum) routes the
120
+ //! event arm — a six-field record built by field NAME
121
+ //! (state/positionMs/durationMs/playing/buffering/
122
+ //! bands; `state`'s enum members are matched by member
123
+ //! name, so the app's declaration order is free) —
124
+ //! until audio_ctl `stop` (or a replacing audio_play,
125
+ //! which re-keys and re-routes the same entry) closes
126
+ //! it. `completed`/`failed`/`rejected` do NOT retire
127
+ //! the entry: the platform may still speak (soundboard
128
+ //! starts the next track from `completed`), and stop
129
+ //! is the explicit close.
130
+ //! audio_ctl -> the engine's control verbs (`fx.pauseAudio`/
131
+ //! `resumeAudio`/`stopAudio`/`seekAudio`/
132
+ //! `setAudioVolume`), gated by the wire key: a verb
133
+ //! whose key does not name the open stream is a no-op
134
+ //! (the playback it aimed at is gone). `stop` also
135
+ //! retires the bridge entry — no events for that key
136
+ //! after it.
137
+ //! cancel -> by wire key, first match wins in this order: the
138
+ //! request table (`fx.cancelHostRequest`, silent), the
139
+ //! named-op table (the entry is marked dropped and
140
+ //! `fx.cancel` issued — the engine's `.cancelled`
141
+ //! terminal retires the entry and the bridge swallows
142
+ //! it: SILENT, no arm dispatches), the stream table
143
+ //! (`fx.cancel` — the child dies and its exit routes
144
+ //! the err arm with "cancelled"; killing a process IS
145
+ //! an observable event, so spawn's cancel stays loud),
146
+ //! the delay table (`fx.cancelTimer`, silent). The
147
+ //! audio stream is not cancel's to end — audio_ctl
148
+ //! `stop` is its close.
149
+ //!
150
+ //! THE KEYED-EFFECT DISCIPLINE is ONE rule across request, read_file,
151
+ //! write_file, fetch, clip_read, and delay: a keyed effect REPLACES its
152
+ //! live predecessor (the superseded effect's result is dropped — no
153
+ //! message), and `cancel` drops it silently (no terminal arm dispatch).
154
+ //! For the named ops the bridge implements the drop by marking the
155
+ //! superseded entry dropped and cancelling its engine call; the
156
+ //! engine's `.cancelled` terminal retires the entry and its Msg is
157
+ //! swallowed before dispatch. The ONE exception is a live `Cmd.spawn`
158
+ //! key: a duplicate REJECTS the new spawn — its err arm dispatches with
159
+ //! "rejected" right after the issuing cycle (the same post-cycle
160
+ //! boundary `now` dispatches use) — because a running subprocess is
161
+ //! never killed implicitly; cancel it first. And spawn's explicit
162
+ //! cancel stays loud (err arm "cancelled"), because killing a process
163
+ //! is an observable event.
164
+ //! Sub timer -> `fx.startTimer` (repeating) with a fixed slot table
165
+ //! reconciled by wire key: a new key arms the first
166
+ //! free slot (slot order — deterministic, never hash
167
+ //! order), a changed interval re-arms the same slot, a
168
+ //! tag-only change re-routes without re-arming, and a
169
+ //! key absent from the set cancels. Each fire
170
+ //! dispatches the named arm with the fire time in
171
+ //! fractional milliseconds.
172
+ //!
173
+ //! THE RESULT-ORDERING CONTRACT: routed results and timer fires are
174
+ //! ordinary engine completions — they queue in completion order and
175
+ //! dispatch when the host drains (`Effects.takeMsg`, i.e. UiApp's
176
+ //! `.effects_wake` and presented-frame drains), exactly like Zig-core
177
+ //! fx results. The bridge adds no scheduler of its own; the one
178
+ //! deliberate exception is `now` (above), which is synchronous the way
179
+ //! `fx.wallMs` is.
180
+ //!
181
+ //! Result payload lifetime: the engine's result bytes are drain
182
+ //! scratch, but a routed result's bytes become a Msg payload the core
183
+ //! may store in the model — so the Msg constructors copy them into the
184
+ //! core's frame arena first, where the commit walkers classify them as
185
+ //! frame-resident and copy whatever the model keeps into the heap.
186
+ //!
187
+ //! Malformed wire bytes are teaching panics, not error codes: the only
188
+ //! producer is the transpiler's own rt builders, so a bad record is a
189
+ //! build-pipeline bug the app author must see immediately.
190
+
191
+ const std = @import("std");
192
+ const runtime_effects = @import("effects.zig");
193
+
194
+ /// Engine-key namespace for bridge-issued host requests: `base + table
195
+ /// index`. High bits spell "TSRQ" so a bridge key is recognizable in
196
+ /// journals and logs and never collides with hand-chosen Zig-core keys.
197
+ pub const request_key_base: u64 = 0x5453_5251_0000_0000;
198
+
199
+ /// Engine-key namespace for bridge-reconciled subscription timers
200
+ /// ("TSTI"). Timer keys are their own engine namespace already; the
201
+ /// base keeps journal entries self-describing.
202
+ pub const timer_key_base: u64 = 0x5453_5449_0000_0000;
203
+
204
+ /// Engine-key namespace for bridge-issued named engine ops — read_file
205
+ /// / write_file / fetch / clip_read ("TSFX"): `base + table index`,
206
+ /// deterministic in issue order, sharing the engine's effect slots
207
+ /// with `request_key_base` keys without ever colliding.
208
+ pub const effect_key_base: u64 = 0x5453_4658_0000_0000;
209
+
210
+ /// Engine-key namespace for one-shot delays ("TSDL"), in the engine's
211
+ /// timer key space alongside `timer_key_base`.
212
+ pub const delay_key_base: u64 = 0x5453_444C_0000_0000;
213
+
214
+ /// Engine-key namespace for fire-and-forget clipboard writes ("TSCW"):
215
+ /// `base + issue counter` (wrapping u32), so back-to-back writes never
216
+ /// collide on an active key.
217
+ pub const clip_write_key_base: u64 = 0x5453_4357_0000_0000;
218
+
219
+ /// Engine-key namespace for spawn STREAMS ("TSSP"): `base + table
220
+ /// index`, deterministic in issue order. Spawns share the engine's
221
+ /// `max_effects` slots with the named ops without ever colliding on a
222
+ /// key.
223
+ pub const spawn_key_base: u64 = 0x5453_5350_0000_0000;
224
+
225
+ /// The engine key of the bridge's single audio playback channel
226
+ /// ("TSAU"). Audio keys are their own engine namespace and one player
227
+ /// is the whole surface, so one constant key is the honest shape.
228
+ pub const audio_key_base: u64 = 0x5453_4155_0000_0000;
229
+
230
+ /// The spawn wire record's "no line routing" tag sentinel (mirrors
231
+ /// rt.zig's `spawn_no_line_tag`).
232
+ pub const spawn_no_line_tag: u8 = 0xFF;
233
+
234
+ /// Longest wire key (request or timer) the format can carry: the key
235
+ /// length field is one byte.
236
+ pub const max_wire_key_bytes: usize = 255;
237
+
238
+ /// Bound on `Cmd.now`-chained dispatches from one external dispatch
239
+ /// (an update whose `now` arm requests another `now`, transitively).
240
+ /// Sized like `max_effect_replay_clock_entries`: more clock reads per
241
+ /// drain window than this is a runaway update loop, not an app shape.
242
+ pub const max_now_chain: usize = 64;
243
+
244
+ /// Most `now` records one command value may carry.
245
+ pub const max_nows_per_cmd: usize = 16;
246
+
247
+ pub fn TsCoreHost(comptime core: type) type {
248
+ return struct {
249
+ pub const Model = core.Model;
250
+ pub const Msg = core.Msg;
251
+ pub const Fx = runtime_effects.Effects(Msg);
252
+
253
+ const msg_arms = @typeInfo(Msg).@"union".fields;
254
+
255
+ const update_returns_cmd = @typeInfo(@TypeOf(core.update)).@"fn".return_type.? != *const Model;
256
+ const init_returns_cmd = @typeInfo(@TypeOf(core.initialModel)).@"fn".return_type.? != *const Model;
257
+ const has_subscriptions = @hasDecl(core, "subscriptions");
258
+
259
+ /// One in-flight routed request: the wire key names it for
260
+ /// replace/cancel, the tags route its terminal, and the table
261
+ /// index IS the engine key (minus `request_key_base`). Entries
262
+ /// retire when their terminal delivers. Sized to the engine's
263
+ /// slot table — the engine cannot hold more in flight anyway.
264
+ const RequestEntry = struct {
265
+ used: bool = false,
266
+ key_len: usize = 0,
267
+ key: [max_wire_key_bytes]u8 = undefined,
268
+ ok_tag: u8 = 0,
269
+ err_tag: u8 = 0,
270
+
271
+ fn wireKey(entry: *const RequestEntry) []const u8 {
272
+ return entry.key[0..entry.key_len];
273
+ }
274
+ };
275
+
276
+ /// One reconciled subscription timer. `every_ms` keeps the wire
277
+ /// value (f64) so interval-change detection compares exactly
278
+ /// what the app declared. Key and tag stay sticky after cancel
279
+ /// (`used = false`): a fire already queued when its timer was
280
+ /// cancelled still routes to the arm it was armed with.
281
+ const TimerEntry = struct {
282
+ used: bool = false,
283
+ key_len: usize = 0,
284
+ key: [max_wire_key_bytes]u8 = undefined,
285
+ every_ms: f64 = 0,
286
+ tag: u8 = 0,
287
+
288
+ fn wireKey(entry: *const TimerEntry) []const u8 {
289
+ return entry.key[0..entry.key_len];
290
+ }
291
+ };
292
+
293
+ /// One in-flight named engine op (read_file / write_file /
294
+ /// fetch / clip_read): same lifecycle as `RequestEntry` — the
295
+ /// table index IS the engine key (minus `effect_key_base`),
296
+ /// entries retire when their terminal delivers. A `dropped`
297
+ /// entry (superseded by a key reuse, or wire-cancelled) stays
298
+ /// in the table so its engine `.cancelled` terminal can retire
299
+ /// it, but its wire key is no longer live and its terminal is
300
+ /// SWALLOWED — the one-rule discipline's silent drop. Sized to
301
+ /// the engine's shared effect slots.
302
+ const EffectEntry = struct {
303
+ used: bool = false,
304
+ dropped: bool = false,
305
+ key_len: usize = 0,
306
+ key: [max_wire_key_bytes]u8 = undefined,
307
+ ok_tag: u8 = 0,
308
+ err_tag: u8 = 0,
309
+
310
+ fn wireKey(entry: *const EffectEntry) []const u8 {
311
+ return entry.key[0..entry.key_len];
312
+ }
313
+ };
314
+
315
+ /// One armed one-shot delay. Retires on fire or cancel;
316
+ /// re-issuing a live wire key re-arms the same slot (the engine
317
+ /// timer replaces in place under the same engine key).
318
+ const DelayEntry = struct {
319
+ used: bool = false,
320
+ key_len: usize = 0,
321
+ key: [max_wire_key_bytes]u8 = undefined,
322
+ tag: u8 = 0,
323
+
324
+ fn wireKey(entry: *const DelayEntry) []const u8 {
325
+ return entry.key[0..entry.key_len];
326
+ }
327
+ };
328
+
329
+ /// One live spawn STREAM — the non-retiring entry kind: line
330
+ /// results route through it repeatedly across dispatches, and
331
+ /// only the exit terminal (or the engine's `.cancelled` end
332
+ /// after a wire cancel) retires it. The table index IS the
333
+ /// engine key (minus `spawn_key_base`), deterministic in issue
334
+ /// order like every bridge table.
335
+ const StreamEntry = struct {
336
+ used: bool = false,
337
+ key_len: usize = 0,
338
+ key: [max_wire_key_bytes]u8 = undefined,
339
+ /// `spawn_no_line_tag` = lines dispatch nothing.
340
+ line_tag: u8 = spawn_no_line_tag,
341
+ exit_tag: u8 = 0,
342
+ err_tag: u8 = 0,
343
+ collect: bool = false,
344
+
345
+ fn wireKey(entry: *const StreamEntry) []const u8 {
346
+ return entry.key[0..entry.key_len];
347
+ }
348
+ };
349
+
350
+ /// The single audio stream entry (one player is the whole
351
+ /// engine surface). Non-retiring: audio_ctl `stop` closes it, a
352
+ /// new audio_play re-keys and re-routes it in place.
353
+ const AudioEntry = struct {
354
+ used: bool = false,
355
+ key_len: usize = 0,
356
+ key: [max_wire_key_bytes]u8 = undefined,
357
+ event_tag: u8 = 0,
358
+
359
+ fn wireKey(entry: *const AudioEntry) []const u8 {
360
+ return entry.key[0..entry.key_len];
361
+ }
362
+ };
363
+
364
+ var model_root: *const Model = undefined;
365
+ /// The platform caches directory for URL audio sources, set by
366
+ /// the wiring (`TsUiApp`'s `audio_cache_dir`, or `setAudioCacheDir`
367
+ /// directly) once at boot — never read from the environment
368
+ /// inside a dispatch, so replay's deterministic-init contract
369
+ /// holds. Empty = no derivation (stream-only playback for URL
370
+ /// records that carry no cache path of their own).
371
+ var audio_cache_dir_len: usize = 0;
372
+ var audio_cache_dir_buf: [runtime_effects.max_effect_audio_path_bytes]u8 = undefined;
373
+ var audio_cache_path_buf: [runtime_effects.max_effect_audio_path_bytes]u8 = undefined;
374
+ var requests: [runtime_effects.max_effects]RequestEntry = @splat(.{});
375
+ var timers: [runtime_effects.max_effect_timers]TimerEntry = @splat(.{});
376
+ var effects_table: [runtime_effects.max_effects]EffectEntry = @splat(.{});
377
+ var delays: [runtime_effects.max_effect_timers]DelayEntry = @splat(.{});
378
+ var streams: [runtime_effects.max_effects]StreamEntry = @splat(.{});
379
+ var audio_entry: AudioEntry = .{};
380
+ var clip_write_counter: u32 = 0;
381
+ /// Set by a result callback whose entry was dropped (replaced
382
+ /// or wire-cancelled): the terminal is journal-visible but must
383
+ /// not reach the core — `dispatch` consumes the flag and skips
384
+ /// exactly the Msg the callback just built. Safe because the
385
+ /// callback runs inside `fx.takeMsg` and the very next bridge
386
+ /// call is `dispatch` with that Msg (both drain paths —
387
+ /// `TsCoreHost.drain` and the `TsUiApp` update_fx seam — keep
388
+ /// that adjacency).
389
+ var swallow_next_dispatch: bool = false;
390
+
391
+ /// A `now` record captured during the command walk, dispatched
392
+ /// after the issuing cycle's frame reset.
393
+ const PendingNow = struct { tag: u8, ms: i64 };
394
+
395
+ /// A spawn issue the bridge itself refused (duplicate live wire
396
+ /// key — the one reject in the keyed-effect discipline),
397
+ /// dispatched as the spawn's err arm with "rejected" after the
398
+ /// issuing cycle's frame reset, at the same boundary `now`
399
+ /// dispatches use.
400
+ const max_rejects_per_cmd: usize = runtime_effects.max_effects;
401
+
402
+ /// Install the core: reset the kernel and the bridge tables
403
+ /// (deterministic re-init — the seam session replay relies on),
404
+ /// run the core's `initialModel`, commit it, and perform the
405
+ /// boot command and initial subscriptions. Wire this to
406
+ /// `UiApp.Options.init_fx` so boot effects fire on the
407
+ /// installing frame, before the first view build — the same
408
+ /// init semantics Zig cores get. (The `TsUiApp` adapter splits
409
+ /// this into `boot` at construction and `performBoot` at
410
+ /// install, so the committed boot model exists before the
411
+ /// effects channel does.)
412
+ pub fn init(fx: *Fx) void {
413
+ boot();
414
+ performBoot(fx);
415
+ }
416
+
417
+ /// The pre-effects half of `init`: reset the kernel and bridge
418
+ /// tables and commit the boot model, performing NO effects. The
419
+ /// committed model is readable immediately (`model()`); the
420
+ /// boot command and initial subscriptions run in `performBoot`,
421
+ /// on the installing frame.
422
+ pub fn boot() void {
423
+ core.rt.resetAll();
424
+ requests = @splat(.{});
425
+ timers = @splat(.{});
426
+ effects_table = @splat(.{});
427
+ delays = @splat(.{});
428
+ streams = @splat(.{});
429
+ audio_entry = .{};
430
+ clip_write_counter = 0;
431
+ audio_cache_dir_len = 0;
432
+ swallow_next_dispatch = false;
433
+ const initial = core.initialModel();
434
+ model_root = core.commitModelRoot(if (comptime init_returns_cmd) initial.model else initial);
435
+ core.rt.frameReset();
436
+ }
437
+
438
+ /// The effects half of `init`: perform the boot command and
439
+ /// reconcile the initial subscriptions against the committed
440
+ /// boot model. The command bytes are re-derived by re-running
441
+ /// the PURE `initialModel` (they were frame-resident and did not
442
+ /// survive `boot`'s frame reset; the duplicate model value is
443
+ /// frame-transient garbage) — purity is the transpiled subset's
444
+ /// own guarantee, so the bytes are identical by construction.
445
+ pub fn performBoot(fx: *Fx) void {
446
+ if (comptime init_returns_cmd) {
447
+ const again = core.initialModel();
448
+ finishCycle(fx, again.cmd, 0);
449
+ } else {
450
+ finishCycle(fx, "", 0);
451
+ }
452
+ }
453
+
454
+ /// The committed model root (valid until the next dispatch).
455
+ pub fn model() *const Model {
456
+ return model_root;
457
+ }
458
+
459
+ /// Configure the caches directory audio-cache derivation uses.
460
+ /// Call after `boot` (which clears it) and before any dispatch —
461
+ /// wiring-time configuration, exactly like soundboard's boot-time
462
+ /// `app_dirs` resolution: no env read ever happens inside update.
463
+ pub fn setAudioCacheDir(dir: []const u8) void {
464
+ if (dir.len > audio_cache_dir_buf.len) {
465
+ @panic("ts core host: the audio cache directory path is longer than the engine's audio path bound");
466
+ }
467
+ @memcpy(audio_cache_dir_buf[0..dir.len], dir);
468
+ audio_cache_dir_len = dir.len;
469
+ }
470
+
471
+ fn audioCacheDir() []const u8 {
472
+ return audio_cache_dir_buf[0..audio_cache_dir_len];
473
+ }
474
+
475
+ /// The cache path an audio_play record plays under: the record's
476
+ /// own when it carries one; otherwise, for URL sources with a
477
+ /// configured caches directory, the engine's conventional
478
+ /// content-addressed path (`<cache_dir>/audio/<sha256[..16]>.<ext>`
479
+ /// via `audioCachePath`) — derived HERE, outside the core, so
480
+ /// update stays pure and the derivation is a fixed function of
481
+ /// the wire bytes (replay re-derives identically). No directory
482
+ /// configured, or a path over the buffer bound, degrades to ""
483
+ /// (stream-only, the engine's own no-cache mode).
484
+ fn effectiveAudioCachePath(cache_path: []const u8, url: []const u8) []const u8 {
485
+ if (cache_path.len > 0 or url.len == 0 or audio_cache_dir_len == 0) return cache_path;
486
+ return runtime_effects.audioCachePath(&audio_cache_path_buf, audioCacheDir(), url) catch "";
487
+ }
488
+
489
+ /// One full dispatch cycle for `msg`. The `TsUiApp` adapter
490
+ /// wires this to `UiApp.Options.update_fx` (refreshing the
491
+ /// app-held root from `model()` afterwards) so host events and
492
+ /// drained effect results run the transpiled core through the
493
+ /// same path Zig cores use. A Msg flagged by its own result
494
+ /// callback as a dropped entry's terminal is swallowed here —
495
+ /// the silent drop the keyed-effect discipline promises.
496
+ pub fn dispatch(fx: *Fx, msg: Msg) void {
497
+ if (swallow_next_dispatch) {
498
+ swallow_next_dispatch = false;
499
+ return;
500
+ }
501
+ dispatchDepth(fx, msg, 0);
502
+ }
503
+
504
+ /// Drain every queued effect completion into the core — the
505
+ /// bridge-shaped mirror of `UiApp.drainEffects`' loop. Hosts
506
+ /// that embed the core without a UiApp call this on wake/frame.
507
+ pub fn drain(fx: *Fx) void {
508
+ while (fx.takeMsg()) |msg| dispatch(fx, msg);
509
+ }
510
+
511
+ fn dispatchDepth(fx: *Fx, msg: Msg, depth: usize) void {
512
+ if (depth >= max_now_chain) {
513
+ @panic("ts core host: more than 64 chained Cmd.now dispatches from one event - update is requesting timestamps in a loop");
514
+ }
515
+ if (comptime update_returns_cmd) {
516
+ const result = core.update(model_root, msg);
517
+ model_root = core.commitModelRoot(result.model);
518
+ finishCycle(fx, result.cmd, depth);
519
+ } else {
520
+ model_root = core.commitModelRoot(core.update(model_root, msg));
521
+ finishCycle(fx, "", depth);
522
+ }
523
+ }
524
+
525
+ /// The tail of every cycle: walk the command bytes, reconcile
526
+ /// subscriptions against the NEW committed model, reset the
527
+ /// frame arena, then run the cycle's `now` dispatches and
528
+ /// bridge-refused spawn rejections (each a full cycle of its
529
+ /// own, on the fresh frame — nows first, rejections after, in
530
+ /// record order; deterministic under record and replay alike).
531
+ fn finishCycle(fx: *Fx, cmd: []const u8, depth: usize) void {
532
+ var nows: [max_nows_per_cmd]PendingNow = undefined;
533
+ var now_count: usize = 0;
534
+ var rejects: [max_rejects_per_cmd]u8 = undefined;
535
+ var reject_count: usize = 0;
536
+ runCmd(fx, cmd, &nows, &now_count, &rejects, &reject_count);
537
+ reconcileTimers(fx);
538
+ core.rt.frameReset();
539
+ for (nows[0..now_count]) |pending| {
540
+ dispatchDepth(fx, msgFromTagNumber(pending.tag, @floatFromInt(pending.ms)), depth + 1);
541
+ }
542
+ for (rejects[0..reject_count]) |err_tag| {
543
+ dispatchDepth(fx, msgFromTagBytes(err_tag, "rejected"), depth + 1);
544
+ }
545
+ }
546
+
547
+ // ------------------------------------------------- command walk
548
+
549
+ /// Walk one command value (v2 wire format; batch is plain
550
+ /// concatenation, the empty slice is `Cmd.none`).
551
+ fn runCmd(
552
+ fx: *Fx,
553
+ cmd: []const u8,
554
+ nows: *[max_nows_per_cmd]PendingNow,
555
+ now_count: *usize,
556
+ rejects: *[max_rejects_per_cmd]u8,
557
+ reject_count: *usize,
558
+ ) void {
559
+ var at: usize = 0;
560
+ while (at < cmd.len) {
561
+ const op = cmd[at];
562
+ at += 1;
563
+ switch (op) {
564
+ // persist [op]
565
+ 0x01 => fx.hostSend("core.persist", ""),
566
+ // now [op][msg_tag]
567
+ 0x02 => {
568
+ const tag = takeByte(cmd, &at);
569
+ if (now_count.* >= max_nows_per_cmd) {
570
+ @panic("ts core host: one command value carries more than 16 Cmd.now records");
571
+ }
572
+ // The journaled clock read (replay pops the same
573
+ // value), captured in record order.
574
+ nows[now_count.*] = .{ .tag = tag, .ms = fx.wallMs() };
575
+ now_count.* += 1;
576
+ },
577
+ // host [op][name_len][name][argc][argc * f64 LE]
578
+ 0x03 => {
579
+ const name = takeShortBytes(cmd, &at);
580
+ const argc: usize = takeByte(cmd, &at);
581
+ const args = takeBytes(cmd, &at, argc * 8);
582
+ fx.hostSend(name, args);
583
+ },
584
+ // host_bytes [op][name_len][name][len u32 LE][payload]
585
+ 0x04 => {
586
+ const name = takeShortBytes(cmd, &at);
587
+ const payload = takeLongBytes(cmd, &at);
588
+ fx.hostSend(name, payload);
589
+ },
590
+ // request [op][name_len][name][key_len][key]
591
+ // [ok_tag][err_tag][len u32 LE][payload]
592
+ 0x05 => {
593
+ const name = takeShortBytes(cmd, &at);
594
+ const key = takeShortBytes(cmd, &at);
595
+ const ok_tag = takeByte(cmd, &at);
596
+ const err_tag = takeByte(cmd, &at);
597
+ const payload = takeLongBytes(cmd, &at);
598
+ issueRequest(fx, name, key, ok_tag, err_tag, payload);
599
+ },
600
+ // cancel [op][key_len][key]
601
+ 0x06 => {
602
+ const key = takeShortBytes(cmd, &at);
603
+ cancelWireKey(fx, key);
604
+ },
605
+ // read_file [op][key_len][key][ok][err][path_len u32 LE][path]
606
+ 0x07 => {
607
+ const head = takeRoutedHead(cmd, &at);
608
+ const file_path = takeLongBytes(cmd, &at);
609
+ fx.readFile(.{
610
+ .key = effect_key_base + allocEffectEntry(fx, head),
611
+ .path = file_path,
612
+ .on_result = fileResultMsg,
613
+ });
614
+ },
615
+ // write_file [op][key_len][key][ok][err]
616
+ // [path_len u32 LE][path][bytes_len u32 LE][bytes]
617
+ 0x08 => {
618
+ const head = takeRoutedHead(cmd, &at);
619
+ const file_path = takeLongBytes(cmd, &at);
620
+ const bytes = takeLongBytes(cmd, &at);
621
+ fx.writeFile(.{
622
+ .key = effect_key_base + allocEffectEntry(fx, head),
623
+ .path = file_path,
624
+ .bytes = bytes,
625
+ .on_result = fileResultMsg,
626
+ });
627
+ },
628
+ // fetch [op][key_len][key][ok][err][method u8][timeout u32 LE]
629
+ // [url_len u32 LE][url][header_count u8]
630
+ // ([name_len u8][name][value_len u32 LE][value])*
631
+ // [body_len u32 LE][body]
632
+ 0x09 => {
633
+ const head = takeRoutedHead(cmd, &at);
634
+ const method = fetchMethod(takeByte(cmd, &at));
635
+ const timeout_bytes = takeBytes(cmd, &at, 4);
636
+ const timeout_ms = std.mem.readInt(u32, timeout_bytes[0..4], .little);
637
+ const url = takeLongBytes(cmd, &at);
638
+ const header_count: usize = takeByte(cmd, &at);
639
+ if (header_count > runtime_effects.max_effect_fetch_headers) {
640
+ @panic("ts core host: a fetch wire record carries more headers than the engine accepts - the transpiler's own bound should have stopped this build");
641
+ }
642
+ var headers: [runtime_effects.max_effect_fetch_headers]std.http.Header = undefined;
643
+ for (0..header_count) |i| {
644
+ const name = takeShortBytes(cmd, &at);
645
+ const value = takeLongBytes(cmd, &at);
646
+ headers[i] = .{ .name = name, .value = value };
647
+ }
648
+ const body = takeLongBytes(cmd, &at);
649
+ fx.fetch(.{
650
+ .key = effect_key_base + allocEffectEntry(fx, head),
651
+ .method = method,
652
+ .url = url,
653
+ .headers = headers[0..header_count],
654
+ .body = if (body.len > 0) body else null,
655
+ // Wire 0 = "the engine's default" — the record
656
+ // never bakes the default in.
657
+ .timeout_ms = if (timeout_ms == 0) runtime_effects.default_effect_fetch_timeout_ms else timeout_ms,
658
+ .on_response = fetchResultMsg,
659
+ });
660
+ },
661
+ // clip_write [op][bytes_len u32 LE][bytes]
662
+ 0x0A => {
663
+ const bytes = takeLongBytes(cmd, &at);
664
+ // Fire-and-forget: no routing, on_result stays null,
665
+ // and the rotating key keeps back-to-back writes off
666
+ // each other's active keys.
667
+ fx.writeClipboard(.{
668
+ .key = clip_write_key_base + clip_write_counter,
669
+ .text = bytes,
670
+ .on_result = null,
671
+ });
672
+ clip_write_counter +%= 1;
673
+ },
674
+ // clip_read [op][key_len][key][ok][err]
675
+ 0x0B => {
676
+ const head = takeRoutedHead(cmd, &at);
677
+ fx.readClipboard(.{
678
+ .key = effect_key_base + allocEffectEntry(fx, head),
679
+ .on_result = clipboardResultMsg,
680
+ });
681
+ },
682
+ // delay [op][key_len][key][after_ms f64 LE][msg_tag]
683
+ 0x0C => {
684
+ const key = takeShortBytes(cmd, &at);
685
+ const after_bits = takeBytes(cmd, &at, 8);
686
+ const after_ms: f64 = @bitCast(std.mem.readInt(u64, after_bits[0..8], .little));
687
+ const tag = takeByte(cmd, &at);
688
+ if (!(after_ms >= 1) or !(after_ms <= 31_536_000_000.0)) {
689
+ // Same bound as Sub.timer: the lower rejects NaN,
690
+ // the upper (one year) keeps ns conversion in range.
691
+ @panic("ts core host: Cmd.delay interval must be between 1ms and one year");
692
+ }
693
+ armDelay(fx, key, after_ms, tag);
694
+ },
695
+ // spawn [op][key_len][key][line_tag][exit_tag][err_tag]
696
+ // [mode u8][argc u8]([arg_len u32 LE][arg])*
697
+ // [stdin_len u32 LE][stdin]
698
+ 0x0D => {
699
+ const key = takeShortBytes(cmd, &at);
700
+ const line_tag = takeByte(cmd, &at);
701
+ const exit_tag = takeByte(cmd, &at);
702
+ const err_tag = takeByte(cmd, &at);
703
+ const mode = takeByte(cmd, &at);
704
+ if (mode > 1) {
705
+ @panic("ts core host: unknown spawn output mode wire value - the core and this runtime disagree on cmd_format_version");
706
+ }
707
+ const argc: usize = takeByte(cmd, &at);
708
+ if (argc == 0 or argc > runtime_effects.max_effect_argv) {
709
+ @panic("ts core host: a spawn wire record carries more argv elements than the engine accepts - the transpiler's own bound should have stopped this build");
710
+ }
711
+ var argv: [runtime_effects.max_effect_argv][]const u8 = undefined;
712
+ for (0..argc) |i| argv[i] = takeLongBytes(cmd, &at);
713
+ const stdin = takeLongBytes(cmd, &at);
714
+ 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);
715
+ },
716
+ // audio_play [op][key_len][key][event_tag]
717
+ // [path_len u32 LE][path][url_len u32 LE][url]
718
+ // [cache_len u32 LE][cache][expected f64 LE]
719
+ 0x0E => {
720
+ const key = takeShortBytes(cmd, &at);
721
+ const event_tag = takeByte(cmd, &at);
722
+ const audio_path = takeLongBytes(cmd, &at);
723
+ const url = takeLongBytes(cmd, &at);
724
+ const cache_path = takeLongBytes(cmd, &at);
725
+ const expected_bits = takeBytes(cmd, &at, 8);
726
+ const expected: f64 = @bitCast(std.mem.readInt(u64, expected_bits[0..8], .little));
727
+ // One player is the whole surface: a new play
728
+ // re-keys and re-routes the single entry in place,
729
+ // exactly as the engine replaces its channel.
730
+ audio_entry.used = true;
731
+ audio_entry.key_len = key.len;
732
+ @memcpy(audio_entry.key[0..key.len], key);
733
+ audio_entry.event_tag = event_tag;
734
+ fx.playAudio(.{
735
+ .key = audio_key_base,
736
+ .path = audio_path,
737
+ .url = url,
738
+ .cache_path = effectiveAudioCachePath(cache_path, url),
739
+ // The wire carries the app's number; anything
740
+ // that is not a representable byte count means
741
+ // "unknown size" (0), the engine's own default.
742
+ .expected_bytes = if (expected >= 1 and expected <= 9007199254740992.0)
743
+ @intFromFloat(expected)
744
+ else
745
+ 0,
746
+ .on_event = audioEventMsg,
747
+ });
748
+ },
749
+ // audio_ctl [op][key_len][key][verb u8][value f64 LE]
750
+ 0x0F => {
751
+ const key = takeShortBytes(cmd, &at);
752
+ const verb = takeByte(cmd, &at);
753
+ const value_bits = takeBytes(cmd, &at, 8);
754
+ const value: f64 = @bitCast(std.mem.readInt(u64, value_bits[0..8], .little));
755
+ runAudioCtl(fx, key, verb, value);
756
+ },
757
+ else => @panic("ts core host: unknown command wire record - the core and this runtime disagree on cmd_format_version"),
758
+ }
759
+ }
760
+ }
761
+
762
+ /// The shared routed-op head: [key_len][key][ok_tag][err_tag].
763
+ const RoutedHead = struct { key: []const u8, ok_tag: u8, err_tag: u8 };
764
+
765
+ fn takeRoutedHead(cmd: []const u8, at: *usize) RoutedHead {
766
+ const key = takeShortBytes(cmd, at);
767
+ const ok_tag = takeByte(cmd, at);
768
+ const err_tag = takeByte(cmd, at);
769
+ return .{ .key = key, .ok_tag = ok_tag, .err_tag = err_tag };
770
+ }
771
+
772
+ fn fetchMethod(wire: u8) std.http.Method {
773
+ return switch (wire) {
774
+ 0 => .GET,
775
+ 1 => .POST,
776
+ 2 => .PUT,
777
+ 3 => .DELETE,
778
+ 4 => .PATCH,
779
+ 5 => .HEAD,
780
+ else => @panic("ts core host: unknown fetch method wire value - the core and this runtime disagree on cmd_format_version"),
781
+ };
782
+ }
783
+
784
+ /// Claim a named-op table entry. A live wire key is the keyed-
785
+ /// effect discipline's REPLACE: the in-flight predecessor is
786
+ /// dropped (marked, its engine call cancelled, its terminal
787
+ /// swallowed — no message) and the new op takes a fresh entry.
788
+ /// A full table is a panic like the request table's — it
789
+ /// mirrors the engine's slot count, which cannot hold more in
790
+ /// flight either (a dropped entry holds its slot only until
791
+ /// its `.cancelled` terminal drains).
792
+ fn allocEffectEntry(fx: *Fx, head: RoutedHead) u64 {
793
+ if (head.key.len > 0) {
794
+ if (findEffect(head.key)) |existing| dropEffectEntry(fx, existing);
795
+ }
796
+ const index = freeEffectIndex() orelse
797
+ @panic("ts core host: more than 16 named engine ops in flight - the op table mirrors the engine's max_effects slots");
798
+ const entry = &effects_table[index];
799
+ entry.used = true;
800
+ entry.dropped = false;
801
+ entry.key_len = head.key.len;
802
+ @memcpy(entry.key[0..head.key.len], head.key);
803
+ entry.ok_tag = head.ok_tag;
804
+ entry.err_tag = head.err_tag;
805
+ return index;
806
+ }
807
+
808
+ /// The silent drop shared by replace and wire cancel: the entry
809
+ /// stops being live (its key is free immediately) and its
810
+ /// engine call is cancelled — the `.cancelled` terminal retires
811
+ /// the entry through the result callback, which swallows it.
812
+ fn dropEffectEntry(fx: *Fx, index: usize) void {
813
+ effects_table[index].dropped = true;
814
+ fx.cancel(effect_key_base + index);
815
+ }
816
+
817
+ /// A dropped entry's key is dead to lookup: reissuing it is a
818
+ /// fresh effect, and cancel aimed at it finds nothing.
819
+ fn findEffect(key: []const u8) ?usize {
820
+ for (&effects_table, 0..) |*entry, index| {
821
+ if (entry.used and !entry.dropped and std.mem.eql(u8, entry.wireKey(), key)) return index;
822
+ }
823
+ return null;
824
+ }
825
+
826
+ fn freeEffectIndex() ?usize {
827
+ for (&effects_table, 0..) |*entry, index| {
828
+ if (!entry.used) return index;
829
+ }
830
+ return null;
831
+ }
832
+
833
+ /// Arm (or re-arm) a one-shot delay. A live wire key reuses its
834
+ /// slot: the engine timer replaces in place under the same
835
+ /// engine key and restarts from now — the debounce discipline.
836
+ fn armDelay(fx: *Fx, key: []const u8, after_ms: f64, tag: u8) void {
837
+ const index = blk: {
838
+ if (key.len > 0) {
839
+ if (findDelay(key)) |existing| break :blk existing;
840
+ }
841
+ break :blk freeDelayIndex() orelse
842
+ @panic("ts core host: more than 16 armed delays - the delay table mirrors the engine's max_effect_timers");
843
+ };
844
+ const entry = &delays[index];
845
+ entry.used = true;
846
+ entry.key_len = key.len;
847
+ @memcpy(entry.key[0..key.len], key);
848
+ entry.tag = tag;
849
+ fx.startTimer(.{
850
+ .key = delay_key_base + index,
851
+ .interval_ms = intervalMs(after_ms),
852
+ .mode = .one_shot,
853
+ .on_fire = delayFireMsg,
854
+ });
855
+ }
856
+
857
+ fn findDelay(key: []const u8) ?usize {
858
+ for (&delays, 0..) |*entry, index| {
859
+ if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
860
+ }
861
+ return null;
862
+ }
863
+
864
+ fn freeDelayIndex() ?usize {
865
+ for (&delays, 0..) |*entry, index| {
866
+ if (!entry.used) return index;
867
+ }
868
+ return null;
869
+ }
870
+
871
+ // ------------------------------------------------ spawn streams
872
+
873
+ const SpawnHead = struct { key: []const u8, line_tag: u8, exit_tag: u8, err_tag: u8 };
874
+
875
+ /// Open a spawn stream: claim a non-retiring stream entry (the
876
+ /// keyed-effect discipline's ONE exception — a live wire key
877
+ /// REJECTS the new spawn, because a running subprocess is never
878
+ /// killed implicitly; cancel it first) and hand the argv to the
879
+ /// engine. Everything dynamic
880
+ /// the engine refuses (argv bytes over the block bound, stdin
881
+ /// over 4 KiB, no free slot) comes back as one `.rejected` exit
882
+ /// through the stream's own err arm — never silent.
883
+ fn issueSpawn(
884
+ fx: *Fx,
885
+ head: SpawnHead,
886
+ collect: bool,
887
+ argv: []const []const u8,
888
+ stdin: []const u8,
889
+ rejects: *[max_rejects_per_cmd]u8,
890
+ reject_count: *usize,
891
+ ) void {
892
+ if (head.key.len > 0 and findStream(head.key) != null) {
893
+ if (reject_count.* >= max_rejects_per_cmd) {
894
+ @panic("ts core host: one command value carries more rejected named ops than the effect table holds");
895
+ }
896
+ rejects[reject_count.*] = head.err_tag;
897
+ reject_count.* += 1;
898
+ return;
899
+ }
900
+ const index = freeStreamIndex() orelse
901
+ @panic("ts core host: more than 16 spawn streams in flight - the stream table mirrors the engine's max_effects slots");
902
+ const entry = &streams[index];
903
+ entry.used = true;
904
+ entry.key_len = head.key.len;
905
+ @memcpy(entry.key[0..head.key.len], head.key);
906
+ entry.line_tag = head.line_tag;
907
+ entry.exit_tag = head.exit_tag;
908
+ entry.err_tag = head.err_tag;
909
+ entry.collect = collect;
910
+ fx.spawn(.{
911
+ .key = spawn_key_base + index,
912
+ .argv = argv,
913
+ .stdin = if (stdin.len > 0) stdin else null,
914
+ .output = if (collect) .collect else .lines,
915
+ .on_line = if (head.line_tag != spawn_no_line_tag) spawnLineMsg else null,
916
+ .on_exit = spawnExitMsg,
917
+ });
918
+ }
919
+
920
+ fn findStream(key: []const u8) ?usize {
921
+ for (&streams, 0..) |*entry, index| {
922
+ if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
923
+ }
924
+ return null;
925
+ }
926
+
927
+ fn freeStreamIndex() ?usize {
928
+ for (&streams, 0..) |*entry, index| {
929
+ if (!entry.used) return index;
930
+ }
931
+ return null;
932
+ }
933
+
934
+ /// The stream entry an engine spawn result names — looked up
935
+ /// WITHOUT retiring (lines flow through it repeatedly; only the
936
+ /// exit terminal retires, in `spawnExitMsg`).
937
+ fn streamAt(key: u64) *StreamEntry {
938
+ if (key < spawn_key_base) {
939
+ @panic("ts core host: a spawn result arrived outside the bridge's stream key namespace");
940
+ }
941
+ const index = key - spawn_key_base;
942
+ if (index >= streams.len or !streams[index].used) {
943
+ @panic("ts core host: a spawn result arrived for a stream the bridge is not tracking");
944
+ }
945
+ return &streams[index];
946
+ }
947
+
948
+ /// `LineMsgFn` for spawn streams: every stdout line routes the
949
+ /// entry's line arm with the line bytes; the entry stays live.
950
+ /// Only set when the wire carries a line arm, so this never
951
+ /// sees `spawn_no_line_tag`.
952
+ fn spawnLineMsg(line: runtime_effects.EffectLine) Msg {
953
+ const entry = streamAt(line.key);
954
+ return msgFromTagBytes(entry.line_tag, line.line);
955
+ }
956
+
957
+ /// `ExitMsgFn` for spawn streams — the stream's ONE terminal,
958
+ /// retiring the entry: a clean `.exited` end routes the exit
959
+ /// arm (line mode: the code as its single number payload;
960
+ /// collect mode: the code/output record, with a truncated
961
+ /// collect routing err "truncated" instead — a cut stdout must
962
+ /// never parse as whole); every other reason routes the err arm
963
+ /// with the reason name as bytes.
964
+ fn spawnExitMsg(exit: runtime_effects.EffectExit) Msg {
965
+ const entry = streamAt(exit.key);
966
+ entry.used = false;
967
+ if (exit.reason == .exited) {
968
+ if (!entry.collect) {
969
+ return msgFromTagNumber(entry.exit_tag, @floatFromInt(exit.code));
970
+ }
971
+ if (!exit.output_truncated) {
972
+ return msgFromTagNumberBytes("spawn exit", "{ code, output }", entry.exit_tag, exit.code, exit.output);
973
+ }
974
+ }
975
+ const reason = if (exit.reason == .exited) "truncated" else @tagName(exit.reason);
976
+ return msgFromTagBytes(entry.err_tag, reason);
977
+ }
978
+
979
+ // ------------------------------------------------- audio stream
980
+
981
+ /// The audio_ctl record: drive the single playback channel,
982
+ /// gated by the wire key — a verb aimed at a key that is not
983
+ /// the open stream no-ops (its playback is already gone), the
984
+ /// same idle no-op the engine's own verbs keep. `stop` closes
985
+ /// the stream: the entry retires and later platform stragglers
986
+ /// are the engine's to swallow.
987
+ fn runAudioCtl(fx: *Fx, key: []const u8, verb: u8, value: f64) void {
988
+ if (!audio_entry.used or !std.mem.eql(u8, audio_entry.wireKey(), key)) return;
989
+ switch (verb) {
990
+ 0 => fx.pauseAudio(),
991
+ 1 => fx.resumeAudio(),
992
+ 2 => {
993
+ audio_entry.used = false;
994
+ fx.stopAudio();
995
+ },
996
+ // The wire carries the app's f64; anything that is not a
997
+ // millisecond offset seeks to 0 (the engine clamps the
998
+ // high end to the duration itself).
999
+ 3 => fx.seekAudio(if (value >= 0 and value <= 9007199254740992.0) @intFromFloat(value) else 0),
1000
+ // The engine clamps volume to 0..1 (NaN clamps to the
1001
+ // bound arithmetic's result deterministically).
1002
+ 4 => fx.setAudioVolume(@floatCast(value)),
1003
+ else => @panic("ts core host: unknown audio_ctl verb wire value - the core and this runtime disagree on cmd_format_version"),
1004
+ }
1005
+ }
1006
+
1007
+ /// `AudioMsgFn` for the audio stream: every playback event
1008
+ /// routes the entry's event arm. The entry never retires here —
1009
+ /// `completed`/`failed` streams may still speak (the app often
1010
+ /// starts the next track from `completed`), and audio_ctl
1011
+ /// `stop` is the explicit close.
1012
+ fn audioEventMsg(event: runtime_effects.EffectAudio) Msg {
1013
+ if (!audio_entry.used) {
1014
+ @panic("ts core host: an audio event arrived with no open bridge stream");
1015
+ }
1016
+ return msgFromTagAudio(audio_entry.event_tag, event);
1017
+ }
1018
+
1019
+ /// The wire `cancel` record: first match wins across the four
1020
+ /// keyed tables — requests (silent drop), named engine ops
1021
+ /// (silent drop: the entry is marked dropped, the engine's
1022
+ /// `.cancelled` terminal retires it, and its Msg is swallowed —
1023
+ /// no arm dispatches), spawn streams (the child dies and its
1024
+ /// exit routes the err arm with "cancelled" — killing a process
1025
+ /// IS an observable event, so spawn's cancel stays loud), then
1026
+ /// delays (silent — a cancelled delay just never fires).
1027
+ /// Unknown keys are a no-op; the audio stream is not cancel's
1028
+ /// to end (audio_ctl `stop` closes it).
1029
+ fn cancelWireKey(fx: *Fx, key: []const u8) void {
1030
+ if (key.len == 0) return;
1031
+ if (findRequest(key)) |index| {
1032
+ fx.cancelHostRequest(request_key_base + index);
1033
+ requests[index].used = false;
1034
+ return;
1035
+ }
1036
+ if (findEffect(key)) |index| {
1037
+ dropEffectEntry(fx, index);
1038
+ return;
1039
+ }
1040
+ if (findStream(key)) |index| {
1041
+ // Same shape: the engine ends the child and the
1042
+ // `.cancelled` exit retires the entry in spawnExitMsg.
1043
+ fx.cancel(spawn_key_base + index);
1044
+ return;
1045
+ }
1046
+ if (findDelay(key)) |index| {
1047
+ fx.cancelTimer(delay_key_base + index);
1048
+ delays[index].used = false;
1049
+ }
1050
+ }
1051
+
1052
+ /// Issue (or replace) a routed request. Keyed requests reuse
1053
+ /// their live table entry — re-routing the tags in place while
1054
+ /// the engine replaces the in-flight call under the same engine
1055
+ /// key. Unkeyed requests (`key.len == 0`) each take a fresh
1056
+ /// entry: nothing can replace or cancel them.
1057
+ fn issueRequest(fx: *Fx, name: []const u8, key: []const u8, ok_tag: u8, err_tag: u8, payload: []const u8) void {
1058
+ const index = blk: {
1059
+ if (key.len > 0) {
1060
+ if (findRequest(key)) |existing| break :blk existing;
1061
+ }
1062
+ break :blk freeRequestIndex() orelse
1063
+ @panic("ts core host: more than 16 host requests in flight - the request table mirrors the engine's max_effects slots");
1064
+ };
1065
+ const entry = &requests[index];
1066
+ entry.used = true;
1067
+ entry.key_len = key.len;
1068
+ @memcpy(entry.key[0..key.len], key);
1069
+ entry.ok_tag = ok_tag;
1070
+ entry.err_tag = err_tag;
1071
+ fx.hostRequest(.{
1072
+ .key = request_key_base + index,
1073
+ .name = name,
1074
+ .payload = payload,
1075
+ .on_result = hostResultMsg,
1076
+ });
1077
+ }
1078
+
1079
+ fn findRequest(key: []const u8) ?usize {
1080
+ for (&requests, 0..) |*entry, index| {
1081
+ if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
1082
+ }
1083
+ return null;
1084
+ }
1085
+
1086
+ fn freeRequestIndex() ?usize {
1087
+ for (&requests, 0..) |*entry, index| {
1088
+ if (!entry.used) return index;
1089
+ }
1090
+ return null;
1091
+ }
1092
+
1093
+ /// `HostMsgFn` for every bridge request: route the terminal to
1094
+ /// the entry's ok/err arm with the result bytes, retiring the
1095
+ /// entry. Runs during the drain, before the Msg dispatches —
1096
+ /// the frame arena is empty, so the payload copy lands at its
1097
+ /// base and commits with the model it may end up in.
1098
+ fn hostResultMsg(result: runtime_effects.EffectHostResult) Msg {
1099
+ if (result.key < request_key_base) {
1100
+ @panic("ts core host: a host result arrived outside the bridge's request key namespace");
1101
+ }
1102
+ const index = result.key - request_key_base;
1103
+ if (index >= requests.len or !requests[index].used) {
1104
+ @panic("ts core host: a host result arrived for a request the bridge is not tracking");
1105
+ }
1106
+ const entry = &requests[index];
1107
+ entry.used = false;
1108
+ return msgFromTagBytes(if (result.ok) entry.ok_tag else entry.err_tag, result.bytes);
1109
+ }
1110
+
1111
+ // ------------------------------------------- named engine ops
1112
+
1113
+ /// Retire the named-op entry an engine terminal names and hand
1114
+ /// back its routing tags plus whether the entry was dropped —
1115
+ /// a dropped entry's terminal must be swallowed, not routed.
1116
+ fn takeEffectEntry(key: u64) struct { ok_tag: u8, err_tag: u8, dropped: bool } {
1117
+ if (key < effect_key_base) {
1118
+ @panic("ts core host: an effect terminal arrived outside the bridge's named-op key namespace");
1119
+ }
1120
+ const index = key - effect_key_base;
1121
+ if (index >= effects_table.len or !effects_table[index].used) {
1122
+ @panic("ts core host: an effect terminal arrived for a named op the bridge is not tracking");
1123
+ }
1124
+ const entry = &effects_table[index];
1125
+ entry.used = false;
1126
+ return .{ .ok_tag = entry.ok_tag, .err_tag = entry.err_tag, .dropped = entry.dropped };
1127
+ }
1128
+
1129
+ /// A dropped entry's terminal (the `.cancelled` end of a
1130
+ /// replaced or wire-cancelled op): flag the next dispatch to
1131
+ /// swallow it and hand back an inert stand-in Msg — the flagged
1132
+ /// dispatch never reads it. The err arm's bytes shape makes a
1133
+ /// valid value; nothing routes.
1134
+ fn swallowedMsg(err_tag: u8) Msg {
1135
+ swallow_next_dispatch = true;
1136
+ return msgFromTagBytes(err_tag, "");
1137
+ }
1138
+
1139
+ /// `FileMsgFn` for read_file/write_file: reads route their ok
1140
+ /// arm with the content bytes, writes their (payload-less) ok
1141
+ /// arm; every non-ok outcome routes the err arm with the
1142
+ /// outcome's name as bytes. A dropped entry's terminal routes
1143
+ /// nothing — the silent drop.
1144
+ fn fileResultMsg(result: runtime_effects.EffectFileResult) Msg {
1145
+ const tags = takeEffectEntry(result.key);
1146
+ if (tags.dropped) return swallowedMsg(tags.err_tag);
1147
+ if (result.outcome == .ok) {
1148
+ if (result.op == .read) return msgFromTagBytes(tags.ok_tag, result.bytes);
1149
+ return msgFromTagVoid(tags.ok_tag);
1150
+ }
1151
+ return msgFromTagBytes(tags.err_tag, @tagName(result.outcome));
1152
+ }
1153
+
1154
+ /// `ResponseMsgFn` for fetch: an `.ok` un-truncated response
1155
+ /// routes the ok arm as `{ status, body }`; everything else —
1156
+ /// truncation included, so a cut body never parses as whole —
1157
+ /// routes the err arm with the reason as bytes. A dropped
1158
+ /// entry's terminal routes nothing — the silent drop.
1159
+ fn fetchResultMsg(response: runtime_effects.EffectResponse) Msg {
1160
+ const tags = takeEffectEntry(response.key);
1161
+ if (tags.dropped) return swallowedMsg(tags.err_tag);
1162
+ if (response.outcome == .ok and !response.truncated) {
1163
+ return msgFromTagNumberBytes("fetch response", "{ status, body }", tags.ok_tag, response.status, response.body);
1164
+ }
1165
+ const reason = if (response.outcome == .ok) "truncated" else @tagName(response.outcome);
1166
+ return msgFromTagBytes(tags.err_tag, reason);
1167
+ }
1168
+
1169
+ /// `ClipboardMsgFn` for clip_read (writes are fire-and-forget
1170
+ /// and never route): ok routes the text bytes, everything else
1171
+ /// the outcome name. A dropped entry's terminal routes nothing
1172
+ /// — the silent drop.
1173
+ fn clipboardResultMsg(result: runtime_effects.EffectClipboardResult) Msg {
1174
+ const tags = takeEffectEntry(result.key);
1175
+ if (tags.dropped) return swallowedMsg(tags.err_tag);
1176
+ if (result.outcome == .ok) return msgFromTagBytes(tags.ok_tag, result.text);
1177
+ return msgFromTagBytes(tags.err_tag, @tagName(result.outcome));
1178
+ }
1179
+
1180
+ /// `TimerMsgFn` for one-shot delays: the slot retires on fire
1181
+ /// (platform one-shots self-stop) and the named arm dispatches
1182
+ /// with the fire time in fractional milliseconds.
1183
+ fn delayFireMsg(timer: runtime_effects.EffectTimer) Msg {
1184
+ if (timer.outcome == .rejected) {
1185
+ @panic("ts core host: the platform rejected a Cmd.delay timer (no timer service, or the fx timer table is full)");
1186
+ }
1187
+ if (timer.key < delay_key_base) {
1188
+ @panic("ts core host: a delay fired outside the bridge's delay key namespace");
1189
+ }
1190
+ const index = timer.key - delay_key_base;
1191
+ if (index >= delays.len or !delays[index].used) {
1192
+ @panic("ts core host: a delay fired for a slot the bridge is not tracking");
1193
+ }
1194
+ delays[index].used = false;
1195
+ const ms = @as(f64, @floatFromInt(timer.timestamp_ns)) / std.time.ns_per_ms;
1196
+ return msgFromTagNumber(delays[index].tag, ms);
1197
+ }
1198
+
1199
+ // ------------------------------------------ subscription timers
1200
+
1201
+ /// Reconcile the declarative subscription set against the fixed
1202
+ /// timer table — the same algorithm as the transpiler package's
1203
+ /// run-fidelity drivers, engine-backed: match by key, arm new
1204
+ /// keys into the first free slot, re-arm on interval change,
1205
+ /// re-route on tag change, cancel the missing. Slot order
1206
+ /// everywhere, so record/replay walk identical tables.
1207
+ fn reconcileTimers(fx: *Fx) void {
1208
+ if (comptime !has_subscriptions) return;
1209
+ const subs = core.subscriptions(model_root);
1210
+ var seen = [_]bool{false} ** timers.len;
1211
+ var at: usize = 0;
1212
+ while (at < subs.len) {
1213
+ const op = takeByte(subs, &at);
1214
+ if (op != 0x01) {
1215
+ @panic("ts core host: unknown subscription wire record - the core and this runtime disagree on cmd_format_version");
1216
+ }
1217
+ // timer [op][key_len][key][every_ms f64 LE][msg_tag]
1218
+ const key = takeShortBytes(subs, &at);
1219
+ const every_bits = takeBytes(subs, &at, 8);
1220
+ const every_ms: f64 = @bitCast(std.mem.readInt(u64, every_bits[0..8], .little));
1221
+ const tag = takeByte(subs, &at);
1222
+ if (!(every_ms >= 1) or !(every_ms <= 31_536_000_000.0)) {
1223
+ // The lower bound also rejects NaN; the upper (one
1224
+ // year) keeps the engine's ns conversion in range.
1225
+ @panic("ts core host: Sub.timer interval must be between 1ms and one year");
1226
+ }
1227
+ var slot: ?usize = null;
1228
+ for (&timers, 0..) |*entry, index| {
1229
+ if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) slot = index;
1230
+ }
1231
+ if (slot) |index| {
1232
+ seen[index] = true;
1233
+ const entry = &timers[index];
1234
+ if (entry.every_ms != every_ms) {
1235
+ entry.every_ms = every_ms;
1236
+ // Interval change re-arms: the engine replaces
1237
+ // the active key in place and the platform timer
1238
+ // restarts from now.
1239
+ fx.startTimer(.{
1240
+ .key = timer_key_base + index,
1241
+ .interval_ms = intervalMs(every_ms),
1242
+ .mode = .repeating,
1243
+ .on_fire = timerFireMsg,
1244
+ });
1245
+ }
1246
+ // A tag-only change re-routes without re-arming.
1247
+ entry.tag = tag;
1248
+ } else {
1249
+ const index = freeTimerIndex() orelse
1250
+ @panic("ts core host: more than 16 subscription timers - the timer table mirrors the engine's max_effect_timers");
1251
+ seen[index] = true;
1252
+ const entry = &timers[index];
1253
+ entry.used = true;
1254
+ entry.key_len = key.len;
1255
+ @memcpy(entry.key[0..key.len], key);
1256
+ entry.every_ms = every_ms;
1257
+ entry.tag = tag;
1258
+ fx.startTimer(.{
1259
+ .key = timer_key_base + index,
1260
+ .interval_ms = intervalMs(every_ms),
1261
+ .mode = .repeating,
1262
+ .on_fire = timerFireMsg,
1263
+ });
1264
+ }
1265
+ }
1266
+ for (&timers, 0..) |*entry, index| {
1267
+ if (entry.used and !seen[index]) {
1268
+ entry.used = false;
1269
+ fx.cancelTimer(timer_key_base + index);
1270
+ }
1271
+ }
1272
+ }
1273
+
1274
+ fn freeTimerIndex() ?usize {
1275
+ for (&timers, 0..) |*entry, index| {
1276
+ if (!entry.used) return index;
1277
+ }
1278
+ return null;
1279
+ }
1280
+
1281
+ /// The engine arms whole milliseconds; the wire carries f64.
1282
+ /// Round half up, floor at 1 (validated above).
1283
+ fn intervalMs(every_ms: f64) u64 {
1284
+ return @intFromFloat(@max(1.0, @round(every_ms)));
1285
+ }
1286
+
1287
+ /// `TimerMsgFn` for every bridge timer: dispatch the slot's arm
1288
+ /// with the fire time in fractional milliseconds.
1289
+ fn timerFireMsg(timer: runtime_effects.EffectTimer) Msg {
1290
+ if (timer.outcome == .rejected) {
1291
+ @panic("ts core host: the platform rejected a subscription timer (no timer service, or the fx timer table is full)");
1292
+ }
1293
+ if (timer.key < timer_key_base) {
1294
+ @panic("ts core host: a timer fired outside the bridge's timer key namespace");
1295
+ }
1296
+ const index = timer.key - timer_key_base;
1297
+ if (index >= timers.len) {
1298
+ @panic("ts core host: a timer fired outside the bridge's timer table");
1299
+ }
1300
+ const ms = @as(f64, @floatFromInt(timer.timestamp_ns)) / std.time.ns_per_ms;
1301
+ return msgFromTagNumber(timers[index].tag, ms);
1302
+ }
1303
+
1304
+ // -------------------------------------------- Msg construction
1305
+
1306
+ /// Build the Msg arm at declaration-order index `tag` carrying
1307
+ /// `bytes` as its single payload. The bytes are copied into the
1308
+ /// core's frame arena first: the engine's slices are drain
1309
+ /// scratch, and the commit walkers only copy frame-resident
1310
+ /// pointers into the model heap.
1311
+ fn msgFromTagBytes(tag: u8, bytes: []const u8) Msg {
1312
+ inline for (msg_arms, 0..) |arm, index| {
1313
+ if (tag == index) {
1314
+ if (comptime arm.type == []const u8) {
1315
+ const copy = core.rt.frameAlloc(u8, bytes.len);
1316
+ @memcpy(copy, bytes);
1317
+ return @unionInit(Msg, arm.name, copy);
1318
+ }
1319
+ @panic("ts core host: a routed result targets Msg arm '" ++ arm.name ++ "', whose payload is not bytes");
1320
+ }
1321
+ }
1322
+ @panic("ts core host: a routed result names a Msg tag outside the union");
1323
+ }
1324
+
1325
+ /// Build the payload-less Msg arm at index `tag` (write_file's
1326
+ /// ok route — success carries nothing).
1327
+ fn msgFromTagVoid(tag: u8) Msg {
1328
+ inline for (msg_arms, 0..) |arm, index| {
1329
+ if (tag == index) {
1330
+ if (comptime arm.type == void) {
1331
+ return @unionInit(Msg, arm.name, {});
1332
+ }
1333
+ @panic("ts core host: a routed result targets Msg arm '" ++ arm.name ++ "', which is not payload-less");
1334
+ }
1335
+ }
1336
+ @panic("ts core host: a routed result names a Msg tag outside the union");
1337
+ }
1338
+
1339
+ /// Build the two-field number/bytes record arm at index `tag`
1340
+ /// (fetch's `{ status, body }` and a collect spawn's
1341
+ /// `{ code, output }`): the arm must be a struct of exactly one
1342
+ /// number field and one bytes field, matched BY TYPE (the
1343
+ /// transpiler validates the shape, so field names stay the
1344
+ /// app's). The bytes copy into the core's frame arena like
1345
+ /// every routed payload; the number widens into its field the
1346
+ /// way the subset's number model classes it (i64 or f64).
1347
+ fn msgFromTagNumberBytes(comptime what: []const u8, comptime shape: []const u8, tag: u8, number: anytype, bytes: []const u8) Msg {
1348
+ inline for (msg_arms, 0..) |arm, index| {
1349
+ if (tag == index) {
1350
+ const arm_info = @typeInfo(arm.type);
1351
+ if (comptime arm_info == .@"struct") {
1352
+ const fields = arm_info.@"struct".fields;
1353
+ const record_shape = comptime blk: {
1354
+ if (fields.len != 2) break :blk false;
1355
+ var bytes_fields = 0;
1356
+ var number_fields = 0;
1357
+ for (fields) |f| {
1358
+ if (f.type == []const u8) bytes_fields += 1;
1359
+ if (f.type == i64 or f.type == f64) number_fields += 1;
1360
+ }
1361
+ break :blk bytes_fields == 1 and number_fields == 1;
1362
+ };
1363
+ if (comptime record_shape) {
1364
+ var payload: arm.type = undefined;
1365
+ inline for (fields) |f| {
1366
+ if (comptime f.type == []const u8) {
1367
+ const copy = core.rt.frameAlloc(u8, bytes.len);
1368
+ @memcpy(copy, bytes);
1369
+ @field(payload, f.name) = copy;
1370
+ } else if (comptime f.type == f64) {
1371
+ @field(payload, f.name) = @floatFromInt(number);
1372
+ } else {
1373
+ @field(payload, f.name) = @intCast(number);
1374
+ }
1375
+ }
1376
+ return @unionInit(Msg, arm.name, payload);
1377
+ }
1378
+ }
1379
+ @panic("ts core host: a " ++ what ++ " targets Msg arm '" ++ arm.name ++ "', which is not a " ++ shape ++ " record");
1380
+ }
1381
+ }
1382
+ @panic("ts core host: a " ++ what ++ " names a Msg tag outside the union");
1383
+ }
1384
+
1385
+ /// Whether an arm payload struct is the audio event record: the
1386
+ /// six SDK-fixed fields, matched by NAME — `state` (any enum;
1387
+ /// its members are matched by member name at delivery),
1388
+ /// `positionMs`/`durationMs` (numbers), `playing`/`buffering`
1389
+ /// (booleans), `bands` (bytes).
1390
+ fn audioArmShape(comptime T: type) bool {
1391
+ const info = @typeInfo(T);
1392
+ if (info != .@"struct") return false;
1393
+ const fields = info.@"struct".fields;
1394
+ if (fields.len != 6) return false;
1395
+ var ok = true;
1396
+ for (fields) |f| {
1397
+ if (std.mem.eql(u8, f.name, "state")) {
1398
+ if (@typeInfo(f.type) != .@"enum") ok = false;
1399
+ } else if (std.mem.eql(u8, f.name, "positionMs") or std.mem.eql(u8, f.name, "durationMs")) {
1400
+ if (f.type != i64 and f.type != f64) ok = false;
1401
+ } else if (std.mem.eql(u8, f.name, "playing") or std.mem.eql(u8, f.name, "buffering")) {
1402
+ if (f.type != bool) ok = false;
1403
+ } else if (std.mem.eql(u8, f.name, "bands")) {
1404
+ if (f.type != []const u8) ok = false;
1405
+ } else {
1406
+ ok = false;
1407
+ }
1408
+ }
1409
+ return ok;
1410
+ }
1411
+
1412
+ /// The arm's `state` member for an engine event kind, matched
1413
+ /// by member NAME (the transpiler pins the member set, so the
1414
+ /// app's declaration order never matters to the wire).
1415
+ fn audioStateValue(comptime E: type, kind: runtime_effects.EffectAudioEventKind) E {
1416
+ const name = @tagName(kind);
1417
+ inline for (@typeInfo(E).@"enum".fields) |f| {
1418
+ if (std.mem.eql(u8, f.name, name)) return @enumFromInt(f.value);
1419
+ }
1420
+ @panic("ts core host: an audio event kind has no member in the event arm's state union - the transpiler's own shape check should have stopped this build");
1421
+ }
1422
+
1423
+ /// Build the six-field audio event arm at index `tag` from an
1424
+ /// engine event, by field name. The band bytes copy into the
1425
+ /// core's frame arena like every routed bytes payload; the
1426
+ /// millisecond fields widen the way the subset's number model
1427
+ /// classes them (i64 or f64).
1428
+ fn msgFromTagAudio(tag: u8, event: runtime_effects.EffectAudio) Msg {
1429
+ inline for (msg_arms, 0..) |arm, index| {
1430
+ if (tag == index) {
1431
+ if (comptime audioArmShape(arm.type)) {
1432
+ const fields = @typeInfo(arm.type).@"struct".fields;
1433
+ var payload: arm.type = undefined;
1434
+ inline for (fields) |f| {
1435
+ if (comptime std.mem.eql(u8, f.name, "state")) {
1436
+ @field(payload, f.name) = audioStateValue(f.type, event.kind);
1437
+ } else if (comptime std.mem.eql(u8, f.name, "positionMs")) {
1438
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.position_ms) else @intCast(event.position_ms);
1439
+ } else if (comptime std.mem.eql(u8, f.name, "durationMs")) {
1440
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.duration_ms) else @intCast(event.duration_ms);
1441
+ } else if (comptime std.mem.eql(u8, f.name, "playing")) {
1442
+ @field(payload, f.name) = event.playing;
1443
+ } else if (comptime std.mem.eql(u8, f.name, "buffering")) {
1444
+ @field(payload, f.name) = event.buffering;
1445
+ } else {
1446
+ const copy = core.rt.frameAlloc(u8, event.bands.len);
1447
+ @memcpy(copy, &event.bands);
1448
+ @field(payload, f.name) = copy;
1449
+ }
1450
+ }
1451
+ return @unionInit(Msg, arm.name, payload);
1452
+ }
1453
+ @panic("ts core host: an audio event targets Msg arm '" ++ arm.name ++ "', which is not the six-field audio event record");
1454
+ }
1455
+ }
1456
+ @panic("ts core host: an audio event names a Msg tag outside the union");
1457
+ }
1458
+
1459
+ /// Build the Msg arm at index `tag` carrying one number (`now`
1460
+ /// timestamps and timer fires; an i64-classed arm truncates the
1461
+ /// way the subset's number model does at index sites).
1462
+ fn msgFromTagNumber(tag: u8, value: f64) Msg {
1463
+ inline for (msg_arms, 0..) |arm, index| {
1464
+ if (tag == index) {
1465
+ if (comptime arm.type == f64) {
1466
+ return @unionInit(Msg, arm.name, value);
1467
+ } else if (comptime arm.type == i64) {
1468
+ return @unionInit(Msg, arm.name, @intFromFloat(value));
1469
+ }
1470
+ @panic("ts core host: a timestamp targets Msg arm '" ++ arm.name ++ "', whose payload is not a number");
1471
+ }
1472
+ }
1473
+ @panic("ts core host: a timestamp names a Msg tag outside the union");
1474
+ }
1475
+
1476
+ // ------------------------------------------------- wire cursor
1477
+
1478
+ fn takeByte(bytes: []const u8, at: *usize) u8 {
1479
+ if (at.* >= bytes.len) @panic("ts core host: truncated wire record");
1480
+ const value = bytes[at.*];
1481
+ at.* += 1;
1482
+ return value;
1483
+ }
1484
+
1485
+ fn takeBytes(bytes: []const u8, at: *usize, len: usize) []const u8 {
1486
+ if (len > bytes.len - at.*) @panic("ts core host: truncated wire record");
1487
+ const slice = bytes[at.* .. at.* + len];
1488
+ at.* += len;
1489
+ return slice;
1490
+ }
1491
+
1492
+ /// A one-byte-length-prefixed field (names and keys).
1493
+ fn takeShortBytes(bytes: []const u8, at: *usize) []const u8 {
1494
+ const len: usize = takeByte(bytes, at);
1495
+ return takeBytes(bytes, at, len);
1496
+ }
1497
+
1498
+ /// A u32-LE-length-prefixed field (payloads).
1499
+ fn takeLongBytes(bytes: []const u8, at: *usize) []const u8 {
1500
+ const len_bytes = takeBytes(bytes, at, 4);
1501
+ const len: usize = std.mem.readInt(u32, len_bytes[0..4], .little);
1502
+ return takeBytes(bytes, at, len);
1503
+ }
1504
+ };
1505
+ }