@native-sdk/cli 0.10.1 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (555) hide show
  1. package/README.md +8 -6
  2. package/bin/native.js +2 -1
  3. package/build/app.zig +393 -97
  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 +2030 -83
  8. package/native-sdk.d.ts +5 -1
  9. package/package.json +20 -14
  10. package/packages/core/compile-surface/core.ts +164 -72
  11. package/packages/core/package-lock.json +75 -357
  12. package/packages/core/package.json +25 -4
  13. package/packages/core/scripts/compiler_command.mjs +17 -12
  14. package/packages/core/scripts/compiler_typecheck.mjs +1 -0
  15. package/packages/core/scripts/gen_declarations.mjs +3 -2
  16. package/packages/core/scripts/gen_service_surface.mjs +22 -10
  17. package/packages/core/scripts/install_scriptc.mjs +182 -0
  18. package/packages/core/scripts/invoke_scriptc.mjs +18 -0
  19. package/packages/core/scripts/merge_static_archives.mjs +6 -1
  20. package/packages/core/scripts/npm_static_spike.mjs +2 -2
  21. package/packages/core/scripts/run_external_core_compiler.mjs +22 -10
  22. package/packages/core/scripts/run_external_service_compiler.mjs +15 -15
  23. package/packages/core/scripts/run_library_compiler.mjs +51 -0
  24. package/packages/core/scripts/run_native_tests.mjs +22 -0
  25. package/packages/core/scripts/scriptc-toolchain.json +101 -0
  26. package/packages/core/scripts/scriptc_toolchain.mjs +121 -0
  27. package/packages/core/scripts/stage_external_core.mjs +68 -1
  28. package/packages/core/scripts/surface_manifest_diff.mjs +19 -12
  29. package/packages/core/sdk/bytes.d.ts +2 -0
  30. package/packages/core/sdk/bytes.ts +86 -0
  31. package/packages/core/sdk/core.d.ts +332 -5
  32. package/packages/core/sdk/core.ts +371 -85
  33. package/packages/core/sdk/events.d.ts +252 -0
  34. package/packages/core/sdk/events.ts +240 -2
  35. package/packages/core/sdk/internal/image_identity.d.ts +7 -0
  36. package/packages/core/sdk/internal/image_identity.ts +71 -0
  37. package/packages/core/sdk/internal/markdown_policy.d.ts +5 -0
  38. package/packages/core/sdk/internal/markdown_policy.ts +878 -0
  39. package/packages/core/sdk/text.d.ts +27 -0
  40. package/packages/core/sdk/text.ts +206 -15
  41. package/packages/core/sdk/theme.d.ts +251 -0
  42. package/packages/core/sdk/theme.ts +267 -0
  43. package/packages/core/src/authorization.ts +137 -0
  44. package/packages/core/src/automation_commands.ts +201 -0
  45. package/packages/core/src/automation_interactions.ts +92 -0
  46. package/packages/core/src/bridge_descriptors.ts +104 -0
  47. package/packages/core/src/builtin_coordination.ts +172 -0
  48. package/packages/core/src/canvas_frame_coordination.ts +81 -0
  49. package/packages/core/src/canvas_presentation_lifecycle.ts +84 -0
  50. package/packages/core/src/canvas_scene_observation.ts +145 -0
  51. package/packages/core/src/chart_content.ts +161 -0
  52. package/packages/core/src/chart_plans.ts +432 -0
  53. package/packages/core/src/checker.ts +186 -19
  54. package/packages/core/src/cli.ts +2 -11
  55. package/packages/core/src/code_content.ts +580 -0
  56. package/packages/core/src/command_coordination.ts +140 -0
  57. package/packages/core/src/component_composition.ts +94 -0
  58. package/packages/core/src/component_construction.ts +149 -0
  59. package/packages/core/src/context_menus.ts +76 -0
  60. package/packages/core/src/contract.ts +25 -7
  61. package/packages/core/src/control_appearance.ts +232 -0
  62. package/packages/core/src/control_commands.ts +115 -0
  63. package/packages/core/src/control_content.ts +105 -0
  64. package/packages/core/src/control_geometry.ts +107 -0
  65. package/packages/core/src/control_payloads.ts +119 -0
  66. package/packages/core/src/control_primitives.ts +134 -0
  67. package/packages/core/src/devhost.ts +82 -7
  68. package/packages/core/src/devhost_journal.mjs +30 -7
  69. package/packages/core/src/diagnostics.ts +7 -0
  70. package/packages/core/src/effect_plans.ts +71 -0
  71. package/packages/core/src/extent_program.ts +53 -0
  72. package/packages/core/src/flow_measurement.ts +121 -0
  73. package/packages/core/src/font_registry.ts +37 -0
  74. package/packages/core/src/frontend.ts +12 -10
  75. package/packages/core/src/glyph_atlas.ts +86 -0
  76. package/packages/core/src/gpu_packet_preparation.ts +130 -0
  77. package/packages/core/src/gpu_planning.ts +123 -0
  78. package/packages/core/src/gpu_presentation.ts +55 -0
  79. package/packages/core/src/host_flow.ts +89 -0
  80. package/packages/core/src/host_input_regions.ts +165 -0
  81. package/packages/core/src/image_registry.ts +66 -0
  82. package/packages/core/src/indicator_plans.ts +132 -0
  83. package/packages/core/src/infer.ts +150 -8
  84. package/packages/core/src/input_composition.ts +116 -0
  85. package/packages/core/src/intrinsic_measure.ts +100 -0
  86. package/packages/core/src/layout_coordination.ts +207 -0
  87. package/packages/core/src/leaf_plans.ts +134 -0
  88. package/packages/core/src/markup_canonical.ts +140 -0
  89. package/packages/core/src/markup_construction.ts +189 -0
  90. package/packages/core/src/markup_development.ts +160 -0
  91. package/packages/core/src/markup_display.ts +43 -0
  92. package/packages/core/src/markup_document.ts +226 -0
  93. package/packages/core/src/markup_elements.ts +225 -0
  94. package/packages/core/src/markup_expressions.ts +79 -0
  95. package/packages/core/src/markup_imports.ts +146 -0
  96. package/packages/core/src/markup_parser.ts +228 -0
  97. package/packages/core/src/markup_runtime.ts +93 -0
  98. package/packages/core/src/markup_scalars.ts +143 -0
  99. package/packages/core/src/markup_shapes.ts +243 -0
  100. package/packages/core/src/markup_specialized.ts +242 -0
  101. package/packages/core/src/markup_text.ts +86 -0
  102. package/packages/core/src/markup_values.ts +336 -0
  103. package/packages/core/src/measurement_coordination.ts +185 -0
  104. package/packages/core/src/modules.ts +1 -1
  105. package/packages/core/src/motion_sampling.ts +100 -0
  106. package/packages/core/src/paragraph_layout.ts +192 -0
  107. package/packages/core/src/portable_sources.json +98 -0
  108. package/packages/core/src/portable_sources.ts +17 -0
  109. package/packages/core/src/registered_font.ts +92 -0
  110. package/packages/core/src/render_animation_lifecycle.ts +128 -0
  111. package/packages/core/src/render_coordination.ts +170 -0
  112. package/packages/core/src/render_resources.ts +234 -0
  113. package/packages/core/src/runtime_policy.ts +3954 -0
  114. package/packages/core/src/scalar_text.ts +82 -0
  115. package/packages/core/src/scroll_mutation.ts +86 -0
  116. package/packages/core/src/scroll_tree.ts +86 -0
  117. package/packages/core/src/service_contract.ts +55 -3
  118. package/packages/core/src/session_codecs.ts +309 -0
  119. package/packages/core/src/shell_admission.ts +126 -0
  120. package/packages/core/src/shell_coordination.ts +93 -0
  121. package/packages/core/src/sqlite_cli.ts +14 -46
  122. package/packages/core/src/sqlite_codegen.ts +84 -0
  123. package/packages/core/src/staged_rebuild.ts +60 -0
  124. package/packages/core/src/status_validation.ts +232 -0
  125. package/packages/core/src/stream_policy.ts +63 -0
  126. package/packages/core/src/surface_recipes.ts +136 -0
  127. package/packages/core/src/system_admission.ts +60 -0
  128. package/packages/core/src/terminal_paint.ts +436 -0
  129. package/packages/core/src/text_document_width.ts +81 -0
  130. package/packages/core/src/text_measurement_cache.ts +69 -0
  131. package/packages/core/src/text_query_layout.ts +179 -0
  132. package/packages/core/src/text_run_layout.ts +410 -0
  133. package/packages/core/src/text_span_queries.ts +355 -0
  134. package/packages/core/src/typed_ast.ts +18 -1
  135. package/packages/core/src/types.ts +7 -5
  136. package/packages/core/src/vector_effects.ts +98 -0
  137. package/packages/core/src/vector_raster.ts +243 -0
  138. package/packages/core/src/view_bridge.ts +161 -0
  139. package/packages/core/src/view_check.ts +145 -0
  140. package/packages/core/src/view_components.ts +2415 -0
  141. package/packages/core/src/view_coordination.ts +198 -0
  142. package/packages/core/src/view_evaluator.ts +823 -0
  143. package/packages/core/src/view_frontend.ts +1102 -0
  144. package/packages/core/src/view_program.ts +221 -0
  145. package/packages/core/src/view_reload.ts +166 -0
  146. package/packages/core/src/view_reload_watch.ts +98 -0
  147. package/packages/core/src/view_sources.ts +34 -0
  148. package/packages/core/src/virtual_windows.ts +88 -0
  149. package/packages/core/src/web_panes.ts +67 -0
  150. package/packages/core/src/widget_audits.ts +202 -0
  151. package/packages/core/src/widget_changes.ts +258 -0
  152. package/packages/core/src/widget_continuity.ts +37 -0
  153. package/packages/core/src/widget_metrics.ts +139 -0
  154. package/packages/core/src/widget_motion.ts +171 -0
  155. package/packages/core/src/widget_paint.ts +272 -0
  156. package/packages/core/src/widget_paint_walk.ts +203 -0
  157. package/packages/core/src/widget_presentation.ts +141 -0
  158. package/packages/core/src/widget_reconcile.ts +63 -0
  159. package/packages/core/src/widget_retention.ts +62 -0
  160. package/packages/core/src/widget_routing.ts +262 -0
  161. package/packages/core/src/window_lifecycle.ts +92 -0
  162. package/packages/core/testing/index.ts +430 -0
  163. package/schemas/app.schema.json +13 -0
  164. package/skill-data/core/SKILL.md +2 -2
  165. package/skill-data/native-ui/SKILL.md +77 -18
  166. package/skill-data/ts-core/SKILL.md +117 -11
  167. package/skill-data/ts-services/SKILL.md +1 -1
  168. package/skill-data/ts-services/references/service-surface.md +288 -144
  169. package/src/app_runner/root.zig +39 -12
  170. package/src/app_runner/ts_compiled_view.zig +1702 -0
  171. package/src/app_runner/ts_core_main.zig +185 -14
  172. package/src/app_runner/ts_core_mobile.zig +25 -13
  173. package/src/automation/server.zig +57 -6
  174. package/src/automation/snapshot.zig +9 -637
  175. package/src/automation/snapshot_reference.zig +656 -0
  176. package/src/automation/snapshot_serialization.zig +566 -0
  177. package/src/embed/host.zig +2 -0
  178. package/src/embed/tests.zig +2 -0
  179. package/src/embed/ui_host.zig +2 -0
  180. package/src/platform/keyboard_input.zig +32 -0
  181. package/src/platform/linux/gtk_host.c +36 -24
  182. package/src/platform/linux/gtk_pixels.h +118 -0
  183. package/src/platform/linux/gtk_pixels_test.c +241 -0
  184. package/src/platform/linux/root.zig +4 -0
  185. package/src/platform/macos/appkit_host.h +7 -2
  186. package/src/platform/macos/appkit_host.m +219 -39
  187. package/src/platform/macos/cef_host.mm +15 -1
  188. package/src/platform/macos/global_shortcuts.zig +138 -0
  189. package/src/platform/macos/key_codes.zig +102 -0
  190. package/src/platform/macos/keyboard_input.zig +81 -0
  191. package/src/platform/macos/pointer_motion_test.m +96 -0
  192. package/src/platform/macos/root.zig +25 -3
  193. package/src/platform/macos/scroll_driver_test.m +105 -0
  194. package/src/platform/macos/spectrum_bins.h +34 -0
  195. package/src/platform/macos/spectrum_bins_test.c +56 -0
  196. package/src/platform/macos/text_keyboard_test.m +80 -0
  197. package/src/platform/macos/webview_inspection_test.m +106 -0
  198. package/src/platform/macos/widget_focus_test.m +66 -0
  199. package/src/platform/null_platform.zig +130 -2
  200. package/src/platform/null_platform_tests.zig +13 -0
  201. package/src/platform/root.zig +15 -0
  202. package/src/platform/types.zig +115 -0
  203. package/src/platform/windows/global_shortcuts.zig +157 -0
  204. package/src/platform/windows/key_codes.zig +63 -0
  205. package/src/platform/windows/keyboard_input.zig +136 -0
  206. package/src/platform/windows/root.zig +17 -0
  207. package/src/platform/windows/webview2_host.cpp +7 -2
  208. package/src/primitives/app_manifest/comptime_scene.zig +1 -1
  209. package/src/primitives/app_manifest/root.zig +2 -0
  210. package/src/primitives/app_manifest/tests.zig +4 -1
  211. package/src/primitives/app_manifest/validation.zig +2 -0
  212. package/src/primitives/canvas/a11y_audit.zig +3 -1
  213. package/src/primitives/canvas/canvas_frame_coordination_policy.zig +134 -0
  214. package/src/primitives/canvas/chart_content_policy.zig +75 -0
  215. package/src/primitives/canvas/chart_plan_policy.zig +196 -0
  216. package/src/primitives/canvas/code_content_policy.zig +162 -0
  217. package/src/primitives/canvas/commands.zig +29 -1
  218. package/src/primitives/canvas/component_composition.zig +125 -0
  219. package/src/primitives/canvas/component_composition_policy.zig +44 -0
  220. package/src/primitives/canvas/component_construction_policy.zig +187 -0
  221. package/src/primitives/canvas/container_layout_policy.zig +87 -0
  222. package/src/primitives/canvas/control_appearance_policy.zig +142 -0
  223. package/src/primitives/canvas/control_command_policy.zig +75 -0
  224. package/src/primitives/canvas/control_content_policy.zig +90 -0
  225. package/src/primitives/canvas/control_geometry_policy.zig +165 -0
  226. package/src/primitives/canvas/control_payload_policy.zig +48 -0
  227. package/src/primitives/canvas/control_primitive_policy.zig +129 -0
  228. package/src/primitives/canvas/decision_reuse.zig +133 -0
  229. package/src/primitives/canvas/effect_plan_policy.zig +96 -0
  230. package/src/primitives/canvas/events.zig +1027 -1
  231. package/src/primitives/canvas/flow_measurement_policy.zig +237 -0
  232. package/src/primitives/canvas/font_ttf.zig +27 -3
  233. package/src/primitives/canvas/fonts/Geist-Bold.ttf +0 -0
  234. package/src/primitives/canvas/fonts/Geist-Medium.ttf +0 -0
  235. package/src/primitives/canvas/fonts/OFL.txt +93 -0
  236. package/src/primitives/canvas/fonts/README.md +15 -0
  237. package/src/primitives/canvas/frame.zig +92 -23
  238. package/src/primitives/canvas/glyph_atlas_policy.zig +40 -0
  239. package/src/primitives/canvas/gpu.zig +10 -0
  240. package/src/primitives/canvas/gpu_packet_preparation_policy.zig +325 -0
  241. package/src/primitives/canvas/gpu_planning_policy.zig +364 -0
  242. package/src/primitives/canvas/gpu_presentation_policy.zig +74 -0
  243. package/src/primitives/canvas/grid_layout_policy.zig +51 -0
  244. package/src/primitives/canvas/indicator_plan_policy.zig +128 -0
  245. package/src/primitives/canvas/intrinsic_layout_policy.zig +87 -0
  246. package/src/primitives/canvas/intrinsic_measure_policy.zig +131 -0
  247. package/src/primitives/canvas/layout_audit.zig +5 -2
  248. package/src/primitives/canvas/layout_coordination_policy.zig +262 -0
  249. package/src/primitives/canvas/leaf_plan_policy.zig +117 -0
  250. package/src/primitives/canvas/markdown.zig +13 -3
  251. package/src/primitives/canvas/markdown_content_policy.zig +227 -0
  252. package/src/primitives/canvas/markdown_image_binding.zig +81 -0
  253. package/src/primitives/canvas/markdown_tests.zig +3 -3
  254. package/src/primitives/canvas/measurement_coordination_policy.zig +288 -0
  255. package/src/primitives/canvas/numeric_capabilities.zig +14 -0
  256. package/src/primitives/canvas/reference.zig +15 -11
  257. package/src/primitives/canvas/reference_tests.zig +58 -0
  258. package/src/primitives/canvas/registered_font_policy.zig +152 -0
  259. package/src/primitives/canvas/render.zig +48 -0
  260. package/src/primitives/canvas/render_cache_policy.zig +184 -0
  261. package/src/primitives/canvas/render_coordination_policy.zig +163 -0
  262. package/src/primitives/canvas/render_damage_policy.zig +160 -0
  263. package/src/primitives/canvas/render_effects.zig +14 -0
  264. package/src/primitives/canvas/render_generic_resources.zig +14 -0
  265. package/src/primitives/canvas/render_images.zig +14 -0
  266. package/src/primitives/canvas/render_layers.zig +14 -0
  267. package/src/primitives/canvas/render_override_policy.zig +119 -0
  268. package/src/primitives/canvas/render_paths.zig +14 -0
  269. package/src/primitives/canvas/render_plan_policy.zig +199 -0
  270. package/src/primitives/canvas/render_resource_policy.zig +476 -0
  271. package/src/primitives/canvas/root.zig +107 -4
  272. package/src/primitives/canvas/semantic_tree_policy.zig +158 -0
  273. package/src/primitives/canvas/serialization.zig +8 -1
  274. package/src/primitives/canvas/surface_layout_policy.zig +36 -0
  275. package/src/primitives/canvas/surface_recipe_policy.zig +231 -0
  276. package/src/primitives/canvas/terminal_grid.zig +10 -696
  277. package/src/primitives/canvas/terminal_grid_reference.zig +709 -0
  278. package/src/primitives/canvas/terminal_paint_policy.zig +191 -0
  279. package/src/primitives/canvas/text.zig +1 -0
  280. package/src/primitives/canvas/text_atlas.zig +113 -0
  281. package/src/primitives/canvas/text_cache_policy.zig +94 -0
  282. package/src/primitives/canvas/text_document_policy.zig +120 -0
  283. package/src/primitives/canvas/text_layout.zig +51 -2
  284. package/src/primitives/canvas/text_layout_cache.zig +29 -0
  285. package/src/primitives/canvas/text_layout_hash.zig +1 -0
  286. package/src/primitives/canvas/text_layout_types.zig +3 -0
  287. package/src/primitives/canvas/text_measure_cache.zig +46 -0
  288. package/src/primitives/canvas/text_measurement_policy.zig +124 -0
  289. package/src/primitives/canvas/text_metrics.zig +53 -37
  290. package/src/primitives/canvas/text_metrics_tests.zig +52 -7
  291. package/src/primitives/canvas/text_query_policy.zig +295 -0
  292. package/src/primitives/canvas/text_run_policy.zig +252 -0
  293. package/src/primitives/canvas/text_scalar_policy.zig +234 -0
  294. package/src/primitives/canvas/text_span_query_policy.zig +232 -0
  295. package/src/primitives/canvas/text_spans.zig +280 -8
  296. package/src/primitives/canvas/text_tests.zig +10 -0
  297. package/src/primitives/canvas/tokens.zig +47 -0
  298. package/src/primitives/canvas/ui.zig +251 -83
  299. package/src/primitives/canvas/ui_markup.zig +207 -46
  300. package/src/primitives/canvas/ui_markup_canonical.zig +237 -0
  301. package/src/primitives/canvas/ui_markup_compiled.zig +1724 -80
  302. package/src/primitives/canvas/ui_markup_compiled_tests.zig +225 -0
  303. package/src/primitives/canvas/ui_markup_compiled_values.zig +76 -0
  304. package/src/primitives/canvas/ui_markup_construction.zig +146 -0
  305. package/src/primitives/canvas/ui_markup_contract.zig +146 -14
  306. package/src/primitives/canvas/ui_markup_contract_tests.zig +77 -0
  307. package/src/primitives/canvas/ui_markup_display.zig +82 -0
  308. package/src/primitives/canvas/ui_markup_document.zig +196 -0
  309. package/src/primitives/canvas/ui_markup_elements.zig +163 -0
  310. package/src/primitives/canvas/ui_markup_expr.zig +192 -2
  311. package/src/primitives/canvas/ui_markup_imports.zig +262 -0
  312. package/src/primitives/canvas/ui_markup_parser.zig +117 -0
  313. package/src/primitives/canvas/ui_markup_reflect.zig +56 -0
  314. package/src/primitives/canvas/ui_markup_runtime.zig +76 -0
  315. package/src/primitives/canvas/ui_markup_scalars.zig +115 -0
  316. package/src/primitives/canvas/ui_markup_shapes.zig +224 -0
  317. package/src/primitives/canvas/ui_markup_specialized.zig +106 -0
  318. package/src/primitives/canvas/ui_markup_tests.zig +116 -0
  319. package/src/primitives/canvas/ui_markup_text.zig +128 -0
  320. package/src/primitives/canvas/ui_markup_values.zig +368 -0
  321. package/src/primitives/canvas/ui_markup_view.zig +3026 -57
  322. package/src/primitives/canvas/ui_markup_view_tests.zig +142 -10
  323. package/src/primitives/canvas/ui_schema.zig +13 -1
  324. package/src/primitives/canvas/ui_schema_tests.zig +11 -7
  325. package/src/primitives/canvas/ui_tests.zig +1 -0
  326. package/src/primitives/canvas/vector.zig +36 -2
  327. package/src/primitives/canvas/vector_effect_policy.zig +236 -0
  328. package/src/primitives/canvas/vector_raster_policy.zig +190 -0
  329. package/src/primitives/canvas/virtual_extent_policy.zig +350 -0
  330. package/src/primitives/canvas/virtual_extents.zig +113 -3
  331. package/src/primitives/canvas/virtual_flow_policy.zig +108 -0
  332. package/src/primitives/canvas/widget_audit_policy.zig +293 -0
  333. package/src/primitives/canvas/widget_change_policy.zig +298 -0
  334. package/src/primitives/canvas/widget_invalidation.zig +113 -2
  335. package/src/primitives/canvas/widget_layout.zig +673 -128
  336. package/src/primitives/canvas/widget_layout_tests.zig +4 -0
  337. package/src/primitives/canvas/widget_metric_policy.zig +129 -0
  338. package/src/primitives/canvas/widget_metrics.zig +45 -6
  339. package/src/primitives/canvas/widget_paint_policy.zig +166 -0
  340. package/src/primitives/canvas/widget_paint_walk_policy.zig +252 -0
  341. package/src/primitives/canvas/widget_presentation_policy.zig +168 -0
  342. package/src/primitives/canvas/widget_render.zig +744 -74
  343. package/src/primitives/canvas/widget_render_controls.zig +1217 -133
  344. package/src/primitives/canvas/widget_render_scroll.zig +11 -3
  345. package/src/primitives/canvas/widget_render_style.zig +94 -0
  346. package/src/primitives/canvas/widget_render_surfaces.zig +61 -50
  347. package/src/primitives/canvas/widget_routing.zig +75 -0
  348. package/src/primitives/canvas/widget_routing_policy.zig +135 -0
  349. package/src/primitives/canvas/widget_runtime.zig +21 -1
  350. package/src/primitives/canvas/widget_semantics.zig +25 -0
  351. package/src/primitives/canvas/widget_text_input.zig +86 -23
  352. package/src/primitives/canvas/widget_text_select.zig +1 -0
  353. package/src/primitives/canvas/widget_tree.zig +8 -1
  354. package/src/primitives/canvas/widgets.zig +42 -12
  355. package/src/primitives/canvas/wrapped_layout_policy.zig +104 -0
  356. package/src/root.zig +26 -0
  357. package/src/runtime/accessibility_policy.zig +122 -0
  358. package/src/runtime/api.zig +29 -0
  359. package/src/runtime/app_dispatch_policy.zig +68 -0
  360. package/src/runtime/authorization_policy.zig +150 -0
  361. package/src/runtime/automation_command_policy.zig +241 -0
  362. package/src/runtime/automation_interaction_policy.zig +107 -0
  363. package/src/runtime/automation_snapshot.zig +52 -22
  364. package/src/runtime/automation_snapshot_reference.zig +290 -0
  365. package/src/runtime/automation_widget_dispatch.zig +267 -355
  366. package/src/runtime/automation_widget_dispatch_reference.zig +900 -0
  367. package/src/runtime/blob_policy.zig +58 -0
  368. package/src/runtime/blob_reference.zig +64 -0
  369. package/src/runtime/bridge_descriptor_policy.zig +206 -0
  370. package/src/runtime/bridge_payload.zig +2 -0
  371. package/src/runtime/builtin_bridge.zig +180 -44
  372. package/src/runtime/builtin_coordination_policy.zig +121 -0
  373. package/src/runtime/callback_policy_test_reference.zig +97 -0
  374. package/src/runtime/canvas_drag_policy.zig +94 -0
  375. package/src/runtime/canvas_fonts.zig +38 -10
  376. package/src/runtime/canvas_frame.zig +590 -134
  377. package/src/runtime/canvas_frame_helpers.zig +1 -0
  378. package/src/runtime/canvas_hover_policy.zig +131 -0
  379. package/src/runtime/canvas_images.zig +59 -30
  380. package/src/runtime/canvas_keyboard_focus_policy.zig +154 -0
  381. package/src/runtime/canvas_limits.zig +1 -1
  382. package/src/runtime/canvas_presentation_lifecycle_policy.zig +86 -0
  383. package/src/runtime/canvas_scene_observation_policy.zig +181 -0
  384. package/src/runtime/canvas_widget_context_menu.zig +183 -4
  385. package/src/runtime/canvas_widget_context_menu_test_cases.zig +1147 -0
  386. package/src/runtime/canvas_widget_context_menu_tests.zig +23 -1098
  387. package/src/runtime/canvas_widget_display.zig +110 -9
  388. package/src/runtime/canvas_widget_events.zig +718 -328
  389. package/src/runtime/canvas_widget_runtime.zig +720 -150
  390. package/src/runtime/canvas_widget_scroll_drivers.zig +39 -1
  391. package/src/runtime/canvas_widget_scroll_tests.zig +31 -0
  392. package/src/runtime/canvas_widget_state.zig +93 -56
  393. package/src/runtime/channel_sources.zig +80 -0
  394. package/src/runtime/command_policy.zig +161 -0
  395. package/src/runtime/component_policy.zig +83 -0
  396. package/src/runtime/context_menu_policy.zig +112 -0
  397. package/src/runtime/core.zig +170 -6
  398. package/src/runtime/desktop_files.zig +189 -0
  399. package/src/runtime/effects.zig +638 -33
  400. package/src/runtime/effects_host_tests.zig +25 -0
  401. package/src/runtime/effects_tests.zig +28 -0
  402. package/src/runtime/file_policy_test_reference.zig +113 -0
  403. package/src/runtime/flow.zig +419 -341
  404. package/src/runtime/flow_reference.zig +1427 -0
  405. package/src/runtime/font_registry_policy.zig +72 -0
  406. package/src/runtime/frame_profile.zig +24 -33
  407. package/src/runtime/global_shortcuts.zig +75 -0
  408. package/src/runtime/gpu_surface_events.zig +97 -35
  409. package/src/runtime/host_event_pump.zig +303 -0
  410. package/src/runtime/host_event_pump_reference.zig +268 -0
  411. package/src/runtime/host_flow_policy.zig +155 -0
  412. package/src/runtime/host_input_regions_policy.zig +156 -0
  413. package/src/runtime/image_registry_policy.zig +94 -0
  414. package/src/runtime/input_composition_policy.zig +138 -0
  415. package/src/runtime/journal_policy.zig +66 -0
  416. package/src/runtime/journal_reference.zig +53 -0
  417. package/src/runtime/keyboard_input.zig +86 -0
  418. package/src/runtime/lifecycle_policy_test_reference.zig +97 -0
  419. package/src/runtime/markup_development_policy.zig +91 -0
  420. package/src/runtime/media_surface.zig +40 -1
  421. package/src/runtime/motion_sampling_policy.zig +159 -0
  422. package/src/runtime/recording_policy.zig +42 -0
  423. package/src/runtime/render_animation_policy.zig +206 -0
  424. package/src/runtime/replay_policy.zig +66 -0
  425. package/src/runtime/replay_policy_reference.zig +326 -0
  426. package/src/runtime/replay_progress_policy.zig +64 -0
  427. package/src/runtime/replay_progress_reference.zig +34 -0
  428. package/src/runtime/request_policy_test_reference.zig +188 -0
  429. package/src/runtime/root.zig +16 -0
  430. package/src/runtime/scroll_mutation_policy.zig +130 -0
  431. package/src/runtime/scroll_mutation_runtime.zig +158 -0
  432. package/src/runtime/scroll_tree_policy.zig +99 -0
  433. package/src/runtime/session_blobs.zig +157 -58
  434. package/src/runtime/session_blobs_reference.zig +692 -0
  435. package/src/runtime/session_codec.zig +361 -0
  436. package/src/runtime/session_codec_reference.zig +1027 -0
  437. package/src/runtime/session_journal.zig +246 -983
  438. package/src/runtime/session_record.zig +231 -45
  439. package/src/runtime/session_replay.zig +157 -415
  440. package/src/runtime/session_tests.zig +552 -0
  441. package/src/runtime/shell_admission_policy.zig +225 -0
  442. package/src/runtime/shell_coordination_policy.zig +138 -0
  443. package/src/runtime/shell_layout.zig +126 -1
  444. package/src/runtime/snapshot_policy.zig +60 -0
  445. package/src/runtime/snapshot_reference.zig +64 -0
  446. package/src/runtime/staged_rebuild_policy.zig +83 -0
  447. package/src/runtime/state.zig +16 -0
  448. package/src/runtime/status_validation.zig +190 -0
  449. package/src/runtime/system_admission_policy.zig +140 -0
  450. package/src/runtime/system_services.zig +65 -36
  451. package/src/runtime/tests.zig +2 -0
  452. package/src/runtime/ts_canvas_hooks.zig +261 -0
  453. package/src/runtime/ts_canvas_hooks_tests.zig +279 -0
  454. package/src/runtime/ts_canvas_icons.zig +234 -0
  455. package/src/runtime/ts_core_host.zig +2451 -411
  456. package/src/runtime/ts_core_host_tests.zig +1982 -0
  457. package/src/runtime/ts_test_host.zig +699 -0
  458. package/src/runtime/ts_ui_app.zig +1111 -45
  459. package/src/runtime/ui_app.zig +1381 -650
  460. package/src/runtime/ui_app_provenance.zig +147 -5
  461. package/src/runtime/ui_app_provenance_reference.zig +370 -0
  462. package/src/runtime/ui_app_tests.zig +667 -188
  463. package/src/runtime/ui_app_window_tests.zig +222 -0
  464. package/src/runtime/view.zig +25 -0
  465. package/src/runtime/view_canvas.zig +30 -6
  466. package/src/runtime/view_coordination_policy.zig +147 -0
  467. package/src/runtime/view_reload.zig +226 -0
  468. package/src/runtime/view_widget_control.zig +51 -14
  469. package/src/runtime/view_widget_scroll.zig +46 -26
  470. package/src/runtime/view_widget_text.zig +153 -68
  471. package/src/runtime/view_widget_tree.zig +503 -69
  472. package/src/runtime/virtual_window_policy.zig +128 -0
  473. package/src/runtime/web_pane_policy.zig +111 -0
  474. package/src/runtime/web_pane_test_cases.zig +204 -0
  475. package/src/runtime/webview_view_bridge_tests.zig +2 -0
  476. package/src/runtime/widget_continuity_policy.zig +73 -0
  477. package/src/runtime/widget_motion_policy.zig +238 -0
  478. package/src/runtime/widget_reconcile_policy.zig +81 -0
  479. package/src/runtime/widget_retention_policy.zig +75 -0
  480. package/src/runtime/window_command_bridge_tests.zig +63 -0
  481. package/src/runtime/window_lifecycle_policy.zig +127 -0
  482. package/src/runtime/window_storage.zig +74 -8
  483. package/src/runtime/window_view_runtime.zig +148 -33
  484. package/src/runtime/window_views.zig +179 -11
  485. package/src/security/root.zig +1 -0
  486. package/src/tooling/components/identity_tests.zig +62 -36
  487. package/src/tooling/components/stepper.native +24 -0
  488. package/src/tooling/components/stepper.zig +0 -19
  489. package/src/tooling/components/timeline-item.native +22 -0
  490. package/src/tooling/components/timeline.native +5 -3
  491. package/src/tooling/components/timeline_item.zig +0 -32
  492. package/src/tooling/eject_components.zig +76 -8
  493. package/src/tooling/ios.zig +66 -12
  494. package/src/tooling/manifest.zig +35 -0
  495. package/src/tooling/raw_manifest.zig +6 -0
  496. package/src/tooling/templates.zig +23 -3
  497. package/src/tooling/ts_core.zig +97 -4
  498. package/src/tooling/verbs.zig +87 -1
  499. package/tools/corewire/build_profile.mjs +54 -0
  500. package/tools/corewire/contract_intake.ts +303 -0
  501. package/tools/corewire/contract_intake.zig +82 -0
  502. package/tools/corewire/core.test.ts +188 -0
  503. package/tools/corewire/core_abi.zig +55 -0
  504. package/tools/corewire/core_cases.ts +233 -0
  505. package/tools/corewire/core_contract.ts +407 -0
  506. package/tools/corewire/core_emission.ts +136 -0
  507. package/tools/corewire/core_emission.zig +69 -0
  508. package/tools/corewire/core_goldens.json +3110 -0
  509. package/tools/corewire/core_policy.ts +14 -0
  510. package/tools/corewire/core_policy.zig +48 -0
  511. package/tools/corewire/core_projection.ts +361 -0
  512. package/tools/corewire/core_vocabulary.ts +6 -0
  513. package/tools/corewire/emit.zig +19 -1590
  514. package/tools/corewire/emit_facade.ts +714 -0
  515. package/tools/corewire/emit_facade.zig +10 -3752
  516. package/tools/corewire/emit_mirror.ts +300 -0
  517. package/tools/corewire/emit_profile.ts +50 -0
  518. package/tools/corewire/emit_service.ts +331 -0
  519. package/tools/corewire/emit_service.zig +23 -842
  520. package/tools/corewire/entry.test.ts +95 -0
  521. package/tools/corewire/entry_coordination.ts +127 -0
  522. package/tools/corewire/entry_coordination.zig +190 -0
  523. package/tools/corewire/facade_templates.ts +85 -0
  524. package/tools/corewire/filesystem.test.ts +166 -0
  525. package/tools/corewire/filesystem_coordination.ts +213 -0
  526. package/tools/corewire/filesystem_coordination.zig +245 -0
  527. package/tools/corewire/intake.test.ts +39 -0
  528. package/tools/corewire/intake_cases.ts +55 -0
  529. package/tools/corewire/intake_goldens.json +12237 -0
  530. package/tools/corewire/invocation.test.ts +28 -0
  531. package/tools/corewire/invocation.ts +175 -0
  532. package/tools/corewire/invocation.zig +136 -0
  533. package/tools/corewire/invocation_cases.ts +60 -0
  534. package/tools/corewire/invocation_fixture.ts +33 -0
  535. package/tools/corewire/invocation_goldens.json +1143 -0
  536. package/tools/corewire/invocation_tests.zig +111 -0
  537. package/tools/corewire/invocation_usage.ts +2 -0
  538. package/tools/corewire/lossless_projection.ts +96 -0
  539. package/tools/corewire/main.zig +7 -680
  540. package/tools/corewire/main_reference.zig +415 -0
  541. package/tools/corewire/mirror_templates.ts +59 -0
  542. package/tools/corewire/profile.test.ts +248 -0
  543. package/tools/corewire/profile.zig +56 -0
  544. package/tools/corewire/profile_emission.ts +204 -0
  545. package/tools/corewire/profile_library.json +29 -0
  546. package/tools/corewire/profile_tests.zig +136 -0
  547. package/tools/corewire/service.test.ts +75 -0
  548. package/tools/corewire/service_cases.ts +61 -0
  549. package/tools/corewire/service_contract.zig +40 -146
  550. package/tools/corewire/service_goldens.json +650 -0
  551. package/tools/corewire/service_projection.zig +52 -0
  552. package/tools/corewire/service_templates.ts +14 -0
  553. package/tools/corewire/shim_rt.zig +9 -0
  554. package/tools/corewire/sidecar.zig +269 -1438
  555. 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
