@native-sdk/cli 0.8.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/build/app.zig +905 -61
  2. package/build.zig +674 -373
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +6 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +455 -3
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  12. package/packages/core/scripts/run_external_core_compiler.mjs +77 -6
  13. package/packages/core/scripts/run_external_service_compiler.mjs +240 -0
  14. package/packages/core/scripts/stage_external_core.mjs +9 -1
  15. package/packages/core/scripts/stage_external_services.mjs +172 -0
  16. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  17. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  18. package/packages/core/sdk/core.d.ts +214 -2
  19. package/packages/core/sdk/core.ts +715 -42
  20. package/packages/core/sdk/events.d.ts +50 -0
  21. package/packages/core/sdk/events.ts +75 -0
  22. package/packages/core/src/checker.ts +528 -15
  23. package/packages/core/src/cli.ts +143 -3
  24. package/packages/core/src/contract.ts +26 -5
  25. package/packages/core/src/devhost.ts +1849 -18
  26. package/packages/core/src/devhost_journal.mjs +181 -0
  27. package/packages/core/src/devhost_resolver.mjs +17 -1
  28. package/packages/core/src/devhost_service_worker.mjs +90 -0
  29. package/packages/core/src/diagnostics.ts +84 -18
  30. package/packages/core/src/frontend.ts +204 -34
  31. package/packages/core/src/modules.ts +129 -80
  32. package/packages/core/src/service_contract.ts +597 -0
  33. package/packages/core/src/sqlite_cli.ts +93 -0
  34. package/packages/core/src/sqlite_codegen.ts +806 -0
  35. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  36. package/packages/core/src/typed_ast.ts +36 -8
  37. package/skill-data/core/SKILL.md +4 -2
  38. package/skill-data/core/references/project-anatomy.md +3 -2
  39. package/skill-data/core/references/web-engines-packaging-debugging.md +3 -1
  40. package/skill-data/native-ui/SKILL.md +55 -8
  41. package/skill-data/ts-core/SKILL.md +92 -40
  42. package/skill-data/ts-services/SKILL.md +126 -0
  43. package/skill-data/ts-services/references/service-surface.md +603 -0
  44. package/skill-data/zig/SKILL.md +1 -1
  45. package/skills/native-sdk/SKILL.md +1 -1
  46. package/src/app_runner/no_migrations.zig +3 -0
  47. package/src/app_runner/no_services.zig +20 -0
  48. package/src/app_runner/root.zig +104 -4
  49. package/src/app_runner/ts_core_main.zig +268 -4
  50. package/src/automation/snapshot.zig +23 -5
  51. package/src/embed/app_exports.zig +11 -1
  52. package/src/embed/c_api.zig +48 -2
  53. package/src/embed/conversions.zig +4 -5
  54. package/src/embed/host.zig +115 -1
  55. package/src/embed/root.zig +7 -0
  56. package/src/embed/tests.zig +213 -0
  57. package/src/embed/types.zig +51 -0
  58. package/src/embed/ui_host.zig +121 -5
  59. package/src/platform/android/NativeSdkActivity.java +131 -0
  60. package/src/platform/android/android_host.c +182 -1
  61. package/src/platform/android/native_sdk_app.h +17 -0
  62. package/src/platform/ios/native_sdk_app.h +17 -0
  63. package/src/platform/ios/uikit_host.m +115 -0
  64. package/src/platform/linux/cef_host.cpp +1 -1
  65. package/src/platform/linux/gtk_host.c +89 -17
  66. package/src/platform/linux/gtk_host.h +3 -0
  67. package/src/platform/linux/root.zig +41 -18
  68. package/src/platform/macos/appkit_host.h +26 -3
  69. package/src/platform/macos/appkit_host.m +1051 -129
  70. package/src/platform/macos/capture_info_plist.c +25 -0
  71. package/src/platform/macos/cef_host.mm +270 -36
  72. package/src/platform/macos/root.zig +312 -34
  73. package/src/platform/null_platform.zig +281 -19
  74. package/src/platform/null_platform_tests.zig +74 -0
  75. package/src/platform/root.zig +16 -0
  76. package/src/platform/types.zig +279 -15
  77. package/src/platform/windows/root.zig +243 -21
  78. package/src/platform/windows/webview2_host.cpp +464 -46
  79. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  80. package/src/primitives/app_manifest/root.zig +4 -0
  81. package/src/primitives/app_manifest/tests.zig +3 -0
  82. package/src/primitives/app_manifest/types.zig +34 -0
  83. package/src/primitives/app_manifest/validation.zig +19 -1
  84. package/src/primitives/canvas/code_tests.zig +9 -9
  85. package/src/primitives/canvas/events.zig +12 -11
  86. package/src/primitives/canvas/frame.zig +44 -9
  87. package/src/primitives/canvas/icons/mic.svg +1 -0
  88. package/src/primitives/canvas/icons.zig +2 -0
  89. package/src/primitives/canvas/root.zig +8 -0
  90. package/src/primitives/canvas/text_span_tests.zig +39 -0
  91. package/src/primitives/canvas/ui.zig +23 -4
  92. package/src/primitives/canvas/ui_markup.zig +15 -0
  93. package/src/primitives/canvas/ui_markup_compiled.zig +9 -0
  94. package/src/primitives/canvas/ui_markup_compiled_tests.zig +1 -1
  95. package/src/primitives/canvas/ui_markup_tests.zig +5 -0
  96. package/src/primitives/canvas/ui_markup_view.zig +9 -0
  97. package/src/primitives/canvas/ui_markup_view_tests.zig +9 -6
  98. package/src/primitives/canvas/ui_schema.zig +19 -10
  99. package/src/primitives/canvas/ui_schema_tests.zig +5 -3
  100. package/src/primitives/canvas/ui_tests.zig +18 -4
  101. package/src/primitives/canvas/widget_invalidation.zig +9 -2
  102. package/src/primitives/canvas/widget_render.zig +296 -114
  103. package/src/primitives/canvas/widget_runtime_tests.zig +133 -0
  104. package/src/primitives/canvas/widget_text_input.zig +10 -10
  105. package/src/primitives/canvas/widget_tree.zig +1 -1
  106. package/src/primitives/canvas/widgets.zig +29 -5
  107. package/src/root.zig +56 -0
  108. package/src/runtime/api.zig +11 -0
  109. package/src/runtime/automation_snapshot.zig +4 -0
  110. package/src/runtime/automation_widget_dispatch.zig +1 -0
  111. package/src/runtime/bridge_payload.zig +2 -0
  112. package/src/runtime/bridge_permission_tests.zig +23 -2
  113. package/src/runtime/bridge_responses.zig +3 -1
  114. package/src/runtime/canvas_frame.zig +31 -13
  115. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  116. package/src/runtime/canvas_frame_invalidation_tests.zig +35 -10
  117. package/src/runtime/canvas_widget_anchored_tests.zig +83 -0
  118. package/src/runtime/canvas_widget_events.zig +69 -24
  119. package/src/runtime/canvas_widget_runtime.zig +101 -6
  120. package/src/runtime/canvas_widget_scroll_driver_tests.zig +47 -4
  121. package/src/runtime/canvas_widget_scroll_drivers.zig +3 -3
  122. package/src/runtime/canvas_widget_semantics_tests.zig +2 -0
  123. package/src/runtime/canvas_widget_split_tree_tests.zig +228 -0
  124. package/src/runtime/canvas_widget_state.zig +6 -1
  125. package/src/runtime/canvas_widget_text_tests.zig +112 -3
  126. package/src/runtime/clock.zig +13 -1
  127. package/src/runtime/core.zig +133 -1
  128. package/src/runtime/credentials_store.zig +115 -0
  129. package/src/runtime/effects.zig +2568 -75
  130. package/src/runtime/effects_audio_capture_tests.zig +251 -0
  131. package/src/runtime/effects_credentials_tests.zig +332 -0
  132. package/src/runtime/effects_host_tests.zig +208 -1
  133. package/src/runtime/effects_relational_tests.zig +314 -0
  134. package/src/runtime/effects_store_tests.zig +211 -0
  135. package/src/runtime/flow.zig +14 -1
  136. package/src/runtime/gpu_surface_events.zig +6 -1
  137. package/src/runtime/native_command_event_tests.zig +42 -0
  138. package/src/runtime/persist_store.zig +666 -0
  139. package/src/runtime/record_store.zig +788 -0
  140. package/src/runtime/relational_store.zig +854 -0
  141. package/src/runtime/root.zig +52 -0
  142. package/src/runtime/runtime_event_tests.zig +70 -0
  143. package/src/runtime/service_host.zig +711 -0
  144. package/src/runtime/service_pool.zig +1314 -0
  145. package/src/runtime/session_blobs.zig +1 -1
  146. package/src/runtime/session_journal.zig +102 -0
  147. package/src/runtime/session_record.zig +177 -0
  148. package/src/runtime/session_replay.zig +109 -4
  149. package/src/runtime/shell_layout.zig +1 -0
  150. package/src/runtime/shell_layout_tests.zig +120 -0
  151. package/src/runtime/sqlite_engine.zig +474 -0
  152. package/src/runtime/state.zig +6 -0
  153. package/src/runtime/system_services.zig +49 -10
  154. package/src/runtime/tests.zig +5 -0
  155. package/src/runtime/ts_core_host.zig +1189 -118
  156. package/src/runtime/ts_core_host_tests.zig +638 -11
  157. package/src/runtime/ts_ui_app.zig +537 -1
  158. package/src/runtime/ui_app.zig +160 -19
  159. package/src/runtime/ui_app_tests.zig +203 -5
  160. package/src/runtime/validation.zig +22 -0
  161. package/src/runtime/view.zig +11 -0
  162. package/src/runtime/view_widget_scroll.zig +56 -5
  163. package/src/runtime/view_widget_text.zig +24 -5
  164. package/src/runtime/view_widget_tree.zig +1 -1
  165. package/src/runtime/window_storage.zig +1 -0
  166. package/src/runtime/window_view_runtime.zig +2 -3
  167. package/src/runtime/window_views.zig +19 -0
  168. package/src/tooling/android.zig +21 -16
  169. package/src/tooling/db.zig +160 -0
  170. package/src/tooling/ios.zig +7 -1
  171. package/src/tooling/manifest.zig +1248 -2
  172. package/src/tooling/package.zig +953 -6
  173. package/src/tooling/raw_manifest.zig +65 -0
  174. package/src/tooling/root.zig +1 -0
  175. package/src/tooling/templates.zig +216 -4
  176. package/src/tooling/ts_core.zig +283 -17
  177. package/src/tooling/verbs.zig +7 -0
  178. package/third_party/sqlite/README.md +13 -0
  179. package/third_party/sqlite/sqlite3.c +269649 -0
  180. package/third_party/sqlite/sqlite3.h +14349 -0
  181. package/tools/corewire/core_abi.zig +14 -2
  182. package/tools/corewire/emit.zig +98 -29
  183. package/tools/corewire/emit_facade.zig +414 -23
  184. package/tools/corewire/emit_profile.zig +6 -2
  185. package/tools/corewire/emit_service.zig +924 -0
  186. package/tools/corewire/main.zig +122 -0
  187. package/tools/corewire/service_contract.zig +250 -0
  188. package/tools/corewire/sidecar.zig +26 -15
@@ -1,6 +1,6 @@
1
1
  //! The native host consumer for compiled TypeScript app cores: bridges
2
2
  //! the versioned command/subscription wire format a compiled core
3
- //! emits (`cmd_format_version` 3) onto the real effect engine
3
+ //! emits (`cmd_format_version` 4) onto the real effect engine
4
4
  //! (`effects.zig`). The TypeScript tier's core module is a pure
5
5
  //! Model/Msg/update core whose effects are INERT BYTES — this module is
6
6
  //! the one place those bytes become engine calls, so the entire
@@ -19,6 +19,8 @@
19
19
  //! arms' declaration-order indices)
20
20
  //! core.initialModel() `*const Model`, or `InitResult{ model, cmd }`
21
21
  //! for a boot command
22
+ //! core.bootCommand() the boot `Cmd` without reinitializing the core,
23
+ //! required when `initialModel` returns `InitResult`
22
24
  //! core.update(m, msg) `*const Model`, or `UpdateResult{ model, cmd }`
23
25
  //! core.commitModelRoot the frame-end commit walker
24
26
  //! core.subscriptions optional: `fn (*const Model) []const u8`
@@ -36,9 +38,10 @@
36
38
  //! command and subscription bytes are frame-arena resident and must be
