@native-sdk/cli 0.10.0 → 0.11.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 (465) hide show
  1. package/README.md +8 -6
  2. package/bin/native.js +2 -1
  3. package/build/app.zig +320 -60
  4. package/build/corewire.zig +53 -0
  5. package/build/test_shards.zig +49 -0
  6. package/build/ts_run.mjs +3 -3
  7. package/build.zig +1818 -87
  8. package/package.json +19 -14
  9. package/packages/core/compile-surface/core.ts +134 -72
  10. package/packages/core/package-lock.json +75 -357
  11. package/packages/core/package.json +25 -4
  12. package/packages/core/scripts/compiler_command.mjs +17 -12
  13. package/packages/core/scripts/compiler_typecheck.mjs +1 -0
  14. package/packages/core/scripts/gen_declarations.mjs +3 -2
  15. package/packages/core/scripts/gen_service_surface.mjs +22 -10
  16. package/packages/core/scripts/install_scriptc.mjs +182 -0
  17. package/packages/core/scripts/invoke_scriptc.mjs +18 -0
  18. package/packages/core/scripts/merge_static_archives.mjs +6 -1
  19. package/packages/core/scripts/npm_static_spike.mjs +2 -2
  20. package/packages/core/scripts/run_external_core_compiler.mjs +22 -10
  21. package/packages/core/scripts/run_external_service_compiler.mjs +15 -15
  22. package/packages/core/scripts/run_library_compiler.mjs +51 -0
  23. package/packages/core/scripts/run_native_tests.mjs +22 -0
  24. package/packages/core/scripts/scriptc-toolchain.json +101 -0
  25. package/packages/core/scripts/scriptc_toolchain.mjs +121 -0
  26. package/packages/core/scripts/stage_external_core.mjs +57 -1
  27. package/packages/core/scripts/surface_manifest_diff.mjs +19 -12
  28. package/packages/core/sdk/bytes.d.ts +2 -0
  29. package/packages/core/sdk/bytes.ts +86 -0
  30. package/packages/core/sdk/core.d.ts +308 -4
  31. package/packages/core/sdk/core.ts +320 -84
  32. package/packages/core/sdk/events.d.ts +247 -0
  33. package/packages/core/sdk/events.ts +230 -2
  34. package/packages/core/sdk/internal/image_identity.d.ts +7 -0
  35. package/packages/core/sdk/internal/image_identity.ts +71 -0
  36. package/packages/core/sdk/internal/markdown_policy.d.ts +5 -0
  37. package/packages/core/sdk/internal/markdown_policy.ts +878 -0
  38. package/packages/core/sdk/text.d.ts +27 -0
  39. package/packages/core/sdk/text.ts +206 -15
  40. package/packages/core/sdk/theme.d.ts +251 -0
  41. package/packages/core/sdk/theme.ts +267 -0
  42. package/packages/core/src/authorization.ts +137 -0
  43. package/packages/core/src/automation_commands.ts +201 -0
  44. package/packages/core/src/automation_interactions.ts +92 -0
  45. package/packages/core/src/bridge_descriptors.ts +104 -0
  46. package/packages/core/src/builtin_coordination.ts +172 -0
  47. package/packages/core/src/canvas_frame_coordination.ts +81 -0
  48. package/packages/core/src/canvas_presentation_lifecycle.ts +84 -0
  49. package/packages/core/src/canvas_scene_observation.ts +145 -0
  50. package/packages/core/src/chart_content.ts +161 -0
  51. package/packages/core/src/chart_plans.ts +432 -0
  52. package/packages/core/src/checker.ts +166 -19
  53. package/packages/core/src/code_content.ts +580 -0
  54. package/packages/core/src/command_coordination.ts +140 -0
  55. package/packages/core/src/component_composition.ts +94 -0
  56. package/packages/core/src/component_construction.ts +149 -0
  57. package/packages/core/src/contract.ts +25 -7
  58. package/packages/core/src/control_appearance.ts +232 -0
  59. package/packages/core/src/control_commands.ts +115 -0
  60. package/packages/core/src/control_content.ts +105 -0
  61. package/packages/core/src/control_geometry.ts +107 -0
  62. package/packages/core/src/control_payloads.ts +119 -0
  63. package/packages/core/src/control_primitives.ts +134 -0
  64. package/packages/core/src/devhost.ts +82 -7
  65. package/packages/core/src/devhost_journal.mjs +30 -7
  66. package/packages/core/src/effect_plans.ts +71 -0
  67. package/packages/core/src/flow_measurement.ts +121 -0
  68. package/packages/core/src/font_registry.ts +37 -0
  69. package/packages/core/src/glyph_atlas.ts +86 -0
  70. package/packages/core/src/gpu_packet_preparation.ts +130 -0
  71. package/packages/core/src/gpu_planning.ts +123 -0
  72. package/packages/core/src/gpu_presentation.ts +55 -0
  73. package/packages/core/src/host_flow.ts +89 -0
  74. package/packages/core/src/host_input_regions.ts +165 -0
  75. package/packages/core/src/image_registry.ts +66 -0
  76. package/packages/core/src/indicator_plans.ts +132 -0
  77. package/packages/core/src/infer.ts +150 -8
  78. package/packages/core/src/input_composition.ts +116 -0
  79. package/packages/core/src/intrinsic_measure.ts +100 -0
  80. package/packages/core/src/layout_coordination.ts +207 -0
  81. package/packages/core/src/leaf_plans.ts +134 -0
  82. package/packages/core/src/markup_development.ts +160 -0
  83. package/packages/core/src/measurement_coordination.ts +185 -0
  84. package/packages/core/src/modules.ts +1 -1
  85. package/packages/core/src/motion_sampling.ts +100 -0
  86. package/packages/core/src/paragraph_layout.ts +192 -0
  87. package/packages/core/src/portable_sources.json +74 -0
  88. package/packages/core/src/portable_sources.ts +17 -0
  89. package/packages/core/src/registered_font.ts +93 -0
  90. package/packages/core/src/render_animation_lifecycle.ts +128 -0
  91. package/packages/core/src/render_coordination.ts +170 -0
  92. package/packages/core/src/render_resources.ts +234 -0
  93. package/packages/core/src/runtime_policy.ts +3930 -0
  94. package/packages/core/src/scalar_text.ts +84 -0
  95. package/packages/core/src/service_contract.ts +2 -1
  96. package/packages/core/src/session_codecs.ts +309 -0
  97. package/packages/core/src/shell_admission.ts +126 -0
  98. package/packages/core/src/shell_coordination.ts +93 -0
  99. package/packages/core/src/sqlite_cli.ts +11 -0
  100. package/packages/core/src/status_validation.ts +232 -0
  101. package/packages/core/src/stream_policy.ts +63 -0
  102. package/packages/core/src/surface_recipes.ts +136 -0
  103. package/packages/core/src/system_admission.ts +60 -0
  104. package/packages/core/src/terminal_paint.ts +436 -0
  105. package/packages/core/src/text_document_width.ts +81 -0
  106. package/packages/core/src/text_measurement_cache.ts +69 -0
  107. package/packages/core/src/text_query_layout.ts +179 -0
  108. package/packages/core/src/text_run_layout.ts +410 -0
  109. package/packages/core/src/text_span_queries.ts +355 -0
  110. package/packages/core/src/typed_ast.ts +18 -1
  111. package/packages/core/src/types.ts +7 -5
  112. package/packages/core/src/vector_effects.ts +98 -0
  113. package/packages/core/src/vector_raster.ts +243 -0
  114. package/packages/core/src/view_components.ts +2415 -0
  115. package/packages/core/src/view_coordination.ts +198 -0
  116. package/packages/core/src/view_frontend.ts +980 -0
  117. package/packages/core/src/widget_audits.ts +202 -0
  118. package/packages/core/src/widget_changes.ts +258 -0
  119. package/packages/core/src/widget_metrics.ts +139 -0
  120. package/packages/core/src/widget_motion.ts +171 -0
  121. package/packages/core/src/widget_paint.ts +272 -0
  122. package/packages/core/src/widget_paint_walk.ts +203 -0
  123. package/packages/core/src/widget_presentation.ts +141 -0
  124. package/packages/core/src/widget_routing.ts +262 -0
  125. package/packages/core/src/window_lifecycle.ts +92 -0
  126. package/packages/core/testing/index.ts +430 -0
  127. package/schemas/app.schema.json +13 -0
  128. package/skill-data/core/SKILL.md +2 -2
  129. package/skill-data/core/references/web-engines-packaging-debugging.md +2 -1
  130. package/skill-data/native-ui/SKILL.md +76 -17
  131. package/skill-data/ts-core/SKILL.md +113 -9
  132. package/skill-data/ts-services/SKILL.md +1 -1
  133. package/skill-data/ts-services/references/service-surface.md +264 -144
  134. package/src/app_runner/root.zig +25 -12
  135. package/src/app_runner/ts_compiled_view.zig +1631 -0
  136. package/src/app_runner/ts_core_main.zig +143 -10
  137. package/src/app_runner/ts_core_mobile.zig +24 -12
  138. package/src/automation/server.zig +1 -3
  139. package/src/automation/snapshot.zig +9 -637
  140. package/src/automation/snapshot_reference.zig +656 -0
  141. package/src/automation/snapshot_serialization.zig +566 -0
  142. package/src/platform/linux/gtk_host.c +36 -24
  143. package/src/platform/linux/gtk_pixels.h +118 -0
  144. package/src/platform/linux/gtk_pixels_test.c +241 -0
  145. package/src/platform/linux/root.zig +2 -0
  146. package/src/platform/macos/appkit_host.m +188 -30
  147. package/src/platform/macos/pointer_motion_test.m +96 -0
  148. package/src/platform/macos/scroll_driver_test.m +105 -0
  149. package/src/platform/macos/spectrum_bins.h +34 -0
  150. package/src/platform/macos/spectrum_bins_test.c +56 -0
  151. package/src/platform/macos/text_keyboard_test.m +80 -0
  152. package/src/platform/macos/widget_focus_test.m +66 -0
  153. package/src/platform/null_platform.zig +26 -2
  154. package/src/platform/null_platform_tests.zig +13 -0
  155. package/src/platform/root.zig +1 -0
  156. package/src/platform/types.zig +13 -0
  157. package/src/platform/windows/root.zig +2 -0
  158. package/src/platform/windows/webview2_host.cpp +7 -2
  159. package/src/primitives/app_manifest/comptime_scene.zig +1 -1
  160. package/src/primitives/app_manifest/root.zig +2 -0
  161. package/src/primitives/app_manifest/tests.zig +4 -1
  162. package/src/primitives/app_manifest/validation.zig +2 -0
  163. package/src/primitives/canvas/a11y_audit.zig +3 -1
  164. package/src/primitives/canvas/canvas_frame_coordination_policy.zig +134 -0
  165. package/src/primitives/canvas/chart_content_policy.zig +75 -0
  166. package/src/primitives/canvas/chart_plan_policy.zig +196 -0
  167. package/src/primitives/canvas/code_content_policy.zig +162 -0
  168. package/src/primitives/canvas/commands.zig +29 -1
  169. package/src/primitives/canvas/component_composition.zig +125 -0
  170. package/src/primitives/canvas/component_composition_policy.zig +44 -0
  171. package/src/primitives/canvas/component_construction_policy.zig +187 -0
  172. package/src/primitives/canvas/container_layout_policy.zig +87 -0
  173. package/src/primitives/canvas/control_appearance_policy.zig +142 -0
  174. package/src/primitives/canvas/control_command_policy.zig +75 -0
  175. package/src/primitives/canvas/control_content_policy.zig +90 -0
  176. package/src/primitives/canvas/control_geometry_policy.zig +165 -0
  177. package/src/primitives/canvas/control_payload_policy.zig +48 -0
  178. package/src/primitives/canvas/control_primitive_policy.zig +129 -0
  179. package/src/primitives/canvas/effect_plan_policy.zig +96 -0
  180. package/src/primitives/canvas/events.zig +1027 -1
  181. package/src/primitives/canvas/flow_measurement_policy.zig +237 -0
  182. package/src/primitives/canvas/frame.zig +92 -23
  183. package/src/primitives/canvas/glyph_atlas_policy.zig +40 -0
  184. package/src/primitives/canvas/gpu.zig +10 -0
  185. package/src/primitives/canvas/gpu_packet_preparation_policy.zig +325 -0
  186. package/src/primitives/canvas/gpu_planning_policy.zig +364 -0
  187. package/src/primitives/canvas/gpu_presentation_policy.zig +74 -0
  188. package/src/primitives/canvas/grid_layout_policy.zig +51 -0
  189. package/src/primitives/canvas/indicator_plan_policy.zig +128 -0
  190. package/src/primitives/canvas/intrinsic_layout_policy.zig +87 -0
  191. package/src/primitives/canvas/intrinsic_measure_policy.zig +128 -0
  192. package/src/primitives/canvas/layout_audit.zig +5 -2
  193. package/src/primitives/canvas/layout_coordination_policy.zig +262 -0
  194. package/src/primitives/canvas/leaf_plan_policy.zig +117 -0
  195. package/src/primitives/canvas/markdown.zig +13 -3
  196. package/src/primitives/canvas/markdown_content_policy.zig +227 -0
  197. package/src/primitives/canvas/markdown_image_binding.zig +81 -0
  198. package/src/primitives/canvas/measurement_coordination_policy.zig +288 -0
  199. package/src/primitives/canvas/numeric_capabilities.zig +14 -0
  200. package/src/primitives/canvas/reference.zig +12 -6
  201. package/src/primitives/canvas/registered_font_policy.zig +152 -0
  202. package/src/primitives/canvas/render.zig +48 -0
  203. package/src/primitives/canvas/render_cache_policy.zig +184 -0
  204. package/src/primitives/canvas/render_coordination_policy.zig +163 -0
  205. package/src/primitives/canvas/render_damage_policy.zig +160 -0
  206. package/src/primitives/canvas/render_effects.zig +14 -0
  207. package/src/primitives/canvas/render_generic_resources.zig +14 -0
  208. package/src/primitives/canvas/render_images.zig +14 -0
  209. package/src/primitives/canvas/render_layers.zig +14 -0
  210. package/src/primitives/canvas/render_override_policy.zig +119 -0
  211. package/src/primitives/canvas/render_paths.zig +14 -0
  212. package/src/primitives/canvas/render_plan_policy.zig +199 -0
  213. package/src/primitives/canvas/render_resource_policy.zig +476 -0
  214. package/src/primitives/canvas/root.zig +100 -0
  215. package/src/primitives/canvas/semantic_tree_policy.zig +158 -0
  216. package/src/primitives/canvas/serialization.zig +8 -1
  217. package/src/primitives/canvas/surface_layout_policy.zig +36 -0
  218. package/src/primitives/canvas/surface_recipe_policy.zig +231 -0
  219. package/src/primitives/canvas/terminal_grid.zig +10 -696
  220. package/src/primitives/canvas/terminal_grid_reference.zig +709 -0
  221. package/src/primitives/canvas/terminal_paint_policy.zig +191 -0
  222. package/src/primitives/canvas/text.zig +1 -0
  223. package/src/primitives/canvas/text_atlas.zig +113 -0
  224. package/src/primitives/canvas/text_cache_policy.zig +94 -0
  225. package/src/primitives/canvas/text_document_policy.zig +120 -0
  226. package/src/primitives/canvas/text_layout.zig +51 -2
  227. package/src/primitives/canvas/text_layout_cache.zig +29 -0
  228. package/src/primitives/canvas/text_layout_hash.zig +1 -0
  229. package/src/primitives/canvas/text_layout_types.zig +3 -0
  230. package/src/primitives/canvas/text_measure_cache.zig +46 -0
  231. package/src/primitives/canvas/text_measurement_policy.zig +124 -0
  232. package/src/primitives/canvas/text_metrics.zig +23 -0
  233. package/src/primitives/canvas/text_query_policy.zig +156 -0
  234. package/src/primitives/canvas/text_run_policy.zig +252 -0
  235. package/src/primitives/canvas/text_scalar_policy.zig +156 -0
  236. package/src/primitives/canvas/text_span_query_policy.zig +232 -0
  237. package/src/primitives/canvas/text_spans.zig +280 -8
  238. package/src/primitives/canvas/text_tests.zig +10 -0
  239. package/src/primitives/canvas/tokens.zig +38 -0
  240. package/src/primitives/canvas/ui.zig +250 -83
  241. package/src/primitives/canvas/ui_markup.zig +139 -33
  242. package/src/primitives/canvas/ui_markup_compiled.zig +319 -59
  243. package/src/primitives/canvas/ui_markup_compiled_tests.zig +225 -0
  244. package/src/primitives/canvas/ui_markup_contract.zig +146 -14
  245. package/src/primitives/canvas/ui_markup_contract_tests.zig +77 -0
  246. package/src/primitives/canvas/ui_markup_reflect.zig +56 -0
  247. package/src/primitives/canvas/ui_markup_tests.zig +116 -0
  248. package/src/primitives/canvas/ui_markup_view.zig +258 -32
  249. package/src/primitives/canvas/ui_markup_view_tests.zig +142 -10
  250. package/src/primitives/canvas/ui_schema.zig +13 -1
  251. package/src/primitives/canvas/ui_schema_tests.zig +11 -7
  252. package/src/primitives/canvas/ui_tests.zig +1 -0
  253. package/src/primitives/canvas/vector.zig +36 -2
  254. package/src/primitives/canvas/vector_effect_policy.zig +236 -0
  255. package/src/primitives/canvas/vector_raster_policy.zig +190 -0
  256. package/src/primitives/canvas/virtual_extent_policy.zig +292 -0
  257. package/src/primitives/canvas/virtual_extents.zig +99 -3
  258. package/src/primitives/canvas/virtual_flow_policy.zig +108 -0
  259. package/src/primitives/canvas/widget_audit_policy.zig +293 -0
  260. package/src/primitives/canvas/widget_change_policy.zig +298 -0
  261. package/src/primitives/canvas/widget_invalidation.zig +113 -2
  262. package/src/primitives/canvas/widget_layout.zig +673 -128
  263. package/src/primitives/canvas/widget_layout_tests.zig +4 -0
  264. package/src/primitives/canvas/widget_metric_policy.zig +126 -0
  265. package/src/primitives/canvas/widget_metrics.zig +45 -6
  266. package/src/primitives/canvas/widget_paint_policy.zig +166 -0
  267. package/src/primitives/canvas/widget_paint_walk_policy.zig +252 -0
  268. package/src/primitives/canvas/widget_presentation_policy.zig +168 -0
  269. package/src/primitives/canvas/widget_render.zig +744 -74
  270. package/src/primitives/canvas/widget_render_controls.zig +1217 -133
  271. package/src/primitives/canvas/widget_render_scroll.zig +11 -3
  272. package/src/primitives/canvas/widget_render_style.zig +94 -0
  273. package/src/primitives/canvas/widget_render_surfaces.zig +61 -50
  274. package/src/primitives/canvas/widget_routing.zig +75 -0
  275. package/src/primitives/canvas/widget_routing_policy.zig +135 -0
  276. package/src/primitives/canvas/widget_runtime.zig +20 -1
  277. package/src/primitives/canvas/widget_semantics.zig +25 -0
  278. package/src/primitives/canvas/widget_text_input.zig +86 -23
  279. package/src/primitives/canvas/widget_text_select.zig +1 -0
  280. package/src/primitives/canvas/widget_tree.zig +8 -1
  281. package/src/primitives/canvas/widgets.zig +42 -12
  282. package/src/primitives/canvas/wrapped_layout_policy.zig +104 -0
  283. package/src/root.zig +21 -0
  284. package/src/runtime/accessibility_policy.zig +122 -0
  285. package/src/runtime/api.zig +28 -0
  286. package/src/runtime/app_dispatch_policy.zig +68 -0
  287. package/src/runtime/authorization_policy.zig +150 -0
  288. package/src/runtime/automation_command_policy.zig +241 -0
  289. package/src/runtime/automation_interaction_policy.zig +107 -0
  290. package/src/runtime/automation_snapshot.zig +52 -22
  291. package/src/runtime/automation_snapshot_reference.zig +290 -0
  292. package/src/runtime/automation_widget_dispatch.zig +267 -355
  293. package/src/runtime/automation_widget_dispatch_reference.zig +900 -0
  294. package/src/runtime/blob_policy.zig +58 -0
  295. package/src/runtime/blob_reference.zig +64 -0
  296. package/src/runtime/bridge_descriptor_policy.zig +206 -0
  297. package/src/runtime/builtin_bridge.zig +180 -44
  298. package/src/runtime/builtin_coordination_policy.zig +121 -0
  299. package/src/runtime/callback_policy_test_reference.zig +97 -0
  300. package/src/runtime/canvas_drag_policy.zig +94 -0
  301. package/src/runtime/canvas_fonts.zig +38 -10
  302. package/src/runtime/canvas_frame.zig +590 -134
  303. package/src/runtime/canvas_frame_helpers.zig +1 -0
  304. package/src/runtime/canvas_hover_policy.zig +131 -0
  305. package/src/runtime/canvas_images.zig +59 -30
  306. package/src/runtime/canvas_keyboard_focus_policy.zig +154 -0
  307. package/src/runtime/canvas_limits.zig +1 -1
  308. package/src/runtime/canvas_presentation_lifecycle_policy.zig +86 -0
  309. package/src/runtime/canvas_scene_observation_policy.zig +181 -0
  310. package/src/runtime/canvas_widget_context_menu.zig +4 -4
  311. package/src/runtime/canvas_widget_display.zig +110 -9
  312. package/src/runtime/canvas_widget_events.zig +718 -328
  313. package/src/runtime/canvas_widget_runtime.zig +437 -81
  314. package/src/runtime/canvas_widget_scroll_drivers.zig +39 -1
  315. package/src/runtime/canvas_widget_scroll_tests.zig +31 -0
  316. package/src/runtime/canvas_widget_state.zig +93 -56
  317. package/src/runtime/channel_sources.zig +80 -0
  318. package/src/runtime/command_policy.zig +161 -0
  319. package/src/runtime/component_policy.zig +83 -0
  320. package/src/runtime/core.zig +156 -6
  321. package/src/runtime/desktop_files.zig +189 -0
  322. package/src/runtime/effects.zig +466 -29
  323. package/src/runtime/effects_tests.zig +28 -0
  324. package/src/runtime/file_policy_test_reference.zig +113 -0
  325. package/src/runtime/flow.zig +418 -341
  326. package/src/runtime/flow_reference.zig +1426 -0
  327. package/src/runtime/font_registry_policy.zig +72 -0
  328. package/src/runtime/frame_profile.zig +24 -33
  329. package/src/runtime/gpu_surface_events.zig +97 -35
  330. package/src/runtime/host_event_pump.zig +303 -0
  331. package/src/runtime/host_event_pump_reference.zig +268 -0
  332. package/src/runtime/host_flow_policy.zig +155 -0
  333. package/src/runtime/host_input_regions_policy.zig +156 -0
  334. package/src/runtime/image_registry_policy.zig +94 -0
  335. package/src/runtime/input_composition_policy.zig +138 -0
  336. package/src/runtime/journal_policy.zig +66 -0
  337. package/src/runtime/journal_reference.zig +53 -0
  338. package/src/runtime/lifecycle_policy_test_reference.zig +97 -0
  339. package/src/runtime/markup_development_policy.zig +91 -0
  340. package/src/runtime/media_surface.zig +40 -1
  341. package/src/runtime/motion_sampling_policy.zig +159 -0
  342. package/src/runtime/recording_policy.zig +42 -0
  343. package/src/runtime/render_animation_policy.zig +206 -0
  344. package/src/runtime/replay_policy.zig +66 -0
  345. package/src/runtime/replay_policy_reference.zig +326 -0
  346. package/src/runtime/replay_progress_policy.zig +64 -0
  347. package/src/runtime/replay_progress_reference.zig +34 -0
  348. package/src/runtime/request_policy_test_reference.zig +188 -0
  349. package/src/runtime/root.zig +13 -0
  350. package/src/runtime/session_blobs.zig +157 -58
  351. package/src/runtime/session_blobs_reference.zig +692 -0
  352. package/src/runtime/session_codec.zig +361 -0
  353. package/src/runtime/session_codec_reference.zig +1027 -0
  354. package/src/runtime/session_journal.zig +246 -983
  355. package/src/runtime/session_record.zig +224 -45
  356. package/src/runtime/session_replay.zig +157 -415
  357. package/src/runtime/session_tests.zig +552 -0
  358. package/src/runtime/shell_admission_policy.zig +225 -0
  359. package/src/runtime/shell_coordination_policy.zig +138 -0
  360. package/src/runtime/shell_layout.zig +126 -1
  361. package/src/runtime/snapshot_policy.zig +60 -0
  362. package/src/runtime/snapshot_reference.zig +64 -0
  363. package/src/runtime/state.zig +16 -0
  364. package/src/runtime/status_validation.zig +190 -0
  365. package/src/runtime/system_admission_policy.zig +140 -0
  366. package/src/runtime/system_services.zig +46 -36
  367. package/src/runtime/tests.zig +1 -0
  368. package/src/runtime/ts_canvas_hooks.zig +261 -0
  369. package/src/runtime/ts_canvas_hooks_tests.zig +279 -0
  370. package/src/runtime/ts_canvas_icons.zig +234 -0
  371. package/src/runtime/ts_core_host.zig +2325 -411
  372. package/src/runtime/ts_core_host_tests.zig +1982 -0
  373. package/src/runtime/ts_test_host.zig +699 -0
  374. package/src/runtime/ts_ui_app.zig +1087 -45
  375. package/src/runtime/ui_app.zig +1117 -629
  376. package/src/runtime/ui_app_provenance.zig +147 -5
  377. package/src/runtime/ui_app_provenance_reference.zig +370 -0
  378. package/src/runtime/ui_app_tests.zig +619 -9
  379. package/src/runtime/ui_app_window_tests.zig +89 -0
  380. package/src/runtime/view.zig +25 -0
  381. package/src/runtime/view_canvas.zig +30 -6
  382. package/src/runtime/view_coordination_policy.zig +147 -0
  383. package/src/runtime/view_widget_control.zig +51 -14
  384. package/src/runtime/view_widget_scroll.zig +16 -5
  385. package/src/runtime/view_widget_text.zig +153 -68
  386. package/src/runtime/view_widget_tree.zig +460 -56
  387. package/src/runtime/webview_view_bridge_tests.zig +2 -0
  388. package/src/runtime/widget_motion_policy.zig +238 -0
  389. package/src/runtime/window_command_bridge_tests.zig +63 -0
  390. package/src/runtime/window_lifecycle_policy.zig +127 -0
  391. package/src/runtime/window_storage.zig +74 -8
  392. package/src/runtime/window_view_runtime.zig +148 -33
  393. package/src/runtime/window_views.zig +163 -10
  394. package/src/tooling/codesign.zig +125 -74
  395. package/src/tooling/components/identity_tests.zig +62 -36
  396. package/src/tooling/components/stepper.native +24 -0
  397. package/src/tooling/components/stepper.zig +0 -19
  398. package/src/tooling/components/timeline-item.native +22 -0
  399. package/src/tooling/components/timeline.native +5 -3
  400. package/src/tooling/components/timeline_item.zig +0 -32
  401. package/src/tooling/eject_components.zig +76 -8
  402. package/src/tooling/ios.zig +66 -12
  403. package/src/tooling/manifest.zig +35 -0
  404. package/src/tooling/package.zig +85 -1
  405. package/src/tooling/raw_manifest.zig +6 -0
  406. package/src/tooling/templates.zig +15 -3
  407. package/src/tooling/ts_core.zig +13 -3
  408. package/src/tooling/verbs.zig +22 -0
  409. package/tools/corewire/build_profile.mjs +54 -0
  410. package/tools/corewire/contract_intake.ts +303 -0
  411. package/tools/corewire/contract_intake.zig +82 -0
  412. package/tools/corewire/core.test.ts +166 -0
  413. package/tools/corewire/core_abi.zig +51 -0
  414. package/tools/corewire/core_cases.ts +233 -0
  415. package/tools/corewire/core_contract.ts +407 -0
  416. package/tools/corewire/core_emission.ts +136 -0
  417. package/tools/corewire/core_emission.zig +69 -0
  418. package/tools/corewire/core_goldens.json +3110 -0
  419. package/tools/corewire/core_policy.ts +14 -0
  420. package/tools/corewire/core_policy.zig +48 -0
  421. package/tools/corewire/core_projection.ts +360 -0
  422. package/tools/corewire/core_vocabulary.ts +6 -0
  423. package/tools/corewire/emit.zig +19 -1590
  424. package/tools/corewire/emit_facade.ts +714 -0
  425. package/tools/corewire/emit_facade.zig +10 -3752
  426. package/tools/corewire/emit_mirror.ts +290 -0
  427. package/tools/corewire/emit_profile.ts +50 -0
  428. package/tools/corewire/emit_service.ts +331 -0
  429. package/tools/corewire/emit_service.zig +23 -842
  430. package/tools/corewire/entry.test.ts +95 -0
  431. package/tools/corewire/entry_coordination.ts +127 -0
  432. package/tools/corewire/entry_coordination.zig +190 -0
  433. package/tools/corewire/facade_templates.ts +85 -0
  434. package/tools/corewire/filesystem.test.ts +166 -0
  435. package/tools/corewire/filesystem_coordination.ts +213 -0
  436. package/tools/corewire/filesystem_coordination.zig +245 -0
  437. package/tools/corewire/intake.test.ts +35 -0
  438. package/tools/corewire/intake_cases.ts +55 -0
  439. package/tools/corewire/intake_goldens.json +12237 -0
  440. package/tools/corewire/invocation.test.ts +24 -0
  441. package/tools/corewire/invocation.ts +175 -0
  442. package/tools/corewire/invocation.zig +136 -0
  443. package/tools/corewire/invocation_cases.ts +60 -0
  444. package/tools/corewire/invocation_fixture.ts +33 -0
  445. package/tools/corewire/invocation_goldens.json +1143 -0
  446. package/tools/corewire/invocation_tests.zig +111 -0
  447. package/tools/corewire/invocation_usage.ts +2 -0
  448. package/tools/corewire/lossless_projection.ts +96 -0
  449. package/tools/corewire/main.zig +7 -680
  450. package/tools/corewire/main_reference.zig +415 -0
  451. package/tools/corewire/mirror_templates.ts +55 -0
  452. package/tools/corewire/profile.test.ts +248 -0
  453. package/tools/corewire/profile.zig +56 -0
  454. package/tools/corewire/profile_emission.ts +202 -0
  455. package/tools/corewire/profile_library.json +29 -0
  456. package/tools/corewire/profile_tests.zig +136 -0
  457. package/tools/corewire/service.test.ts +75 -0
  458. package/tools/corewire/service_cases.ts +61 -0
  459. package/tools/corewire/service_contract.zig +40 -146
  460. package/tools/corewire/service_goldens.json +650 -0
  461. package/tools/corewire/service_projection.zig +52 -0
  462. package/tools/corewire/service_templates.ts +14 -0
  463. package/tools/corewire/shim_rt.zig +9 -0
  464. package/tools/corewire/sidecar.zig +267 -1438
  465. package/tools/corewire/emit_profile.zig +0 -521