@@ -439,6 +439,8 @@ pub const db_key_base: u64 = 0x5453_4442_0000_0000;
439
439
  /// Dedicated raw-file stream key namespace ("TSFS").
440
440
  pub const file_stream_key_base: u64 = 0x5453_4653_0000_0000;
441
441
 
442
+ pub const global_shortcut_key: u64 = 0x5453_4753_0000_0000;
443
+
442
444
  /// The spawn wire record's "no line routing" tag sentinel (the wire
443
445
  /// format's shared constant).
444
446
  pub const spawn_no_line_tag: u8 = 0xFF;
@@ -457,8 +459,18 @@ pub const max_now_chain: usize = 64;
457
459
  pub const max_nows_per_cmd: usize = 16;
458
460
 
459
461
  pub fn TsCoreHost(comptime core: type) type {
462
+ return TsCoreHostWithRuntimeModel(core, false);
463
+ }
464
+
465
+ /// Compiled views use a stateless handle. Reference views retain the full
466
+ /// source model; commands, subscriptions and restoration share one bridge.
467
+ pub fn TsCoreHostWithRuntimeModel(comptime core: type, comptime compiled_model: bool) type {
468
+ const use_runtime_model = compiled_model and @hasDecl(core, "RuntimeModel");
460
469
  return struct {
461
- pub const Model = core.Model;
470
+ pub const Model = if (use_runtime_model) core.RuntimeModel else core.Model;
471
+ const initialModel = if (use_runtime_model) core.initialRuntimeModel else core.initialModel;
472
+ const updateModel = if (use_runtime_model) core.updateRuntimeModel else core.update;
473
+ const commitModel = if (use_runtime_model) core.commitRuntimeModel else core.commitModelRoot;
462
474
  pub const Msg = core.Msg;
463
475
  pub const Fx = runtime_effects.Effects(Msg);
464
476
 
@@ -473,9 +485,10 @@ pub fn TsCoreHost(comptime core: type) type {
473
485
 
474
486
  const msg_arms = @typeInfo(Msg).@"union".fields;
475
487
 
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;
488
+ const update_returns_cmd = @typeInfo(@TypeOf(updateModel)).@"fn".return_type.? != *const Model;
489
+ const init_returns_cmd = @typeInfo(@TypeOf(initialModel)).@"fn".return_type.? != *const Model;
478
490
  const has_subscriptions = @hasDecl(core, "subscriptions");
491
+ pub const environment_messages = if (@hasDecl(core, "envMsgs")) core.envMsgs else .{};
479
492
 
480
493
  /// One in-flight routed request: the wire key names it for
481
494
  /// replace/cancel, the tags route its terminal, and the table
@@ -514,6 +527,9 @@ pub fn TsCoreHost(comptime core: type) type {
514
527
  }
515
528
  };
516
529
 
530
+ const GlobalShortcutEntry = struct { used: bool = false, declared: bool = false, binding: platform.OwnedShortcut = .{}, tag: u8 = 0, pressed: bool = false };
531
+ const DeclaredShortcut = struct { shortcut: platform.Shortcut, tag: u8 };
532
+
517
533
  /// One in-flight named engine op (read_file / write_file /
518
534
  /// fetch / clip_read): same lifecycle as `RequestEntry` — the
519
535
  /// table index IS the engine key (minus `effect_key_base`),
@@ -525,6 +541,7 @@ pub fn TsCoreHost(comptime core: type) type {
525
541
  /// the engine's shared effect slots.
526
542
  const EffectEntry = struct {
527
543
  used: bool = false,
544
+ full_result: bool = false,
528
545
  dropped: bool = false,
529
546
  key_len: usize = 0,
530
547
  key: [max_wire_key_bytes]u8 = undefined,
@@ -541,6 +558,8 @@ pub fn TsCoreHost(comptime core: type) type {
541
558
  /// timer replaces in place under the same engine key).
542
559
  const DelayEntry = struct {
543
560
  used: bool = false,
561
+ full_result: bool = false,
562
+ mode: runtime_effects.TimerMode = .one_shot,
544
563
  key_len: usize = 0,
545
564
  key: [max_wire_key_bytes]u8 = undefined,
546
565
  tag: u8 = 0,
@@ -566,6 +585,7 @@ pub fn TsCoreHost(comptime core: type) type {
566
585
  exit_tag: u8 = 0,
567
586
  err_tag: u8 = 0,
568
587
  collect: bool = false,
588
+ complete_events: bool = false,
569
589
  /// Fetch lines are data records, so a cut or dropped line makes
570
590
  /// the eventual success terminal unusable. Spawn line mode keeps
571
591
  /// its existing best-effort contract.
@@ -672,6 +692,7 @@ pub fn TsCoreHost(comptime core: type) type {
672
692
  /// table.
673
693
  const PtyEntry = struct {
674
694
  used: bool = false,
695
+ bound: bool = false,
675
696
  key_len: usize = 0,
676
697
  key: [max_wire_key_bytes]u8 = undefined,
677
698
  event_tag: u8 = 0,
@@ -720,6 +741,10 @@ pub fn TsCoreHost(comptime core: type) type {
720
741
  var audio_captures: [runtime_effects.max_effect_channels]AudioCaptureEntry = @splat(.{});
721
742
  var ptys: [runtime_effects.max_effect_ptys]PtyEntry = @splat(.{});
722
743
  var dbs: [runtime_effects.max_db_effects]DbEntry = @splat(.{});
744
+ var global_shortcuts: [2 * platform.max_global_shortcuts]GlobalShortcutEntry = @splat(.{});
745
+ var global_shortcut_count: usize = 0;
746
+ var rejected_shortcuts: [platform.max_global_shortcuts]u64 = undefined;
747
+ var rejected_shortcut_count: usize = 0;
723
748
  /// The platform caches directory for URL image sources, the
724
749
  /// audio cache dir's twin (`setImageCacheDir` / `TsUiApp`'s
725
750
  /// `image_cache_dir`): bridge-side derivation of the
@@ -746,7 +771,24 @@ pub fn TsCoreHost(comptime core: type) type {
746
771
 
747
772
  /// A `now` record captured during the command walk, dispatched
748
773
  /// after the issuing cycle's frame reset.
749
- const PendingNow = struct { tag: u8, ms: i64 };
774
+ const ClipboardWriteEntry = struct {
775
+ used: bool = false,
776
+ key: [max_wire_key_bytes]u8 = undefined,
777
+ key_len: usize = 0,
778
+ tag: u8 = 0,
779
+ fn wireKey(self: *const ClipboardWriteEntry) []const u8 {
780
+ return self.key[0..self.key_len];
781
+ }
782
+ };
783
+ var clipboard_writes: [runtime_effects.max_effects]ClipboardWriteEntry = @splat(.{});
784
+ const clipboard_result_key_base: u64 = 0x5453_4352_0000_0000;
785
+
786
+ const PendingNow = union(enum) {
787
+ channel_source: struct { tag: u8, key: u64, state: runtime_effects.EffectChannelSourceState, bytes: [255]u8, len: u8 },
788
+ clock: struct { tag: u8, ms: i64 },
789
+ decimal_clock: struct { tag: u8, ms: i64 },
790
+ video: struct { tag: u8, snapshot: Fx.VideoSnapshot, key: [max_wire_key_bytes]u8, key_len: usize },
791
+ };
750
792
 
751
793
  // Bridge-refused dispatches (a spawn under a live wire key, an
752
794
  // image load or channel open under a duplicate live id/key, an
@@ -795,6 +837,7 @@ pub fn TsCoreHost(comptime core: type) type {
795
837
  effects_table = @splat(.{});
796
838
  delays = @splat(.{});
797
839
  streams = @splat(.{});
840
+ file_streams = @splat(.{});
798
841
  audio_entry = .{};
799
842
  video_entry = .{};
800
843
  images = @splat(.{});
@@ -802,12 +845,16 @@ pub fn TsCoreHost(comptime core: type) type {
802
845
  audio_captures = @splat(.{});
803
846
  ptys = @splat(.{});
804
847
  dbs = @splat(.{});
848
+ global_shortcuts = @splat(.{});
849
+ global_shortcut_count = 0;
850
+ rejected_shortcut_count = 0;
805
851
  clip_write_counter = 0;
852
+ clipboard_writes = @splat(.{});
806
853
  audio_cache_dir_len = 0;
807
854
  image_cache_dir_len = 0;
808
855
  swallow_next_dispatch = false;
809
- const initial = core.initialModel();
810
- model_root = core.commitModelRoot(if (comptime init_returns_cmd) initial.model else initial);
856
+ const initial = initialModel();
857
+ model_root = commitModel(if (comptime init_returns_cmd) initial.model else initial);
811
858
  core.rt.frameReset();
812
859
  }
813
860
 
@@ -826,18 +873,24 @@ pub fn TsCoreHost(comptime core: type) type {
826
873
  }
827
874
 
828
875
  /// The committed model root (valid until the next dispatch).
829
- pub fn model() *const Model {
876
+ pub fn runtimeModel() *const Model {
830
877
  return model_root;
831
878
  }
832
879
 
833
- /// Replace the committed core model from canonical snapshot bytes and
834
- /// refresh the host mirror. Generated external cores expose the inverse
880
+ /// Complete source state for diagnostics and replay. Compiled apps
881
+ /// decode only here; returned roots follow the shim snapshot lifetime.
882
+ pub fn model() *const core.Model {
883
+ return if (comptime use_runtime_model) core.snapshotModel() else model_root;
884
+ }
885
+
886
+ /// Replace the committed core model from canonical snapshot bytes.
887
+ /// Reference mode refreshes its mirror; compiled mode keeps its handle. Generated external cores expose the inverse
835
888
  /// of `modelSnapshot`; hand-written test cores intentionally do not.
836
889
  pub fn restoreSnapshot(snapshot: []const u8) void {
837
890
  if (comptime !@hasDecl(core, "restoreModel")) {
838
891
  @panic("ts core host: this core exposes no restoreModel entry - regenerate it with core ABI version 2");
839
892
  } else {
840
- model_root = core.restoreModel(snapshot);
893
+ model_root = if (comptime use_runtime_model) core.restoreRuntimeModel(snapshot) else core.restoreModel(snapshot);
841
894
  }
842
895
  }
843
896
 
@@ -926,6 +979,20 @@ pub fn TsCoreHost(comptime core: type) type {
926
979
  dispatchDepth(fx, msg, 0);
927
980
  }
928
981
 
982
+ /// Commit a pure retained-control observation at the UiApp sync
983
+ /// boundary. Effects and subscriptions belong to normal dispatch.
984
+ pub fn syncControls(msg: Msg) void {
985
+ if (comptime update_returns_cmd) {
986
+ const result = updateModel(model_root, msg);
987
+ if (result.cmd.len != 0) @panic("sliderStateMsg must produce a state-only update without commands");
988
+ model_root = commitModel(result.model);
989
+ } else {
990
+ model_root = commitModel(updateModel(model_root, msg));
991
+ }
992
+ // The enclosing dispatch may already hold a frame-backed message
993
+ // (for example exact frame clocks). It owns the scratch reset.
994
+ }
995
+
929
996
  /// Drain every queued effect completion into the core — the
930
997
  /// bridge-shaped mirror of `UiApp.drainEffects`' loop. Hosts
931
998
  /// that embed the core without a UiApp call this on wake/frame.
@@ -944,11 +1011,11 @@ pub fn TsCoreHost(comptime core: type) type {
944
1011
  @panic("ts core host: more than 64 chained Cmd.now dispatches from one event - update is requesting timestamps in a loop");
945
1012
  }
946
1013
  if (comptime update_returns_cmd) {
947
- const result = core.update(model_root, msg);
948
- model_root = core.commitModelRoot(result.model);
1014
+ const result = updateModel(model_root, msg);
1015
+ model_root = commitModel(result.model);
949
1016
  finishCycle(fx, result.cmd, depth);
950
1017
  } else {
951
- model_root = core.commitModelRoot(core.update(model_root, msg));
1018
+ model_root = commitModel(updateModel(model_root, msg));
952
1019
  finishCycle(fx, "", depth);
953
1020
  }
954
1021
  }
@@ -967,14 +1034,20 @@ pub fn TsCoreHost(comptime core: type) type {
967
1034
  reconcileSubscriptions(fx);
968
1035
  fx.flushDbSubscriptions();
969
1036
  core.rt.frameReset();
970
- for (nows[0..now_count]) |pending| {
971
- dispatchDepth(fx, msgFromTagNumber(pending.tag, @floatFromInt(pending.ms)), depth + 1);
1037
+ for (nows[0..now_count]) |*pending| {
1038
+ const reply = switch (pending.*) {
1039
+ .channel_source => |*source| msgFromTagChannelSource(source.tag, .{ .key = source.key, .state = source.state, .bytes = source.bytes[0..source.len] }),
1040
+ .clock => |clock| msgFromTagNumber(clock.tag, @floatFromInt(clock.ms)),
1041
+ .decimal_clock => |clock| msgFromTagBytes(clock.tag, decimalFrame(clock.ms)),
1042
+ .video => |*video| msgFromVideoSnapshot(video.tag, video.snapshot, video.key[0..video.key_len]),
1043
+ };
1044
+ dispatchDepth(fx, reply, depth + 1);
972
1045
  }
973
1046
  }
974
1047
 
975
1048
  // ------------------------------------------------- command walk
976
1049
 
977
- /// Walk one command value (v3 wire format; batch is plain
1050
+ /// Walk one command value (generation 10; batch is plain
978
1051
  /// concatenation, the empty slice is `Cmd.none`).
979
1052
  fn runCmd(
980
1053
  fx: *Fx,
@@ -1000,7 +1073,7 @@ pub fn TsCoreHost(comptime core: type) type {
1000
1073
  }
1001
1074
  // The journaled clock read (replay pops the same
1002
1075
  // value), captured in record order.
1003
- nows[now_count.*] = .{ .tag = tag, .ms = fx.wallMs() };
1076
+ nows[now_count.*] = .{ .clock = .{ .tag = tag, .ms = fx.wallMs() } };
1004
1077
  now_count.* += 1;
1005
1078
  },
1006
1079
  // host [op][name_len][name][argc][argc * f64 LE]
@@ -1033,6 +1106,40 @@ pub fn TsCoreHost(comptime core: type) type {
1033
1106
  const key = takeShortBytes(cmd, &at);
1034
1107
  cancelWireKey(fx, key);
1035
1108
  },
1109
+ // Complete file terminals and exact journaled clocks.
1110
+ 0x37, 0x38, 0x3e, 0x3f => {
1111
+ const key = takeShortBytes(cmd, &at);
1112
+ const tag = takeByte(cmd, &at);
1113
+ const file_path = takeLongBytes(cmd, &at);
1114
+ const bytes = if (op == 0x38 or op == 0x3f) takeLongBytes(cmd, &at) else "";
1115
+ const file_op: runtime_effects.EffectFileOp = if (op == 0x38 or op == 0x3f) .write else .read;
1116
+ const index = allocEffectEntryWithFilePolicy(fx, .{ .key = key, .ok_tag = tag, .err_tag = tag }, file_op, op == 0x37 or op == 0x38) orelse continue;
1117
+ 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 });
1118
+ },
1119
+ 0x39 => {
1120
+ const tag = takeByte(cmd, &at);
1121
+ if (now_count.* >= max_nows_per_cmd) @panic("ts core host: too many clock replies");
1122
+ nows[now_count.*] = .{ .decimal_clock = .{ .tag = tag, .ms = fx.wallMs() } };
1123
+ now_count.* += 1;
1124
+ },
1125
+ 0x40 => {
1126
+ const key = takeShortBytes(cmd, &at);
1127
+ const mode = takeByte(cmd, &at);
1128
+ if (mode > 1) @panic("ts core host: invalid timer mode");
1129
+ const decimal = takeLongBytes(cmd, &at);
1130
+ const tag = takeByte(cmd, &at);
1131
+ const exact = parseExactTimerInterval(decimal);
1132
+ const ms: f64 = if (exact) |value| @floatFromInt(value) else 0;
1133
+ armResultTimer(fx, key, ms, tag, if (mode == 1) .repeating else .one_shot, true);
1134
+ },
1135
+ 0x3A => {
1136
+ const key = takeShortBytes(cmd, &at);
1137
+ const mode = takeByte(cmd, &at);
1138
+ if (mode > 1) @panic("ts core host: invalid timer mode");
1139
+ const ms: f64 = @bitCast(std.mem.readInt(u64, takeBytes(cmd, &at, 8)[0..8], .little));
1140
+ const tag = takeByte(cmd, &at);
1141
+ armResultTimer(fx, key, ms, tag, if (mode == 1) .repeating else .one_shot, false);
1142
+ },
1036
1143
  // read_file [op][key_len][key][ok][err][path_len u32 LE][path]
1037
1144
  0x07 => {
1038
1145
  const head = takeRoutedHead(cmd, &at);
@@ -1124,7 +1231,7 @@ pub fn TsCoreHost(comptime core: type) type {
1124
1231
  // otherwise find this named op first and leave the
1125
1232
  // stream running. The live stream owns the key, so
1126
1233
  // reject the newcomer through its own err arm.
1127
- if (head.key.len > 0 and (findStream(head.key) != null or fileStreamOccupiesKey(head.key))) {
1234
+ if (head.key.len > 0 and (findStream(head.key) != null or reservedWireKeyOccupied(head.key))) {
1128
1235
  fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1129
1236
  } else {
1130
1237
  const effect_index = allocEffectEntry(fx, head) orelse continue;
@@ -1154,6 +1261,57 @@ pub fn TsCoreHost(comptime core: type) type {
1154
1261
  });
1155
1262
  clip_write_counter +%= 1;
1156
1263
  },
1264
+ // Complete spawn records; the legacy opcode remains unchanged.
1265
+ 0x46 => {
1266
+ const key = parseExactUnsigned(takeLongBytes(cmd, &at)) orelse
1267
+ @panic("ts core host: invalid exact subprocess identity");
1268
+ const line_tag = takeByte(cmd, &at);
1269
+ const exit_tag = takeByte(cmd, &at);
1270
+ const mode = takeByte(cmd, &at);
1271
+ const argc = takeByte(cmd, &at);
1272
+ if (mode > 1) @panic("ts core host: invalid exact subprocess output mode");
1273
+ var argv: [runtime_effects.max_effect_argv][]const u8 = undefined;
1274
+ for (0..argc) |i| {
1275
+ const arg = takeLongBytes(cmd, &at);
1276
+ if (i < argv.len) argv[i] = arg;
1277
+ }
1278
+ const stdin = takeLongBytes(cmd, &at);
1279
+ // An over-capacity argv is a native rejected request.
1280
+ const retained = if (argc <= argv.len) argv[0..argc] else &.{};
1281
+ issueSpawnExact(fx, key, line_tag, exit_tag, mode == 1, retained, stdin);
1282
+ },
1283
+ 0x47 => fx.cancel(parseExactUnsigned(takeLongBytes(cmd, &at)) orelse
1284
+ @panic("ts core host: invalid exact cancellation identity")),
1285
+ 0x33 => {
1286
+ const key = takeShortBytes(cmd, &at);
1287
+ const line_tag = takeByte(cmd, &at);
1288
+ const exit_tag = takeByte(cmd, &at);
1289
+ const mode = takeByte(cmd, &at);
1290
+ const argc = takeByte(cmd, &at);
1291
+ if (mode > 1 or argc == 0 or argc > runtime_effects.max_effect_argv) @panic("ts core host: invalid complete spawn wire record");
1292
+ var argv: [runtime_effects.max_effect_argv][]const u8 = undefined;
1293
+ for (0..argc) |i| argv[i] = takeLongBytes(cmd, &at);
1294
+ const stdin = takeLongBytes(cmd, &at);
1295
+ 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);
1296
+ },
1297
+ // Routed write completion, including rejection and cancellation.
1298
+ 0x34 => {
1299
+ const key = takeShortBytes(cmd, &at);
1300
+ const tag = takeByte(cmd, &at);
1301
+ const bytes = takeLongBytes(cmd, &at);
1302
+ issueClipboardWrite(fx, key, tag, bytes);
1303
+ },
1304
+ // Capture now; reply after resetting the ABI result arena, in
1305
+ // command order like Cmd.now. No intervening host turn occurs.
1306
+ 0x35 => {
1307
+ const tag = takeByte(cmd, &at);
1308
+ if (now_count.* >= max_nows_per_cmd) @panic("ts core host: over 16 immediate capability replies in one command");
1309
+ const snapshot = fx.videoSnapshot();
1310
+ const key = if (video_entry.used and fx.videoOwnerToken() == video_entry.token) video_entry.wireKey() else "";
1311
+ nows[now_count.*] = .{ .video = .{ .tag = tag, .snapshot = snapshot, .key = undefined, .key_len = key.len } };
1312
+ @memcpy(nows[now_count.*].video.key[0..key.len], key);
1313
+ now_count.* += 1;
1314
+ },
1157
1315
  // clip_read [op][key_len][key][ok][err]
1158
1316
  0x0B => {
1159
1317
  const head = takeRoutedHead(cmd, &at);
@@ -1169,10 +1327,12 @@ pub fn TsCoreHost(comptime core: type) type {
1169
1327
  const after_bits = takeBytes(cmd, &at, 8);
1170
1328
  const after_ms: f64 = @bitCast(std.mem.readInt(u64, after_bits[0..8], .little));
1171
1329
  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");
1330
+ if (comptime !@hasDecl(core, "nativeTimerPolicy")) {
1331
+ if (!(after_ms >= 1) or !(after_ms <= 31_536_000_000.0)) {
1332
+ // Same bound as Sub.timer: the lower rejects NaN,
1333
+ // the upper (one year) keeps ns conversion in range.
1334
+ @panic("ts core host: Cmd.delay interval must be between 1ms and one year");
1335
+ }
1176
1336
  }
1177
1337
  armDelay(fx, key, after_ms, tag);
1178
1338
  },
@@ -1208,27 +1368,7 @@ pub fn TsCoreHost(comptime core: type) type {
1208
1368
  const cache_path = takeLongBytes(cmd, &at);
1209
1369
  const expected_bits = takeBytes(cmd, &at, 8);
1210
1370
  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
- });
1371
+ issueAudioPlay(fx, key, event_tag, audio_path, url, cache_path, expected);
1232
1372
  },
1233
1373
  // audio_ctl [op][key_len][key][verb u8][value f64 LE]
1234
1374
  0x0F => {
@@ -1238,13 +1378,72 @@ pub fn TsCoreHost(comptime core: type) type {
1238
1378
  const value: f64 = @bitCast(std.mem.readInt(u64, value_bits[0..8], .little));
1239
1379
  runAudioCtl(fx, key, verb, value);
1240
1380
  },
1381
+ // Exact audio: decimal key, load-owned route, source and cache facts.
1382
+ 0x42 => {
1383
+ const key = parseExactUnsigned(takeLongBytes(cmd, &at)) orelse
1384
+ @panic("ts core host: invalid exact audio identity");
1385
+ const tag = takeByte(cmd, &at);
1386
+ const audio_path = takeLongBytes(cmd, &at);
1387
+ const url = takeLongBytes(cmd, &at);
1388
+ const cache_path = takeLongBytes(cmd, &at);
1389
+ const cache_dir = takeLongBytes(cmd, &at);
1390
+ const expected_bits = takeBytes(cmd, &at, 8);
1391
+ const expected: f64 = @bitCast(std.mem.readInt(u64, expected_bits[0..8], .little));
1392
+ issueAudioPlayExact(fx, key, tag, audio_path, url, cache_path, cache_dir, expected);
1393
+ },
1394
+ // Single-player transport. Seek retains the native u64 range.
1395
+ 0x43 => switch (takeByte(cmd, &at)) {
1396
+ 0 => fx.pauseAudio(),
1397
+ 1 => fx.resumeAudio(),
1398
+ 2 => {
1399
+ audio_entry.used = false;
1400
+ fx.stopAudio();
1401
+ },
1402
+ 3 => fx.seekAudio(parseExactUnsigned(takeLongBytes(cmd, &at)) orelse
1403
+ @panic("ts core host: invalid exact audio seek position")),
1404
+ 4 => {
1405
+ const bits = takeBytes(cmd, &at, 8);
1406
+ const value: f64 = @bitCast(std.mem.readInt(u64, bits[0..8], .little));
1407
+ if (!std.math.isFinite(value) or @abs(value) > std.math.floatMax(f32))
1408
+ @panic("ts core host: invalid audio volume");
1409
+ fx.setAudioVolume(@floatCast(value));
1410
+ },
1411
+ else => @panic("ts core host: invalid audio transport verb"),
1412
+ },
1241
1413
  // window_show [op][label_len][label]
1242
1414
  0x10 => {
1243
1415
  const label = takeShortBytes(cmd, &at);
1244
1416
  fx.showWindow(label);
1245
1417
  },
1418
+ // Native close/minimize preserve the ordinary window policy.
1419
+ 0x44 => fx.closeWindow(takeShortBytes(cmd, &at)),
1420
+ 0x45 => fx.minimizeWindow(takeShortBytes(cmd, &at)),
1246
1421
  // quit_app [op]
1247
1422
  0x11 => fx.quitApp(),
1423
+ // Lossless identity: two unsigned little-endian words.
1424
+ 0x3b => {
1425
+ const id_bytes = takeBytes(cmd, &at, 8);
1426
+ const id = std.mem.readInt(u64, id_bytes[0..8], .little);
1427
+ const tag = takeByte(cmd, &at);
1428
+ const image_path = takeLongBytes(cmd, &at);
1429
+ const url = takeLongBytes(cmd, &at);
1430
+ const cache = takeLongBytes(cmd, &at);
1431
+ const expected_bytes = takeBytes(cmd, &at, 8);
1432
+ const expected: f64 = @bitCast(std.mem.readInt(u64, expected_bytes[0..8], .little));
1433
+ issueImageLoadWords(fx, id, tag, image_path, url, cache, expected);
1434
+ },
1435
+ 0x3c, 0x3d => {
1436
+ const id_bytes = takeBytes(cmd, &at, 8);
1437
+ const id = std.mem.readInt(u64, id_bytes[0..8], .little);
1438
+ const table: []const ImageEntry = if (op == 0x3c) &images else &.{};
1439
+ const plan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
1440
+ compiledMediaIdentityPlan(0, 4, id, 0, 0, .microphone, 0, 0, 0, table, true)
1441
+ else
1442
+ MediaPlan{ .valid = imageWordIdValid(id), .slot = findImage(id), .key = id, .tag = 0, .retire = false, .expected_bytes = 0, .source = .microphone, .sample_rate = 0, .capture_channels = 0 };
1443
+ if (op == 0x3c) {
1444
+ if (plan.valid and plan.slot != null) fx.cancelImage(plan.key);
1445
+ } else if (plan.valid) _ = fx.unregisterImage(plan.key);
1446
+ },
1248
1447
  // image_load [op][id f64 LE][event_tag]
1249
1448
  // [path_len u32 LE][path][url_len u32 LE][url]
1250
1449
  // [cache_len u32 LE][cache][expected f64 LE]
@@ -1279,6 +1478,26 @@ pub fn TsCoreHost(comptime core: type) type {
1279
1478
  const max_pending = takeByte(cmd, &at);
1280
1479
  _ = issueChannelOpen(fx, key_value, event_tag, max_pending);
1281
1480
  },
1481
+ // channel_open_source [op][key f64 LE][event_tag][started_tag]
1482
+ // [max_pending][source short][payload long]
1483
+ 0x41 => {
1484
+ const key_bits = takeBytes(cmd, &at, 8);
1485
+ const key_value: f64 = @bitCast(std.mem.readInt(u64, key_bits[0..8], .little));
1486
+ const event_tag = takeByte(cmd, &at);
1487
+ const started_tag = takeByte(cmd, &at);
1488
+ const max_pending = takeByte(cmd, &at);
1489
+ const name = takeShortBytes(cmd, &at);
1490
+ const payload = takeLongBytes(cmd, &at);
1491
+ if (name.len == 0 or payload.len > runtime_effects.max_channel_source_payload or now_count.* >= max_nows_per_cmd)
1492
+ @panic("ts core host: invalid channel source command");
1493
+ const accepted = issueChannelOpen(fx, key_value, event_tag, max_pending);
1494
+ 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;
1495
+ const result = fx.startChannelSource(key, if (accepted) fx.channelHandle(key) else null, name, payload);
1496
+ const pending = &nows[now_count.*];
1497
+ pending.* = .{ .channel_source = .{ .tag = started_tag, .key = key, .state = result.state, .bytes = undefined, .len = @intCast(result.bytes.len) } };
1498
+ @memcpy(pending.channel_source.bytes[0..result.bytes.len], result.bytes);
1499
+ now_count.* += 1;
1500
+ },
1282
1501
  // channel_close [op][key f64 LE]
1283
1502
  0x16 => {
1284
1503
  const key_bits = takeBytes(cmd, &at, 8);
@@ -1296,58 +1515,7 @@ pub fn TsCoreHost(comptime core: type) type {
1296
1515
  const video_path = takeLongBytes(cmd, &at);
1297
1516
  const url = takeLongBytes(cmd, &at);
1298
1517
  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
- }
1518
+ issueVideoLoad(fx, key, event_tag, surface, video_path, url, flags);
1351
1519
  },
1352
1520
  // video_ctl [op][key_len][key][verb u8][value f64 LE]
1353
1521
  0x18 => {
@@ -1720,22 +1888,44 @@ pub fn TsCoreHost(comptime core: type) type {
1720
1888
  /// flight either (a dropped entry holds its slot only until
1721
1889
  /// its `.cancelled` terminal drains).
1722
1890
  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"));
1891
+ return allocEffectEntryWithFileResult(fx, head, null);
1892
+ }
1893
+ fn allocEffectEntryWithFileResult(fx: *Fx, head: RoutedHead, file_op: ?runtime_effects.EffectFileOp) ?u64 {
1894
+ return allocEffectEntryWithFilePolicy(fx, head, file_op, true);
1895
+ }
1896
+ fn allocEffectEntryWithFilePolicy(fx: *Fx, head: RoutedHead, file_op: ?runtime_effects.EffectFileOp, replace: bool) ?u64 {
1897
+ 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)));
1898
+ const plan = if (comptime @hasDecl(core, "nativeEffectPolicy")) compiledEffectDeclaration(head, blocked) else blk: {
1899
+ break :blk EffectPlan{
1900
+ .admitted = !blocked,
1901
+ .slot = if (blocked) null else freeEffectIndex(),
1902
+ .drop = if (blocked or head.key.len == 0) null else findEffect(head.key),
1903
+ .ok_tag = head.ok_tag,
1904
+ .err_tag = head.err_tag,
1905
+ };
1906
+ };
1907
+ if (!plan.admitted) {
1908
+ if (file_op) |operation| stageFileRejected(fx, head, operation) else fx.stageLoopMsg(msgFromTagStaticBytes(plan.err_tag, "rejected"));
1909
+ return null;
1910
+ }
1911
+ // A dropped predecessor remains occupied until its terminal drains.
1912
+ // Preserve the reference order even when no free slot is available.
1913
+ if (plan.drop) |existing| dropEffectEntry(fx, existing);
1914
+ const index = plan.slot orelse {
1915
+ if (file_op) |operation| {
1916
+ stageFileRejected(fx, head, operation);
1726
1917
  return null;
1727
1918
  }
1728
- if (findEffect(head.key)) |existing| dropEffectEntry(fx, existing);
1729
- }
1730
- const index = freeEffectIndex() orelse
1731
1919
  @panic("ts core host: more than 16 named engine ops in flight - the op table mirrors the engine's max_effects slots");
1920
+ };
1732
1921
  const entry = &effects_table[index];
1733
1922
  entry.used = true;
1734
1923
  entry.dropped = false;
1924
+ entry.full_result = file_op != null;
1735
1925
  entry.key_len = head.key.len;
1736
1926
  @memcpy(entry.key[0..head.key.len], head.key);
1737
- entry.ok_tag = head.ok_tag;
1738
- entry.err_tag = head.err_tag;
1927
+ entry.ok_tag = plan.ok_tag;
1928
+ entry.err_tag = plan.err_tag;
1739
1929
  return index;
1740
1930
  }
1741
1931
 
@@ -1745,12 +1935,13 @@ pub fn TsCoreHost(comptime core: type) type {
1745
1935
  /// the entry through the result callback, which swallows it.
1746
1936
  fn dropEffectEntry(fx: *Fx, index: usize) void {
1747
1937
  effects_table[index].dropped = true;
1748
- fx.cancel(effect_key_base + index);
1938
+ fx.cancelNonImage(effect_key_base + index);
1749
1939
  }
1750
1940
 
1751
1941
  /// A dropped entry's key is dead to lookup: reissuing it is a
1752
1942
  /// fresh effect, and cancel aimed at it finds nothing.
1753
1943
  fn findEffect(key: []const u8) ?usize {
1944
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) return compiledEffectLookup(key);
1754
1945
  for (&effects_table, 0..) |*entry, index| {
1755
1946
  if (entry.used and !entry.dropped and std.mem.eql(u8, entry.wireKey(), key)) return index;
1756
1947
  }
@@ -1764,6 +1955,67 @@ pub fn TsCoreHost(comptime core: type) type {
1764
1955
  return null;
1765
1956
  }
1766
1957
 
1958
+ const EffectPlan = struct { admitted: bool, slot: ?usize, drop: ?usize, ok_tag: u8, err_tag: u8 };
1959
+ const max_effect_policy_bytes = 5 + max_wire_key_bytes + 16 * (5 + max_wire_key_bytes);
1960
+
1961
+ fn writeEffectTable(request: []u8, start: usize) usize {
1962
+ var at = start;
1963
+ for (&effects_table) |*entry| {
1964
+ request[at] = @intFromBool(entry.used);
1965
+ request[at + 1] = @intFromBool(entry.dropped);
1966
+ request[at + 2] = @intCast(entry.key_len);
1967
+ @memcpy(request[at + 3 ..][0..entry.key_len], entry.wireKey());
1968
+ at += 3 + entry.key_len;
1969
+ request[at] = entry.ok_tag;
1970
+ request[at + 1] = entry.err_tag;
1971
+ at += 2;
1972
+ }
1973
+ return at;
1974
+ }
1975
+
1976
+ fn compiledEffectDeclaration(head: RoutedHead, blocked: bool) EffectPlan {
1977
+ var request: [max_effect_policy_bytes]u8 = undefined;
1978
+ request[0] = 0;
1979
+ request[1] = @intCast(head.key.len);
1980
+ @memcpy(request[2..][0..head.key.len], head.key);
1981
+ const at = 2 + head.key.len;
1982
+ request[at] = @intFromBool(blocked);
1983
+ request[at + 1] = head.ok_tag;
1984
+ request[at + 2] = head.err_tag;
1985
+ const end = writeEffectTable(&request, at + 3);
1986
+ var result: [5]u8 = undefined;
1987
+ if (core.nativeEffectPolicy(request[0..end], &result) != result.len or result[0] > 1)
1988
+ @panic("ts core host: invalid compiled effect declaration result");
1989
+ const slot: ?usize = if (result[1] == 255) null else result[1];
1990
+ const drop: ?usize = if (result[2] == 255) null else result[2];
1991
+ if (slot) |index| {
1992
+ if (index >= effects_table.len or effects_table[index].used)
1993
+ @panic("ts core host: invalid compiled effect allocation slot");
1994
+ }
1995
+ if (drop) |index| {
1996
+ if (index >= effects_table.len or !effects_table[index].used or effects_table[index].dropped)
1997
+ @panic("ts core host: invalid compiled effect predecessor slot");
1998
+ }
1999
+ if (result[0] == 0 and (slot != null or drop != null))
2000
+ @panic("ts core host: rejected effect declaration contains live slots");
2001
+ return .{ .admitted = result[0] == 1, .slot = slot, .drop = drop, .ok_tag = result[3], .err_tag = result[4] };
2002
+ }
2003
+
2004
+ fn compiledEffectLookup(key: []const u8) ?usize {
2005
+ var request: [max_effect_policy_bytes]u8 = undefined;
2006
+ request[0] = 1;
2007
+ request[1] = @intCast(key.len);
2008
+ @memcpy(request[2..][0..key.len], key);
2009
+ const end = writeEffectTable(&request, 2 + key.len);
2010
+ var result: [1]u8 = undefined;
2011
+ if (core.nativeEffectPolicy(request[0..end], &result) != result.len)
2012
+ @panic("ts core host: invalid compiled effect lookup result");
2013
+ if (result[0] == 255) return null;
2014
+ if (result[0] >= effects_table.len or !effects_table[result[0]].used or effects_table[result[0]].dropped)
2015
+ @panic("ts core host: invalid compiled effect lookup slot");
2016
+ return result[0];
2017
+ }
2018
+
1767
2019
  /// Arm (or re-arm) a one-shot delay. A live wire key reuses its
1768
2020
  /// slot: the engine timer replaces in place under the same
1769
2021
  /// engine key and restarts from now — the debounce discipline.
@@ -1771,28 +2023,33 @@ pub fn TsCoreHost(comptime core: type) type {
1771
2023
  // A delay has no err arm. Preserve an incumbent file stream and
1772
2024
  // fail closed instead of creating a second owner that Cmd.cancel
1773
2025
  // 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");
2026
+ const plan: DelayPlan = if (comptime @hasDecl(core, "nativeTimerPolicy")) compiledDelayDeclaration(key, after_ms, tag, reservedWireKeyOccupiedExcept(key, .delay), false) orelse return else blk: {
2027
+ if (reservedWireKeyOccupiedExcept(key, .delay)) return;
2028
+ const index = if (key.len > 0) findDelay(key) orelse freeDelayIndex() else freeDelayIndex();
2029
+ break :blk .{
2030
+ .slot = index orelse @panic("ts core host: more than 16 armed delays - the delay table mirrors the engine's max_effect_timers"),
2031
+ .tag = tag,
2032
+ .interval_ms = intervalMs(after_ms),
2033
+ };
1781
2034
  };
2035
+ const index = plan.slot;
1782
2036
  const entry = &delays[index];
1783
2037
  entry.used = true;
1784
2038
  entry.key_len = key.len;
1785
2039
  @memcpy(entry.key[0..key.len], key);
1786
- entry.tag = tag;
2040
+ entry.tag = plan.tag;
2041
+ entry.full_result = false;
2042
+ entry.mode = .one_shot;
1787
2043
  fx.startTimer(.{
1788
2044
  .key = delay_key_base + index,
1789
- .interval_ms = intervalMs(after_ms),
2045
+ .interval_ms = plan.interval_ms,
1790
2046
  .mode = .one_shot,
1791
2047
  .on_fire = delayFireMsg,
1792
2048
  });
1793
2049
  }
1794
2050
 
1795
2051
  fn findDelay(key: []const u8) ?usize {
2052
+ if (comptime @hasDecl(core, "nativeTimerPolicy")) return compiledDelayLookup(key);
1796
2053
  for (&delays, 0..) |*entry, index| {
1797
2054
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
1798
2055
  }
@@ -1808,7 +2065,49 @@ pub fn TsCoreHost(comptime core: type) type {
1808
2065
 
1809
2066
  // ------------------------------------------- spawn / fetch streams
1810
2067
 
1811
- const SpawnHead = struct { key: []const u8, line_tag: u8, exit_tag: u8, err_tag: u8 };
2068
+ const SpawnHead = struct { key: []const u8, line_tag: u8, exit_tag: u8, err_tag: u8, complete_events: bool = false };
2069
+
2070
+ /// The engine copies the request and owns admission, pending routes,
2071
+ /// cancellation and lifetime. Per-arm callback thunks retain the route
2072
+ /// of each request, including refusals under an already occupied key.
2073
+ fn issueSpawnExact(fx: *Fx, key: u64, line_tag: u8, exit_tag: u8, collect: bool, argv: []const []const u8, stdin: []const u8) void {
2074
+ inline for (msg_arms, 0..) |arm, index| {
2075
+ if (exit_tag == index) {
2076
+ if (comptime exactSpawnArmShape(arm.type, false)) {
2077
+ const Exit = struct {
2078
+ fn message(exit: runtime_effects.EffectExit) Msg {
2079
+ return msgFromSpawnExit(index, exit, decimalFrame(exit.key));
2080
+ }
2081
+ };
2082
+ var options: Fx.SpawnOptions = .{ .key = key, .argv = argv,
2083
+ .stdin = if (stdin.len > 0) stdin else null,
2084
+ .output = if (collect) .collect else .lines, .on_exit = Exit.message };
2085
+ if (line_tag == spawn_no_line_tag) {
2086
+ fx.spawn(options);
2087
+ return;
2088
+ }
2089
+ inline for (msg_arms, 0..) |line_arm, line_index| {
2090
+ if (line_tag == line_index) {
2091
+ if (comptime exactSpawnArmShape(line_arm.type, true)) {
2092
+ const Line = struct {
2093
+ fn message(line: runtime_effects.EffectLine) Msg {
2094
+ return msgFromSpawnLine(line_index, line, decimalFrame(line.key));
2095
+ }
2096
+ };
2097
+ options.on_line = Line.message;
2098
+ fx.spawn(options);
2099
+ return;
2100
+ }
2101
+ @panic("ts core host: incompatible exact subprocess line arm");
2102
+ }
2103
+ }
2104
+ @panic("ts core host: invalid exact subprocess line tag");
2105
+ }
2106
+ @panic("ts core host: incompatible exact subprocess terminal arm");
2107
+ }
2108
+ }
2109
+ @panic("ts core host: invalid exact subprocess terminal tag");
2110
+ }
1812
2111
 
1813
2112
  /// Open a spawn stream: claim a non-retiring stream entry (the
1814
2113
  /// keyed-effect discipline's ONE exception — a live wire key
@@ -1825,19 +2124,18 @@ pub fn TsCoreHost(comptime core: type) type {
1825
2124
  argv: []const []const u8,
1826
2125
  stdin: []const u8,
1827
2126
  ) 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"));
2127
+ const index = if (comptime @hasDecl(core, "nativeStreamPolicy")) compiledStreamAdmission(head.key, false) else blk: {
2128
+ if (head.key.len > 0 and (findStream(head.key) != null or reservedWireKeyOccupied(head.key))) break :blk null;
2129
+ break :blk freeStreamIndex();
2130
+ };
2131
+ const slot = index orelse {
2132
+ fx.stageLoopMsg(if (head.complete_events)
2133
+ msgFromSpawnExit(head.exit_tag, .{ .key = 0, .reason = .rejected }, fx.stageLoopKey(head.key))
2134
+ else
2135
+ msgFromTagStaticBytes(head.err_tag, "rejected"));
1838
2136
  return;
1839
2137
  };
1840
- const entry = &streams[index];
2138
+ const entry = &streams[slot];
1841
2139
  entry.used = true;
1842
2140
  entry.key_len = head.key.len;
1843
2141
  @memcpy(entry.key[0..head.key.len], head.key);
@@ -1845,10 +2143,11 @@ pub fn TsCoreHost(comptime core: type) type {
1845
2143
  entry.exit_tag = head.exit_tag;
1846
2144
  entry.err_tag = head.err_tag;
1847
2145
  entry.collect = collect;
2146
+ entry.complete_events = head.complete_events;
1848
2147
  entry.fetch = false;
1849
2148
  entry.damaged = false;
1850
2149
  fx.spawn(.{
1851
- .key = spawn_key_base + index,
2150
+ .key = spawn_key_base + slot,
1852
2151
  .argv = argv,
1853
2152
  .stdin = if (stdin.len > 0) stdin else null,
1854
2153
  .output = if (collect) .collect else .lines,
@@ -1871,17 +2170,15 @@ pub fn TsCoreHost(comptime core: type) type {
1871
2170
  /// replacing a source that has already delivered lines would splice
1872
2171
  /// two HTTP responses into one app-owned stream.
1873
2172
  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 {
2173
+ const index = if (comptime @hasDecl(core, "nativeStreamPolicy")) compiledStreamAdmission(head.key, true) else blk: {
2174
+ if (head.key.len > 0 and (findStream(head.key) != null or findEffect(head.key) != null or reservedWireKeyOccupied(head.key))) break :blk null;
2175
+ break :blk freeStreamIndex();
2176
+ };
2177
+ const slot = index orelse {
1881
2178
  fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1882
2179
  return;
1883
2180
  };
1884
- const entry = &streams[index];
2181
+ const entry = &streams[slot];
1885
2182
  entry.used = true;
1886
2183
  entry.key_len = head.key.len;
1887
2184
  @memcpy(entry.key[0..head.key.len], head.key);
@@ -1890,9 +2187,10 @@ pub fn TsCoreHost(comptime core: type) type {
1890
2187
  entry.err_tag = head.err_tag;
1891
2188
  entry.collect = false;
1892
2189
  entry.fetch = true;
2190
+ entry.complete_events = false;
1893
2191
  entry.damaged = false;
1894
2192
  fx.fetch(.{
1895
- .key = spawn_key_base + index,
2193
+ .key = spawn_key_base + slot,
1896
2194
  .method = options.method,
1897
2195
  .url = options.url,
1898
2196
  .headers = options.headers,
@@ -1906,6 +2204,7 @@ pub fn TsCoreHost(comptime core: type) type {
1906
2204
  }
1907
2205
 
1908
2206
  fn findStream(key: []const u8) ?usize {
2207
+ if (comptime @hasDecl(core, "nativeStreamPolicy")) return compiledStreamLookup(key);
1909
2208
  for (&streams, 0..) |*entry, index| {
1910
2209
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
1911
2210
  }
@@ -1919,15 +2218,118 @@ pub fn TsCoreHost(comptime core: type) type {
1919
2218
  return null;
1920
2219
  }
1921
2220
 
2221
+ const max_stream_policy_bytes = 5 + max_wire_key_bytes + runtime_effects.max_effects * (2 + max_wire_key_bytes);
2222
+
2223
+ fn appendStreamTable(request: []u8, start: usize) usize {
2224
+ var at = start;
2225
+ for (streams) |entry| {
2226
+ request[at] = @intFromBool(entry.used);
2227
+ request[at + 1] = @intCast(entry.key_len);
2228
+ at += 2;
2229
+ @memcpy(request[at..][0..entry.key_len], entry.wireKey());
2230
+ at += entry.key_len;
2231
+ }
2232
+ return at;
2233
+ }
2234
+
2235
+ fn compiledStreamSlot(request: []const u8) ?usize {
2236
+ var result: [1]u8 = undefined;
2237
+ if (core.nativeStreamPolicy(request, &result) != result.len) @panic("ts core host: invalid compiled stream slot result");
2238
+ if (result[0] == 255) return null;
2239
+ if (result[0] >= streams.len) @panic("ts core host: compiled stream slot outside table");
2240
+ return result[0];
2241
+ }
2242
+
2243
+ fn compiledStreamAdmission(key: []const u8, fetch: bool) ?usize {
2244
+ var request: [max_stream_policy_bytes]u8 = undefined;
2245
+ request[0] = 0;
2246
+ request[1] = @intFromBool(fetch);
2247
+ request[2] = @intFromBool(reservedWireKeyOccupied(key));
2248
+ request[3] = @intFromBool(fetch and key.len > 0 and findEffect(key) != null);
2249
+ request[4] = @intCast(key.len);
2250
+ @memcpy(request[5..][0..key.len], key);
2251
+ const end = appendStreamTable(&request, 5 + key.len);
2252
+ const slot = compiledStreamSlot(request[0..end]) orelse return null;
2253
+ if (streams[slot].used) @panic("ts core host: compiled stream admission selected occupied slot");
2254
+ return slot;
2255
+ }
2256
+
2257
+ fn compiledStreamLookup(key: []const u8) ?usize {
2258
+ var request: [max_stream_policy_bytes]u8 = undefined;
2259
+ request[0] = 1;
2260
+ request[1] = @intCast(key.len);
2261
+ @memcpy(request[2..][0..key.len], key);
2262
+ const end = appendStreamTable(&request, 2 + key.len);
2263
+ const slot = compiledStreamSlot(request[0..end]) orelse return null;
2264
+ if (!streams[slot].used) @panic("ts core host: compiled stream lookup selected unused slot");
2265
+ return slot;
2266
+ }
2267
+
2268
+ const StreamCompletion = struct { tag: u8, shape: enum { bytes, number, number_bytes }, damaged: bool, retire: bool, truncated: bool };
2269
+
2270
+ fn compiledStreamCompletion(request: []const u8) StreamCompletion {
2271
+ var result: [5]u8 = undefined;
2272
+ if (core.nativeStreamPolicy(request, &result) != result.len or result[1] > 2 or result[2] > 1 or result[3] > 1 or result[4] > 1)
2273
+ @panic("ts core host: invalid compiled stream completion result");
2274
+ return .{ .tag = result[0], .shape = @enumFromInt(result[1]), .damaged = result[2] != 0, .retire = result[3] != 0, .truncated = result[4] != 0 };
2275
+ }
2276
+
2277
+ /// Copied portable plans borrow native-owned slot facts and key bytes.
2278
+ /// OS operations and engine namespace checks stay in this host.
2279
+ 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 {
2280
+ var request: [12 + max_wire_key_bytes + file_streams.len * (8 + max_wire_key_bytes)]u8 = @splat(0);
2281
+ request[0..12].* = .{ 15, action, @intCast(key.len), @intFromBool(blocked), slot, op, event, outcome, chunk_tag, done_tag, err_tag, 0 };
2282
+ @memcpy(request[12..][0..key.len], key);
2283
+ var at: usize = 12 + key.len;
2284
+ for (&file_streams) |*entry| {
2285
+ const name = if (entry.used) entry.wireKey() else "";
2286
+ 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) };
2287
+ @memcpy(request[at + 8 ..][0..name.len], name);
2288
+ at += 8 + name.len;
2289
+ }
2290
+ var result: [8]u8 = undefined;
2291
+ 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))
2292
+ @panic("ts core host: invalid compiled file stream plan");
2293
+ if (action == 5) {
2294
+ if (result[0] != slot or result[1] != 0) @panic("ts core host: invalid compiled file completion owner");
2295
+ } else if (result[0] != 255) {
2296
+ const entry = &file_streams[result[0]];
2297
+ if ((action == 0 or action >= 3) and (!entry.used or !std.mem.eql(u8, entry.wireKey(), key)))
2298
+ @panic("ts core host: invalid compiled file lookup owner");
2299
+ 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)))
2300
+ @panic("ts core host: compiled file admission overwrites another owner");
2301
+ if (result[1] != 0) @panic("ts core host: compiled file plan admits a refused command");
2302
+ }
2303
+ return result;
2304
+ }
2305
+
1922
2306
  fn findFileStream(key: []const u8) ?usize {
2307
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2308
+ const plan = compiledFileStreamPlan(0, key, false, 0, 0, 0, 0, 0, 0, 0);
2309
+ return if (plan[0] == 255) null else plan[0];
2310
+ }
1923
2311
  for (&file_streams, 0..) |*entry, index| {
1924
2312
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
1925
2313
  }
1926
2314
  return null;
1927
2315
  }
1928
2316
 
1929
- fn fileStreamOccupiesKey(key: []const u8) bool {
1930
- return key.len > 0 and findFileStream(key) != null;
2317
+ fn reservedWireKeyOccupied(key: []const u8) bool {
2318
+ return reservedWireKeyOccupiedExcept(key, .none);
2319
+ }
2320
+
2321
+ /// Complete results reserve one owner across every command family.
2322
+ /// Same-family replacements retain the existing silent-drop contract.
2323
+ fn reservedWireKeyOccupiedExcept(key: []const u8, family: enum { none, effect, delay }) bool {
2324
+ if (key.len == 0) return false;
2325
+ if (findFileStream(key) != null or findClipboardWrite(key) != null) return true;
2326
+ if (family != .effect) if (findEffect(key)) |index| if (effects_table[index].full_result) return true;
2327
+ // Capability ownership is the recorded wire key, independent of
2328
+ // the compiled policy's cancellation lookup and routing decisions.
2329
+ if (family != .delay) for (&delays) |*entry| {
2330
+ if (entry.used and entry.full_result and std.mem.eql(u8, entry.wireKey(), key)) return true;
2331
+ };
2332
+ return false;
1931
2333
  }
1932
2334
 
1933
2335
  /// Every string-keyed command family shares one authored key surface.
@@ -1940,7 +2342,8 @@ pub fn TsCoreHost(comptime core: type) type {
1940
2342
  findStream(key) != null or
1941
2343
  findDelay(key) != null or
1942
2344
  findPty(key) != null or
1943
- findDb(key) != null;
2345
+ findDb(key) != null or
2346
+ findClipboardWrite(key) != null;
1944
2347
  }
1945
2348
 
1946
2349
  fn freeFileStreamIndex() ?usize {
@@ -1949,6 +2352,18 @@ pub fn TsCoreHost(comptime core: type) type {
1949
2352
  }
1950
2353
 
1951
2354
  fn issueReadFileStream(fx: *Fx, key: []const u8, chunk_tag: u8, done_tag: u8, err_tag: u8, path: []const u8) void {
2355
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2356
+ const plan = compiledFileStreamPlan(1, key, wireKeyOccupiedOutsideFileStreams(key), 0, 0, 0, 0, chunk_tag, done_tag, err_tag);
2357
+ if (plan[0] == 255) {
2358
+ fx.stageLoopMsg(msgFromTagStaticBytes(plan[2], "rejected"));
2359
+ return;
2360
+ }
2361
+ const entry = &file_streams[plan[0]];
2362
+ entry.* = .{ .used = true, .key_len = key.len, .chunk_tag = chunk_tag, .done_tag = plan[2], .err_tag = err_tag };
2363
+ @memcpy(entry.key[0..key.len], key);
2364
+ fx.readFileStream(.{ .key = file_stream_key_base + plan[0], .path = path, .on_result = fileStreamResultMsg });
2365
+ return;
2366
+ }
1952
2367
  if (wireKeyOccupiedOutsideFileStreams(key)) {
1953
2368
  fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
1954
2369
  return;
@@ -1974,6 +2389,18 @@ pub fn TsCoreHost(comptime core: type) type {
1974
2389
  }
1975
2390
 
1976
2391
  fn issueWriteFileStream(fx: *Fx, head: RoutedHead, path: []const u8) void {
2392
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2393
+ const plan = compiledFileStreamPlan(2, head.key, wireKeyOccupiedOutsideFileStreams(head.key), 0, 0, 0, 0, 0, head.ok_tag, head.err_tag);
2394
+ if (plan[0] == 255) {
2395
+ fx.stageLoopMsg(msgFromTagStaticBytes(plan[2], "rejected"));
2396
+ return;
2397
+ }
2398
+ const entry = &file_streams[plan[0]];
2399
+ entry.* = .{ .used = true, .sink = true, .busy = true, .key_len = head.key.len, .done_tag = plan[2], .err_tag = head.err_tag };
2400
+ @memcpy(entry.key[0..head.key.len], head.key);
2401
+ fx.writeFileStream(.{ .key = file_stream_key_base + plan[0], .path = path, .on_result = fileStreamResultMsg });
2402
+ return;
2403
+ }
1977
2404
  if (head.key.len == 0 or findFileStream(head.key) != null or wireKeyOccupiedOutsideFileStreams(head.key)) {
1978
2405
  fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
1979
2406
  return;
@@ -1989,6 +2416,19 @@ pub fn TsCoreHost(comptime core: type) type {
1989
2416
  }
1990
2417
 
1991
2418
  fn issueWriteFileChunk(fx: *Fx, head: RoutedHead, bytes: []const u8) void {
2419
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2420
+ const plan = compiledFileStreamPlan(3, head.key, false, 0, 0, 0, 0, 0, head.ok_tag, head.err_tag);
2421
+ if (plan[0] == 255) {
2422
+ fx.stageLoopMsg(if (plan[1] == 3) msgFromTagStaticBytes(plan[2], "out_of_order") else msgFromTagStaticBytes(plan[2], "sink_missing"));
2423
+ return;
2424
+ }
2425
+ const entry = &file_streams[plan[0]];
2426
+ entry.busy = true;
2427
+ entry.done_tag = plan[2];
2428
+ entry.err_tag = head.err_tag;
2429
+ fx.writeFileChunk(.{ .key = file_stream_key_base + plan[0], .bytes = bytes, .on_result = fileStreamResultMsg });
2430
+ return;
2431
+ }
1992
2432
  const index = findFileStream(head.key) orelse {
1993
2433
  fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "sink_missing"));
1994
2434
  return;
@@ -2012,6 +2452,19 @@ pub fn TsCoreHost(comptime core: type) type {
2012
2452
  }
2013
2453
 
2014
2454
  fn issueWriteFileClose(fx: *Fx, head: RoutedHead) void {
2455
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2456
+ const plan = compiledFileStreamPlan(4, head.key, false, 0, 0, 0, 0, 0, head.ok_tag, head.err_tag);
2457
+ if (plan[0] == 255) {
2458
+ fx.stageLoopMsg(if (plan[1] == 3) msgFromTagStaticBytes(plan[2], "out_of_order") else msgFromTagStaticBytes(plan[2], "sink_missing"));
2459
+ return;
2460
+ }
2461
+ const entry = &file_streams[plan[0]];
2462
+ entry.busy = true;
2463
+ entry.done_tag = plan[2];
2464
+ entry.err_tag = head.err_tag;
2465
+ fx.writeFileClose(.{ .key = file_stream_key_base + plan[0], .on_result = fileStreamResultMsg });
2466
+ return;
2467
+ }
2015
2468
  const index = findFileStream(head.key) orelse {
2016
2469
  fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "sink_missing"));
2017
2470
  return;
@@ -2039,6 +2492,18 @@ pub fn TsCoreHost(comptime core: type) type {
2039
2492
  const index = result.key - file_stream_key_base;
2040
2493
  if (index >= file_streams.len or !file_streams[index].used) @panic("ts core host: untracked file stream result");
2041
2494
  const entry = &file_streams[index];
2495
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2496
+ const plan = compiledFileStreamPlan(5, "", false, @intCast(index), @intFromEnum(result.op), @intFromEnum(result.event), @intFromEnum(result.outcome), 0, 0, 0);
2497
+ if (plan[4] == 1) entry.used = false;
2498
+ if (plan[5] == 1) entry.busy = false;
2499
+ return switch (plan[3]) {
2500
+ 0 => msgFromTagVoid(plan[2]),
2501
+ 1 => msgFromTagBytes(plan[2], result.bytes),
2502
+ 3 => msgFromTagBytes(plan[2], @tagName(result.outcome)),
2503
+ 2 => msgFromTagNumber(plan[2], @floatFromInt(result.total)),
2504
+ else => unreachable,
2505
+ };
2506
+ }
2042
2507
  if (entry.cancelling and result.outcome == .cancelled) {
2043
2508
  entry.used = false;
2044
2509
  return msgFromTagBytes(entry.err_tag, "cancelled");
@@ -2082,6 +2547,14 @@ pub fn TsCoreHost(comptime core: type) type {
2082
2547
  /// complete.
2083
2548
  fn streamLineMsg(line: runtime_effects.EffectLine) Msg {
2084
2549
  const entry = streamAt(line.key);
2550
+ if (entry.complete_events) return msgFromSpawnLine(entry.line_tag, line, entry.wireKey());
2551
+ if (comptime @hasDecl(core, "nativeStreamPolicy")) {
2552
+ const plan = compiledStreamCompletion(&.{ 2, @intFromBool(entry.fetch), @intFromBool(entry.damaged), @intFromBool(line.truncated), @intFromBool(line.dropped_before != 0), entry.line_tag });
2553
+ if (plan.shape != .bytes) @panic("ts core host: invalid compiled stream line payload");
2554
+ entry.damaged = plan.damaged;
2555
+ if (plan.retire) entry.used = false;
2556
+ return msgFromTagBytes(plan.tag, line.line);
2557
+ }
2085
2558
  if (entry.fetch and (line.truncated or line.dropped_before != 0)) {
2086
2559
  entry.damaged = true;
2087
2560
  }
@@ -2097,6 +2570,19 @@ pub fn TsCoreHost(comptime core: type) type {
2097
2570
  /// with the reason name as bytes.
2098
2571
  fn spawnExitMsg(exit: runtime_effects.EffectExit) Msg {
2099
2572
  const entry = streamAt(exit.key);
2573
+ if (entry.complete_events) {
2574
+ entry.used = false;
2575
+ return msgFromSpawnExit(entry.exit_tag, exit, entry.wireKey());
2576
+ }
2577
+ if (comptime @hasDecl(core, "nativeStreamPolicy")) {
2578
+ const plan = compiledStreamCompletion(&.{ 3, @intFromBool(entry.collect), @intFromBool(exit.reason == .exited), @intFromBool(exit.output_truncated), entry.exit_tag, entry.err_tag });
2579
+ if (plan.retire) entry.used = false;
2580
+ return switch (plan.shape) {
2581
+ .bytes => msgFromTagBytes(plan.tag, if (plan.truncated) "truncated" else @tagName(exit.reason)),
2582
+ .number => msgFromTagNumber(plan.tag, @floatFromInt(exit.code)),
2583
+ .number_bytes => msgFromTagNumberBytes("spawn exit", "{ code, output }", plan.tag, exit.code, exit.output),
2584
+ };
2585
+ }
2100
2586
  entry.used = false;
2101
2587
  if (exit.reason == .exited) {
2102
2588
  if (!entry.collect) {
@@ -2118,6 +2604,16 @@ pub fn TsCoreHost(comptime core: type) type {
2118
2604
  /// shared stream entry, so no later line can route for the key.
2119
2605
  fn fetchStreamResultMsg(response: runtime_effects.EffectResponse) Msg {
2120
2606
  const entry = streamAt(response.key);
2607
+ if (comptime @hasDecl(core, "nativeStreamPolicy")) {
2608
+ 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 });
2609
+ entry.damaged = plan.damaged;
2610
+ if (plan.retire) entry.used = false;
2611
+ return switch (plan.shape) {
2612
+ .bytes => if (plan.truncated) msgFromTagStaticBytes(plan.tag, "truncated") else msgFromTagBytes(plan.tag, @tagName(response.outcome)),
2613
+ .number => msgFromTagNumber(plan.tag, @floatFromInt(response.status)),
2614
+ .number_bytes => @panic("ts core host: invalid compiled fetch terminal payload"),
2615
+ };
2616
+ }
2121
2617
  const damaged = entry.damaged or response.truncated or response.dropped_before != 0;
2122
2618
  entry.used = false;
2123
2619
  if (response.outcome == .ok) {
@@ -2127,6 +2623,206 @@ pub fn TsCoreHost(comptime core: type) type {
2127
2623
  return msgFromTagBytes(entry.err_tag, @tagName(response.outcome));
2128
2624
  }
2129
2625
 
2626
+ const MediaPlan = struct {
2627
+ valid: bool,
2628
+ slot: ?usize,
2629
+ tag: u8,
2630
+ retire: bool,
2631
+ key: u64,
2632
+ expected_bytes: u64,
2633
+ source: platform.AudioCaptureSource,
2634
+ sample_rate: u32,
2635
+ capture_channels: u8,
2636
+ };
2637
+
2638
+ /// The tables and capability identities remain native-owned. The
2639
+ /// compiled core selects admission, routing and terminal retirement;
2640
+ /// exact u64 keys cross as opaque bytes, never as rounded numbers.
2641
+ fn compiledMediaPlan(
2642
+ comptime family: u8,
2643
+ operation: u8,
2644
+ key_bits: u64,
2645
+ event_kind: u8,
2646
+ tag: u8,
2647
+ source: platform.AudioCaptureSource,
2648
+ sample_rate: u32,
2649
+ capture_channels: u8,
2650
+ expected: f64,
2651
+ table: anytype,
2652
+ ) MediaPlan {
2653
+ return compiledMediaIdentityPlan(family, operation, key_bits, event_kind, tag, source, sample_rate, capture_channels, expected, table, false);
2654
+ }
2655
+
2656
+ 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 {
2657
+ var request: [28 + @as(usize, @max(runtime_effects.max_effects, runtime_effects.max_effect_channels)) * 16]u8 = @splat(0);
2658
+ request[0] = operation;
2659
+ request[1] = family;
2660
+ request[2] = @intCast(table.len);
2661
+ request[3] = event_kind;
2662
+ request[4] = tag;
2663
+ request[5] = @intFromEnum(source);
2664
+ request[6] = capture_channels;
2665
+ request[7] = @intFromBool(words);
2666
+ std.mem.writeInt(u64, request[8..16], key_bits, .little);
2667
+ std.mem.writeInt(u32, request[16..20], sample_rate, .little);
2668
+ std.mem.writeInt(u64, request[20..28], @bitCast(expected), .little);
2669
+ for (table, 0..) |entry, slot| {
2670
+ const at = 28 + slot * 16;
2671
+ request[at] = @intFromBool(entry.used);
2672
+ std.mem.writeInt(u64, request[at + 1 ..][0..8], if (comptime family == 0) entry.id else entry.key, .little);
2673
+ request[at + 9] = entry.event_tag;
2674
+ if (comptime family == 2) {
2675
+ request[at + 10] = @intFromEnum(entry.source);
2676
+ std.mem.writeInt(u32, request[at + 11 ..][0..4], entry.sample_rate, .little);
2677
+ request[at + 15] = entry.channels;
2678
+ }
2679
+ }
2680
+ var result: [28]u8 = undefined;
2681
+ if (core.nativeEffectPolicy(request[0 .. 28 + table.len * 16], &result) != result.len or
2682
+ result[0] > 1 or result[3] > 1 or result[4] > 1 or result[6] != 0 or result[7] != 0)
2683
+ @panic("ts core host: invalid compiled media plan");
2684
+ const slot: ?usize = if (result[1] == 255) null else result[1];
2685
+ if (slot) |index| {
2686
+ if (index >= table.len) @panic("ts core host: invalid compiled media slot");
2687
+ if (operation != 3 and !table[index].used) @panic("ts core host: compiled media lookup names an idle slot");
2688
+ if (operation == 3 and table[index].used) @panic("ts core host: compiled media admission names a live slot");
2689
+ }
2690
+ return .{
2691
+ .valid = result[0] == 1,
2692
+ .slot = slot,
2693
+ .tag = result[2],
2694
+ .retire = result[3] == 1,
2695
+ .source = @enumFromInt(result[4]),
2696
+ .capture_channels = result[5],
2697
+ .key = std.mem.readInt(u64, result[8..16], .little),
2698
+ .expected_bytes = std.mem.readInt(u64, result[16..24], .little),
2699
+ .sample_rate = std.mem.readInt(u32, result[24..28], .little),
2700
+ };
2701
+ }
2702
+
2703
+ fn compiledMediaLookup(comptime family: u8, key: u64, table: anytype) ?usize {
2704
+ return compiledMediaPlan(family, 7, key, 0, 0, .microphone, 0, 0, 0, table).slot;
2705
+ }
2706
+
2707
+ const MediaTransportPlan = struct { action: u8, retire: bool, rekey: bool, value: f64 };
2708
+
2709
+ fn compiledMediaTransport(video: bool, used: bool, ownership: u8, stored: []const u8, key: []const u8, verb: u8, value: f64) MediaTransportPlan {
2710
+ var request: [15 + max_wire_key_bytes * 2]u8 = @splat(0);
2711
+ request[0] = 6;
2712
+ request[1] = @intFromBool(video);
2713
+ request[2] = @intFromBool(used);
2714
+ request[3] = ownership;
2715
+ request[4] = verb;
2716
+ request[5] = @intCast(key.len);
2717
+ request[6] = @intCast(stored.len);
2718
+ std.mem.writeInt(u64, request[7..15], @bitCast(value), .little);
2719
+ @memcpy(request[15..][0..key.len], key);
2720
+ @memcpy(request[15 + key.len ..][0..stored.len], stored);
2721
+ var result: [12]u8 = undefined;
2722
+ if (core.nativeEffectPolicy(request[0 .. 15 + key.len + stored.len], &result) != result.len or
2723
+ (result[0] != 255 and result[0] > (if (video) @as(u8, 7) else @as(u8, 4))) or
2724
+ result[1] > 1 or result[2] > 1 or result[3] != 0)
2725
+ @panic("ts core host: invalid compiled media transport plan");
2726
+ return .{ .action = result[0], .retire = result[1] == 1, .rekey = result[2] == 1, .value = @bitCast(std.mem.readInt(u64, result[4..12], .little)) };
2727
+ }
2728
+
2729
+ const PlaybackLoadPlan = struct { accepted: bool, tag: u8, flags: u8, surface: u64, expected_bytes: u64 };
2730
+
2731
+ fn compiledPlaybackLoad(video: bool, tag: u8, flags: u8, value: f64, path: []const u8, url: []const u8) PlaybackLoadPlan {
2732
+ var request: [24 + runtime_effects.max_effect_video_path_bytes]u8 = @splat(0);
2733
+ request[0] = 8;
2734
+ request[1] = @intFromBool(video);
2735
+ request[2] = tag;
2736
+ request[3] = flags;
2737
+ std.mem.writeInt(u64, request[8..16], @bitCast(value), .little);
2738
+ std.mem.writeInt(u32, request[16..20], @intCast(path.len), .little);
2739
+ std.mem.writeInt(u32, request[20..24], @intCast(url.len), .little);
2740
+ const size = @min(url.len, runtime_effects.max_effect_video_path_bytes);
2741
+ @memcpy(request[24..][0..size], url[0..size]);
2742
+ var result: [24]u8 = undefined;
2743
+ if (core.nativeEffectPolicy(request[0 .. 24 + size], &result) != result.len or result[0] > 1 or result[2] > 7 or
2744
+ !std.mem.allEqual(u8, result[3..8], 0)) @panic("ts core host: invalid compiled playback load plan");
2745
+ 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) };
2746
+ }
2747
+
2748
+ fn issueAudioPlay(fx: *Fx, key: []const u8, tag: u8, path: []const u8, url: []const u8, cache: []const u8, expected: f64) void {
2749
+ const plan: PlaybackLoadPlan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
2750
+ compiledPlaybackLoad(false, tag, 0, expected, path, url)
2751
+ else
2752
+ .{ .accepted = true, .tag = tag, .flags = 0, .surface = 0, .expected_bytes = if (expected >= 1 and expected <= 9007199254740992.0) @intFromFloat(expected) else 0 };
2753
+ if (!plan.accepted) @panic("ts core host: audio load cannot refuse bridge admission");
2754
+ // Audio always commits before the capability, including failed sources.
2755
+ audio_entry.used = true;
2756
+ audio_entry.key_len = key.len;
2757
+ @memcpy(audio_entry.key[0..key.len], key);
2758
+ audio_entry.event_tag = plan.tag;
2759
+ fx.playAudio(.{ .key = audio_key_base, .path = path, .url = url, .cache_path = effectiveAudioCachePath(cache, url), .expected_bytes = plan.expected_bytes, .on_event = audioEventMsg });
2760
+ }
2761
+
2762
+ fn issueAudioPlayExact(fx: *Fx, key: u64, tag: u8, path: []const u8, url: []const u8, cache: []const u8, cache_dir: []const u8, expected: f64) void {
2763
+ const plan: PlaybackLoadPlan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
2764
+ compiledPlaybackLoad(false, tag, 0, expected, path, url)
2765
+ else
2766
+ .{ .accepted = true, .tag = tag, .flags = 0, .surface = 0, .expected_bytes = if (expected >= 1 and expected <= 9007199254740992.0) @intFromFloat(expected) else 0 };
2767
+ if (!plan.accepted) @panic("ts core host: exact audio load cannot refuse bridge admission");
2768
+ var cache_buffer: [runtime_effects.max_effect_audio_path_bytes]u8 = undefined;
2769
+ 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 "";
2770
+ inline for (msg_arms, 0..) |arm, index| {
2771
+ if (plan.tag == index) {
2772
+ if (comptime exactAudioArmShape(arm.type)) {
2773
+ const Callback = struct {
2774
+ fn eventMsg(event: runtime_effects.EffectAudio) Msg {
2775
+ const bands = core.rt.frameAlloc(u8, event.bands.len);
2776
+ @memcpy(bands, &event.bands);
2777
+ 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) });
2778
+ }
2779
+ };
2780
+ const options: Fx.PlayAudioOptions = .{ .key = key, .path = path, .url = url, .cache_path = cache_path, .expected_bytes = plan.expected_bytes, .on_event = Callback.eventMsg };
2781
+ // Rejection retains the prior native player and its compatibility route.
2782
+ if (!Fx.audioPlayRejected(options)) audio_entry.used = false;
2783
+ fx.playAudio(options);
2784
+ return;
2785
+ }
2786
+ @panic("ts core host: exact audio targets an incompatible message arm");
2787
+ }
2788
+ }
2789
+ @panic("ts core host: invalid exact audio message tag");
2790
+ }
2791
+
2792
+ fn issueVideoLoad(fx: *Fx, key: []const u8, tag: u8, surface: f64, path: []const u8, url: []const u8, flags: u8) void {
2793
+ const plan: PlaybackLoadPlan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
2794
+ compiledPlaybackLoad(true, tag, flags, surface, path, url)
2795
+ else blk: {
2796
+ const id: u64 = if (surface >= 1 and surface < 9007199254740992.0 and @floor(surface) == surface) @intFromFloat(surface) else 0;
2797
+ const options: Fx.LoadVideoOptions = .{ .key = videoKeyForTag(tag), .surface = id, .path = path, .url = url, .on_event = videoEventMsg };
2798
+ break :blk .{ .accepted = !Fx.videoLoadRejected(options), .tag = tag, .flags = flags & 7, .surface = id, .expected_bytes = 0 };
2799
+ };
2800
+ 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 };
2801
+ if (!plan.accepted) {
2802
+ // Refusal leaves the surviving player's key, route and exact token intact.
2803
+ fx.stageLoopMsg(msgFromTagVideo(plan.tag, .{ .key = options.key, .kind = .rejected }));
2804
+ return;
2805
+ }
2806
+ video_entry.used = true;
2807
+ video_entry.key_len = key.len;
2808
+ @memcpy(video_entry.key[0..key.len], key);
2809
+ video_entry.event_tag = plan.tag;
2810
+ fx.loadVideo(options);
2811
+ video_entry.token = fx.videoMintedToken();
2812
+ }
2813
+
2814
+ fn compiledPlaybackEvent(video: bool, used: bool, tag: u8, key: u64) u8 {
2815
+ var request: [12]u8 = @splat(0);
2816
+ request[0] = 10;
2817
+ request[1] = @intFromBool(video);
2818
+ request[2] = @intFromBool(used);
2819
+ request[3] = tag;
2820
+ std.mem.writeInt(u64, request[4..12], key, .little);
2821
+ var result: [1]u8 = undefined;
2822
+ if (core.nativeEffectPolicy(&request, &result) != result.len) @panic("ts core host: invalid compiled playback event route");
2823
+ return result[0];
2824
+ }
2825
+
2130
2826
  // ------------------------------------------------- audio stream
2131
2827
 
2132
2828
  /// The audio_ctl record: drive the single playback channel,
@@ -2136,6 +2832,20 @@ pub fn TsCoreHost(comptime core: type) type {
2136
2832
  /// the stream: the entry retires and later platform stragglers
2137
2833
  /// are the engine's to swallow.
2138
2834
  fn runAudioCtl(fx: *Fx, key: []const u8, verb: u8, value: f64) void {
2835
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2836
+ const plan = compiledMediaTransport(false, audio_entry.used, 1, audio_entry.wireKey(), key, verb, value);
2837
+ if (plan.retire) audio_entry.used = false;
2838
+ switch (plan.action) {
2839
+ 0 => fx.pauseAudio(),
2840
+ 1 => fx.resumeAudio(),
2841
+ 2 => fx.stopAudio(),
2842
+ 3 => fx.seekAudio(@intFromFloat(plan.value)),
2843
+ 4 => fx.setAudioVolume(@floatCast(value)),
2844
+ 255 => {},
2845
+ else => unreachable,
2846
+ }
2847
+ return;
2848
+ }
2139
2849
  if (!audio_entry.used or !std.mem.eql(u8, audio_entry.wireKey(), key)) return;
2140
2850
  switch (verb) {
2141
2851
  0 => fx.pauseAudio(),
@@ -2144,12 +2854,7 @@ pub fn TsCoreHost(comptime core: type) type {
2144
2854
  audio_entry.used = false;
2145
2855
  fx.stopAudio();
2146
2856
  },
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
2857
  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
2858
  4 => fx.setAudioVolume(@floatCast(value)),
2154
2859
  else => @panic("ts core host: unknown audio_ctl verb wire value - the core and this runtime disagree on cmd_format_version"),
2155
2860
  }
@@ -2161,10 +2866,13 @@ pub fn TsCoreHost(comptime core: type) type {
2161
2866
  /// starts the next track from `completed`), and audio_ctl
2162
2867
  /// `stop` is the explicit close.
2163
2868
  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);
2869
+ const tag = if (comptime @hasDecl(core, "nativeEffectPolicy"))
2870
+ compiledPlaybackEvent(false, audio_entry.used, audio_entry.event_tag, event.key)
2871
+ else blk: {
2872
+ if (!audio_entry.used) @panic("ts core host: an audio event arrived with no open bridge stream");
2873
+ break :blk audio_entry.event_tag;
2874
+ };
2875
+ return msgFromTagAudio(tag, event);
2168
2876
  }
2169
2877
 
2170
2878
  // ------------------------------------------------- video stream
@@ -2176,6 +2884,26 @@ pub fn TsCoreHost(comptime core: type) type {
2176
2884
  /// the stream: the entry retires and later platform stragglers
2177
2885
  /// are the engine's to swallow.
2178
2886
  fn runVideoCtl(fx: *Fx, key: []const u8, verb: u8, value: f64) void {
2887
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
2888
+ const owner = fx.videoOwnerToken();
2889
+ const ownership: u8 = if (owner == video_entry.token) 1 else if (owner == 0) 2 else 0;
2890
+ const plan = compiledMediaTransport(true, video_entry.used, ownership, video_entry.wireKey(), key, verb, value);
2891
+ if (plan.retire) video_entry.used = false;
2892
+ switch (plan.action) {
2893
+ 0 => fx.playVideo(),
2894
+ 1 => fx.pauseVideo(),
2895
+ 2 => fx.stopVideoCancel(video_entry.token),
2896
+ 3 => fx.seekVideo(@intFromFloat(plan.value)),
2897
+ 4 => fx.setVideoVolume(@floatCast(value)),
2898
+ 5 => fx.setVideoMuted(plan.value != 0),
2899
+ 6 => fx.setVideoLoop(plan.value != 0),
2900
+ 7 => fx.restartVideo(),
2901
+ 255 => {},
2902
+ else => unreachable,
2903
+ }
2904
+ if (plan.rekey) video_entry.token = fx.videoMintedToken();
2905
+ return;
2906
+ }
2179
2907
  if (!video_entry.used or !std.mem.eql(u8, video_entry.wireKey(), key)) return;
2180
2908
  if (verb == 2) {
2181
2909
  // `Cmd.videoStop` is the stream's CANCEL: the engine
@@ -2233,6 +2961,10 @@ pub fn TsCoreHost(comptime core: type) type {
2233
2961
  4 => fx.setVideoVolume(@floatCast(value)),
2234
2962
  5 => fx.setVideoMuted(value != 0),
2235
2963
  6 => fx.setVideoLoop(value != 0),
2964
+ 7 => {
2965
+ fx.restartVideo();
2966
+ video_entry.token = fx.videoMintedToken();
2967
+ },
2236
2968
  else => @panic("ts core host: unknown video_ctl verb wire value - the core and this runtime disagree on cmd_format_version"),
2237
2969
  }
2238
2970
  }
@@ -2252,7 +2984,11 @@ pub fn TsCoreHost(comptime core: type) type {
2252
2984
  /// starts the next clip from `completed`), and video_ctl
2253
2985
  /// `stop` is the explicit close.
2254
2986
  fn videoEventMsg(event: runtime_effects.EffectVideo) Msg {
2255
- return msgFromTagVideo(@intCast(event.key & 0xFF), event);
2987
+ const tag = if (comptime @hasDecl(core, "nativeEffectPolicy"))
2988
+ compiledPlaybackEvent(true, video_entry.used, video_entry.event_tag, event.key)
2989
+ else
2990
+ @as(u8, @intCast(event.key & 0xFF));
2991
+ return msgFromTagVideo(tag, event);
2256
2992
  }
2257
2993
 
2258
2994
  /// Issue one image load. The keyed-effect discipline here is
@@ -2276,39 +3012,53 @@ pub fn TsCoreHost(comptime core: type) type {
2276
3012
  cache_path: []const u8,
2277
3013
  expected: f64,
2278
3014
  ) 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;
3015
+ const Selection = struct { key: u64, index: usize, tag: u8, expected_bytes: u64 };
3016
+ const selection: ?Selection = if (comptime @hasDecl(core, "nativeEffectPolicy")) blk: {
3017
+ const plan = compiledMediaPlan(0, 3, @bitCast(id_value), 0, event_tag, .microphone, 0, 0, expected, &images);
3018
+ const index = plan.slot orelse {
3019
+ fx.stageLoopMsg(msgFromTagImage(plan.tag, .{ .id = plan.key, .outcome = .rejected }));
3020
+ break :blk null;
3021
+ };
3022
+ break :blk .{ .key = plan.key, .index = index, .tag = plan.tag, .expected_bytes = plan.expected_bytes };
3023
+ } else native: {
3024
+ // Strictly BELOW 2^53 (the SDK contract): at 2^53 the f64
3025
+ // grid steps by 2, so 2^53 is the first value that aliases
3026
+ // a neighbor (2^53 + 1) on the wire — the bridge rejects it
3027
+ // rather than guess which integer the app meant. 2^53 - 1
3028
+ // is the last id every tier carries exactly.
3029
+ const representable = std.math.isFinite(id_value) and
3030
+ id_value >= 1 and id_value < 9007199254740992.0 and
3031
+ @floor(id_value) == id_value;
3032
+ if (!representable) {
3033
+ fx.stageLoopMsg(msgFromTagImage(event_tag, .{ .id = 0, .outcome = .rejected }));
3034
+ break :native null;
3035
+ }
3036
+ const id: u64 = @intFromFloat(id_value);
3037
+ if (findImage(id) != null) {
3038
+ fx.stageLoopMsg(msgFromTagImage(event_tag, .{ .id = id, .outcome = .rejected }));
3039
+ break :native null;
3040
+ }
3041
+ const index = freeImageIndex() orelse {
3042
+ // All 16 entries hold live loads — one gallery screen's
3043
+ // Cmd.batch reaches this. The engine answers its own
3044
+ // slot exhaustion with a dynamic `.rejected` result, and
3045
+ // the audio channel's exhaustion story is a quiet
3046
+ // in-place replace; a full bridge table speaks the same
3047
+ // vocabulary: exactly one rejected result through the
3048
+ // event arm, never a crash — however many loads one
3049
+ // batch stages against it.
3050
+ fx.stageLoopMsg(msgFromTagImage(event_tag, .{ .id = id, .outcome = .rejected }));
3051
+ break :native null;
3052
+ };
3053
+ 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
3054
  };
3055
+ const chosen = selection orelse return;
3056
+ const id = chosen.key;
3057
+ const index = chosen.index;
2308
3058
  const entry = &images[index];
2309
3059
  entry.used = true;
2310
3060
  entry.id = id;
2311
- entry.event_tag = event_tag;
3061
+ entry.event_tag = chosen.tag;
2312
3062
  fx.loadImage(.{
2313
3063
  .id = id,
2314
3064
  .path = image_path,
@@ -2329,15 +3079,31 @@ pub fn TsCoreHost(comptime core: type) type {
2329
3079
  // size every real download misses. 0 is the honest
2330
3080
  // mapping; the emitter already stops the literal
2331
3081
  // spellings (NS1030).
2332
- .expected_bytes = if (expected >= 1 and expected < 9007199254740992.0 and @floor(expected) == expected)
2333
- @intFromFloat(expected)
2334
- else
2335
- 0,
3082
+ .expected_bytes = chosen.expected_bytes,
2336
3083
  .on_result = imageResultMsg,
2337
3084
  });
2338
3085
  }
2339
3086
 
3087
+ fn imageWordIdValid(id: u64) bool {
3088
+ return id != 0 and id >> 63 == 0;
3089
+ }
3090
+
3091
+ fn issueImageLoadWords(fx: *Fx, id: u64, tag: u8, image_path: []const u8, url: []const u8, cache: []const u8, expected: f64) void {
3092
+ const plan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
3093
+ compiledMediaIdentityPlan(0, 3, id, 0, tag, .microphone, 0, 0, expected, &images, true)
3094
+ else
3095
+ 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 };
3096
+ const index = plan.slot orelse {
3097
+ // Invalid identities still echo the complete requested words.
3098
+ fx.stageLoopMsg(msgFromTagImage(tag, .{ .id = id, .outcome = .rejected }));
3099
+ return;
3100
+ };
3101
+ images[index] = .{ .used = true, .id = plan.key, .event_tag = plan.tag };
3102
+ fx.loadImage(.{ .id = plan.key, .path = image_path, .url = url, .cache_path = effectiveImageCachePath(cache, url), .expected_bytes = plan.expected_bytes, .on_result = imageResultMsg });
3103
+ }
3104
+
2340
3105
  fn findImage(id: u64) ?usize {
3106
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) return compiledMediaLookup(0, id, &images);
2341
3107
  for (&images, 0..) |*entry, index| {
2342
3108
  if (entry.used and entry.id == id) return index;
2343
3109
  }
@@ -2363,13 +3129,18 @@ pub fn TsCoreHost(comptime core: type) type {
2363
3129
  /// bridge namespace), and every bridge key base sits above 2^53,
2364
3130
  /// so the cancel can never reach another table's slot.
2365
3131
  fn runImageCancel(fx: *Fx, id_value: f64) void {
3132
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3133
+ const plan = compiledMediaPlan(0, 4, @bitCast(id_value), 0, 0, .microphone, 0, 0, 0, &images);
3134
+ if (plan.slot != null) fx.cancelImage(plan.key);
3135
+ return;
3136
+ }
2366
3137
  const representable = std.math.isFinite(id_value) and
2367
3138
  id_value >= 1 and id_value < 9007199254740992.0 and
2368
3139
  @floor(id_value) == id_value;
2369
3140
  if (!representable) return;
2370
3141
  const id: u64 = @intFromFloat(id_value);
2371
3142
  if (findImage(id) == null) return;
2372
- fx.cancel(id);
3143
+ fx.cancelImage(id);
2373
3144
  }
2374
3145
 
2375
3146
  /// The image_unregister record: free the registry slot under
@@ -2385,6 +3156,11 @@ pub fn TsCoreHost(comptime core: type) type {
2385
3156
  /// id the wire cannot carry exactly could never have been
2386
3157
  /// registered through this bridge, so it no-ops the same way.
2387
3158
  fn runImageUnregister(fx: *Fx, id_value: f64) void {
3159
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3160
+ const plan = compiledMediaPlan(0, 4, @bitCast(id_value), 0, 0, .microphone, 0, 0, 0, &[_]ImageEntry{});
3161
+ if (plan.valid) _ = fx.unregisterImage(plan.key);
3162
+ return;
3163
+ }
2388
3164
  const representable = std.math.isFinite(id_value) and
2389
3165
  id_value >= 1 and id_value < 9007199254740992.0 and
2390
3166
  @floor(id_value) == id_value;
@@ -2396,6 +3172,12 @@ pub fn TsCoreHost(comptime core: type) type {
2396
3172
  /// `ImageMsgFn` for image loads: the ONE terminal routes the
2397
3173
  /// entry's event arm and retires the entry.
2398
3174
  fn imageResultMsg(result: runtime_effects.EffectImageResult) Msg {
3175
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3176
+ const plan = compiledMediaPlan(0, 5, result.id, 0, 0, .microphone, 0, 0, 0, &images);
3177
+ const index = plan.slot orelse @panic("ts core host: image result has no compiled owner");
3178
+ if (plan.retire) images[index].used = false;
3179
+ return msgFromTagImage(plan.tag, result);
3180
+ }
2399
3181
  const index = findImage(result.id) orelse
2400
3182
  @panic("ts core host: an image result arrived with no open bridge entry");
2401
3183
  const entry = &images[index];
@@ -2425,27 +3207,42 @@ pub fn TsCoreHost(comptime core: type) type {
2425
3207
  event_tag: u8,
2426
3208
  max_pending: u8,
2427
3209
  ) 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;
3210
+ const Selection = struct { key: u64, index: usize, tag: u8 };
3211
+ const selection: ?Selection = if (comptime @hasDecl(core, "nativeEffectPolicy")) blk: {
3212
+ const plan = compiledMediaPlan(1, 3, @bitCast(key_value), 0, event_tag, .microphone, 0, 0, 0, &channels);
3213
+ const index = plan.slot orelse {
3214
+ fx.stageLoopMsg(msgFromTagChannel(plan.tag, .{ .key = plan.key, .kind = .rejected }));
3215
+ break :blk null;
3216
+ };
3217
+ break :blk .{ .key = plan.key, .index = index, .tag = plan.tag };
3218
+ } else native: {
3219
+ const representable = std.math.isFinite(key_value) and
3220
+ key_value >= 1 and key_value < 9007199254740992.0 and
3221
+ @floor(key_value) == key_value;
3222
+ if (!representable) {
3223
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = 0, .kind = .rejected }));
3224
+ break :native null;
3225
+ }
3226
+ const key: u64 = @intFromFloat(key_value);
3227
+ if (findChannel(key) != null) {
3228
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = key, .kind = .rejected }));
3229
+ break :native null;
3230
+ }
3231
+ const index = freeChannelIndex() orelse {
3232
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = key, .kind = .rejected }));
3233
+ break :native null;
3234
+ };
3235
+ break :native .{ .key = key, .index = index, .tag = event_tag };
2443
3236
  };
3237
+ const chosen = selection orelse return false;
3238
+ const key = chosen.key;
3239
+ const index = chosen.index;
2444
3240
  const entry = &channels[index];
2445
3241
  entry.used = true;
2446
3242
  entry.key = key;
2447
- entry.event_tag = event_tag;
2448
- _ = fx.openChannel(.{
3243
+ entry.event_tag = chosen.tag;
3244
+ const already_open = fx.channelHandle(key) != null;
3245
+ const opened = fx.openChannel(.{
2449
3246
  .key = key,
2450
3247
  .on_event = channelEventMsg,
2451
3248
  .max_pending = max_pending,
@@ -2454,10 +3251,11 @@ pub fn TsCoreHost(comptime core: type) type {
2454
3251
  // both live execution and replay (whose accepted handle is inert).
2455
3252
  // Validation and capacity refusals stage their rejection without
2456
3253
  // leaving an open slot.
2457
- return fx.channelHandle(key) != null;
3254
+ return opened.live() or (!already_open and fx.replayArmed() and fx.channelHandle(key) != null);
2458
3255
  }
2459
3256
 
2460
3257
  fn findChannel(key: u64) ?usize {
3258
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) return compiledMediaLookup(1, key, &channels);
2461
3259
  for (&channels, 0..) |*entry, index| {
2462
3260
  if (entry.used and entry.key == key) return index;
2463
3261
  }
@@ -2481,6 +3279,11 @@ pub fn TsCoreHost(comptime core: type) type {
2481
3279
  /// convention; every bridge key base sits above 2^53, so this
2482
3280
  /// can never reach another table's slot).
2483
3281
  fn runChannelClose(fx: *Fx, key_value: f64) void {
3282
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3283
+ const plan = compiledMediaPlan(1, 4, @bitCast(key_value), 0, 0, .microphone, 0, 0, 0, &channels);
3284
+ if (plan.slot != null) fx.closeChannel(plan.key);
3285
+ return;
3286
+ }
2484
3287
  const representable = std.math.isFinite(key_value) and
2485
3288
  key_value >= 1 and key_value < 9007199254740992.0 and
2486
3289
  @floor(key_value) == key_value;
@@ -2495,6 +3298,17 @@ pub fn TsCoreHost(comptime core: type) type {
2495
3298
  /// terminals retire the entry (freeing the key for a fresh
2496
3299
  /// open), `data` events keep it live — the spawn stream shape.
2497
3300
  fn channelEventMsg(event: runtime_effects.EffectChannelEvent) Msg {
3301
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3302
+ const kind: u8 = switch (event.kind) {
3303
+ .data => 0,
3304
+ .closed => 1,
3305
+ .rejected => 2,
3306
+ };
3307
+ const plan = compiledMediaPlan(1, 5, event.key, kind, 0, .microphone, 0, 0, 0, &channels);
3308
+ const index = plan.slot orelse @panic("ts core host: channel event has no compiled owner");
3309
+ if (plan.retire) channels[index].used = false;
3310
+ return msgFromTagChannel(plan.tag, event);
3311
+ }
2498
3312
  const index = findChannel(event.key) orelse
2499
3313
  @panic("ts core host: a channel event arrived with no open bridge entry");
2500
3314
  const entry = &channels[index];
@@ -2512,62 +3326,77 @@ pub fn TsCoreHost(comptime core: type) type {
2512
3326
  capture_channels: u8,
2513
3327
  event_tag: u8,
2514
3328
  ) 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,
3329
+ const Selection = struct { key: u64, index: usize, tag: u8, source: platform.AudioCaptureSource, rate: u32, channels: u8 };
3330
+ const selection: ?Selection = if (comptime @hasDecl(core, "nativeEffectPolicy")) blk: {
3331
+ const plan = compiledMediaPlan(2, 3, @bitCast(key_value), 0, event_tag, source, sample_rate, capture_channels, 0, &audio_captures);
3332
+ const index = plan.slot orelse {
3333
+ fx.stageLoopMsg(msgFromTagAudioCapture(plan.tag, .{ .key = plan.key, .kind = .rejected, .source = plan.source, .sample_rate = plan.sample_rate, .channels = plan.capture_channels }));
3334
+ break :blk null;
3335
+ };
3336
+ break :blk .{ .key = plan.key, .index = index, .tag = plan.tag, .source = plan.source, .rate = plan.sample_rate, .channels = plan.capture_channels };
3337
+ } else native: {
3338
+ const representable = std.math.isFinite(key_value) and
3339
+ key_value >= 1 and key_value < 9007199254740992.0 and
3340
+ @floor(key_value) == key_value;
3341
+ const format: platform.AudioCaptureFormat = .{
2548
3342
  .sample_rate = sample_rate,
2549
3343
  .channels = capture_channels,
2550
- }));
2551
- return;
3344
+ };
3345
+ if (!representable or !format.valid()) {
3346
+ fx.stageLoopMsg(msgFromTagAudioCapture(event_tag, .{
3347
+ .key = if (representable) @intFromFloat(key_value) else 0,
3348
+ .kind = .rejected,
3349
+ .source = source,
3350
+ .sample_rate = sample_rate,
3351
+ .channels = capture_channels,
3352
+ }));
3353
+ break :native null;
3354
+ }
3355
+ const key: u64 = @intFromFloat(key_value);
3356
+ if (findAudioCapture(key) != null) {
3357
+ fx.stageLoopMsg(msgFromTagAudioCapture(event_tag, .{
3358
+ .key = key,
3359
+ .kind = .rejected,
3360
+ .source = source,
3361
+ .sample_rate = sample_rate,
3362
+ .channels = capture_channels,
3363
+ }));
3364
+ break :native null;
3365
+ }
3366
+ const index = freeAudioCaptureIndex() orelse {
3367
+ fx.stageLoopMsg(msgFromTagAudioCapture(event_tag, .{
3368
+ .key = key,
3369
+ .kind = .rejected,
3370
+ .source = source,
3371
+ .sample_rate = sample_rate,
3372
+ .channels = capture_channels,
3373
+ }));
3374
+ break :native null;
3375
+ };
3376
+ break :native .{ .key = key, .index = index, .tag = event_tag, .source = source, .rate = sample_rate, .channels = capture_channels };
2552
3377
  };
3378
+ const chosen = selection orelse return;
3379
+ const key = chosen.key;
3380
+ const index = chosen.index;
2553
3381
  audio_captures[index] = .{
2554
3382
  .used = true,
2555
3383
  .key = key,
2556
- .event_tag = event_tag,
2557
- .source = source,
2558
- .sample_rate = sample_rate,
2559
- .channels = capture_channels,
3384
+ .event_tag = chosen.tag,
3385
+ .source = chosen.source,
3386
+ .sample_rate = chosen.rate,
3387
+ .channels = chosen.channels,
2560
3388
  };
2561
3389
  fx.startAudioCapture(.{
2562
3390
  .key = key,
2563
- .source = source,
2564
- .sample_rate = sample_rate,
2565
- .channels = capture_channels,
3391
+ .source = chosen.source,
3392
+ .sample_rate = chosen.rate,
3393
+ .channels = chosen.channels,
2566
3394
  .on_event = audioCaptureEventMsg,
2567
3395
  });
2568
3396
  }
2569
3397
 
2570
3398
  fn findAudioCapture(key: u64) ?usize {
3399
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) return compiledMediaLookup(2, key, &audio_captures);
2571
3400
  for (&audio_captures, 0..) |*entry, index| {
2572
3401
  if (entry.used and entry.key == key) return index;
2573
3402
  }
@@ -2582,6 +3411,11 @@ pub fn TsCoreHost(comptime core: type) type {
2582
3411
  }
2583
3412
 
2584
3413
  fn runAudioCaptureStop(fx: *Fx, key_value: f64) void {
3414
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3415
+ const plan = compiledMediaPlan(2, 4, @bitCast(key_value), 0, 0, .microphone, 0, 0, 0, &audio_captures);
3416
+ if (plan.slot != null) fx.stopAudioCapture(plan.key);
3417
+ return;
3418
+ }
2585
3419
  const representable = std.math.isFinite(key_value) and
2586
3420
  key_value >= 1 and key_value < 9007199254740992.0 and
2587
3421
  @floor(key_value) == key_value;
@@ -2592,6 +3426,23 @@ pub fn TsCoreHost(comptime core: type) type {
2592
3426
  }
2593
3427
 
2594
3428
  fn audioCaptureEventMsg(channel_event: runtime_effects.EffectChannelEvent) Msg {
3429
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3430
+ var event = runtime_effects.decodeAudioCaptureChannelEvent(channel_event);
3431
+ const kind: u8 = switch (event.kind) {
3432
+ .started => 0,
3433
+ .data => 1,
3434
+ .failed => 2,
3435
+ .stopped => 3,
3436
+ .rejected => 4,
3437
+ };
3438
+ const plan = compiledMediaPlan(2, 5, channel_event.key, kind, 0, event.source, event.sample_rate, event.channels, 0, &audio_captures);
3439
+ const index = plan.slot orelse @panic("ts core host: capture event has no compiled owner");
3440
+ event.source = plan.source;
3441
+ event.sample_rate = plan.sample_rate;
3442
+ event.channels = plan.capture_channels;
3443
+ if (plan.retire) audio_captures[index].used = false;
3444
+ return msgFromTagAudioCapture(plan.tag, event);
3445
+ }
2595
3446
  const index = findAudioCapture(channel_event.key) orelse
2596
3447
  @panic("ts core host: an audio capture event arrived with no open bridge entry");
2597
3448
  const entry = &audio_captures[index];
@@ -2618,6 +3469,44 @@ pub fn TsCoreHost(comptime core: type) type {
2618
3469
  /// "rejected" exit through the entry's own event arm — never
2619
3470
  /// silent — and a transport that could not start as one
2620
3471
  /// "spawn_failed".
3472
+ const PtyPlan = struct { slot: ?usize, tag: u8, retire: bool, bind: bool, cols: u16, rows: u16, engine_key: u64 };
3473
+
3474
+ fn compiledPtyPlan(action: u8, key: []const u8, tag: u8, cols: f64, rows: f64, blocked: bool, event_key: u64, event_kind: u8) PtyPlan {
3475
+ var request: [32 + max_wire_key_bytes + runtime_effects.max_effect_ptys * (4 + max_wire_key_bytes)]u8 = @splat(0);
3476
+ request[0] = 9;
3477
+ request[1] = action;
3478
+ request[2] = @intCast(ptys.len);
3479
+ request[3] = @intFromBool(blocked);
3480
+ request[4] = event_kind;
3481
+ request[5] = tag;
3482
+ request[6] = @intCast(key.len);
3483
+ std.mem.writeInt(u64, request[8..16], event_key, .little);
3484
+ std.mem.writeInt(u64, request[16..24], @bitCast(cols), .little);
3485
+ std.mem.writeInt(u64, request[24..32], @bitCast(rows), .little);
3486
+ @memcpy(request[32..][0..key.len], key);
3487
+ var at: usize = 32 + key.len;
3488
+ for (&ptys) |*entry| {
3489
+ request[at] = @intFromBool(entry.used);
3490
+ request[at + 1] = @intFromBool(entry.bound);
3491
+ request[at + 2] = entry.event_tag;
3492
+ request[at + 3] = @intCast(entry.key_len);
3493
+ @memcpy(request[at + 4 ..][0..entry.key_len], entry.wireKey());
3494
+ at += 4 + entry.key_len;
3495
+ }
3496
+ var result: [16]u8 = undefined;
3497
+ if (core.nativeEffectPolicy(request[0..at], &result) != result.len or result[2] > 1 or result[3] > 1)
3498
+ @panic("ts core host: invalid compiled PTY plan");
3499
+ const slot: ?usize = if (result[0] == 255) null else result[0];
3500
+ const engine_key = std.mem.readInt(u64, result[8..16], .little);
3501
+ if (slot) |index| {
3502
+ if (index >= ptys.len or engine_key != pty_key_base + index)
3503
+ @panic("ts core host: invalid compiled PTY identity");
3504
+ if ((action == 0 and ptys[index].used) or ((action == 1 or action == 2 or action == 4) and !ptys[index].used))
3505
+ @panic("ts core host: compiled PTY plan names an invalid owner");
3506
+ } else if (engine_key != 0) @panic("ts core host: absent compiled PTY identity is nonzero");
3507
+ 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 };
3508
+ }
3509
+
2621
3510
  fn issuePtySpawn(
2622
3511
  fx: *Fx,
2623
3512
  key: []const u8,
@@ -2627,47 +3516,38 @@ pub fn TsCoreHost(comptime core: type) type {
2627
3516
  term: []const u8,
2628
3517
  argv: []const []const u8,
2629
3518
  ) 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 }));
3519
+ const plan: PtyPlan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
3520
+ compiledPtyPlan(0, key, event_tag, cols, rows, reservedWireKeyOccupied(key), 0, 0)
3521
+ else blk: {
3522
+ const index = if (key.len > 0 and (findPty(key) != null or reservedWireKeyOccupied(key))) null else reusableBoundPty(key) orelse freePtyIndex();
3523
+ 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 };
3524
+ };
3525
+ const index = plan.slot orelse {
3526
+ // Refusals outlive the borrowed command frame; intern their key.
3527
+ fx.stageLoopMsg(msgFromTagPty(plan.tag, fx.stageLoopKey(key), true, .{ .key = 0, .kind = .exit, .reason = .rejected }));
2648
3528
  return;
2649
3529
  };
2650
3530
  const entry = &ptys[index];
2651
3531
  entry.used = true;
2652
3532
  entry.key_len = key.len;
2653
3533
  @memcpy(entry.key[0..key.len], key);
2654
- entry.event_tag = event_tag;
3534
+ entry.event_tag = plan.tag;
2655
3535
  if (term.len == 0) {
2656
3536
  // Wire "" = "the engine's default TERM" — the record
2657
3537
  // never bakes the default in (the fetch-timeout rule).
2658
3538
  fx.ptySpawn(.{
2659
- .key = pty_key_base + index,
3539
+ .key = plan.engine_key,
2660
3540
  .argv = argv,
2661
- .cols = ptyDimension(cols),
2662
- .rows = ptyDimension(rows),
3541
+ .cols = plan.cols,
3542
+ .rows = plan.rows,
2663
3543
  .on_event = ptyEventMsg,
2664
3544
  });
2665
3545
  } else {
2666
3546
  fx.ptySpawn(.{
2667
- .key = pty_key_base + index,
3547
+ .key = plan.engine_key,
2668
3548
  .argv = argv,
2669
- .cols = ptyDimension(cols),
2670
- .rows = ptyDimension(rows),
3549
+ .cols = plan.cols,
3550
+ .rows = plan.rows,
2671
3551
  .term = term,
2672
3552
  .on_event = ptyEventMsg,
2673
3553
  });
@@ -2691,6 +3571,11 @@ pub fn TsCoreHost(comptime core: type) type {
2691
3571
  /// the engine's clamp would otherwise shrink the child to a
2692
3572
  /// 1x1 the app never asked for).
2693
3573
  fn runPtyResize(fx: *Fx, key: []const u8, cols: f64, rows: f64) void {
3574
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3575
+ const plan = compiledPtyPlan(2, key, 0, cols, rows, false, 0, 0);
3576
+ if (plan.slot != null) fx.ptyResize(plan.engine_key, plan.cols, plan.rows);
3577
+ return;
3578
+ }
2694
3579
  const index = findPty(key) orelse return;
2695
3580
  const c = ptyDimension(cols);
2696
3581
  const r = ptyDimension(rows);
@@ -2699,6 +3584,7 @@ pub fn TsCoreHost(comptime core: type) type {
2699
3584
  }
2700
3585
 
2701
3586
  fn findPty(key: []const u8) ?usize {
3587
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) return compiledPtyPlan(1, key, 0, 0, 0, false, 0, 0).slot;
2702
3588
  if (key.len == 0) return null;
2703
3589
  for (&ptys, 0..) |*entry, index| {
2704
3590
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
@@ -2706,9 +3592,36 @@ pub fn TsCoreHost(comptime core: type) type {
2706
3592
  return null;
2707
3593
  }
2708
3594
 
3595
+ /// Named terminal bindings reserve their identity until this host resets.
3596
+ /// An ended grid remains addressable; another name cannot inherit it.
3597
+ pub fn resolvePtyKey(key: []const u8) u64 {
3598
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3599
+ const plan = compiledPtyPlan(3, key, 0, 0, 0, false, 0, 0);
3600
+ if (plan.slot) |index| if (plan.bind) {
3601
+ ptys[index].bound = true;
3602
+ };
3603
+ return plan.engine_key;
3604
+ }
3605
+ if (key.len == 0) return 0;
3606
+ for (&ptys, 0..) |*entry, index| {
3607
+ if ((entry.used or entry.bound) and std.mem.eql(u8, entry.wireKey(), key)) {
3608
+ entry.bound = true;
3609
+ return pty_key_base + index;
3610
+ }
3611
+ }
3612
+ return 0;
3613
+ }
3614
+
3615
+ fn reusableBoundPty(key: []const u8) ?usize {
3616
+ for (&ptys, 0..) |*entry, index| {
3617
+ if (entry.bound and !entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
3618
+ }
3619
+ return null;
3620
+ }
3621
+
2709
3622
  fn freePtyIndex() ?usize {
2710
3623
  for (&ptys, 0..) |*entry, index| {
2711
- if (!entry.used) return index;
3624
+ if (!entry.used and !entry.bound) return index;
2712
3625
  }
2713
3626
  return null;
2714
3627
  }
@@ -2718,6 +3631,12 @@ pub fn TsCoreHost(comptime core: type) type {
2718
3631
  /// (freeing the wire key for a fresh session), "output"
2719
3632
  /// batches keep it live — the spawn stream shape.
2720
3633
  fn ptyEventMsg(event: runtime_effects.EffectPtyEvent) Msg {
3634
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3635
+ const plan = compiledPtyPlan(4, "", 0, 0, 0, false, event.key, @intFromEnum(event.kind));
3636
+ const entry = &ptys[plan.slot orelse @panic("ts core host: compiled PTY event has no slot")];
3637
+ if (plan.retire) entry.used = false;
3638
+ return msgFromTagPty(plan.tag, entry.wireKey(), false, event);
3639
+ }
2721
3640
  if (event.key < pty_key_base) {
2722
3641
  @panic("ts core host: a pty event arrived outside the bridge's pty key namespace");
2723
3642
  }
@@ -2732,6 +3651,142 @@ pub fn TsCoreHost(comptime core: type) type {
2732
3651
  return msgFromTagPty(entry.event_tag, wire_key, false, event);
2733
3652
  }
2734
3653
 
3654
+ /// Native owns slots and opaque handles; the policy borrows an exact
3655
+ /// packed view and returns a copied plan before any capability runs.
3656
+ 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 {
3657
+ var request: [16 + max_wire_key_bytes + requests.len * (15 + max_wire_key_bytes)]u8 = @splat(0);
3658
+ 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) };
3659
+ @memcpy(request[16..][0..key.len], key);
3660
+ var at: usize = 16 + key.len;
3661
+ for (&requests) |*entry| {
3662
+ const name = if (entry.used) entry.wireKey() else "";
3663
+ request[at] = @intFromBool(entry.used);
3664
+ request[at + 1] = @intCast(name.len);
3665
+ @memcpy(request[at + 2 ..][0..name.len], name);
3666
+ const route = at + 2 + name.len;
3667
+ request[route..][0..5].* = .{ entry.ok_tag, entry.err_tag, @intFromBool(entry.ok_void), @intFromBool(entry.service_operation != null), @intFromBool(entry.service_channel != null) };
3668
+ std.mem.writeInt(u64, request[route + 5 ..][0..8], entry.service_channel orelse 0, .little);
3669
+ at = route + 13;
3670
+ }
3671
+ var result: [16]u8 = undefined;
3672
+ if (core.nativeEffectPolicy(request[0..at], &result) != result.len or result[6] != 0 or result[7] != 0)
3673
+ @panic("ts core host: invalid compiled request plan");
3674
+ for (result[0..2]) |slot| if (slot != 255 and slot >= requests.len)
3675
+ @panic("ts core host: invalid compiled request slot");
3676
+ if (action == 0) {
3677
+ if (result[4] > 1) @panic("ts core host: invalid compiled request void flag");
3678
+ if (result[0] != 255 and requestPoolAt(result[0]) != pool) @panic("ts core host: compiled request names the wrong pool");
3679
+ 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())))
3680
+ @panic("ts core host: invalid compiled request predecessor");
3681
+ if (result[0] != 255 and requests[result[0]].used and (key.len == 0 or !std.mem.eql(u8, key, requests[result[0]].wireKey())))
3682
+ @panic("ts core host: compiled request overwrites another owner");
3683
+ } else if (action == 1) {
3684
+ if (result[0] != 255 and (!requests[result[0]].used or !std.mem.eql(u8, key, requests[result[0]].wireKey())))
3685
+ @panic("ts core host: invalid compiled request lookup");
3686
+ } else if (action == 2) {
3687
+ if (result[0] != result_slot or result[3] > 2 or result[4] > 1 or result[5] > 1 or
3688
+ (result[3] == 2 and requests[result_slot].service_operation == null) or
3689
+ (result[5] == 1 and (requests[result_slot].service_channel == null or std.mem.readInt(u64, result[8..16], .little) != requests[result_slot].service_channel.?)))
3690
+ @panic("ts core host: invalid compiled request completion");
3691
+ } else if (result[3] > 3) @panic("ts core host: invalid compiled service guard");
3692
+ return result;
3693
+ }
3694
+
3695
+ 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 {
3696
+ var request: [12 + max_wire_key_bytes + dbs.len * (7 + max_wire_key_bytes)]u8 = @splat(0);
3697
+ 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 };
3698
+ @memcpy(request[12..][0..key.len], key);
3699
+ var at: usize = 12 + key.len;
3700
+ for (&dbs) |*entry| {
3701
+ const name = if (entry.used) entry.wireKey() else "";
3702
+ 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) };
3703
+ @memcpy(request[at + 7 ..][0..name.len], name);
3704
+ at += 7 + name.len;
3705
+ }
3706
+ var result: [8]u8 = undefined;
3707
+ 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))
3708
+ @panic("ts core host: invalid compiled database command plan");
3709
+ 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))
3710
+ @panic("ts core host: compiled database command overwrites another owner");
3711
+ if (action == 1 and result[0] != result_slot) @panic("ts core host: compiled database completion changed its owner");
3712
+ return result;
3713
+ }
3714
+
3715
+ fn appendCancellationSlot(request: []u8, at: *usize, used: bool, flags: u8, key: []const u8, err_tag: u8) void {
3716
+ const name = if (used) key else "";
3717
+ request[at.*..][0..3].* = .{ @intFromBool(used), flags, @intCast(name.len) };
3718
+ @memcpy(request[at.* + 3 ..][0..name.len], name);
3719
+ request[at.* + 3 + name.len] = err_tag;
3720
+ at.* += 4 + name.len;
3721
+ }
3722
+
3723
+ fn compiledCancelWireKey(fx: *Fx, key: []const u8) void {
3724
+ const count = requests.len + effects_table.len + clipboard_writes.len + streams.len + file_streams.len + delays.len + dbs.len;
3725
+ var request: [2 + max_wire_key_bytes + count * (4 + max_wire_key_bytes)]u8 = @splat(0);
3726
+ request[0] = 12;
3727
+ request[1] = @intCast(key.len);
3728
+ @memcpy(request[2..][0..key.len], key);
3729
+ var at: usize = 2 + key.len;
3730
+ for (&requests) |*e| appendCancellationSlot(&request, &at, e.used, @intFromBool(e.service_channel != null), e.wireKey(), e.err_tag);
3731
+ for (&effects_table) |*e| appendCancellationSlot(&request, &at, e.used, @intFromBool(e.dropped), e.wireKey(), e.err_tag);
3732
+ for (&clipboard_writes) |*e| appendCancellationSlot(&request, &at, e.used, 0, e.wireKey(), e.tag);
3733
+ for (&streams) |*e| appendCancellationSlot(&request, &at, e.used, 0, e.wireKey(), e.err_tag);
3734
+ for (&file_streams) |*e| appendCancellationSlot(&request, &at, e.used, @intFromBool(e.sink), e.wireKey(), e.err_tag);
3735
+ for (&delays) |*e| appendCancellationSlot(&request, &at, e.used, 0, e.wireKey(), e.tag);
3736
+ for (&dbs) |*e| appendCancellationSlot(&request, &at, e.used, @as(u8, @intFromBool(e.query)) | (@as(u8, @intFromBool(e.live)) << 1), e.wireKey(), e.err_tag);
3737
+ var result: [8]u8 = undefined;
3738
+ if (core.nativeEffectPolicy(request[0..at], &result) != result.len or (result[0] != 255 and result[0] > 6))
3739
+ @panic("ts core host: invalid compiled cancellation plan");
3740
+ for (result[2..6]) |flag| if (flag > 1) @panic("ts core host: invalid compiled cancellation flag");
3741
+ if (result[7] > 1) @panic("ts core host: invalid compiled cancellation message flag");
3742
+ if (result[0] == 255) return;
3743
+ const slot: usize = result[1];
3744
+ // Authenticate table ownership independently of portable selection.
3745
+ const valid = switch (result[0]) {
3746
+ 0 => slot < requests.len and requests[slot].used and std.mem.eql(u8, key, requests[slot].wireKey()),
3747
+ 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()),
3748
+ 2 => slot < clipboard_writes.len and clipboard_writes[slot].used and std.mem.eql(u8, key, clipboard_writes[slot].wireKey()),
3749
+ 3 => slot < streams.len and streams[slot].used and std.mem.eql(u8, key, streams[slot].wireKey()),
3750
+ 4 => slot < file_streams.len and file_streams[slot].used and std.mem.eql(u8, key, file_streams[slot].wireKey()),
3751
+ 5 => slot < delays.len and delays[slot].used and std.mem.eql(u8, key, delays[slot].wireKey()),
3752
+ 6 => slot < dbs.len and dbs[slot].used and std.mem.eql(u8, key, dbs[slot].wireKey()),
3753
+ else => unreachable,
3754
+ };
3755
+ 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))
3756
+ @panic("ts core host: compiled cancellation names an invalid owner");
3757
+ switch (result[0]) {
3758
+ 0 => {
3759
+ if (result[3] == 1) fx.cancelHostRequest(request_key_base + slot);
3760
+ if (result[2] == 1) requests[slot].used = false;
3761
+ if (result[5] == 1) fx.closeChannel(requests[slot].service_channel.?);
3762
+ },
3763
+ 1 => if (result[3] == 1) {
3764
+ dropEffectEntry(fx, slot);
3765
+ },
3766
+ 2 => if (result[3] == 1) {
3767
+ fx.cancelNonImage(clipboard_result_key_base + slot);
3768
+ },
3769
+ 3 => if (result[3] == 1) {
3770
+ fx.cancelNonImage(spawn_key_base + slot);
3771
+ },
3772
+ 4 => {
3773
+ if (result[2] == 1) file_streams[slot].used = false;
3774
+ if (result[4] == 1) file_streams[slot].cancelling = true;
3775
+ if (result[3] == 1) fx.cancelNonImage(file_stream_key_base + slot);
3776
+ },
3777
+ 5 => {
3778
+ if (result[3] == 1) fx.cancelTimer(delay_key_base + slot);
3779
+ if (result[2] == 1) delays[slot].used = false;
3780
+ },
3781
+ 6 => {
3782
+ if (result[3] == 1) fx.cancelDbQuery(db_key_base + slot);
3783
+ if (result[2] == 1) dbs[slot].used = false;
3784
+ },
3785
+ else => unreachable,
3786
+ }
3787
+ if (result[7] == 1) fx.stageLoopMsg(msgFromTagStaticBytes(result[6], "cancelled"));
3788
+ }
3789
+
2735
3790
  fn allocDbEntry(
2736
3791
  fx: *Fx,
2737
3792
  key: []const u8,
@@ -2740,28 +3795,38 @@ pub fn TsCoreHost(comptime core: type) type {
2740
3795
  done_tag: u8,
2741
3796
  err_tag: u8,
2742
3797
  ) ?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 {
3798
+ const plan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
3799
+ compiledDbCommandPlan(0, key, reservedWireKeyOccupied(key), query, page_tag, done_tag, err_tag, 0, 0, false)
3800
+ else blk: {
3801
+ if (reservedWireKeyOccupied(key)) {
2761
3802
  fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
2762
3803
  return null;
3804
+ }
3805
+ const index = native: {
3806
+ if (key.len > 0) {
3807
+ if (findDb(key)) |existing| {
3808
+ // One-shot queries replace only earlier one-shot
3809
+ // queries. A live subscription owns its slot until
3810
+ // subscription reconciliation removes or re-arms it;
3811
+ // a command with the same wire key must reject rather
3812
+ // than silently erase that subscription.
3813
+ if (query and dbs[existing].query and !dbs[existing].live) break :native existing;
3814
+ fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
3815
+ return null;
3816
+ }
3817
+ }
3818
+ break :native freeDbIndex() orelse {
3819
+ fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
3820
+ return null;
3821
+ };
2763
3822
  };
3823
+ break :blk [8]u8{ @intCast(index), page_tag, done_tag, err_tag, 0, 0, 0, 0 };
2764
3824
  };
3825
+ if (plan[0] == 255) {
3826
+ fx.stageLoopMsg(msgFromTagStaticBytes(plan[3], "rejected"));
3827
+ return null;
3828
+ }
3829
+ const index: usize = plan[0];
2765
3830
  const entry = &dbs[index];
2766
3831
  entry.used = true;
2767
3832
  entry.query = query;
@@ -2769,13 +3834,14 @@ pub fn TsCoreHost(comptime core: type) type {
2769
3834
  entry.signature = 0;
2770
3835
  entry.key_len = key.len;
2771
3836
  @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;
3837
+ entry.page_tag = plan[1];
3838
+ entry.done_tag = plan[2];
3839
+ entry.err_tag = plan[3];
2775
3840
  return index;
2776
3841
  }
2777
3842
 
2778
3843
  fn findDb(key: []const u8) ?usize {
3844
+ if (comptime @hasDecl(core, "nativeDbPolicy")) return compiledDbLookup(key);
2779
3845
  if (key.len == 0) return null;
2780
3846
  for (&dbs, 0..) |*entry, index| {
2781
3847
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
@@ -2792,6 +3858,21 @@ pub fn TsCoreHost(comptime core: type) type {
2792
3858
  if (result.key < db_key_base) @panic("ts core host: a relational result arrived outside the bridge DB key namespace");
2793
3859
  const index = result.key - db_key_base;
2794
3860
  if (index >= dbs.len or !dbs[index].used) @panic("ts core host: a relational result arrived for an untracked command");
3861
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
3862
+ const kind: u8 = switch (result.kind) {
3863
+ .page => 0,
3864
+ .done => 1,
3865
+ .exec => 2,
3866
+ };
3867
+ const plan = compiledDbCommandPlan(1, "", false, false, 0, 0, 0, @intCast(index), kind, result.outcome == .ok);
3868
+ if (plan[6] == 1) dbs[index].used = false;
3869
+ return switch (plan[5]) {
3870
+ 0 => msgFromTagBytes(plan[4], result.bytes),
3871
+ 1 => msgFromTagVoid(plan[4]),
3872
+ 2 => msgFromTagBytes(plan[4], @tagName(result.outcome)),
3873
+ else => unreachable,
3874
+ };
3875
+ }
2795
3876
  const entry = &dbs[index];
2796
3877
  if (result.outcome != .ok) {
2797
3878
  if (!entry.live) entry.used = false;
@@ -2823,6 +3904,7 @@ pub fn TsCoreHost(comptime core: type) type {
2823
3904
  /// Unknown keys are a no-op; the audio stream is not cancel's
2824
3905
  /// to end (audio_ctl `stop` closes it).
2825
3906
  fn cancelWireKey(fx: *Fx, key: []const u8) void {
3907
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) return compiledCancelWireKey(fx, key);
2826
3908
  if (key.len == 0) return;
2827
3909
  if (findRequest(key)) |index| {
2828
3910
  const entry = requests[index];
@@ -2838,10 +3920,14 @@ pub fn TsCoreHost(comptime core: type) type {
2838
3920
  dropEffectEntry(fx, index);
2839
3921
  return;
2840
3922
  }
3923
+ if (findClipboardWrite(key)) |index| {
3924
+ fx.cancelNonImage(clipboard_result_key_base + index);
3925
+ return;
3926
+ }
2841
3927
  if (findStream(key)) |index| {
2842
3928
  // The engine's `.cancelled` terminal retires the entry in
2843
3929
  // spawnExitMsg or fetchStreamResultMsg.
2844
- fx.cancel(spawn_key_base + index);
3930
+ fx.cancelNonImage(spawn_key_base + index);
2845
3931
  return;
2846
3932
  }
2847
3933
  if (findFileStream(key)) |index| {
@@ -2852,7 +3938,7 @@ pub fn TsCoreHost(comptime core: type) type {
2852
3938
  } else {
2853
3939
  file_streams[index].cancelling = true;
2854
3940
  }
2855
- fx.cancel(file_stream_key_base + index);
3941
+ fx.cancelNonImage(file_stream_key_base + index);
2856
3942
  return;
2857
3943
  }
2858
3944
  if (findDelay(key)) |index| {
@@ -2877,7 +3963,7 @@ pub fn TsCoreHost(comptime core: type) type {
2877
3963
  }
2878
3964
  }
2879
3965
 
2880
- const RequestPool = enum { host, store, credentials };
3966
+ const RequestPool = enum(u8) { host, store, credentials };
2881
3967
 
2882
3968
  fn requestPoolAt(index: usize) RequestPool {
2883
3969
  if (index < runtime_effects.max_effects) return .host;
@@ -2895,36 +3981,51 @@ pub fn TsCoreHost(comptime core: type) type {
2895
3981
  err_tag: u8,
2896
3982
  ok_void: bool,
2897
3983
  pool: RequestPool,
3984
+ reject_duplicate: bool,
2898
3985
  ) ?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;
3986
+ const plan = if (comptime @hasDecl(core, "nativeEffectPolicy"))
3987
+ compiledRequestPlan(0, pool, key, reservedWireKeyOccupied(key), reject_duplicate, ok_tag, err_tag, ok_void, false, 0, false)
3988
+ else blk: {
3989
+ if (reject_duplicate and key.len > 0 and findRequest(key) != null) return null;
3990
+ if (reservedWireKeyOccupied(key)) return null;
3991
+ const index = native: {
3992
+ if (key.len > 0) {
3993
+ if (findRequest(key)) |existing| {
3994
+ if (requestPoolAt(existing) == pool) break :native existing;
3995
+ fx.cancelHostRequest(request_key_base + existing);
3996
+ requests[existing].used = false;
3997
+ }
2906
3998
  }
2907
- }
2908
- break :blk switch (pool) {
2909
- .host => freeRequestIndex(),
2910
- .store => freeStoreRequestIndex(),
2911
- .credentials => freeCredentialsRequestIndex(),
2912
- } orelse return null;
3999
+ break :native switch (pool) {
4000
+ .host => freeRequestIndex(),
4001
+ .store => freeStoreRequestIndex(),
4002
+ .credentials => freeCredentialsRequestIndex(),
4003
+ } orelse return null;
4004
+ };
4005
+ var result: [16]u8 = @splat(0);
4006
+ result[0..5].* = .{ @intCast(index), 255, ok_tag, err_tag, @intFromBool(ok_void) };
4007
+ break :blk result;
2913
4008
  };
4009
+ if (plan[1] != 255) {
4010
+ fx.cancelHostRequest(request_key_base + plan[1]);
4011
+ requests[plan[1]].used = false;
4012
+ }
4013
+ if (plan[0] == 255) return null;
4014
+ const index: usize = plan[0];
2914
4015
  const entry = &requests[index];
2915
4016
  entry.used = true;
2916
4017
  entry.key_len = key.len;
2917
4018
  @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;
4019
+ entry.ok_tag = plan[2];
4020
+ entry.err_tag = plan[3];
4021
+ entry.ok_void = plan[4] == 1;
2921
4022
  entry.service_operation = null;
2922
4023
  entry.service_channel = null;
2923
4024
  return index;
2924
4025
  }
2925
4026
 
2926
4027
  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 {
4028
+ const index = allocRequestEntry(fx, head.key, head.ok_tag, head.err_tag, ok_void, .store, false) orelse {
2928
4029
  fx.stageLoopMsg(msgFromTagStaticBytes(head.err_tag, "rejected"));
2929
4030
  return null;
2930
4031
  };
@@ -2932,7 +4033,7 @@ pub fn TsCoreHost(comptime core: type) type {
2932
4033
  }
2933
4034
 
2934
4035
  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 {
4036
+ const index = allocRequestEntry(fx, key, ok_tag, err_tag, ok_void, .credentials, false) orelse {
2936
4037
  fx.stageLoopMsg(msgFromTagStaticBytes(err_tag, "rejected"));
2937
4038
  return null;
2938
4039
  };
@@ -2950,11 +4051,7 @@ pub fn TsCoreHost(comptime core: type) type {
2950
4051
  issueCredentialsRequest(fx, name, key, ok_tag, err_tag, payload);
2951
4052
  return;
2952
4053
  }
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 {
4054
+ const index = allocRequestEntry(fx, key, ok_tag, err_tag, false, .host, typed_service or fx.rejectsDuplicateHostRequestKeys()) orelse {
2958
4055
  stageRequestRejected(fx, err_tag);
2959
4056
  return;
2960
4057
  };
@@ -2977,6 +4074,34 @@ pub fn TsCoreHost(comptime core: type) type {
2977
4074
  }
2978
4075
 
2979
4076
  fn issueCredentialsRequest(fx: *Fx, name: []const u8, key: []const u8, ok_tag: u8, err_tag: u8, payload: []const u8) void {
4077
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4078
+ if (name.len > 255) {
4079
+ stageRequestRejected(fx, err_tag);
4080
+ return;
4081
+ }
4082
+ const request = core.rt.frameAlloc(u8, 2 + name.len + payload.len);
4083
+ request[0] = 13;
4084
+ request[1] = @intCast(name.len);
4085
+ @memcpy(request[2..][0..name.len], name);
4086
+ @memcpy(request[2 + name.len ..], payload);
4087
+ var plan: [20]u8 = undefined;
4088
+ if (core.nativeEffectPolicy(request, &plan) != plan.len or plan[0] > 1 or plan[1] > 2 or plan[2] != 0 or plan[3] != 0)
4089
+ @panic("ts core host: invalid compiled credential plan");
4090
+ if (plan[0] == 0) {
4091
+ stageRequestRejected(fx, err_tag);
4092
+ return;
4093
+ }
4094
+ const credential_key = credentialPlanBytes(payload, plan[4..12]);
4095
+ const secret = if (plan[1] == 0) credentialPlanBytes(payload, plan[12..20]) else "";
4096
+ const request_key = allocCredentialsRequestEntry(fx, key, ok_tag, err_tag, plan[1] != 1) orelse return;
4097
+ switch (plan[1]) {
4098
+ 0 => fx.credentialsSet(.{ .key = request_key, .credential_key = credential_key, .secret = secret, .host_result = hostResultMsg }),
4099
+ 1 => fx.credentialsGet(.{ .key = request_key, .credential_key = credential_key, .host_result = hostResultMsg }),
4100
+ 2 => fx.credentialsDelete(.{ .key = request_key, .credential_key = credential_key, .host_result = hostResultMsg }),
4101
+ else => unreachable,
4102
+ }
4103
+ return;
4104
+ }
2980
4105
  const is_set = std.mem.eql(u8, name, "core.credentials.set");
2981
4106
  const is_get = std.mem.eql(u8, name, "core.credentials.get");
2982
4107
  const is_delete = std.mem.eql(u8, name, "core.credentials.delete");
@@ -3033,6 +4158,13 @@ pub fn TsCoreHost(comptime core: type) type {
3033
4158
  }
3034
4159
  }
3035
4160
 
4161
+ fn credentialPlanBytes(payload: []const u8, span: *const [8]u8) []const u8 {
4162
+ const offset: usize = std.mem.readInt(u32, span[0..4], .little);
4163
+ const length: usize = std.mem.readInt(u32, span[4..8], .little);
4164
+ if (offset > payload.len or length > payload.len - offset) @panic("ts core host: compiled credential span is outside its borrowed packet");
4165
+ return payload[offset .. offset + length];
4166
+ }
4167
+
3036
4168
  /// Credential records can also arrive through public `Cmd.request`,
3037
4169
  /// so their inner fields are untrusted even though the outer command
3038
4170
  /// wire was emitted correctly. Decode them fallibly and route a
@@ -3064,27 +4196,48 @@ pub fn TsCoreHost(comptime core: type) type {
3064
4196
  max_pending: u8,
3065
4197
  payload: []const u8,
3066
4198
  ) 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 }));
4199
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4200
+ const channel_key = exactEngineKey(channel_value);
4201
+ const occupied = if (channel_key) |value| findChannel(value) != null or fx.channelHandle(value) != null else false;
4202
+ const plan = compiledRequestPlan(3, .host, key, reservedWireKeyOccupied(key), true, ok_tag, err_tag, false, false, 0, occupied);
4203
+ switch (plan[3]) {
4204
+ 0 => {},
4205
+ 1 => {
4206
+ stageRequestRejected(fx, err_tag);
4207
+ return;
4208
+ },
4209
+ 2 => @panic("ts core host: more than 16 host requests in flight - the request table mirrors the engine's max_effects slots"),
4210
+ 3 => {
4211
+ const value = channel_key orelse @panic("ts core host: compiled service refusal names an invalid channel");
4212
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = value, .kind = .rejected }));
4213
+ stageRequestRejected(fx, err_tag);
4214
+ return;
4215
+ },
4216
+ else => unreachable,
4217
+ }
4218
+ } else {
4219
+ if (key.len > 0 and (findRequest(key) != null or reservedWireKeyOccupied(key))) {
3085
4220
  stageRequestRejected(fx, err_tag);
3086
4221
  return;
3087
4222
  }
4223
+ // Fail the existing request-table bound before opening a channel;
4224
+ // an admission failure must not leave an orphaned stream.
4225
+ if (freeRequestIndex() == null) {
4226
+ @panic("ts core host: more than 16 host requests in flight - the request table mirrors the engine's max_effects slots");
4227
+ }
4228
+
4229
+ const channel_key = exactEngineKey(channel_value);
4230
+ if (channel_key) |value| {
4231
+ // `findChannel` covers every TS bridge occupancy, including a
4232
+ // rejected terminal waiting to drain. `channelHandle` also
4233
+ // sees an open embedder-owned channel and replay's parked
4234
+ // occupancy. Never let this service acquire either one.
4235
+ if (findChannel(value) != null or fx.channelHandle(value) != null) {
4236
+ fx.stageLoopMsg(msgFromTagChannel(event_tag, .{ .key = value, .kind = .rejected }));
4237
+ stageRequestRejected(fx, err_tag);
4238
+ return;
4239
+ }
4240
+ }
3088
4241
  }
3089
4242
 
3090
4243
  // Validation/table refusals generated by the bridge are final for
@@ -3101,6 +4254,10 @@ pub fn TsCoreHost(comptime core: type) type {
3101
4254
  }
3102
4255
 
3103
4256
  fn findRequest(key: []const u8) ?usize {
4257
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4258
+ const plan = compiledRequestPlan(1, .host, key, false, false, 0, 0, false, false, 0, false);
4259
+ return if (plan[0] == 255) null else plan[0];
4260
+ }
3104
4261
  for (&requests, 0..) |*entry, index| {
3105
4262
  if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
3106
4263
  }
@@ -3144,6 +4301,18 @@ pub fn TsCoreHost(comptime core: type) type {
3144
4301
  if (index >= requests.len or !requests[index].used) {
3145
4302
  @panic("ts core host: a host result arrived for a request the bridge is not tracking");
3146
4303
  }
4304
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4305
+ const plan = compiledRequestPlan(2, .host, "", false, false, 0, 0, false, result.ok, @intCast(index), false);
4306
+ const entry = requests[index];
4307
+ if (plan[4] == 1) requests[index].used = false;
4308
+ if (plan[5] == 1) pending_service_channel_close = std.mem.readInt(u64, plan[8..16], .little);
4309
+ return switch (plan[3]) {
4310
+ 0 => msgFromTagBytes(plan[2], result.bytes),
4311
+ 1 => msgFromTagVoid(plan[2]),
4312
+ 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),
4313
+ else => unreachable,
4314
+ };
4315
+ }
3147
4316
  const entry = &requests[index];