37
39
  //! consumed before the reset. Wire records map onto the engine as:
38
40
  //!
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.
41
+ //! persist -> `fx.hostSend("core.persist", core.persistenceSnapshot())`
42
+ //! — no model bytes ride the Cmd wire; the host asks
43
+ //! the already-committed core for canonical bytes while
44
+ //! walking the command.
42
45
  //! now -> `fx.wallMs()` (the journaled clock read) captured
43
46
  //! during the walk; the named arm dispatches with that
44
47
  //! time SYNCHRONOUSLY — immediately after the issuing
@@ -73,6 +76,15 @@
73
76
  //! ("truncated") rather than passing a silently cut
74
77
  //! body as ok. Wire timeout 0 means the engine
75
78
  //! default.
79
+ //! fetch_stream -> `fx.fetch` (`.stream`) through the STREAM table;
80
+ //! every complete response line routes the line arm,
81
+ //! and the ONE terminal retires the entry: `.ok`
82
+ //! routes the HTTP status through the one-number ok
83
+ //! arm, every other outcome routes the err arm with
84
+ //! its name. Wire timeout 0 and max-line 0 select the
85
+ //! engine defaults. `cancel` is loud for a live fetch
86
+ //! stream: it ends with err "cancelled", with no lines
87
+ //! after the cancel.
76
88
  //! clip_write -> `fx.writeClipboard` fire-and-forget (`on_result`
77
89
  //! null): a refused or over-bound write is dropped by
78
90
  //! design — there is no route to report on. Engine
@@ -285,6 +297,12 @@
285
297
  //! activate (the tray "Open" consequence of the
286
298
  //! menu-bar-app loop). No result Msg; the window's own
287
299
  //! frame event carries the state.
300
+ //! window_hide -> `fx.hideWindow(label)` — retain the live window and
301
+ //! its views while ordering it out; window_show is the
302
+ //! inverse.
303
+ //! dock_presence -> `fx.setDockPresence(visible)` — macOS regular/
304
+ //! accessory activation-policy switch; unsupported
305
+ //! hosts safely ignore it.
288
306
  //! quit_app -> `fx.quitApp()` — the graceful terminate through the
289
307
  //! same shutdown path a last-window close takes.
290
308
  //! show_notification -> `fx.showNotification` fire-and-forget; invalid or
@@ -357,6 +375,7 @@
357
375
 
358
376
  const std = @import("std");
359
377
  const runtime_effects = @import("effects.zig");
378
+ const platform = @import("../platform/root.zig");
360
379
 
361
380
  /// Engine-key namespace for bridge-issued host requests: `base + table
362
381
  /// index`. High bits spell "TSRQ" so a bridge key is recognizable in
