@native-sdk/cli 0.8.4 → 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 (146) hide show
  1. package/build/app.zig +859 -62
  2. package/build.zig +543 -13
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +2 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +365 -2
  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 +149 -0
  19. package/packages/core/sdk/core.ts +529 -12
  20. package/packages/core/sdk/events.d.ts +36 -0
  21. package/packages/core/sdk/events.ts +57 -0
  22. package/packages/core/src/checker.ts +468 -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 +1847 -16
  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 +82 -16
  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/references/project-anatomy.md +1 -1
  38. package/skill-data/native-ui/SKILL.md +47 -0
  39. package/skill-data/ts-core/SKILL.md +80 -31
  40. package/skill-data/ts-services/SKILL.md +126 -0
  41. package/skill-data/ts-services/references/service-surface.md +603 -0
  42. package/skill-data/zig/SKILL.md +1 -1
  43. package/skills/native-sdk/SKILL.md +1 -1
  44. package/src/app_runner/no_migrations.zig +3 -0
  45. package/src/app_runner/no_services.zig +20 -0
  46. package/src/app_runner/root.zig +104 -4
  47. package/src/app_runner/ts_core_main.zig +249 -8
  48. package/src/automation/snapshot.zig +23 -5
  49. package/src/embed/app_exports.zig +11 -1
  50. package/src/embed/c_api.zig +48 -2
  51. package/src/embed/conversions.zig +4 -5
  52. package/src/embed/host.zig +109 -1
  53. package/src/embed/root.zig +7 -0
  54. package/src/embed/tests.zig +213 -0
  55. package/src/embed/types.zig +51 -0
  56. package/src/embed/ui_host.zig +119 -5
  57. package/src/platform/android/NativeSdkActivity.java +131 -0
  58. package/src/platform/android/android_host.c +182 -1
  59. package/src/platform/android/native_sdk_app.h +17 -0
  60. package/src/platform/ios/native_sdk_app.h +17 -0
  61. package/src/platform/ios/uikit_host.m +115 -0
  62. package/src/platform/linux/cef_host.cpp +1 -1
  63. package/src/platform/linux/gtk_host.c +89 -17
  64. package/src/platform/linux/gtk_host.h +3 -0
  65. package/src/platform/linux/root.zig +40 -18
  66. package/src/platform/macos/appkit_host.h +16 -3
  67. package/src/platform/macos/appkit_host.m +536 -36
  68. package/src/platform/macos/cef_host.mm +248 -36
  69. package/src/platform/macos/root.zig +244 -34
  70. package/src/platform/null_platform.zig +223 -19
  71. package/src/platform/null_platform_tests.zig +74 -0
  72. package/src/platform/root.zig +9 -0
  73. package/src/platform/types.zig +179 -15
  74. package/src/platform/windows/root.zig +187 -21
  75. package/src/platform/windows/webview2_host.cpp +293 -46
  76. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  77. package/src/primitives/app_manifest/root.zig +4 -0
  78. package/src/primitives/app_manifest/tests.zig +3 -0
  79. package/src/primitives/app_manifest/types.zig +32 -0
  80. package/src/primitives/app_manifest/validation.zig +19 -1
  81. package/src/root.zig +46 -0
  82. package/src/runtime/api.zig +11 -0
  83. package/src/runtime/automation_snapshot.zig +4 -0
  84. package/src/runtime/bridge_permission_tests.zig +23 -2
  85. package/src/runtime/bridge_responses.zig +3 -1
  86. package/src/runtime/canvas_frame.zig +18 -11
  87. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  88. package/src/runtime/clock.zig +13 -1
  89. package/src/runtime/core.zig +133 -1
  90. package/src/runtime/credentials_store.zig +115 -0
  91. package/src/runtime/effects.zig +2295 -113
  92. package/src/runtime/effects_credentials_tests.zig +332 -0
  93. package/src/runtime/effects_host_tests.zig +208 -1
  94. package/src/runtime/effects_relational_tests.zig +314 -0
  95. package/src/runtime/effects_store_tests.zig +211 -0
  96. package/src/runtime/flow.zig +14 -1
  97. package/src/runtime/gpu_surface_events.zig +6 -1
  98. package/src/runtime/native_command_event_tests.zig +42 -0
  99. package/src/runtime/persist_store.zig +666 -0
  100. package/src/runtime/record_store.zig +788 -0
  101. package/src/runtime/relational_store.zig +854 -0
  102. package/src/runtime/root.zig +49 -0
  103. package/src/runtime/runtime_event_tests.zig +70 -0
  104. package/src/runtime/service_host.zig +711 -0
  105. package/src/runtime/service_pool.zig +1314 -0
  106. package/src/runtime/session_blobs.zig +1 -1
  107. package/src/runtime/session_journal.zig +102 -0
  108. package/src/runtime/session_record.zig +177 -0
  109. package/src/runtime/session_replay.zig +109 -4
  110. package/src/runtime/shell_layout.zig +1 -0
  111. package/src/runtime/shell_layout_tests.zig +120 -0
  112. package/src/runtime/sqlite_engine.zig +474 -0
  113. package/src/runtime/state.zig +6 -0
  114. package/src/runtime/system_services.zig +49 -10
  115. package/src/runtime/tests.zig +4 -0
  116. package/src/runtime/ts_core_host.zig +788 -86
  117. package/src/runtime/ts_core_host_tests.zig +231 -11
  118. package/src/runtime/ts_ui_app.zig +499 -1
  119. package/src/runtime/ui_app.zig +142 -16
  120. package/src/runtime/ui_app_tests.zig +155 -5
  121. package/src/runtime/validation.zig +22 -0
  122. package/src/runtime/view.zig +9 -0
  123. package/src/runtime/window_storage.zig +1 -0
  124. package/src/runtime/window_view_runtime.zig +2 -3
  125. package/src/runtime/window_views.zig +19 -0
  126. package/src/tooling/android.zig +21 -16
  127. package/src/tooling/db.zig +160 -0
  128. package/src/tooling/ios.zig +7 -1
  129. package/src/tooling/manifest.zig +214 -2
  130. package/src/tooling/package.zig +116 -0
  131. package/src/tooling/raw_manifest.zig +30 -0
  132. package/src/tooling/root.zig +1 -0
  133. package/src/tooling/templates.zig +161 -4
  134. package/src/tooling/ts_core.zig +283 -17
  135. package/src/tooling/verbs.zig +7 -0
  136. package/third_party/sqlite/README.md +13 -0
  137. package/third_party/sqlite/sqlite3.c +269649 -0
  138. package/third_party/sqlite/sqlite3.h +14349 -0
  139. package/tools/corewire/core_abi.zig +14 -2
  140. package/tools/corewire/emit.zig +98 -29
  141. package/tools/corewire/emit_facade.zig +378 -23
  142. package/tools/corewire/emit_profile.zig +6 -2
  143. package/tools/corewire/emit_service.zig +924 -0
  144. package/tools/corewire/main.zig +122 -0
  145. package/tools/corewire/service_contract.zig +250 -0
  146. 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