3148
4317
  entry.used = false;
3149
4318
  if (entry.service_channel) |channel_key| pending_service_channel_close = channel_key;
@@ -3163,17 +4332,72 @@ pub fn TsCoreHost(comptime core: type) type {
3163
4332
  /// Retire the named-op entry an engine terminal names and hand
3164
4333
  /// back its routing tags plus whether the entry was dropped —
3165
4334
  /// 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) {
4335
+ const EffectSuccess = enum(u8) { void_msg, bytes, stat, response };
4336
+ const EffectPayload = enum(u8) { swallow, void_msg, bytes, stat, response, reason };
4337
+ const EffectCompletion = struct { tag: u8, payload: EffectPayload, reason: u8 };
4338
+
4339
+ const BufferedFamily = enum(u8) { file, complete_file, fetch, clipboard };
4340
+ const BufferedCompletion = struct { slot: usize, tag: u8, payload: u8, reason: u8, swallow: bool };
4341
+
4342
+ fn bufferedCompletion(key: u64, family: BufferedFamily, operation: u8, outcome: u8, truncated: bool) BufferedCompletion {
4343
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4344
+ var request: [88]u8 = @splat(0);
4345
+ request[0..5].* = .{ 17, @intFromEnum(family), operation, outcome, @intFromBool(truncated) };
4346
+ std.mem.writeInt(u64, request[8..16], key, .little);
4347
+ std.mem.writeInt(u64, request[16..24], effect_key_base, .little);
4348
+ for (&effects_table, 0..) |*entry, slot| {
4349
+ request[24 + slot * 4 ..][0..4].* = .{ @intFromBool(entry.used), @intFromBool(entry.dropped), entry.ok_tag, entry.err_tag };
4350
+ }
4351
+ var result: [8]u8 = undefined;
4352
+ if (core.nativeEffectPolicy(&request, &result) != result.len or result[0] >= effects_table.len or
4353
+ !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)
4354
+ @panic("ts core host: invalid compiled buffered completion plan");
4355
+ if (result[4] == 1) effects_table[result[0]].used = false;
4356
+ return .{ .slot = result[0], .tag = result[1], .payload = result[2], .reason = result[3], .swallow = result[5] == 1 };
4357
+ }
4358
+ const success: EffectSuccess = switch (family) {
4359
+ .file => if (operation == @intFromEnum(runtime_effects.EffectFileOp.read)) .bytes else if (operation == @intFromEnum(runtime_effects.EffectFileOp.stat)) .stat else .void_msg,
4360
+ .complete_file => .void_msg,
4361
+ .fetch => .response,
4362
+ .clipboard => .bytes,
4363
+ };
4364
+ const route = takeEffectEntry(key, success, family == .complete_file or outcome == 0, truncated);
4365
+ 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 };
4366
+ }
4367
+
4368
+ fn takeEffectEntry(key: u64, success: EffectSuccess, ok: bool, truncated: bool) EffectCompletion {
4369
+ if (key < effect_key_base)
3168
4370
  @panic("ts core host: an effect terminal arrived outside the bridge's named-op key namespace");
3169
- }
3170
4371
  const index = key - effect_key_base;