@@ -413,6 +432,10 @@ pub fn videoKeyForTag(event_tag: u8) u64 {
413
432
  /// families' one engine key space without ever colliding on a key.
414
433
  pub const pty_key_base: u64 = 0x5453_5054_0000_0000;
415
434
 
435
+ /// Engine-key namespace for relational effects ("TSDB"). The DB family has
436
+ /// its own engine table, so these never consume the general request slots.
437
+ pub const db_key_base: u64 = 0x5453_4442_0000_0000;
438
+
416
439
  /// The spawn wire record's "no line routing" tag sentinel (the wire
417
440
  /// format's shared constant).
418
441
  pub const spawn_no_line_tag: u8 = 0xFF;
@@ -436,6 +459,15 @@ pub fn TsCoreHost(comptime core: type) type {
436
459
  pub const Msg = core.Msg;
437
460
  pub const Fx = runtime_effects.Effects(Msg);
438
461
 
462
+ /// Generated service contracts bind their operation table and the
463
+ /// canonical result decoder here. Ordinary HostCallBinding users do
464
+ /// not install this seam, so raw Cmd.request keeps its byte result.
465
+ pub const ServiceResultBinding = struct {
466
+ index_fn: *const fn (name: []const u8) ?u16,
467
+ streaming_fn: *const fn (operation: u16) bool,
468
+ decode_fn: *const fn (operation: u16, tag: u8, bytes: []const u8) Msg,
469
+ };
470
+
439
471
  const msg_arms = @typeInfo(Msg).@"union".fields;
440
472
 
441
473
  const update_returns_cmd = @typeInfo(@TypeOf(core.update)).@"fn".return_type.? != *const Model;
@@ -453,6 +485,9 @@ pub fn TsCoreHost(comptime core: type) type {
453
485
  key: [max_wire_key_bytes]u8 = undefined,
454
486
  ok_tag: u8 = 0,
455
487
  err_tag: u8 = 0,
488
+ service_operation: ?u16 = null,
489
+ service_channel: ?u64 = null,
490
+ ok_void: bool = false,
456
491
 
457
492
  fn wireKey(entry: *const RequestEntry) []const u8 {
458
493
  return entry.key[0..entry.key_len];
@@ -512,7 +547,7 @@ pub fn TsCoreHost(comptime core: type) type {
512
547
  }
513
548
  };
514
549
 
515
- /// One live spawn STREAM — the non-retiring entry kind: line
550
+ /// One live spawn or fetch STREAM — the non-retiring entry kind: line
516
551
  /// results route through it repeatedly across dispatches, and
517
552
  /// only the exit terminal (or the engine's `.cancelled` end
518
553
  /// after a wire cancel) retires it. The table index IS the
@@ -522,11 +557,17 @@ pub fn TsCoreHost(comptime core: type) type {
522
557
  used: bool = false,
523
558
  key_len: usize = 0,
524
559
  key: [max_wire_key_bytes]u8 = undefined,
525
- /// `spawn_no_line_tag` = lines dispatch nothing.
560
+ /// `spawn_no_line_tag` = lines dispatch nothing (spawn only;
561
+ /// fetch streams always carry a line route).
526
562
  line_tag: u8 = spawn_no_line_tag,
527
563
  exit_tag: u8 = 0,
528
564
  err_tag: u8 = 0,
529
565
  collect: bool = false,
566
+ /// Fetch lines are data records, so a cut or dropped line makes
567
+ /// the eventual success terminal unusable. Spawn line mode keeps
568
+ /// its existing best-effort contract.
569
+ fetch: bool = false,
570
+ damaged: bool = false,
530
571
 
531
572
  fn wireKey(entry: *const StreamEntry) []const u8 {
532
573
  return entry.key[0..entry.key_len];
@@ -591,6 +632,20 @@ pub fn TsCoreHost(comptime core: type) type {
591
632
  event_tag: u8 = 0,
592
633
  };
593
634
 
635
+ /// One microphone/system capture stream. Capture uses the engine's
636
+ /// channel transport internally but keeps a distinct bridge table so
637
+ /// terminal events retain the requested source and output format.
638
+ /// Replacing a source may briefly leave its old entry closing while
639
+ /// the new key is already live, so this mirrors channel capacity.
640
+ const AudioCaptureEntry = struct {
641
+ used: bool = false,
642
+ key: u64 = 0,
643
+ event_tag: u8 = 0,
644
+ source: platform.AudioCaptureSource = .microphone,
645
+ sample_rate: u32 = 0,
646
+ channels: u8 = 0,
647
+ };
648
+
594
649
  /// One live pty session — the stream entries' non-retiring
595
650
  /// shape: "output" events route through it repeatedly across
596
651
  /// dispatches, and only the one "exit" terminal retires it. The
@@ -608,6 +663,22 @@ pub fn TsCoreHost(comptime core: type) type {
608
663
  }
609
664
  };
610
665
 
666
+ const DbEntry = struct {
667
+ used: bool = false,
668
+ query: bool = true,
669
+ live: bool = false,
670
+ signature: u64 = 0,
671
+ key_len: usize = 0,
672
+ key: [max_wire_key_bytes]u8 = undefined,
673
+ page_tag: u8 = 0,
674
+ done_tag: u8 = 0,
675
+ err_tag: u8 = 0,
676
+
677
+ fn wireKey(entry: *const DbEntry) []const u8 {
678
+ return entry.key[0..entry.key_len];
679
+ }
680
+ };
681
+
611
682
  var model_root: *const Model = undefined;
612
683
  /// The platform caches directory for URL audio sources, set by
613
684
  /// the wiring (`TsUiApp`'s `audio_cache_dir`, or `setAudioCacheDir`
@@ -618,7 +689,7 @@ pub fn TsCoreHost(comptime core: type) type {
618
689
  var audio_cache_dir_len: usize = 0;
619
690
  var audio_cache_dir_buf: [runtime_effects.max_effect_audio_path_bytes]u8 = undefined;
620
691
  var audio_cache_path_buf: [runtime_effects.max_effect_audio_path_bytes]u8 = undefined;
621
- var requests: [runtime_effects.max_effects]RequestEntry = @splat(.{});
692
+ var requests: [runtime_effects.max_effects + runtime_effects.max_store_effects + runtime_effects.max_credentials_effects]RequestEntry = @splat(.{});
622
693
  var timers: [runtime_effects.max_effect_timers]TimerEntry = @splat(.{});
623
694
  var effects_table: [runtime_effects.max_effects]EffectEntry = @splat(.{});
624
695
  var delays: [runtime_effects.max_effect_timers]DelayEntry = @splat(.{});
@@ -627,7 +698,9 @@ pub fn TsCoreHost(comptime core: type) type {
627
698
  var video_entry: VideoEntry = .{};
628
699
  var images: [runtime_effects.max_effects]ImageEntry = @splat(.{});
629
700
  var channels: [runtime_effects.max_effect_channels]ChannelEntry = @splat(.{});
701
+ var audio_captures: [runtime_effects.max_effect_channels]AudioCaptureEntry = @splat(.{});
630
702
  var ptys: [runtime_effects.max_effect_ptys]PtyEntry = @splat(.{});
703
+ var dbs: [runtime_effects.max_db_effects]DbEntry = @splat(.{});
631
704
  /// The platform caches directory for URL image sources, the
632
705
  /// audio cache dir's twin (`setImageCacheDir` / `TsUiApp`'s
633
706
  /// `image_cache_dir`): bridge-side derivation of the
@@ -645,6 +718,12 @@ pub fn TsCoreHost(comptime core: type) type {
645
718
  /// `TsCoreHost.drain` and the `TsUiApp` update_fx seam — keep
646
719
  /// that adjacency).
647
720
  var swallow_next_dispatch: bool = false;
721
+ var service_results: ?ServiceResultBinding = null;
722
+ var pending_service_channel_close: ?u64 = null;
723
+
724
+ pub fn bindServiceResults(binding: ?ServiceResultBinding) void {
725
+ service_results = binding;
726
+ }
648
727
 
649
728
  /// A `now` record captured during the command walk, dispatched
650
729
  /// after the issuing cycle's frame reset.
@@ -701,7 +780,9 @@ pub fn TsCoreHost(comptime core: type) type {
701
780
  video_entry = .{};
702
781
  images = @splat(.{});
703
782
  channels = @splat(.{});
783
+ audio_captures = @splat(.{});
704
784
  ptys = @splat(.{});
785
+ dbs = @splat(.{});
705
786
  clip_write_counter = 0;
706
787
  audio_cache_dir_len = 0;
707
788
  image_cache_dir_len = 0;
@@ -713,15 +794,13 @@ pub fn TsCoreHost(comptime core: type) type {
713
794
 
714
795
  /// The effects half of `init`: perform the boot command and
715
796
  /// reconcile the initial subscriptions against the committed
716
- /// boot model. The command bytes are re-derived by re-running
717
- /// the PURE `initialModel` (they were frame-resident and did not
718
- /// survive `boot`'s frame reset; the duplicate model value is
719
- /// frame-transient garbage) — purity is the app-core subset's
720
- /// own guarantee, so the bytes are identical by construction.
797
+ /// boot model. The generated shim re-materializes only the boot
798
+ /// command through `bootCommand`; calling `initialModel` here would
799
+ /// reinitialize the compiled core and discard a model restored
800
+ /// between `boot` and `performBoot`.
721
801
  pub fn performBoot(fx: *Fx) void {
722
802
  if (comptime init_returns_cmd) {
723
- const again = core.initialModel();
724
- finishCycle(fx, again.cmd, 0);
803
+ finishCycle(fx, core.bootCommand(), 0);
725
804
  } else {
726
805
  finishCycle(fx, "", 0);
727
806
  }
@@ -732,6 +811,26 @@ pub fn TsCoreHost(comptime core: type) type {
732
811
  return model_root;
733
812
  }
734
813
 
814
+ /// Replace the committed core model from canonical snapshot bytes and
815
+ /// refresh the host mirror. Generated external cores expose the inverse
816
+ /// of `modelSnapshot`; hand-written test cores intentionally do not.
817
+ pub fn restoreSnapshot(snapshot: []const u8) void {
818
+ if (comptime !@hasDecl(core, "restoreModel")) {
819
+ @panic("ts core host: this core exposes no restoreModel entry - regenerate it with core ABI version 2");
820
+ } else {
821
+ model_root = core.restoreModel(snapshot);
822
+ }
823
+ }
824
+
825
+ /// Run the generated pure migration seam. The returned bytes are a
826
+ /// host-owned current-format snapshot and must be freed by `allocator`.
827
+ pub fn migrateSnapshot(snapshot: []const u8, from_version: u64, allocator: std.mem.Allocator) ?[]u8 {
828
+ if (comptime @hasDecl(core, "migrateModel")) {
829
+ return core.migrateModel(snapshot, from_version, allocator);
830
+ }
831
+ return null;
832
+ }
833
+
735
834
  /// Configure the caches directory audio-cache derivation uses.
736
835
  /// Call after `boot` (which clears it) and before any dispatch —
737
836
  /// wiring-time configuration, exactly like soundboard's boot-time
@@ -801,6 +900,10 @@ pub fn TsCoreHost(comptime core: type) type {
801
900
  swallow_next_dispatch = false;
802
901
  return;
803
902
  }
903
+ if (pending_service_channel_close) |channel_key| {
904
+ pending_service_channel_close = null;
905
+ fx.closeChannel(channel_key);
906
+ }
804
907
  dispatchDepth(fx, msg, 0);
805
908
  }
806
909
 
@@ -842,7 +945,8 @@ pub fn TsCoreHost(comptime core: type) type {
842
945
  var nows: [max_nows_per_cmd]PendingNow = undefined;
843
946
  var now_count: usize = 0;
844
947
  runCmd(fx, cmd, &nows, &now_count);
845
- reconcileTimers(fx);
948
+ reconcileSubscriptions(fx);
949
+ fx.flushDbSubscriptions();
846
950
  core.rt.frameReset();
847
951
  for (nows[0..now_count]) |pending| {
848
952
  dispatchDepth(fx, msgFromTagNumber(pending.tag, @floatFromInt(pending.ms)), depth + 1);
@@ -865,7 +969,10 @@ pub fn TsCoreHost(comptime core: type) type {
865
969
  at += 1;
866
970
  switch (op) {
867
971
  // persist [op]
868
- 0x01 => fx.hostSend("core.persist", ""),
972
+ 0x01 => {
973
+ const snapshot = if (comptime @hasDecl(core, "persistenceSnapshot")) core.persistenceSnapshot() else "";
974
+ fx.hostSend("core.persist", snapshot);
975
+ },
869
976
  // now [op][msg_tag]
870
977
  0x02 => {
871
978
  const tag = takeByte(cmd, &at);
@@ -891,14 +998,16 @@ pub fn TsCoreHost(comptime core: type) type {
891
998
  fx.hostSend(name, payload);
892
999
  },
893
1000
  // request [op][name_len][name][key_len][key]
894
- // [ok_tag][err_tag][len u32 LE][payload]
1001
+ // [ok_tag][err_tag][typed_service][len u32 LE][payload]
895
1002
  0x05 => {
896
1003
  const name = takeShortBytes(cmd, &at);
897
1004
  const key = takeShortBytes(cmd, &at);
898
1005
  const ok_tag = takeByte(cmd, &at);
899
1006
  const err_tag = takeByte(cmd, &at);
1007
+ const typed_service = takeByte(cmd, &at);
1008
+ if (typed_service > 1) @panic("ts core host: invalid typed-service request flag");
900
1009
  const payload = takeLongBytes(cmd, &at);
901
- issueRequest(fx, name, key, ok_tag, err_tag, payload);
1010
+ issueRequest(fx, name, key, ok_tag, err_tag, typed_service == 1, payload);
902
1011
  },
903
1012
  // cancel [op][key_len][key]
904
1013
  0x06 => {
@@ -949,17 +1058,27 @@ pub fn TsCoreHost(comptime core: type) type {
949
1058
  headers[i] = .{ .name = name, .value = value };
950
1059
  }
951
1060
  const body = takeLongBytes(cmd, &at);
952
- fx.fetch(.{
953
- .key = effect_key_base + allocEffectEntry(fx, head),
954
- .method = method,
955
- .url = url,
956
- .headers = headers[0..header_count],
957
- .body = if (body.len > 0) body else null,
958
- // Wire 0 = "the engine's default" — the record
959
- // never bakes the default in.
960
- .timeout_ms = if (timeout_ms == 0) runtime_effects.default_effect_fetch_timeout_ms else timeout_ms,
961
- .on_response = fetchResultMsg,
962
- });
1061
+ // Both Cmd.fetch overloads occupy one public key
1062
+ // space. A buffered fetch must not start beside a
1063
+ // live line stream under the same key: cancel would
1064
+ // otherwise find this named op first and leave the
1065
+ // stream running. The live stream owns the key, so
1066
+ // reject the newcomer through its own err arm.
1067
+ if (head.key.len > 0 and findStream(head.key) != null) {
1068
+ fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1069
+ } else {
1070
+ fx.fetch(.{
1071
+ .key = effect_key_base + allocEffectEntry(fx, head),
1072
+ .method = method,
1073
+ .url = url,
1074
+ .headers = headers[0..header_count],
1075
+ .body = if (body.len > 0) body else null,
1076
+ // Wire 0 = "the engine's default" — the record
1077
+ // never bakes the default in.
1078
+ .timeout_ms = if (timeout_ms == 0) runtime_effects.default_effect_fetch_timeout_ms else timeout_ms,
1079
+ .on_response = fetchResultMsg,
1080
+ });
1081
+ }
963
1082
  },
964
1083
  // clip_write [op][bytes_len u32 LE][bytes]
965
1084
  0x0A => {
@@ -1090,12 +1209,13 @@ pub fn TsCoreHost(comptime core: type) type {
1090
1209
  const id_value: f64 = @bitCast(std.mem.readInt(u64, id_bits[0..8], .little));
1091
1210
  runImageUnregister(fx, id_value);
1092
1211
  },
1093
- // channel_open [op][key f64 LE][event_tag]
1212
+ // channel_open [op][key f64 LE][event_tag][max_pending]
1094
1213
  0x15 => {
1095
1214
  const key_bits = takeBytes(cmd, &at, 8);
1096
1215
  const key_value: f64 = @bitCast(std.mem.readInt(u64, key_bits[0..8], .little));
1097
1216
  const event_tag = takeByte(cmd, &at);
1098
- issueChannelOpen(fx, key_value, event_tag);
1217
+ const max_pending = takeByte(cmd, &at);
1218
+ _ = issueChannelOpen(fx, key_value, event_tag, max_pending);
1099
1219
  },
1100
1220
  // channel_close [op][key f64 LE]
1101
1221
  0x16 => {
@@ -1233,6 +1353,239 @@ pub fn TsCoreHost(comptime core: type) type {
1233
1353
  .body = body,
1234
1354
  });
1235
1355
  },
1356
+ // audio_capture_start [op][key f64 LE][source u8]
1357
+ // [sample_rate u32 LE][channels u8]
1358
+ // [event_tag u8]
1359
+ 0x1E => {
1360
+ const key_bits = takeBytes(cmd, &at, 8);
1361
+ const key_value: f64 = @bitCast(std.mem.readInt(u64, key_bits[0..8], .little));
1362
+ const source_wire = takeByte(cmd, &at);
1363
+ const source = std.enums.fromInt(platform.AudioCaptureSource, source_wire) orelse
1364
+ @panic("ts core host: unknown audio capture source wire value - the core and this runtime disagree on cmd_format_version");
1365
+ const sample_rate = std.mem.readInt(u32, takeBytes(cmd, &at, 4)[0..4], .little);
1366
+ const capture_channels = takeByte(cmd, &at);
1367
+ const event_tag = takeByte(cmd, &at);
1368
+ issueAudioCaptureStart(fx, key_value, source, sample_rate, capture_channels, event_tag);
1369
+ },
1370
+ // audio_capture_stop [op][key f64 LE]
1371
+ 0x1F => {
1372
+ const key_bits = takeBytes(cmd, &at, 8);
1373
+ const key_value: f64 = @bitCast(std.mem.readInt(u64, key_bits[0..8], .little));
1374
+ runAudioCaptureStop(fx, key_value);
1375
+ },
1376
+ // fetch_stream [op][key_len][key][line][ok][err]
1377
+ // [method u8][timeout u32 LE]
1378
+ // [max_line_bytes u32 LE]
1379
+ // [url_len u32 LE][url][header_count u8]
1380
+ // ([name_len u8][name][value_len u32 LE][value])*
1381
+ // [body_len u32 LE][body]
1382
+ 0x20 => {
1383
+ const key = takeShortBytes(cmd, &at);
1384
+ const line_tag = takeByte(cmd, &at);
1385
+ const ok_tag = takeByte(cmd, &at);
1386
+ const err_tag = takeByte(cmd, &at);
1387
+ const method = fetchMethod(takeByte(cmd, &at));
1388
+ const timeout_bytes = takeBytes(cmd, &at, 4);
1389
+ const timeout_ms = std.mem.readInt(u32, timeout_bytes[0..4], .little);
1390
+ const max_line_bytes_wire = takeBytes(cmd, &at, 4);
1391
+ const max_line_bytes = std.mem.readInt(u32, max_line_bytes_wire[0..4], .little);
1392
+ const url = takeLongBytes(cmd, &at);
1393
+ const header_count: usize = takeByte(cmd, &at);
1394
+ if (header_count > runtime_effects.max_effect_fetch_headers) {
1395
+ @panic("ts core host: a streaming fetch wire record carries more headers than the engine accepts - the frontend's own bound should have stopped this build");
1396
+ }
1397
+ var headers: [runtime_effects.max_effect_fetch_headers]std.http.Header = undefined;
1398
+ for (0..header_count) |i| {
1399
+ const name = takeShortBytes(cmd, &at);
1400
+ const value = takeLongBytes(cmd, &at);
1401
+ headers[i] = .{ .name = name, .value = value };
1402
+ }
1403
+ const body = takeLongBytes(cmd, &at);
1404
+ issueFetchStream(fx, .{
1405
+ .key = key,
1406
+ .line_tag = line_tag,
1407
+ .exit_tag = ok_tag,
1408
+ .err_tag = err_tag,
1409
+ }, .{
1410
+ .method = method,
1411
+ .url = url,
1412
+ .headers = headers[0..header_count],
1413
+ .body = if (body.len > 0) body else null,
1414
+ .timeout_ms = if (timeout_ms == 0) runtime_effects.default_effect_fetch_timeout_ms else timeout_ms,
1415
+ .max_line_bytes = if (max_line_bytes == 0) runtime_effects.max_effect_line_bytes else max_line_bytes,
1416
+ });
1417
+ },
1418
+ // window_hide [op][label_len][label]
1419
+ 0x21 => {
1420
+ const label = takeShortBytes(cmd, &at);
1421
+ fx.hideWindow(label);
1422
+ },
1423
+ // dock_presence [op][visible u8]
1424
+ 0x22 => fx.setDockPresence(takeByte(cmd, &at) != 0),
1425
+ // service_stream_request [op][channel_key f64 LE]
1426
+ // [event_tag][max_pending]
1427
+ // [name_len][name][key_len][key]
1428
+ // [ok_tag][err_tag]
1429
+ // [payload_len u32 LE][payload]
1430
+ 0x28 => {
1431
+ const channel_bits = takeBytes(cmd, &at, 8);
1432
+ const channel_value: f64 = @bitCast(std.mem.readInt(u64, channel_bits[0..8], .little));
1433
+ const event_tag = takeByte(cmd, &at);
1434
+ const max_pending = takeByte(cmd, &at);
1435
+ const name = takeShortBytes(cmd, &at);
1436
+ const key = takeShortBytes(cmd, &at);
1437
+ const ok_tag = takeByte(cmd, &at);
1438
+ const err_tag = takeByte(cmd, &at);
1439
+ const payload = takeLongBytes(cmd, &at);
1440
+ issueServiceStreamRequest(fx, name, key, ok_tag, err_tag, channel_value, event_tag, max_pending, payload);
1441
+ },
1442
+ // store_set [op][route][scope u32][key bytes][value bytes]
1443
+ 0x23 => {
1444
+ const head = takeRoutedHead(cmd, &at);
1445
+ const scope = takeU32(cmd, &at);
1446
+ if (scope != 0) @panic("ts core host: record-store scope is reserved and must be zero in cmd format v3");
1447
+ const record_key = takeLongBytes(cmd, &at);
1448
+ const bytes = takeLongBytes(cmd, &at);
1449
+ const request_key = allocStoreRequestEntry(fx, head, true) orelse continue;
1450
+ fx.storeSet(.{
1451
+ .key = request_key,
1452
+ .record_key = record_key,
1453
+ .bytes = bytes,
1454
+ .on_result = hostResultMsg,
1455
+ });
1456
+ },
1457
+ // store_get [op][route][scope u32][key bytes]
1458
+ 0x24 => {
1459
+ const head = takeRoutedHead(cmd, &at);
1460
+ const scope = takeU32(cmd, &at);
1461
+ if (scope != 0) @panic("ts core host: record-store scope is reserved and must be zero in cmd format v3");
1462
+ const record_key = takeLongBytes(cmd, &at);
1463
+ const request_key = allocStoreRequestEntry(fx, head, false) orelse continue;
1464
+ fx.storeGet(.{
1465
+ .key = request_key,
1466
+ .record_key = record_key,
1467
+ .on_result = hostResultMsg,
1468
+ });
1469
+ },
1470
+ // store_delete [op][route][scope u32][key bytes]
1471
+ 0x25 => {
1472
+ const head = takeRoutedHead(cmd, &at);
1473
+ const scope = takeU32(cmd, &at);
1474
+ if (scope != 0) @panic("ts core host: record-store scope is reserved and must be zero in cmd format v3");
1475
+ const record_key = takeLongBytes(cmd, &at);
1476
+ const request_key = allocStoreRequestEntry(fx, head, true) orelse continue;
1477
+ fx.storeDelete(.{
1478
+ .key = request_key,
1479
+ .record_key = record_key,
1480
+ .on_result = hostResultMsg,
1481
+ });
1482
+ },
1483
+ // store_scan [op][route][scope u32][prefix bytes]
1484
+ // [limit u32][after bytes]
1485
+ 0x26 => {
1486
+ const head = takeRoutedHead(cmd, &at);
1487
+ const scope = takeU32(cmd, &at);
1488
+ if (scope != 0) @panic("ts core host: record-store scope is reserved and must be zero in cmd format v3");
1489
+ const prefix = takeLongBytes(cmd, &at);
1490
+ const limit = takeU32(cmd, &at);
1491
+ const after = takeLongBytes(cmd, &at);
1492
+ const request_key = allocStoreRequestEntry(fx, head, false) orelse continue;
1493
+ fx.storeScan(.{
1494
+ .key = request_key,
1495
+ .prefix = prefix,
1496
+ .limit = limit,
1497
+ .after = after,
1498
+ .on_result = hostResultMsg,
1499
+ });
1500
+ },
1501
+ // store_set_many [op][route][scope u32][count u32]
1502
+ // [count * (key bytes,value bytes)]
1503
+ 0x27 => {
1504
+ const head = takeRoutedHead(cmd, &at);
1505
+ const scope = takeU32(cmd, &at);
1506
+ if (scope != 0) @panic("ts core host: record-store scope is reserved and must be zero in cmd format v3");
1507
+ const count: usize = @intCast(takeU32(cmd, &at));
1508
+ var entries: [runtime_effects.max_effect_store_batch_entries]Fx.StoreEntry = undefined;
1509
+ var kept: usize = 0;
1510
+ for (0..count) |_| {
1511
+ const record_key = takeLongBytes(cmd, &at);
1512
+ const bytes = takeLongBytes(cmd, &at);
1513
+ if (kept < entries.len) {
1514
+ entries[kept] = .{ .key = record_key, .bytes = bytes };
1515
+ kept += 1;
1516
+ }
1517
+ }
1518
+ const request_key = allocStoreRequestEntry(fx, head, true) orelse continue;
1519
+ fx.storeSetMany(.{
1520
+ .key = request_key,
1521
+ .entries = if (count <= entries.len) entries[0..kept] else &.{},
1522
+ .on_result = hostResultMsg,
1523
+ });
1524
+ },
1525
+ // db_query [op][key][page][done][err][sql bytes]
1526
+ // [param count u32][tagged params]
1527
+ 0x29 => {
1528
+ const key = takeShortBytes(cmd, &at);
1529
+ const page_tag = takeByte(cmd, &at);
1530
+ const done_tag = takeByte(cmd, &at);
1531
+ const err_tag = takeByte(cmd, &at);
1532
+ const sql = takeLongBytes(cmd, &at);
1533
+ const count: usize = @intCast(takeU32(cmd, &at));
1534
+ var params: [runtime_effects.max_effect_db_parameters]runtime_effects.EffectDbValue = undefined;
1535
+ var kept: usize = 0;
1536
+ for (0..count) |_| {
1537
+ const value = takeDbValue(cmd, &at);
1538
+ if (kept < params.len) {
1539
+ params[kept] = value;
1540
+ kept += 1;
1541
+ }
1542
+ }
1543
+ const index = allocDbEntry(fx, key, true, page_tag, done_tag, err_tag) orelse continue;
1544
+ fx.dbQuery(.{
1545
+ .key = db_key_base + index,
1546
+ .sql = if (count <= params.len) sql else "",
1547
+ .params = if (count <= params.len) params[0..kept] else &.{},
1548
+ .on_result = dbResultMsg,
1549
+ });
1550
+ },
1551
+ // db_exec [op][key][ok][err][statement count u32]
1552
+ // [statement sql bytes][param count u32][params]...
1553
+ 0x2A => {
1554
+ const key = takeShortBytes(cmd, &at);
1555
+ const ok_tag = takeByte(cmd, &at);
1556
+ const err_tag = takeByte(cmd, &at);
1557
+ const count: usize = @intCast(takeU32(cmd, &at));
1558
+ var statements: [runtime_effects.max_effect_db_exec_statements]runtime_effects.EffectDbStatement = undefined;
1559
+ var values: [runtime_effects.max_effect_db_exec_statements * runtime_effects.max_effect_db_parameters]runtime_effects.EffectDbValue = undefined;
1560
+ var statement_kept: usize = 0;
1561
+ var value_kept: usize = 0;
1562
+ var valid = count <= statements.len;
1563
+ for (0..count) |_| {
1564
+ const sql = takeLongBytes(cmd, &at);
1565
+ const param_count: usize = @intCast(takeU32(cmd, &at));
1566
+ const start = value_kept;
1567
+ if (param_count > runtime_effects.max_effect_db_parameters) valid = false;
1568
+ for (0..param_count) |_| {
1569
+ const value = takeDbValue(cmd, &at);
1570
+ if (value_kept < values.len) {
1571
+ values[value_kept] = value;
1572
+ value_kept += 1;
1573
+ } else {
1574
+ valid = false;
1575
+ }
1576
+ }
1577
+ if (statement_kept < statements.len and start + param_count <= value_kept) {
1578
+ statements[statement_kept] = .{ .sql = sql, .params = values[start .. start + param_count] };
1579
+ statement_kept += 1;
1580
+ }
1581
+ }
1582
+ const index = allocDbEntry(fx, key, false, 0, ok_tag, err_tag) orelse continue;
1583
+ fx.dbExec(.{
1584
+ .key = db_key_base + index,
1585
+ .statements = if (valid and count == statement_kept) statements[0..statement_kept] else &.{},
1586
+ .on_result = dbResultMsg,
1587
+ });
1588
+ },
1236
1589
  else => @panic("ts core host: unknown command wire record - the core and this runtime disagree on cmd_format_version"),
1237
1590
  }
1238
1591
  }
@@ -1248,6 +1601,24 @@ pub fn TsCoreHost(comptime core: type) type {
1248
1601
  return .{ .key = key, .ok_tag = ok_tag, .err_tag = err_tag };
1249
1602
  }
1250
1603
 
1604
+ fn takeDbValue(cmd: []const u8, at: *usize) runtime_effects.EffectDbValue {
1605
+ return switch (takeByte(cmd, at)) {
1606
+ 0 => .null_value,
1607
+ 1 => blk: {
1608
+ const raw = takeBytes(cmd, at, 8);
1609
+ const number: f64 = @bitCast(std.mem.readInt(u64, raw[0..8], .little));
1610
+ if (std.math.isFinite(number) and @trunc(number) == number and number >= -9_007_199_254_740_991.0 and number <= 9_007_199_254_740_991.0) {
1611
+ break :blk .{ .integer = @intFromFloat(number) };
1612
+ }
1613
+ break :blk .{ .real = number };
1614
+ },
1615
+ 2 => .{ .text = takeLongBytes(cmd, at) },
1616
+ 3 => .{ .blob = takeLongBytes(cmd, at) },
1617
+ 4 => .{ .integer = if (takeByte(cmd, at) == 0) 0 else 1 },
1618
+ else => @panic("ts core host: unknown SQLite parameter tag - the core and runtime disagree on cmd_format_version"),
1619
+ };
1620
+ }
1621
+
1251
1622
  fn fetchMethod(wire: u8) std.http.Method {
1252
1623
  return switch (wire) {
1253
1624
  0 => .GET,
@@ -1347,7 +1718,7 @@ pub fn TsCoreHost(comptime core: type) type {
1347
1718
  return null;
1348
1719
  }
1349
1720
 
1350
- // ------------------------------------------------ spawn streams
1721
+ // ------------------------------------------- spawn / fetch streams
1351
1722
 
1352
1723
  const SpawnHead = struct { key: []const u8, line_tag: u8, exit_tag: u8, err_tag: u8 };
1353
1724
 
@@ -1370,8 +1741,14 @@ pub fn TsCoreHost(comptime core: type) type {
1370
1741
  fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1371
1742
  return;
1372
1743
  }
1373
- const index = freeStreamIndex() orelse
1374
- @panic("ts core host: more than 16 spawn streams in flight - the stream table mirrors the engine's max_effects slots");
1744
+ const index = freeStreamIndex() orelse {
1745
+ // Resource refusal is an ordinary stream terminal. The
1746
+ // engine would report the same rejection if it owned one
1747
+ // more routing slot; the bridge table must not turn that
1748
+ // public outcome into a process panic.
1749
+ fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1750
+ return;
1751
+ };
1375
1752
  const entry = &streams[index];
1376
1753
  entry.used = true;
1377
1754
  entry.key_len = head.key.len;
@@ -1380,16 +1757,66 @@ pub fn TsCoreHost(comptime core: type) type {
1380
1757
  entry.exit_tag = head.exit_tag;
1381
1758
  entry.err_tag = head.err_tag;
1382
1759
  entry.collect = collect;
1760
+ entry.fetch = false;
1761
+ entry.damaged = false;
1383
1762
  fx.spawn(.{
1384
1763
  .key = spawn_key_base + index,
1385
1764
  .argv = argv,
1386
1765
  .stdin = if (stdin.len > 0) stdin else null,
1387
1766
  .output = if (collect) .collect else .lines,
1388
- .on_line = if (head.line_tag != spawn_no_line_tag) spawnLineMsg else null,
1767
+ .on_line = if (head.line_tag != spawn_no_line_tag) streamLineMsg else null,
1389
1768
  .on_exit = spawnExitMsg,
1390
1769
  });
1391
1770
  }
1392
1771
 
1772
+ const FetchStreamOptions = struct {
1773
+ method: std.http.Method,
1774
+ url: []const u8,
1775
+ headers: []const std.http.Header,
1776
+ body: ?[]const u8,
1777
+ timeout_ms: u32,
1778
+ max_line_bytes: usize,
1779
+ };
1780
+
1781
+ /// Open a line-streamed fetch in the shared stream table. Like a
1782
+ /// spawn, a duplicate live wire key is rejected rather than replaced:
1783
+ /// replacing a source that has already delivered lines would splice
1784
+ /// two HTTP responses into one app-owned stream.
1785
+ fn issueFetchStream(fx: *Fx, head: SpawnHead, options: FetchStreamOptions) void {
1786
+ if (head.key.len > 0 and
1787
+ (findStream(head.key) != null or findEffect(head.key) != null))
1788
+ {
1789
+ fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1790
+ return;
1791
+ }
1792
+ const index = freeStreamIndex() orelse {
1793
+ fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1794
+ return;
1795
+ };
1796
+ const entry = &streams[index];
1797
+ entry.used = true;
1798
+ entry.key_len = head.key.len;
1799
+ @memcpy(entry.key[0..head.key.len], head.key);
1800
+ entry.line_tag = head.line_tag;
1801
+ entry.exit_tag = head.exit_tag;
1802
+ entry.err_tag = head.err_tag;
1803
+ entry.collect = false;
1804
+ entry.fetch = true;
1805
+ entry.damaged = false;
1806
+ fx.fetch(.{
1807
+ .key = spawn_key_base + index,
1808
+ .method = options.method,
1809
+ .url = options.url,
1810
+ .headers = options.headers,
1811
+ .body = options.body,
1812
+ .timeout_ms = options.timeout_ms,
1813
+ .response = .stream,
1814
+ .on_line = streamLineMsg,
1815
+ .max_line_bytes = options.max_line_bytes,
1816
+ .on_response = fetchStreamResultMsg,
1817
+ });
1818
+ }
1819
+
1393
1820
  fn findStream(key: []const u8) ?usize {
1394
1821
  for (&streams, 0..) |*entry, index| {
1395
1822
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
@@ -1404,26 +1831,30 @@ pub fn TsCoreHost(comptime core: type) type {
1404
1831
  return null;
1405
1832
  }
1406
1833
 
1407
- /// The stream entry an engine spawn result names — looked up
1834
+ /// The stream entry an engine spawn/fetch result names — looked up
1408
1835
  /// WITHOUT retiring (lines flow through it repeatedly; only the
1409
- /// exit terminal retires, in `spawnExitMsg`).
1836
+ /// terminal retires it).
1410
1837
  fn streamAt(key: u64) *StreamEntry {
1411
1838
  if (key < spawn_key_base) {
1412
- @panic("ts core host: a spawn result arrived outside the bridge's stream key namespace");
1839
+ @panic("ts core host: a stream result arrived outside the bridge's stream key namespace");
1413
1840
  }
1414
1841
  const index = key - spawn_key_base;
1415
1842
  if (index >= streams.len or !streams[index].used) {
1416
- @panic("ts core host: a spawn result arrived for a stream the bridge is not tracking");
1843
+ @panic("ts core host: a result arrived for a stream the bridge is not tracking");
1417
1844
  }
1418
1845
  return &streams[index];
1419
1846
  }
1420
1847
 
1421
- /// `LineMsgFn` for spawn streams: every stdout line routes the
1422
- /// entry's line arm with the line bytes; the entry stays live.
1423
- /// Only set when the wire carries a line arm, so this never
1424
- /// sees `spawn_no_line_tag`.
1425
- fn spawnLineMsg(line: runtime_effects.EffectLine) Msg {
1848
+ /// Shared `LineMsgFn` for spawn and fetch streams: every delivered
1849
+ /// source line routes the entry's line arm; the entry stays live.
1850
+ /// Fetch streams additionally remember any cut line or preceding
1851
+ /// queue loss so their terminal cannot later claim the response was
1852
+ /// complete.
1853
+ fn streamLineMsg(line: runtime_effects.EffectLine) Msg {
1426
1854
  const entry = streamAt(line.key);
1855
+ if (entry.fetch and (line.truncated or line.dropped_before != 0)) {
1856
+ entry.damaged = true;
1857
+ }
1427
1858
  return msgFromTagBytes(entry.line_tag, line.line);
1428
1859
  }
1429
1860
 
@@ -1449,6 +1880,23 @@ pub fn TsCoreHost(comptime core: type) type {
1449
1880
  return msgFromTagBytes(entry.err_tag, reason);
1450
1881
  }
1451
1882
 
1883
+ /// The streamed fetch's ONE terminal. A delivered, lossless response
1884
+ /// — any HTTP status, including non-2xx — routes the status through
1885
+ /// the ok arm. A cut/dropped line routes `truncated`; transport
1886
+ /// failure, timeout, rejection, and cancellation route their
1887
+ /// machine-readable outcome through err. The terminal retires the
1888
+ /// shared stream entry, so no later line can route for the key.
1889
+ fn fetchStreamResultMsg(response: runtime_effects.EffectResponse) Msg {
1890
+ const entry = streamAt(response.key);
1891
+ const damaged = entry.damaged or response.truncated or response.dropped_before != 0;
1892
+ entry.used = false;
1893
+ if (response.outcome == .ok) {
1894
+ if (damaged) return msgFromTagStaticBytes(entry.err_tag, "truncated");
1895
+ return msgFromTagNumber(entry.exit_tag, @floatFromInt(response.status));
1896
+ }
1897
+ return msgFromTagBytes(entry.err_tag, @tagName(response.outcome));
1898
+ }
1899
+
1452
1900
  // ------------------------------------------------- audio stream
1453
1901
 
1454
1902
  /// The audio_ctl record: drive the single playback channel,
@@ -1745,22 +2193,23 @@ pub fn TsCoreHost(comptime core: type) type {
1745
2193
  fx: *Fx,
1746
2194
  key_value: f64,
1747
2195
  event_tag: u8,
1748
- ) void {
2196
+ max_pending: u8,
2197
+ ) bool {
1749
2198
  const representable = std.math.isFinite(key_value) and
1750
2199
  key_value >= 1 and key_value < 9007199254740992.0 and
1751
2200
  @floor(key_value) == key_value;
1752
2201
  if (!representable) {
1753
2202
  fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = 0, .kind = .rejected }));
1754
- return;
2203
+ return false;
1755
2204
  }
1756
2205
  const key: u64 = @intFromFloat(key_value);
1757
2206
  if (findChannel(key) != null) {
1758
2207
  fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = key, .kind = .rejected }));
1759
- return;
2208
+ return false;
1760
2209
  }
1761
2210
  const index = freeChannelIndex() orelse {
1762
2211
  fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = key, .kind = .rejected }));
1763
- return;
2212
+ return false;
1764
2213
  };
1765
2214
  const entry = &channels[index];
1766
2215
  entry.used = true;
@@ -1769,7 +2218,13 @@ pub fn TsCoreHost(comptime core: type) type {
1769
2218
  _ = fx.openChannel(.{
1770
2219
  .key = key,
1771
2220
  .on_event = channelEventMsg,
2221
+ .max_pending = max_pending,
1772
2222
  });
2223
+ // A non-null lookup means the engine accepted the occupancy in
2224
+ // both live execution and replay (whose accepted handle is inert).
2225
+ // Validation and capacity refusals stage their rejection without
2226
+ // leaving an open slot.
2227
+ return fx.channelHandle(key) != null;
1773
2228
  }
1774
2229
 
1775
2230
  fn findChannel(key: u64) ?usize {
@@ -1817,6 +2272,110 @@ pub fn TsCoreHost(comptime core: type) type {
1817
2272
  return msgFromTagChannel(entry.event_tag, event);
1818
2273
  }
1819
2274
 
2275
+ // --------------------------------------------- audio capture streams
2276
+
2277
+ fn issueAudioCaptureStart(
2278
+ fx: *Fx,
2279
+ key_value: f64,
2280
+ source: platform.AudioCaptureSource,
2281
+ sample_rate: u32,
2282
+ capture_channels: u8,
2283
+ event_tag: u8,
2284
+ ) void {
2285
+ const representable = std.math.isFinite(key_value) and
2286
+ key_value >= 1 and key_value < 9007199254740992.0 and
2287
+ @floor(key_value) == key_value;
2288
+ const format: platform.AudioCaptureFormat = .{
2289
+ .sample_rate = sample_rate,
2290
+ .channels = capture_channels,
2291
+ };
2292
+ if (!representable or !format.valid()) {
2293
+ fx.stageLoopMsg(msgFromTagAudioCapture(event_tag, .{
2294
+ .key = if (representable) @intFromFloat(key_value) else 0,
2295
+ .kind = .rejected,
2296
+ .source = source,
2297
+ .sample_rate = sample_rate,
2298
+ .channels = capture_channels,
2299
+ }));
2300
+ return;
2301
+ }
2302
+ const key: u64 = @intFromFloat(key_value);
2303
+ if (findAudioCapture(key) != null) {
2304
+ fx.stageLoopMsg(msgFromTagAudioCapture(event_tag, .{
2305
+ .key = key,
2306
+ .kind = .rejected,
2307
+ .source = source,
2308
+ .sample_rate = sample_rate,
2309
+ .channels = capture_channels,
2310
+ }));
2311
+ return;
2312
+ }
2313
+ const index = freeAudioCaptureIndex() orelse {
2314
+ fx.stageLoopMsg(msgFromTagAudioCapture(event_tag, .{
2315
+ .key = key,
2316
+ .kind = .rejected,
2317
+ .source = source,
2318
+ .sample_rate = sample_rate,
2319
+ .channels = capture_channels,
2320
+ }));
2321
+ return;
2322
+ };
2323
+ audio_captures[index] = .{
2324
+ .used = true,
2325
+ .key = key,
2326
+ .event_tag = event_tag,
2327
+ .source = source,
2328
+ .sample_rate = sample_rate,
2329
+ .channels = capture_channels,
2330
+ };
2331
+ fx.startAudioCapture(.{
2332
+ .key = key,
2333
+ .source = source,
2334
+ .sample_rate = sample_rate,
2335
+ .channels = capture_channels,
2336
+ .on_event = audioCaptureEventMsg,
2337
+ });
2338
+ }
2339
+
2340
+ fn findAudioCapture(key: u64) ?usize {
2341
+ for (&audio_captures, 0..) |*entry, index| {
2342
+ if (entry.used and entry.key == key) return index;
2343
+ }
2344
+ return null;
2345
+ }
2346
+
2347
+ fn freeAudioCaptureIndex() ?usize {
2348
+ for (&audio_captures, 0..) |*entry, index| {
2349
+ if (!entry.used) return index;
2350
+ }
2351
+ return null;
2352
+ }
2353
+
2354
+ fn runAudioCaptureStop(fx: *Fx, key_value: f64) void {
2355
+ const representable = std.math.isFinite(key_value) and
2356
+ key_value >= 1 and key_value < 9007199254740992.0 and
2357
+ @floor(key_value) == key_value;
2358
+ if (!representable) return;
2359
+ const key: u64 = @intFromFloat(key_value);
2360
+ if (findAudioCapture(key) == null) return;
2361
+ fx.stopAudioCapture(key);
2362
+ }
2363
+
2364
+ fn audioCaptureEventMsg(channel_event: runtime_effects.EffectChannelEvent) Msg {
2365
+ const index = findAudioCapture(channel_event.key) orelse
2366
+ @panic("ts core host: an audio capture event arrived with no open bridge entry");
2367
+ const entry = &audio_captures[index];
2368
+ var event = runtime_effects.decodeAudioCaptureChannelEvent(channel_event);
2369
+ // The channel's terminal envelope carries no capture packet;
2370
+ // restore the requested identity/format from the bridge entry.
2371
+ event.source = entry.source;
2372
+ if (event.sample_rate == 0) event.sample_rate = entry.sample_rate;
2373
+ if (event.channels == 0) event.channels = entry.channels;
2374
+ const event_tag = entry.event_tag;
2375
+ if (event.kind == .stopped or event.kind == .rejected) entry.used = false;
2376
+ return msgFromTagAudioCapture(event_tag, event);
2377
+ }
2378
+
1820
2379
  // -------------------------------------------------- pty sessions
1821
2380
 
1822
2381
  /// Open a pty session: claim a non-retiring entry (the spawn
@@ -1943,21 +2502,102 @@ pub fn TsCoreHost(comptime core: type) type {
1943
2502
  return msgFromTagPty(entry.event_tag, wire_key, false, event);
1944
2503
  }
1945
2504
 
2505
+ fn allocDbEntry(
2506
+ fx: *Fx,
2507
+ key: []const u8,
2508
+ query: bool,
2509
+ page_tag: u8,
2510
+ done_tag: u8,
2511
+ err_tag: u8,
2512
+ ) ?usize {
2513
+ const index = blk: {
2514
+ if (key.len > 0) {
2515
+ if (findDb(key)) |existing| {
2516
+ // One-shot queries replace only earlier one-shot
2517
+ // queries. A live subscription owns its slot until
2518
+ // subscription reconciliation removes or re-arms it;
2519
+ // a command with the same wire key must reject rather
2520
+ // than silently erase that subscription.
2521
+ if (query and dbs[existing].query and !dbs[existing].live) break :blk existing;
2522
+ fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
2523
+ return null;
2524
+ }
2525
+ }
2526
+ break :blk freeDbIndex() orelse {
2527
+ fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
2528
+ return null;
2529
+ };
2530
+ };
2531
+ const entry = &dbs[index];
2532
+ entry.used = true;
2533
+ entry.query = query;
2534
+ entry.live = false;
2535
+ entry.signature = 0;
2536
+ entry.key_len = key.len;
2537
+ @memcpy(entry.key[0..key.len], key);
2538
+ entry.page_tag = page_tag;
2539
+ entry.done_tag = done_tag;
2540
+ entry.err_tag = err_tag;
2541
+ return index;
2542
+ }
2543
+
2544
+ fn findDb(key: []const u8) ?usize {
2545
+ if (key.len == 0) return null;
2546
+ for (&dbs, 0..) |*entry, index| {
2547
+ if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
2548
+ }
2549
+ return null;
2550
+ }
2551
+
2552
+ fn freeDbIndex() ?usize {
2553
+ for (&dbs, 0..) |*entry, index| if (!entry.used) return index;
2554
+ return null;
2555
+ }
2556
+
2557
+ fn dbResultMsg(result: runtime_effects.EffectDbResult) Msg {
2558
+ if (result.key < db_key_base) @panic("ts core host: a relational result arrived outside the bridge DB key namespace");
2559
+ const index = result.key - db_key_base;
2560
+ if (index >= dbs.len or !dbs[index].used) @panic("ts core host: a relational result arrived for an untracked command");
2561
+ const entry = &dbs[index];
2562
+ if (result.outcome != .ok) {
2563
+ if (!entry.live) entry.used = false;
2564
+ return msgFromTagBytes(entry.err_tag, @tagName(result.outcome));
2565
+ }
2566
+ return switch (result.kind) {
2567
+ .page => msgFromTagBytes(entry.page_tag, result.bytes),
2568
+ .done => blk: {
2569
+ if (!entry.query) @panic("ts core host: a query terminal reached an exec route");
2570
+ if (!entry.live) entry.used = false;
2571
+ break :blk msgFromTagVoid(entry.done_tag);
2572
+ },
2573
+ .exec => blk: {
2574
+ if (entry.query) @panic("ts core host: an exec terminal reached a query route");
2575
+ entry.used = false;
2576
+ break :blk msgFromTagVoid(entry.done_tag);
2577
+ },
2578
+ };
2579
+ }
2580
+
1946
2581
  /// The wire `cancel` record: first match wins across the four
1947
2582
  /// keyed tables — requests (silent drop), named engine ops
1948
2583
  /// (silent drop: the entry is marked dropped, the engine's
1949
2584
  /// `.cancelled` terminal retires it, and its Msg is swallowed —
1950
- /// no arm dispatches), spawn streams (the child dies and its
1951
- /// exit routes the err arm with "cancelled" — killing a process
1952
- /// IS an observable event, so spawn's cancel stays loud), then
1953
- /// delays (silent — a cancelled delay just never fires).
2585
+ /// no arm dispatches), spawn/fetch streams (their terminal routes
2586
+ /// the err arm with "cancelled" — ending a stream is observable,
2587
+ /// so stream cancellation stays loud), then delays (silent — a
2588
+ /// cancelled delay just never fires).
1954
2589
  /// Unknown keys are a no-op; the audio stream is not cancel's
1955
2590
  /// to end (audio_ctl `stop` closes it).
1956
2591
  fn cancelWireKey(fx: *Fx, key: []const u8) void {
1957
2592
  if (key.len == 0) return;
1958
2593
  if (findRequest(key)) |index| {
2594
+ const entry = requests[index];
1959
2595
  fx.cancelHostRequest(request_key_base + index);
1960
2596
  requests[index].used = false;
2597
+ if (entry.service_channel) |channel_key| {
2598
+ fx.closeChannel(channel_key);
2599
+ fx.stageLoopMsg(msgFromTagStaticBytes(entry.err_tag, "cancelled"));
2600
+ }
1961
2601
  return;
1962
2602
  }
1963
2603
  if (findEffect(key)) |index| {
@@ -1965,29 +2605,65 @@ pub fn TsCoreHost(comptime core: type) type {
1965
2605
  return;
1966
2606
  }
1967
2607
  if (findStream(key)) |index| {
1968
- // Same shape: the engine ends the child and the
1969
- // `.cancelled` exit retires the entry in spawnExitMsg.
2608
+ // The engine's `.cancelled` terminal retires the entry in
2609
+ // spawnExitMsg or fetchStreamResultMsg.
1970
2610
  fx.cancel(spawn_key_base + index);
1971
2611
  return;
1972
2612
  }
1973
2613
  if (findDelay(key)) |index| {
1974
2614
  fx.cancelTimer(delay_key_base + index);
1975
2615
  delays[index].used = false;
2616
+ return;
2617
+ }
2618
+ if (findDb(key)) |index| {
2619
+ // Declarative live queries belong exclusively to subscription
2620
+ // reconciliation. Cmd.cancel may share their public key, but
2621
+ // it must neither hide the bridge entry nor strand the
2622
+ // engine's `.live` slot; dropping the Sub below performs the
2623
+ // matching dbUnsubscribe.
2624
+ if (dbs[index].query and !dbs[index].live) {
2625
+ fx.cancelDbQuery(db_key_base + index);
2626
+ dbs[index].used = false;
2627
+ }
2628
+ // Transactions are already synchronous host work by the time
2629
+ // the next record in a batch is walked. Cancel never hides
2630
+ // their terminal (or makes the bridge forget its route).
2631
+ return;
1976
2632
  }
1977
2633
  }
1978
2634
 
1979
- /// Issue (or replace) a routed request. Keyed requests reuse
1980
- /// their live table entry — re-routing the tags in place while
1981
- /// the engine replaces the in-flight call under the same engine
1982
- /// key. Unkeyed requests (`key.len == 0`) each take a fresh
1983
- /// entry: nothing can replace or cancel them.
1984
- fn issueRequest(fx: *Fx, name: []const u8, key: []const u8, ok_tag: u8, err_tag: u8, payload: []const u8) void {
2635
+ const RequestPool = enum { host, store, credentials };
2636
+
2637
+ fn requestPoolAt(index: usize) RequestPool {
2638
+ if (index < runtime_effects.max_effects) return .host;
2639
+ if (index < runtime_effects.max_effects + runtime_effects.max_store_effects) return .store;
2640
+ return .credentials;
2641
+ }
2642
+
2643
+ /// Allocate a routed request slot. Host, record-store, and credential
2644
+ /// pools are disjoint, while wire keys still share one replacement
2645
+ /// namespace.
2646
+ fn allocRequestEntry(
2647
+ fx: *Fx,
2648
+ key: []const u8,
2649
+ ok_tag: u8,
2650
+ err_tag: u8,
2651
+ ok_void: bool,
2652
+ pool: RequestPool,
2653
+ ) ?u64 {
1985
2654
  const index = blk: {
1986
2655
  if (key.len > 0) {
1987
- if (findRequest(key)) |existing| break :blk existing;
2656
+ if (findRequest(key)) |existing| {
2657
+ if (requestPoolAt(existing) == pool) break :blk existing;
2658
+ fx.cancelHostRequest(request_key_base + existing);
2659
+ requests[existing].used = false;
2660
+ }
1988
2661
  }
1989
- break :blk freeRequestIndex() orelse
1990
- @panic("ts core host: more than 16 host requests in flight - the request table mirrors the engine's max_effects slots");
2662
+ break :blk switch (pool) {
2663
+ .host => freeRequestIndex(),
2664
+ .store => freeStoreRequestIndex(),
2665
+ .credentials => freeCredentialsRequestIndex(),
2666
+ } orelse return null;
1991
2667
  };
1992
2668
  const entry = &requests[index];
1993
2669
  entry.used = true;
@@ -1995,6 +2671,57 @@ pub fn TsCoreHost(comptime core: type) type {
1995
2671
  @memcpy(entry.key[0..key.len], key);
1996
2672
  entry.ok_tag = ok_tag;
1997
2673
  entry.err_tag = err_tag;
2674
+ entry.ok_void = ok_void;
2675
+ entry.service_operation = null;
2676
+ entry.service_channel = null;
2677
+ return index;
2678
+ }
2679
+
2680
+ fn allocStoreRequestEntry(fx: *Fx, head: RoutedHead, ok_void: bool) ?u64 {
2681
+ const index = allocRequestEntry(fx, head.key, head.ok_tag, head.err_tag, ok_void, .store) orelse {
2682
+ fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
2683
+ return null;
2684
+ };
2685
+ return request_key_base + index;
2686
+ }
2687
+
2688
+ fn allocCredentialsRequestEntry(fx: *Fx, key: []const u8, ok_tag: u8, err_tag: u8, ok_void: bool) ?u64 {
2689
+ const index = allocRequestEntry(fx, key, ok_tag, err_tag, ok_void, .credentials) orelse {
2690
+ fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
2691
+ return null;
2692
+ };
2693
+ return request_key_base + index;
2694
+ }
2695
+
2696
+ /// Issue (or replace) a routed request. Raw keyed requests reuse their
2697
+ /// live table entry when the bound host supports replacement. Typed
2698
+ /// services and reject-on-duplicate host bindings refuse before
2699
+ /// touching the original entry, so its eventual terminal still owns
2700
+ /// the route and table slot it started with. Unkeyed requests each
2701
+ /// take a fresh entry.
2702
+ fn issueRequest(fx: *Fx, name: []const u8, key: []const u8, ok_tag: u8, err_tag: u8, typed_service: bool, payload: []const u8) void {
2703
+ if (!typed_service and std.mem.startsWith(u8, name, "core.credentials.")) {
2704
+ issueCredentialsRequest(fx, name, key, ok_tag, err_tag, payload);
2705
+ return;
2706
+ }
2707
+ if (key.len > 0 and findRequest(key) != null and (typed_service or fx.rejectsDuplicateHostRequestKeys())) {
2708
+ stageRequestRejected(fx, err_tag);
2709
+ return;
2710
+ }
2711
+ const index = allocRequestEntry(fx, key, ok_tag, err_tag, false, .host) orelse {
2712
+ stageRequestRejected(fx, err_tag);
2713
+ return;
2714
+ };
2715
+ const entry = &requests[index];
2716
+ if (typed_service) if (service_results) |binding| {
2717
+ entry.service_operation = binding.index_fn(name);
2718
+ };
2719
+ if (entry.service_operation) |operation| {
2720
+ const binding = service_results.?;
2721
+ if (binding.streaming_fn(operation) and payload.len >= 8) {
2722
+ entry.service_channel = exactEngineKey(readF64(payload, 0));
2723
+ }
2724
+ }
1998
2725
  fx.hostRequest(.{
1999
2726
  .key = request_key_base + index,
2000
2727
  .name = name,
@@ -2003,6 +2730,130 @@ pub fn TsCoreHost(comptime core: type) type {
2003
2730
  });
2004
2731
  }
2005
2732
 
2733
+ fn issueCredentialsRequest(fx: *Fx, name: []const u8, key: []const u8, ok_tag: u8, err_tag: u8, payload: []const u8) void {
2734
+ const is_set = std.mem.eql(u8, name, "core.credentials.set");
2735
+ const is_get = std.mem.eql(u8, name, "core.credentials.get");
2736
+ const is_delete = std.mem.eql(u8, name, "core.credentials.delete");
2737
+ if (!is_set and !is_get and !is_delete) {
2738
+ stageRequestRejected(fx, err_tag);
2739
+ return;
2740
+ }
2741
+ var at: usize = 0;
2742
+ const credential_key = takeCredentialBytes(payload, &at) orelse {
2743
+ stageRequestRejected(fx, err_tag);
2744
+ return;
2745
+ };
2746
+ if (is_set) {
2747
+ const secret = takeCredentialBytes(payload, &at) orelse {
2748
+ stageRequestRejected(fx, err_tag);
2749
+ return;
2750
+ };
2751
+ if (at != payload.len) {
2752
+ stageRequestRejected(fx, err_tag);
2753
+ return;
2754
+ }
2755
+ const request_key = allocCredentialsRequestEntry(fx, key, ok_tag, err_tag, true) orelse return;
2756
+ fx.credentialsSet(.{
2757
+ .key = request_key,
2758
+ .credential_key = credential_key,
2759
+ .secret = secret,
2760
+ .host_result = hostResultMsg,
2761
+ });
2762
+ return;
2763
+ }
2764
+ if (at != payload.len) {
2765
+ stageRequestRejected(fx, err_tag);
2766
+ return;
2767
+ }
2768
+ const request_key = allocCredentialsRequestEntry(
2769
+ fx,
2770
+ key,
2771
+ ok_tag,
2772
+ err_tag,
2773
+ is_delete,
2774
+ ) orelse return;
2775
+ if (is_get) {
2776
+ fx.credentialsGet(.{
2777
+ .key = request_key,
2778
+ .credential_key = credential_key,
2779
+ .host_result = hostResultMsg,
2780
+ });
2781
+ } else {
2782
+ fx.credentialsDelete(.{
2783
+ .key = request_key,
2784
+ .credential_key = credential_key,
2785
+ .host_result = hostResultMsg,
2786
+ });
2787
+ }
2788
+ }
2789
+
2790
+ /// Credential records can also arrive through public `Cmd.request`,
2791
+ /// so their inner fields are untrusted even though the outer command
2792
+ /// wire was emitted correctly. Decode them fallibly and route a
2793
+ /// normal rejection instead of turning authored bytes into a panic.
2794
+ fn takeCredentialBytes(bytes: []const u8, at: *usize) ?[]const u8 {
2795
+ if (at.* > bytes.len or bytes.len - at.* < 4) return null;
2796
+ const len: usize = std.mem.readInt(u32, bytes[at.*..][0..4], .little);
2797
+ at.* += 4;
2798
+ if (len > bytes.len - at.*) return null;
2799
+ const field = bytes[at.* .. at.* + len];
2800
+ at.* += len;
2801
+ return field;
2802
+ }
2803
+
2804
+ /// Streaming services are one admission, not a channel-open/request
2805
+ /// batch. A duplicate route key or an already-open channel rejects
2806
+ /// before either table changes; otherwise the ordinary channel and
2807
+ /// request issuers retain their journal/replay behavior. An engine-side
2808
+ /// channel refusal is followed by the service err arm's matching
2809
+ /// rejection without starting the service transport.
2810
+ fn issueServiceStreamRequest(
2811
+ fx: *Fx,
2812
+ name: []const u8,
2813
+ key: []const u8,
2814
+ ok_tag: u8,
2815
+ err_tag: u8,
2816
+ channel_value: f64,
2817
+ event_tag: u8,
2818
+ max_pending: u8,
2819
+ payload: []const u8,
2820
+ ) void {
2821
+ if (key.len > 0 and findRequest(key) != null) {
2822
+ stageRequestRejected(fx, err_tag);
2823
+ return;
2824
+ }
2825
+ // Fail the existing request-table bound before opening a channel;
2826
+ // an admission failure must not leave an orphaned stream.
2827
+ if (freeRequestIndex() == null) {
2828
+ @panic("ts core host: more than 16 host requests in flight - the request table mirrors the engine's max_effects slots");
2829
+ }
2830
+
2831
+ const channel_key = exactEngineKey(channel_value);
2832
+ if (channel_key) |value| {
2833
+ // `findChannel` covers every TS bridge occupancy, including a
2834
+ // rejected terminal waiting to drain. `channelHandle` also
2835
+ // sees an open embedder-owned channel and replay's parked
2836
+ // occupancy. Never let this service acquire either one.
2837
+ if (findChannel(value) != null or fx.channelHandle(value) != null) {
2838
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = value, .kind = .rejected }));
2839
+ stageRequestRejected(fx, err_tag);
2840
+ return;
2841
+ }
2842
+ }
2843
+
2844
+ // Validation/table refusals generated by the bridge are final for
2845
+ // this combined command, so no service request may follow them.
2846
+ if (!issueChannelOpen(fx, channel_value, event_tag, max_pending)) {
2847
+ stageRequestRejected(fx, err_tag);
2848
+ return;
2849
+ }
2850
+ issueRequest(fx, name, key, ok_tag, err_tag, true, payload);
2851
+ }
2852
+
2853
+ fn stageRequestRejected(fx: *Fx, err_tag: u8) void {
2854
+ fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
2855
+ }
2856
+
2006
2857
  fn findRequest(key: []const u8) ?usize {
2007
2858
  for (&requests, 0..) |*entry, index| {
2008
2859
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
@@ -2011,7 +2862,24 @@ pub fn TsCoreHost(comptime core: type) type {
2011
2862
  }
2012
2863
 
2013
2864
  fn freeRequestIndex() ?usize {
2014
- for (&requests, 0..) |*entry, index| {
2865
+ for (requests[0..runtime_effects.max_effects], 0..) |*entry, index| {
2866
+ if (!entry.used) return index;
2867
+ }
2868
+ return null;
2869
+ }
2870
+
2871
+ fn freeStoreRequestIndex() ?usize {
2872
+ const first = runtime_effects.max_effects;
2873
+ const end = first + runtime_effects.max_store_effects;
2874
+ for (requests[first..end], first..) |*entry, index| {
2875
+ if (!entry.used) return index;
2876
+ }
2877
+ return null;
2878
+ }
2879
+
2880
+ fn freeCredentialsRequestIndex() ?usize {
2881
+ const first = runtime_effects.max_effects + runtime_effects.max_store_effects;
2882
+ for (requests[first..], first..) |*entry, index| {
2015
2883
  if (!entry.used) return index;
2016
2884
  }
2017
2885
  return null;
@@ -2032,6 +2900,15 @@ pub fn TsCoreHost(comptime core: type) type {
2032
2900
  }
2033
2901
  const entry = &requests[index];
2034
2902
  entry.used = false;
2903
+ if (entry.service_channel) |channel_key| pending_service_channel_close = channel_key;
2904
+ if (result.ok) {
2905
+ if (entry.service_operation) |operation| {
2906
+ const binding = service_results orelse
2907
+ @panic("ts core host: a typed service result arrived after its decoder was unbound");
2908
+ return binding.decode_fn(operation, entry.ok_tag, result.bytes);
2909
+ }
2910
+ }
2911
+ if (result.ok and entry.ok_void) return msgFromTagVoid(entry.ok_tag);
2035
2912
  return msgFromTagBytes(if (result.ok) entry.ok_tag else entry.err_tag, result.bytes);
2036
2913
  }
2037
2914
 
@@ -2123,7 +3000,7 @@ pub fn TsCoreHost(comptime core: type) type {
2123
3000
  return msgFromTagNumber(delays[index].tag, ms);
2124
3001
  }
2125
3002
 
2126
- // ------------------------------------------ subscription timers
3003
+ // ----------------------------------------------- subscriptions
2127
3004
 
2128
3005
  /// Reconcile the declarative subscription set against the fixed
2129
3006
  /// timer table — the same algorithm as the @native-sdk/core package's
@@ -2131,73 +3008,167 @@ pub fn TsCoreHost(comptime core: type) type {
2131
3008
  /// keys into the first free slot, re-arm on interval change,
2132
3009
  /// re-route on tag change, cancel the missing. Slot order
2133
3010
  /// everywhere, so record/replay walk identical tables.
2134
- fn reconcileTimers(fx: *Fx) void {
3011
+ fn reconcileSubscriptions(fx: *Fx) void {
2135
3012
  if (comptime !has_subscriptions) return;
2136
3013
  const subs = core.subscriptions(model_root);
2137
- var seen = [_]bool{false} ** timers.len;
3014
+ var seen_timers = [_]bool{false} ** timers.len;
3015
+ var seen_db = [_]bool{false} ** dbs.len;
3016
+
3017
+ // Free live DB slots whose wire keys disappeared before the pass
3018
+ // allocates replacements. Otherwise two independently valid sets
3019
+ // can overflow the shared family at their transient union (for
3020
+ // example, sixteen old keys replaced by one new key).
3021
+ const retained_db = retainedDbSubscriptions(subs);
3022
+ for (&dbs, 0..) |*entry, index| {
3023
+ if (entry.used and entry.live and !retained_db[index]) {
3024
+ fx.dbUnsubscribe(db_key_base + index);
3025
+ entry.used = false;
3026
+ }
3027
+ }
3028
+
2138
3029
  var at: usize = 0;
2139
3030
  while (at < subs.len) {
3031
+ const record_start = at;
2140
3032
  const op = takeByte(subs, &at);
2141
- if (op != 0x01) {
2142
- @panic("ts core host: unknown subscription wire record - the core and this runtime disagree on cmd_format_version");
2143
- }
2144
- // timer [op][key_len][key][every_ms f64 LE][msg_tag]
2145
- const key = takeShortBytes(subs, &at);
2146
- const every_bits = takeBytes(subs, &at, 8);
2147
- const every_ms: f64 = @bitCast(std.mem.readInt(u64, every_bits[0..8], .little));
2148
- const tag = takeByte(subs, &at);
2149
- if (!(every_ms >= 1) or !(every_ms <= 31_536_000_000.0)) {
2150
- // The lower bound also rejects NaN; the upper (one
2151
- // year) keeps the engine's ns conversion in range.
2152
- @panic("ts core host: Sub.timer interval must be between 1ms and one year");
2153
- }
2154
- var slot: ?usize = null;
2155
- for (&timers, 0..) |*entry, index| {
2156
- if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) slot = index;
2157
- }
2158
- if (slot) |index| {
2159
- seen[index] = true;
2160
- const entry = &timers[index];
2161
- if (entry.every_ms != every_ms) {
2162
- entry.every_ms = every_ms;
2163
- // Interval change re-arms: the engine replaces
2164
- // the active key in place and the platform timer
2165
- // restarts from now.
2166
- fx.startTimer(.{
2167
- .key = timer_key_base + index,
2168
- .interval_ms = intervalMs(every_ms),
2169
- .mode = .repeating,
2170
- .on_fire = timerFireMsg,
2171
- });
2172
- }
2173
- // A tag-only change re-routes without re-arming.
2174
- entry.tag = tag;
2175
- } else {
2176
- const index = freeTimerIndex() orelse
2177
- @panic("ts core host: more than 16 subscription timers - the timer table mirrors the engine's max_effect_timers");
2178
- seen[index] = true;
2179
- const entry = &timers[index];
2180
- entry.used = true;
2181
- entry.key_len = key.len;
2182
- @memcpy(entry.key[0..key.len], key);
2183
- entry.every_ms = every_ms;
2184
- entry.tag = tag;
2185
- fx.startTimer(.{
2186
- .key = timer_key_base + index,
2187
- .interval_ms = intervalMs(every_ms),
2188
- .mode = .repeating,
2189
- .on_fire = timerFireMsg,
2190
- });
3033
+ switch (op) {
3034
+ // timer [op][key_len][key][every_ms f64 LE][msg_tag]
3035
+ 0x01 => {
3036
+ const key = takeShortBytes(subs, &at);
3037
+ const every_bits = takeBytes(subs, &at, 8);
3038
+ const every_ms: f64 = @bitCast(std.mem.readInt(u64, every_bits[0..8], .little));
3039
+ const tag = takeByte(subs, &at);
3040
+ if (!(every_ms >= 1) or !(every_ms <= 31_536_000_000.0)) {
3041
+ @panic("ts core host: Sub.timer interval must be between 1ms and one year");
3042
+ }
3043
+ var slot: ?usize = null;
3044
+ for (&timers, 0..) |*entry, index| {
3045
+ if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) slot = index;
3046
+ }
3047
+ if (slot) |index| {
3048
+ seen_timers[index] = true;
3049
+ const entry = &timers[index];
3050
+ if (entry.every_ms != every_ms) {
3051
+ entry.every_ms = every_ms;
3052
+ fx.startTimer(.{
3053
+ .key = timer_key_base + index,
3054
+ .interval_ms = intervalMs(every_ms),
3055
+ .mode = .repeating,
3056
+ .on_fire = timerFireMsg,
3057
+ });
3058
+ }
3059
+ entry.tag = tag;
3060
+ } else {
3061
+ const index = freeTimerIndex() orelse
3062
+ @panic("ts core host: more than 16 subscription timers - the timer table mirrors the engine's max_effect_timers");
3063
+ seen_timers[index] = true;
3064
+ const entry = &timers[index];
3065
+ entry.used = true;
3066
+ entry.key_len = key.len;
3067
+ @memcpy(entry.key[0..key.len], key);
3068
+ entry.every_ms = every_ms;
3069
+ entry.tag = tag;
3070
+ fx.startTimer(.{
3071
+ .key = timer_key_base + index,
3072
+ .interval_ms = intervalMs(every_ms),
3073
+ .mode = .repeating,
3074
+ .on_fire = timerFireMsg,
3075
+ });
3076
+ }
3077
+ },
3078
+ // live query [op][key][page][done][err][sql bytes]
3079
+ // [param count][tagged params]
3080
+ // [table count][short table names]
3081
+ 0x02 => {
3082
+ const key = takeShortBytes(subs, &at);
3083
+ if (key.len == 0) @panic("ts core host: a live query requires a non-empty subscription key");
3084
+ const page_tag = takeByte(subs, &at);
3085
+ const done_tag = takeByte(subs, &at);
3086
+ const err_tag = takeByte(subs, &at);
3087
+ const sql = takeLongBytes(subs, &at);
3088
+ const param_count: usize = @intCast(takeU32(subs, &at));
3089
+ var params: [runtime_effects.max_effect_db_parameters]runtime_effects.EffectDbValue = undefined;
3090
+ if (param_count > params.len) @panic("ts core host: a live query carries too many SQL parameters");
3091
+ for (0..param_count) |index| params[index] = takeDbValue(subs, &at);
3092
+ const table_count: usize = @intCast(takeU32(subs, &at));
3093
+ var tables: [runtime_effects.max_effect_db_live_tables][]const u8 = undefined;
3094
+ if (table_count == 0 or table_count > tables.len) @panic("ts core host: a live query carries an invalid dependency table set");
3095
+ for (0..table_count) |index| tables[index] = takeShortBytes(subs, &at);
3096
+
3097
+ const signature = std.hash.Wyhash.hash(0, subs[record_start..at]);
3098
+ const index = findDb(key) orelse freeDbIndex() orelse
3099
+ @panic("ts core host: more relational commands and live queries are active than the database slot family can hold");
3100
+ const entry = &dbs[index];
3101
+ if (entry.used and !entry.live) @panic("ts core host: a live-query key collides with an in-flight database command");
3102
+ if (seen_db[index]) @panic("ts core host: duplicate live-query subscription key");
3103
+ seen_db[index] = true;
3104
+ if (!entry.used or entry.signature != signature) {
3105
+ if (entry.used) fx.dbUnsubscribe(db_key_base + index);
3106
+ entry.* = .{
3107
+ .used = true,
3108
+ .query = true,
3109
+ .live = true,
3110
+ .signature = signature,
3111
+ .key_len = key.len,
3112
+ .page_tag = page_tag,
3113
+ .done_tag = done_tag,
3114
+ .err_tag = err_tag,
3115
+ };
3116
+ @memcpy(entry.key[0..key.len], key);
3117
+ fx.dbSubscribe(.{
3118
+ .key = db_key_base + index,
3119
+ .sql = sql,
3120
+ .params = params[0..param_count],
3121
+ .tables = tables[0..table_count],
3122
+ .on_result = dbResultMsg,
3123
+ });
3124
+ }
3125
+ },
3126
+ else => @panic("ts core host: unknown subscription wire record - the core and this runtime disagree on cmd_format_version"),
2191
3127
  }
2192
3128
  }
2193
3129
  for (&timers, 0..) |*entry, index| {
2194
- if (entry.used and !seen[index]) {
3130
+ if (entry.used and !seen_timers[index]) {
2195
3131
  entry.used = false;
2196
3132
  fx.cancelTimer(timer_key_base + index);
2197
3133
  }
2198
3134
  }
2199
3135
  }
2200
3136
 
3137
+ /// Parse the inert subscription stream without mutating it and mark
3138
+ /// the currently-live DB entries whose public keys remain declared.
3139
+ /// Reconciliation uses this pre-pass to retire genuinely stale slots
3140
+ /// before it allocates any new ones.
3141
+ fn retainedDbSubscriptions(subs: []const u8) [runtime_effects.max_db_effects]bool {
3142
+ var retained = [_]bool{false} ** runtime_effects.max_db_effects;
3143
+ var at: usize = 0;
3144
+ while (at < subs.len) switch (takeByte(subs, &at)) {
3145
+ 0x01 => {
3146
+ _ = takeShortBytes(subs, &at);
3147
+ _ = takeBytes(subs, &at, 8);
3148
+ _ = takeByte(subs, &at);
3149
+ },
3150
+ 0x02 => {
3151
+ const key = takeShortBytes(subs, &at);
3152
+ if (key.len == 0) @panic("ts core host: a live query requires a non-empty subscription key");
3153
+ _ = takeByte(subs, &at);
3154
+ _ = takeByte(subs, &at);
3155
+ _ = takeByte(subs, &at);
3156
+ _ = takeLongBytes(subs, &at);
3157
+ const param_count: usize = @intCast(takeU32(subs, &at));
3158
+ if (param_count > runtime_effects.max_effect_db_parameters) @panic("ts core host: a live query carries too many SQL parameters");
3159
+ for (0..param_count) |_| _ = takeDbValue(subs, &at);
3160
+ const table_count: usize = @intCast(takeU32(subs, &at));
3161
+ if (table_count == 0 or table_count > runtime_effects.max_effect_db_live_tables) @panic("ts core host: a live query carries an invalid dependency table set");
3162
+ for (0..table_count) |_| _ = takeShortBytes(subs, &at);
3163
+ if (findDb(key)) |index| {
3164
+ if (dbs[index].live) retained[index] = true;
3165
+ }
3166
+ },
3167
+ else => @panic("ts core host: unknown subscription wire record - the core and this runtime disagree on cmd_format_version"),
3168
+ };
3169
+ return retained;
3170
+ }
3171
+
2201
3172
  fn freeTimerIndex() ?usize {
2202
3173
  for (&timers, 0..) |*entry, index| {
2203
3174
  if (!entry.used) return index;
@@ -2625,6 +3596,90 @@ pub fn TsCoreHost(comptime core: type) type {
2625
3596
  @panic("ts core host: a channel event names a Msg tag outside the union");
2626
3597
  }
2627
3598
 
3599
+ fn audioCaptureArmShape(comptime T: type) bool {
3600
+ const info = @typeInfo(T);
3601
+ if (info != .@"struct") return false;
3602
+ const fields = info.@"struct".fields;
3603
+ if (fields.len != 10) return false;
3604
+ var ok = true;
3605
+ for (fields) |f| {
3606
+ if (std.mem.eql(u8, f.name, "state") or std.mem.eql(u8, f.name, "source")) {
3607
+ if (@typeInfo(f.type) != .@"enum") ok = false;
3608
+ } else if (std.mem.eql(u8, f.name, "pcm")) {
3609
+ if (f.type != []const u8) ok = false;
3610
+ } else if (std.mem.eql(u8, f.name, "key") or
3611
+ std.mem.eql(u8, f.name, "sampleRate") or
3612
+ std.mem.eql(u8, f.name, "channels") or
3613
+ std.mem.eql(u8, f.name, "timestampMs") or
3614
+ std.mem.eql(u8, f.name, "frames") or
3615
+ std.mem.eql(u8, f.name, "droppedPending") or
3616
+ std.mem.eql(u8, f.name, "droppedTotal"))
3617
+ {
3618
+ if (f.type != i64 and f.type != u64 and f.type != f64) ok = false;
3619
+ } else {
3620
+ ok = false;
3621
+ }
3622
+ }
3623
+ return ok;
3624
+ }
3625
+
3626
+ fn audioCaptureStateValue(comptime E: type, kind: runtime_effects.EffectAudioCaptureEventKind) E {
3627
+ const name = @tagName(kind);
3628
+ inline for (@typeInfo(E).@"enum".fields) |f| {
3629
+ if (std.mem.eql(u8, f.name, name)) return @enumFromInt(f.value);
3630
+ }
3631
+ @panic("ts core host: an audio capture event kind has no member in the event arm's state union - the frontend's own shape check should have stopped this build");
3632
+ }
3633
+
3634
+ fn audioCaptureSourceValue(comptime E: type, source: platform.AudioCaptureSource) E {
3635
+ const name = @tagName(source);
3636
+ inline for (@typeInfo(E).@"enum".fields) |f| {
3637
+ if (std.mem.eql(u8, f.name, name)) return @enumFromInt(f.value);
3638
+ }
3639
+ @panic("ts core host: an audio capture source has no member in the event arm's source union - the frontend's own shape check should have stopped this build");
3640
+ }
3641
+
3642
+ fn msgFromTagAudioCapture(tag: u8, event: runtime_effects.EffectAudioCaptureEvent) Msg {
3643
+ inline for (msg_arms, 0..) |arm, index| {
3644
+ if (tag == index) {
3645
+ if (comptime audioCaptureArmShape(arm.type)) {
3646
+ const fields = @typeInfo(arm.type).@"struct".fields;
3647
+ var payload: arm.type = undefined;
3648
+ inline for (fields) |f| {
3649
+ if (comptime std.mem.eql(u8, f.name, "state")) {
3650
+ @field(payload, f.name) = audioCaptureStateValue(f.type, event.kind);
3651
+ } else if (comptime std.mem.eql(u8, f.name, "source")) {
3652
+ @field(payload, f.name) = audioCaptureSourceValue(f.type, event.source);
3653
+ } else if (comptime std.mem.eql(u8, f.name, "key")) {
3654
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.key) else @intCast(event.key);
3655
+ } else if (comptime std.mem.eql(u8, f.name, "sampleRate")) {
3656
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.sample_rate) else @intCast(event.sample_rate);
3657
+ } else if (comptime std.mem.eql(u8, f.name, "channels")) {
3658
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.channels) else @intCast(event.channels);
3659
+ } else if (comptime std.mem.eql(u8, f.name, "timestampMs")) {
3660
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.timestamp_ms) else @intCast(event.timestamp_ms);
3661
+ } else if (comptime std.mem.eql(u8, f.name, "frames")) {
3662
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.frames) else @intCast(event.frames);
3663
+ } else if (comptime std.mem.eql(u8, f.name, "droppedPending")) {
3664
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.dropped_pending) else @intCast(event.dropped_pending);
3665
+ } else if (comptime std.mem.eql(u8, f.name, "droppedTotal")) {
3666
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.dropped_total) else @intCast(event.dropped_total);
3667
+ } else if (event.pcm_s16le.len == 0) {
3668
+ @field(payload, f.name) = "";
3669
+ } else {
3670
+ const copy = core.rt.frameAlloc(u8, event.pcm_s16le.len);
3671
+ @memcpy(copy, event.pcm_s16le);
3672
+ @field(payload, f.name) = copy;
3673
+ }
3674
+ }
3675
+ return @unionInit(Msg, arm.name, payload);
3676
+ }
3677
+ @panic("ts core host: an audio capture event targets Msg arm '" ++ arm.name ++ "', which is not the ten-field audio capture event record");
3678
+ }
3679
+ }
3680
+ @panic("ts core host: an audio capture event names a Msg tag outside the union");
3681
+ }
3682
+
2628
3683
  /// The six-field pty event record, matched by field name —
2629
3684
  /// `channelArmShape`'s twin: `state` and `reason` (any enums;
2630
3685
  /// members matched by name at delivery), `bytes` (bytes),
@@ -2766,6 +3821,16 @@ pub fn TsCoreHost(comptime core: type) type {
2766
3821
 
2767
3822
  // ------------------------------------------------- wire cursor
2768
3823
 
3824
+ fn readF64(bytes: []const u8, at: usize) f64 {
3825
+ if (at + 8 > bytes.len) @panic("ts core host: truncated f64 service metadata");
3826
+ return @bitCast(std.mem.readInt(u64, bytes[at..][0..8], .little));
3827
+ }
3828
+
3829
+ fn exactEngineKey(value: f64) ?u64 {
3830
+ if (!std.math.isFinite(value) or value < 1 or value >= 9007199254740992.0 or @floor(value) != value) return null;
3831
+ return @intFromFloat(value);
3832
+ }
3833
+
2769
3834
  fn takeByte(bytes: []const u8, at: *usize) u8 {
2770
3835
  if (at.* >= bytes.len) @panic("ts core host: truncated wire record");
2771
3836
  const value = bytes[at.*];
@@ -2780,6 +3845,12 @@ pub fn TsCoreHost(comptime core: type) type {
2780
3845
  return slice;
2781
3846
  }
2782
3847
 
3848
+ /// A fixed-width little-endian integer.
3849
+ fn takeU32(bytes: []const u8, at: *usize) u32 {
3850
+ const raw = takeBytes(bytes, at, 4);
3851
+ return std.mem.readInt(u32, raw[0..4], .little);
3852
+ }
3853
+
2783
3854
  /// A one-byte-length-prefixed field (names and keys).
2784
3855
  fn takeShortBytes(bytes: []const u8, at: *usize) []const u8 {
2785
3856
  const len: usize = takeByte(bytes, at);