@@ -294,6 +297,12 @@
294
297
  //! activate (the tray "Open" consequence of the
295
298
  //! menu-bar-app loop). No result Msg; the window's own
296
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.
297
306
  //! quit_app -> `fx.quitApp()` — the graceful terminate through the
298
307
  //! same shutdown path a last-window close takes.
299
308
  //! show_notification -> `fx.showNotification` fire-and-forget; invalid or
@@ -423,6 +432,10 @@ pub fn videoKeyForTag(event_tag: u8) u64 {
423
432
  /// families' one engine key space without ever colliding on a key.
424
433
  pub const pty_key_base: u64 = 0x5453_5054_0000_0000;
425
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
+
426
439
  /// The spawn wire record's "no line routing" tag sentinel (the wire
427
440
  /// format's shared constant).
428
441
  pub const spawn_no_line_tag: u8 = 0xFF;
@@ -446,6 +459,15 @@ pub fn TsCoreHost(comptime core: type) type {
446
459
  pub const Msg = core.Msg;
447
460
  pub const Fx = runtime_effects.Effects(Msg);
448
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
+
449
471
  const msg_arms = @typeInfo(Msg).@"union".fields;
450
472
 
451
473
  const update_returns_cmd = @typeInfo(@TypeOf(core.update)).@"fn".return_type.? != *const Model;
@@ -463,6 +485,9 @@ pub fn TsCoreHost(comptime core: type) type {
463
485
  key: [max_wire_key_bytes]u8 = undefined,
464
486
  ok_tag: u8 = 0,
465
487
  err_tag: u8 = 0,
488
+ service_operation: ?u16 = null,
489
+ service_channel: ?u64 = null,
490
+ ok_void: bool = false,
466
491
 
467
492
  fn wireKey(entry: *const RequestEntry) []const u8 {
468
493
  return entry.key[0..entry.key_len];
@@ -638,6 +663,22 @@ pub fn TsCoreHost(comptime core: type) type {
638
663
  }
639
664
  };
640
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
+
641
682
  var model_root: *const Model = undefined;
642
683
  /// The platform caches directory for URL audio sources, set by
643
684
  /// the wiring (`TsUiApp`'s `audio_cache_dir`, or `setAudioCacheDir`
@@ -648,7 +689,7 @@ pub fn TsCoreHost(comptime core: type) type {
648
689
  var audio_cache_dir_len: usize = 0;
649
690
  var audio_cache_dir_buf: [runtime_effects.max_effect_audio_path_bytes]u8 = undefined;
650
691
  var audio_cache_path_buf: [runtime_effects.max_effect_audio_path_bytes]u8 = undefined;
651
- 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(.{});
652
693
  var timers: [runtime_effects.max_effect_timers]TimerEntry = @splat(.{});
653
694
  var effects_table: [runtime_effects.max_effects]EffectEntry = @splat(.{});
654
695
  var delays: [runtime_effects.max_effect_timers]DelayEntry = @splat(.{});
@@ -659,6 +700,7 @@ pub fn TsCoreHost(comptime core: type) type {
659
700
  var channels: [runtime_effects.max_effect_channels]ChannelEntry = @splat(.{});
660
701
  var audio_captures: [runtime_effects.max_effect_channels]AudioCaptureEntry = @splat(.{});
661
702
  var ptys: [runtime_effects.max_effect_ptys]PtyEntry = @splat(.{});
703
+ var dbs: [runtime_effects.max_db_effects]DbEntry = @splat(.{});
662
704
  /// The platform caches directory for URL image sources, the
663
705
  /// audio cache dir's twin (`setImageCacheDir` / `TsUiApp`'s
664
706
  /// `image_cache_dir`): bridge-side derivation of the
@@ -676,6 +718,12 @@ pub fn TsCoreHost(comptime core: type) type {
676
718
  /// `TsCoreHost.drain` and the `TsUiApp` update_fx seam — keep
677
719
  /// that adjacency).
678
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
+ }
679
727
 
680
728
  /// A `now` record captured during the command walk, dispatched
681
729
  /// after the issuing cycle's frame reset.
@@ -734,6 +782,7 @@ pub fn TsCoreHost(comptime core: type) type {
734
782
  channels = @splat(.{});
735
783
  audio_captures = @splat(.{});
736
784
  ptys = @splat(.{});
785
+ dbs = @splat(.{});
737
786
  clip_write_counter = 0;
738
787
  audio_cache_dir_len = 0;
739
788
  image_cache_dir_len = 0;
@@ -745,15 +794,13 @@ pub fn TsCoreHost(comptime core: type) type {
745
794
 
746
795
  /// The effects half of `init`: perform the boot command and
747
796
  /// reconcile the initial subscriptions against the committed
748
- /// boot model. The command bytes are re-derived by re-running
749
- /// the PURE `initialModel` (they were frame-resident and did not
750
- /// survive `boot`'s frame reset; the duplicate model value is
751
- /// frame-transient garbage) — purity is the app-core subset's
752
- /// 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`.
753
801
  pub fn performBoot(fx: *Fx) void {
754
802
  if (comptime init_returns_cmd) {
755
- const again = core.initialModel();
756
- finishCycle(fx, again.cmd, 0);
803
+ finishCycle(fx, core.bootCommand(), 0);
757
804
  } else {
758
805
  finishCycle(fx, "", 0);
759
806
  }
@@ -764,6 +811,26 @@ pub fn TsCoreHost(comptime core: type) type {
764
811
  return model_root;
765
812
  }
766
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
+
767
834
  /// Configure the caches directory audio-cache derivation uses.
768
835
  /// Call after `boot` (which clears it) and before any dispatch —
769
836
  /// wiring-time configuration, exactly like soundboard's boot-time
@@ -833,6 +900,10 @@ pub fn TsCoreHost(comptime core: type) type {
833
900
  swallow_next_dispatch = false;
834
901
  return;
835
902
  }
903
+ if (pending_service_channel_close) |channel_key| {
904
+ pending_service_channel_close = null;
905
+ fx.closeChannel(channel_key);
906
+ }
836
907
  dispatchDepth(fx, msg, 0);
837
908
  }
838
909
 
@@ -874,7 +945,8 @@ pub fn TsCoreHost(comptime core: type) type {
874
945
  var nows: [max_nows_per_cmd]PendingNow = undefined;
875
946
  var now_count: usize = 0;
876
947
  runCmd(fx, cmd, &nows, &now_count);
877
- reconcileTimers(fx);
948
+ reconcileSubscriptions(fx);
949
+ fx.flushDbSubscriptions();
878
950
  core.rt.frameReset();
879
951
  for (nows[0..now_count]) |pending| {
880
952
  dispatchDepth(fx, msgFromTagNumber(pending.tag, @floatFromInt(pending.ms)), depth + 1);
@@ -897,7 +969,10 @@ pub fn TsCoreHost(comptime core: type) type {
897
969
  at += 1;
898
970
  switch (op) {
899
971
  // persist [op]
900
- 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
+ },
901
976
  // now [op][msg_tag]
902
977
  0x02 => {
903
978
  const tag = takeByte(cmd, &at);
@@ -923,14 +998,16 @@ pub fn TsCoreHost(comptime core: type) type {
923
998
  fx.hostSend(name, payload);
924
999
  },
925
1000
  // request [op][name_len][name][key_len][key]
926
- // [ok_tag][err_tag][len u32 LE][payload]
1001
+ // [ok_tag][err_tag][typed_service][len u32 LE][payload]
927
1002
  0x05 => {
928
1003
  const name = takeShortBytes(cmd, &at);
929
1004
  const key = takeShortBytes(cmd, &at);
930
1005
  const ok_tag = takeByte(cmd, &at);
931
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");
932
1009
  const payload = takeLongBytes(cmd, &at);
933
- issueRequest(fx, name, key, ok_tag, err_tag, payload);
1010
+ issueRequest(fx, name, key, ok_tag, err_tag, typed_service == 1, payload);
934
1011
  },
935
1012
  // cancel [op][key_len][key]
936
1013
  0x06 => {
@@ -1132,12 +1209,13 @@ pub fn TsCoreHost(comptime core: type) type {
1132
1209
  const id_value: f64 = @bitCast(std.mem.readInt(u64, id_bits[0..8], .little));
1133
1210
  runImageUnregister(fx, id_value);
1134
1211
  },
1135
- // channel_open [op][key f64 LE][event_tag]
1212
+ // channel_open [op][key f64 LE][event_tag][max_pending]
1136
1213
  0x15 => {
1137
1214
  const key_bits = takeBytes(cmd, &at, 8);
1138
1215
  const key_value: f64 = @bitCast(std.mem.readInt(u64, key_bits[0..8], .little));
1139
1216
  const event_tag = takeByte(cmd, &at);
1140
- issueChannelOpen(fx, key_value, event_tag);
1217
+ const max_pending = takeByte(cmd, &at);
1218
+ _ = issueChannelOpen(fx, key_value, event_tag, max_pending);
1141
1219
  },
1142
1220
  // channel_close [op][key f64 LE]
1143
1221
  0x16 => {
@@ -1337,6 +1415,177 @@ pub fn TsCoreHost(comptime core: type) type {
1337
1415
  .max_line_bytes = if (max_line_bytes == 0) runtime_effects.max_effect_line_bytes else max_line_bytes,
1338
1416
  });
1339
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
+ },
1340
1589
  else => @panic("ts core host: unknown command wire record - the core and this runtime disagree on cmd_format_version"),
1341
1590
  }
1342
1591
  }
@@ -1352,6 +1601,24 @@ pub fn TsCoreHost(comptime core: type) type {
1352
1601
  return .{ .key = key, .ok_tag = ok_tag, .err_tag = err_tag };
1353
1602
  }
1354
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
+
1355
1622
  fn fetchMethod(wire: u8) std.http.Method {
1356
1623
  return switch (wire) {
1357
1624
  0 => .GET,
@@ -1926,22 +2193,23 @@ pub fn TsCoreHost(comptime core: type) type {
1926
2193
  fx: *Fx,
1927
2194
  key_value: f64,
1928
2195
  event_tag: u8,
1929
- ) void {
2196
+ max_pending: u8,
2197
+ ) bool {
1930
2198
  const representable = std.math.isFinite(key_value) and
1931
2199
  key_value >= 1 and key_value < 9007199254740992.0 and
1932
2200
  @floor(key_value) == key_value;
1933
2201
  if (!representable) {
1934
2202
  fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = 0, .kind = .rejected }));
1935
- return;
2203
+ return false;
1936
2204
  }
1937
2205
  const key: u64 = @intFromFloat(key_value);
1938
2206
  if (findChannel(key) != null) {
1939
2207
  fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = key, .kind = .rejected }));
1940
- return;
2208
+ return false;
1941
2209
  }
1942
2210
  const index = freeChannelIndex() orelse {
1943
2211
  fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = key, .kind = .rejected }));
1944
- return;
2212
+ return false;
1945
2213
  };
1946
2214
  const entry = &channels[index];
1947
2215
  entry.used = true;
@@ -1950,7 +2218,13 @@ pub fn TsCoreHost(comptime core: type) type {
1950
2218
  _ = fx.openChannel(.{
1951
2219
  .key = key,
1952
2220
  .on_event = channelEventMsg,
2221
+ .max_pending = max_pending,
1953
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;
1954
2228
  }
1955
2229
 
1956
2230
  fn findChannel(key: u64) ?usize {
@@ -2228,6 +2502,82 @@ pub fn TsCoreHost(comptime core: type) type {
2228
2502
  return msgFromTagPty(entry.event_tag, wire_key, false, event);
2229
2503
  }
2230
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
+
2231
2581
  /// The wire `cancel` record: first match wins across the four
2232
2582
  /// keyed tables — requests (silent drop), named engine ops
2233
2583
  /// (silent drop: the entry is marked dropped, the engine's
@@ -2241,8 +2591,13 @@ pub fn TsCoreHost(comptime core: type) type {
2241
2591
  fn cancelWireKey(fx: *Fx, key: []const u8) void {
2242
2592
  if (key.len == 0) return;
2243
2593
  if (findRequest(key)) |index| {
2594
+ const entry = requests[index];
2244
2595
  fx.cancelHostRequest(request_key_base + index);
2245
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
+ }
2246
2601
  return;
2247
2602
  }
2248
2603
  if (findEffect(key)) |index| {
@@ -2258,21 +2613,57 @@ pub fn TsCoreHost(comptime core: type) type {
2258
2613
  if (findDelay(key)) |index| {
2259
2614
  fx.cancelTimer(delay_key_base + index);
2260
2615
  delays[index].used = false;
2616
+ return;
2261
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;
2632
+ }
2633
+ }
2634
+
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;
2262
2641
  }
2263
2642
 
2264
- /// Issue (or replace) a routed request. Keyed requests reuse
2265
- /// their live table entry — re-routing the tags in place while
2266
- /// the engine replaces the in-flight call under the same engine
2267
- /// key. Unkeyed requests (`key.len == 0`) each take a fresh
2268
- /// entry: nothing can replace or cancel them.
2269
- fn issueRequest(fx: *Fx, name: []const u8, key: []const u8, ok_tag: u8, err_tag: u8, payload: []const u8) void {
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 {
2270
2654
  const index = blk: {
2271
2655
  if (key.len > 0) {
2272
- 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
+ }
2273
2661
  }
2274
- break :blk freeRequestIndex() orelse
2275
- @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;
2276
2667
  };
2277
2668
  const entry = &requests[index];
2278
2669
  entry.used = true;
@@ -2280,6 +2671,57 @@ pub fn TsCoreHost(comptime core: type) type {
2280
2671
  @memcpy(entry.key[0..key.len], key);
2281
2672
  entry.ok_tag = ok_tag;
2282
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
+ }
2283
2725
  fx.hostRequest(.{
2284
2726
  .key = request_key_base + index,
2285
2727
  .name = name,
@@ -2288,6 +2730,130 @@ pub fn TsCoreHost(comptime core: type) type {
2288
2730
  });
2289
2731
  }
2290
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
+
2291
2857
  fn findRequest(key: []const u8) ?usize {
2292
2858
  for (&requests, 0..) |*entry, index| {
2293
2859
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
@@ -2296,7 +2862,24 @@ pub fn TsCoreHost(comptime core: type) type {
2296
2862
  }
2297
2863
 
2298
2864
  fn freeRequestIndex() ?usize {
2299
- 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| {
2300
2883
  if (!entry.used) return index;
2301
2884
  }
2302
2885
  return null;
@@ -2317,6 +2900,15 @@ pub fn TsCoreHost(comptime core: type) type {
2317
2900
  }
2318
2901
  const entry = &requests[index];
2319
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);
2320
2912
  return msgFromTagBytes(if (result.ok) entry.ok_tag else entry.err_tag, result.bytes);
2321
2913
  }
2322
2914
 
@@ -2408,7 +3000,7 @@ pub fn TsCoreHost(comptime core: type) type {
2408
3000
  return msgFromTagNumber(delays[index].tag, ms);
2409
3001
  }
2410
3002
 
2411
- // ------------------------------------------ subscription timers
3003
+ // ----------------------------------------------- subscriptions
2412
3004
 
2413
3005
  /// Reconcile the declarative subscription set against the fixed
2414
3006
  /// timer table — the same algorithm as the @native-sdk/core package's
@@ -2416,73 +3008,167 @@ pub fn TsCoreHost(comptime core: type) type {
2416
3008
  /// keys into the first free slot, re-arm on interval change,
2417
3009
  /// re-route on tag change, cancel the missing. Slot order
2418
3010
  /// everywhere, so record/replay walk identical tables.
2419
- fn reconcileTimers(fx: *Fx) void {
3011
+ fn reconcileSubscriptions(fx: *Fx) void {
2420
3012
  if (comptime !has_subscriptions) return;
2421
3013
  const subs = core.subscriptions(model_root);
2422
- 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
+
2423
3029
  var at: usize = 0;
2424
3030
  while (at < subs.len) {
3031
+ const record_start = at;
2425
3032
  const op = takeByte(subs, &at);
2426
- if (op != 0x01) {
2427
- @panic("ts core host: unknown subscription wire record - the core and this runtime disagree on cmd_format_version");
2428
- }
2429
- // timer [op][key_len][key][every_ms f64 LE][msg_tag]
2430
- const key = takeShortBytes(subs, &at);
2431
- const every_bits = takeBytes(subs, &at, 8);
2432
- const every_ms: f64 = @bitCast(std.mem.readInt(u64, every_bits[0..8], .little));
2433
- const tag = takeByte(subs, &at);
2434
- if (!(every_ms >= 1) or !(every_ms <= 31_536_000_000.0)) {
2435
- // The lower bound also rejects NaN; the upper (one
2436
- // year) keeps the engine's ns conversion in range.
2437
- @panic("ts core host: Sub.timer interval must be between 1ms and one year");
2438
- }
2439
- var slot: ?usize = null;
2440
- for (&timers, 0..) |*entry, index| {
2441
- if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) slot = index;
2442
- }
2443
- if (slot) |index| {
2444
- seen[index] = true;
2445
- const entry = &timers[index];
2446
- if (entry.every_ms != every_ms) {
2447
- entry.every_ms = every_ms;
2448
- // Interval change re-arms: the engine replaces
2449
- // the active key in place and the platform timer
2450
- // restarts from now.
2451
- fx.startTimer(.{
2452
- .key = timer_key_base + index,
2453
- .interval_ms = intervalMs(every_ms),
2454
- .mode = .repeating,
2455
- .on_fire = timerFireMsg,
2456
- });
2457
- }
2458
- // A tag-only change re-routes without re-arming.
2459
- entry.tag = tag;
2460
- } else {
2461
- const index = freeTimerIndex() orelse
2462
- @panic("ts core host: more than 16 subscription timers - the timer table mirrors the engine's max_effect_timers");
2463
- seen[index] = true;
2464
- const entry = &timers[index];
2465
- entry.used = true;
2466
- entry.key_len = key.len;
2467
- @memcpy(entry.key[0..key.len], key);
2468
- entry.every_ms = every_ms;
2469
- entry.tag = tag;
2470
- fx.startTimer(.{
2471
- .key = timer_key_base + index,
2472
- .interval_ms = intervalMs(every_ms),
2473
- .mode = .repeating,
2474
- .on_fire = timerFireMsg,
2475
- });
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"),
2476
3127
  }
2477
3128
  }
2478
3129
  for (&timers, 0..) |*entry, index| {
2479
- if (entry.used and !seen[index]) {
3130
+ if (entry.used and !seen_timers[index]) {
2480
3131
  entry.used = false;
2481
3132
  fx.cancelTimer(timer_key_base + index);
2482
3133
  }
2483
3134
  }
2484
3135
  }
2485
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
+
2486
3172
  fn freeTimerIndex() ?usize {
2487
3173
  for (&timers, 0..) |*entry, index| {
2488
3174
  if (!entry.used) return index;
@@ -3135,6 +3821,16 @@ pub fn TsCoreHost(comptime core: type) type {
3135
3821
 
3136
3822
  // ------------------------------------------------- wire cursor
3137
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
+
3138
3834
  fn takeByte(bytes: []const u8, at: *usize) u8 {
3139
3835
  if (at.* >= bytes.len) @panic("ts core host: truncated wire record");
3140
3836
  const value = bytes[at.*];
@@ -3149,6 +3845,12 @@ pub fn TsCoreHost(comptime core: type) type {
3149
3845
  return slice;
3150
3846
  }
3151
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
+
3152
3854
  /// A one-byte-length-prefixed field (names and keys).
3153
3855
  fn takeShortBytes(bytes: []const u8, at: *usize) []const u8 {
3154
3856
  const len: usize = takeByte(bytes, at);