3171
- if (index >= effects_table.len or !effects_table[index].used) {
4372
+ if (index >= effects_table.len or !effects_table[index].used)
3172
4373
  @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 };
4374
+ const plan = if (comptime @hasDecl(core, "nativeEffectPolicy")) blk: {
4375
+ var request: [69]u8 = undefined;
4376
+ request[0] = 2;
4377
+ request[1] = @intCast(index);
4378
+ request[2] = @intFromEnum(success);
4379
+ request[3] = @intFromBool(ok);
4380
+ request[4] = @intFromBool(truncated);
4381
+ for (&effects_table, 0..) |*entry, slot| {
4382
+ const at = 5 + slot * 4;
4383
+ request[at] = @intFromBool(entry.used);
4384
+ request[at + 1] = @intFromBool(entry.dropped);
4385
+ request[at + 2] = entry.ok_tag;
4386
+ request[at + 3] = entry.err_tag;
4387
+ }
4388
+ var result: [4]u8 = undefined;
4389
+ if (core.nativeEffectPolicy(&request, &result) != result.len or result[0] != index or result[2] > 5 or result[3] > 2)
4390
+ @panic("ts core host: invalid compiled effect completion result");
4391
+ break :blk EffectCompletion{ .tag = result[1], .payload = @enumFromInt(result[2]), .reason = result[3] };
4392
+ } else blk: {
4393
+ const entry = &effects_table[index];
4394
+ if (entry.dropped) break :blk EffectCompletion{ .tag = entry.err_tag, .payload = .swallow, .reason = 0 };
4395
+ const cut = success == .response and truncated;
4396
+ if (ok and !cut) break :blk EffectCompletion{ .tag = entry.ok_tag, .payload = @enumFromInt(@intFromEnum(success) + 1), .reason = 0 };
4397
+ break :blk EffectCompletion{ .tag = entry.err_tag, .payload = .reason, .reason = if (ok and cut) 2 else 1 };
4398
+ };
4399
+ effects_table[index].used = false;
4400
+ return plan;
3177
4401
  }