@@ -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` 7) onto the real effect engine
3
+ //! emits (`cmd_format_version` 10) 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
@@ -166,7 +166,7 @@
166
166
  //! Image loads are not the string-keyed cancel's to
167
167
  //! end (they are keyed by numeric id, not a wire key)
168
168
  //! — `image_cancel` is their cancel.
169
- //! image_cancel-> `fx.cancel(id)` on the live load under the id, if
169
+ //! image_cancel-> `fx.cancelImage(id)` on the live load under the id, if
170
170
  //! any: the engine's `.cancelled` terminal routes the
171
171
  //! load's own event arm (state "cancelled") and
172
172
  //! retires the entry, freeing the id for a fresh load
@@ -457,8 +457,18 @@ pub const max_now_chain: usize = 64;
457
457
  pub const max_nows_per_cmd: usize = 16;
458
458
 
459
459
  pub fn TsCoreHost(comptime core: type) type {
460
+ return TsCoreHostWithRuntimeModel(core, false);
461
+ }
462
+
463
+ /// Compiled views use a stateless handle. Reference views retain the full
464
+ /// source model; commands, subscriptions and restoration share one bridge.
465
+ pub fn TsCoreHostWithRuntimeModel(comptime core: type, comptime compiled_model: bool) type {
466
+ const use_runtime_model = compiled_model and @hasDecl(core, "RuntimeModel");
460
467
  return struct {
461
- pub const Model = core.Model;
468
+ pub const Model = if (use_runtime_model) core.RuntimeModel else core.Model;
469
+ const initialModel = if (use_runtime_model) core.initialRuntimeModel else core.initialModel;
470
+ const updateModel = if (use_runtime_model) core.updateRuntimeModel else core.update;
471
+ const commitModel = if (use_runtime_model) core.commitRuntimeModel else core.commitModelRoot;
462
472
  pub const Msg = core.Msg;
463
473
  pub const Fx = runtime_effects.Effects(Msg);
464
474
 
@@ -473,9 +483,10 @@ pub fn TsCoreHost(comptime core: type) type {
473
483
 
474
484
  const msg_arms = @typeInfo(Msg).@"union".fields;
475
485
 
476
- const update_returns_cmd = @typeInfo(@TypeOf(core.update)).@"fn".return_type.? != *const Model;
477
- const init_returns_cmd = @typeInfo(@TypeOf(core.initialModel)).@"fn".return_type.? != *const Model;
486
+ const update_returns_cmd = @typeInfo(@TypeOf(updateModel)).@"fn".return_type.? != *const Model;
487
+ const init_returns_cmd = @typeInfo(@TypeOf(initialModel)).@"fn".return_type.? != *const Model;
478
488
  const has_subscriptions = @hasDecl(core, "subscriptions");
489
+ pub const environment_messages = if (@hasDecl(core, "envMsgs")) core.envMsgs else .{};
479
490
 
480
491
  /// One in-flight routed request: the wire key names it for
481
492
  /// replace/cancel, the tags route its terminal, and the table
@@ -525,6 +536,7 @@ pub fn TsCoreHost(comptime core: type) type {
525
536
  /// the engine's shared effect slots.
526
537
  const EffectEntry = struct {
527
538
  used: bool = false,
539
+ full_result: bool = false,
528
540
  dropped: bool = false,
529
541
  key_len: usize = 0,
530
542
  key: [max_wire_key_bytes]u8 = undefined,
@@ -541,6 +553,8 @@ pub fn TsCoreHost(comptime core: type) type {
541
553
  /// timer replaces in place under the same engine key).
542
554
  const DelayEntry = struct {
543
555
  used: bool = false,
556
+ full_result: bool = false,
557
+ mode: runtime_effects.TimerMode = .one_shot,
544
558
  key_len: usize = 0,
545
559
  key: [max_wire_key_bytes]u8 = undefined,
546
560
  tag: u8 = 0,
@@ -566,6 +580,7 @@ pub fn TsCoreHost(comptime core: type) type {
566
580
  exit_tag: u8 = 0,
567
581
  err_tag: u8 = 0,
568
582
  collect: bool = false,
583
+ complete_events: bool = false,
569
584
  /// Fetch lines are data records, so a cut or dropped line makes
570
585
  /// the eventual success terminal unusable. Spawn line mode keeps
571
586
  /// its existing best-effort contract.
@@ -672,6 +687,7 @@ pub fn TsCoreHost(comptime core: type) type {
672
687
  /// table.
673
688
  const PtyEntry = struct {
674
689
  used: bool = false,
690
+ bound: bool = false,
675
691
  key_len: usize = 0,
676
692
  key: [max_wire_key_bytes]u8 = undefined,
677
693
  event_tag: u8 = 0,
@@ -746,7 +762,24 @@ pub fn TsCoreHost(comptime core: type) type {
746
762
 
747
763
  /// A `now` record captured during the command walk, dispatched
748
764
  /// after the issuing cycle's frame reset.
749
- const PendingNow = struct { tag: u8, ms: i64 };
765
+ const ClipboardWriteEntry = struct {
766
+ used: bool = false,
767
+ key: [max_wire_key_bytes]u8 = undefined,
768
+ key_len: usize = 0,
769
+ tag: u8 = 0,
770
+ fn wireKey(self: *const ClipboardWriteEntry) []const u8 {
771
+ return self.key[0..self.key_len];
772
+ }
773
+ };
774
+ var clipboard_writes: [runtime_effects.max_effects]ClipboardWriteEntry = @splat(.{});
775
+ const clipboard_result_key_base: u64 = 0x5453_4352_0000_0000;
776
+
777
+ const PendingNow = union(enum) {
778
+ channel_source: struct { tag: u8, key: u64, state: runtime_effects.EffectChannelSourceState, bytes: [255]u8, len: u8 },
779
+ clock: struct { tag: u8, ms: i64 },
780
+ decimal_clock: struct { tag: u8, ms: i64 },
781
+ video: struct { tag: u8, snapshot: Fx.VideoSnapshot, key: [max_wire_key_bytes]u8, key_len: usize },
782
+ };
750
783
 
751
784
  // Bridge-refused dispatches (a spawn under a live wire key, an
752
785
  // image load or channel open under a duplicate live id/key, an
@@ -795,6 +828,7 @@ pub fn TsCoreHost(comptime core: type) type {
795
828
  effects_table = @splat(.{});
796
829
  delays = @splat(.{});
797
830
  streams = @splat(.{});
831
+ file_streams = @splat(.{});
798
832
  audio_entry = .{};
799
833
  video_entry = .{};
800
834
  images = @splat(.{});
@@ -803,11 +837,12 @@ pub fn TsCoreHost(comptime core: type) type {
803
837
  ptys = @splat(.{});
804
838
  dbs = @splat(.{});
805
839
  clip_write_counter = 0;
840
+ clipboard_writes = @splat(.{});
806
841
  audio_cache_dir_len = 0;
807
842
  image_cache_dir_len = 0;
808
843
  swallow_next_dispatch = false;
809
- const initial = core.initialModel();
810
- model_root = core.commitModelRoot(if (comptime init_returns_cmd) initial.model else initial);
844
+ const initial = initialModel();
845
+ model_root = commitModel(if (comptime init_returns_cmd) initial.model else initial);
811
846
  core.rt.frameReset();
812
847
  }
813
848
 
@@ -826,18 +861,24 @@ pub fn TsCoreHost(comptime core: type) type {
826
861
  }
827
862
 
828
863
  /// The committed model root (valid until the next dispatch).
829
- pub fn model() *const Model {
864
+ pub fn runtimeModel() *const Model {
830
865
  return model_root;
831
866
  }
832
867
 
833
- /// Replace the committed core model from canonical snapshot bytes and
834
- /// refresh the host mirror. Generated external cores expose the inverse
868
+ /// Complete source state for diagnostics and replay. Compiled apps
869
+ /// decode only here; returned roots follow the shim snapshot lifetime.
870
+ pub fn model() *const core.Model {
871
+ return if (comptime use_runtime_model) core.snapshotModel() else model_root;
872
+ }
873
+
874
+ /// Replace the committed core model from canonical snapshot bytes.
875
+ /// Reference mode refreshes its mirror; compiled mode keeps its handle. Generated external cores expose the inverse
835
876
  /// of `modelSnapshot`; hand-written test cores intentionally do not.
836
877
  pub fn restoreSnapshot(snapshot: []const u8) void {
837
878
  if (comptime !@hasDecl(core, "restoreModel")) {
838
879
  @panic("ts core host: this core exposes no restoreModel entry - regenerate it with core ABI version 2");
839
880
  } else {
840
- model_root = core.restoreModel(snapshot);
881
+ model_root = if (comptime use_runtime_model) core.restoreRuntimeModel(snapshot) else core.restoreModel(snapshot);
841
882
  }
842
883
  }
843
884
 
@@ -926,6 +967,20 @@ pub fn TsCoreHost(comptime core: type) type {
926
967
  dispatchDepth(fx, msg, 0);
927
968
  }
928
969
 
970
+ /// Commit a pure retained-control observation at the UiApp sync
971
+ /// boundary. Effects and subscriptions belong to normal dispatch.
972
+ pub fn syncControls(msg: Msg) void {
973
+ if (comptime update_returns_cmd) {
974
+ const result = updateModel(model_root, msg);
975
+ if (result.cmd.len != 0) @panic("sliderStateMsg must produce a state-only update without commands");
976
+ model_root = commitModel(result.model);
977
+ } else {
978
+ model_root = commitModel(updateModel(model_root, msg));
979
+ }
980
+ // The enclosing dispatch may already hold a frame-backed message
981
+ // (for example exact frame clocks). It owns the scratch reset.
982
+ }
983
+
929
984
  /// Drain every queued effect completion into the core — the
930
985
  /// bridge-shaped mirror of `UiApp.drainEffects`' loop. Hosts
931
986
  /// that embed the core without a UiApp call this on wake/frame.
@@ -944,11 +999,11 @@ pub fn TsCoreHost(comptime core: type) type {
944
999
  @panic("ts core host: more than 64 chained Cmd.now dispatches from one event - update is requesting timestamps in a loop");
945
1000
  }
946
1001
  if (comptime update_returns_cmd) {
947
- const result = core.update(model_root, msg);
948
- model_root = core.commitModelRoot(result.model);
1002
+ const result = updateModel(model_root, msg);
1003
+ model_root = commitModel(result.model);
949
1004
  finishCycle(fx, result.cmd, depth);
950
1005
  } else {
951
- model_root = core.commitModelRoot(core.update(model_root, msg));
1006
+ model_root = commitModel(updateModel(model_root, msg));
952
1007
  finishCycle(fx, "", depth);
953
1008
  }
954
1009
  }
@@ -967,14 +1022,20 @@ pub fn TsCoreHost(comptime core: type) type {
967
1022
  reconcileSubscriptions(fx);
968
1023
  fx.flushDbSubscriptions();
969
1024
  core.rt.frameReset();
970
- for (nows[0..now_count]) |pending| {
971
- dispatchDepth(fx, msgFromTagNumber(pending.tag, @floatFromInt(pending.ms)), depth + 1);
1025
+ for (nows[0..now_count]) |*pending| {
1026
+ const reply = switch (pending.*) {
1027
+ .channel_source => |*source| msgFromTagChannelSource(source.tag, .{ .key = source.key, .state = source.state, .bytes = source.bytes[0..source.len] }),
1028
+ .clock => |clock| msgFromTagNumber(clock.tag, @floatFromInt(clock.ms)),
1029
+ .decimal_clock => |clock| msgFromTagBytes(clock.tag, decimalFrame(clock.ms)),
1030
+ .video => |*video| msgFromVideoSnapshot(video.tag, video.snapshot, video.key[0..video.key_len]),
1031
+ };
1032
+ dispatchDepth(fx, reply, depth + 1);
972
1033
  }
973
1034
  }
974
1035
 
975
1036
  // ------------------------------------------------- command walk
976
1037
 
977
- /// Walk one command value (v3 wire format; batch is plain
1038
+ /// Walk one command value (generation 10; batch is plain
978
1039
  /// concatenation, the empty slice is `Cmd.none`).
979
1040
  fn runCmd(
980
1041
  fx: *Fx,
@@ -1000,7 +1061,7 @@ pub fn TsCoreHost(comptime core: type) type {
1000
1061
  }
1001
1062
  // The journaled clock read (replay pops the same
1002
1063
  // value), captured in record order.
1003
- nows[now_count.*] = .{ .tag = tag, .ms = fx.wallMs() };
1064
+ nows[now_count.*] = .{ .clock = .{ .tag = tag, .ms = fx.wallMs() } };
1004
1065
  now_count.* += 1;
1005
1066
  },
1006
1067
  // host [op][name_len][name][argc][argc * f64 LE]
@@ -1033,6 +1094,40 @@ pub fn TsCoreHost(comptime core: type) type {
1033
1094
  const key = takeShortBytes(cmd, &at);
1034
1095
  cancelWireKey(fx, key);
1035
1096
  },
1097
+ // Complete file terminals and exact journaled clocks.
1098
+ 0x37, 0x38, 0x3e, 0x3f => {
1099
+ const key = takeShortBytes(cmd, &at);
1100
+ const tag = takeByte(cmd, &at);
1101
+ const file_path = takeLongBytes(cmd, &at);
1102
+ const bytes = if (op == 0x38 or op == 0x3f) takeLongBytes(cmd, &at) else "";
1103
+ const file_op: runtime_effects.EffectFileOp = if (op == 0x38 or op == 0x3f) .write else .read;
1104
+ const index = allocEffectEntryWithFilePolicy(fx, .{ .key = key, .ok_tag = tag, .err_tag = tag }, file_op, op == 0x37 or op == 0x38) orelse continue;
1105
+ if (file_op == .read) fx.readFile(.{ .key = effect_key_base + index, .path = file_path, .on_result = completeFileResultMsg }) else fx.writeFile(.{ .key = effect_key_base + index, .path = file_path, .bytes = bytes, .on_result = completeFileResultMsg });
1106
+ },
1107
+ 0x39 => {
1108
+ const tag = takeByte(cmd, &at);
1109
+ if (now_count.* >= max_nows_per_cmd) @panic("ts core host: too many clock replies");
1110
+ nows[now_count.*] = .{ .decimal_clock = .{ .tag = tag, .ms = fx.wallMs() } };
1111
+ now_count.* += 1;
1112
+ },
1113
+ 0x40 => {
1114
+ const key = takeShortBytes(cmd, &at);
1115
+ const mode = takeByte(cmd, &at);
1116
+ if (mode > 1) @panic("ts core host: invalid timer mode");
1117
+ const decimal = takeLongBytes(cmd, &at);
1118
+ const tag = takeByte(cmd, &at);
1119
+ const exact = parseExactTimerInterval(decimal);
1120
+ const ms: f64 = if (exact) |value| @floatFromInt(value) else 0;
1121
+ armResultTimer(fx, key, ms, tag, if (mode == 1) .repeating else .one_shot, true);
1122
+ },
1123
+ 0x3A => {
1124
+ const key = takeShortBytes(cmd, &at);
1125
+ const mode = takeByte(cmd, &at);
1126
+ if (mode > 1) @panic("ts core host: invalid timer mode");
1127
+ const ms: f64 = @bitCast(std.mem.readInt(u64, takeBytes(cmd, &at, 8)[0..8], .little));
1128
+ const tag = takeByte(cmd, &at);
1129
+ armResultTimer(fx, key, ms, tag, if (mode == 1) .repeating else .one_shot, false);
1130
+ },
1036
1131
  // read_file [op][key_len][key][ok][err][path_len u32 LE][path]
1037
1132
  0x07 => {
1038
1133
  const head = takeRoutedHead(cmd, &at);
@@ -1124,7 +1219,7 @@ pub fn TsCoreHost(comptime core: type) type {
1124
1219
  // otherwise find this named op first and leave the
1125
1220
  // stream running. The live stream owns the key, so
1126
1221
  // reject the newcomer through its own err arm.
1127
- if (head.key.len > 0 and (findStream(head.key) != null or fileStreamOccupiesKey(head.key))) {
1222
+ if (head.key.len > 0 and (findStream(head.key) != null or reservedWireKeyOccupied(head.key))) {
1128
1223
  fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1129
1224
  } else {
1130
1225
  const effect_index = allocEffectEntry(fx, head) orelse continue;
@@ -1154,6 +1249,57 @@ pub fn TsCoreHost(comptime core: type) type {
1154
1249
  });
1155
1250
  clip_write_counter +%= 1;
1156
1251
  },
1252
+ // Complete spawn records; the legacy opcode remains unchanged.
1253
+ 0x46 => {
1254
+ const key = parseExactUnsigned(takeLongBytes(cmd, &at)) orelse
1255
+ @panic("ts core host: invalid exact subprocess identity");
1256
+ const line_tag = takeByte(cmd, &at);
1257
+ const exit_tag = takeByte(cmd, &at);
1258
+ const mode = takeByte(cmd, &at);
1259
+ const argc = takeByte(cmd, &at);
1260
+ if (mode > 1) @panic("ts core host: invalid exact subprocess output mode");
1261
+ var argv: [runtime_effects.max_effect_argv][]const u8 = undefined;
1262
+ for (0..argc) |i| {
1263
+ const arg = takeLongBytes(cmd, &at);
1264
+ if (i < argv.len) argv[i] = arg;
1265
+ }
1266
+ const stdin = takeLongBytes(cmd, &at);
1267
+ // An over-capacity argv is a native rejected request.
1268
+ const retained = if (argc <= argv.len) argv[0..argc] else &.{};
1269
+ issueSpawnExact(fx, key, line_tag, exit_tag, mode == 1, retained, stdin);
1270
+ },
1271
+ 0x47 => fx.cancel(parseExactUnsigned(takeLongBytes(cmd, &at)) orelse
1272
+ @panic("ts core host: invalid exact cancellation identity")),
1273
+ 0x33 => {
1274
+ const key = takeShortBytes(cmd, &at);
1275
+ const line_tag = takeByte(cmd, &at);
1276
+ const exit_tag = takeByte(cmd, &at);
1277
+ const mode = takeByte(cmd, &at);
1278
+ const argc = takeByte(cmd, &at);
1279
+ if (mode > 1 or argc == 0 or argc > runtime_effects.max_effect_argv) @panic("ts core host: invalid complete spawn wire record");
1280
+ var argv: [runtime_effects.max_effect_argv][]const u8 = undefined;
1281
+ for (0..argc) |i| argv[i] = takeLongBytes(cmd, &at);
1282
+ const stdin = takeLongBytes(cmd, &at);
1283
+ issueSpawn(fx, .{ .key = key, .line_tag = line_tag, .exit_tag = exit_tag, .err_tag = exit_tag, .complete_events = true }, mode == 1, argv[0..argc], stdin);
1284
+ },
1285
+ // Routed write completion, including rejection and cancellation.
1286
+ 0x34 => {
1287
+ const key = takeShortBytes(cmd, &at);
1288
+ const tag = takeByte(cmd, &at);
1289
+ const bytes = takeLongBytes(cmd, &at);
1290
+ issueClipboardWrite(fx, key, tag, bytes);
1291
+ },
1292
+ // Capture now; reply after resetting the ABI result arena, in
1293
+ // command order like Cmd.now. No intervening host turn occurs.
1294
+ 0x35 => {
1295
+ const tag = takeByte(cmd, &at);
1296
+ if (now_count.* >= max_nows_per_cmd) @panic("ts core host: over 16 immediate capability replies in one command");
1297
+ const snapshot = fx.videoSnapshot();
1298
+ const key = if (video_entry.used and fx.videoOwnerToken() == video_entry.token) video_entry.wireKey() else "";
1299
+ nows[now_count.*] = .{ .video = .{ .tag = tag, .snapshot = snapshot, .key = undefined, .key_len = key.len } };
1300
+ @memcpy(nows[now_count.*].video.key[0..key.len], key);
1301
+ now_count.* += 1;
1302
+ },
1157
1303
  // clip_read [op][key_len][key][ok][err]
1158
1304
  0x0B => {
1159
1305
  const head = takeRoutedHead(cmd, &at);
@@ -1169,10 +1315,12 @@ pub fn TsCoreHost(comptime core: type) type {
1169
1315
  const after_bits = takeBytes(cmd, &at, 8);
1170
1316
  const after_ms: f64 = @bitCast(std.mem.readInt(u64, after_bits[0..8], .little));
1171
1317
  const tag = takeByte(cmd, &at);
1172
- if (!(after_ms >= 1) or !(after_ms <= 31_536_000_000.0)) {
1173
- // Same bound as Sub.timer: the lower rejects NaN,
1174
- // the upper (one year) keeps ns conversion in range.
1175
- @panic("ts core host: Cmd.delay interval must be between 1ms and one year");
1318
+ if (comptime !@hasDecl(core, "nativeTimerPolicy")) {
1319
+ if (!(after_ms >= 1) or !(after_ms <= 31_536_000_000.0)) {
1320
+ // Same bound as Sub.timer: the lower rejects NaN,
1321
+ // the upper (one year) keeps ns conversion in range.
1322
+ @panic("ts core host: Cmd.delay interval must be between 1ms and one year");
1323
+ }
1176
1324
  }
1177
1325
  armDelay(fx, key, after_ms, tag);
1178
1326
  },
@@ -1208,27 +1356,7 @@ pub fn TsCoreHost(comptime core: type) type {
1208
1356
  const cache_path = takeLongBytes(cmd, &at);
1209
1357
  const expected_bits = takeBytes(cmd, &at, 8);
1210
1358
  const expected: f64 = @bitCast(std.mem.readInt(u64, expected_bits[0..8], .little));
1211
- // One player is the whole surface: a new play
1212
- // re-keys and re-routes the single entry in place,
1213
- // exactly as the engine replaces its channel.
1214
- audio_entry.used = true;
1215
- audio_entry.key_len = key.len;
1216
- @memcpy(audio_entry.key[0..key.len], key);
1217
- audio_entry.event_tag = event_tag;
1218
- fx.playAudio(.{
1219
- .key = audio_key_base,
1220
- .path = audio_path,
1221
- .url = url,
1222
- .cache_path = effectiveAudioCachePath(cache_path, url),
1223
- // The wire carries the app's number; anything
1224
- // that is not a representable byte count means
1225
- // "unknown size" (0), the engine's own default.
1226
- .expected_bytes = if (expected >= 1 and expected <= 9007199254740992.0)
1227
- @intFromFloat(expected)
1228
- else
1229
- 0,
1230
- .on_event = audioEventMsg,
1231
- });
1359
+ issueAudioPlay(fx, key, event_tag, audio_path, url, cache_path, expected);
1232
1360
  },
1233
1361
  // audio_ctl [op][key_len][key][verb u8][value f64 LE]
1234
1362
  0x0F => {
@@ -1238,13 +1366,72 @@ pub fn TsCoreHost(comptime core: type) type {
1238
1366
  const value: f64 = @bitCast(std.mem.readInt(u64, value_bits[0..8], .little));
1239
1367
  runAudioCtl(fx, key, verb, value);
1240
1368
  },
1369
+ // Exact audio: decimal key, load-owned route, source and cache facts.
1370
+ 0x42 => {
1371
+ const key = parseExactUnsigned(takeLongBytes(cmd, &at)) orelse
1372
+ @panic("ts core host: invalid exact audio identity");
1373
+ const tag = takeByte(cmd, &at);
1374
+ const audio_path = takeLongBytes(cmd, &at);
1375
+ const url = takeLongBytes(cmd, &at);
1376
+ const cache_path = takeLongBytes(cmd, &at);
1377
+ const cache_dir = takeLongBytes(cmd, &at);
1378
+ const expected_bits = takeBytes(cmd, &at, 8);
1379
+ const expected: f64 = @bitCast(std.mem.readInt(u64, expected_bits[0..8], .little));
1380
+ issueAudioPlayExact(fx, key, tag, audio_path, url, cache_path, cache_dir, expected);
1381
+ },
1382
+ // Single-player transport. Seek retains the native u64 range.
1383
+ 0x43 => switch (takeByte(cmd, &at)) {
1384
+ 0 => fx.pauseAudio(),
1385
+ 1 => fx.resumeAudio(),
1386
+ 2 => {
1387
+ audio_entry.used = false;
1388
+ fx.stopAudio();
1389
+ },
1390
+ 3 => fx.seekAudio(parseExactUnsigned(takeLongBytes(cmd, &at)) orelse
1391
+ @panic("ts core host: invalid exact audio seek position")),
1392
+ 4 => {
1393
+ const bits = takeBytes(cmd, &at, 8);
1394
+ const value: f64 = @bitCast(std.mem.readInt(u64, bits[0..8], .little));
1395
+ if (!std.math.isFinite(value) or @abs(value) > std.math.floatMax(f32))
1396
+ @panic("ts core host: invalid audio volume");
1397
+ fx.setAudioVolume(@floatCast(value));
1398
+ },
1399
+ else => @panic("ts core host: invalid audio transport verb"),
1400
+ },
1241
1401
  // window_show [op][label_len][label]
1242
1402
  0x10 => {
1243
1403
  const label = takeShortBytes(cmd, &at);
1244
1404
  fx.showWindow(label);
1245
1405
  },
1406
+ // Native close/minimize preserve the ordinary window policy.
1407
+ 0x44 => fx.closeWindow(takeShortBytes(cmd, &at)),
1408
+ 0x45 => fx.minimizeWindow(takeShortBytes(cmd, &at)),
1246
1409
  // quit_app [op]
1247
1410
  0x11 => fx.quitApp(),
1411
+ // Lossless identity: two unsigned little-endian words.
1412
+ 0x3b => {
1413
+ const id_bytes = takeBytes(cmd, &at, 8);
1414
+ const id = std.mem.readInt(u64, id_bytes[0..8], .little);
1415
+ const tag = takeByte(cmd, &at);
1416
+ const image_path = takeLongBytes(cmd, &at);
1417
+ const url = takeLongBytes(cmd, &at);
1418
+ const cache = takeLongBytes(cmd, &at);
1419
+ const expected_bytes = takeBytes(cmd, &at, 8);
1420
+ const expected: f64 = @bitCast(std.mem.readInt(u64, expected_bytes[0..8], .little));
1421
+ issueImageLoadWords(fx, id, tag, image_path, url, cache, expected);
1422
+ },
1423
+ 0x3c, 0x3d => {
1424
+ const id_bytes = takeBytes(cmd, &at, 8);
1425
+ const id = std.mem.readInt(u64, id_bytes[0..8], .little);
1426
+ const table: []const ImageEntry = if (op == 0x3c) &images else &.{};
1427
+ const plan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
1428
+ compiledMediaIdentityPlan(0, 4, id, 0, 0, .microphone, 0, 0, 0, table, true)
1429
+ else
1430
+ MediaPlan{ .valid = imageWordIdValid(id), .slot = findImage(id), .key = id, .tag = 0, .retire = false, .expected_bytes = 0, .source = .microphone, .sample_rate = 0, .capture_channels = 0 };
1431
+ if (op == 0x3c) {
1432
+ if (plan.valid and plan.slot != null) fx.cancelImage(plan.key);
1433
+ } else if (plan.valid) _ = fx.unregisterImage(plan.key);
1434
+ },
1248
1435
  // image_load [op][id f64 LE][event_tag]
1249
1436
  // [path_len u32 LE][path][url_len u32 LE][url]
1250
1437
  // [cache_len u32 LE][cache][expected f64 LE]
@@ -1279,6 +1466,26 @@ pub fn TsCoreHost(comptime core: type) type {
1279
1466
  const max_pending = takeByte(cmd, &at);
1280
1467
  _ = issueChannelOpen(fx, key_value, event_tag, max_pending);
1281
1468
  },
1469
+ // channel_open_source [op][key f64 LE][event_tag][started_tag]
1470
+ // [max_pending][source short][payload long]
1471
+ 0x41 => {
1472
+ const key_bits = takeBytes(cmd, &at, 8);
1473
+ const key_value: f64 = @bitCast(std.mem.readInt(u64, key_bits[0..8], .little));
1474
+ const event_tag = takeByte(cmd, &at);
1475
+ const started_tag = takeByte(cmd, &at);
1476
+ const max_pending = takeByte(cmd, &at);
1477
+ const name = takeShortBytes(cmd, &at);
1478
+ const payload = takeLongBytes(cmd, &at);
1479
+ if (name.len == 0 or payload.len > runtime_effects.max_channel_source_payload or now_count.* >= max_nows_per_cmd)
1480
+ @panic("ts core host: invalid channel source command");
1481
+ const accepted = issueChannelOpen(fx, key_value, event_tag, max_pending);
1482
+ const key: u64 = if (std.math.isFinite(key_value) and key_value >= 1 and key_value < 9007199254740992.0 and @floor(key_value) == key_value) @intFromFloat(key_value) else 0;
1483
+ const result = fx.startChannelSource(key, if (accepted) fx.channelHandle(key) else null, name, payload);
1484
+ const pending = &nows[now_count.*];
1485
+ pending.* = .{ .channel_source = .{ .tag = started_tag, .key = key, .state = result.state, .bytes = undefined, .len = @intCast(result.bytes.len) } };
1486
+ @memcpy(pending.channel_source.bytes[0..result.bytes.len], result.bytes);
1487
+ now_count.* += 1;
1488
+ },
1282
1489
  // channel_close [op][key f64 LE]
1283
1490
  0x16 => {
1284
1491
  const key_bits = takeBytes(cmd, &at, 8);
@@ -1296,58 +1503,7 @@ pub fn TsCoreHost(comptime core: type) type {
1296
1503
  const video_path = takeLongBytes(cmd, &at);
1297
1504
  const url = takeLongBytes(cmd, &at);
1298
1505
  const flags = takeByte(cmd, &at);
1299
- const options: Fx.LoadVideoOptions = .{
1300
- // The tag rides the key's low byte so every
1301
- // event routes the arm of the load that
1302
- // produced it (see `videoKeyForTag`).
1303
- .key = videoKeyForTag(event_tag),
1304
- // The wire carries the app's number; a surface
1305
- // that is not an exactly-carried positive
1306
- // integer (0, negatives, fractions, 2^53 and
1307
- // past — the image id bound) reaches the engine
1308
- // as 0, which the validation refuses with one
1309
- // `.rejected` event — never silent.
1310
- .surface = if (surface >= 1 and surface < 9007199254740992.0 and @floor(surface) == surface)
1311
- @intFromFloat(surface)
1312
- else
1313
- 0,
1314
- .path = video_path,
1315
- .url = url,
1316
- .autoplay = (flags & 0x01) != 0,
1317
- .loop = (flags & 0x02) != 0,
1318
- .muted = (flags & 0x04) != 0,
1319
- .on_event = videoEventMsg,
1320
- };
1321
- // A load the engine's own deterministic gates
1322
- // would refuse must not commit the routing
1323
- // entry: the engine keeps the CURRENT playback
1324
- // on a rejected load, so re-keying first would
1325
- // route the surviving stream's events and verbs
1326
- // through the refused load's key and arm. Stage
1327
- // the rejection to the refused arm directly
1328
- // (the channel-admission precedent) and leave
1329
- // the entry — and the engine — untouched.
1330
- if (Fx.videoLoadRejected(options)) {
1331
- fx.stageLoopMsg(msgFromTagVideo(event_tag, .{
1332
- .key = videoKeyForTag(event_tag),
1333
- .kind = .rejected,
1334
- }));
1335
- } else {
1336
- // One player is the whole surface: an
1337
- // accepted load re-keys and re-routes the
1338
- // single entry in place, exactly as the
1339
- // engine replaces its channel.
1340
- video_entry.used = true;
1341
- video_entry.key_len = key.len;
1342
- @memcpy(video_entry.key[0..key.len], key);
1343
- video_entry.event_tag = event_tag;
1344
- fx.loadVideo(options);
1345
- // The identity this load minted (valid even
1346
- // when a synchronous refusal already reset
1347
- // the channel): the entry's verbs prove
1348
- // ownership against it.
1349
- video_entry.token = fx.videoMintedToken();
1350
- }
1506
+ issueVideoLoad(fx, key, event_tag, surface, video_path, url, flags);
1351
1507
  },
1352
1508
  // video_ctl [op][key_len][key][verb u8][value f64 LE]
1353
1509
  0x18 => {
@@ -1720,22 +1876,44 @@ pub fn TsCoreHost(comptime core: type) type {
1720
1876
  /// flight either (a dropped entry holds its slot only until
1721
1877
  /// its `.cancelled` terminal drains).
1722
1878
  fn allocEffectEntry(fx: *Fx, head: RoutedHead) ?u64 {
1723
- if (head.key.len > 0) {
1724
- if (fileStreamOccupiesKey(head.key)) {
1725
- fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1879
+ return allocEffectEntryWithFileResult(fx, head, null);
1880
+ }
1881
+ fn allocEffectEntryWithFileResult(fx: *Fx, head: RoutedHead, file_op: ?runtime_effects.EffectFileOp) ?u64 {
1882
+ return allocEffectEntryWithFilePolicy(fx, head, file_op, true);
1883
+ }
1884
+ fn allocEffectEntryWithFilePolicy(fx: *Fx, head: RoutedHead, file_op: ?runtime_effects.EffectFileOp, replace: bool) ?u64 {
1885
+ const blocked = (!replace and head.key.len > 0 and findEffect(head.key) != null) or head.key.len > 0 and (reservedWireKeyOccupiedExcept(head.key, .effect) or (file_op != null and (findRequest(head.key) != null or findStream(head.key) != null or findDelay(head.key) != null or findPty(head.key) != null or findDb(head.key) != null)));
1886
+ const plan = if (comptime @hasDecl(core, "nativeEffectPolicy")) compiledEffectDeclaration(head, blocked) else blk: {
1887
+ break :blk EffectPlan{
1888
+ .admitted = !blocked,
1889
+ .slot = if (blocked) null else freeEffectIndex(),
1890
+ .drop = if (blocked or head.key.len == 0) null else findEffect(head.key),
1891
+ .ok_tag = head.ok_tag,
1892
+ .err_tag = head.err_tag,
1893
+ };
1894
+ };
1895
+ if (!plan.admitted) {
1896
+ if (file_op) |operation| stageFileRejected(fx, head, operation) else fx.stageLoopMsg(msgFromTagStaticBytes(plan.err_tag, "rejected"));
1897
+ return null;
1898
+ }
1899
+ // A dropped predecessor remains occupied until its terminal drains.
1900
+ // Preserve the reference order even when no free slot is available.
1901
+ if (plan.drop) |existing| dropEffectEntry(fx, existing);
1902
+ const index = plan.slot orelse {
1903
+ if (file_op) |operation| {
1904
+ stageFileRejected(fx, head, operation);
1726
1905
  return null;
1727
1906
  }
1728
- if (findEffect(head.key)) |existing| dropEffectEntry(fx, existing);
1729
- }
1730
- const index = freeEffectIndex() orelse
1731
1907
  @panic("ts core host: more than 16 named engine ops in flight - the op table mirrors the engine's max_effects slots");
1908
+ };
1732
1909
  const entry = &effects_table[index];
1733
1910
  entry.used = true;
1734
1911
  entry.dropped = false;
1912
+ entry.full_result = file_op != null;
1735
1913
  entry.key_len = head.key.len;
1736
1914
  @memcpy(entry.key[0..head.key.len], head.key);
1737
- entry.ok_tag = head.ok_tag;
1738
- entry.err_tag = head.err_tag;
1915
+ entry.ok_tag = plan.ok_tag;
1916
+ entry.err_tag = plan.err_tag;
1739
1917
  return index;
1740
1918
  }
1741
1919
 
@@ -1745,12 +1923,13 @@ pub fn TsCoreHost(comptime core: type) type {
1745
1923
  /// the entry through the result callback, which swallows it.
1746
1924
  fn dropEffectEntry(fx: *Fx, index: usize) void {
1747
1925
  effects_table[index].dropped = true;
1748
- fx.cancel(effect_key_base + index);
1926
+ fx.cancelNonImage(effect_key_base + index);
1749
1927
  }
1750
1928
 
1751
1929
  /// A dropped entry's key is dead to lookup: reissuing it is a
1752
1930
  /// fresh effect, and cancel aimed at it finds nothing.
1753
1931
  fn findEffect(key: []const u8) ?usize {
1932
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) return compiledEffectLookup(key);
1754
1933
  for (&effects_table, 0..) |*entry, index| {
1755
1934
  if (entry.used and !entry.dropped and std.mem.eql(u8, entry.wireKey(), key)) return index;
1756
1935
  }
@@ -1764,6 +1943,67 @@ pub fn TsCoreHost(comptime core: type) type {
1764
1943
  return null;
1765
1944
  }
1766
1945
 
1946
+ const EffectPlan = struct { admitted: bool, slot: ?usize, drop: ?usize, ok_tag: u8, err_tag: u8 };
1947
+ const max_effect_policy_bytes = 5 + max_wire_key_bytes + 16 * (5 + max_wire_key_bytes);
1948
+
1949
+ fn writeEffectTable(request: []u8, start: usize) usize {
1950
+ var at = start;
1951
+ for (&effects_table) |*entry| {
1952
+ request[at] = @intFromBool(entry.used);
1953
+ request[at + 1] = @intFromBool(entry.dropped);
1954
+ request[at + 2] = @intCast(entry.key_len);
1955
+ @memcpy(request[at + 3 ..][0..entry.key_len], entry.wireKey());
1956
+ at += 3 + entry.key_len;
1957
+ request[at] = entry.ok_tag;
1958
+ request[at + 1] = entry.err_tag;
1959
+ at += 2;
1960
+ }
1961
+ return at;
1962
+ }
1963
+
1964
+ fn compiledEffectDeclaration(head: RoutedHead, blocked: bool) EffectPlan {
1965
+ var request: [max_effect_policy_bytes]u8 = undefined;
1966
+ request[0] = 0;
1967
+ request[1] = @intCast(head.key.len);
1968
+ @memcpy(request[2..][0..head.key.len], head.key);
1969
+ const at = 2 + head.key.len;
1970
+ request[at] = @intFromBool(blocked);
1971
+ request[at + 1] = head.ok_tag;
1972
+ request[at + 2] = head.err_tag;
1973
+ const end = writeEffectTable(&request, at + 3);
1974
+ var result: [5]u8 = undefined;
1975
+ if (core.nativeEffectPolicy(request[0..end], &result) != result.len or result[0] > 1)
1976
+ @panic("ts core host: invalid compiled effect declaration result");
1977
+ const slot: ?usize = if (result[1] == 255) null else result[1];
1978
+ const drop: ?usize = if (result[2] == 255) null else result[2];
1979
+ if (slot) |index| {
1980
+ if (index >= effects_table.len or effects_table[index].used)
1981
+ @panic("ts core host: invalid compiled effect allocation slot");
1982
+ }
1983
+ if (drop) |index| {
1984
+ if (index >= effects_table.len or !effects_table[index].used or effects_table[index].dropped)
1985
+ @panic("ts core host: invalid compiled effect predecessor slot");
1986
+ }
1987
+ if (result[0] == 0 and (slot != null or drop != null))
1988
+ @panic("ts core host: rejected effect declaration contains live slots");
1989
+ return .{ .admitted = result[0] == 1, .slot = slot, .drop = drop, .ok_tag = result[3], .err_tag = result[4] };
1990
+ }
1991
+
1992
+ fn compiledEffectLookup(key: []const u8) ?usize {
1993
+ var request: [max_effect_policy_bytes]u8 = undefined;
1994
+ request[0] = 1;
1995
+ request[1] = @intCast(key.len);
1996
+ @memcpy(request[2..][0..key.len], key);
1997
+ const end = writeEffectTable(&request, 2 + key.len);
1998
+ var result: [1]u8 = undefined;
1999
+ if (core.nativeEffectPolicy(request[0..end], &result) != result.len)
2000
+ @panic("ts core host: invalid compiled effect lookup result");
2001
+ if (result[0] == 255) return null;
2002
+ if (result[0] >= effects_table.len or !effects_table[result[0]].used or effects_table[result[0]].dropped)
2003
+ @panic("ts core host: invalid compiled effect lookup slot");
2004
+ return result[0];
2005
+ }
2006
+
1767
2007
  /// Arm (or re-arm) a one-shot delay. A live wire key reuses its
1768
2008
  /// slot: the engine timer replaces in place under the same
1769
2009
  /// engine key and restarts from now — the debounce discipline.
@@ -1771,28 +2011,33 @@ pub fn TsCoreHost(comptime core: type) type {
1771
2011
  // A delay has no err arm. Preserve an incumbent file stream and
1772
2012
  // fail closed instead of creating a second owner that Cmd.cancel
1773
2013
  // could not address unambiguously.
1774
- if (fileStreamOccupiesKey(key)) return;
1775
- const index = blk: {
1776
- if (key.len > 0) {
1777
- if (findDelay(key)) |existing| break :blk existing;
1778
- }
1779
- break :blk freeDelayIndex() orelse
1780
- @panic("ts core host: more than 16 armed delays - the delay table mirrors the engine's max_effect_timers");
2014
+ const plan: DelayPlan = if (comptime @hasDecl(core, "nativeTimerPolicy")) compiledDelayDeclaration(key, after_ms, tag, reservedWireKeyOccupiedExcept(key, .delay), false) orelse return else blk: {
2015
+ if (reservedWireKeyOccupiedExcept(key, .delay)) return;
2016
+ const index = if (key.len > 0) findDelay(key) orelse freeDelayIndex() else freeDelayIndex();
2017
+ break :blk .{
2018
+ .slot = index orelse @panic("ts core host: more than 16 armed delays - the delay table mirrors the engine's max_effect_timers"),
2019
+ .tag = tag,
2020
+ .interval_ms = intervalMs(after_ms),
2021
+ };
1781
2022
  };
2023
+ const index = plan.slot;
1782
2024
  const entry = &delays[index];
1783
2025
  entry.used = true;
1784
2026
  entry.key_len = key.len;
1785
2027
  @memcpy(entry.key[0..key.len], key);
1786
- entry.tag = tag;
2028
+ entry.tag = plan.tag;
2029
+ entry.full_result = false;
2030
+ entry.mode = .one_shot;
1787
2031
  fx.startTimer(.{
1788
2032
  .key = delay_key_base + index,
1789
- .interval_ms = intervalMs(after_ms),
2033
+ .interval_ms = plan.interval_ms,
1790
2034
  .mode = .one_shot,
1791
2035
  .on_fire = delayFireMsg,
1792
2036
  });
1793
2037
  }
1794
2038
 
1795
2039
  fn findDelay(key: []const u8) ?usize {
2040
+ if (comptime @hasDecl(core, "nativeTimerPolicy")) return compiledDelayLookup(key);
1796
2041
  for (&delays, 0..) |*entry, index| {
1797
2042
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
1798
2043
  }
@@ -1808,7 +2053,49 @@ pub fn TsCoreHost(comptime core: type) type {
1808
2053
 
1809
2054
  // ------------------------------------------- spawn / fetch streams
1810
2055
 
1811
- const SpawnHead = struct { key: []const u8, line_tag: u8, exit_tag: u8, err_tag: u8 };
2056
+ const SpawnHead = struct { key: []const u8, line_tag: u8, exit_tag: u8, err_tag: u8, complete_events: bool = false };
2057
+
2058
+ /// The engine copies the request and owns admission, pending routes,
2059
+ /// cancellation and lifetime. Per-arm callback thunks retain the route
2060
+ /// of each request, including refusals under an already occupied key.
2061
+ fn issueSpawnExact(fx: *Fx, key: u64, line_tag: u8, exit_tag: u8, collect: bool, argv: []const []const u8, stdin: []const u8) void {
2062
+ inline for (msg_arms, 0..) |arm, index| {
2063
+ if (exit_tag == index) {
2064
+ if (comptime exactSpawnArmShape(arm.type, false)) {
2065
+ const Exit = struct {
2066
+ fn message(exit: runtime_effects.EffectExit) Msg {
2067
+ return msgFromSpawnExit(index, exit, decimalFrame(exit.key));
2068
+ }
2069
+ };
2070
+ var options: Fx.SpawnOptions = .{ .key = key, .argv = argv,
2071
+ .stdin = if (stdin.len > 0) stdin else null,
2072
+ .output = if (collect) .collect else .lines, .on_exit = Exit.message };
2073
+ if (line_tag == spawn_no_line_tag) {
2074
+ fx.spawn(options);
2075
+ return;
2076
+ }
2077
+ inline for (msg_arms, 0..) |line_arm, line_index| {
2078
+ if (line_tag == line_index) {
2079
+ if (comptime exactSpawnArmShape(line_arm.type, true)) {
2080
+ const Line = struct {
2081
+ fn message(line: runtime_effects.EffectLine) Msg {
2082
+ return msgFromSpawnLine(line_index, line, decimalFrame(line.key));
2083
+ }
2084
+ };
2085
+ options.on_line = Line.message;
2086
+ fx.spawn(options);
2087
+ return;
2088
+ }
2089
+ @panic("ts core host: incompatible exact subprocess line arm");
2090
+ }
2091
+ }
2092
+ @panic("ts core host: invalid exact subprocess line tag");
2093
+ }
2094
+ @panic("ts core host: incompatible exact subprocess terminal arm");
2095
+ }
2096
+ }
2097
+ @panic("ts core host: invalid exact subprocess terminal tag");
2098
+ }
1812
2099
 
1813
2100
  /// Open a spawn stream: claim a non-retiring stream entry (the
1814
2101
  /// keyed-effect discipline's ONE exception — a live wire key
@@ -1825,19 +2112,18 @@ pub fn TsCoreHost(comptime core: type) type {
1825
2112
  argv: []const []const u8,
1826
2113
  stdin: []const u8,
1827
2114
  ) void {
1828
- if (head.key.len > 0 and (findStream(head.key) != null or fileStreamOccupiesKey(head.key))) {
1829
- fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1830
- return;
1831
- }
1832
- const index = freeStreamIndex() orelse {
1833
- // Resource refusal is an ordinary stream terminal. The
1834
- // engine would report the same rejection if it owned one
1835
- // more routing slot; the bridge table must not turn that
1836
- // public outcome into a process panic.
1837
- fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
2115
+ const index = if (comptime @hasDecl(core, "nativeStreamPolicy")) compiledStreamAdmission(head.key, false) else blk: {
2116
+ if (head.key.len > 0 and (findStream(head.key) != null or reservedWireKeyOccupied(head.key))) break :blk null;
2117
+ break :blk freeStreamIndex();
2118
+ };
2119
+ const slot = index orelse {
2120
+ fx.stageLoopMsg(if (head.complete_events)
2121
+ msgFromSpawnExit(head.exit_tag, .{ .key = 0, .reason = .rejected }, fx.stageLoopKey(head.key))
2122
+ else
2123
+ msgFromTagStaticBytes(head.err_tag, "rejected"));
1838
2124
  return;
1839
2125
  };
1840
- const entry = &streams[index];
2126
+ const entry = &streams[slot];
1841
2127
  entry.used = true;
1842
2128
  entry.key_len = head.key.len;
1843
2129
  @memcpy(entry.key[0..head.key.len], head.key);
@@ -1845,10 +2131,11 @@ pub fn TsCoreHost(comptime core: type) type {
1845
2131
  entry.exit_tag = head.exit_tag;
1846
2132
  entry.err_tag = head.err_tag;
1847
2133
  entry.collect = collect;
2134
+ entry.complete_events = head.complete_events;
1848
2135
  entry.fetch = false;
1849
2136
  entry.damaged = false;
1850
2137
  fx.spawn(.{
1851
- .key = spawn_key_base + index,
2138
+ .key = spawn_key_base + slot,
1852
2139
  .argv = argv,
1853
2140
  .stdin = if (stdin.len > 0) stdin else null,
1854
2141
  .output = if (collect) .collect else .lines,
@@ -1871,17 +2158,15 @@ pub fn TsCoreHost(comptime core: type) type {
1871
2158
  /// replacing a source that has already delivered lines would splice
1872
2159
  /// two HTTP responses into one app-owned stream.
1873
2160
  fn issueFetchStream(fx: *Fx, head: SpawnHead, options: FetchStreamOptions) void {
1874
- if (head.key.len > 0 and
1875
- (findStream(head.key) != null or findEffect(head.key) != null or fileStreamOccupiesKey(head.key)))
1876
- {
1877
- fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1878
- return;
1879
- }
1880
- const index = freeStreamIndex() orelse {
2161
+ const index = if (comptime @hasDecl(core, "nativeStreamPolicy")) compiledStreamAdmission(head.key, true) else blk: {
2162
+ if (head.key.len > 0 and (findStream(head.key) != null or findEffect(head.key) != null or reservedWireKeyOccupied(head.key))) break :blk null;
2163
+ break :blk freeStreamIndex();
2164
+ };
2165
+ const slot = index orelse {
1881
2166
  fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1882
2167
  return;
1883
2168
  };
1884
- const entry = &streams[index];
2169
+ const entry = &streams[slot];
1885
2170
  entry.used = true;
1886
2171
  entry.key_len = head.key.len;
1887
2172
  @memcpy(entry.key[0..head.key.len], head.key);
@@ -1890,9 +2175,10 @@ pub fn TsCoreHost(comptime core: type) type {
1890
2175
  entry.err_tag = head.err_tag;
1891
2176
  entry.collect = false;
1892
2177
  entry.fetch = true;
2178
+ entry.complete_events = false;
1893
2179
  entry.damaged = false;
1894
2180
  fx.fetch(.{
1895
- .key = spawn_key_base + index,
2181
+ .key = spawn_key_base + slot,
1896
2182
  .method = options.method,
1897
2183
  .url = options.url,
1898
2184
  .headers = options.headers,
@@ -1906,6 +2192,7 @@ pub fn TsCoreHost(comptime core: type) type {
1906
2192
  }
1907
2193
 
1908
2194
  fn findStream(key: []const u8) ?usize {
2195
+ if (comptime @hasDecl(core, "nativeStreamPolicy")) return compiledStreamLookup(key);
1909
2196
  for (&streams, 0..) |*entry, index| {
1910
2197
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
1911
2198
  }
@@ -1919,15 +2206,118 @@ pub fn TsCoreHost(comptime core: type) type {
1919
2206
  return null;
1920
2207
  }
1921
2208
 
2209
+ const max_stream_policy_bytes = 5 + max_wire_key_bytes + runtime_effects.max_effects * (2 + max_wire_key_bytes);
2210
+
2211
+ fn appendStreamTable(request: []u8, start: usize) usize {
2212
+ var at = start;
2213
+ for (streams) |entry| {
2214
+ request[at] = @intFromBool(entry.used);
2215
+ request[at + 1] = @intCast(entry.key_len);
2216
+ at += 2;
2217
+ @memcpy(request[at..][0..entry.key_len], entry.wireKey());
2218
+ at += entry.key_len;
2219
+ }
2220
+ return at;
2221
+ }
2222
+
2223
+ fn compiledStreamSlot(request: []const u8) ?usize {
2224
+ var result: [1]u8 = undefined;
2225
+ if (core.nativeStreamPolicy(request, &result) != result.len) @panic("ts core host: invalid compiled stream slot result");
2226
+ if (result[0] == 255) return null;
2227
+ if (result[0] >= streams.len) @panic("ts core host: compiled stream slot outside table");
2228
+ return result[0];
2229
+ }
2230
+
2231
+ fn compiledStreamAdmission(key: []const u8, fetch: bool) ?usize {
2232
+ var request: [max_stream_policy_bytes]u8 = undefined;
2233
+ request[0] = 0;
2234
+ request[1] = @intFromBool(fetch);
2235
+ request[2] = @intFromBool(reservedWireKeyOccupied(key));
2236
+ request[3] = @intFromBool(fetch and key.len > 0 and findEffect(key) != null);
2237
+ request[4] = @intCast(key.len);
2238
+ @memcpy(request[5..][0..key.len], key);
2239
+ const end = appendStreamTable(&request, 5 + key.len);
2240
+ const slot = compiledStreamSlot(request[0..end]) orelse return null;
2241
+ if (streams[slot].used) @panic("ts core host: compiled stream admission selected occupied slot");
2242
+ return slot;
2243
+ }
2244
+
2245
+ fn compiledStreamLookup(key: []const u8) ?usize {
2246
+ var request: [max_stream_policy_bytes]u8 = undefined;
2247
+ request[0] = 1;
2248
+ request[1] = @intCast(key.len);
2249
+ @memcpy(request[2..][0..key.len], key);
2250
+ const end = appendStreamTable(&request, 2 + key.len);
2251
+ const slot = compiledStreamSlot(request[0..end]) orelse return null;
2252
+ if (!streams[slot].used) @panic("ts core host: compiled stream lookup selected unused slot");
2253
+ return slot;
2254
+ }
2255
+
2256
+ const StreamCompletion = struct { tag: u8, shape: enum { bytes, number, number_bytes }, damaged: bool, retire: bool, truncated: bool };
2257
+
2258
+ fn compiledStreamCompletion(request: []const u8) StreamCompletion {
2259
+ var result: [5]u8 = undefined;
2260
+ if (core.nativeStreamPolicy(request, &result) != result.len or result[1] > 2 or result[2] > 1 or result[3] > 1 or result[4] > 1)
2261
+ @panic("ts core host: invalid compiled stream completion result");
2262
+ return .{ .tag = result[0], .shape = @enumFromInt(result[1]), .damaged = result[2] != 0, .retire = result[3] != 0, .truncated = result[4] != 0 };
2263
+ }
2264
+
2265
+ /// Copied portable plans borrow native-owned slot facts and key bytes.
2266
+ /// OS operations and engine namespace checks stay in this host.
2267
+ fn compiledFileStreamPlan(action: u8, key: []const u8, blocked: bool, slot: u8, op: u8, event: u8, outcome: u8, chunk_tag: u8, done_tag: u8, err_tag: u8) [8]u8 {
2268
+ var request: [12 + max_wire_key_bytes + file_streams.len * (8 + max_wire_key_bytes)]u8 = @splat(0);
2269
+ request[0..12].* = .{ 15, action, @intCast(key.len), @intFromBool(blocked), slot, op, event, outcome, chunk_tag, done_tag, err_tag, 0 };
2270
+ @memcpy(request[12..][0..key.len], key);
2271
+ var at: usize = 12 + key.len;
2272
+ for (&file_streams) |*entry| {
2273
+ const name = if (entry.used) entry.wireKey() else "";
2274
+ request[at..][0..8].* = .{ @intFromBool(entry.used), @intFromBool(entry.sink), @intFromBool(entry.busy), @intFromBool(entry.cancelling), entry.chunk_tag, entry.done_tag, entry.err_tag, @intCast(name.len) };
2275
+ @memcpy(request[at + 8 ..][0..name.len], name);
2276
+ at += 8 + name.len;
2277
+ }
2278
+ var result: [8]u8 = undefined;
2279
+ if (core.nativeEffectPolicy(request[0..at], &result) != result.len or result[1] > 3 or result[3] > 3 or result[4] > 1 or result[5] > 1 or result[6] != 0 or result[7] != 0 or (result[0] != 255 and result[0] >= file_streams.len))
2280
+ @panic("ts core host: invalid compiled file stream plan");
2281
+ if (action == 5) {
2282
+ if (result[0] != slot or result[1] != 0) @panic("ts core host: invalid compiled file completion owner");
2283
+ } else if (result[0] != 255) {
2284
+ const entry = &file_streams[result[0]];
2285
+ if ((action == 0 or action >= 3) and (!entry.used or !std.mem.eql(u8, entry.wireKey(), key)))
2286
+ @panic("ts core host: invalid compiled file lookup owner");
2287
+ if ((action == 1 or action == 2) and entry.used and (action == 2 or key.len == 0 or entry.sink or !std.mem.eql(u8, entry.wireKey(), key)))
2288
+ @panic("ts core host: compiled file admission overwrites another owner");
2289
+ if (result[1] != 0) @panic("ts core host: compiled file plan admits a refused command");
2290
+ }
2291
+ return result;
2292
+ }
2293
+
1922
2294
  fn findFileStream(key: []const u8) ?usize {
2295
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2296
+ const plan = compiledFileStreamPlan(0, key, false, 0, 0, 0, 0, 0, 0, 0);
2297
+ return if (plan[0] == 255) null else plan[0];
2298
+ }
1923
2299
  for (&file_streams, 0..) |*entry, index| {
1924
2300
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
1925
2301
  }
1926
2302
  return null;
1927
2303
  }
1928
2304
 
1929
- fn fileStreamOccupiesKey(key: []const u8) bool {
1930
- return key.len > 0 and findFileStream(key) != null;
2305
+ fn reservedWireKeyOccupied(key: []const u8) bool {
2306
+ return reservedWireKeyOccupiedExcept(key, .none);
2307
+ }
2308
+
2309
+ /// Complete results reserve one owner across every command family.
2310
+ /// Same-family replacements retain the existing silent-drop contract.
2311
+ fn reservedWireKeyOccupiedExcept(key: []const u8, family: enum { none, effect, delay }) bool {
2312
+ if (key.len == 0) return false;
2313
+ if (findFileStream(key) != null or findClipboardWrite(key) != null) return true;
2314
+ if (family != .effect) if (findEffect(key)) |index| if (effects_table[index].full_result) return true;
2315
+ // Capability ownership is the recorded wire key, independent of
2316
+ // the compiled policy's cancellation lookup and routing decisions.
2317
+ if (family != .delay) for (&delays) |*entry| {
2318
+ if (entry.used and entry.full_result and std.mem.eql(u8, entry.wireKey(), key)) return true;
2319
+ };
2320
+ return false;
1931
2321
  }
1932
2322
 
1933
2323
  /// Every string-keyed command family shares one authored key surface.
@@ -1940,7 +2330,8 @@ pub fn TsCoreHost(comptime core: type) type {
1940
2330
  findStream(key) != null or
1941
2331
  findDelay(key) != null or
1942
2332
  findPty(key) != null or
1943
- findDb(key) != null;
2333
+ findDb(key) != null or
2334
+ findClipboardWrite(key) != null;
1944
2335
  }
1945
2336
 
1946
2337
  fn freeFileStreamIndex() ?usize {
@@ -1949,6 +2340,18 @@ pub fn TsCoreHost(comptime core: type) type {
1949
2340
  }
1950
2341
 
1951
2342
  fn issueReadFileStream(fx: *Fx, key: []const u8, chunk_tag: u8, done_tag: u8, err_tag: u8, path: []const u8) void {
2343
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2344
+ const plan = compiledFileStreamPlan(1, key, wireKeyOccupiedOutsideFileStreams(key), 0, 0, 0, 0, chunk_tag, done_tag, err_tag);
2345
+ if (plan[0] == 255) {
2346
+ fx.stageLoopMsg(msgFromTagStaticBytes(plan[2], "rejected"));
2347
+ return;
2348
+ }
2349
+ const entry = &file_streams[plan[0]];
2350
+ entry.* = .{ .used = true, .key_len = key.len, .chunk_tag = chunk_tag, .done_tag = plan[2], .err_tag = err_tag };
2351
+ @memcpy(entry.key[0..key.len], key);
2352
+ fx.readFileStream(.{ .key = file_stream_key_base + plan[0], .path = path, .on_result = fileStreamResultMsg });
2353
+ return;
2354
+ }
1952
2355
  if (wireKeyOccupiedOutsideFileStreams(key)) {
1953
2356
  fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
1954
2357
  return;
@@ -1974,6 +2377,18 @@ pub fn TsCoreHost(comptime core: type) type {
1974
2377
  }
1975
2378
 
1976
2379
  fn issueWriteFileStream(fx: *Fx, head: RoutedHead, path: []const u8) void {
2380
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2381
+ const plan = compiledFileStreamPlan(2, head.key, wireKeyOccupiedOutsideFileStreams(head.key), 0, 0, 0, 0, 0, head.ok_tag, head.err_tag);
2382
+ if (plan[0] == 255) {
2383
+ fx.stageLoopMsg(msgFromTagStaticBytes(plan[2], "rejected"));
2384
+ return;
2385
+ }
2386
+ const entry = &file_streams[plan[0]];
2387
+ entry.* = .{ .used = true, .sink = true, .busy = true, .key_len = head.key.len, .done_tag = plan[2], .err_tag = head.err_tag };
2388
+ @memcpy(entry.key[0..head.key.len], head.key);
2389
+ fx.writeFileStream(.{ .key = file_stream_key_base + plan[0], .path = path, .on_result = fileStreamResultMsg });
2390
+ return;
2391
+ }
1977
2392
  if (head.key.len == 0 or findFileStream(head.key) != null or wireKeyOccupiedOutsideFileStreams(head.key)) {
1978
2393
  fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1979
2394
  return;
@@ -1989,6 +2404,19 @@ pub fn TsCoreHost(comptime core: type) type {
1989
2404
  }
1990
2405
 
1991
2406
  fn issueWriteFileChunk(fx: *Fx, head: RoutedHead, bytes: []const u8) void {
2407
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2408
+ const plan = compiledFileStreamPlan(3, head.key, false, 0, 0, 0, 0, 0, head.ok_tag, head.err_tag);
2409
+ if (plan[0] == 255) {
2410
+ fx.stageLoopMsg(if (plan[1] == 3) msgFromTagStaticBytes(plan[2], "out_of_order") else msgFromTagStaticBytes(plan[2], "sink_missing"));
2411
+ return;
2412
+ }
2413
+ const entry = &file_streams[plan[0]];
2414
+ entry.busy = true;
2415
+ entry.done_tag = plan[2];
2416
+ entry.err_tag = head.err_tag;
2417
+ fx.writeFileChunk(.{ .key = file_stream_key_base + plan[0], .bytes = bytes, .on_result = fileStreamResultMsg });
2418
+ return;
2419
+ }
1992
2420
  const index = findFileStream(head.key) orelse {
1993
2421
  fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "sink_missing"));
1994
2422
  return;
@@ -2012,6 +2440,19 @@ pub fn TsCoreHost(comptime core: type) type {
2012
2440
  }
2013
2441
 
2014
2442
  fn issueWriteFileClose(fx: *Fx, head: RoutedHead) void {
2443
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2444
+ const plan = compiledFileStreamPlan(4, head.key, false, 0, 0, 0, 0, 0, head.ok_tag, head.err_tag);
2445
+ if (plan[0] == 255) {
2446
+ fx.stageLoopMsg(if (plan[1] == 3) msgFromTagStaticBytes(plan[2], "out_of_order") else msgFromTagStaticBytes(plan[2], "sink_missing"));
2447
+ return;
2448
+ }
2449
+ const entry = &file_streams[plan[0]];
2450
+ entry.busy = true;
2451
+ entry.done_tag = plan[2];
2452
+ entry.err_tag = head.err_tag;
2453
+ fx.writeFileClose(.{ .key = file_stream_key_base + plan[0], .on_result = fileStreamResultMsg });
2454
+ return;
2455
+ }
2015
2456
  const index = findFileStream(head.key) orelse {
2016
2457
  fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "sink_missing"));
2017
2458
  return;
@@ -2039,6 +2480,18 @@ pub fn TsCoreHost(comptime core: type) type {
2039
2480
  const index = result.key - file_stream_key_base;
2040
2481
  if (index >= file_streams.len or !file_streams[index].used) @panic("ts core host: untracked file stream result");
2041
2482
  const entry = &file_streams[index];
2483
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2484
+ const plan = compiledFileStreamPlan(5, "", false, @intCast(index), @intFromEnum(result.op), @intFromEnum(result.event), @intFromEnum(result.outcome), 0, 0, 0);
2485
+ if (plan[4] == 1) entry.used = false;
2486
+ if (plan[5] == 1) entry.busy = false;
2487
+ return switch (plan[3]) {
2488
+ 0 => msgFromTagVoid(plan[2]),
2489
+ 1 => msgFromTagBytes(plan[2], result.bytes),
2490
+ 3 => msgFromTagBytes(plan[2], @tagName(result.outcome)),
2491
+ 2 => msgFromTagNumber(plan[2], @floatFromInt(result.total)),
2492
+ else => unreachable,
2493
+ };
2494
+ }
2042
2495
  if (entry.cancelling and result.outcome == .cancelled) {
2043
2496
  entry.used = false;
2044
2497
  return msgFromTagBytes(entry.err_tag, "cancelled");
@@ -2082,6 +2535,14 @@ pub fn TsCoreHost(comptime core: type) type {
2082
2535
  /// complete.
2083
2536
  fn streamLineMsg(line: runtime_effects.EffectLine) Msg {
2084
2537
  const entry = streamAt(line.key);
2538
+ if (entry.complete_events) return msgFromSpawnLine(entry.line_tag, line, entry.wireKey());
2539
+ if (comptime @hasDecl(core, "nativeStreamPolicy")) {
2540
+ const plan = compiledStreamCompletion(&.{ 2, @intFromBool(entry.fetch), @intFromBool(entry.damaged), @intFromBool(line.truncated), @intFromBool(line.dropped_before != 0), entry.line_tag });
2541
+ if (plan.shape != .bytes) @panic("ts core host: invalid compiled stream line payload");
2542
+ entry.damaged = plan.damaged;
2543
+ if (plan.retire) entry.used = false;
2544
+ return msgFromTagBytes(plan.tag, line.line);
2545
+ }
2085
2546
  if (entry.fetch and (line.truncated or line.dropped_before != 0)) {
2086
2547
  entry.damaged = true;
2087
2548
  }
@@ -2097,6 +2558,19 @@ pub fn TsCoreHost(comptime core: type) type {
2097
2558
  /// with the reason name as bytes.
2098
2559
  fn spawnExitMsg(exit: runtime_effects.EffectExit) Msg {
2099
2560
  const entry = streamAt(exit.key);
2561
+ if (entry.complete_events) {
2562
+ entry.used = false;
2563
+ return msgFromSpawnExit(entry.exit_tag, exit, entry.wireKey());
2564
+ }
2565
+ if (comptime @hasDecl(core, "nativeStreamPolicy")) {
2566
+ const plan = compiledStreamCompletion(&.{ 3, @intFromBool(entry.collect), @intFromBool(exit.reason == .exited), @intFromBool(exit.output_truncated), entry.exit_tag, entry.err_tag });
2567
+ if (plan.retire) entry.used = false;
2568
+ return switch (plan.shape) {
2569
+ .bytes => msgFromTagBytes(plan.tag, if (plan.truncated) "truncated" else @tagName(exit.reason)),
2570
+ .number => msgFromTagNumber(plan.tag, @floatFromInt(exit.code)),
2571
+ .number_bytes => msgFromTagNumberBytes("spawn exit", "{ code, output }", plan.tag, exit.code, exit.output),
2572
+ };
2573
+ }
2100
2574
  entry.used = false;
2101
2575
  if (exit.reason == .exited) {
2102
2576
  if (!entry.collect) {
@@ -2118,6 +2592,16 @@ pub fn TsCoreHost(comptime core: type) type {
2118
2592
  /// shared stream entry, so no later line can route for the key.
2119
2593
  fn fetchStreamResultMsg(response: runtime_effects.EffectResponse) Msg {
2120
2594
  const entry = streamAt(response.key);
2595
+ if (comptime @hasDecl(core, "nativeStreamPolicy")) {
2596
+ const plan = compiledStreamCompletion(&.{ 4, @intFromBool(entry.damaged), @intFromBool(response.truncated), @intFromBool(response.dropped_before != 0), @intFromBool(response.outcome == .ok), entry.exit_tag, entry.err_tag });
2597
+ entry.damaged = plan.damaged;
2598
+ if (plan.retire) entry.used = false;
2599
+ return switch (plan.shape) {
2600
+ .bytes => if (plan.truncated) msgFromTagStaticBytes(plan.tag, "truncated") else msgFromTagBytes(plan.tag, @tagName(response.outcome)),
2601
+ .number => msgFromTagNumber(plan.tag, @floatFromInt(response.status)),
2602
+ .number_bytes => @panic("ts core host: invalid compiled fetch terminal payload"),
2603
+ };
2604
+ }
2121
2605
  const damaged = entry.damaged or response.truncated or response.dropped_before != 0;
2122
2606
  entry.used = false;
2123
2607
  if (response.outcome == .ok) {
@@ -2127,6 +2611,206 @@ pub fn TsCoreHost(comptime core: type) type {
2127
2611
  return msgFromTagBytes(entry.err_tag, @tagName(response.outcome));
2128
2612
  }
2129
2613
 
2614
+ const MediaPlan = struct {
2615
+ valid: bool,
2616
+ slot: ?usize,
2617
+ tag: u8,
2618
+ retire: bool,
2619
+ key: u64,
2620
+ expected_bytes: u64,
2621
+ source: platform.AudioCaptureSource,
2622
+ sample_rate: u32,
2623
+ capture_channels: u8,
2624
+ };
2625
+
2626
+ /// The tables and capability identities remain native-owned. The
2627
+ /// compiled core selects admission, routing and terminal retirement;
2628
+ /// exact u64 keys cross as opaque bytes, never as rounded numbers.
2629
+ fn compiledMediaPlan(
2630
+ comptime family: u8,
2631
+ operation: u8,
2632
+ key_bits: u64,
2633
+ event_kind: u8,
2634
+ tag: u8,
2635
+ source: platform.AudioCaptureSource,
2636
+ sample_rate: u32,
2637
+ capture_channels: u8,
2638
+ expected: f64,
2639
+ table: anytype,
2640
+ ) MediaPlan {
2641
+ return compiledMediaIdentityPlan(family, operation, key_bits, event_kind, tag, source, sample_rate, capture_channels, expected, table, false);
2642
+ }
2643
+
2644
+ fn compiledMediaIdentityPlan(comptime family: u8, operation: u8, key_bits: u64, event_kind: u8, tag: u8, source: platform.AudioCaptureSource, sample_rate: u32, capture_channels: u8, expected: f64, table: anytype, words: bool) MediaPlan {
2645
+ var request: [28 + @as(usize, @max(runtime_effects.max_effects, runtime_effects.max_effect_channels)) * 16]u8 = @splat(0);
2646
+ request[0] = operation;
2647
+ request[1] = family;
2648
+ request[2] = @intCast(table.len);
2649
+ request[3] = event_kind;
2650
+ request[4] = tag;
2651
+ request[5] = @intFromEnum(source);
2652
+ request[6] = capture_channels;
2653
+ request[7] = @intFromBool(words);
2654
+ std.mem.writeInt(u64, request[8..16], key_bits, .little);
2655
+ std.mem.writeInt(u32, request[16..20], sample_rate, .little);
2656
+ std.mem.writeInt(u64, request[20..28], @bitCast(expected), .little);
2657
+ for (table, 0..) |entry, slot| {
2658
+ const at = 28 + slot * 16;
2659
+ request[at] = @intFromBool(entry.used);
2660
+ std.mem.writeInt(u64, request[at + 1 ..][0..8], if (comptime family == 0) entry.id else entry.key, .little);
2661
+ request[at + 9] = entry.event_tag;
2662
+ if (comptime family == 2) {
2663
+ request[at + 10] = @intFromEnum(entry.source);
2664
+ std.mem.writeInt(u32, request[at + 11 ..][0..4], entry.sample_rate, .little);
2665
+ request[at + 15] = entry.channels;
2666
+ }
2667
+ }
2668
+ var result: [28]u8 = undefined;
2669
+ if (core.nativeEffectPolicy(request[0 .. 28 + table.len * 16], &result) != result.len or
2670
+ result[0] > 1 or result[3] > 1 or result[4] > 1 or result[6] != 0 or result[7] != 0)
2671
+ @panic("ts core host: invalid compiled media plan");
2672
+ const slot: ?usize = if (result[1] == 255) null else result[1];
2673
+ if (slot) |index| {
2674
+ if (index >= table.len) @panic("ts core host: invalid compiled media slot");
2675
+ if (operation != 3 and !table[index].used) @panic("ts core host: compiled media lookup names an idle slot");
2676
+ if (operation == 3 and table[index].used) @panic("ts core host: compiled media admission names a live slot");
2677
+ }
2678
+ return .{
2679
+ .valid = result[0] == 1,
2680
+ .slot = slot,
2681
+ .tag = result[2],
2682
+ .retire = result[3] == 1,
2683
+ .source = @enumFromInt(result[4]),
2684
+ .capture_channels = result[5],
2685
+ .key = std.mem.readInt(u64, result[8..16], .little),
2686
+ .expected_bytes = std.mem.readInt(u64, result[16..24], .little),
2687
+ .sample_rate = std.mem.readInt(u32, result[24..28], .little),
2688
+ };
2689
+ }
2690
+
2691
+ fn compiledMediaLookup(comptime family: u8, key: u64, table: anytype) ?usize {
2692
+ return compiledMediaPlan(family, 7, key, 0, 0, .microphone, 0, 0, 0, table).slot;
2693
+ }
2694
+
2695
+ const MediaTransportPlan = struct { action: u8, retire: bool, rekey: bool, value: f64 };
2696
+
2697
+ fn compiledMediaTransport(video: bool, used: bool, ownership: u8, stored: []const u8, key: []const u8, verb: u8, value: f64) MediaTransportPlan {
2698
+ var request: [15 + max_wire_key_bytes * 2]u8 = @splat(0);
2699
+ request[0] = 6;
2700
+ request[1] = @intFromBool(video);
2701
+ request[2] = @intFromBool(used);
2702
+ request[3] = ownership;
2703
+ request[4] = verb;
2704
+ request[5] = @intCast(key.len);
2705
+ request[6] = @intCast(stored.len);
2706
+ std.mem.writeInt(u64, request[7..15], @bitCast(value), .little);
2707
+ @memcpy(request[15..][0..key.len], key);
2708
+ @memcpy(request[15 + key.len ..][0..stored.len], stored);
2709
+ var result: [12]u8 = undefined;
2710
+ if (core.nativeEffectPolicy(request[0 .. 15 + key.len + stored.len], &result) != result.len or
2711
+ (result[0] != 255 and result[0] > (if (video) @as(u8, 7) else @as(u8, 4))) or
2712
+ result[1] > 1 or result[2] > 1 or result[3] != 0)
2713
+ @panic("ts core host: invalid compiled media transport plan");
2714
+ return .{ .action = result[0], .retire = result[1] == 1, .rekey = result[2] == 1, .value = @bitCast(std.mem.readInt(u64, result[4..12], .little)) };
2715
+ }
2716
+
2717
+ const PlaybackLoadPlan = struct { accepted: bool, tag: u8, flags: u8, surface: u64, expected_bytes: u64 };
2718
+
2719
+ fn compiledPlaybackLoad(video: bool, tag: u8, flags: u8, value: f64, path: []const u8, url: []const u8) PlaybackLoadPlan {
2720
+ var request: [24 + runtime_effects.max_effect_video_path_bytes]u8 = @splat(0);
2721
+ request[0] = 8;
2722
+ request[1] = @intFromBool(video);
2723
+ request[2] = tag;
2724
+ request[3] = flags;
2725
+ std.mem.writeInt(u64, request[8..16], @bitCast(value), .little);
2726
+ std.mem.writeInt(u32, request[16..20], @intCast(path.len), .little);
2727
+ std.mem.writeInt(u32, request[20..24], @intCast(url.len), .little);
2728
+ const size = @min(url.len, runtime_effects.max_effect_video_path_bytes);
2729
+ @memcpy(request[24..][0..size], url[0..size]);
2730
+ var result: [24]u8 = undefined;
2731
+ if (core.nativeEffectPolicy(request[0 .. 24 + size], &result) != result.len or result[0] > 1 or result[2] > 7 or
2732
+ !std.mem.allEqual(u8, result[3..8], 0)) @panic("ts core host: invalid compiled playback load plan");
2733
+ return .{ .accepted = result[0] == 1, .tag = result[1], .flags = result[2], .surface = std.mem.readInt(u64, result[8..16], .little), .expected_bytes = std.mem.readInt(u64, result[16..24], .little) };
2734
+ }
2735
+
2736
+ fn issueAudioPlay(fx: *Fx, key: []const u8, tag: u8, path: []const u8, url: []const u8, cache: []const u8, expected: f64) void {
2737
+ const plan: PlaybackLoadPlan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
2738
+ compiledPlaybackLoad(false, tag, 0, expected, path, url)
2739
+ else
2740
+ .{ .accepted = true, .tag = tag, .flags = 0, .surface = 0, .expected_bytes = if (expected >= 1 and expected <= 9007199254740992.0) @intFromFloat(expected) else 0 };
2741
+ if (!plan.accepted) @panic("ts core host: audio load cannot refuse bridge admission");
2742
+ // Audio always commits before the capability, including failed sources.
2743
+ audio_entry.used = true;
2744
+ audio_entry.key_len = key.len;
2745
+ @memcpy(audio_entry.key[0..key.len], key);
2746
+ audio_entry.event_tag = plan.tag;
2747
+ fx.playAudio(.{ .key = audio_key_base, .path = path, .url = url, .cache_path = effectiveAudioCachePath(cache, url), .expected_bytes = plan.expected_bytes, .on_event = audioEventMsg });
2748
+ }
2749
+
2750
+ fn issueAudioPlayExact(fx: *Fx, key: u64, tag: u8, path: []const u8, url: []const u8, cache: []const u8, cache_dir: []const u8, expected: f64) void {
2751
+ const plan: PlaybackLoadPlan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
2752
+ compiledPlaybackLoad(false, tag, 0, expected, path, url)
2753
+ else
2754
+ .{ .accepted = true, .tag = tag, .flags = 0, .surface = 0, .expected_bytes = if (expected >= 1 and expected <= 9007199254740992.0) @intFromFloat(expected) else 0 };
2755
+ if (!plan.accepted) @panic("ts core host: exact audio load cannot refuse bridge admission");
2756
+ var cache_buffer: [runtime_effects.max_effect_audio_path_bytes]u8 = undefined;
2757
+ const cache_path = if (cache.len > 0 or url.len == 0 or cache_dir.len == 0) cache else runtime_effects.audioCachePath(&cache_buffer, cache_dir, url) catch "";
2758
+ inline for (msg_arms, 0..) |arm, index| {
2759
+ if (plan.tag == index) {
2760
+ if (comptime exactAudioArmShape(arm.type)) {
2761
+ const Callback = struct {
2762
+ fn eventMsg(event: runtime_effects.EffectAudio) Msg {
2763
+ const bands = core.rt.frameAlloc(u8, event.bands.len);
2764
+ @memcpy(bands, &event.bands);
2765
+ return msgFromCapability(index, .{ .key = decimalFrame(event.key), .state = event.kind, .positionMs = decimalFrame(event.position_ms), .durationMs = decimalFrame(event.duration_ms), .playing = event.playing, .buffering = event.buffering, .bands = @as([]const u8, bands) });
2766
+ }
2767
+ };
2768
+ const options: Fx.PlayAudioOptions = .{ .key = key, .path = path, .url = url, .cache_path = cache_path, .expected_bytes = plan.expected_bytes, .on_event = Callback.eventMsg };
2769
+ // Rejection retains the prior native player and its compatibility route.
2770
+ if (!Fx.audioPlayRejected(options)) audio_entry.used = false;
2771
+ fx.playAudio(options);
2772
+ return;
2773
+ }
2774
+ @panic("ts core host: exact audio targets an incompatible message arm");
2775
+ }
2776
+ }
2777
+ @panic("ts core host: invalid exact audio message tag");
2778
+ }
2779
+
2780
+ fn issueVideoLoad(fx: *Fx, key: []const u8, tag: u8, surface: f64, path: []const u8, url: []const u8, flags: u8) void {
2781
+ const plan: PlaybackLoadPlan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
2782
+ compiledPlaybackLoad(true, tag, flags, surface, path, url)
2783
+ else blk: {
2784
+ const id: u64 = if (surface >= 1 and surface < 9007199254740992.0 and @floor(surface) == surface) @intFromFloat(surface) else 0;
2785
+ const options: Fx.LoadVideoOptions = .{ .key = videoKeyForTag(tag), .surface = id, .path = path, .url = url, .on_event = videoEventMsg };
2786
+ break :blk .{ .accepted = !Fx.videoLoadRejected(options), .tag = tag, .flags = flags & 7, .surface = id, .expected_bytes = 0 };
2787
+ };
2788
+ const options: Fx.LoadVideoOptions = .{ .key = videoKeyForTag(plan.tag), .surface = plan.surface, .path = path, .url = url, .autoplay = (plan.flags & 1) != 0, .loop = (plan.flags & 2) != 0, .muted = (plan.flags & 4) != 0, .on_event = videoEventMsg };
2789
+ if (!plan.accepted) {
2790
+ // Refusal leaves the surviving player's key, route and exact token intact.
2791
+ fx.stageLoopMsg(msgFromTagVideo(plan.tag, .{ .key = options.key, .kind = .rejected }));
2792
+ return;
2793
+ }
2794
+ video_entry.used = true;
2795
+ video_entry.key_len = key.len;
2796
+ @memcpy(video_entry.key[0..key.len], key);
2797
+ video_entry.event_tag = plan.tag;
2798
+ fx.loadVideo(options);
2799
+ video_entry.token = fx.videoMintedToken();
2800
+ }
2801
+
2802
+ fn compiledPlaybackEvent(video: bool, used: bool, tag: u8, key: u64) u8 {
2803
+ var request: [12]u8 = @splat(0);
2804
+ request[0] = 10;
2805
+ request[1] = @intFromBool(video);
2806
+ request[2] = @intFromBool(used);
2807
+ request[3] = tag;
2808
+ std.mem.writeInt(u64, request[4..12], key, .little);
2809
+ var result: [1]u8 = undefined;
2810
+ if (core.nativeEffectPolicy(&request, &result) != result.len) @panic("ts core host: invalid compiled playback event route");
2811
+ return result[0];
2812
+ }
2813
+
2130
2814
  // ------------------------------------------------- audio stream
2131
2815
 
2132
2816
  /// The audio_ctl record: drive the single playback channel,
@@ -2136,6 +2820,20 @@ pub fn TsCoreHost(comptime core: type) type {
2136
2820
  /// the stream: the entry retires and later platform stragglers
2137
2821
  /// are the engine's to swallow.
2138
2822
  fn runAudioCtl(fx: *Fx, key: []const u8, verb: u8, value: f64) void {
2823
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2824
+ const plan = compiledMediaTransport(false, audio_entry.used, 1, audio_entry.wireKey(), key, verb, value);
2825
+ if (plan.retire) audio_entry.used = false;
2826
+ switch (plan.action) {
2827
+ 0 => fx.pauseAudio(),
2828
+ 1 => fx.resumeAudio(),
2829
+ 2 => fx.stopAudio(),
2830
+ 3 => fx.seekAudio(@intFromFloat(plan.value)),
2831
+ 4 => fx.setAudioVolume(@floatCast(value)),
2832
+ 255 => {},
2833
+ else => unreachable,
2834
+ }
2835
+ return;
2836
+ }
2139
2837
  if (!audio_entry.used or !std.mem.eql(u8, audio_entry.wireKey(), key)) return;
2140
2838
  switch (verb) {
2141
2839
  0 => fx.pauseAudio(),
@@ -2144,12 +2842,7 @@ pub fn TsCoreHost(comptime core: type) type {
2144
2842
  audio_entry.used = false;
2145
2843
  fx.stopAudio();
2146
2844
  },
2147
- // The wire carries the app's f64; anything that is not a
2148
- // millisecond offset seeks to 0 (the engine clamps the
2149
- // high end to the duration itself).
2150
2845
  3 => fx.seekAudio(if (value >= 0 and value <= 9007199254740992.0) @intFromFloat(value) else 0),
2151
- // The engine clamps volume to 0..1 (NaN clamps to the
2152
- // bound arithmetic's result deterministically).
2153
2846
  4 => fx.setAudioVolume(@floatCast(value)),
2154
2847
  else => @panic("ts core host: unknown audio_ctl verb wire value - the core and this runtime disagree on cmd_format_version"),
2155
2848
  }
@@ -2161,10 +2854,13 @@ pub fn TsCoreHost(comptime core: type) type {
2161
2854
  /// starts the next track from `completed`), and audio_ctl
2162
2855
  /// `stop` is the explicit close.
2163
2856
  fn audioEventMsg(event: runtime_effects.EffectAudio) Msg {
2164
- if (!audio_entry.used) {
2165
- @panic("ts core host: an audio event arrived with no open bridge stream");
2166
- }
2167
- return msgFromTagAudio(audio_entry.event_tag, event);
2857
+ const tag = if (comptime @hasDecl(core, "nativeEffectPolicy"))
2858
+ compiledPlaybackEvent(false, audio_entry.used, audio_entry.event_tag, event.key)
2859
+ else blk: {
2860
+ if (!audio_entry.used) @panic("ts core host: an audio event arrived with no open bridge stream");
2861
+ break :blk audio_entry.event_tag;
2862
+ };
2863
+ return msgFromTagAudio(tag, event);
2168
2864
  }
2169
2865
 
2170
2866
  // ------------------------------------------------- video stream
@@ -2176,6 +2872,26 @@ pub fn TsCoreHost(comptime core: type) type {
2176
2872
  /// the stream: the entry retires and later platform stragglers
2177
2873
  /// are the engine's to swallow.
2178
2874
  fn runVideoCtl(fx: *Fx, key: []const u8, verb: u8, value: f64) void {
2875
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2876
+ const owner = fx.videoOwnerToken();
2877
+ const ownership: u8 = if (owner == video_entry.token) 1 else if (owner == 0) 2 else 0;
2878
+ const plan = compiledMediaTransport(true, video_entry.used, ownership, video_entry.wireKey(), key, verb, value);
2879
+ if (plan.retire) video_entry.used = false;
2880
+ switch (plan.action) {
2881
+ 0 => fx.playVideo(),
2882
+ 1 => fx.pauseVideo(),
2883
+ 2 => fx.stopVideoCancel(video_entry.token),
2884
+ 3 => fx.seekVideo(@intFromFloat(plan.value)),
2885
+ 4 => fx.setVideoVolume(@floatCast(value)),
2886
+ 5 => fx.setVideoMuted(plan.value != 0),
2887
+ 6 => fx.setVideoLoop(plan.value != 0),
2888
+ 7 => fx.restartVideo(),
2889
+ 255 => {},
2890
+ else => unreachable,
2891
+ }
2892
+ if (plan.rekey) video_entry.token = fx.videoMintedToken();
2893
+ return;
2894
+ }
2179
2895
  if (!video_entry.used or !std.mem.eql(u8, video_entry.wireKey(), key)) return;
2180
2896
  if (verb == 2) {
2181
2897
  // `Cmd.videoStop` is the stream's CANCEL: the engine
@@ -2233,6 +2949,10 @@ pub fn TsCoreHost(comptime core: type) type {
2233
2949
  4 => fx.setVideoVolume(@floatCast(value)),
2234
2950
  5 => fx.setVideoMuted(value != 0),
2235
2951
  6 => fx.setVideoLoop(value != 0),
2952
+ 7 => {
2953
+ fx.restartVideo();
2954
+ video_entry.token = fx.videoMintedToken();
2955
+ },
2236
2956
  else => @panic("ts core host: unknown video_ctl verb wire value - the core and this runtime disagree on cmd_format_version"),
2237
2957
  }
2238
2958
  }
@@ -2252,7 +2972,11 @@ pub fn TsCoreHost(comptime core: type) type {
2252
2972
  /// starts the next clip from `completed`), and video_ctl
2253
2973
  /// `stop` is the explicit close.
2254
2974
  fn videoEventMsg(event: runtime_effects.EffectVideo) Msg {
2255
- return msgFromTagVideo(@intCast(event.key & 0xFF), event);
2975
+ const tag = if (comptime @hasDecl(core, "nativeEffectPolicy"))
2976
+ compiledPlaybackEvent(true, video_entry.used, video_entry.event_tag, event.key)
2977
+ else
2978
+ @as(u8, @intCast(event.key & 0xFF));
2979
+ return msgFromTagVideo(tag, event);
2256
2980
  }
2257
2981
 
2258
2982
  /// Issue one image load. The keyed-effect discipline here is
@@ -2276,39 +3000,53 @@ pub fn TsCoreHost(comptime core: type) type {
2276
3000
  cache_path: []const u8,
2277
3001
  expected: f64,
2278
3002
  ) void {
2279
- // Strictly BELOW 2^53 (the SDK contract): at 2^53 the f64
2280
- // grid steps by 2, so 2^53 is the first value that aliases
2281
- // a neighbor (2^53 + 1) on the wire — the bridge rejects it
2282
- // rather than guess which integer the app meant. 2^53 - 1
2283
- // is the last id every tier carries exactly.
2284
- const representable = std.math.isFinite(id_value) and
2285
- id_value >= 1 and id_value < 9007199254740992.0 and
2286
- @floor(id_value) == id_value;
2287
- if (!representable) {
2288
- fx.stageLoopMsg(msgFromTagImage(event_tag, .{ .id = 0, .outcome = .rejected }));
2289
- return;
2290
- }
2291
- const id: u64 = @intFromFloat(id_value);
2292
- if (findImage(id) != null) {
2293
- fx.stageLoopMsg(msgFromTagImage(event_tag, .{ .id = id, .outcome = .rejected }));
2294
- return;
2295
- }
2296
- const index = freeImageIndex() orelse {
2297
- // All 16 entries hold live loads — one gallery screen's
2298
- // Cmd.batch reaches this. The engine answers its own
2299
- // slot exhaustion with a dynamic `.rejected` result, and
2300
- // the audio channel's exhaustion story is a quiet
2301
- // in-place replace; a full bridge table speaks the same
2302
- // vocabulary: exactly one rejected result through the
2303
- // event arm, never a crash — however many loads one
2304
- // batch stages against it.
2305
- fx.stageLoopMsg(msgFromTagImage(event_tag, .{ .id = id, .outcome = .rejected }));
2306
- return;
3003
+ const Selection = struct { key: u64, index: usize, tag: u8, expected_bytes: u64 };
3004
+ const selection: ?Selection = if (comptime @hasDecl(core, "nativeEffectPolicy")) blk: {
3005
+ const plan = compiledMediaPlan(0, 3, @bitCast(id_value), 0, event_tag, .microphone, 0, 0, expected, &images);
3006
+ const index = plan.slot orelse {
3007
+ fx.stageLoopMsg(msgFromTagImage(plan.tag, .{ .id = plan.key, .outcome = .rejected }));
3008
+ break :blk null;
3009
+ };
3010
+ break :blk .{ .key = plan.key, .index = index, .tag = plan.tag, .expected_bytes = plan.expected_bytes };
3011
+ } else native: {
3012
+ // Strictly BELOW 2^53 (the SDK contract): at 2^53 the f64
3013
+ // grid steps by 2, so 2^53 is the first value that aliases
3014
+ // a neighbor (2^53 + 1) on the wire — the bridge rejects it
3015
+ // rather than guess which integer the app meant. 2^53 - 1
3016
+ // is the last id every tier carries exactly.
3017
+ const representable = std.math.isFinite(id_value) and
3018
+ id_value >= 1 and id_value < 9007199254740992.0 and
3019
+ @floor(id_value) == id_value;
3020
+ if (!representable) {
3021
+ fx.stageLoopMsg(msgFromTagImage(event_tag, .{ .id = 0, .outcome = .rejected }));
3022
+ break :native null;
3023
+ }
3024
+ const id: u64 = @intFromFloat(id_value);
3025
+ if (findImage(id) != null) {
3026
+ fx.stageLoopMsg(msgFromTagImage(event_tag, .{ .id = id, .outcome = .rejected }));
3027
+ break :native null;
3028
+ }
3029
+ const index = freeImageIndex() orelse {
3030
+ // All 16 entries hold live loads — one gallery screen's
3031
+ // Cmd.batch reaches this. The engine answers its own
3032
+ // slot exhaustion with a dynamic `.rejected` result, and
3033
+ // the audio channel's exhaustion story is a quiet
3034
+ // in-place replace; a full bridge table speaks the same
3035
+ // vocabulary: exactly one rejected result through the
3036
+ // event arm, never a crash — however many loads one
3037
+ // batch stages against it.
3038
+ fx.stageLoopMsg(msgFromTagImage(event_tag, .{ .id = id, .outcome = .rejected }));
3039
+ break :native null;
3040
+ };
3041
+ break :native .{ .key = id, .index = index, .tag = event_tag, .expected_bytes = if (expected >= 1 and expected < 9007199254740992.0 and @floor(expected) == expected) @intFromFloat(expected) else 0 };
2307
3042
  };
3043
+ const chosen = selection orelse return;
3044
+ const id = chosen.key;
3045
+ const index = chosen.index;
2308
3046
  const entry = &images[index];
2309
3047
  entry.used = true;
2310
3048
  entry.id = id;
2311
- entry.event_tag = event_tag;
3049
+ entry.event_tag = chosen.tag;
2312
3050
  fx.loadImage(.{
2313
3051
  .id = id,
2314
3052
  .path = image_path,
@@ -2329,15 +3067,31 @@ pub fn TsCoreHost(comptime core: type) type {
2329
3067
  // size every real download misses. 0 is the honest
2330
3068
  // mapping; the emitter already stops the literal
2331
3069
  // spellings (NS1030).
2332
- .expected_bytes = if (expected >= 1 and expected < 9007199254740992.0 and @floor(expected) == expected)
2333
- @intFromFloat(expected)
2334
- else
2335
- 0,
3070
+ .expected_bytes = chosen.expected_bytes,
2336
3071
  .on_result = imageResultMsg,
2337
3072
  });
2338
3073
  }
2339
3074
 
3075
+ fn imageWordIdValid(id: u64) bool {
3076
+ return id != 0 and id >> 63 == 0;
3077
+ }
3078
+
3079
+ fn issueImageLoadWords(fx: *Fx, id: u64, tag: u8, image_path: []const u8, url: []const u8, cache: []const u8, expected: f64) void {
3080
+ const plan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
3081
+ compiledMediaIdentityPlan(0, 3, id, 0, tag, .microphone, 0, 0, expected, &images, true)
3082
+ else
3083
+ MediaPlan{ .valid = imageWordIdValid(id), .slot = if (imageWordIdValid(id) and findImage(id) == null) freeImageIndex() else null, .key = id, .tag = tag, .retire = false, .expected_bytes = if (expected >= 1 and expected < 9007199254740992.0 and @floor(expected) == expected) @intFromFloat(expected) else 0, .source = .microphone, .sample_rate = 0, .capture_channels = 0 };
3084
+ const index = plan.slot orelse {
3085
+ // Invalid identities still echo the complete requested words.
3086
+ fx.stageLoopMsg(msgFromTagImage(tag, .{ .id = id, .outcome = .rejected }));
3087
+ return;
3088
+ };
3089
+ images[index] = .{ .used = true, .id = plan.key, .event_tag = plan.tag };
3090
+ fx.loadImage(.{ .id = plan.key, .path = image_path, .url = url, .cache_path = effectiveImageCachePath(cache, url), .expected_bytes = plan.expected_bytes, .on_result = imageResultMsg });
3091
+ }
3092
+
2340
3093
  fn findImage(id: u64) ?usize {
3094
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) return compiledMediaLookup(0, id, &images);
2341
3095
  for (&images, 0..) |*entry, index| {
2342
3096
  if (entry.used and entry.id == id) return index;
2343
3097
  }
@@ -2363,13 +3117,18 @@ pub fn TsCoreHost(comptime core: type) type {
2363
3117
  /// bridge namespace), and every bridge key base sits above 2^53,
2364
3118
  /// so the cancel can never reach another table's slot.
2365
3119
  fn runImageCancel(fx: *Fx, id_value: f64) void {
3120
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3121
+ const plan = compiledMediaPlan(0, 4, @bitCast(id_value), 0, 0, .microphone, 0, 0, 0, &images);
3122
+ if (plan.slot != null) fx.cancelImage(plan.key);
3123
+ return;
3124
+ }
2366
3125
  const representable = std.math.isFinite(id_value) and
2367
3126
  id_value >= 1 and id_value < 9007199254740992.0 and
2368
3127
  @floor(id_value) == id_value;
2369
3128
  if (!representable) return;
2370
3129
  const id: u64 = @intFromFloat(id_value);
2371
3130
  if (findImage(id) == null) return;
2372
- fx.cancel(id);
3131
+ fx.cancelImage(id);
2373
3132
  }
2374
3133
 
2375
3134
  /// The image_unregister record: free the registry slot under
@@ -2385,6 +3144,11 @@ pub fn TsCoreHost(comptime core: type) type {
2385
3144
  /// id the wire cannot carry exactly could never have been
2386
3145
  /// registered through this bridge, so it no-ops the same way.
2387
3146
  fn runImageUnregister(fx: *Fx, id_value: f64) void {
3147
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3148
+ const plan = compiledMediaPlan(0, 4, @bitCast(id_value), 0, 0, .microphone, 0, 0, 0, &[_]ImageEntry{});
3149
+ if (plan.valid) _ = fx.unregisterImage(plan.key);
3150
+ return;
3151
+ }
2388
3152
  const representable = std.math.isFinite(id_value) and
2389
3153
  id_value >= 1 and id_value < 9007199254740992.0 and
2390
3154
  @floor(id_value) == id_value;
@@ -2396,6 +3160,12 @@ pub fn TsCoreHost(comptime core: type) type {
2396
3160
  /// `ImageMsgFn` for image loads: the ONE terminal routes the
2397
3161
  /// entry's event arm and retires the entry.
2398
3162
  fn imageResultMsg(result: runtime_effects.EffectImageResult) Msg {
3163
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3164
+ const plan = compiledMediaPlan(0, 5, result.id, 0, 0, .microphone, 0, 0, 0, &images);
3165
+ const index = plan.slot orelse @panic("ts core host: image result has no compiled owner");
3166
+ if (plan.retire) images[index].used = false;
3167
+ return msgFromTagImage(plan.tag, result);
3168
+ }
2399
3169
  const index = findImage(result.id) orelse
2400
3170
  @panic("ts core host: an image result arrived with no open bridge entry");
2401
3171
  const entry = &images[index];
@@ -2425,27 +3195,42 @@ pub fn TsCoreHost(comptime core: type) type {
2425
3195
  event_tag: u8,
2426
3196
  max_pending: u8,
2427
3197
  ) bool {
2428
- const representable = std.math.isFinite(key_value) and
2429
- key_value >= 1 and key_value < 9007199254740992.0 and
2430
- @floor(key_value) == key_value;
2431
- if (!representable) {
2432
- fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = 0, .kind = .rejected }));
2433
- return false;
2434
- }
2435
- const key: u64 = @intFromFloat(key_value);
2436
- if (findChannel(key) != null) {
2437
- fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = key, .kind = .rejected }));
2438
- return false;
2439
- }
2440
- const index = freeChannelIndex() orelse {
2441
- fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = key, .kind = .rejected }));
2442
- return false;
3198
+ const Selection = struct { key: u64, index: usize, tag: u8 };
3199
+ const selection: ?Selection = if (comptime @hasDecl(core, "nativeEffectPolicy")) blk: {
3200
+ const plan = compiledMediaPlan(1, 3, @bitCast(key_value), 0, event_tag, .microphone, 0, 0, 0, &channels);
3201
+ const index = plan.slot orelse {
3202
+ fx.stageLoopMsg(msgFromTagChannel(plan.tag, .{ .key = plan.key, .kind = .rejected }));
3203
+ break :blk null;
3204
+ };
3205
+ break :blk .{ .key = plan.key, .index = index, .tag = plan.tag };
3206
+ } else native: {
3207
+ const representable = std.math.isFinite(key_value) and
3208
+ key_value >= 1 and key_value < 9007199254740992.0 and
3209
+ @floor(key_value) == key_value;
3210
+ if (!representable) {
3211
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = 0, .kind = .rejected }));
3212
+ break :native null;
3213
+ }
3214
+ const key: u64 = @intFromFloat(key_value);
3215
+ if (findChannel(key) != null) {
3216
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = key, .kind = .rejected }));
3217
+ break :native null;
3218
+ }
3219
+ const index = freeChannelIndex() orelse {
3220
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = key, .kind = .rejected }));
3221
+ break :native null;
3222
+ };
3223
+ break :native .{ .key = key, .index = index, .tag = event_tag };
2443
3224
  };
3225
+ const chosen = selection orelse return false;
3226
+ const key = chosen.key;
3227
+ const index = chosen.index;
2444
3228
  const entry = &channels[index];
2445
3229
  entry.used = true;
2446
3230
  entry.key = key;
2447
- entry.event_tag = event_tag;
2448
- _ = fx.openChannel(.{
3231
+ entry.event_tag = chosen.tag;
3232
+ const already_open = fx.channelHandle(key) != null;
3233
+ const opened = fx.openChannel(.{
2449
3234
  .key = key,
2450
3235
  .on_event = channelEventMsg,
2451
3236
  .max_pending = max_pending,
@@ -2454,10 +3239,11 @@ pub fn TsCoreHost(comptime core: type) type {
2454
3239
  // both live execution and replay (whose accepted handle is inert).
2455
3240
  // Validation and capacity refusals stage their rejection without
2456
3241
  // leaving an open slot.
2457
- return fx.channelHandle(key) != null;
3242
+ return opened.live() or (!already_open and fx.replayArmed() and fx.channelHandle(key) != null);
2458
3243
  }
2459
3244
 
2460
3245
  fn findChannel(key: u64) ?usize {
3246
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) return compiledMediaLookup(1, key, &channels);
2461
3247
  for (&channels, 0..) |*entry, index| {
2462
3248
  if (entry.used and entry.key == key) return index;
2463
3249
  }
@@ -2481,6 +3267,11 @@ pub fn TsCoreHost(comptime core: type) type {
2481
3267
  /// convention; every bridge key base sits above 2^53, so this
2482
3268
  /// can never reach another table's slot).
2483
3269
  fn runChannelClose(fx: *Fx, key_value: f64) void {
3270
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3271
+ const plan = compiledMediaPlan(1, 4, @bitCast(key_value), 0, 0, .microphone, 0, 0, 0, &channels);
3272
+ if (plan.slot != null) fx.closeChannel(plan.key);
3273
+ return;
3274
+ }
2484
3275
  const representable = std.math.isFinite(key_value) and
2485
3276
  key_value >= 1 and key_value < 9007199254740992.0 and
2486
3277
  @floor(key_value) == key_value;
@@ -2495,6 +3286,17 @@ pub fn TsCoreHost(comptime core: type) type {
2495
3286
  /// terminals retire the entry (freeing the key for a fresh
2496
3287
  /// open), `data` events keep it live — the spawn stream shape.
2497
3288
  fn channelEventMsg(event: runtime_effects.EffectChannelEvent) Msg {
3289
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3290
+ const kind: u8 = switch (event.kind) {
3291
+ .data => 0,
3292
+ .closed => 1,
3293
+ .rejected => 2,
3294
+ };
3295
+ const plan = compiledMediaPlan(1, 5, event.key, kind, 0, .microphone, 0, 0, 0, &channels);
3296
+ const index = plan.slot orelse @panic("ts core host: channel event has no compiled owner");
3297
+ if (plan.retire) channels[index].used = false;
3298
+ return msgFromTagChannel(plan.tag, event);
3299
+ }
2498
3300
  const index = findChannel(event.key) orelse
2499
3301
  @panic("ts core host: a channel event arrived with no open bridge entry");
2500
3302
  const entry = &channels[index];
@@ -2512,62 +3314,77 @@ pub fn TsCoreHost(comptime core: type) type {
2512
3314
  capture_channels: u8,
2513
3315
  event_tag: u8,
2514
3316
  ) void {
2515
- const representable = std.math.isFinite(key_value) and
2516
- key_value >= 1 and key_value < 9007199254740992.0 and
2517
- @floor(key_value) == key_value;
2518
- const format: platform.AudioCaptureFormat = .{
2519
- .sample_rate = sample_rate,
2520
- .channels = capture_channels,
2521
- };
2522
- if (!representable or !format.valid()) {
2523
- fx.stageLoopMsg(msgFromTagAudioCapture(event_tag, .{
2524
- .key = if (representable) @intFromFloat(key_value) else 0,
2525
- .kind = .rejected,
2526
- .source = source,
2527
- .sample_rate = sample_rate,
2528
- .channels = capture_channels,
2529
- }));
2530
- return;
2531
- }
2532
- const key: u64 = @intFromFloat(key_value);
2533
- if (findAudioCapture(key) != null) {
2534
- fx.stageLoopMsg(msgFromTagAudioCapture(event_tag, .{
2535
- .key = key,
2536
- .kind = .rejected,
2537
- .source = source,
2538
- .sample_rate = sample_rate,
2539
- .channels = capture_channels,
2540
- }));
2541
- return;
2542
- }
2543
- const index = freeAudioCaptureIndex() orelse {
2544
- fx.stageLoopMsg(msgFromTagAudioCapture(event_tag, .{
2545
- .key = key,
2546
- .kind = .rejected,
2547
- .source = source,
3317
+ const Selection = struct { key: u64, index: usize, tag: u8, source: platform.AudioCaptureSource, rate: u32, channels: u8 };
3318
+ const selection: ?Selection = if (comptime @hasDecl(core, "nativeEffectPolicy")) blk: {
3319
+ const plan = compiledMediaPlan(2, 3, @bitCast(key_value), 0, event_tag, source, sample_rate, capture_channels, 0, &audio_captures);
3320
+ const index = plan.slot orelse {
3321
+ fx.stageLoopMsg(msgFromTagAudioCapture(plan.tag, .{ .key = plan.key, .kind = .rejected, .source = plan.source, .sample_rate = plan.sample_rate, .channels = plan.capture_channels }));
3322
+ break :blk null;
3323
+ };
3324
+ break :blk .{ .key = plan.key, .index = index, .tag = plan.tag, .source = plan.source, .rate = plan.sample_rate, .channels = plan.capture_channels };
3325
+ } else native: {
3326
+ const representable = std.math.isFinite(key_value) and
3327
+ key_value >= 1 and key_value < 9007199254740992.0 and
3328
+ @floor(key_value) == key_value;
3329
+ const format: platform.AudioCaptureFormat = .{
2548
3330
  .sample_rate = sample_rate,
2549
3331
  .channels = capture_channels,
2550
- }));
2551
- return;
3332
+ };
3333
+ if (!representable or !format.valid()) {
3334
+ fx.stageLoopMsg(msgFromTagAudioCapture(event_tag, .{
3335
+ .key = if (representable) @intFromFloat(key_value) else 0,
3336
+ .kind = .rejected,
3337
+ .source = source,
3338
+ .sample_rate = sample_rate,
3339
+ .channels = capture_channels,
3340
+ }));
3341
+ break :native null;
3342
+ }
3343
+ const key: u64 = @intFromFloat(key_value);
3344
+ if (findAudioCapture(key) != null) {
3345
+ fx.stageLoopMsg(msgFromTagAudioCapture(event_tag, .{
3346
+ .key = key,
3347
+ .kind = .rejected,
3348
+ .source = source,
3349
+ .sample_rate = sample_rate,
3350
+ .channels = capture_channels,
3351
+ }));
3352
+ break :native null;
3353
+ }
3354
+ const index = freeAudioCaptureIndex() orelse {
3355
+ fx.stageLoopMsg(msgFromTagAudioCapture(event_tag, .{
3356
+ .key = key,
3357
+ .kind = .rejected,
3358
+ .source = source,
3359
+ .sample_rate = sample_rate,
3360
+ .channels = capture_channels,
3361
+ }));
3362
+ break :native null;
3363
+ };
3364
+ break :native .{ .key = key, .index = index, .tag = event_tag, .source = source, .rate = sample_rate, .channels = capture_channels };
2552
3365
  };
3366
+ const chosen = selection orelse return;
3367
+ const key = chosen.key;
3368
+ const index = chosen.index;
2553
3369
  audio_captures[index] = .{
2554
3370
  .used = true,
2555
3371
  .key = key,
2556
- .event_tag = event_tag,
2557
- .source = source,
2558
- .sample_rate = sample_rate,
2559
- .channels = capture_channels,
3372
+ .event_tag = chosen.tag,
3373
+ .source = chosen.source,
3374
+ .sample_rate = chosen.rate,
3375
+ .channels = chosen.channels,
2560
3376
  };
2561
3377
  fx.startAudioCapture(.{
2562
3378
  .key = key,
2563
- .source = source,
2564
- .sample_rate = sample_rate,
2565
- .channels = capture_channels,
3379
+ .source = chosen.source,
3380
+ .sample_rate = chosen.rate,
3381
+ .channels = chosen.channels,
2566
3382
  .on_event = audioCaptureEventMsg,
2567
3383
  });
2568
3384
  }
2569
3385
 
2570
3386
  fn findAudioCapture(key: u64) ?usize {
3387
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) return compiledMediaLookup(2, key, &audio_captures);
2571
3388
  for (&audio_captures, 0..) |*entry, index| {
2572
3389
  if (entry.used and entry.key == key) return index;
2573
3390
  }
@@ -2582,6 +3399,11 @@ pub fn TsCoreHost(comptime core: type) type {
2582
3399
  }
2583
3400
 
2584
3401
  fn runAudioCaptureStop(fx: *Fx, key_value: f64) void {
3402
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3403
+ const plan = compiledMediaPlan(2, 4, @bitCast(key_value), 0, 0, .microphone, 0, 0, 0, &audio_captures);
3404
+ if (plan.slot != null) fx.stopAudioCapture(plan.key);
3405
+ return;
3406
+ }
2585
3407
  const representable = std.math.isFinite(key_value) and
2586
3408
  key_value >= 1 and key_value < 9007199254740992.0 and
2587
3409
  @floor(key_value) == key_value;
@@ -2592,6 +3414,23 @@ pub fn TsCoreHost(comptime core: type) type {
2592
3414
  }
2593
3415
 
2594
3416
  fn audioCaptureEventMsg(channel_event: runtime_effects.EffectChannelEvent) Msg {
3417
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3418
+ var event = runtime_effects.decodeAudioCaptureChannelEvent(channel_event);
3419
+ const kind: u8 = switch (event.kind) {
3420
+ .started => 0,
3421
+ .data => 1,
3422
+ .failed => 2,
3423
+ .stopped => 3,
3424
+ .rejected => 4,
3425
+ };
3426
+ const plan = compiledMediaPlan(2, 5, channel_event.key, kind, 0, event.source, event.sample_rate, event.channels, 0, &audio_captures);
3427
+ const index = plan.slot orelse @panic("ts core host: capture event has no compiled owner");
3428
+ event.source = plan.source;
3429
+ event.sample_rate = plan.sample_rate;
3430
+ event.channels = plan.capture_channels;
3431
+ if (plan.retire) audio_captures[index].used = false;
3432
+ return msgFromTagAudioCapture(plan.tag, event);
3433
+ }
2595
3434
  const index = findAudioCapture(channel_event.key) orelse
2596
3435
  @panic("ts core host: an audio capture event arrived with no open bridge entry");
2597
3436
  const entry = &audio_captures[index];
@@ -2618,6 +3457,44 @@ pub fn TsCoreHost(comptime core: type) type {
2618
3457
  /// "rejected" exit through the entry's own event arm — never
2619
3458
  /// silent — and a transport that could not start as one
2620
3459
  /// "spawn_failed".
3460
+ const PtyPlan = struct { slot: ?usize, tag: u8, retire: bool, bind: bool, cols: u16, rows: u16, engine_key: u64 };
3461
+
3462
+ fn compiledPtyPlan(action: u8, key: []const u8, tag: u8, cols: f64, rows: f64, blocked: bool, event_key: u64, event_kind: u8) PtyPlan {
3463
+ var request: [32 + max_wire_key_bytes + runtime_effects.max_effect_ptys * (4 + max_wire_key_bytes)]u8 = @splat(0);
3464
+ request[0] = 9;
3465
+ request[1] = action;
3466
+ request[2] = @intCast(ptys.len);
3467
+ request[3] = @intFromBool(blocked);
3468
+ request[4] = event_kind;
3469
+ request[5] = tag;
3470
+ request[6] = @intCast(key.len);
3471
+ std.mem.writeInt(u64, request[8..16], event_key, .little);
3472
+ std.mem.writeInt(u64, request[16..24], @bitCast(cols), .little);
3473
+ std.mem.writeInt(u64, request[24..32], @bitCast(rows), .little);
3474
+ @memcpy(request[32..][0..key.len], key);
3475
+ var at: usize = 32 + key.len;
3476
+ for (&ptys) |*entry| {
3477
+ request[at] = @intFromBool(entry.used);
3478
+ request[at + 1] = @intFromBool(entry.bound);
3479
+ request[at + 2] = entry.event_tag;
3480
+ request[at + 3] = @intCast(entry.key_len);
3481
+ @memcpy(request[at + 4 ..][0..entry.key_len], entry.wireKey());
3482
+ at += 4 + entry.key_len;
3483
+ }
3484
+ var result: [16]u8 = undefined;
3485
+ if (core.nativeEffectPolicy(request[0..at], &result) != result.len or result[2] > 1 or result[3] > 1)
3486
+ @panic("ts core host: invalid compiled PTY plan");
3487
+ const slot: ?usize = if (result[0] == 255) null else result[0];
3488
+ const engine_key = std.mem.readInt(u64, result[8..16], .little);
3489
+ if (slot) |index| {
3490
+ if (index >= ptys.len or engine_key != pty_key_base + index)
3491
+ @panic("ts core host: invalid compiled PTY identity");
3492
+ if ((action == 0 and ptys[index].used) or ((action == 1 or action == 2 or action == 4) and !ptys[index].used))
3493
+ @panic("ts core host: compiled PTY plan names an invalid owner");
3494
+ } else if (engine_key != 0) @panic("ts core host: absent compiled PTY identity is nonzero");
3495
+ return .{ .slot = slot, .tag = result[1], .retire = result[2] == 1, .bind = result[3] == 1, .cols = std.mem.readInt(u16, result[4..6], .little), .rows = std.mem.readInt(u16, result[6..8], .little), .engine_key = engine_key };
3496
+ }
3497
+
2621
3498
  fn issuePtySpawn(
2622
3499
  fx: *Fx,
2623
3500
  key: []const u8,
@@ -2627,47 +3504,38 @@ pub fn TsCoreHost(comptime core: type) type {
2627
3504
  term: []const u8,
2628
3505
  argv: []const []const u8,
2629
3506
  ) void {
2630
- if (key.len > 0 and (findPty(key) != null or fileStreamOccupiesKey(key))) {
2631
- // The rejection is STAGED (delivered a later frame), so its
2632
- // key must be self-contained: the wire key points into this
2633
- // dispatch's command buffer, gone by delivery, so intern
2634
- // it in the engine's instance-lived staged-key store and
2635
- // reference that. The app's key rides the refusal,
2636
- // correlating it with its command — and the interned
2637
- // slice stays valid even committed into the model.
2638
- fx.stageLoopMsg(msgFromTagPty(event_tag, fx.stageLoopKey(key), true, .{ .key = 0, .kind = .exit, .reason = .rejected }));
2639
- return;
2640
- }
2641
- const index = freePtyIndex() orelse {
2642
- // The bridge table mirrors the engine's pty table, whose
2643
- // own exhaustion answer is the same rejected exit — one
2644
- // vocabulary for every refusal, never a crash. Staged, so
2645
- // the requested key rides the engine's interned
2646
- // instance-lived staged-key store, not the frame arena.
2647
- fx.stageLoopMsg(msgFromTagPty(event_tag, fx.stageLoopKey(key), true, .{ .key = 0, .kind = .exit, .reason = .rejected }));
3507
+ const plan: PtyPlan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
3508
+ compiledPtyPlan(0, key, event_tag, cols, rows, reservedWireKeyOccupied(key), 0, 0)
3509
+ else blk: {
3510
+ const index = if (key.len > 0 and (findPty(key) != null or reservedWireKeyOccupied(key))) null else reusableBoundPty(key) orelse freePtyIndex();
3511
+ break :blk .{ .slot = index, .tag = event_tag, .retire = false, .bind = false, .cols = ptyDimension(cols), .rows = ptyDimension(rows), .engine_key = if (index) |i| pty_key_base + i else 0 };
3512
+ };
3513
+ const index = plan.slot orelse {
3514
+ // Refusals outlive the borrowed command frame; intern their key.
3515
+ fx.stageLoopMsg(msgFromTagPty(plan.tag, fx.stageLoopKey(key), true, .{ .key = 0, .kind = .exit, .reason = .rejected }));
2648
3516
  return;
2649
3517
  };
2650
3518
  const entry = &ptys[index];
2651
3519
  entry.used = true;
2652
3520
  entry.key_len = key.len;
2653
3521
  @memcpy(entry.key[0..key.len], key);
2654
- entry.event_tag = event_tag;
3522
+ entry.event_tag = plan.tag;
2655
3523
  if (term.len == 0) {
2656
3524
  // Wire "" = "the engine's default TERM" — the record
2657
3525
  // never bakes the default in (the fetch-timeout rule).
2658
3526
  fx.ptySpawn(.{
2659
- .key = pty_key_base + index,
3527
+ .key = plan.engine_key,
2660
3528
  .argv = argv,
2661
- .cols = ptyDimension(cols),
2662
- .rows = ptyDimension(rows),
3529
+ .cols = plan.cols,
3530
+ .rows = plan.rows,
2663
3531
  .on_event = ptyEventMsg,
2664
3532
  });
2665
3533
  } else {
2666
3534
  fx.ptySpawn(.{
2667
- .key = pty_key_base + index,
3535
+ .key = plan.engine_key,
2668
3536
  .argv = argv,
2669
- .cols = ptyDimension(cols),
2670
- .rows = ptyDimension(rows),
3537
+ .cols = plan.cols,
3538
+ .rows = plan.rows,
2671
3539
  .term = term,
2672
3540
  .on_event = ptyEventMsg,
2673
3541
  });
@@ -2691,6 +3559,11 @@ pub fn TsCoreHost(comptime core: type) type {
2691
3559
  /// the engine's clamp would otherwise shrink the child to a
2692
3560
  /// 1x1 the app never asked for).
2693
3561
  fn runPtyResize(fx: *Fx, key: []const u8, cols: f64, rows: f64) void {
3562
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3563
+ const plan = compiledPtyPlan(2, key, 0, cols, rows, false, 0, 0);
3564
+ if (plan.slot != null) fx.ptyResize(plan.engine_key, plan.cols, plan.rows);
3565
+ return;
3566
+ }
2694
3567
  const index = findPty(key) orelse return;
2695
3568
  const c = ptyDimension(cols);
2696
3569
  const r = ptyDimension(rows);
@@ -2699,6 +3572,7 @@ pub fn TsCoreHost(comptime core: type) type {
2699
3572
  }
2700
3573
 
2701
3574
  fn findPty(key: []const u8) ?usize {
3575
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) return compiledPtyPlan(1, key, 0, 0, 0, false, 0, 0).slot;
2702
3576
  if (key.len == 0) return null;
2703
3577
  for (&ptys, 0..) |*entry, index| {
2704
3578
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
@@ -2706,9 +3580,36 @@ pub fn TsCoreHost(comptime core: type) type {
2706
3580
  return null;
2707
3581
  }
2708
3582
 
3583
+ /// Named terminal bindings reserve their identity until this host resets.
3584
+ /// An ended grid remains addressable; another name cannot inherit it.
3585
+ pub fn resolvePtyKey(key: []const u8) u64 {
3586
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3587
+ const plan = compiledPtyPlan(3, key, 0, 0, 0, false, 0, 0);
3588
+ if (plan.slot) |index| if (plan.bind) {
3589
+ ptys[index].bound = true;
3590
+ };
3591
+ return plan.engine_key;
3592
+ }
3593
+ if (key.len == 0) return 0;
3594
+ for (&ptys, 0..) |*entry, index| {
3595
+ if ((entry.used or entry.bound) and std.mem.eql(u8, entry.wireKey(), key)) {
3596
+ entry.bound = true;
3597
+ return pty_key_base + index;
3598
+ }
3599
+ }
3600
+ return 0;
3601
+ }
3602
+
3603
+ fn reusableBoundPty(key: []const u8) ?usize {
3604
+ for (&ptys, 0..) |*entry, index| {
3605
+ if (entry.bound and !entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
3606
+ }
3607
+ return null;
3608
+ }
3609
+
2709
3610
  fn freePtyIndex() ?usize {
2710
3611
  for (&ptys, 0..) |*entry, index| {
2711
- if (!entry.used) return index;
3612
+ if (!entry.used and !entry.bound) return index;
2712
3613
  }
2713
3614
  return null;
2714
3615
  }
@@ -2718,6 +3619,12 @@ pub fn TsCoreHost(comptime core: type) type {
2718
3619
  /// (freeing the wire key for a fresh session), "output"
2719
3620
  /// batches keep it live — the spawn stream shape.
2720
3621
  fn ptyEventMsg(event: runtime_effects.EffectPtyEvent) Msg {
3622
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3623
+ const plan = compiledPtyPlan(4, "", 0, 0, 0, false, event.key, @intFromEnum(event.kind));
3624
+ const entry = &ptys[plan.slot orelse @panic("ts core host: compiled PTY event has no slot")];
3625
+ if (plan.retire) entry.used = false;
3626
+ return msgFromTagPty(plan.tag, entry.wireKey(), false, event);
3627
+ }
2721
3628
  if (event.key < pty_key_base) {
2722
3629
  @panic("ts core host: a pty event arrived outside the bridge's pty key namespace");
2723
3630
  }
@@ -2732,6 +3639,142 @@ pub fn TsCoreHost(comptime core: type) type {
2732
3639
  return msgFromTagPty(entry.event_tag, wire_key, false, event);
2733
3640
  }
2734
3641
 
3642
+ /// Native owns slots and opaque handles; the policy borrows an exact
3643
+ /// packed view and returns a copied plan before any capability runs.
3644
+ fn compiledRequestPlan(action: u8, pool: RequestPool, key: []const u8, blocked: bool, reject_duplicate: bool, ok_tag: u8, err_tag: u8, ok_void: bool, result_ok: bool, result_slot: u8, channel_occupied: bool) [16]u8 {
3645
+ var request: [16 + max_wire_key_bytes + requests.len * (15 + max_wire_key_bytes)]u8 = @splat(0);
3646
+ request[0..12].* = .{ 11, action, @intFromEnum(pool), @intCast(key.len), @intFromBool(blocked), @intFromBool(reject_duplicate), ok_tag, err_tag, @intFromBool(ok_void), @intFromBool(result_ok), result_slot, @intFromBool(channel_occupied) };
3647
+ @memcpy(request[16..][0..key.len], key);
3648
+ var at: usize = 16 + key.len;
3649
+ for (&requests) |*entry| {
3650
+ const name = if (entry.used) entry.wireKey() else "";
3651
+ request[at] = @intFromBool(entry.used);
3652
+ request[at + 1] = @intCast(name.len);
3653
+ @memcpy(request[at + 2 ..][0..name.len], name);
3654
+ const route = at + 2 + name.len;
3655
+ request[route..][0..5].* = .{ entry.ok_tag, entry.err_tag, @intFromBool(entry.ok_void), @intFromBool(entry.service_operation != null), @intFromBool(entry.service_channel != null) };
3656
+ std.mem.writeInt(u64, request[route + 5 ..][0..8], entry.service_channel orelse 0, .little);
3657
+ at = route + 13;
3658
+ }
3659
+ var result: [16]u8 = undefined;
3660
+ if (core.nativeEffectPolicy(request[0..at], &result) != result.len or result[6] != 0 or result[7] != 0)
3661
+ @panic("ts core host: invalid compiled request plan");
3662
+ for (result[0..2]) |slot| if (slot != 255 and slot >= requests.len)
3663
+ @panic("ts core host: invalid compiled request slot");
3664
+ if (action == 0) {
3665
+ if (result[4] > 1) @panic("ts core host: invalid compiled request void flag");
3666
+ if (result[0] != 255 and requestPoolAt(result[0]) != pool) @panic("ts core host: compiled request names the wrong pool");
3667
+ if (result[1] != 255 and (!requests[result[1]].used or requestPoolAt(result[1]) == pool or key.len == 0 or !std.mem.eql(u8, key, requests[result[1]].wireKey())))
3668
+ @panic("ts core host: invalid compiled request predecessor");
3669
+ if (result[0] != 255 and requests[result[0]].used and (key.len == 0 or !std.mem.eql(u8, key, requests[result[0]].wireKey())))
3670
+ @panic("ts core host: compiled request overwrites another owner");
3671
+ } else if (action == 1) {
3672
+ if (result[0] != 255 and (!requests[result[0]].used or !std.mem.eql(u8, key, requests[result[0]].wireKey())))
3673
+ @panic("ts core host: invalid compiled request lookup");
3674
+ } else if (action == 2) {
3675
+ if (result[0] != result_slot or result[3] > 2 or result[4] > 1 or result[5] > 1 or
3676
+ (result[3] == 2 and requests[result_slot].service_operation == null) or
3677
+ (result[5] == 1 and (requests[result_slot].service_channel == null or std.mem.readInt(u64, result[8..16], .little) != requests[result_slot].service_channel.?)))
3678
+ @panic("ts core host: invalid compiled request completion");
3679
+ } else if (result[3] > 3) @panic("ts core host: invalid compiled service guard");
3680
+ return result;
3681
+ }
3682
+
3683
+ fn compiledDbCommandPlan(action: u8, key: []const u8, blocked: bool, query: bool, page_tag: u8, done_tag: u8, err_tag: u8, result_slot: u8, result_kind: u8, outcome_ok: bool) [8]u8 {
3684
+ var request: [12 + max_wire_key_bytes + dbs.len * (7 + max_wire_key_bytes)]u8 = @splat(0);
3685
+ request[0..12].* = .{ 14, action, @intCast(key.len), @intFromBool(blocked), @intFromBool(query), page_tag, done_tag, err_tag, result_slot, result_kind, @intFromBool(outcome_ok), 0 };
3686
+ @memcpy(request[12..][0..key.len], key);
3687
+ var at: usize = 12 + key.len;
3688
+ for (&dbs) |*entry| {
3689
+ const name = if (entry.used) entry.wireKey() else "";
3690
+ request[at..][0..7].* = .{ @intFromBool(entry.used), @intFromBool(entry.query), @intFromBool(entry.live), entry.page_tag, entry.done_tag, entry.err_tag, @intCast(name.len) };
3691
+ @memcpy(request[at + 7 ..][0..name.len], name);
3692
+ at += 7 + name.len;
3693
+ }
3694
+ var result: [8]u8 = undefined;
3695
+ if (core.nativeEffectPolicy(request[0..at], &result) != result.len or result[5] > 2 or result[6] > 1 or result[7] != 0 or (result[0] != 255 and result[0] >= dbs.len))
3696
+ @panic("ts core host: invalid compiled database command plan");
3697
+ if (action == 0 and result[0] != 255 and dbs[result[0]].used and (key.len == 0 or !std.mem.eql(u8, key, dbs[result[0]].wireKey()) or !dbs[result[0]].query or dbs[result[0]].live))
3698
+ @panic("ts core host: compiled database command overwrites another owner");
3699
+ if (action == 1 and result[0] != result_slot) @panic("ts core host: compiled database completion changed its owner");
3700
+ return result;
3701
+ }
3702
+
3703
+ fn appendCancellationSlot(request: []u8, at: *usize, used: bool, flags: u8, key: []const u8, err_tag: u8) void {
3704
+ const name = if (used) key else "";
3705
+ request[at.*..][0..3].* = .{ @intFromBool(used), flags, @intCast(name.len) };
3706
+ @memcpy(request[at.* + 3 ..][0..name.len], name);
3707
+ request[at.* + 3 + name.len] = err_tag;
3708
+ at.* += 4 + name.len;
3709
+ }
3710
+
3711
+ fn compiledCancelWireKey(fx: *Fx, key: []const u8) void {
3712
+ const count = requests.len + effects_table.len + clipboard_writes.len + streams.len + file_streams.len + delays.len + dbs.len;
3713
+ var request: [2 + max_wire_key_bytes + count * (4 + max_wire_key_bytes)]u8 = @splat(0);
3714
+ request[0] = 12;
3715
+ request[1] = @intCast(key.len);
3716
+ @memcpy(request[2..][0..key.len], key);
3717
+ var at: usize = 2 + key.len;
3718
+ for (&requests) |*e| appendCancellationSlot(&request, &at, e.used, @intFromBool(e.service_channel != null), e.wireKey(), e.err_tag);
3719
+ for (&effects_table) |*e| appendCancellationSlot(&request, &at, e.used, @intFromBool(e.dropped), e.wireKey(), e.err_tag);
3720
+ for (&clipboard_writes) |*e| appendCancellationSlot(&request, &at, e.used, 0, e.wireKey(), e.tag);
3721
+ for (&streams) |*e| appendCancellationSlot(&request, &at, e.used, 0, e.wireKey(), e.err_tag);
3722
+ for (&file_streams) |*e| appendCancellationSlot(&request, &at, e.used, @intFromBool(e.sink), e.wireKey(), e.err_tag);
3723
+ for (&delays) |*e| appendCancellationSlot(&request, &at, e.used, 0, e.wireKey(), e.tag);
3724
+ for (&dbs) |*e| appendCancellationSlot(&request, &at, e.used, @as(u8, @intFromBool(e.query)) | (@as(u8, @intFromBool(e.live)) << 1), e.wireKey(), e.err_tag);
3725
+ var result: [8]u8 = undefined;
3726
+ if (core.nativeEffectPolicy(request[0..at], &result) != result.len or (result[0] != 255 and result[0] > 6))
3727
+ @panic("ts core host: invalid compiled cancellation plan");
3728
+ for (result[2..6]) |flag| if (flag > 1) @panic("ts core host: invalid compiled cancellation flag");
3729
+ if (result[7] > 1) @panic("ts core host: invalid compiled cancellation message flag");
3730
+ if (result[0] == 255) return;
3731
+ const slot: usize = result[1];
3732
+ // Authenticate table ownership independently of portable selection.
3733
+ const valid = switch (result[0]) {
3734
+ 0 => slot < requests.len and requests[slot].used and std.mem.eql(u8, key, requests[slot].wireKey()),
3735
+ 1 => slot < effects_table.len and effects_table[slot].used and !effects_table[slot].dropped and std.mem.eql(u8, key, effects_table[slot].wireKey()),
3736
+ 2 => slot < clipboard_writes.len and clipboard_writes[slot].used and std.mem.eql(u8, key, clipboard_writes[slot].wireKey()),
3737
+ 3 => slot < streams.len and streams[slot].used and std.mem.eql(u8, key, streams[slot].wireKey()),
3738
+ 4 => slot < file_streams.len and file_streams[slot].used and std.mem.eql(u8, key, file_streams[slot].wireKey()),
3739
+ 5 => slot < delays.len and delays[slot].used and std.mem.eql(u8, key, delays[slot].wireKey()),
3740
+ 6 => slot < dbs.len and dbs[slot].used and std.mem.eql(u8, key, dbs[slot].wireKey()),
3741
+ else => unreachable,
3742
+ };
3743
+ if (!valid or key.len == 0 or (result[5] == 1 and (result[0] != 0 or requests[slot].service_channel == null)) or (result[4] == 1 and result[0] != 4))
3744
+ @panic("ts core host: compiled cancellation names an invalid owner");
3745
+ switch (result[0]) {
3746
+ 0 => {
3747
+ if (result[3] == 1) fx.cancelHostRequest(request_key_base + slot);
3748
+ if (result[2] == 1) requests[slot].used = false;
3749
+ if (result[5] == 1) fx.closeChannel(requests[slot].service_channel.?);
3750
+ },
3751
+ 1 => if (result[3] == 1) {
3752
+ dropEffectEntry(fx, slot);
3753
+ },
3754
+ 2 => if (result[3] == 1) {
3755
+ fx.cancelNonImage(clipboard_result_key_base + slot);
3756
+ },
3757
+ 3 => if (result[3] == 1) {
3758
+ fx.cancelNonImage(spawn_key_base + slot);
3759
+ },
3760
+ 4 => {
3761
+ if (result[2] == 1) file_streams[slot].used = false;
3762
+ if (result[4] == 1) file_streams[slot].cancelling = true;
3763
+ if (result[3] == 1) fx.cancelNonImage(file_stream_key_base + slot);
3764
+ },
3765
+ 5 => {
3766
+ if (result[3] == 1) fx.cancelTimer(delay_key_base + slot);
3767
+ if (result[2] == 1) delays[slot].used = false;
3768
+ },
3769
+ 6 => {
3770
+ if (result[3] == 1) fx.cancelDbQuery(db_key_base + slot);
3771
+ if (result[2] == 1) dbs[slot].used = false;
3772
+ },
3773
+ else => unreachable,
3774
+ }
3775
+ if (result[7] == 1) fx.stageLoopMsg(msgFromTagStaticBytes(result[6], "cancelled"));
3776
+ }
3777
+
2735
3778
  fn allocDbEntry(
2736
3779
  fx: *Fx,
2737
3780
  key: []const u8,
@@ -2740,28 +3783,38 @@ pub fn TsCoreHost(comptime core: type) type {
2740
3783
  done_tag: u8,
2741
3784
  err_tag: u8,
2742
3785
  ) ?usize {
2743
- if (fileStreamOccupiesKey(key)) {
2744
- fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
2745
- return null;
2746
- }
2747
- const index = blk: {
2748
- if (key.len > 0) {
2749
- if (findDb(key)) |existing| {
2750
- // One-shot queries replace only earlier one-shot
2751
- // queries. A live subscription owns its slot until
2752
- // subscription reconciliation removes or re-arms it;
2753
- // a command with the same wire key must reject rather
2754
- // than silently erase that subscription.
2755
- if (query and dbs[existing].query and !dbs[existing].live) break :blk existing;
2756
- fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
2757
- return null;
2758
- }
2759
- }
2760
- break :blk freeDbIndex() orelse {
3786
+ const plan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
3787
+ compiledDbCommandPlan(0, key, reservedWireKeyOccupied(key), query, page_tag, done_tag, err_tag, 0, 0, false)
3788
+ else blk: {
3789
+ if (reservedWireKeyOccupied(key)) {
2761
3790
  fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
2762
3791
  return null;
3792
+ }
3793
+ const index = native: {
3794
+ if (key.len > 0) {
3795
+ if (findDb(key)) |existing| {
3796
+ // One-shot queries replace only earlier one-shot
3797
+ // queries. A live subscription owns its slot until
3798
+ // subscription reconciliation removes or re-arms it;
3799
+ // a command with the same wire key must reject rather
3800
+ // than silently erase that subscription.
3801
+ if (query and dbs[existing].query and !dbs[existing].live) break :native existing;
3802
+ fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
3803
+ return null;
3804
+ }
3805
+ }
3806
+ break :native freeDbIndex() orelse {
3807
+ fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
3808
+ return null;
3809
+ };
2763
3810
  };
3811
+ break :blk [8]u8{ @intCast(index), page_tag, done_tag, err_tag, 0, 0, 0, 0 };
2764
3812
  };
3813
+ if (plan[0] == 255) {
3814
+ fx.stageLoopMsg(msgFromTagStaticBytes(plan[3], "rejected"));
3815
+ return null;
3816
+ }
3817
+ const index: usize = plan[0];
2765
3818
  const entry = &dbs[index];
2766
3819
  entry.used = true;
2767
3820
  entry.query = query;
@@ -2769,13 +3822,14 @@ pub fn TsCoreHost(comptime core: type) type {
2769
3822
  entry.signature = 0;
2770
3823
  entry.key_len = key.len;
2771
3824
  @memcpy(entry.key[0..key.len], key);
2772
- entry.page_tag = page_tag;
2773
- entry.done_tag = done_tag;
2774
- entry.err_tag = err_tag;
3825
+ entry.page_tag = plan[1];
3826
+ entry.done_tag = plan[2];
3827
+ entry.err_tag = plan[3];
2775
3828
  return index;
2776
3829
  }
2777
3830
 
2778
3831
  fn findDb(key: []const u8) ?usize {
3832
+ if (comptime @hasDecl(core, "nativeDbPolicy")) return compiledDbLookup(key);
2779
3833
  if (key.len == 0) return null;
2780
3834
  for (&dbs, 0..) |*entry, index| {
2781
3835
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
@@ -2792,6 +3846,21 @@ pub fn TsCoreHost(comptime core: type) type {
2792
3846
  if (result.key < db_key_base) @panic("ts core host: a relational result arrived outside the bridge DB key namespace");
2793
3847
  const index = result.key - db_key_base;
2794
3848
  if (index >= dbs.len or !dbs[index].used) @panic("ts core host: a relational result arrived for an untracked command");
3849
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3850
+ const kind: u8 = switch (result.kind) {
3851
+ .page => 0,
3852
+ .done => 1,
3853
+ .exec => 2,
3854
+ };
3855
+ const plan = compiledDbCommandPlan(1, "", false, false, 0, 0, 0, @intCast(index), kind, result.outcome == .ok);
3856
+ if (plan[6] == 1) dbs[index].used = false;
3857
+ return switch (plan[5]) {
3858
+ 0 => msgFromTagBytes(plan[4], result.bytes),
3859
+ 1 => msgFromTagVoid(plan[4]),
3860
+ 2 => msgFromTagBytes(plan[4], @tagName(result.outcome)),
3861
+ else => unreachable,
3862
+ };
3863
+ }
2795
3864
  const entry = &dbs[index];
2796
3865
  if (result.outcome != .ok) {
2797
3866
  if (!entry.live) entry.used = false;
@@ -2823,6 +3892,7 @@ pub fn TsCoreHost(comptime core: type) type {
2823
3892
  /// Unknown keys are a no-op; the audio stream is not cancel's
2824
3893
  /// to end (audio_ctl `stop` closes it).
2825
3894
  fn cancelWireKey(fx: *Fx, key: []const u8) void {
3895
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) return compiledCancelWireKey(fx, key);
2826
3896
  if (key.len == 0) return;
2827
3897
  if (findRequest(key)) |index| {
2828
3898
  const entry = requests[index];
@@ -2838,10 +3908,14 @@ pub fn TsCoreHost(comptime core: type) type {
2838
3908
  dropEffectEntry(fx, index);
2839
3909
  return;
2840
3910
  }
3911
+ if (findClipboardWrite(key)) |index| {
3912
+ fx.cancelNonImage(clipboard_result_key_base + index);
3913
+ return;
3914
+ }
2841
3915
  if (findStream(key)) |index| {
2842
3916
  // The engine's `.cancelled` terminal retires the entry in
2843
3917
  // spawnExitMsg or fetchStreamResultMsg.
2844
- fx.cancel(spawn_key_base + index);
3918
+ fx.cancelNonImage(spawn_key_base + index);
2845
3919
  return;
2846
3920
  }
2847
3921
  if (findFileStream(key)) |index| {
@@ -2852,7 +3926,7 @@ pub fn TsCoreHost(comptime core: type) type {
2852
3926
  } else {
2853
3927
  file_streams[index].cancelling = true;
2854
3928
  }
2855
- fx.cancel(file_stream_key_base + index);
3929
+ fx.cancelNonImage(file_stream_key_base + index);
2856
3930
  return;
2857
3931
  }
2858
3932
  if (findDelay(key)) |index| {
@@ -2877,7 +3951,7 @@ pub fn TsCoreHost(comptime core: type) type {
2877
3951
  }
2878
3952
  }
2879
3953
 
2880
- const RequestPool = enum { host, store, credentials };
3954
+ const RequestPool = enum(u8) { host, store, credentials };
2881
3955
 
2882
3956
  fn requestPoolAt(index: usize) RequestPool {
2883
3957
  if (index < runtime_effects.max_effects) return .host;
@@ -2895,36 +3969,51 @@ pub fn TsCoreHost(comptime core: type) type {
2895
3969
  err_tag: u8,
2896
3970
  ok_void: bool,
2897
3971
  pool: RequestPool,
3972
+ reject_duplicate: bool,
2898
3973
  ) ?u64 {
2899
- if (fileStreamOccupiesKey(key)) return null;
2900
- const index = blk: {
2901
- if (key.len > 0) {
2902
- if (findRequest(key)) |existing| {
2903
- if (requestPoolAt(existing) == pool) break :blk existing;
2904
- fx.cancelHostRequest(request_key_base + existing);
2905
- requests[existing].used = false;
3974
+ const plan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
3975
+ compiledRequestPlan(0, pool, key, reservedWireKeyOccupied(key), reject_duplicate, ok_tag, err_tag, ok_void, false, 0, false)
3976
+ else blk: {
3977
+ if (reject_duplicate and key.len > 0 and findRequest(key) != null) return null;
3978
+ if (reservedWireKeyOccupied(key)) return null;
3979
+ const index = native: {
3980
+ if (key.len > 0) {
3981
+ if (findRequest(key)) |existing| {
3982
+ if (requestPoolAt(existing) == pool) break :native existing;
3983
+ fx.cancelHostRequest(request_key_base + existing);
3984
+ requests[existing].used = false;
3985
+ }
2906
3986
  }
2907
- }
2908
- break :blk switch (pool) {
2909
- .host => freeRequestIndex(),
2910
- .store => freeStoreRequestIndex(),
2911
- .credentials => freeCredentialsRequestIndex(),
2912
- } orelse return null;
3987
+ break :native switch (pool) {
3988
+ .host => freeRequestIndex(),
3989
+ .store => freeStoreRequestIndex(),
3990
+ .credentials => freeCredentialsRequestIndex(),
3991
+ } orelse return null;
3992
+ };
3993
+ var result: [16]u8 = @splat(0);
3994
+ result[0..5].* = .{ @intCast(index), 255, ok_tag, err_tag, @intFromBool(ok_void) };
3995
+ break :blk result;
2913
3996
  };
3997
+ if (plan[1] != 255) {
3998
+ fx.cancelHostRequest(request_key_base + plan[1]);
3999
+ requests[plan[1]].used = false;
4000
+ }
4001
+ if (plan[0] == 255) return null;
4002
+ const index: usize = plan[0];
2914
4003
  const entry = &requests[index];
2915
4004
  entry.used = true;
2916
4005
  entry.key_len = key.len;
2917
4006
  @memcpy(entry.key[0..key.len], key);
2918
- entry.ok_tag = ok_tag;
2919
- entry.err_tag = err_tag;
2920
- entry.ok_void = ok_void;
4007
+ entry.ok_tag = plan[2];
4008
+ entry.err_tag = plan[3];
4009
+ entry.ok_void = plan[4] == 1;
2921
4010
  entry.service_operation = null;
2922
4011
  entry.service_channel = null;
2923
4012
  return index;
2924
4013
  }
2925
4014
 
2926
4015
  fn allocStoreRequestEntry(fx: *Fx, head: RoutedHead, ok_void: bool) ?u64 {
2927
- const index = allocRequestEntry(fx, head.key, head.ok_tag, head.err_tag, ok_void, .store) orelse {
4016
+ const index = allocRequestEntry(fx, head.key, head.ok_tag, head.err_tag, ok_void, .store, false) orelse {
2928
4017
  fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
2929
4018
  return null;
2930
4019
  };
@@ -2932,7 +4021,7 @@ pub fn TsCoreHost(comptime core: type) type {
2932
4021
  }
2933
4022
 
2934
4023
  fn allocCredentialsRequestEntry(fx: *Fx, key: []const u8, ok_tag: u8, err_tag: u8, ok_void: bool) ?u64 {
2935
- const index = allocRequestEntry(fx, key, ok_tag, err_tag, ok_void, .credentials) orelse {
4024
+ const index = allocRequestEntry(fx, key, ok_tag, err_tag, ok_void, .credentials, false) orelse {
2936
4025
  fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
2937
4026
  return null;
2938
4027
  };
@@ -2950,11 +4039,7 @@ pub fn TsCoreHost(comptime core: type) type {
2950
4039
  issueCredentialsRequest(fx, name, key, ok_tag, err_tag, payload);
2951
4040
  return;
2952
4041
  }
2953
- if (key.len > 0 and findRequest(key) != null and (typed_service or fx.rejectsDuplicateHostRequestKeys())) {
2954
- stageRequestRejected(fx, err_tag);
2955
- return;
2956
- }
2957
- const index = allocRequestEntry(fx, key, ok_tag, err_tag, false, .host) orelse {
4042
+ const index = allocRequestEntry(fx, key, ok_tag, err_tag, false, .host, typed_service or fx.rejectsDuplicateHostRequestKeys()) orelse {
2958
4043
  stageRequestRejected(fx, err_tag);
2959
4044
  return;
2960
4045
  };
@@ -2977,6 +4062,34 @@ pub fn TsCoreHost(comptime core: type) type {
2977
4062
  }
2978
4063
 
2979
4064
  fn issueCredentialsRequest(fx: *Fx, name: []const u8, key: []const u8, ok_tag: u8, err_tag: u8, payload: []const u8) void {
4065
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4066
+ if (name.len > 255) {
4067
+ stageRequestRejected(fx, err_tag);
4068
+ return;
4069
+ }
4070
+ const request = core.rt.frameAlloc(u8, 2 + name.len + payload.len);
4071
+ request[0] = 13;
4072
+ request[1] = @intCast(name.len);
4073
+ @memcpy(request[2..][0..name.len], name);
4074
+ @memcpy(request[2 + name.len ..], payload);
4075
+ var plan: [20]u8 = undefined;
4076
+ if (core.nativeEffectPolicy(request, &plan) != plan.len or plan[0] > 1 or plan[1] > 2 or plan[2] != 0 or plan[3] != 0)
4077
+ @panic("ts core host: invalid compiled credential plan");
4078
+ if (plan[0] == 0) {
4079
+ stageRequestRejected(fx, err_tag);
4080
+ return;
4081
+ }
4082
+ const credential_key = credentialPlanBytes(payload, plan[4..12]);
4083
+ const secret = if (plan[1] == 0) credentialPlanBytes(payload, plan[12..20]) else "";
4084
+ const request_key = allocCredentialsRequestEntry(fx, key, ok_tag, err_tag, plan[1] != 1) orelse return;
4085
+ switch (plan[1]) {
4086
+ 0 => fx.credentialsSet(.{ .key = request_key, .credential_key = credential_key, .secret = secret, .host_result = hostResultMsg }),
4087
+ 1 => fx.credentialsGet(.{ .key = request_key, .credential_key = credential_key, .host_result = hostResultMsg }),
4088
+ 2 => fx.credentialsDelete(.{ .key = request_key, .credential_key = credential_key, .host_result = hostResultMsg }),
4089
+ else => unreachable,
4090
+ }
4091
+ return;
4092
+ }
2980
4093
  const is_set = std.mem.eql(u8, name, "core.credentials.set");
2981
4094
  const is_get = std.mem.eql(u8, name, "core.credentials.get");
2982
4095
  const is_delete = std.mem.eql(u8, name, "core.credentials.delete");
@@ -3033,6 +4146,13 @@ pub fn TsCoreHost(comptime core: type) type {
3033
4146
  }
3034
4147
  }
3035
4148
 
4149
+ fn credentialPlanBytes(payload: []const u8, span: *const [8]u8) []const u8 {
4150
+ const offset: usize = std.mem.readInt(u32, span[0..4], .little);
4151
+ const length: usize = std.mem.readInt(u32, span[4..8], .little);
4152
+ if (offset > payload.len or length > payload.len - offset) @panic("ts core host: compiled credential span is outside its borrowed packet");
4153
+ return payload[offset .. offset + length];
4154
+ }
4155
+
3036
4156
  /// Credential records can also arrive through public `Cmd.request`,
3037
4157
  /// so their inner fields are untrusted even though the outer command
3038
4158
  /// wire was emitted correctly. Decode them fallibly and route a
@@ -3064,27 +4184,48 @@ pub fn TsCoreHost(comptime core: type) type {
3064
4184
  max_pending: u8,
3065
4185
  payload: []const u8,
3066
4186
  ) void {
3067
- if (key.len > 0 and (findRequest(key) != null or fileStreamOccupiesKey(key))) {
3068
- stageRequestRejected(fx, err_tag);
3069
- return;
3070
- }
3071
- // Fail the existing request-table bound before opening a channel;
3072
- // an admission failure must not leave an orphaned stream.
3073
- if (freeRequestIndex() == null) {
3074
- @panic("ts core host: more than 16 host requests in flight - the request table mirrors the engine's max_effects slots");
3075
- }
3076
-
3077
- const channel_key = exactEngineKey(channel_value);
3078
- if (channel_key) |value| {
3079
- // `findChannel` covers every TS bridge occupancy, including a
3080
- // rejected terminal waiting to drain. `channelHandle` also
3081
- // sees an open embedder-owned channel and replay's parked
3082
- // occupancy. Never let this service acquire either one.
3083
- if (findChannel(value) != null or fx.channelHandle(value) != null) {
3084
- fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = value, .kind = .rejected }));
4187
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4188
+ const channel_key = exactEngineKey(channel_value);
4189
+ const occupied = if (channel_key) |value| findChannel(value) != null or fx.channelHandle(value) != null else false;
4190
+ const plan = compiledRequestPlan(3, .host, key, reservedWireKeyOccupied(key), true, ok_tag, err_tag, false, false, 0, occupied);
4191
+ switch (plan[3]) {
4192
+ 0 => {},
4193
+ 1 => {
4194
+ stageRequestRejected(fx, err_tag);
4195
+ return;
4196
+ },
4197
+ 2 => @panic("ts core host: more than 16 host requests in flight - the request table mirrors the engine's max_effects slots"),
4198
+ 3 => {
4199
+ const value = channel_key orelse @panic("ts core host: compiled service refusal names an invalid channel");
4200
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = value, .kind = .rejected }));
4201
+ stageRequestRejected(fx, err_tag);
4202
+ return;
4203
+ },
4204
+ else => unreachable,
4205
+ }
4206
+ } else {
4207
+ if (key.len > 0 and (findRequest(key) != null or reservedWireKeyOccupied(key))) {
3085
4208
  stageRequestRejected(fx, err_tag);
3086
4209
  return;
3087
4210
  }
4211
+ // Fail the existing request-table bound before opening a channel;
4212
+ // an admission failure must not leave an orphaned stream.
4213
+ if (freeRequestIndex() == null) {
4214
+ @panic("ts core host: more than 16 host requests in flight - the request table mirrors the engine's max_effects slots");
4215
+ }
4216
+
4217
+ const channel_key = exactEngineKey(channel_value);
4218
+ if (channel_key) |value| {
4219
+ // `findChannel` covers every TS bridge occupancy, including a
4220
+ // rejected terminal waiting to drain. `channelHandle` also
4221
+ // sees an open embedder-owned channel and replay's parked
4222
+ // occupancy. Never let this service acquire either one.
4223
+ if (findChannel(value) != null or fx.channelHandle(value) != null) {
4224
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = value, .kind = .rejected }));
4225
+ stageRequestRejected(fx, err_tag);
4226
+ return;
4227
+ }
4228
+ }
3088
4229
  }
3089
4230
 
3090
4231
  // Validation/table refusals generated by the bridge are final for
@@ -3101,6 +4242,10 @@ pub fn TsCoreHost(comptime core: type) type {
3101
4242
  }
3102
4243
 
3103
4244
  fn findRequest(key: []const u8) ?usize {
4245
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4246
+ const plan = compiledRequestPlan(1, .host, key, false, false, 0, 0, false, false, 0, false);
4247
+ return if (plan[0] == 255) null else plan[0];
4248
+ }
3104
4249
  for (&requests, 0..) |*entry, index| {
3105
4250
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
3106
4251
  }
@@ -3144,6 +4289,18 @@ pub fn TsCoreHost(comptime core: type) type {
3144
4289
  if (index >= requests.len or !requests[index].used) {
3145
4290
  @panic("ts core host: a host result arrived for a request the bridge is not tracking");
3146
4291
  }
4292
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4293
+ const plan = compiledRequestPlan(2, .host, "", false, false, 0, 0, false, result.ok, @intCast(index), false);
4294
+ const entry = requests[index];
4295
+ if (plan[4] == 1) requests[index].used = false;
4296
+ if (plan[5] == 1) pending_service_channel_close = std.mem.readInt(u64, plan[8..16], .little);
4297
+ return switch (plan[3]) {
4298
+ 0 => msgFromTagBytes(plan[2], result.bytes),
4299
+ 1 => msgFromTagVoid(plan[2]),
4300
+ 2 => (service_results orelse @panic("ts core host: a typed service result arrived after its decoder was unbound")).decode_fn(entry.service_operation.?, plan[2], result.bytes),
4301
+ else => unreachable,
4302
+ };
4303
+ }
3147
4304
  const entry = &requests[index];
3148
4305
  entry.used = false;
3149
4306
  if (entry.service_channel) |channel_key| pending_service_channel_close = channel_key;
@@ -3163,17 +4320,72 @@ pub fn TsCoreHost(comptime core: type) type {
3163
4320
  /// Retire the named-op entry an engine terminal names and hand
3164
4321
  /// back its routing tags plus whether the entry was dropped —
3165
4322
  /// a dropped entry's terminal must be swallowed, not routed.
3166
- fn takeEffectEntry(key: u64) struct { ok_tag: u8, err_tag: u8, dropped: bool } {
3167
- if (key < effect_key_base) {
4323
+ const EffectSuccess = enum(u8) { void_msg, bytes, stat, response };
4324
+ const EffectPayload = enum(u8) { swallow, void_msg, bytes, stat, response, reason };
4325
+ const EffectCompletion = struct { tag: u8, payload: EffectPayload, reason: u8 };
4326
+
4327
+ const BufferedFamily = enum(u8) { file, complete_file, fetch, clipboard };
4328
+ const BufferedCompletion = struct { slot: usize, tag: u8, payload: u8, reason: u8, swallow: bool };
4329
+
4330
+ fn bufferedCompletion(key: u64, family: BufferedFamily, operation: u8, outcome: u8, truncated: bool) BufferedCompletion {
4331
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4332
+ var request: [88]u8 = @splat(0);
4333
+ request[0..5].* = .{ 17, @intFromEnum(family), operation, outcome, @intFromBool(truncated) };
4334
+ std.mem.writeInt(u64, request[8..16], key, .little);
4335
+ std.mem.writeInt(u64, request[16..24], effect_key_base, .little);
4336
+ for (&effects_table, 0..) |*entry, slot| {
4337
+ request[24 + slot * 4 ..][0..4].* = .{ @intFromBool(entry.used), @intFromBool(entry.dropped), entry.ok_tag, entry.err_tag };
4338
+ }
4339
+ var result: [8]u8 = undefined;
4340
+ if (core.nativeEffectPolicy(&request, &result) != result.len or result[0] >= effects_table.len or
4341
+ !effects_table[result[0]].used or result[2] > 6 or result[3] > 2 or result[4] > 1 or result[5] > 1 or result[6] != 0 or result[7] != 0)
4342
+ @panic("ts core host: invalid compiled buffered completion plan");
4343
+ if (result[4] == 1) effects_table[result[0]].used = false;
4344
+ return .{ .slot = result[0], .tag = result[1], .payload = result[2], .reason = result[3], .swallow = result[5] == 1 };
4345
+ }
4346
+ const success: EffectSuccess = switch (family) {
4347
+ .file => if (operation == @intFromEnum(runtime_effects.EffectFileOp.read)) .bytes else if (operation == @intFromEnum(runtime_effects.EffectFileOp.stat)) .stat else .void_msg,
4348
+ .complete_file => .void_msg,
4349
+ .fetch => .response,
4350
+ .clipboard => .bytes,
4351
+ };
4352
+ const route = takeEffectEntry(key, success, family == .complete_file or outcome == 0, truncated);
4353
+ return .{ .slot = @intCast(key - effect_key_base), .tag = route.tag, .payload = if (family == .complete_file) 6 else @intFromEnum(route.payload), .reason = route.reason, .swallow = route.payload == .swallow };
4354
+ }
4355
+
4356
+ fn takeEffectEntry(key: u64, success: EffectSuccess, ok: bool, truncated: bool) EffectCompletion {
4357
+ if (key < effect_key_base)
3168
4358
  @panic("ts core host: an effect terminal arrived outside the bridge's named-op key namespace");
3169
- }
3170
4359
  const index = key - effect_key_base;
3171
- if (index >= effects_table.len or !effects_table[index].used) {
4360
+ if (index >= effects_table.len or !effects_table[index].used)
3172
4361
  @panic("ts core host: an effect terminal arrived for a named op the bridge is not tracking");
3173
- }
3174
- const entry = &effects_table[index];
3175
- entry.used = false;
3176
- return .{ .ok_tag = entry.ok_tag, .err_tag = entry.err_tag, .dropped = entry.dropped };
4362
+ const plan = if (comptime @hasDecl(core, "nativeEffectPolicy")) blk: {
4363
+ var request: [69]u8 = undefined;
4364
+ request[0] = 2;
4365
+ request[1] = @intCast(index);
4366
+ request[2] = @intFromEnum(success);
4367
+ request[3] = @intFromBool(ok);
4368
+ request[4] = @intFromBool(truncated);
4369
+ for (&effects_table, 0..) |*entry, slot| {
4370
+ const at = 5 + slot * 4;
4371
+ request[at] = @intFromBool(entry.used);
4372
+ request[at + 1] = @intFromBool(entry.dropped);
4373
+ request[at + 2] = entry.ok_tag;
4374
+ request[at + 3] = entry.err_tag;
4375
+ }
4376
+ var result: [4]u8 = undefined;
4377
+ if (core.nativeEffectPolicy(&request, &result) != result.len or result[0] != index or result[2] > 5 or result[3] > 2)
4378
+ @panic("ts core host: invalid compiled effect completion result");
4379
+ break :blk EffectCompletion{ .tag = result[1], .payload = @enumFromInt(result[2]), .reason = result[3] };
4380
+ } else blk: {
4381
+ const entry = &effects_table[index];
4382
+ if (entry.dropped) break :blk EffectCompletion{ .tag = entry.err_tag, .payload = .swallow, .reason = 0 };
4383
+ const cut = success == .response and truncated;
4384
+ if (ok and !cut) break :blk EffectCompletion{ .tag = entry.ok_tag, .payload = @enumFromInt(@intFromEnum(success) + 1), .reason = 0 };
4385
+ break :blk EffectCompletion{ .tag = entry.err_tag, .payload = .reason, .reason = if (ok and cut) 2 else 1 };
4386
+ };
4387
+ effects_table[index].used = false;
4388
+ return plan;
3177
4389
  }
3178
4390
 
3179
4391
  /// A dropped entry's terminal (the `.cancelled` end of a
@@ -3191,15 +4403,73 @@ pub fn TsCoreHost(comptime core: type) type {
3191
4403
  /// arm; every non-ok outcome routes the err arm with the
3192
4404
  /// outcome's name as bytes. A dropped entry's terminal routes
3193
4405
  /// nothing — the silent drop.
4406
+ fn parseExactUnsigned(decimal: []const u8) ?u64 {
4407
+ if (decimal.len == 0 or decimal.len > 20 or (decimal.len > 1 and decimal[0] == '0')) return null;
4408
+ for (decimal) |byte| if (byte < '0' or byte > '9') return null;
4409
+ return std.fmt.parseInt(u64, decimal, 10) catch null;
4410
+ }
4411
+
4412
+ fn parseExactTimerInterval(decimal: []const u8) ?u64 {
4413
+ const value = parseExactUnsigned(decimal) orelse return null;
4414
+ if (value > std.math.maxInt(u64) / std.time.ns_per_ms) return null;
4415
+ return value;
4416
+ }
4417
+
4418
+ fn armResultTimer(fx: *Fx, key: []const u8, ms: f64, tag: u8, mode: runtime_effects.TimerMode, native_range: bool) void {
4419
+ const blocked = key.len > 0 and (reservedWireKeyOccupiedExcept(key, .delay) or findRequest(key) != null or findEffect(key) != null or findStream(key) != null or findPty(key) != null or findDb(key) != null);
4420
+ const plan: ?DelayPlan = if (comptime @hasDecl(core, "nativeTimerPolicy")) compiledDelayDeclarationRange(key, ms, tag, blocked, true, native_range) else blk: {
4421
+ if (blocked or !std.math.isFinite(ms) or ms < 1 or ms > (if (native_range) @as(f64, 18_446_744_073_709) else 31_536_000_000)) break :blk null;
4422
+ const slot = (if (key.len > 0) findDelay(key) orelse freeDelayIndex() else freeDelayIndex()) orelse break :blk null;
4423
+ break :blk .{ .slot = slot, .tag = tag, .interval_ms = intervalMs(ms) };
4424
+ };
4425
+ const admitted = plan orelse {
4426
+ fx.stageLoopMsg(msgFromTimerResult(tag, .{ .key = 0, .outcome = .rejected }, fx.stageLoopKey(key)));
4427
+ return;
4428
+ };
4429
+ const entry = &delays[admitted.slot];
4430
+ entry.used = true;
4431
+ entry.full_result = true;
4432
+ entry.mode = mode;
4433
+ entry.key_len = key.len;
4434
+ @memcpy(entry.key[0..key.len], key);
4435
+ entry.tag = admitted.tag;
4436
+ fx.startTimer(.{ .key = delay_key_base + admitted.slot, .interval_ms = admitted.interval_ms, .mode = mode, .on_fire = delayFireMsg });
4437
+ }
4438
+ fn decimalFrame(value: anytype) []const u8 {
4439
+ var buffer: [21]u8 = undefined;
4440
+ const text = std.fmt.bufPrint(&buffer, "{d}", .{value}) catch unreachable;
4441
+ if (value == 0) return "0";
4442
+ const owned = core.rt.frameAlloc(u8, text.len);
4443
+ @memcpy(owned, text);
4444
+ return owned;
4445
+ }
4446
+ fn msgFromTimerResult(tag: u8, timer: runtime_effects.EffectTimer, key: []const u8) Msg {
4447
+ return msgFromCapability(tag, .{ .key = key, .timestampNs = decimalFrame(timer.timestamp_ns), .outcome = timer.outcome });
4448
+ }
4449
+ fn stageFileRejected(fx: *Fx, head: RoutedHead, operation: runtime_effects.EffectFileOp) void {
4450
+ fx.stageLoopMsg(msgFromFileResult(head.ok_tag, .{ .key = 0, .op = operation, .outcome = .rejected }, fx.stageLoopKey(head.key)));
4451
+ }
4452
+ fn msgFromFileResult(tag: u8, result: runtime_effects.EffectFileResult, key: []const u8) Msg {
4453
+ return msgFromCapability(tag, .{ .key = key, .operation = result.op, .event = result.event, .outcome = result.outcome, .bytes = result.bytes, .totalBytes = decimalFrame(result.total), .mtimeMs = decimalFrame(result.mtime_ms), .exists = result.exists, .droppedBefore = result.dropped_before });
4454
+ }
4455
+ fn completeFileResultMsg(result: runtime_effects.EffectFileResult) Msg {
4456
+ const route = bufferedCompletion(result.key, .complete_file, @intFromEnum(result.op), @intFromEnum(result.outcome), false);
4457
+ if (route.payload != 6) @panic("ts core host: complete file received an incompatible payload plan");
4458
+ if (route.swallow) swallow_next_dispatch = true;
4459
+ return msgFromFileResult(route.tag, result, effects_table[route.slot].wireKey());
4460
+ }
4461
+
3194
4462
  fn fileResultMsg(result: runtime_effects.EffectFileResult) Msg {
3195
- const tags = takeEffectEntry(result.key);
3196
- if (tags.dropped) return swallowedMsg(tags.err_tag);
3197
- if (result.outcome == .ok) {
3198
- if (result.op == .read) return msgFromTagBytes(tags.ok_tag, result.bytes);
3199
- if (result.op == .stat) return msgFromTagFileStat(tags.ok_tag, result);
3200
- return msgFromTagVoid(tags.ok_tag);
3201
- }
3202
- return msgFromTagBytes(tags.err_tag, @tagName(result.outcome));
4463
+ const route = bufferedCompletion(result.key, .file, @intFromEnum(result.op), @intFromEnum(result.outcome), false);
4464
+ if (route.payload > 5) @panic("ts core host: file completion received an incompatible payload plan");
4465
+ return switch (@as(EffectPayload, @enumFromInt(route.payload))) {
4466
+ .swallow => swallowedMsg(route.tag),
4467
+ .void_msg => msgFromTagVoid(route.tag),
4468
+ .bytes => msgFromTagBytes(route.tag, result.bytes),
4469
+ .stat => msgFromTagFileStat(route.tag, result),
4470
+ .reason => msgFromTagBytes(route.tag, @tagName(result.outcome)),
4471
+ .response => @panic("ts core host: file completion received a response payload plan"),
4472
+ };
3203
4473
  }
3204
4474
 
3205
4475
  fn msgFromTagFileStat(tag: u8, result: runtime_effects.EffectFileResult) Msg {
@@ -3231,43 +4501,178 @@ pub fn TsCoreHost(comptime core: type) type {
3231
4501
  /// routes the err arm with the reason as bytes. A dropped
3232
4502
  /// entry's terminal routes nothing — the silent drop.
3233
4503
  fn fetchResultMsg(response: runtime_effects.EffectResponse) Msg {
3234
- const tags = takeEffectEntry(response.key);
3235
- if (tags.dropped) return swallowedMsg(tags.err_tag);
3236
- if (response.outcome == .ok and !response.truncated) {
3237
- return msgFromTagNumberBytes("fetch response", "{ status, body }", tags.ok_tag, response.status, response.body);
3238
- }
3239
- const reason = if (response.outcome == .ok) "truncated" else @tagName(response.outcome);
3240
- return msgFromTagBytes(tags.err_tag, reason);
4504
+ const route = bufferedCompletion(response.key, .fetch, 0, @intFromEnum(response.outcome), response.truncated);
4505
+ if (route.payload > 5) @panic("ts core host: fetch completion received an incompatible payload plan");
4506
+ return switch (@as(EffectPayload, @enumFromInt(route.payload))) {
4507
+ .swallow => swallowedMsg(route.tag),
4508
+ .response => msgFromTagNumberBytes("fetch response", "{ status, body }", route.tag, response.status, response.body),
4509
+ .reason => msgFromTagBytes(route.tag, if (route.reason == 2) "truncated" else @tagName(response.outcome)),
4510
+ else => @panic("ts core host: fetch completion received an incompatible payload plan"),
4511
+ };
3241
4512
  }
3242
4513
 
3243
4514
  /// `ClipboardMsgFn` for clip_read (writes are fire-and-forget
3244
4515
  /// and never route): ok routes the text bytes, everything else
3245
4516
  /// the outcome name. A dropped entry's terminal routes nothing
3246
4517
  /// — the silent drop.
4518
+ fn compiledClipboardWritePlan(action: u8, key: []const u8, blocked: bool, slot: u8, tag: u8) [4]u8 {
4519
+ var request: [8 + max_wire_key_bytes + clipboard_writes.len * (3 + max_wire_key_bytes)]u8 = @splat(0);
4520
+ request[0..8].* = .{ 16, action, @intCast(key.len), @intFromBool(blocked), slot, tag, 0, 0 };
4521
+ @memcpy(request[8..][0..key.len], key);
4522
+ var at: usize = 8 + key.len;
4523
+ for (&clipboard_writes) |*entry| {
4524
+ const name = if (entry.used) entry.wireKey() else "";
4525
+ request[at..][0..3].* = .{ @intFromBool(entry.used), entry.tag, @intCast(name.len) };
4526
+ @memcpy(request[at + 3 ..][0..name.len], name);
4527
+ at += 3 + name.len;
4528
+ }
4529
+ var result: [4]u8 = undefined;
4530
+ if (core.nativeEffectPolicy(request[0..at], &result) != result.len or result[2] > 1 or result[3] != 0 or (result[0] != 255 and result[0] >= clipboard_writes.len))
4531
+ @panic("ts core host: invalid compiled clipboard write plan");
4532
+ if (action == 2) {
4533
+ if (result[0] != slot) @panic("ts core host: invalid compiled clipboard completion owner");
4534
+ } else if (result[0] != 255) {
4535
+ const entry = &clipboard_writes[result[0]];
4536
+ if (action == 0 and (key.len == 0 or !entry.used or !std.mem.eql(u8, entry.wireKey(), key)))
4537
+ @panic("ts core host: invalid compiled clipboard lookup owner");
4538
+ if (action == 1 and entry.used) @panic("ts core host: compiled clipboard overwrites another owner");
4539
+ }
4540
+ return result;
4541
+ }
4542
+
4543
+ fn findClipboardWrite(key: []const u8) ?usize {
4544
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4545
+ const plan = compiledClipboardWritePlan(0, key, false, 0, 0);
4546
+ return if (plan[0] == 255) null else plan[0];
4547
+ }
4548
+ if (key.len == 0) return null;
4549
+ for (&clipboard_writes, 0..) |*entry, index| if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
4550
+ return null;
4551
+ }
4552
+ fn issueClipboardWrite(fx: *Fx, key: []const u8, tag: u8, bytes: []const u8) void {
4553
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4554
+ const plan = compiledClipboardWritePlan(1, key, reservedWireKeyOccupied(key) or wireKeyOccupiedOutsideFileStreams(key), 0, tag);
4555
+ if (plan[0] == 255) {
4556
+ fx.stageLoopMsg(msgFromClipboard(plan[1], .{ .key = 0, .outcome = .rejected }, fx.stageLoopKey(key)));
4557
+ return;
4558
+ }
4559
+ clipboard_writes[plan[0]] = .{ .used = true, .key = undefined, .key_len = key.len, .tag = plan[1] };
4560
+ @memcpy(clipboard_writes[plan[0]].key[0..key.len], key);
4561
+ fx.writeClipboard(.{ .key = clipboard_result_key_base + plan[0], .text = bytes, .on_result = clipboardWriteResultMsg });
4562
+ return;
4563
+ }
4564
+ var slot: ?usize = null;
4565
+ if (!reservedWireKeyOccupied(key) and !wireKeyOccupiedOutsideFileStreams(key)) {
4566
+ for (&clipboard_writes, 0..) |*entry, index| if (!entry.used) {
4567
+ slot = index;
4568
+ break;
4569
+ };
4570
+ }
4571
+ const index = slot orelse {
4572
+ fx.stageLoopMsg(msgFromClipboard(tag, .{ .key = 0, .outcome = .rejected }, fx.stageLoopKey(key)));
4573
+ return;
4574
+ };
4575
+ clipboard_writes[index] = .{ .used = true, .key = undefined, .key_len = key.len, .tag = tag };
4576
+ @memcpy(clipboard_writes[index].key[0..key.len], key);
4577
+ fx.writeClipboard(.{ .key = clipboard_result_key_base + index, .text = bytes, .on_result = clipboardWriteResultMsg });
4578
+ }
4579
+ fn clipboardWriteResultMsg(result: runtime_effects.EffectClipboardResult) Msg {
4580
+ if (result.key < clipboard_result_key_base) @panic("ts core host: clipboard result outside its namespace");
4581
+ const index = result.key - clipboard_result_key_base;
4582
+ if (index >= clipboard_writes.len or !clipboard_writes[index].used) @panic("ts core host: untracked clipboard completion");
4583
+ const entry = &clipboard_writes[index];
4584
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4585
+ const plan = compiledClipboardWritePlan(2, "", false, @intCast(index), 0);
4586
+ if (plan[2] == 1) entry.used = false;
4587
+ return msgFromClipboard(plan[1], result, entry.wireKey());
4588
+ }
4589
+ entry.used = false;
4590
+ return msgFromClipboard(entry.tag, result, entry.wireKey());
4591
+ }
4592
+ /// Match complete capability records by field NAME and type. Bytes are
4593
+ /// borrowed only until this dispatch; the core ABI copies all retained
4594
+ /// values into its committed graph. Native engine keys remain private.
4595
+ fn msgFromCapability(tag: u8, record: anytype) Msg {
4596
+ inline for (msg_arms, 0..) |arm, index| {
4597
+ if (tag == index) {
4598
+ if (comptime @typeInfo(arm.type) == .@"struct" and @typeInfo(arm.type).@"struct".fields.len == @typeInfo(@TypeOf(record)).@"struct".fields.len) {
4599
+ var result: arm.type = undefined;
4600
+ inline for (@typeInfo(arm.type).@"struct".fields) |field| {
4601
+ if (comptime @hasField(@TypeOf(record), field.name)) {
4602
+ const value = @field(record, field.name);
4603
+ const V = @TypeOf(value);
4604
+ if (comptime @typeInfo(V) == .@"enum" and @typeInfo(field.type) == .@"enum") {
4605
+ @field(result, field.name) = std.meta.stringToEnum(field.type, @tagName(value)) orelse @panic("ts core host: incomplete capability enum");
4606
+ } else if (comptime (@typeInfo(V) == .int or @typeInfo(V) == .comptime_int) and field.type == f64) {
4607
+ @field(result, field.name) = @floatFromInt(value);
4608
+ } else if (comptime (@typeInfo(V) == .int or @typeInfo(V) == .comptime_int) and (@typeInfo(field.type) == .int)) {
4609
+ @field(result, field.name) = @intCast(value);
4610
+ } else if (comptime V == f32 and field.type == f64) {
4611
+ @field(result, field.name) = value;
4612
+ } else if (comptime V == field.type) {
4613
+ @field(result, field.name) = value;
4614
+ } else @panic("ts core host: incompatible capability field type");
4615
+ } else @panic("ts core host: missing capability field");
4616
+ }
4617
+ return @unionInit(Msg, arm.name, result);
4618
+ }
4619
+ @panic("ts core host: invalid capability record arm");
4620
+ }
4621
+ }
4622
+ @panic("ts core host: invalid capability message tag");
4623
+ }
4624
+ fn msgFromSpawnLine(tag: u8, line: runtime_effects.EffectLine, key: []const u8) Msg {
4625
+ return msgFromCapability(tag, .{ .key = key, .line = line.line, .truncated = line.truncated, .droppedBefore = line.dropped_before });
4626
+ }
4627
+ fn msgFromSpawnExit(tag: u8, exit: runtime_effects.EffectExit, key: []const u8) Msg {
4628
+ return msgFromCapability(tag, .{ .key = key, .code = exit.code, .reason = exit.reason, .droppedLines = exit.dropped_lines, .output = exit.output, .outputTruncated = exit.output_truncated, .stderrTail = exit.stderr_tail, .stderrTruncated = exit.stderr_truncated });
4629
+ }
4630
+ fn msgFromClipboard(tag: u8, result: runtime_effects.EffectClipboardResult, key: []const u8) Msg {
4631
+ return msgFromCapability(tag, .{ .key = key, .operation = result.op, .outcome = result.outcome, .text = result.text, .droppedBefore = result.dropped_before });
4632
+ }
4633
+ fn msgFromVideoSnapshot(tag: u8, snapshot: Fx.VideoSnapshot, key: []const u8) Msg {
4634
+ return msgFromCapability(tag, .{ .key = key, .active = snapshot.active, .surface = snapshot.surface, .playing = snapshot.playing, .buffering = snapshot.buffering, .completed = snapshot.completed, .looping = snapshot.looping, .muted = snapshot.muted, .source = snapshot.source, .positionMs = snapshot.position_ms, .durationMs = snapshot.duration_ms, .width = snapshot.width, .height = snapshot.height, .volume = snapshot.volume });
4635
+ }
4636
+
3247
4637
  fn clipboardResultMsg(result: runtime_effects.EffectClipboardResult) Msg {
3248
- const tags = takeEffectEntry(result.key);
3249
- if (tags.dropped) return swallowedMsg(tags.err_tag);
3250
- if (result.outcome == .ok) return msgFromTagBytes(tags.ok_tag, result.text);
3251
- return msgFromTagBytes(tags.err_tag, @tagName(result.outcome));
4638
+ const route = bufferedCompletion(result.key, .clipboard, 0, @intFromEnum(result.outcome), false);
4639
+ if (route.payload > 5) @panic("ts core host: clipboard completion received an incompatible payload plan");
4640
+ return switch (@as(EffectPayload, @enumFromInt(route.payload))) {
4641
+ .swallow => swallowedMsg(route.tag),
4642
+ .bytes => msgFromTagBytes(route.tag, result.text),
4643
+ .reason => msgFromTagBytes(route.tag, @tagName(result.outcome)),
4644
+ else => @panic("ts core host: clipboard completion received an incompatible payload plan"),
4645
+ };
3252
4646
  }
3253
4647
 
3254
4648
  /// `TimerMsgFn` for one-shot delays: the slot retires on fire
3255
4649
  /// (platform one-shots self-stop) and the named arm dispatches
3256
4650
  /// with the fire time in fractional milliseconds.
3257
4651
  fn delayFireMsg(timer: runtime_effects.EffectTimer) Msg {
3258
- if (timer.outcome == .rejected) {
3259
- @panic("ts core host: the platform rejected a Cmd.delay timer (no timer service, or the fx timer table is full)");
4652
+ if (comptime @hasDecl(core, "nativeTimerPolicy")) {
4653
+ const plan = compiledTimerCompletion(timer, false);
4654
+ const entry = &delays[plan[0]];
4655
+ if (plan[3] == 1) entry.used = false;
4656
+ return timerCompletionMsg(plan, timer, entry.wireKey());
3260
4657
  }
3261
4658
  if (timer.key < delay_key_base) {
3262
4659
  @panic("ts core host: a delay fired outside the bridge's delay key namespace");
3263
4660
  }
3264
4661
  const index = timer.key - delay_key_base;
3265
- if (index >= delays.len or !delays[index].used) {
3266
- @panic("ts core host: a delay fired for a slot the bridge is not tracking");
4662
+ if (index >= delays.len) @panic("ts core host: a delay fired outside the bridge's delay table");
4663
+ const completion = blk: {
4664
+ if (!delays[index].used) @panic("ts core host: a delay fired for a slot the bridge is not tracking");
4665
+ break :blk .{ .slot = @as(usize, @intCast(index)), .tag = delays[index].tag };
4666
+ };
4667
+ const entry = &delays[completion.slot];
4668
+ if (entry.full_result) {
4669
+ if (entry.mode == .one_shot or timer.outcome == .rejected) entry.used = false;
4670
+ return msgFromTimerResult(completion.tag, timer, entry.wireKey());
3267
4671
  }
3268
- delays[index].used = false;
4672
+ if (timer.outcome == .rejected) @panic("ts core host: the platform rejected a Cmd.delay timer");
4673
+ entry.used = false;
3269
4674
  const ms = @as(f64, @floatFromInt(timer.timestamp_ns)) / std.time.ns_per_ms;
3270
- return msgFromTagNumber(delays[index].tag, ms);
4675
+ return msgFromTagNumber(completion.tag, ms);
3271
4676
  }
3272
4677
 
3273
4678
  // ----------------------------------------------- subscriptions
@@ -3280,7 +4685,14 @@ pub fn TsCoreHost(comptime core: type) type {
3280
4685
  /// everywhere, so record/replay walk identical tables.
3281
4686
  fn reconcileSubscriptions(fx: *Fx) void {
3282
4687
  if (comptime !has_subscriptions) return;
3283
- const subs = core.subscriptions(model_root);
4688
+ const borrowed_subs = if (comptime use_runtime_model) core.runtimeSubscriptions(model_root) else core.subscriptions(model_root);
4689
+ // A cycle policy may allocate in the compiler frame. Keep the
4690
+ // stream in the shim arena, and reset both only in finishCycle.
4691
+ const subs = if (comptime @hasDecl(core, "nativeTimerPolicy") or @hasDecl(core, "nativeDbPolicy") or @hasDecl(core, "nativeEffectPolicy")) blk: {
4692
+ const copy = core.rt.frameAlloc(u8, borrowed_subs.len);
4693
+ @memcpy(copy, borrowed_subs);
4694
+ break :blk copy;
4695
+ } else borrowed_subs;
3284
4696
  var seen_timers = [_]bool{false} ** timers.len;
3285
4697
  var seen_db = [_]bool{false} ** dbs.len;
3286
4698
 
@@ -3307,18 +4719,51 @@ pub fn TsCoreHost(comptime core: type) type {
3307
4719
  const every_bits = takeBytes(subs, &at, 8);
3308
4720
  const every_ms: f64 = @bitCast(std.mem.readInt(u64, every_bits[0..8], .little));
3309
4721
  const tag = takeByte(subs, &at);
3310
- if (!(every_ms >= 1) or !(every_ms <= 31_536_000_000.0)) {
3311
- @panic("ts core host: Sub.timer interval must be between 1ms and one year");
3312
- }
3313
- var slot: ?usize = null;
3314
- for (&timers, 0..) |*entry, index| {
3315
- if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) slot = index;
3316
- }
3317
- if (slot) |index| {
3318
- seen_timers[index] = true;
3319
- const entry = &timers[index];
3320
- if (entry.every_ms != every_ms) {
4722
+ if (comptime @hasDecl(core, "nativeTimerPolicy")) {
4723
+ const plan = compiledTimerDeclaration(key, every_ms, tag, &seen_timers);
4724
+ const entry = &timers[plan.slot];
4725
+ entry.used = true;
4726
+ entry.key_len = key.len;
4727
+ @memcpy(entry.key[0..key.len], key);
4728
+ entry.every_ms = every_ms;
4729
+ entry.tag = plan.tag;
4730
+ if (plan.start) fx.startTimer(.{
4731
+ .key = timer_key_base + plan.slot,
4732
+ .interval_ms = plan.interval_ms,
4733
+ .mode = .repeating,
4734
+ .on_fire = timerFireMsg,
4735
+ });
4736
+ } else {
4737
+ if (!(every_ms >= 1) or !(every_ms <= 31_536_000_000.0)) {
4738
+ @panic("ts core host: Sub.timer interval must be between 1ms and one year");
4739
+ }
4740
+ var slot: ?usize = null;
4741
+ for (&timers, 0..) |*entry, index| {
4742
+ if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) slot = index;
4743
+ }
4744
+ if (slot) |index| {
4745
+ seen_timers[index] = true;
4746
+ const entry = &timers[index];
4747
+ if (entry.every_ms != every_ms) {
4748
+ entry.every_ms = every_ms;
4749
+ fx.startTimer(.{
4750
+ .key = timer_key_base + index,
4751
+ .interval_ms = intervalMs(every_ms),
4752
+ .mode = .repeating,
4753
+ .on_fire = timerFireMsg,
4754
+ });
4755
+ }
4756
+ entry.tag = tag;
4757
+ } else {
4758
+ const index = freeTimerIndex() orelse
4759
+ @panic("ts core host: more than 16 subscription timers - the timer table mirrors the engine's max_effect_timers");
4760
+ seen_timers[index] = true;
4761
+ const entry = &timers[index];
4762
+ entry.used = true;
4763
+ entry.key_len = key.len;
4764
+ @memcpy(entry.key[0..key.len], key);
3321
4765
  entry.every_ms = every_ms;
4766
+ entry.tag = tag;
3322
4767
  fx.startTimer(.{
3323
4768
  .key = timer_key_base + index,
3324
4769
  .interval_ms = intervalMs(every_ms),
@@ -3326,23 +4771,6 @@ pub fn TsCoreHost(comptime core: type) type {
3326
4771
  .on_fire = timerFireMsg,
3327
4772
  });
3328
4773
  }
3329
- entry.tag = tag;
3330
- } else {
3331
- const index = freeTimerIndex() orelse
3332
- @panic("ts core host: more than 16 subscription timers - the timer table mirrors the engine's max_effect_timers");
3333
- seen_timers[index] = true;
3334
- const entry = &timers[index];
3335
- entry.used = true;
3336
- entry.key_len = key.len;
3337
- @memcpy(entry.key[0..key.len], key);
3338
- entry.every_ms = every_ms;
3339
- entry.tag = tag;
3340
- fx.startTimer(.{
3341
- .key = timer_key_base + index,
3342
- .interval_ms = intervalMs(every_ms),
3343
- .mode = .repeating,
3344
- .on_fire = timerFireMsg,
3345
- });
3346
4774
  }
3347
4775
  },
3348
4776
  // live query [op][key][page][done][err][sql bytes]
@@ -3365,23 +4793,29 @@ pub fn TsCoreHost(comptime core: type) type {
3365
4793
  for (0..table_count) |index| tables[index] = takeShortBytes(subs, &at);
3366
4794
 
3367
4795
  const signature = std.hash.Wyhash.hash(0, subs[record_start..at]);
3368
- const index = findDb(key) orelse freeDbIndex() orelse
3369
- @panic("ts core host: more relational commands and live queries are active than the database slot family can hold");
4796
+ const plan: DbPlan = if (comptime @hasDecl(core, "nativeDbPolicy")) compiledDbDeclaration(key, signature, page_tag, done_tag, err_tag, &seen_db) else blk: {
4797
+ const index = findDb(key) orelse freeDbIndex() orelse
4798
+ @panic("ts core host: more relational commands and live queries are active than the database slot family can hold");
4799
+ const entry = &dbs[index];
4800
+ if (entry.used and !entry.live) @panic("ts core host: a live-query key collides with an in-flight database command");
4801
+ if (seen_db[index]) @panic("ts core host: duplicate live-query subscription key");
4802
+ seen_db[index] = true;
4803
+ const changed = !entry.used or entry.signature != signature;
4804
+ break :blk .{ .slot = index, .start = changed, .stop = entry.used and changed, .page_tag = page_tag, .done_tag = done_tag, .err_tag = err_tag };
4805
+ };
4806
+ const index = plan.slot;
3370
4807
  const entry = &dbs[index];
3371
- if (entry.used and !entry.live) @panic("ts core host: a live-query key collides with an in-flight database command");
3372
- if (seen_db[index]) @panic("ts core host: duplicate live-query subscription key");
3373
- seen_db[index] = true;
3374
- if (!entry.used or entry.signature != signature) {
3375
- if (entry.used) fx.dbUnsubscribe(db_key_base + index);
4808
+ if (plan.stop) fx.dbUnsubscribe(db_key_base + index);
4809
+ if (plan.start) {
3376
4810
  entry.* = .{
3377
4811
  .used = true,
3378
4812
  .query = true,
3379
4813
  .live = true,
3380
4814
  .signature = signature,
3381
4815
  .key_len = key.len,
3382
- .page_tag = page_tag,
3383
- .done_tag = done_tag,
3384
- .err_tag = err_tag,
4816
+ .page_tag = plan.page_tag,
4817
+ .done_tag = plan.done_tag,
4818
+ .err_tag = plan.err_tag,
3385
4819
  };
3386
4820
  @memcpy(entry.key[0..key.len], key);
3387
4821
  fx.dbSubscribe(.{
@@ -3396,20 +4830,177 @@ pub fn TsCoreHost(comptime core: type) type {
3396
4830
  else => @panic("ts core host: unknown subscription wire record - the core and this runtime disagree on cmd_format_version"),
3397
4831
  }
3398
4832
  }
4833
+ const cancellations: ?u16 = if (comptime @hasDecl(core, "nativeTimerPolicy")) compiledTimerCancellations(seen_timers) else null;
3399
4834
  for (&timers, 0..) |*entry, index| {
3400
- if (entry.used and !seen_timers[index]) {
4835
+ const cancel = if (cancellations) |mask| mask & (@as(u16, 1) << @intCast(index)) != 0 else entry.used and !seen_timers[index];
4836
+ if (cancel) {
3401
4837
  entry.used = false;
3402
4838
  fx.cancelTimer(timer_key_base + index);
3403
4839
  }
3404
4840
  }
3405
4841
  }
3406
4842
 
4843
+ const TimerPlan = struct { slot: usize, start: bool, tag: u8, interval_ms: u64 };
4844
+
4845
+ /// Native supplies owned table facts; TypeScript resolves slot order,
4846
+ /// key matching, interval changes, routes and the seen set. The callback
4847
+ /// copies the response and leaves both cycle arenas alive.
4848
+ fn compiledTimerDeclaration(key: []const u8, every_ms: f64, tag: u8, seen: *[runtime_effects.max_effect_timers]bool) TimerPlan {
4849
+ comptime std.debug.assert(runtime_effects.max_effect_timers == 16);
4850
+ var request: [13 + max_wire_key_bytes + 16 * (10 + max_wire_key_bytes)]u8 = undefined;
4851
+ request[0] = 0;
4852
+ std.mem.writeInt(u16, request[1..3], timerSeenMask(seen.*), .little);
4853
+ request[3] = @intCast(key.len);
4854
+ @memcpy(request[4..][0..key.len], key);
4855
+ var at: usize = 4 + key.len;
4856
+ std.mem.writeInt(u64, request[at..][0..8], @bitCast(every_ms), .little);
4857
+ request[at + 8] = tag;
4858
+ at += 9;
4859
+ for (&timers) |*entry| {
4860
+ const length = if (entry.used) entry.key_len else 0;
4861
+ request[at] = @intFromBool(entry.used);
4862
+ request[at + 1] = @intCast(length);
4863
+ at += 2;
4864
+ @memcpy(request[at..][0..length], entry.key[0..length]);
4865
+ at += length;
4866
+ std.mem.writeInt(u64, request[at..][0..8], @bitCast(if (entry.used) entry.every_ms else @as(f64, 0)), .little);
4867
+ at += 8;
4868
+ }
4869
+ var result: [14]u8 = undefined;
4870
+ if (core.nativeTimerPolicy(request[0..at], &result) != result.len or result[0] >= timers.len or result[1] > 1 or result[3] != 0)
4871
+ @panic("ts core host: invalid compiled timer declaration result");
4872
+ const rounded: f64 = @bitCast(std.mem.readInt(u64, result[4..12], .little));
4873
+ if (!std.math.isFinite(rounded) or rounded < 1 or rounded > 31_536_000_000 or @floor(rounded) != rounded)
4874
+ @panic("ts core host: invalid compiled timer interval result");
4875
+ const mask = std.mem.readInt(u16, result[12..14], .little);
4876
+ for (seen, 0..) |*value, index| value.* = mask & (@as(u16, 1) << @intCast(index)) != 0;
4877
+ return .{ .slot = result[0], .start = result[1] == 1, .tag = result[2], .interval_ms = @intFromFloat(rounded) };
4878
+ }
4879
+
4880
+ const DelayPlan = struct { slot: usize, tag: u8, interval_ms: u64 };
4881
+ const max_delay_policy_bytes = 12 + max_wire_key_bytes + 16 * (3 + max_wire_key_bytes);
4882
+
4883
+ /// Copy native-owned facts into a borrowed request. No policy call may
4884
+ /// reset the command frame: later records in a batch still borrow it.
4885
+ fn writeDelayTable(request: []u8, start: usize) usize {
4886
+ comptime std.debug.assert(runtime_effects.max_effect_timers == 16);
4887
+ var at = start;
4888
+ for (&delays) |*entry| {
4889
+ const length = if (entry.used) entry.key_len else 0;
4890
+ request[at] = @intFromBool(entry.used);
4891
+ request[at + 1] = @intCast(length);
4892
+ at += 2;
4893
+ @memcpy(request[at..][0..length], entry.key[0..length]);
4894
+ at += length;
4895
+ request[at] = entry.tag;
4896
+ at += 1;
4897
+ }
4898
+ return at;
4899
+ }
4900
+
4901
+ fn compiledDelayDeclaration(key: []const u8, after_ms: f64, tag: u8, blocked: bool, rejectable: bool) ?DelayPlan {
4902
+ return compiledDelayDeclarationRange(key, after_ms, tag, blocked, rejectable, false);
4903
+ }
4904
+
4905
+ fn compiledDelayDeclarationRange(key: []const u8, after_ms: f64, tag: u8, blocked: bool, rejectable: bool, native_range: bool) ?DelayPlan {
4906
+ var request: [max_delay_policy_bytes]u8 = undefined;
4907
+ request[0] = if (native_range) 8 else if (rejectable) 6 else 2;
4908
+ request[1] = @intCast(key.len);
4909
+ @memcpy(request[2..][0..key.len], key);
4910
+ const value_at = 2 + key.len;
4911
+ std.mem.writeInt(u64, request[value_at..][0..8], @bitCast(after_ms), .little);
4912
+ request[value_at + 8] = tag;
4913
+ request[value_at + 9] = @intFromBool(blocked);
4914
+ const at = writeDelayTable(&request, value_at + 10);
4915
+ var result: [10]u8 = undefined;
4916
+ if (core.nativeTimerPolicy(request[0..at], &result) != result.len)
4917
+ @panic("ts core host: invalid compiled delay declaration result");
4918
+ if (result[0] == 255) return null;
4919
+ if (result[0] >= delays.len) @panic("ts core host: invalid compiled delay declaration slot");
4920
+ const rounded: f64 = @bitCast(std.mem.readInt(u64, result[2..10], .little));
4921
+ if (!std.math.isFinite(rounded) or rounded < 1 or rounded > (if (native_range) @as(f64, 18_446_744_073_709) else 31_536_000_000) or @floor(rounded) != rounded)
4922
+ @panic("ts core host: invalid compiled delay interval result");
4923
+ return .{ .slot = result[0], .tag = result[1], .interval_ms = @intFromFloat(rounded) };
4924
+ }
4925
+
4926
+ fn compiledDelayLookup(key: []const u8) ?usize {
4927
+ var request: [max_delay_policy_bytes]u8 = undefined;
4928
+ request[0] = 3;
4929
+ request[1] = @intCast(key.len);
4930
+ @memcpy(request[2..][0..key.len], key);
4931
+ const at = writeDelayTable(&request, 2 + key.len);
4932
+ var result: [1]u8 = undefined;
4933
+ if (core.nativeTimerPolicy(request[0..at], &result) != result.len)
4934
+ @panic("ts core host: invalid compiled delay lookup result");
4935
+ if (result[0] == 255) return null;
4936
+ if (result[0] >= delays.len or !delays[result[0]].used)
4937
+ @panic("ts core host: invalid compiled delay lookup slot");
4938
+ return result[0];
4939
+ }
4940
+
4941
+ fn compiledTimerCompletion(timer: runtime_effects.EffectTimer, subscription: bool) [40]u8 {
4942
+ var request: [96]u8 = @splat(0);
4943
+ request[0..3].* = .{ 7, @intFromBool(subscription), @intFromEnum(timer.outcome) };
4944
+ std.mem.writeInt(u64, request[4..12], timer.key, .little);
4945
+ std.mem.writeInt(u64, request[12..20], timer.timestamp_ns, .little);
4946
+ std.mem.writeInt(u64, request[20..28], if (subscription) timer_key_base else delay_key_base, .little);
4947
+ for (0..16) |slot| {
4948
+ request[32 + slot * 4 ..][0..4].* = if (subscription)
4949
+ .{ @intFromBool(timers[slot].used), 0, 0, timers[slot].tag }
4950
+ else
4951
+ .{ @intFromBool(delays[slot].used), @intFromBool(delays[slot].full_result), @intFromEnum(delays[slot].mode), delays[slot].tag };
4952
+ }
4953
+ var result: [40]u8 = undefined;
4954
+ if (core.nativeTimerPolicy(&request, &result) != result.len or result[0] >= 16 or result[2] > 1 or result[3] > 1 or result[4] < 1 or result[4] > 20 or
4955
+ result[5] != 0 or result[6] != 0 or result[7] != 0 or !std.math.isFinite(@as(f64, @bitCast(std.mem.readInt(u64, result[8..16], .little)))))
4956
+ @panic("ts core host: invalid compiled timer completion plan");
4957
+ for (result[16..][0..result[4]]) |digit| if (digit < '0' or digit > '9') @panic("ts core host: invalid compiled timer timestamp");
4958
+ return result;
4959
+ }
4960
+
4961
+ fn timerCompletionMsg(plan: [40]u8, timer: runtime_effects.EffectTimer, key: []const u8) Msg {
4962
+ if (plan[2] == 0) return msgFromTagNumber(plan[1], @bitCast(std.mem.readInt(u64, plan[8..16], .little)));
4963
+ // The copied plan is stack-owned. Its decimal bytes must survive
4964
+ // in the dispatch frame until the app consumes the complete Msg.
4965
+ const timestamp = core.rt.frameAlloc(u8, plan[4]);
4966
+ @memcpy(timestamp, plan[16..][0..plan[4]]);
4967
+ return msgFromCapability(plan[1], .{ .key = key, .timestampNs = @as([]const u8, timestamp), .outcome = timer.outcome });
4968
+ }
4969
+
4970
+ fn timerSeenMask(seen: [runtime_effects.max_effect_timers]bool) u16 {
4971
+ var mask: u16 = 0;
4972
+ for (seen, 0..) |value, index| if (value) {
4973
+ mask |= @as(u16, 1) << @intCast(index);
4974
+ };
4975
+ return mask;
4976
+ }
4977
+
4978
+ fn compiledTimerCancellations(seen: [runtime_effects.max_effect_timers]bool) u16 {
4979
+ var used: u16 = 0;
4980
+ for (&timers, 0..) |*entry, index| if (entry.used) {
4981
+ used |= @as(u16, 1) << @intCast(index);
4982
+ };
4983
+ var request: [5]u8 = undefined;
4984
+ request[0] = 1;
4985
+ std.mem.writeInt(u16, request[1..3], used, .little);
4986
+ std.mem.writeInt(u16, request[3..5], timerSeenMask(seen), .little);
4987
+ var result: [2]u8 = undefined;
4988
+ if (core.nativeTimerPolicy(&request, &result) != result.len) @panic("ts core host: invalid compiled timer cancellation result");
4989
+ const mask = std.mem.readInt(u16, &result, .little);
4990
+ if (mask & ~used != 0) @panic("ts core host: invalid compiled timer cancellation slots");
4991
+ return mask;
4992
+ }
4993
+
3407
4994
  /// Parse the inert subscription stream without mutating it and mark
3408
4995
  /// the currently-live DB entries whose public keys remain declared.
3409
4996
  /// Reconciliation uses this pre-pass to retire genuinely stale slots
3410
4997
  /// before it allocates any new ones.
3411
4998
  fn retainedDbSubscriptions(subs: []const u8) [runtime_effects.max_db_effects]bool {
3412
4999
  var retained = [_]bool{false} ** runtime_effects.max_db_effects;
5000
+ // Keep the complete key list separate from the borrowed stream;
5001
+ // policy allocation never revokes subsequent subscription records.
5002
+ const request: []u8 = if (comptime @hasDecl(core, "nativeDbPolicy")) core.rt.frameAlloc(u8, subs.len + max_db_policy_bytes + 5) else &.{};
5003
+ var keys_at: usize = 5;
3413
5004
  var at: usize = 0;
3414
5005
  while (at < subs.len) switch (takeByte(subs, &at)) {
3415
5006
  0x01 => {
@@ -3430,15 +5021,82 @@ pub fn TsCoreHost(comptime core: type) type {
3430
5021
  const table_count: usize = @intCast(takeU32(subs, &at));
3431
5022
  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");
3432
5023
  for (0..table_count) |_| _ = takeShortBytes(subs, &at);
3433
- if (findDb(key)) |index| {
5024
+ if (comptime @hasDecl(core, "nativeDbPolicy")) {
5025
+ request[keys_at] = @intCast(key.len);
5026
+ keys_at += 1;
5027
+ @memcpy(request[keys_at..][0..key.len], key);
5028
+ keys_at += key.len;
5029
+ } else if (findDb(key)) |index| {
3434
5030
  if (dbs[index].live) retained[index] = true;
3435
5031
  }
3436
5032
  },
3437
5033
  else => @panic("ts core host: unknown subscription wire record - the core and this runtime disagree on cmd_format_version"),
3438
5034
  };
5035
+ if (comptime @hasDecl(core, "nativeDbPolicy")) {
5036
+ request[0] = 1;
5037
+ std.mem.writeInt(u32, request[1..5], @intCast(keys_at - 5), .little);
5038
+ const end = writeDbTable(request, keys_at);
5039
+ var result: [2]u8 = undefined;
5040
+ if (core.nativeDbPolicy(request[0..end], &result) != result.len) @panic("ts core host: invalid compiled database retention result");
5041
+ const mask = std.mem.readInt(u16, &result, .little);
5042
+ for (&retained, 0..) |*value, index| value.* = mask & (@as(u16, 1) << @intCast(index)) != 0;
5043
+ }
3439
5044
  return retained;
3440
5045
  }
3441
5046
 
5047
+ const DbPlan = struct { slot: usize, start: bool, stop: bool, page_tag: u8, done_tag: u8, err_tag: u8 };
5048
+ const max_db_policy_bytes = 15 + max_wire_key_bytes + 16 * (11 + max_wire_key_bytes);
5049
+
5050
+ fn writeDbTable(request: []u8, start: usize) usize {
5051
+ comptime std.debug.assert(runtime_effects.max_db_effects == 16);
5052
+ var at = start;
5053
+ for (&dbs) |*entry| {
5054
+ const length = if (entry.used) entry.key_len else 0;
5055
+ request[at] = @intFromBool(entry.used);
5056
+ request[at + 1] = @intFromBool(entry.live);
5057
+ request[at + 2] = @intCast(length);
5058
+ at += 3;
5059
+ @memcpy(request[at..][0..length], entry.key[0..length]);
5060
+ at += length;
5061
+ std.mem.writeInt(u64, request[at..][0..8], entry.signature, .little);
5062
+ at += 8;
5063
+ }
5064
+ return at;
5065
+ }
5066
+
5067
+ fn compiledDbLookup(key: []const u8) ?usize {
5068
+ var request: [max_db_policy_bytes]u8 = undefined;
5069
+ request[0] = 0;
5070
+ request[1] = @intCast(key.len);
5071
+ @memcpy(request[2..][0..key.len], key);
5072
+ const at = writeDbTable(&request, 2 + key.len);
5073
+ var result: [1]u8 = undefined;
5074
+ if (core.nativeDbPolicy(request[0..at], &result) != result.len) @panic("ts core host: invalid compiled database lookup result");
5075
+ if (result[0] == 255) return null;
5076
+ if (result[0] >= dbs.len or !dbs[result[0]].used) @panic("ts core host: invalid compiled database lookup slot");
5077
+ return result[0];
5078
+ }
5079
+
5080
+ fn compiledDbDeclaration(key: []const u8, signature: u64, page_tag: u8, done_tag: u8, err_tag: u8, seen: *[runtime_effects.max_db_effects]bool) DbPlan {
5081
+ var request: [max_db_policy_bytes]u8 = undefined;
5082
+ request[0] = 2;
5083
+ std.mem.writeInt(u16, request[1..3], timerSeenMask(seen.*), .little);
5084
+ request[3] = @intCast(key.len);
5085
+ @memcpy(request[4..][0..key.len], key);
5086
+ const at = 4 + key.len;
5087
+ std.mem.writeInt(u64, request[at..][0..8], signature, .little);
5088
+ request[at + 8] = page_tag;
5089
+ request[at + 9] = done_tag;
5090
+ request[at + 10] = err_tag;
5091
+ const end = writeDbTable(&request, at + 11);
5092
+ var result: [8]u8 = undefined;
5093
+ if (core.nativeDbPolicy(request[0..end], &result) != result.len or result[0] >= dbs.len or result[1] > 1 or result[2] > 1)
5094
+ @panic("ts core host: invalid compiled database declaration result");
5095
+ const mask = std.mem.readInt(u16, result[6..8], .little);
5096
+ for (seen, 0..) |*value, index| value.* = mask & (@as(u16, 1) << @intCast(index)) != 0;
5097
+ return .{ .slot = result[0], .start = result[1] == 1, .stop = result[2] == 1, .page_tag = result[3], .done_tag = result[4], .err_tag = result[5] };
5098
+ }
5099
+
3442
5100
  fn freeTimerIndex() ?usize {
3443
5101
  for (&timers, 0..) |*entry, index| {
3444
5102
  if (!entry.used) return index;
@@ -3455,6 +5113,11 @@ pub fn TsCoreHost(comptime core: type) type {
3455
5113
  /// `TimerMsgFn` for every bridge timer: dispatch the slot's arm
3456
5114
  /// with the fire time in fractional milliseconds.
3457
5115
  fn timerFireMsg(timer: runtime_effects.EffectTimer) Msg {
5116
+ if (comptime @hasDecl(core, "nativeTimerPolicy")) {
5117
+ const plan = compiledTimerCompletion(timer, true);
5118
+ if (plan[3] == 1) timers[plan[0]].used = false;
5119
+ return timerCompletionMsg(plan, timer, timers[plan[0]].wireKey());
5120
+ }
3458
5121
  if (timer.outcome == .rejected) {
3459
5122
  @panic("ts core host: the platform rejected a subscription timer (no timer service, or the fx timer table is full)");
3460
5123
  }
@@ -3607,6 +5270,69 @@ pub fn TsCoreHost(comptime core: type) type {
3607
5270
  return ok;
3608
5271
  }
3609
5272
 
5273
+ fn exactAudioArmShape(comptime T: type) bool {
5274
+ if (@typeInfo(T) != .@"struct") return false;
5275
+ const fields = @typeInfo(T).@"struct".fields;
5276
+ if (fields.len != 7) return false;
5277
+ for (fields) |field| {
5278
+ if (std.mem.eql(u8, field.name, "state")) {
5279
+ if (@typeInfo(field.type) != .@"enum") return false;
5280
+ const states = @typeInfo(field.type).@"enum".fields;
5281
+ if (states.len != 6) return false;
5282
+ for (states) |state| {
5283
+ var found = false;
5284
+ for (@typeInfo(runtime_effects.EffectAudioEventKind).@"enum".fields) |expected|
5285
+ if (std.mem.eql(u8, expected.name, state.name)) {
5286
+ found = true;
5287
+ };
5288
+ if (!found) return false;
5289
+ }
5290
+ } else if (std.mem.eql(u8, field.name, "playing") or std.mem.eql(u8, field.name, "buffering")) {
5291
+ if (field.type != bool) return false;
5292
+ } else if (std.mem.eql(u8, field.name, "key") or std.mem.eql(u8, field.name, "positionMs") or
5293
+ std.mem.eql(u8, field.name, "durationMs") or std.mem.eql(u8, field.name, "bands"))
5294
+ {
5295
+ if (field.type != []const u8) return false;
5296
+ } else return false;
5297
+ }
5298
+ return true;
5299
+ }
5300
+
5301
+ fn exactSpawnArmShape(comptime T: type, comptime line: bool) bool {
5302
+ if (@typeInfo(T) != .@"struct") return false;
5303
+ const fields = @typeInfo(T).@"struct".fields;
5304
+ if (fields.len != (if (line) @as(usize, 4) else 8)) return false;
5305
+ for (fields) |field| {
5306
+ if (std.mem.eql(u8, field.name, "key") or
5307
+ (line and std.mem.eql(u8, field.name, "line")) or
5308
+ (!line and (std.mem.eql(u8, field.name, "output") or std.mem.eql(u8, field.name, "stderrTail"))))
5309
+ {
5310
+ if (field.type != []const u8) return false;
5311
+ } else if ((line and std.mem.eql(u8, field.name, "truncated")) or
5312
+ (!line and (std.mem.eql(u8, field.name, "outputTruncated") or std.mem.eql(u8, field.name, "stderrTruncated"))))
5313
+ {
5314
+ if (field.type != bool) return false;
5315
+ } else if ((line and std.mem.eql(u8, field.name, "droppedBefore")) or
5316
+ (!line and (std.mem.eql(u8, field.name, "code") or std.mem.eql(u8, field.name, "droppedLines"))))
5317
+ {
5318
+ if (field.type != f64 and field.type != i64 and field.type != u64) return false;
5319
+ } else if (!line and std.mem.eql(u8, field.name, "reason")) {
5320
+ if (@typeInfo(field.type) != .@"enum") return false;
5321
+ const reasons = @typeInfo(field.type).@"enum".fields;
5322
+ const expected = @typeInfo(runtime_effects.EffectExitReason).@"enum".fields;
5323
+ if (reasons.len != expected.len) return false;
5324
+ for (reasons) |reason| {
5325
+ var found = false;
5326
+ for (expected) |value| if (std.mem.eql(u8, reason.name, value.name)) {
5327
+ found = true;
5328
+ };
5329
+ if (!found) return false;
5330
+ }
5331
+ } else return false;
5332
+ }
5333
+ return true;
5334
+ }
5335
+
3610
5336
  /// The arm's `state` member for an engine event kind, matched
3611
5337
  /// by member NAME (the frontend pins the member set, so the
3612
5338
  /// app's declaration order never matters to the wire).
@@ -3732,12 +5458,13 @@ pub fn TsCoreHost(comptime core: type) type {
3732
5458
  const info = @typeInfo(T);
3733
5459
  if (info != .@"struct") return false;
3734
5460
  const fields = info.@"struct".fields;
3735
- if (fields.len != 5) return false;
5461
+ if (fields.len != 5 and fields.len != 6) return false;
5462
+ const words = fields.len == 6;
3736
5463
  var ok = true;
3737
5464
  for (fields) |f| {
3738
5465
  if (std.mem.eql(u8, f.name, "state")) {
3739
5466
  if (@typeInfo(f.type) != .@"enum") ok = false;
3740
- } else if (std.mem.eql(u8, f.name, "id") or std.mem.eql(u8, f.name, "width") or std.mem.eql(u8, f.name, "height") or std.mem.eql(u8, f.name, "status")) {
5467
+ } else if ((!words and std.mem.eql(u8, f.name, "id")) or (words and (std.mem.eql(u8, f.name, "imageLower") or std.mem.eql(u8, f.name, "imageUpper"))) or std.mem.eql(u8, f.name, "width") or std.mem.eql(u8, f.name, "height") or std.mem.eql(u8, f.name, "status")) {
3741
5468
  if (f.type != i64 and f.type != u64 and f.type != f64) ok = false;
3742
5469
  } else {
3743
5470
  ok = false;
@@ -3769,6 +5496,9 @@ pub fn TsCoreHost(comptime core: type) type {
3769
5496
  inline for (fields) |f| {
3770
5497
  if (comptime std.mem.eql(u8, f.name, "state")) {
3771
5498
  @field(payload, f.name) = imageStateValue(f.type, result.outcome);
5499
+ } else if (comptime std.mem.eql(u8, f.name, "imageLower") or std.mem.eql(u8, f.name, "imageUpper")) {
5500
+ const word: u32 = if (comptime std.mem.eql(u8, f.name, "imageLower")) @truncate(result.id) else @truncate(result.id >> 32);
5501
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(word) else @intCast(word);
3772
5502
  } else if (comptime std.mem.eql(u8, f.name, "id")) {
3773
5503
  @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(result.id) else @intCast(result.id);
3774
5504
  } else if (comptime std.mem.eql(u8, f.name, "width")) {
@@ -3791,6 +5521,77 @@ pub fn TsCoreHost(comptime core: type) type {
3791
5521
  /// `imageArmShape`'s twin: `key` (number), `state` (any enum;
3792
5522
  /// members matched by name at delivery), `bytes` (bytes),
3793
5523
  /// `droppedPending`/`droppedTotal` (numbers).
5524
+ fn channelSourceArmShape(comptime T: type) bool {
5525
+ const info = @typeInfo(T);
5526
+ if (info != .@"struct") return false;
5527
+ const fields = info.@"struct".fields;
5528
+ if (fields.len != 3) return false;
5529
+ var ok = true;
5530
+ for (fields) |f| {
5531
+ if (std.mem.eql(u8, f.name, "state")) {
5532
+ if (@typeInfo(f.type) != .@"enum") ok = false;
5533
+ } else if (std.mem.eql(u8, f.name, "bytes")) {
5534
+ if (f.type != []const u8) ok = false;
5535
+ } else if (std.mem.eql(u8, f.name, "key")) {
5536
+ if (f.type != i64 and f.type != u64 and f.type != f64) ok = false;
5537
+ } else {
5538
+ ok = false;
5539
+ }
5540
+ }
5541
+ return ok;
5542
+ }
5543
+
5544
+ /// The arm's `state` member for an engine channel source result kind,
5545
+ /// matched by member NAME — `imageStateValue`'s twin.
5546
+ fn channelSourceStateValue(comptime E: type, kind: runtime_effects.EffectChannelSourceState) E {
5547
+ const name = @tagName(kind);
5548
+ inline for (@typeInfo(E).@"enum".fields) |f| {
5549
+ if (std.mem.eql(u8, f.name, name)) return @enumFromInt(f.value);
5550
+ }
5551
+ @panic("ts core host: a channel source result kind has no member in the event arm's state union - the frontend's own shape check should have stopped this build");
5552
+ }
5553
+
5554
+ /// Build the three-field channel source result arm at index `tag` from
5555
+ /// an engine event, by field name. The bytes copy into the
5556
+ /// core's frame arena like every routed payload (the engine's
5557
+ /// slice is drain scratch); `key` is the channel key echoed
5558
+ /// verbatim (always below 2^53 — the bridge refused anything
5559
+ /// wider — so both number classes carry it exactly), and the
5560
+ /// drop counters widen the way the subset's number model
5561
+ /// classes them.
5562
+ fn msgFromTagChannelSource(tag: u8, event: runtime_effects.EffectChannelSourceResult) Msg {
5563
+ inline for (msg_arms, 0..) |arm, index| {
5564
+ if (tag == index) {
5565
+ if (comptime channelSourceArmShape(arm.type)) {
5566
+ const fields = @typeInfo(arm.type).@"struct".fields;
5567
+ var payload: arm.type = undefined;
5568
+ inline for (fields) |f| {
5569
+ if (comptime std.mem.eql(u8, f.name, "state")) {
5570
+ @field(payload, f.name) = channelSourceStateValue(f.type, event.state);
5571
+ } else if (comptime std.mem.eql(u8, f.name, "key")) {
5572
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.key) else @intCast(event.key);
5573
+ } else if (event.bytes.len == 0) {
5574
+ // Payload-free events (rejected/closed
5575
+ // terminals, and the staged rejection
5576
+ // Msgs that must be self-contained
5577
+ // across the frame reset) carry the
5578
+ // static empty slice, never a
5579
+ // zero-length frame pointer.
5580
+ @field(payload, f.name) = "";
5581
+ } else {
5582
+ const copy = core.rt.frameAlloc(u8, event.bytes.len);
5583
+ @memcpy(copy, event.bytes);
5584
+ @field(payload, f.name) = copy;
5585
+ }
5586
+ }
5587
+ return @unionInit(Msg, arm.name, payload);
5588
+ }
5589
+ @panic("ts core host: a channel source result targets Msg arm '" ++ arm.name ++ "', which is not the three-field channel source result record");
5590
+ }
5591
+ }
5592
+ @panic("ts core host: a channel source result names a Msg tag outside the union");
5593
+ }
5594
+
3794
5595
  fn channelArmShape(comptime T: type) bool {
3795
5596
  const info = @typeInfo(T);
3796
5597
  if (info != .@"struct") return false;
@@ -4135,3 +5936,116 @@ pub fn TsCoreHost(comptime core: type) type {
4135
5936
  }
4136
5937
  };
4137
5938
  }
5939
+
5940
+ const PtyBindingTestCore = struct {
5941
+ pub const Model = struct {};
5942
+ const PtyState = enum { output, exit };
5943
+ const Reason = enum { exited, signaled, cancelled, rejected, spawn_failed };
5944
+ pub const Msg = union(enum) { event: struct { key: []const u8, state: PtyState, bytes: []const u8, code: f64, reason: Reason, signal: f64, droppedWrites: f64 } };
5945
+ var value: Model = .{};
5946
+ pub fn initialModel() *const Model {
5947
+ return &value;
5948
+ }
5949
+ pub fn update(model: *const Model, _: Msg) *const Model {
5950
+ return model;
5951
+ }
5952
+ pub fn commitModelRoot(model: *const Model) *const Model {
5953
+ return model;
5954
+ }
5955
+ pub const rt = struct {
5956
+ var arena: std.heap.ArenaAllocator = undefined;
5957
+ pub fn frameAlloc(comptime T: type, len: usize) []T {
5958
+ return arena.allocator().alloc(T, len) catch unreachable;
5959
+ }
5960
+ pub fn frameReset() void {
5961
+ _ = arena.reset(.retain_capacity);
5962
+ }
5963
+ pub fn resetAll() void {
5964
+ frameReset();
5965
+ }
5966
+ };
5967
+ };
5968
+
5969
+ test "exact timer wire admission preserves unsigned decimal ownership and nanosecond limits" {
5970
+ const Host = TsCoreHost(PtyBindingTestCore);
5971
+ for ([_]u64{ 0, 1, 31_536_000_001, std.math.maxInt(u64) / std.time.ns_per_ms }) |value| {
5972
+ var decimal: [20]u8 = undefined;
5973
+ const text = try std.fmt.bufPrint(&decimal, "{d}", .{value});
5974
+ try std.testing.expectEqual(value, Host.parseExactTimerInterval(text).?);
5975
+ @memset(&decimal, 'x');
5976
+ }
5977
+ for ([_][]const u8{ "", "00", "+1", "-0", "1_0", "1.0", "1e2", " 1", "1 ", "1\x00", "18446744073710", "18446744073709551615", "18446744073709551616", "123456789012345678901" }) |text|
5978
+ try std.testing.expect(Host.parseExactTimerInterval(text) == null);
5979
+ }
5980
+
5981
+ test "exact audio identities and seek positions admit every canonical u64 without rounding" {
5982
+ const Host = TsCoreHost(PtyBindingTestCore);
5983
+ for ([_]u64{ 0, 1, 9007199254740991, 9007199254740993, std.math.maxInt(u64) }) |value| {
5984
+ var buffer: [20]u8 = undefined;
5985
+ const text = try std.fmt.bufPrint(&buffer, "{d}", .{value});
5986
+ try std.testing.expectEqual(value, Host.parseExactUnsigned(text).?);
5987
+ @memset(&buffer, 'x');
5988
+ }
5989
+ for ([_][]const u8{ "", "00", "01", "+1", "-0", "-1", "1.0", "1e2", " 1", "1 ", "1\x00", "18446744073709551616", "123456789012345678901" }) |text|
5990
+ try std.testing.expect(Host.parseExactUnsigned(text) == null);
5991
+ }
5992
+
5993
+ test "PTY name bindings own bytes and retain ended identities without restricting unbound reuse" {
5994
+ const Core = PtyBindingTestCore;
5995
+ const Host = TsCoreHost(Core);
5996
+ Core.rt.arena = .init(std.testing.allocator);
5997
+ defer Core.rt.arena.deinit();
5998
+ var fx = Host.Fx.init(std.testing.allocator);
5999
+ defer fx.deinit();
6000
+ fx.executor = .fake;
6001
+ Host.boot();
6002
+ var name = [_]u8{ 's', 'h', 255, 0 };
6003
+ Host.issuePtySpawn(&fx, &name, 0, 80, 24, "", &.{"/bin/sh"});
6004
+ const original = Host.resolvePtyKey(&name);
6005
+ try std.testing.expect(original != 0);
6006
+ @memset(&name, 'x');
6007
+ try std.testing.expectEqual(original, Host.resolvePtyKey("sh\xff\x00"));
6008
+ try std.testing.expectEqual(@as(u64, 0), Host.resolvePtyKey(&name));
6009
+ try fx.feedPtyOutput(original, "owned screen");
6010
+ const output = fx.takeMsg().?.event;
6011
+ try std.testing.expectEqualStrings("sh\xff\x00", output.key);
6012
+ try std.testing.expectEqualStrings("owned screen", output.bytes);
6013
+ try fx.feedPtyExit(original, 0, 0, .exited, 0);
6014
+ _ = fx.takeMsg();
6015
+ try std.testing.expectEqual(original, Host.resolvePtyKey("sh\xff\x00"));
6016
+ // Distinct unbound names repeatedly reuse an available effect slot, while
6017
+ // the named terminal's ended screen keeps its identity through every exit.
6018
+ for (0..8) |i| {
6019
+ var buffer: [30]u8 = undefined;
6020
+ const other = try std.fmt.bufPrint(&buffer, "unbound-{d}", .{i});
6021
+ Host.issuePtySpawn(&fx, other, 0, 80, 24, "", &.{"/bin/sh"});
6022
+ const key = fx.pendingPtyAt(0).?.key;
6023
+ try std.testing.expect(key != original);
6024
+ try fx.feedPtyExit(key, 0, 0, .exited, 0);
6025
+ _ = fx.takeMsg();
6026
+ try std.testing.expectEqual(original, Host.resolvePtyKey("sh\xff\x00"));
6027
+ }
6028
+ Host.issuePtySpawn(&fx, "sh\xff\x00", 0, 80, 24, "", &.{"/bin/sh"});
6029
+ try std.testing.expectEqual(original, fx.pendingPtyAt(0).?.key);
6030
+ Host.issuePtySpawn(&fx, "sh\xff\x00", 0, 80, 24, "", &.{"/bin/sh"});
6031
+ const refused = fx.takeMsg().?.event;
6032
+ try std.testing.expectEqual(Core.Reason.rejected, refused.reason);
6033
+ try std.testing.expectEqualStrings("sh\xff\x00", refused.key);
6034
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingPtyCount());
6035
+ // Bound ended grids occupy the documented budget. Exhaustion still
6036
+ // delivers the normal one rejected terminal instead of aliasing a screen.
6037
+ for ([_][]const u8{ "second", "third", "fourth" }) |name_key| {
6038
+ Host.issuePtySpawn(&fx, name_key, 0, 80, 24, "", &.{"/bin/sh"});
6039
+ const key = Host.resolvePtyKey(name_key);
6040
+ try std.testing.expect(key != 0 and key != original);
6041
+ try fx.feedPtyExit(key, 0, 0, .exited, 0);
6042
+ _ = fx.takeMsg();
6043
+ }
6044
+ Host.issuePtySpawn(&fx, "fifth", 0, 80, 24, "", &.{"/bin/sh"});
6045
+ const full = fx.takeMsg().?.event;
6046
+ try std.testing.expectEqual(Core.Reason.rejected, full.reason);
6047
+ try std.testing.expectEqualStrings("fifth", full.key);
6048
+ try std.testing.expectEqual(@as(u64, 0), Host.resolvePtyKey("fifth"));
6049
+ Host.boot();
6050
+ try std.testing.expectEqual(@as(u64, 0), Host.resolvePtyKey("sh\xff\x00"));
6051
+ }