3178
4402
 
3179
4403
  /// A dropped entry's terminal (the `.cancelled` end of a
@@ -3191,15 +4415,73 @@ pub fn TsCoreHost(comptime core: type) type {
3191
4415
  /// arm; every non-ok outcome routes the err arm with the
3192
4416
  /// outcome's name as bytes. A dropped entry's terminal routes
3193
4417
  /// nothing — the silent drop.
4418
+ fn parseExactUnsigned(decimal: []const u8) ?u64 {
4419
+ if (decimal.len == 0 or decimal.len > 20 or (decimal.len > 1 and decimal[0] == '0')) return null;
4420
+ for (decimal) |byte| if (byte < '0' or byte > '9') return null;
4421
+ return std.fmt.parseInt(u64, decimal, 10) catch null;
4422
+ }
4423
+
4424
+ fn parseExactTimerInterval(decimal: []const u8) ?u64 {
4425
+ const value = parseExactUnsigned(decimal) orelse return null;
4426
+ if (value > std.math.maxInt(u64) / std.time.ns_per_ms) return null;
4427
+ return value;
4428
+ }
4429
+
4430
+ fn armResultTimer(fx: *Fx, key: []const u8, ms: f64, tag: u8, mode: runtime_effects.TimerMode, native_range: bool) void {
4431
+ 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);
4432
+ const plan: ?DelayPlan = if (comptime @hasDecl(core, "nativeTimerPolicy")) compiledDelayDeclarationRange(key, ms, tag, blocked, true, native_range) else blk: {
4433
+ 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;
4434
+ const slot = (if (key.len > 0) findDelay(key) orelse freeDelayIndex() else freeDelayIndex()) orelse break :blk null;
4435
+ break :blk .{ .slot = slot, .tag = tag, .interval_ms = intervalMs(ms) };
4436
+ };
4437
+ const admitted = plan orelse {
4438
+ fx.stageLoopMsg(msgFromTimerResult(tag, .{ .key = 0, .outcome = .rejected }, fx.stageLoopKey(key)));
4439
+ return;
4440
+ };
4441
+ const entry = &delays[admitted.slot];
4442
+ entry.used = true;
4443
+ entry.full_result = true;
4444
+ entry.mode = mode;
4445
+ entry.key_len = key.len;
4446
+ @memcpy(entry.key[0..key.len], key);
4447
+ entry.tag = admitted.tag;
4448
+ fx.startTimer(.{ .key = delay_key_base + admitted.slot, .interval_ms = admitted.interval_ms, .mode = mode, .on_fire = delayFireMsg });
4449
+ }
4450
+ fn decimalFrame(value: anytype) []const u8 {
4451
+ var buffer: [21]u8 = undefined;
4452
+ const text = std.fmt.bufPrint(&buffer, "{d}", .{value}) catch unreachable;
4453
+ if (value == 0) return "0";
4454
+ const owned = core.rt.frameAlloc(u8, text.len);
4455
+ @memcpy(owned, text);
4456
+ return owned;
4457
+ }
4458
+ fn msgFromTimerResult(tag: u8, timer: runtime_effects.EffectTimer, key: []const u8) Msg {
4459
+ return msgFromCapability(tag, .{ .key = key, .timestampNs = decimalFrame(timer.timestamp_ns), .outcome = timer.outcome });
4460
+ }
4461
+ fn stageFileRejected(fx: *Fx, head: RoutedHead, operation: runtime_effects.EffectFileOp) void {
4462
+ fx.stageLoopMsg(msgFromFileResult(head.ok_tag, .{ .key = 0, .op = operation, .outcome = .rejected }, fx.stageLoopKey(head.key)));
4463
+ }
4464
+ fn msgFromFileResult(tag: u8, result: runtime_effects.EffectFileResult, key: []const u8) Msg {
4465
+ 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 });
4466
+ }
4467
+ fn completeFileResultMsg(result: runtime_effects.EffectFileResult) Msg {
4468
+ const route = bufferedCompletion(result.key, .complete_file, @intFromEnum(result.op), @intFromEnum(result.outcome), false);
4469
+ if (route.payload != 6) @panic("ts core host: complete file received an incompatible payload plan");
4470
+ if (route.swallow) swallow_next_dispatch = true;
4471
+ return msgFromFileResult(route.tag, result, effects_table[route.slot].wireKey());
4472
+ }
4473
+
3194
4474
  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));
4475
+ const route = bufferedCompletion(result.key, .file, @intFromEnum(result.op), @intFromEnum(result.outcome), false);
4476
+ if (route.payload > 5) @panic("ts core host: file completion received an incompatible payload plan");
4477
+ return switch (@as(EffectPayload, @enumFromInt(route.payload))) {
4478
+ .swallow => swallowedMsg(route.tag),
4479
+ .void_msg => msgFromTagVoid(route.tag),
4480
+ .bytes => msgFromTagBytes(route.tag, result.bytes),
4481
+ .stat => msgFromTagFileStat(route.tag, result),
4482
+ .reason => msgFromTagBytes(route.tag, @tagName(result.outcome)),
4483
+ .response => @panic("ts core host: file completion received a response payload plan"),
4484
+ };
3203
4485
  }
3204
4486
 
3205
4487
  fn msgFromTagFileStat(tag: u8, result: runtime_effects.EffectFileResult) Msg {
@@ -3231,43 +4513,178 @@ pub fn TsCoreHost(comptime core: type) type {
3231
4513
  /// routes the err arm with the reason as bytes. A dropped
3232
4514
  /// entry's terminal routes nothing — the silent drop.
3233
4515
  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);
4516
+ const route = bufferedCompletion(response.key, .fetch, 0, @intFromEnum(response.outcome), response.truncated);
4517
+ if (route.payload > 5) @panic("ts core host: fetch completion received an incompatible payload plan");
4518
+ return switch (@as(EffectPayload, @enumFromInt(route.payload))) {
4519
+ .swallow => swallowedMsg(route.tag),
4520
+ .response => msgFromTagNumberBytes("fetch response", "{ status, body }", route.tag, response.status, response.body),
4521
+ .reason => msgFromTagBytes(route.tag, if (route.reason == 2) "truncated" else @tagName(response.outcome)),
4522
+ else => @panic("ts core host: fetch completion received an incompatible payload plan"),
4523
+ };
3241
4524
  }
3242
4525
 
3243
4526
  /// `ClipboardMsgFn` for clip_read (writes are fire-and-forget
3244
4527
  /// and never route): ok routes the text bytes, everything else
3245
4528
  /// the outcome name. A dropped entry's terminal routes nothing
3246
4529
  /// — the silent drop.
4530
+ fn compiledClipboardWritePlan(action: u8, key: []const u8, blocked: bool, slot: u8, tag: u8) [4]u8 {
4531
+ var request: [8 + max_wire_key_bytes + clipboard_writes.len * (3 + max_wire_key_bytes)]u8 = @splat(0);
4532
+ request[0..8].* = .{ 16, action, @intCast(key.len), @intFromBool(blocked), slot, tag, 0, 0 };
4533
+ @memcpy(request[8..][0..key.len], key);
4534
+ var at: usize = 8 + key.len;
4535
+ for (&clipboard_writes) |*entry| {
4536
+ const name = if (entry.used) entry.wireKey() else "";
4537
+ request[at..][0..3].* = .{ @intFromBool(entry.used), entry.tag, @intCast(name.len) };
4538
+ @memcpy(request[at + 3 ..][0..name.len], name);
4539
+ at += 3 + name.len;
4540
+ }
4541
+ var result: [4]u8 = undefined;
4542
+ 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))
4543
+ @panic("ts core host: invalid compiled clipboard write plan");
4544
+ if (action == 2) {
4545
+ if (result[0] != slot) @panic("ts core host: invalid compiled clipboard completion owner");
4546
+ } else if (result[0] != 255) {
4547
+ const entry = &clipboard_writes[result[0]];
4548
+ if (action == 0 and (key.len == 0 or !entry.used or !std.mem.eql(u8, entry.wireKey(), key)))
4549
+ @panic("ts core host: invalid compiled clipboard lookup owner");
4550
+ if (action == 1 and entry.used) @panic("ts core host: compiled clipboard overwrites another owner");
4551
+ }
4552
+ return result;
4553
+ }
4554
+
4555
+ fn findClipboardWrite(key: []const u8) ?usize {
4556
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4557
+ const plan = compiledClipboardWritePlan(0, key, false, 0, 0);
4558
+ return if (plan[0] == 255) null else plan[0];
4559
+ }
4560
+ if (key.len == 0) return null;
4561
+ for (&clipboard_writes, 0..) |*entry, index| if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) return index;
4562
+ return null;
4563
+ }
4564
+ fn issueClipboardWrite(fx: *Fx, key: []const u8, tag: u8, bytes: []const u8) void {
4565
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4566
+ const plan = compiledClipboardWritePlan(1, key, reservedWireKeyOccupied(key) or wireKeyOccupiedOutsideFileStreams(key), 0, tag);
4567
+ if (plan[0] == 255) {
4568
+ fx.stageLoopMsg(msgFromClipboard(plan[1], .{ .key = 0, .outcome = .rejected }, fx.stageLoopKey(key)));
4569
+ return;
4570
+ }
4571
+ clipboard_writes[plan[0]] = .{ .used = true, .key = undefined, .key_len = key.len, .tag = plan[1] };
4572
+ @memcpy(clipboard_writes[plan[0]].key[0..key.len], key);
4573
+ fx.writeClipboard(.{ .key = clipboard_result_key_base + plan[0], .text = bytes, .on_result = clipboardWriteResultMsg });
4574
+ return;
4575
+ }
4576
+ var slot: ?usize = null;
4577
+ if (!reservedWireKeyOccupied(key) and !wireKeyOccupiedOutsideFileStreams(key)) {
4578
+ for (&clipboard_writes, 0..) |*entry, index| if (!entry.used) {
4579
+ slot = index;
4580
+ break;
4581
+ };
4582
+ }
4583
+ const index = slot orelse {
4584
+ fx.stageLoopMsg(msgFromClipboard(tag, .{ .key = 0, .outcome = .rejected }, fx.stageLoopKey(key)));
4585
+ return;
4586
+ };
4587
+ clipboard_writes[index] = .{ .used = true, .key = undefined, .key_len = key.len, .tag = tag };
4588
+ @memcpy(clipboard_writes[index].key[0..key.len], key);
4589
+ fx.writeClipboard(.{ .key = clipboard_result_key_base + index, .text = bytes, .on_result = clipboardWriteResultMsg });
4590
+ }
4591
+ fn clipboardWriteResultMsg(result: runtime_effects.EffectClipboardResult) Msg {
4592
+ if (result.key < clipboard_result_key_base) @panic("ts core host: clipboard result outside its namespace");
4593
+ const index = result.key - clipboard_result_key_base;
4594
+ if (index >= clipboard_writes.len or !clipboard_writes[index].used) @panic("ts core host: untracked clipboard completion");
4595
+ const entry = &clipboard_writes[index];
4596
+ if (comptime @hasDecl(core, "nativeEffectPolicy")) {
4597
+ const plan = compiledClipboardWritePlan(2, "", false, @intCast(index), 0);
4598
+ if (plan[2] == 1) entry.used = false;
4599
+ return msgFromClipboard(plan[1], result, entry.wireKey());
4600
+ }
4601
+ entry.used = false;
4602
+ return msgFromClipboard(entry.tag, result, entry.wireKey());
4603
+ }
4604
+ /// Match complete capability records by field NAME and type. Bytes are
4605
+ /// borrowed only until this dispatch; the core ABI copies all retained
4606
+ /// values into its committed graph. Native engine keys remain private.
4607
+ fn msgFromCapability(tag: u8, record: anytype) Msg {
4608
+ inline for (msg_arms, 0..) |arm, index| {
4609
+ if (tag == index) {
4610
+ if (comptime @typeInfo(arm.type) == .@"struct" and @typeInfo(arm.type).@"struct".fields.len == @typeInfo(@TypeOf(record)).@"struct".fields.len) {
4611
+ var result: arm.type = undefined;
4612
+ inline for (@typeInfo(arm.type).@"struct".fields) |field| {
4613
+ if (comptime @hasField(@TypeOf(record), field.name)) {
4614
+ const value = @field(record, field.name);
4615
+ const V = @TypeOf(value);
4616
+ if (comptime @typeInfo(V) == .@"enum" and @typeInfo(field.type) == .@"enum") {
4617
+ @field(result, field.name) = std.meta.stringToEnum(field.type, @tagName(value)) orelse @panic("ts core host: incomplete capability enum");
4618
+ } else if (comptime (@typeInfo(V) == .int or @typeInfo(V) == .comptime_int) and field.type == f64) {
4619
+ @field(result, field.name) = @floatFromInt(value);
4620
+ } else if (comptime (@typeInfo(V) == .int or @typeInfo(V) == .comptime_int) and (@typeInfo(field.type) == .int)) {
4621
+ @field(result, field.name) = @intCast(value);
4622
+ } else if (comptime V == f32 and field.type == f64) {
4623
+ @field(result, field.name) = value;
4624
+ } else if (comptime V == field.type) {
4625
+ @field(result, field.name) = value;
4626
+ } else @panic("ts core host: incompatible capability field type");
4627
+ } else @panic("ts core host: missing capability field");
4628
+ }
4629
+ return @unionInit(Msg, arm.name, result);
4630
+ }
4631
+ @panic("ts core host: invalid capability record arm");
4632
+ }
4633
+ }
4634
+ @panic("ts core host: invalid capability message tag");
4635
+ }
4636
+ fn msgFromSpawnLine(tag: u8, line: runtime_effects.EffectLine, key: []const u8) Msg {
4637
+ return msgFromCapability(tag, .{ .key = key, .line = line.line, .truncated = line.truncated, .droppedBefore = line.dropped_before });
4638
+ }
4639
+ fn msgFromSpawnExit(tag: u8, exit: runtime_effects.EffectExit, key: []const u8) Msg {
4640
+ 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 });
4641
+ }
4642
+ fn msgFromClipboard(tag: u8, result: runtime_effects.EffectClipboardResult, key: []const u8) Msg {
4643
+ return msgFromCapability(tag, .{ .key = key, .operation = result.op, .outcome = result.outcome, .text = result.text, .droppedBefore = result.dropped_before });
4644
+ }
4645
+ fn msgFromVideoSnapshot(tag: u8, snapshot: Fx.VideoSnapshot, key: []const u8) Msg {
4646
+ 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 });
4647
+ }
4648
+
3247
4649
  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));
4650
+ const route = bufferedCompletion(result.key, .clipboard, 0, @intFromEnum(result.outcome), false);
4651
+ if (route.payload > 5) @panic("ts core host: clipboard completion received an incompatible payload plan");
4652
+ return switch (@as(EffectPayload, @enumFromInt(route.payload))) {
4653
+ .swallow => swallowedMsg(route.tag),
4654
+ .bytes => msgFromTagBytes(route.tag, result.text),
4655
+ .reason => msgFromTagBytes(route.tag, @tagName(result.outcome)),
4656
+ else => @panic("ts core host: clipboard completion received an incompatible payload plan"),
4657
+ };
3252
4658
  }
3253
4659
 
3254
4660
  /// `TimerMsgFn` for one-shot delays: the slot retires on fire
3255
4661
  /// (platform one-shots self-stop) and the named arm dispatches
3256
4662
  /// with the fire time in fractional milliseconds.
3257
4663
  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)");
4664
+ if (comptime @hasDecl(core, "nativeTimerPolicy")) {
4665
+ const plan = compiledTimerCompletion(timer, false);
4666
+ const entry = &delays[plan[0]];
4667
+ if (plan[3] == 1) entry.used = false;
4668
+ return timerCompletionMsg(plan, timer, entry.wireKey());
3260
4669
  }
3261
4670
  if (timer.key < delay_key_base) {
3262
4671
  @panic("ts core host: a delay fired outside the bridge's delay key namespace");
3263
4672
  }
3264
4673
  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");
4674
+ if (index >= delays.len) @panic("ts core host: a delay fired outside the bridge's delay table");
4675
+ const completion = blk: {
4676
+ if (!delays[index].used) @panic("ts core host: a delay fired for a slot the bridge is not tracking");
4677
+ break :blk .{ .slot = @as(usize, @intCast(index)), .tag = delays[index].tag };
4678
+ };
4679
+ const entry = &delays[completion.slot];
4680
+ if (entry.full_result) {
4681
+ if (entry.mode == .one_shot or timer.outcome == .rejected) entry.used = false;
4682
+ return msgFromTimerResult(completion.tag, timer, entry.wireKey());
3267
4683
  }
3268
- delays[index].used = false;
4684
+ if (timer.outcome == .rejected) @panic("ts core host: the platform rejected a Cmd.delay timer");
4685
+ entry.used = false;
3269
4686
  const ms = @as(f64, @floatFromInt(timer.timestamp_ns)) / std.time.ns_per_ms;
3270
- return msgFromTagNumber(delays[index].tag, ms);
4687
+ return msgFromTagNumber(completion.tag, ms);
3271
4688
  }
3272
4689
 
3273
4690
  // ----------------------------------------------- subscriptions
@@ -3280,9 +4697,20 @@ pub fn TsCoreHost(comptime core: type) type {
3280
4697
  /// everywhere, so record/replay walk identical tables.
3281
4698
  fn reconcileSubscriptions(fx: *Fx) void {
3282
4699
  if (comptime !has_subscriptions) return;
3283
- const subs = core.subscriptions(model_root);
4700
+ const borrowed_subs = if (comptime use_runtime_model) core.runtimeSubscriptions(model_root) else core.subscriptions(model_root);
4701
+ // A cycle policy may allocate in the compiler frame. Keep the
4702
+ // stream in the shim arena, and reset both only in finishCycle.
4703
+ const subs = if (comptime @hasDecl(core, "nativeTimerPolicy") or @hasDecl(core, "nativeDbPolicy") or @hasDecl(core, "nativeEffectPolicy")) blk: {
4704
+ const copy = core.rt.frameAlloc(u8, borrowed_subs.len);
4705
+ @memcpy(copy, borrowed_subs);
4706
+ break :blk copy;
4707
+ } else borrowed_subs;
3284
4708
  var seen_timers = [_]bool{false} ** timers.len;
3285
4709
  var seen_db = [_]bool{false} ** dbs.len;
4710
+ var declared_shortcuts: [platform.max_global_shortcuts]DeclaredShortcut = undefined;
4711
+ var declared_shortcut_count: usize = 0;
4712
+ var rejected_now: [platform.max_global_shortcuts]u64 = undefined;
4713
+ var rejected_now_count: usize = 0;
3286
4714
 
3287
4715
  // Free live DB slots whose wire keys disappeared before the pass
3288
4716
  // allocates replacements. Otherwise two independently valid sets
@@ -3307,18 +4735,51 @@ pub fn TsCoreHost(comptime core: type) type {
3307
4735
  const every_bits = takeBytes(subs, &at, 8);
3308
4736
  const every_ms: f64 = @bitCast(std.mem.readInt(u64, every_bits[0..8], .little));
3309
4737
  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) {
4738
+ if (comptime @hasDecl(core, "nativeTimerPolicy")) {
4739
+ const plan = compiledTimerDeclaration(key, every_ms, tag, &seen_timers);
4740
+ const entry = &timers[plan.slot];
4741
+ entry.used = true;
4742
+ entry.key_len = key.len;
4743
+ @memcpy(entry.key[0..key.len], key);
4744
+ entry.every_ms = every_ms;
4745
+ entry.tag = plan.tag;
4746
+ if (plan.start) fx.startTimer(.{
4747
+ .key = timer_key_base + plan.slot,
4748
+ .interval_ms = plan.interval_ms,
4749
+ .mode = .repeating,
4750
+ .on_fire = timerFireMsg,
4751
+ });
4752
+ } else {
4753
+ if (!(every_ms >= 1) or !(every_ms <= 31_536_000_000.0)) {
4754
+ @panic("ts core host: Sub.timer interval must be between 1ms and one year");
4755
+ }
4756
+ var slot: ?usize = null;
4757
+ for (&timers, 0..) |*entry, index| {
4758
+ if (entry.used and std.mem.eql(u8, entry.wireKey(), key)) slot = index;
4759
+ }
4760
+ if (slot) |index| {
4761
+ seen_timers[index] = true;
4762
+ const entry = &timers[index];
4763
+ if (entry.every_ms != every_ms) {
4764
+ entry.every_ms = every_ms;
4765
+ fx.startTimer(.{
4766
+ .key = timer_key_base + index,
4767
+ .interval_ms = intervalMs(every_ms),
4768
+ .mode = .repeating,
4769
+ .on_fire = timerFireMsg,
4770
+ });
4771
+ }
4772
+ entry.tag = tag;
4773
+ } else {
4774
+ const index = freeTimerIndex() orelse
4775
+ @panic("ts core host: more than 16 subscription timers - the timer table mirrors the engine's max_effect_timers");
4776
+ seen_timers[index] = true;
4777
+ const entry = &timers[index];
4778
+ entry.used = true;
4779
+ entry.key_len = key.len;
4780
+ @memcpy(entry.key[0..key.len], key);
3321
4781
  entry.every_ms = every_ms;
4782
+ entry.tag = tag;
3322
4783
  fx.startTimer(.{
3323
4784
  .key = timer_key_base + index,
3324
4785
  .interval_ms = intervalMs(every_ms),
@@ -3326,23 +4787,6 @@ pub fn TsCoreHost(comptime core: type) type {
3326
4787
  .on_fire = timerFireMsg,
3327
4788
  });
3328
4789
  }
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
4790
  }
3347
4791
  },
3348
4792
  // live query [op][key][page][done][err][sql bytes]
@@ -3365,23 +4809,29 @@ pub fn TsCoreHost(comptime core: type) type {
3365
4809
  for (0..table_count) |index| tables[index] = takeShortBytes(subs, &at);
3366
4810
 
3367
4811
  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");
4812
+ const plan: DbPlan = if (comptime @hasDecl(core, "nativeDbPolicy")) compiledDbDeclaration(key, signature, page_tag, done_tag, err_tag, &seen_db) else blk: {
4813
+ const index = findDb(key) orelse freeDbIndex() orelse
4814
+ @panic("ts core host: more relational commands and live queries are active than the database slot family can hold");
4815
+ const entry = &dbs[index];
4816
+ if (entry.used and !entry.live) @panic("ts core host: a live-query key collides with an in-flight database command");
4817
+ if (seen_db[index]) @panic("ts core host: duplicate live-query subscription key");
4818
+ seen_db[index] = true;
4819
+ const changed = !entry.used or entry.signature != signature;
4820
+ break :blk .{ .slot = index, .start = changed, .stop = entry.used and changed, .page_tag = page_tag, .done_tag = done_tag, .err_tag = err_tag };
4821
+ };
4822
+ const index = plan.slot;
3370
4823
  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);
4824
+ if (plan.stop) fx.dbUnsubscribe(db_key_base + index);
4825
+ if (plan.start) {
3376
4826
  entry.* = .{
3377
4827
  .used = true,
3378
4828
  .query = true,
3379
4829
  .live = true,
3380
4830
  .signature = signature,
3381
4831
  .key_len = key.len,
3382
- .page_tag = page_tag,
3383
- .done_tag = done_tag,
3384
- .err_tag = err_tag,
4832
+ .page_tag = plan.page_tag,
4833
+ .done_tag = plan.done_tag,
4834
+ .err_tag = plan.err_tag,
3385
4835
  };
3386
4836
  @memcpy(entry.key[0..key.len], key);
3387
4837
  fx.dbSubscribe(.{
@@ -3393,23 +4843,270 @@ pub fn TsCoreHost(comptime core: type) type {
3393
4843
  });
3394
4844
  }
3395
4845
  },
4846
+ 0x03 => {
4847
+ const id = takeShortBytes(subs, &at);
4848
+ const key = takeLongBytes(subs, &at);
4849
+ const modifiers = @import("global_shortcuts.zig").modifiersFromMask(takeByte(subs, &at));
4850
+ const tag = takeByte(subs, &at);
4851
+ const duplicate = for (declared_shortcuts[0..declared_shortcut_count]) |declared| {
4852
+ if (std.mem.eql(u8, declared.shortcut.id, id)) break true;
4853
+ } else false;
4854
+ if (id.len == 0 or id.len > platform.max_shortcut_id_bytes or duplicate or declared_shortcut_count == declared_shortcuts.len) {
4855
+ const signature = std.hash.Wyhash.hash(tag, id);
4856
+ if (rejected_now_count == rejected_now.len) continue;
4857
+ rejected_now[rejected_now_count] = signature;
4858
+ rejected_now_count += 1;
4859
+ const reported = std.mem.indexOfScalar(u64, rejected_shortcuts[0..rejected_shortcut_count], signature) != null;
4860
+ if (!reported) fx.stageLoopMsg(msgFromTagGlobalShortcut(tag, .rejected, fx.stageLoopKey(id)));
4861
+ continue;
4862
+ }
4863
+ declared_shortcuts[declared_shortcut_count] = .{ .shortcut = .{ .id = id, .key = key[0..@min(key.len, platform.max_shortcut_key_bytes)], .modifiers = modifiers }, .tag = tag };
4864
+ declared_shortcut_count += 1;
4865
+ },
3396
4866
  else => @panic("ts core host: unknown subscription wire record - the core and this runtime disagree on cmd_format_version"),
3397
4867
  }
3398
4868
  }
4869
+ @memcpy(rejected_shortcuts[0..rejected_now_count], rejected_now[0..rejected_now_count]);
4870
+ rejected_shortcut_count = rejected_now_count;
4871
+ reconcileGlobalShortcuts(fx, declared_shortcuts[0..declared_shortcut_count]);
4872
+ const cancellations: ?u16 = if (comptime @hasDecl(core, "nativeTimerPolicy")) compiledTimerCancellations(seen_timers) else null;
3399
4873
  for (&timers, 0..) |*entry, index| {
3400
- if (entry.used and !seen_timers[index]) {
4874
+ const cancel = if (cancellations) |mask| mask & (@as(u16, 1) << @intCast(index)) != 0 else entry.used and !seen_timers[index];
4875
+ if (cancel) {
3401
4876
  entry.used = false;
3402
4877
  fx.cancelTimer(timer_key_base + index);
3403
4878
  }
3404
4879
  }
3405
4880
  }
3406
4881
 
4882
+ fn reconcileGlobalShortcuts(fx: *Fx, declared: []const DeclaredShortcut) void {
4883
+ var changed = declared.len != global_shortcut_count;
4884
+ var was_declared: [global_shortcuts.len]bool = undefined;
4885
+ for (&global_shortcuts, &was_declared) |*entry, *was| {
4886
+ was.* = entry.declared;
4887
+ entry.declared = false;
4888
+ }
4889
+ var shortcuts: [platform.max_global_shortcuts]platform.Shortcut = undefined;
4890
+ for (declared, 0..) |item, position| {
4891
+ const index = findGlobalShortcut(item.shortcut.id) orelse freeGlobalShortcutIndex();
4892
+ const entry = &global_shortcuts[index];
4893
+ if (!was_declared[index] or !entry.binding.matches(item.shortcut)) changed = true;
4894
+ entry.* = .{ .used = true, .declared = true, .binding = .init(item.shortcut), .tag = item.tag, .pressed = entry.pressed };
4895
+ shortcuts[position] = entry.binding.shortcut();
4896
+ }
4897
+ global_shortcut_count = declared.len;
4898
+ if (changed) fx.setGlobalShortcuts(.{ .key = global_shortcut_key, .shortcuts = shortcuts[0..declared.len], .on_event = globalShortcutEventMsg });
4899
+ }
4900
+
4901
+ fn findGlobalShortcut(id: []const u8) ?usize {
4902
+ for (&global_shortcuts, 0..) |*entry, index| {
4903
+ if (entry.used and std.mem.eql(u8, entry.binding.shortcut().id, id)) return index;
4904
+ }
4905
+ return null;
4906
+ }
4907
+
4908
+ fn freeGlobalShortcutIndex() usize {
4909
+ for (&global_shortcuts, 0..) |*entry, index| {
4910
+ if (!entry.used) return index;
4911
+ }
4912
+ for (&global_shortcuts, 0..) |*entry, index| {
4913
+ if (!entry.declared and !entry.pressed) return index;
4914
+ }
4915
+ unreachable;
4916
+ }
4917
+
4918
+ fn channelReportIndex() usize {
4919
+ for (&global_shortcuts, 0..) |*entry, index| {
4920
+ if (entry.declared) return index;
4921
+ }
4922
+ for (&global_shortcuts, 0..) |*entry, index| {
4923
+ if (entry.used) return index;
4924
+ }
4925
+ @panic("ts core host: a global shortcut channel report arrived with no route");
4926
+ }
4927
+
4928
+ fn globalShortcutEventMsg(event: runtime_effects.EffectChannelEvent) Msg {
4929
+ const report = @import("global_shortcuts.zig").decodeChannelEvent(event);
4930
+ const index = findGlobalShortcut(report.shortcut.id) orelse if (report.shortcut.id.len == 0)
4931
+ channelReportIndex()
4932
+ else
4933
+ @panic("ts core host: a global shortcut report arrived with no bridge entry");
4934
+ const entry = &global_shortcuts[index];
4935
+ switch (report.kind) {
4936
+ .pressed => entry.pressed = true,
4937
+ .released => entry.pressed = false,
4938
+ else => {},
4939
+ }
4940
+ var id: []const u8 = "";
4941
+ if (report.shortcut.id.len > 0) {
4942
+ const copy = core.rt.frameAlloc(u8, report.shortcut.id.len);
4943
+ @memcpy(copy, report.shortcut.id);
4944
+ id = copy;
4945
+ }
4946
+ return msgFromTagGlobalShortcut(entry.tag, report.kind, id);
4947
+ }
4948
+
4949
+ const TimerPlan = struct { slot: usize, start: bool, tag: u8, interval_ms: u64 };
4950
+
4951
+ /// Native supplies owned table facts; TypeScript resolves slot order,
4952
+ /// key matching, interval changes, routes and the seen set. The callback
4953
+ /// copies the response and leaves both cycle arenas alive.
4954
+ fn compiledTimerDeclaration(key: []const u8, every_ms: f64, tag: u8, seen: *[runtime_effects.max_effect_timers]bool) TimerPlan {
4955
+ comptime std.debug.assert(runtime_effects.max_effect_timers == 16);
4956
+ var request: [13 + max_wire_key_bytes + 16 * (10 + max_wire_key_bytes)]u8 = undefined;
4957
+ request[0] = 0;
4958
+ std.mem.writeInt(u16, request[1..3], timerSeenMask(seen.*), .little);
4959
+ request[3] = @intCast(key.len);
4960
+ @memcpy(request[4..][0..key.len], key);
4961
+ var at: usize = 4 + key.len;
4962
+ std.mem.writeInt(u64, request[at..][0..8], @bitCast(every_ms), .little);
4963
+ request[at + 8] = tag;
4964
+ at += 9;
4965
+ for (&timers) |*entry| {
4966
+ const length = if (entry.used) entry.key_len else 0;
4967
+ request[at] = @intFromBool(entry.used);
4968
+ request[at + 1] = @intCast(length);
4969
+ at += 2;
4970
+ @memcpy(request[at..][0..length], entry.key[0..length]);
4971
+ at += length;
4972
+ std.mem.writeInt(u64, request[at..][0..8], @bitCast(if (entry.used) entry.every_ms else @as(f64, 0)), .little);
4973
+ at += 8;
4974
+ }
4975
+ var result: [14]u8 = undefined;
4976
+ if (core.nativeTimerPolicy(request[0..at], &result) != result.len or result[0] >= timers.len or result[1] > 1 or result[3] != 0)
4977
+ @panic("ts core host: invalid compiled timer declaration result");
4978
+ const rounded: f64 = @bitCast(std.mem.readInt(u64, result[4..12], .little));
4979
+ if (!std.math.isFinite(rounded) or rounded < 1 or rounded > 31_536_000_000 or @floor(rounded) != rounded)
4980
+ @panic("ts core host: invalid compiled timer interval result");
4981
+ const mask = std.mem.readInt(u16, result[12..14], .little);
4982
+ for (seen, 0..) |*value, index| value.* = mask & (@as(u16, 1) << @intCast(index)) != 0;
4983
+ return .{ .slot = result[0], .start = result[1] == 1, .tag = result[2], .interval_ms = @intFromFloat(rounded) };
4984
+ }
4985
+
4986
+ const DelayPlan = struct { slot: usize, tag: u8, interval_ms: u64 };
4987
+ const max_delay_policy_bytes = 12 + max_wire_key_bytes + 16 * (3 + max_wire_key_bytes);
4988
+
4989
+ /// Copy native-owned facts into a borrowed request. No policy call may
4990
+ /// reset the command frame: later records in a batch still borrow it.
4991
+ fn writeDelayTable(request: []u8, start: usize) usize {
4992
+ comptime std.debug.assert(runtime_effects.max_effect_timers == 16);
4993
+ var at = start;
4994
+ for (&delays) |*entry| {
4995
+ const length = if (entry.used) entry.key_len else 0;
4996
+ request[at] = @intFromBool(entry.used);
4997
+ request[at + 1] = @intCast(length);
4998
+ at += 2;
4999
+ @memcpy(request[at..][0..length], entry.key[0..length]);
5000
+ at += length;
5001
+ request[at] = entry.tag;
5002
+ at += 1;
5003
+ }
5004
+ return at;
5005
+ }
5006
+
5007
+ fn compiledDelayDeclaration(key: []const u8, after_ms: f64, tag: u8, blocked: bool, rejectable: bool) ?DelayPlan {
5008
+ return compiledDelayDeclarationRange(key, after_ms, tag, blocked, rejectable, false);
5009
+ }
5010
+
5011
+ fn compiledDelayDeclarationRange(key: []const u8, after_ms: f64, tag: u8, blocked: bool, rejectable: bool, native_range: bool) ?DelayPlan {
5012
+ var request: [max_delay_policy_bytes]u8 = undefined;
5013
+ request[0] = if (native_range) 8 else if (rejectable) 6 else 2;
5014
+ request[1] = @intCast(key.len);
5015
+ @memcpy(request[2..][0..key.len], key);
5016
+ const value_at = 2 + key.len;
5017
+ std.mem.writeInt(u64, request[value_at..][0..8], @bitCast(after_ms), .little);
5018
+ request[value_at + 8] = tag;
5019
+ request[value_at + 9] = @intFromBool(blocked);
5020
+ const at = writeDelayTable(&request, value_at + 10);
5021
+ var result: [10]u8 = undefined;
5022
+ if (core.nativeTimerPolicy(request[0..at], &result) != result.len)
5023
+ @panic("ts core host: invalid compiled delay declaration result");
5024
+ if (result[0] == 255) return null;
5025
+ if (result[0] >= delays.len) @panic("ts core host: invalid compiled delay declaration slot");
5026
+ const rounded: f64 = @bitCast(std.mem.readInt(u64, result[2..10], .little));
5027
+ 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)
5028
+ @panic("ts core host: invalid compiled delay interval result");
5029
+ return .{ .slot = result[0], .tag = result[1], .interval_ms = @intFromFloat(rounded) };
5030
+ }
5031
+
5032
+ fn compiledDelayLookup(key: []const u8) ?usize {
5033
+ var request: [max_delay_policy_bytes]u8 = undefined;
5034
+ request[0] = 3;
5035
+ request[1] = @intCast(key.len);
5036
+ @memcpy(request[2..][0..key.len], key);
5037
+ const at = writeDelayTable(&request, 2 + key.len);
5038
+ var result: [1]u8 = undefined;
5039
+ if (core.nativeTimerPolicy(request[0..at], &result) != result.len)
5040
+ @panic("ts core host: invalid compiled delay lookup result");
5041
+ if (result[0] == 255) return null;
5042
+ if (result[0] >= delays.len or !delays[result[0]].used)
5043
+ @panic("ts core host: invalid compiled delay lookup slot");
5044
+ return result[0];
5045
+ }
5046
+
5047
+ fn compiledTimerCompletion(timer: runtime_effects.EffectTimer, subscription: bool) [40]u8 {
5048
+ var request: [96]u8 = @splat(0);
5049
+ request[0..3].* = .{ 7, @intFromBool(subscription), @intFromEnum(timer.outcome) };
5050
+ std.mem.writeInt(u64, request[4..12], timer.key, .little);
5051
+ std.mem.writeInt(u64, request[12..20], timer.timestamp_ns, .little);
5052
+ std.mem.writeInt(u64, request[20..28], if (subscription) timer_key_base else delay_key_base, .little);
5053
+ for (0..16) |slot| {
5054
+ request[32 + slot * 4 ..][0..4].* = if (subscription)
5055
+ .{ @intFromBool(timers[slot].used), 0, 0, timers[slot].tag }
5056
+ else
5057
+ .{ @intFromBool(delays[slot].used), @intFromBool(delays[slot].full_result), @intFromEnum(delays[slot].mode), delays[slot].tag };
5058
+ }
5059
+ var result: [40]u8 = undefined;
5060
+ 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
5061
+ 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)))))
5062
+ @panic("ts core host: invalid compiled timer completion plan");
5063
+ for (result[16..][0..result[4]]) |digit| if (digit < '0' or digit > '9') @panic("ts core host: invalid compiled timer timestamp");
5064
+ return result;
5065
+ }
5066
+
5067
+ fn timerCompletionMsg(plan: [40]u8, timer: runtime_effects.EffectTimer, key: []const u8) Msg {
5068
+ if (plan[2] == 0) return msgFromTagNumber(plan[1], @bitCast(std.mem.readInt(u64, plan[8..16], .little)));
5069
+ // The copied plan is stack-owned. Its decimal bytes must survive
5070
+ // in the dispatch frame until the app consumes the complete Msg.
5071
+ const timestamp = core.rt.frameAlloc(u8, plan[4]);
5072
+ @memcpy(timestamp, plan[16..][0..plan[4]]);
5073
+ return msgFromCapability(plan[1], .{ .key = key, .timestampNs = @as([]const u8, timestamp), .outcome = timer.outcome });
5074
+ }
5075
+
5076
+ fn timerSeenMask(seen: [runtime_effects.max_effect_timers]bool) u16 {
5077
+ var mask: u16 = 0;
5078
+ for (seen, 0..) |value, index| if (value) {
5079
+ mask |= @as(u16, 1) << @intCast(index);
5080
+ };
5081
+ return mask;
5082
+ }
5083
+
5084
+ fn compiledTimerCancellations(seen: [runtime_effects.max_effect_timers]bool) u16 {
5085
+ var used: u16 = 0;
5086
+ for (&timers, 0..) |*entry, index| if (entry.used) {
5087
+ used |= @as(u16, 1) << @intCast(index);
5088
+ };
5089
+ var request: [5]u8 = undefined;
5090
+ request[0] = 1;
5091
+ std.mem.writeInt(u16, request[1..3], used, .little);
5092
+ std.mem.writeInt(u16, request[3..5], timerSeenMask(seen), .little);
5093
+ var result: [2]u8 = undefined;
5094
+ if (core.nativeTimerPolicy(&request, &result) != result.len) @panic("ts core host: invalid compiled timer cancellation result");
5095
+ const mask = std.mem.readInt(u16, &result, .little);
5096
+ if (mask & ~used != 0) @panic("ts core host: invalid compiled timer cancellation slots");
5097
+ return mask;
5098
+ }
5099
+
3407
5100
  /// Parse the inert subscription stream without mutating it and mark
3408
5101
  /// the currently-live DB entries whose public keys remain declared.
3409
5102
  /// Reconciliation uses this pre-pass to retire genuinely stale slots
3410
5103
  /// before it allocates any new ones.
3411
5104
  fn retainedDbSubscriptions(subs: []const u8) [runtime_effects.max_db_effects]bool {
3412
5105
  var retained = [_]bool{false} ** runtime_effects.max_db_effects;
5106
+ // Keep the complete key list separate from the borrowed stream;
5107
+ // policy allocation never revokes subsequent subscription records.
5108
+ const request: []u8 = if (comptime @hasDecl(core, "nativeDbPolicy")) core.rt.frameAlloc(u8, subs.len + max_db_policy_bytes + 5) else &.{};
5109
+ var keys_at: usize = 5;
3413
5110
  var at: usize = 0;
3414
5111
  while (at < subs.len) switch (takeByte(subs, &at)) {
3415
5112
  0x01 => {
@@ -3417,6 +5114,11 @@ pub fn TsCoreHost(comptime core: type) type {
3417
5114
  _ = takeBytes(subs, &at, 8);
3418
5115
  _ = takeByte(subs, &at);
3419
5116
  },
5117
+ 0x03 => {
5118
+ _ = takeShortBytes(subs, &at);
5119
+ _ = takeLongBytes(subs, &at);
5120
+ _ = takeBytes(subs, &at, 2);
5121
+ },
3420
5122
  0x02 => {
3421
5123
  const key = takeShortBytes(subs, &at);
3422
5124
  if (key.len == 0) @panic("ts core host: a live query requires a non-empty subscription key");
@@ -3430,15 +5132,82 @@ pub fn TsCoreHost(comptime core: type) type {
3430
5132
  const table_count: usize = @intCast(takeU32(subs, &at));
3431
5133
  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
5134
  for (0..table_count) |_| _ = takeShortBytes(subs, &at);
3433
- if (findDb(key)) |index| {
5135
+ if (comptime @hasDecl(core, "nativeDbPolicy")) {
5136
+ request[keys_at] = @intCast(key.len);
5137
+ keys_at += 1;
5138
+ @memcpy(request[keys_at..][0..key.len], key);
5139
+ keys_at += key.len;
5140
+ } else if (findDb(key)) |index| {
3434
5141
  if (dbs[index].live) retained[index] = true;
3435
5142
  }
3436
5143
  },
3437
5144
  else => @panic("ts core host: unknown subscription wire record - the core and this runtime disagree on cmd_format_version"),
3438
5145
  };
5146
+ if (comptime @hasDecl(core, "nativeDbPolicy")) {
5147
+ request[0] = 1;
5148
+ std.mem.writeInt(u32, request[1..5], @intCast(keys_at - 5), .little);
5149
+ const end = writeDbTable(request, keys_at);
5150
+ var result: [2]u8 = undefined;
5151
+ if (core.nativeDbPolicy(request[0..end], &result) != result.len) @panic("ts core host: invalid compiled database retention result");
5152
+ const mask = std.mem.readInt(u16, &result, .little);
5153
+ for (&retained, 0..) |*value, index| value.* = mask & (@as(u16, 1) << @intCast(index)) != 0;
5154
+ }
3439
5155
  return retained;
3440
5156
  }
3441
5157
 
5158
+ const DbPlan = struct { slot: usize, start: bool, stop: bool, page_tag: u8, done_tag: u8, err_tag: u8 };
5159
+ const max_db_policy_bytes = 15 + max_wire_key_bytes + 16 * (11 + max_wire_key_bytes);
5160
+
5161
+ fn writeDbTable(request: []u8, start: usize) usize {
5162
+ comptime std.debug.assert(runtime_effects.max_db_effects == 16);
5163
+ var at = start;
5164
+ for (&dbs) |*entry| {
5165
+ const length = if (entry.used) entry.key_len else 0;
5166
+ request[at] = @intFromBool(entry.used);
5167
+ request[at + 1] = @intFromBool(entry.live);
5168
+ request[at + 2] = @intCast(length);
5169
+ at += 3;
5170
+ @memcpy(request[at..][0..length], entry.key[0..length]);
5171
+ at += length;
5172
+ std.mem.writeInt(u64, request[at..][0..8], entry.signature, .little);
5173
+ at += 8;
5174
+ }
5175
+ return at;
5176
+ }
5177
+
5178
+ fn compiledDbLookup(key: []const u8) ?usize {
5179
+ var request: [max_db_policy_bytes]u8 = undefined;
5180
+ request[0] = 0;
5181
+ request[1] = @intCast(key.len);
5182
+ @memcpy(request[2..][0..key.len], key);
5183
+ const at = writeDbTable(&request, 2 + key.len);
5184
+ var result: [1]u8 = undefined;
5185
+ if (core.nativeDbPolicy(request[0..at], &result) != result.len) @panic("ts core host: invalid compiled database lookup result");
5186
+ if (result[0] == 255) return null;
5187
+ if (result[0] >= dbs.len or !dbs[result[0]].used) @panic("ts core host: invalid compiled database lookup slot");
5188
+ return result[0];
5189
+ }
5190
+
5191
+ fn compiledDbDeclaration(key: []const u8, signature: u64, page_tag: u8, done_tag: u8, err_tag: u8, seen: *[runtime_effects.max_db_effects]bool) DbPlan {
5192
+ var request: [max_db_policy_bytes]u8 = undefined;
5193
+ request[0] = 2;
5194
+ std.mem.writeInt(u16, request[1..3], timerSeenMask(seen.*), .little);
5195
+ request[3] = @intCast(key.len);
5196
+ @memcpy(request[4..][0..key.len], key);
5197
+ const at = 4 + key.len;
5198
+ std.mem.writeInt(u64, request[at..][0..8], signature, .little);
5199
+ request[at + 8] = page_tag;
5200
+ request[at + 9] = done_tag;
5201
+ request[at + 10] = err_tag;
5202
+ const end = writeDbTable(&request, at + 11);
5203
+ var result: [8]u8 = undefined;
5204
+ if (core.nativeDbPolicy(request[0..end], &result) != result.len or result[0] >= dbs.len or result[1] > 1 or result[2] > 1)
5205
+ @panic("ts core host: invalid compiled database declaration result");
5206
+ const mask = std.mem.readInt(u16, result[6..8], .little);
5207
+ for (seen, 0..) |*value, index| value.* = mask & (@as(u16, 1) << @intCast(index)) != 0;
5208
+ return .{ .slot = result[0], .start = result[1] == 1, .stop = result[2] == 1, .page_tag = result[3], .done_tag = result[4], .err_tag = result[5] };
5209
+ }
5210
+
3442
5211
  fn freeTimerIndex() ?usize {
3443
5212
  for (&timers, 0..) |*entry, index| {
3444
5213
  if (!entry.used) return index;
@@ -3455,6 +5224,11 @@ pub fn TsCoreHost(comptime core: type) type {
3455
5224
  /// `TimerMsgFn` for every bridge timer: dispatch the slot's arm
3456
5225
  /// with the fire time in fractional milliseconds.
3457
5226
  fn timerFireMsg(timer: runtime_effects.EffectTimer) Msg {
5227
+ if (comptime @hasDecl(core, "nativeTimerPolicy")) {
5228
+ const plan = compiledTimerCompletion(timer, true);
5229
+ if (plan[3] == 1) timers[plan[0]].used = false;
5230
+ return timerCompletionMsg(plan, timer, timers[plan[0]].wireKey());
5231
+ }
3458
5232
  if (timer.outcome == .rejected) {
3459
5233
  @panic("ts core host: the platform rejected a subscription timer (no timer service, or the fx timer table is full)");
3460
5234
  }
@@ -3607,6 +5381,69 @@ pub fn TsCoreHost(comptime core: type) type {
3607
5381
  return ok;
3608
5382
  }
3609
5383
 
5384
+ fn exactAudioArmShape(comptime T: type) bool {
5385
+ if (@typeInfo(T) != .@"struct") return false;
5386
+ const fields = @typeInfo(T).@"struct".fields;
5387
+ if (fields.len != 7) return false;
5388
+ for (fields) |field| {
5389
+ if (std.mem.eql(u8, field.name, "state")) {
5390
+ if (@typeInfo(field.type) != .@"enum") return false;
5391
+ const states = @typeInfo(field.type).@"enum".fields;
5392
+ if (states.len != 6) return false;
5393
+ for (states) |state| {
5394
+ var found = false;
5395
+ for (@typeInfo(runtime_effects.EffectAudioEventKind).@"enum".fields) |expected|
5396
+ if (std.mem.eql(u8, expected.name, state.name)) {
5397
+ found = true;
5398
+ };
5399
+ if (!found) return false;
5400
+ }
5401
+ } else if (std.mem.eql(u8, field.name, "playing") or std.mem.eql(u8, field.name, "buffering")) {
5402
+ if (field.type != bool) return false;
5403
+ } else if (std.mem.eql(u8, field.name, "key") or std.mem.eql(u8, field.name, "positionMs") or
5404
+ std.mem.eql(u8, field.name, "durationMs") or std.mem.eql(u8, field.name, "bands"))
5405
+ {
5406
+ if (field.type != []const u8) return false;
5407
+ } else return false;
5408
+ }
5409
+ return true;
5410
+ }
5411
+
5412
+ fn exactSpawnArmShape(comptime T: type, comptime line: bool) bool {
5413
+ if (@typeInfo(T) != .@"struct") return false;
5414
+ const fields = @typeInfo(T).@"struct".fields;
5415
+ if (fields.len != (if (line) @as(usize, 4) else 8)) return false;
5416
+ for (fields) |field| {
5417
+ if (std.mem.eql(u8, field.name, "key") or
5418
+ (line and std.mem.eql(u8, field.name, "line")) or
5419
+ (!line and (std.mem.eql(u8, field.name, "output") or std.mem.eql(u8, field.name, "stderrTail"))))
5420
+ {
5421
+ if (field.type != []const u8) return false;
5422
+ } else if ((line and std.mem.eql(u8, field.name, "truncated")) or
5423
+ (!line and (std.mem.eql(u8, field.name, "outputTruncated") or std.mem.eql(u8, field.name, "stderrTruncated"))))
5424
+ {
5425
+ if (field.type != bool) return false;
5426
+ } else if ((line and std.mem.eql(u8, field.name, "droppedBefore")) or
5427
+ (!line and (std.mem.eql(u8, field.name, "code") or std.mem.eql(u8, field.name, "droppedLines"))))
5428
+ {
5429
+ if (field.type != f64 and field.type != i64 and field.type != u64) return false;
5430
+ } else if (!line and std.mem.eql(u8, field.name, "reason")) {
5431
+ if (@typeInfo(field.type) != .@"enum") return false;
5432
+ const reasons = @typeInfo(field.type).@"enum".fields;
5433
+ const expected = @typeInfo(runtime_effects.EffectExitReason).@"enum".fields;
5434
+ if (reasons.len != expected.len) return false;
5435
+ for (reasons) |reason| {
5436
+ var found = false;
5437
+ for (expected) |value| if (std.mem.eql(u8, reason.name, value.name)) {
5438
+ found = true;
5439
+ };
5440
+ if (!found) return false;
5441
+ }
5442
+ } else return false;
5443
+ }
5444
+ return true;
5445
+ }
5446
+
3610
5447
  /// The arm's `state` member for an engine event kind, matched
3611
5448
  /// by member NAME (the frontend pins the member set, so the
3612
5449
  /// app's declaration order never matters to the wire).
@@ -3732,12 +5569,13 @@ pub fn TsCoreHost(comptime core: type) type {
3732
5569
  const info = @typeInfo(T);
3733
5570
  if (info != .@"struct") return false;
3734
5571
  const fields = info.@"struct".fields;
3735
- if (fields.len != 5) return false;
5572
+ if (fields.len != 5 and fields.len != 6) return false;
5573
+ const words = fields.len == 6;
3736
5574
  var ok = true;
3737
5575
  for (fields) |f| {
3738
5576
  if (std.mem.eql(u8, f.name, "state")) {
3739
5577
  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")) {
5578
+ } 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
5579
  if (f.type != i64 and f.type != u64 and f.type != f64) ok = false;
3742
5580
  } else {
3743
5581
  ok = false;
@@ -3769,6 +5607,9 @@ pub fn TsCoreHost(comptime core: type) type {
3769
5607
  inline for (fields) |f| {
3770
5608
  if (comptime std.mem.eql(u8, f.name, "state")) {
3771
5609
  @field(payload, f.name) = imageStateValue(f.type, result.outcome);
5610
+ } else if (comptime std.mem.eql(u8, f.name, "imageLower") or std.mem.eql(u8, f.name, "imageUpper")) {
5611
+ const word: u32 = if (comptime std.mem.eql(u8, f.name, "imageLower")) @truncate(result.id) else @truncate(result.id >> 32);
5612
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(word) else @intCast(word);
3772
5613
  } else if (comptime std.mem.eql(u8, f.name, "id")) {
3773
5614
  @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(result.id) else @intCast(result.id);
3774
5615
  } else if (comptime std.mem.eql(u8, f.name, "width")) {
@@ -3791,6 +5632,77 @@ pub fn TsCoreHost(comptime core: type) type {
3791
5632
  /// `imageArmShape`'s twin: `key` (number), `state` (any enum;
3792
5633
  /// members matched by name at delivery), `bytes` (bytes),
3793
5634
  /// `droppedPending`/`droppedTotal` (numbers).
5635
+ fn channelSourceArmShape(comptime T: type) bool {
5636
+ const info = @typeInfo(T);
5637
+ if (info != .@"struct") return false;
5638
+ const fields = info.@"struct".fields;
5639
+ if (fields.len != 3) return false;
5640
+ var ok = true;
5641
+ for (fields) |f| {
5642
+ if (std.mem.eql(u8, f.name, "state")) {
5643
+ if (@typeInfo(f.type) != .@"enum") ok = false;
5644
+ } else if (std.mem.eql(u8, f.name, "bytes")) {
5645
+ if (f.type != []const u8) ok = false;
5646
+ } else if (std.mem.eql(u8, f.name, "key")) {
5647
+ if (f.type != i64 and f.type != u64 and f.type != f64) ok = false;
5648
+ } else {
5649
+ ok = false;
5650
+ }
5651
+ }
5652
+ return ok;
5653
+ }
5654
+
5655
+ /// The arm's `state` member for an engine channel source result kind,
5656
+ /// matched by member NAME — `imageStateValue`'s twin.
5657
+ fn channelSourceStateValue(comptime E: type, kind: runtime_effects.EffectChannelSourceState) E {
5658
+ const name = @tagName(kind);
5659
+ inline for (@typeInfo(E).@"enum".fields) |f| {
5660
+ if (std.mem.eql(u8, f.name, name)) return @enumFromInt(f.value);
5661
+ }
5662
+ @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");
5663
+ }
5664
+
5665
+ /// Build the three-field channel source result arm at index `tag` from
5666
+ /// an engine event, by field name. The bytes copy into the
5667
+ /// core's frame arena like every routed payload (the engine's
5668
+ /// slice is drain scratch); `key` is the channel key echoed
5669
+ /// verbatim (always below 2^53 — the bridge refused anything
5670
+ /// wider — so both number classes carry it exactly), and the
5671
+ /// drop counters widen the way the subset's number model
5672
+ /// classes them.
5673
+ fn msgFromTagChannelSource(tag: u8, event: runtime_effects.EffectChannelSourceResult) Msg {
5674
+ inline for (msg_arms, 0..) |arm, index| {
5675
+ if (tag == index) {
5676
+ if (comptime channelSourceArmShape(arm.type)) {
5677
+ const fields = @typeInfo(arm.type).@"struct".fields;
5678
+ var payload: arm.type = undefined;
5679
+ inline for (fields) |f| {
5680
+ if (comptime std.mem.eql(u8, f.name, "state")) {
5681
+ @field(payload, f.name) = channelSourceStateValue(f.type, event.state);
5682
+ } else if (comptime std.mem.eql(u8, f.name, "key")) {
5683
+ @field(payload, f.name) = if (comptime f.type == f64) @floatFromInt(event.key) else @intCast(event.key);
5684
+ } else if (event.bytes.len == 0) {
5685
+ // Payload-free events (rejected/closed
5686
+ // terminals, and the staged rejection
5687
+ // Msgs that must be self-contained
5688
+ // across the frame reset) carry the
5689
+ // static empty slice, never a
5690
+ // zero-length frame pointer.
5691
+ @field(payload, f.name) = "";
5692
+ } else {
5693
+ const copy = core.rt.frameAlloc(u8, event.bytes.len);
5694
+ @memcpy(copy, event.bytes);
5695
+ @field(payload, f.name) = copy;
5696
+ }
5697
+ }
5698
+ return @unionInit(Msg, arm.name, payload);
5699
+ }
5700
+ @panic("ts core host: a channel source result targets Msg arm '" ++ arm.name ++ "', which is not the three-field channel source result record");
5701
+ }
5702
+ }
5703
+ @panic("ts core host: a channel source result names a Msg tag outside the union");
5704
+ }
5705
+
3794
5706
  fn channelArmShape(comptime T: type) bool {
3795
5707
  const info = @typeInfo(T);
3796
5708
  if (info != .@"struct") return false;
@@ -3866,6 +5778,21 @@ pub fn TsCoreHost(comptime core: type) type {
3866
5778
  @panic("ts core host: a channel event names a Msg tag outside the union");
3867
5779
  }
3868
5780
 
5781
+ fn msgFromTagGlobalShortcut(tag: u8, kind: runtime_effects.EffectGlobalShortcutEventKind, id: []const u8) Msg {
5782
+ inline for (msg_arms, 0..) |arm, index| {
5783
+ if (tag == index) {
5784
+ const T = arm.type;
5785
+ if (comptime @typeInfo(T) != .@"struct" or @typeInfo(T).@"struct".fields.len != 2 or !@hasField(T, "id") or !@hasField(T, "state") or
5786
+ @FieldType(T, "id") != []const u8 or @typeInfo(@FieldType(T, "state")) != .@"enum")
5787
+ @panic("ts core host: a global shortcut report targets Msg arm '" ++ arm.name ++ "', which is not the { id, state } record");
5788
+ const state = std.meta.stringToEnum(@FieldType(T, "state"), if (kind == .stopped) "rejected" else @tagName(kind)) orelse
5789
+ @panic("ts core host: a global shortcut report state has no member in the arm's state union");
5790
+ return @unionInit(Msg, arm.name, .{ .id = id, .state = state });
5791
+ }
5792
+ }
5793
+ @panic("ts core host: a global shortcut report names a Msg tag outside the union");
5794
+ }
5795
+
3869
5796
  fn audioCaptureArmShape(comptime T: type) bool {
3870
5797
  const info = @typeInfo(T);
3871
5798
  if (info != .@"struct") return false;
@@ -4135,3 +6062,116 @@ pub fn TsCoreHost(comptime core: type) type {
4135
6062
  }
4136
6063
  };
4137
6064
  }
6065
+
6066
+ const PtyBindingTestCore = struct {
6067
+ pub const Model = struct {};
6068
+ const PtyState = enum { output, exit };
6069
+ const Reason = enum { exited, signaled, cancelled, rejected, spawn_failed };
6070
+ pub const Msg = union(enum) { event: struct { key: []const u8, state: PtyState, bytes: []const u8, code: f64, reason: Reason, signal: f64, droppedWrites: f64 } };
6071
+ var value: Model = .{};
6072
+ pub fn initialModel() *const Model {
6073
+ return &value;
6074
+ }
6075
+ pub fn update(model: *const Model, _: Msg) *const Model {
6076
+ return model;
6077
+ }
6078
+ pub fn commitModelRoot(model: *const Model) *const Model {
6079
+ return model;
6080
+ }
6081
+ pub const rt = struct {
6082
+ var arena: std.heap.ArenaAllocator = undefined;
6083
+ pub fn frameAlloc(comptime T: type, len: usize) []T {
6084
+ return arena.allocator().alloc(T, len) catch unreachable;
6085
+ }
6086
+ pub fn frameReset() void {
6087
+ _ = arena.reset(.retain_capacity);
6088
+ }
6089
+ pub fn resetAll() void {
6090
+ frameReset();
6091
+ }
6092
+ };
6093
+ };
6094
+
6095
+ test "exact timer wire admission preserves unsigned decimal ownership and nanosecond limits" {
6096
+ const Host = TsCoreHost(PtyBindingTestCore);
6097
+ for ([_]u64{ 0, 1, 31_536_000_001, std.math.maxInt(u64) / std.time.ns_per_ms }) |value| {
6098
+ var decimal: [20]u8 = undefined;
6099
+ const text = try std.fmt.bufPrint(&decimal, "{d}", .{value});
6100
+ try std.testing.expectEqual(value, Host.parseExactTimerInterval(text).?);
6101
+ @memset(&decimal, 'x');
6102
+ }
6103
+ for ([_][]const u8{ "", "00", "+1", "-0", "1_0", "1.0", "1e2", " 1", "1 ", "1\x00", "18446744073710", "18446744073709551615", "18446744073709551616", "123456789012345678901" }) |text|
6104
+ try std.testing.expect(Host.parseExactTimerInterval(text) == null);
6105
+ }
6106
+
6107
+ test "exact audio identities and seek positions admit every canonical u64 without rounding" {
6108
+ const Host = TsCoreHost(PtyBindingTestCore);
6109
+ for ([_]u64{ 0, 1, 9007199254740991, 9007199254740993, std.math.maxInt(u64) }) |value| {
6110
+ var buffer: [20]u8 = undefined;
6111
+ const text = try std.fmt.bufPrint(&buffer, "{d}", .{value});
6112
+ try std.testing.expectEqual(value, Host.parseExactUnsigned(text).?);
6113
+ @memset(&buffer, 'x');
6114
+ }
6115
+ for ([_][]const u8{ "", "00", "01", "+1", "-0", "-1", "1.0", "1e2", " 1", "1 ", "1\x00", "18446744073709551616", "123456789012345678901" }) |text|
6116
+ try std.testing.expect(Host.parseExactUnsigned(text) == null);
6117
+ }
6118
+
6119
+ test "PTY name bindings own bytes and retain ended identities without restricting unbound reuse" {
6120
+ const Core = PtyBindingTestCore;
6121
+ const Host = TsCoreHost(Core);
6122
+ Core.rt.arena = .init(std.testing.allocator);
6123
+ defer Core.rt.arena.deinit();
6124
+ var fx = Host.Fx.init(std.testing.allocator);
6125
+ defer fx.deinit();
6126
+ fx.executor = .fake;
6127
+ Host.boot();
6128
+ var name = [_]u8{ 's', 'h', 255, 0 };
6129
+ Host.issuePtySpawn(&fx, &name, 0, 80, 24, "", &.{"/bin/sh"});
6130
+ const original = Host.resolvePtyKey(&name);
6131
+ try std.testing.expect(original != 0);
6132
+ @memset(&name, 'x');
6133
+ try std.testing.expectEqual(original, Host.resolvePtyKey("sh\xff\x00"));
6134
+ try std.testing.expectEqual(@as(u64, 0), Host.resolvePtyKey(&name));
6135
+ try fx.feedPtyOutput(original, "owned screen");
6136
+ const output = fx.takeMsg().?.event;
6137
+ try std.testing.expectEqualStrings("sh\xff\x00", output.key);
6138
+ try std.testing.expectEqualStrings("owned screen", output.bytes);
6139
+ try fx.feedPtyExit(original, 0, 0, .exited, 0);
6140
+ _ = fx.takeMsg();
6141
+ try std.testing.expectEqual(original, Host.resolvePtyKey("sh\xff\x00"));
6142
+ // Distinct unbound names repeatedly reuse an available effect slot, while
6143
+ // the named terminal's ended screen keeps its identity through every exit.
6144
+ for (0..8) |i| {
6145
+ var buffer: [30]u8 = undefined;
6146
+ const other = try std.fmt.bufPrint(&buffer, "unbound-{d}", .{i});
6147
+ Host.issuePtySpawn(&fx, other, 0, 80, 24, "", &.{"/bin/sh"});
6148
+ const key = fx.pendingPtyAt(0).?.key;
6149
+ try std.testing.expect(key != original);
6150
+ try fx.feedPtyExit(key, 0, 0, .exited, 0);
6151
+ _ = fx.takeMsg();
6152
+ try std.testing.expectEqual(original, Host.resolvePtyKey("sh\xff\x00"));
6153
+ }
6154
+ Host.issuePtySpawn(&fx, "sh\xff\x00", 0, 80, 24, "", &.{"/bin/sh"});
6155
+ try std.testing.expectEqual(original, fx.pendingPtyAt(0).?.key);
6156
+ Host.issuePtySpawn(&fx, "sh\xff\x00", 0, 80, 24, "", &.{"/bin/sh"});
6157
+ const refused = fx.takeMsg().?.event;
6158
+ try std.testing.expectEqual(Core.Reason.rejected, refused.reason);
6159
+ try std.testing.expectEqualStrings("sh\xff\x00", refused.key);
6160
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingPtyCount());
6161
+ // Bound ended grids occupy the documented budget. Exhaustion still
6162
+ // delivers the normal one rejected terminal instead of aliasing a screen.
6163
+ for ([_][]const u8{ "second", "third", "fourth" }) |name_key| {
6164
+ Host.issuePtySpawn(&fx, name_key, 0, 80, 24, "", &.{"/bin/sh"});
6165
+ const key = Host.resolvePtyKey(name_key);
6166
+ try std.testing.expect(key != 0 and key != original);
6167
+ try fx.feedPtyExit(key, 0, 0, .exited, 0);
6168
+ _ = fx.takeMsg();
6169
+ }
6170
+ Host.issuePtySpawn(&fx, "fifth", 0, 80, 24, "", &.{"/bin/sh"});
6171
+ const full = fx.takeMsg().?.event;
6172
+ try std.testing.expectEqual(Core.Reason.rejected, full.reason);
6173
+ try std.testing.expectEqualStrings("fifth", full.key);
6174
+ try std.testing.expectEqual(@as(u64, 0), Host.resolvePtyKey("fifth"));
6175
+ Host.boot();
6176
+ try std.testing.expectEqual(@as(u64, 0), Host.resolvePtyKey("sh\xff\x00"));
6177
+ }