@native-sdk/cli 0.8.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/build/app.zig +905 -61
  2. package/build.zig +674 -373
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +6 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +455 -3
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  12. package/packages/core/scripts/run_external_core_compiler.mjs +77 -6
  13. package/packages/core/scripts/run_external_service_compiler.mjs +240 -0
  14. package/packages/core/scripts/stage_external_core.mjs +9 -1
  15. package/packages/core/scripts/stage_external_services.mjs +172 -0
  16. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  17. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  18. package/packages/core/sdk/core.d.ts +214 -2
  19. package/packages/core/sdk/core.ts +715 -42
  20. package/packages/core/sdk/events.d.ts +50 -0
  21. package/packages/core/sdk/events.ts +75 -0
  22. package/packages/core/src/checker.ts +528 -15
  23. package/packages/core/src/cli.ts +143 -3
  24. package/packages/core/src/contract.ts +26 -5
  25. package/packages/core/src/devhost.ts +1849 -18
  26. package/packages/core/src/devhost_journal.mjs +181 -0
  27. package/packages/core/src/devhost_resolver.mjs +17 -1
  28. package/packages/core/src/devhost_service_worker.mjs +90 -0
  29. package/packages/core/src/diagnostics.ts +84 -18
  30. package/packages/core/src/frontend.ts +204 -34
  31. package/packages/core/src/modules.ts +129 -80
  32. package/packages/core/src/service_contract.ts +597 -0
  33. package/packages/core/src/sqlite_cli.ts +93 -0
  34. package/packages/core/src/sqlite_codegen.ts +806 -0
  35. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  36. package/packages/core/src/typed_ast.ts +36 -8
  37. package/skill-data/core/SKILL.md +4 -2
  38. package/skill-data/core/references/project-anatomy.md +3 -2
  39. package/skill-data/core/references/web-engines-packaging-debugging.md +3 -1
  40. package/skill-data/native-ui/SKILL.md +55 -8
  41. package/skill-data/ts-core/SKILL.md +92 -40
  42. package/skill-data/ts-services/SKILL.md +126 -0
  43. package/skill-data/ts-services/references/service-surface.md +603 -0
  44. package/skill-data/zig/SKILL.md +1 -1
  45. package/skills/native-sdk/SKILL.md +1 -1
  46. package/src/app_runner/no_migrations.zig +3 -0
  47. package/src/app_runner/no_services.zig +20 -0
  48. package/src/app_runner/root.zig +104 -4
  49. package/src/app_runner/ts_core_main.zig +268 -4
  50. package/src/automation/snapshot.zig +23 -5
  51. package/src/embed/app_exports.zig +11 -1
  52. package/src/embed/c_api.zig +48 -2
  53. package/src/embed/conversions.zig +4 -5
  54. package/src/embed/host.zig +115 -1
  55. package/src/embed/root.zig +7 -0
  56. package/src/embed/tests.zig +213 -0
  57. package/src/embed/types.zig +51 -0
  58. package/src/embed/ui_host.zig +121 -5
  59. package/src/platform/android/NativeSdkActivity.java +131 -0
  60. package/src/platform/android/android_host.c +182 -1
  61. package/src/platform/android/native_sdk_app.h +17 -0
  62. package/src/platform/ios/native_sdk_app.h +17 -0
  63. package/src/platform/ios/uikit_host.m +115 -0
  64. package/src/platform/linux/cef_host.cpp +1 -1
  65. package/src/platform/linux/gtk_host.c +89 -17
  66. package/src/platform/linux/gtk_host.h +3 -0
  67. package/src/platform/linux/root.zig +41 -18
  68. package/src/platform/macos/appkit_host.h +26 -3
  69. package/src/platform/macos/appkit_host.m +1051 -129
  70. package/src/platform/macos/capture_info_plist.c +25 -0
  71. package/src/platform/macos/cef_host.mm +270 -36
  72. package/src/platform/macos/root.zig +312 -34
  73. package/src/platform/null_platform.zig +281 -19
  74. package/src/platform/null_platform_tests.zig +74 -0
  75. package/src/platform/root.zig +16 -0
  76. package/src/platform/types.zig +279 -15
  77. package/src/platform/windows/root.zig +243 -21
  78. package/src/platform/windows/webview2_host.cpp +464 -46
  79. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  80. package/src/primitives/app_manifest/root.zig +4 -0
  81. package/src/primitives/app_manifest/tests.zig +3 -0
  82. package/src/primitives/app_manifest/types.zig +34 -0
  83. package/src/primitives/app_manifest/validation.zig +19 -1
  84. package/src/primitives/canvas/code_tests.zig +9 -9
  85. package/src/primitives/canvas/events.zig +12 -11
  86. package/src/primitives/canvas/frame.zig +44 -9
  87. package/src/primitives/canvas/icons/mic.svg +1 -0
  88. package/src/primitives/canvas/icons.zig +2 -0
  89. package/src/primitives/canvas/root.zig +8 -0
  90. package/src/primitives/canvas/text_span_tests.zig +39 -0
  91. package/src/primitives/canvas/ui.zig +23 -4
  92. package/src/primitives/canvas/ui_markup.zig +15 -0
  93. package/src/primitives/canvas/ui_markup_compiled.zig +9 -0
  94. package/src/primitives/canvas/ui_markup_compiled_tests.zig +1 -1
  95. package/src/primitives/canvas/ui_markup_tests.zig +5 -0
  96. package/src/primitives/canvas/ui_markup_view.zig +9 -0
  97. package/src/primitives/canvas/ui_markup_view_tests.zig +9 -6
  98. package/src/primitives/canvas/ui_schema.zig +19 -10
  99. package/src/primitives/canvas/ui_schema_tests.zig +5 -3
  100. package/src/primitives/canvas/ui_tests.zig +18 -4
  101. package/src/primitives/canvas/widget_invalidation.zig +9 -2
  102. package/src/primitives/canvas/widget_render.zig +296 -114
  103. package/src/primitives/canvas/widget_runtime_tests.zig +133 -0
  104. package/src/primitives/canvas/widget_text_input.zig +10 -10
  105. package/src/primitives/canvas/widget_tree.zig +1 -1
  106. package/src/primitives/canvas/widgets.zig +29 -5
  107. package/src/root.zig +56 -0
  108. package/src/runtime/api.zig +11 -0
  109. package/src/runtime/automation_snapshot.zig +4 -0
  110. package/src/runtime/automation_widget_dispatch.zig +1 -0
  111. package/src/runtime/bridge_payload.zig +2 -0
  112. package/src/runtime/bridge_permission_tests.zig +23 -2
  113. package/src/runtime/bridge_responses.zig +3 -1
  114. package/src/runtime/canvas_frame.zig +31 -13
  115. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  116. package/src/runtime/canvas_frame_invalidation_tests.zig +35 -10
  117. package/src/runtime/canvas_widget_anchored_tests.zig +83 -0
  118. package/src/runtime/canvas_widget_events.zig +69 -24
  119. package/src/runtime/canvas_widget_runtime.zig +101 -6
  120. package/src/runtime/canvas_widget_scroll_driver_tests.zig +47 -4
  121. package/src/runtime/canvas_widget_scroll_drivers.zig +3 -3
  122. package/src/runtime/canvas_widget_semantics_tests.zig +2 -0
  123. package/src/runtime/canvas_widget_split_tree_tests.zig +228 -0
  124. package/src/runtime/canvas_widget_state.zig +6 -1
  125. package/src/runtime/canvas_widget_text_tests.zig +112 -3
  126. package/src/runtime/clock.zig +13 -1
  127. package/src/runtime/core.zig +133 -1
  128. package/src/runtime/credentials_store.zig +115 -0
  129. package/src/runtime/effects.zig +2568 -75
  130. package/src/runtime/effects_audio_capture_tests.zig +251 -0
  131. package/src/runtime/effects_credentials_tests.zig +332 -0
  132. package/src/runtime/effects_host_tests.zig +208 -1
  133. package/src/runtime/effects_relational_tests.zig +314 -0
  134. package/src/runtime/effects_store_tests.zig +211 -0
  135. package/src/runtime/flow.zig +14 -1
  136. package/src/runtime/gpu_surface_events.zig +6 -1
  137. package/src/runtime/native_command_event_tests.zig +42 -0
  138. package/src/runtime/persist_store.zig +666 -0
  139. package/src/runtime/record_store.zig +788 -0
  140. package/src/runtime/relational_store.zig +854 -0
  141. package/src/runtime/root.zig +52 -0
  142. package/src/runtime/runtime_event_tests.zig +70 -0
  143. package/src/runtime/service_host.zig +711 -0
  144. package/src/runtime/service_pool.zig +1314 -0
  145. package/src/runtime/session_blobs.zig +1 -1
  146. package/src/runtime/session_journal.zig +102 -0
  147. package/src/runtime/session_record.zig +177 -0
  148. package/src/runtime/session_replay.zig +109 -4
  149. package/src/runtime/shell_layout.zig +1 -0
  150. package/src/runtime/shell_layout_tests.zig +120 -0
  151. package/src/runtime/sqlite_engine.zig +474 -0
  152. package/src/runtime/state.zig +6 -0
  153. package/src/runtime/system_services.zig +49 -10
  154. package/src/runtime/tests.zig +5 -0
  155. package/src/runtime/ts_core_host.zig +1189 -118
  156. package/src/runtime/ts_core_host_tests.zig +638 -11
  157. package/src/runtime/ts_ui_app.zig +537 -1
  158. package/src/runtime/ui_app.zig +160 -19
  159. package/src/runtime/ui_app_tests.zig +203 -5
  160. package/src/runtime/validation.zig +22 -0
  161. package/src/runtime/view.zig +11 -0
  162. package/src/runtime/view_widget_scroll.zig +56 -5
  163. package/src/runtime/view_widget_text.zig +24 -5
  164. package/src/runtime/view_widget_tree.zig +1 -1
  165. package/src/runtime/window_storage.zig +1 -0
  166. package/src/runtime/window_view_runtime.zig +2 -3
  167. package/src/runtime/window_views.zig +19 -0
  168. package/src/tooling/android.zig +21 -16
  169. package/src/tooling/db.zig +160 -0
  170. package/src/tooling/ios.zig +7 -1
  171. package/src/tooling/manifest.zig +1248 -2
  172. package/src/tooling/package.zig +953 -6
  173. package/src/tooling/raw_manifest.zig +65 -0
  174. package/src/tooling/root.zig +1 -0
  175. package/src/tooling/templates.zig +216 -4
  176. package/src/tooling/ts_core.zig +283 -17
  177. package/src/tooling/verbs.zig +7 -0
  178. package/third_party/sqlite/README.md +13 -0
  179. package/third_party/sqlite/sqlite3.c +269649 -0
  180. package/third_party/sqlite/sqlite3.h +14349 -0
  181. package/tools/corewire/core_abi.zig +14 -2
  182. package/tools/corewire/emit.zig +98 -29
  183. package/tools/corewire/emit_facade.zig +414 -23
  184. package/tools/corewire/emit_profile.zig +6 -2
  185. package/tools/corewire/emit_service.zig +924 -0
  186. package/tools/corewire/main.zig +122 -0
  187. package/tools/corewire/service_contract.zig +250 -0
  188. package/tools/corewire/sidecar.zig +26 -15
@@ -14,6 +14,9 @@
14
14
  // {"advance": 500} advance the virtual clock 500ms,
15
15
  // firing due Sub timers and Cmd.delay
16
16
  // one-shots in time order
17
+ // {"restart": true} simulate a new process boot; an
18
+ // in-memory Cmd.persist snapshot restores
19
+ // through the configured boot route
17
20
  //
18
21
  // Transcript, one line per fact:
19
22
  // model <json> the committed model after a dispatch
@@ -33,8 +36,12 @@
33
36
  // - timer/now/delay arms carry exactly one number payload field (pinned
34
37
  // by tsc), so the harness constructs them shape-directed without
35
38
  // needing the field's name.
36
- // Every other effect (files, fetch, clipboard, notifications, spawn, audio,
37
- // host commands)
39
+ // Cmd.persist snapshots the committed model in virtual-host memory, and
40
+ // capability-enabled Cmd.store performs against a process-local byte map;
41
+ // Cmd.db uses a real process-local SQLite database, and typed app services
42
+ // execute directly through their generated contract.
43
+ // Every other effect (files, buffered/streaming fetch, clipboard,
44
+ // notifications, spawn, audio, raw host commands)
38
45
  // is printed as `cmd ...` and NOT performed — feed its result back yourself
39
46
  // as an ordinary Msg line. That is the point: results are plain messages,
40
47
  // and the loop stays deterministic.
@@ -43,8 +50,15 @@ import fs from "node:fs";
43
50
  import path from "node:path";
44
51
  import readline from "node:readline";
45
52
  import { register } from "node:module";
53
+ import { constants as sqliteConstants, DatabaseSync } from "node:sqlite";
46
54
  import { pathToFileURL } from "node:url";
55
+ import os from "node:os";
56
+ import crypto from "node:crypto";
57
+ import { Worker } from "node:worker_threads";
47
58
  import { installTextMethods } from "./text_polyfill.ts";
59
+ import { checkFile, formatDiagnostic } from "./frontend.ts";
60
+ import { DevhostJournalWriter, readDevhostJournal, requestKeyBase } from "./devhost_journal.mjs";
61
+ import { inspectRelationalSql, relationalRuntimePolicy, setRelationalAuthorizer } from "./sqlite_runtime_policy.ts";
48
62
 
49
63
  interface Cmdish {
50
64
  readonly op: string;
@@ -52,7 +66,7 @@ interface Cmdish {
52
66
  }
53
67
 
54
68
  function usage(): never {
55
- console.error("usage: devhost.ts <core.ts> [--script <msgs.ndjson>]");
69
+ console.error("usage: devhost.ts <core.ts> [--script <msgs.ndjson>] [--service-cwd <app-data-dir>] [--app-id <id>] [--capability <name>]... [--permission <name>]... [--sdk-core <generated-core.ts>] [--sqlite-src <src>]");
56
70
  console.error("core-logic loop only (update/effects under a virtual host) - not a renderer;");
57
71
  console.error("run the real app with `native dev`.");
58
72
  process.exit(2);
@@ -61,13 +75,91 @@ function usage(): never {
61
75
  const args = process.argv.slice(2);
62
76
  let entry: string | null = null;
63
77
  let script: string | null = null;
78
+ let persistOk: string | null = null;
79
+ let persistNone: string | null = null;
80
+ let persistErr: string | null = null;
81
+ let sdkCore: string | null = null;
82
+ let sqliteSrc: string | null = null;
83
+ let journalRecordArg: string | null = null;
84
+ let journalReplayArg: string | null = null;
85
+ let serviceCwd: string | null = null;
86
+ let canvasLabel = "canvas";
87
+ let windowWidth = 800;
88
+ let windowHeight = 600;
89
+ let appName: string | null = null;
90
+ let appId = "app";
91
+ const servicePackages: { name: string; version: string; content_hash: string }[] = [];
92
+ const capabilities = new Set<string>();
93
+ const permissions = new Set<string>();
64
94
  for (let i = 0; i < args.length; i++) {
65
95
  if (args[i] === "--script") script = args[++i] ?? null;
96
+ else if (args[i] === "--capability") {
97
+ const capability = args[++i] ?? null;
98
+ if (capability === null) usage();
99
+ capabilities.add(capability);
100
+ }
101
+ else if (args[i] === "--permission") {
102
+ const permission = args[++i] ?? null;
103
+ if (permission === null) usage();
104
+ permissions.add(permission);
105
+ }
106
+ else if (args[i] === "--persist-ok") persistOk = args[++i] ?? null;
107
+ else if (args[i] === "--persist-none") persistNone = args[++i] ?? null;
108
+ else if (args[i] === "--persist-err") persistErr = args[++i] ?? null;
109
+ else if (args[i] === "--sdk-core") sdkCore = args[++i] ?? null;
110
+ else if (args[i] === "--sqlite-src") sqliteSrc = args[++i] ?? null;
111
+ else if (args[i] === "--record-journal") journalRecordArg = args[++i] ?? null;
112
+ else if (args[i] === "--replay-journal") journalReplayArg = args[++i] ?? null;
113
+ else if (args[i] === "--service-cwd") serviceCwd = args[++i] ?? null;
114
+ else if (args[i] === "--canvas-label") canvasLabel = args[++i] ?? canvasLabel;
115
+ else if (args[i] === "--window-width") windowWidth = Number(args[++i]);
116
+ else if (args[i] === "--window-height") windowHeight = Number(args[++i]);
117
+ else if (args[i] === "--app-name") appName = args[++i] ?? null;
118
+ else if (args[i] === "--app-id") appId = args[++i] ?? appId;
119
+ else if (args[i] === "--service-package") {
120
+ const [name, version, content_hash] = (args[++i] ?? "").split("|");
121
+ if (!name || !version || !/^[0-9a-f]{64}$/.test(content_hash ?? "")) usage();
122
+ servicePackages.push({ name, version, content_hash });
123
+ }
66
124
  else if (args[i] === "--help" || args[i] === "-h") usage();
67
125
  else if (!args[i].startsWith("-")) entry = args[i];
68
126
  else usage();
69
127
  }
70
128
  if (!entry) usage();
129
+ if (!Number.isFinite(windowWidth) || windowWidth <= 0 || !Number.isFinite(windowHeight) || windowHeight <= 0) usage();
130
+ const launchCwd = process.cwd();
131
+ entry = path.resolve(launchCwd, entry);
132
+ if (script !== null) script = path.resolve(launchCwd, script);
133
+ if (serviceCwd !== null) serviceCwd = path.resolve(launchCwd, serviceCwd);
134
+ const journalRecordValue = process.env.NATIVE_SDK_SESSION_RECORD ?? journalRecordArg;
135
+ const journalReplayValue = process.env.NATIVE_SDK_SESSION_REPLAY ?? journalReplayArg;
136
+ const journalRecordPath = journalRecordValue ? path.resolve(launchCwd, journalRecordValue) : null;
137
+ const journalReplayPath = journalReplayValue ? path.resolve(launchCwd, journalReplayValue) : null;
138
+ if (journalRecordPath && journalReplayPath) throw new Error("record and replay cannot be armed together");
139
+ if (serviceCwd !== null) {
140
+ fs.mkdirSync(serviceCwd, { recursive: true });
141
+ process.chdir(serviceCwd);
142
+ }
143
+ const persistRouteCount = [persistOk, persistNone, persistErr].filter((route) => route !== null).length;
144
+ if (persistRouteCount !== 0 && persistRouteCount !== 3) usage();
145
+ let checked: ReturnType<typeof checkFile> | null = null;
146
+ if (capabilities.size > 0 || permissions.size > 0 || (persistOk !== null && persistNone !== null && persistErr !== null) || fs.existsSync(path.join(path.dirname(path.resolve(entry)), "services"))) {
147
+ // Type information is erased by the time this module imports the app core.
148
+ // Run the frontend inside the watched process so every node --watch restart
149
+ // revalidates manifest-owned routes against the newly edited Msg union.
150
+ checked = checkFile(entry, {
151
+ capabilities: [...new Set([...capabilities, ...(persistOk === null ? [] : ["persist"])])],
152
+ permissions: [...permissions],
153
+ persistRoutes: persistOk !== null && persistNone !== null && persistErr !== null ? { ok: persistOk, none: persistNone, err: persistErr } : undefined,
154
+ servicesContract: true,
155
+ servicePackages,
156
+ sdkCorePath: sdkCore ?? undefined,
157
+ });
158
+ for (const error of checked.typeErrors) console.error(error);
159
+ for (const diagnostic of checked.diagnostics) console.error(formatDiagnostic(diagnostic));
160
+ for (const warning of checked.warnings) console.error(formatDiagnostic(warning, "warning"));
161
+ if (!checked.ok) process.exit(1);
162
+ }
71
163
 
72
164
  // The resolver hook maps "@native-sdk/core" onto this package's own SDK
73
165
  // module (app trees carry no node_modules for bare resolution to find),
@@ -75,7 +167,101 @@ if (!entry) usage();
75
167
  // on Uint8Array.prototype before the core loads — locale-free simple
76
168
  // case tables, the semantics the compiled core carries natively.
77
169
  installTextMethods();
78
- register(new URL("./devhost_resolver.mjs", import.meta.url));
170
+ const devScratch = fs.mkdtempSync(path.join(os.tmpdir(), "native-services-dev-"));
171
+ const servicesClientPath = path.join(devScratch, "services.gen.ts");
172
+ if (checked?.servicesClient) {
173
+ fs.writeFileSync(servicesClientPath, checked.servicesClient);
174
+ const editorDir = path.join(path.dirname(path.dirname(path.resolve(entry))), "node_modules", "@native-sdk", "services");
175
+ fs.mkdirSync(editorDir, { recursive: true });
176
+ const sourcePrefix = path.relative(editorDir, path.dirname(path.resolve(entry))).split(path.sep).join("/");
177
+ fs.writeFileSync(path.join(editorDir, "index.ts"), checked.servicesClient.replaceAll('from "./', `from "${sourcePrefix}/`));
178
+ fs.writeFileSync(path.join(editorDir, "package.json"), `${JSON.stringify({
179
+ name: "@native-sdk/services",
180
+ private: true,
181
+ type: "module",
182
+ types: "./index.ts",
183
+ exports: { ".": { types: "./index.ts", default: "./index.ts" } },
184
+ }, null, 2)}\n`);
185
+ }
186
+
187
+ function packageRuntimeEntry(packageName: string): string {
188
+ const packageRoot = path.join(path.dirname(path.resolve(entry!)), "services", "vendor", ...packageName.split("/"));
189
+ const manifest = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8")) as Record<string, unknown>;
190
+ let target: unknown = manifest.module ?? manifest.main ?? "index.js";
191
+ const exportsField = manifest.exports;
192
+ if (typeof exportsField === "string") target = exportsField;
193
+ else if (exportsField && typeof exportsField === "object") {
194
+ const rootExport = (exportsField as Record<string, unknown>)["."] ?? exportsField;
195
+ if (typeof rootExport === "string") target = rootExport;
196
+ else if (rootExport && typeof rootExport === "object") {
197
+ const choices = rootExport as Record<string, unknown>;
198
+ target = choices.import ?? choices.node ?? choices.default ?? target;
199
+ }
200
+ }
201
+ if (typeof target !== "string") throw new Error(`cannot resolve the runtime entry of vendored service package ${packageName}`);
202
+ return pathToFileURL(path.resolve(packageRoot, target)).href;
203
+ }
204
+
205
+ function verifyDevPackage(packageEntry: { name: string; version: string; content_hash: string }): void {
206
+ const packageRoot = path.join(path.dirname(path.resolve(entry!)), "services", "vendor", ...packageEntry.name.split("/"));
207
+ const manifest = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8")) as { name?: string; version?: string };
208
+ if (manifest.name !== packageEntry.name || manifest.version !== packageEntry.version) {
209
+ throw new Error(`vendored ${packageEntry.name} is ${manifest.name ?? "?"}@${manifest.version ?? "?"}, expected ${packageEntry.name}@${packageEntry.version}`);
210
+ }
211
+ const files: { rel: string; absolute: string }[] = [];
212
+ const walk = (current: string, prefix = ""): void => {
213
+ for (const item of fs.readdirSync(current, { withFileTypes: true })) {
214
+ const rel = prefix ? `${prefix}/${item.name}` : item.name;
215
+ const absolute = path.join(current, item.name);
216
+ if (item.isSymbolicLink()) throw new Error(`vendored package contains a symlink: ${rel}`);
217
+ if (item.isDirectory()) walk(absolute, rel);
218
+ else if (item.isFile()) files.push({ rel, absolute });
219
+ }
220
+ };
221
+ walk(packageRoot);
222
+ files.sort((a, b) => a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0);
223
+ const hash = crypto.createHash("sha256");
224
+ hash.update("native-sdk.service-package.v1\0");
225
+ for (const file of files) {
226
+ const bytes = fs.readFileSync(file.absolute);
227
+ const size = Buffer.alloc(8);
228
+ size.writeBigUInt64LE(BigInt(bytes.length));
229
+ hash.update(file.rel); hash.update("\0"); hash.update(size); hash.update(bytes);
230
+ }
231
+ const actual = hash.digest("hex");
232
+ if (actual !== packageEntry.content_hash) throw new Error(`vendored ${packageEntry.name}@${packageEntry.version} hashes to ${actual}, expected ${packageEntry.content_hash}`);
233
+ }
234
+
235
+ for (const packageEntry of servicePackages) verifyDevPackage(packageEntry);
236
+
237
+ const resolverData = {
238
+ generatedCoreUrl: sdkCore === null ? null : pathToFileURL(path.resolve(sdkCore)).href,
239
+ servicesClientUrl: checked?.servicesClient ? pathToFileURL(servicesClientPath).href : null,
240
+ servicePackages: Object.fromEntries(servicePackages.map((packageEntry) => [packageEntry.name, packageRuntimeEntry(packageEntry.name)])),
241
+ };
242
+ register(new URL("./devhost_resolver.mjs", import.meta.url), { data: resolverData });
243
+
244
+ interface ServiceTypeRef {
245
+ readonly kind: string;
246
+ readonly name?: string;
247
+ readonly inner?: ServiceTypeRef;
248
+ readonly elem?: ServiceTypeRef;
249
+ }
250
+ interface ServiceOperationRuntime {
251
+ readonly name: string;
252
+ readonly module: string;
253
+ readonly export: string;
254
+ readonly request: ServiceTypeRef;
255
+ readonly result: ServiceTypeRef;
256
+ readonly deadline_ms: number | null;
257
+ readonly cancellable: boolean;
258
+ readonly stream: { readonly chunk: ServiceTypeRef; readonly in_flight: number } | null;
259
+ }
260
+ const serviceContract = checked?.servicesContract ? JSON.parse(checked.servicesContract) as {
261
+ operations: ServiceOperationRuntime[];
262
+ types: { records: { name: string; fields: { name: string; type: ServiceTypeRef }[] }[]; enums: { name: string; members: string[] }[]; unions: { name: string; arms: { name: string; fields: { name: string; type: ServiceTypeRef }[] }[] }[] };
263
+ } : null;
264
+ const serviceOperations = new Map(serviceContract?.operations.map((operation) => [operation.name, operation]) ?? []);
79
265
 
80
266
  const mod = await import(pathToFileURL(path.resolve(entry)).href);
81
267
  if (typeof mod.initialModel !== "function" || typeof mod.update !== "function") {
@@ -86,6 +272,7 @@ if (typeof mod.initialModel !== "function" || typeof mod.update !== "function")
86
272
  // ---------------------------------------------------------- transcript i/o
87
273
 
88
274
  const decoder = new TextDecoder();
275
+ const strictDecoder = new TextDecoder("utf-8", { fatal: true });
89
276
  const encoder = new TextEncoder();
90
277
 
91
278
  function jsonable(value: unknown): unknown {
@@ -124,6 +311,190 @@ let now = 0;
124
311
  const timers = new Map<string, { everyMs: number; msgKind: string; nextAt: number }>();
125
312
  /// Armed one-shots (Cmd.delay), by key.
126
313
  const delays = new Map<string, { msgKind: string; at: number }>();
314
+ const serviceChannels = new Map<number, string>();
315
+ /// Process-local Tier-1 store. `structuredClone` preserves Uint8Array and
316
+ /// nested model data without making the app own a serialization format.
317
+ let persistedModel: unknown | null = null;
318
+ interface VirtualStoreRecord {
319
+ readonly key: Uint8Array;
320
+ readonly value: Uint8Array;
321
+ }
322
+
323
+ /// Process-local Tier-2 store. Like SQLite, record identity is the encoded
324
+ /// UTF-8 key rather than the source JavaScript string. That distinction is
325
+ /// observable for ill-formed UTF-16: TextEncoder canonicalizes every lone
326
+ /// surrogate to U+FFFD, so strings with the same encoded bytes must address
327
+ /// one record here just as they do in the native host.
328
+ const recordStore = new Map<string, VirtualStoreRecord>();
329
+ /// Process-local Tier-4 backing. The namespace includes the manifest app id,
330
+ /// matching the native keychain service/account split. Transcript output
331
+ /// never includes the stored bytes.
332
+ const credentialStore = new Map<string, Uint8Array>();
333
+ const maxCredentialSecretBytes = 5 * 512;
334
+
335
+ interface PendingStoreResult {
336
+ readonly seq: number;
337
+ readonly routeKey: string;
338
+ readonly okKind: string;
339
+ readonly errKind: string;
340
+ readonly ok: boolean;
341
+ readonly okVoid: boolean;
342
+ readonly bytes: Uint8Array;
343
+ active: boolean;
344
+ }
345
+
346
+ /// Store operations are performed in command-stream order, but their routed
347
+ /// results wait until the dispatch's complete command walk has returned. This
348
+ /// is the native effect boundary: a later command in one Cmd.batch can replace
349
+ /// or cancel an earlier result before either arm runs.
350
+ const pendingStoreResults: PendingStoreResult[] = [];
351
+ const pendingStoreByKey = new Map<string, PendingStoreResult>();
352
+ let dispatchDepth = 0;
353
+ let nextEffectResultSeq = 1;
354
+ let drainingEffectResults = false;
355
+
356
+ type DbOutcome = "constraint" | "busy" | "io_failed" | "corrupt" | "misuse" | "rejected" | "cancelled";
357
+ type DbResultKind = "page" | "done" | "exec";
358
+
359
+ interface PendingDbOperation {
360
+ readonly routeKey: string;
361
+ readonly query: boolean;
362
+ readonly live: boolean;
363
+ readonly pageKind: string;
364
+ readonly doneKind: string;
365
+ readonly errKind: string;
366
+ active: boolean;
367
+ }
368
+
369
+ interface PendingDbResult {
370
+ readonly seq: number;
371
+ readonly operation: PendingDbOperation;
372
+ readonly kind: DbResultKind;
373
+ readonly outcome: "ok" | DbOutcome;
374
+ readonly bytes: Uint8Array;
375
+ }
376
+
377
+ const relationalDb = new DatabaseSync(":memory:");
378
+ relationalDb.exec("PRAGMA foreign_keys=ON; PRAGMA busy_timeout=250;");
379
+ let relationalTrackWrites = false;
380
+ let relationalAllowTransaction = false;
381
+ const relationalChangedTables = new Set<string>();
382
+ let relationalChangedAllTables = false;
383
+ const relationalSchemaActions = new Set([
384
+ sqliteConstants.SQLITE_CREATE_INDEX, sqliteConstants.SQLITE_CREATE_TABLE,
385
+ sqliteConstants.SQLITE_CREATE_TEMP_INDEX, sqliteConstants.SQLITE_CREATE_TEMP_TABLE,
386
+ sqliteConstants.SQLITE_CREATE_TEMP_TRIGGER, sqliteConstants.SQLITE_CREATE_TEMP_VIEW,
387
+ sqliteConstants.SQLITE_CREATE_TRIGGER, sqliteConstants.SQLITE_CREATE_VIEW,
388
+ sqliteConstants.SQLITE_DROP_INDEX, sqliteConstants.SQLITE_DROP_TABLE,
389
+ sqliteConstants.SQLITE_DROP_TEMP_INDEX, sqliteConstants.SQLITE_DROP_TEMP_TABLE,
390
+ sqliteConstants.SQLITE_DROP_TEMP_TRIGGER, sqliteConstants.SQLITE_DROP_TEMP_VIEW,
391
+ sqliteConstants.SQLITE_DROP_TRIGGER, sqliteConstants.SQLITE_DROP_VIEW,
392
+ sqliteConstants.SQLITE_ALTER_TABLE, sqliteConstants.SQLITE_CREATE_VTABLE,
393
+ sqliteConstants.SQLITE_DROP_VTABLE,
394
+ ]);
395
+ const relationalAuthorizer = (action: number, first: string | null, second: string | null): number => {
396
+ if (relationalTrackWrites && relationalSchemaActions.has(action)) relationalChangedAllTables = true;
397
+ if (relationalTrackWrites && first !== null &&
398
+ (action === sqliteConstants.SQLITE_INSERT || action === sqliteConstants.SQLITE_UPDATE || action === sqliteConstants.SQLITE_DELETE)) {
399
+ relationalChangedTables.add(first);
400
+ }
401
+ if (!relationalAllowTransaction &&
402
+ (action === sqliteConstants.SQLITE_TRANSACTION || action === sqliteConstants.SQLITE_SAVEPOINT)) {
403
+ return sqliteConstants.SQLITE_DENY;
404
+ }
405
+ return relationalRuntimePolicy(action, first, second);
406
+ };
407
+ const relationalAuthorizerAvailable = setRelationalAuthorizer(relationalDb, relationalAuthorizer);
408
+
409
+ function applyDevMigrations(src: string): void {
410
+ const schemaDir = path.join(src, "schema");
411
+ if (!fs.existsSync(schemaDir)) return;
412
+ const names = fs.readdirSync(schemaDir)
413
+ .filter((name) => /^\d{4}_[a-z0-9][a-z0-9_-]*\.sql$/.test(name))
414
+ .sort();
415
+ for (let i = 0; i < names.length; i++) {
416
+ const expected = String(i + 1).padStart(4, "0") + "_";
417
+ if (!names[i]!.startsWith(expected)) throw new Error(`SQLite migration chain must be contiguous at ${expected}*.sql`);
418
+ }
419
+ if (relationalAuthorizerAvailable) setRelationalAuthorizer(relationalDb, null);
420
+ try {
421
+ relationalDb.exec("BEGIN IMMEDIATE;");
422
+ if (relationalAuthorizerAvailable) setRelationalAuthorizer(relationalDb, relationalAuthorizer);
423
+ for (let i = 0; i < names.length; i++) {
424
+ let tail = fs.readFileSync(path.join(schemaDir, names[i]!), "utf8");
425
+ while (dbTailHasStatement(tail, "")) {
426
+ const statement = relationalDb.prepare(tail);
427
+ const inspection = inspectRelationalSql(statement.sourceSQL, true);
428
+ if (inspection.error !== null) throw new Error(inspection.error);
429
+ statement.run();
430
+ tail = tail.slice(statement.sourceSQL.length);
431
+ }
432
+ }
433
+ if (relationalAuthorizerAvailable) setRelationalAuthorizer(relationalDb, null);
434
+ relationalDb.exec(`PRAGMA user_version=${names.length};`);
435
+ relationalDb.exec("COMMIT;");
436
+ } catch (reason) {
437
+ if (relationalAuthorizerAvailable) setRelationalAuthorizer(relationalDb, null);
438
+ try { relationalDb.exec("ROLLBACK;"); } catch {}
439
+ throw reason;
440
+ } finally {
441
+ if (relationalAuthorizerAvailable) setRelationalAuthorizer(relationalDb, relationalAuthorizer);
442
+ }
443
+ }
444
+
445
+ if (sqliteSrc !== null) applyDevMigrations(sqliteSrc);
446
+
447
+ function setRelationalQueryOnly(enabled: boolean): void {
448
+ if (relationalAuthorizerAvailable) setRelationalAuthorizer(relationalDb, null);
449
+ try {
450
+ relationalDb.exec(`PRAGMA query_only=${enabled ? "ON" : "OFF"};`);
451
+ } finally {
452
+ if (relationalAuthorizerAvailable) setRelationalAuthorizer(relationalDb, relationalAuthorizer);
453
+ }
454
+ }
455
+
456
+ function relationalTransaction(sql: "BEGIN IMMEDIATE;" | "COMMIT;" | "ROLLBACK;"): void {
457
+ relationalAllowTransaction = true;
458
+ try {
459
+ relationalDb.exec(sql);
460
+ } finally {
461
+ relationalAllowTransaction = false;
462
+ }
463
+ }
464
+ const pendingDbResults: PendingDbResult[] = [];
465
+ const pendingDbByKey = new Map<string, PendingDbOperation>();
466
+ /// The packaged TS bridge and Zig Effects host share one fixed relational
467
+ /// slot family. Track every devhost operation explicitly too: keyed,
468
+ /// unkeyed, one-shot, and live subscriptions all consume the same capacity.
469
+ const activeDbOperations = new Set<PendingDbOperation>();
470
+
471
+ interface LiveDbSubscription {
472
+ readonly operation: PendingDbOperation;
473
+ readonly signature: string;
474
+ readonly sql: string;
475
+ readonly params: readonly unknown[];
476
+ readonly tables: readonly string[];
477
+ }
478
+
479
+ const liveDbByKey = new Map<string, LiveDbSubscription>();
480
+ const dirtyLiveDbKeys = new Set<string>();
481
+
482
+ const maxStoreKeyBytes = 512;
483
+ const maxStoreValueBytes = 1024 * 1024;
484
+ const maxStoreBatchEntries = 64;
485
+ const maxStoreBatchBytes = 8 * 1024 * 1024;
486
+ const maxStoreScanLimit = 256;
487
+ const maxStoreResultBytes = maxStoreValueBytes + (2 * maxStoreKeyBytes) + 32;
488
+ const maxDbEffects = 16;
489
+ const maxDbSqlBytes = 64 * 1024;
490
+ const maxDbParameters = 64;
491
+ const maxDbExecStatements = 64;
492
+ const maxDbParameterBytes = 1024 * 1024;
493
+ const maxDbExecParameterBytes = 8 * 1024 * 1024;
494
+ const maxDbPageRows = 256;
495
+ const maxDbPageBytes = 256 * 1024;
496
+ const maxDbResultRows = 8 * 1024;
497
+ const maxDbResultBytes = 8 * 1024 * 1024;
127
498
 
128
499
  /// Timer/now/delay arms carry exactly one number payload field (tsc pins
129
500
  /// the shape), so a proxy that answers every non-kind read with the
@@ -138,6 +509,1154 @@ function timestampMsg(kind: string, atMs: number): unknown {
138
509
  );
139
510
  }
140
511
 
512
+ function bytesMsg(kind: string, bytes: Uint8Array): unknown {
513
+ return new Proxy(
514
+ { kind },
515
+ {
516
+ get: (_target, prop) => (prop === "kind" ? kind : bytes),
517
+ has: () => true,
518
+ },
519
+ );
520
+ }
521
+
522
+ function valueMsg(kind: string, value: unknown): unknown {
523
+ return new Proxy({ kind }, { get: (_target, prop) => prop === "kind" ? kind : value, has: () => true });
524
+ }
525
+
526
+ class ServiceReader {
527
+ at = 0;
528
+ readonly bytes: Uint8Array;
529
+ constructor(bytes: Uint8Array) { this.bytes = bytes; }
530
+ take(length: number): Uint8Array {
531
+ if (this.at + length > this.bytes.length) throw new Error("truncated service value");
532
+ const value = this.bytes.subarray(this.at, this.at + length);
533
+ this.at += length;
534
+ return value;
535
+ }
536
+ u8(): number { return this.take(1)[0]; }
537
+ u32(): number { const b = this.take(4); return (b[0] | b[1] << 8 | b[2] << 16 | b[3] << 24) >>> 0; }
538
+ f64(): number { const b = this.take(8); return new DataView(b.buffer, b.byteOffset, 8).getFloat64(0, true); }
539
+ i64(): number { const b = this.take(8); const v = new DataView(b.buffer, b.byteOffset, 8); return v.getUint32(0, true) + v.getInt32(4, true) * 4294967296; }
540
+ }
541
+
542
+ function decodeServiceValue(type: ServiceTypeRef, reader: ServiceReader): unknown {
543
+ switch (type.kind) {
544
+ case "bool": { const value = reader.u8(); if (value > 1) throw new Error("invalid service boolean"); return value === 1; }
545
+ case "f64": return reader.f64();
546
+ case "i64": return reader.i64();
547
+ case "bytes": return reader.take(reader.u32());
548
+ case "optional": { const present = reader.u8(); if (present === 0) return null; if (present !== 1) throw new Error("invalid service optional"); return decodeServiceValue(type.inner!, reader); }
549
+ case "slice": { const count = reader.u32(); return Array.from({ length: count }, () => decodeServiceValue(type.elem!, reader)); }
550
+ case "record": {
551
+ const record = serviceContract!.types.records.find((candidate) => candidate.name === type.name)!;
552
+ return Object.fromEntries(record.fields.map((field) => [field.name, decodeServiceValue(field.type, reader)]));
553
+ }
554
+ case "enum": {
555
+ const enumType = serviceContract!.types.enums.find((candidate) => candidate.name === type.name)!;
556
+ const value = enumType.members[reader.u32()];
557
+ if (value === undefined) throw new Error("invalid service enum");
558
+ return value;
559
+ }
560
+ case "union": {
561
+ const unionType = serviceContract!.types.unions.find((candidate) => candidate.name === type.name)!;
562
+ const arm = unionType.arms[reader.u8()];
563
+ if (!arm) throw new Error("invalid service union");
564
+ return { kind: arm.name, ...Object.fromEntries(arm.fields.map((field) => [field.name, decodeServiceValue(field.type, reader)])) };
565
+ }
566
+ default: throw new Error(`unsupported service type ${type.kind}`);
567
+ }
568
+ }
569
+
570
+ function serviceErrorBytes(error: unknown): Uint8Array {
571
+ if (error && typeof error === "object") {
572
+ const value = error as { kind?: unknown; name?: unknown; message?: unknown };
573
+ const kind = typeof value.kind === "string" ? value.kind : typeof value.name === "string" ? value.name : "service_error";
574
+ const message = typeof value.message === "string" ? value.message : "service operation threw";
575
+ return encoder.encode(JSON.stringify({ kind, message }));
576
+ }
577
+ return encoder.encode(JSON.stringify({ kind: "service_error", message: "service operation threw" }));
578
+ }
579
+
580
+ function serviceU32(value: number): Uint8Array {
581
+ return new Uint8Array([value & 255, (value >>> 8) & 255, (value >>> 16) & 255, (value >>> 24) & 255]);
582
+ }
583
+
584
+ function concatService(parts: readonly Uint8Array[]): Uint8Array {
585
+ const out = new Uint8Array(parts.reduce((length, part) => length + part.length, 0));
586
+ let at = 0;
587
+ for (const part of parts) { out.set(part, at); at += part.length; }
588
+ return out;
589
+ }
590
+
591
+ function encodeServiceValue(type: ServiceTypeRef, value: unknown): Uint8Array {
592
+ switch (type.kind) {
593
+ case "bool": return new Uint8Array([value ? 1 : 0]);
594
+ case "f64": { const out = new Uint8Array(8); new DataView(out.buffer).setFloat64(0, value as number, true); return out; }
595
+ case "i64": {
596
+ const out = new Uint8Array(8); const view = new DataView(out.buffer); const number = value as number; const base = 4294967296;
597
+ let low = number % base; if (low < 0) low += base;
598
+ view.setUint32(0, low, true); view.setInt32(4, Math.floor(number / base), true); return out;
599
+ }
600
+ case "bytes": return concatService([serviceU32((value as Uint8Array).length), value as Uint8Array]);
601
+ case "optional": return value === null ? new Uint8Array([0]) : concatService([new Uint8Array([1]), encodeServiceValue(type.inner!, value)]);
602
+ case "slice": return concatService([serviceU32((value as unknown[]).length), ...(value as unknown[]).map((item) => encodeServiceValue(type.elem!, item))]);
603
+ case "record": {
604
+ const record = serviceContract!.types.records.find((candidate) => candidate.name === type.name)!;
605
+ return concatService(record.fields.map((field) => encodeServiceValue(field.type, (value as Record<string, unknown>)[field.name])));
606
+ }
607
+ case "enum": {
608
+ const enumType = serviceContract!.types.enums.find((candidate) => candidate.name === type.name)!;
609
+ return serviceU32(enumType.members.indexOf(value as string));
610
+ }
611
+ case "union": {
612
+ const unionType = serviceContract!.types.unions.find((candidate) => candidate.name === type.name)!;
613
+ const record = value as Record<string, unknown>;
614
+ const index = unionType.arms.findIndex((arm) => arm.name === record.kind);
615
+ const arm = unionType.arms[index];
616
+ return concatService([new Uint8Array([index]), ...arm.fields.map((field) => encodeServiceValue(field.type, record[field.name]))]);
617
+ }
618
+ default: throw new Error(`unsupported service type ${type.kind}`);
619
+ }
620
+ }
621
+
622
+ function channelMsg(
623
+ kind: string,
624
+ key: number,
625
+ state: "data" | "closed" | "rejected",
626
+ bytes = new Uint8Array(0),
627
+ droppedPending = 0,
628
+ droppedTotal = 0,
629
+ ): unknown {
630
+ return { kind, key, state, bytes, droppedPending, droppedTotal };
631
+ }
632
+
633
+ interface ServiceTask {
634
+ readonly id: number;
635
+ readonly cmd: Cmdish;
636
+ readonly operation: ServiceOperationRuntime;
637
+ readonly request: unknown;
638
+ readonly channelKey: number | null;
639
+ readonly channelEvent: string | null;
640
+ readonly cancelFlag: Int32Array;
641
+ readonly streamStateBuffer: SharedArrayBuffer;
642
+ readonly streamInFlight: Int32Array;
643
+ readonly streamDrops: BigUint64Array;
644
+ readonly engineIndex: number;
645
+ readonly deadlineAt: number | null;
646
+ deadlineTimer: ReturnType<typeof setTimeout> | null;
647
+ hardTimer: ReturnType<typeof setTimeout> | null;
648
+ cancelled: boolean;
649
+ timedOut: boolean;
650
+ responseDelivered: boolean;
651
+ chunks: number;
652
+ }
653
+
654
+ const cooperativeCancelGraceMs = 100;
655
+ const serviceQueue: ServiceTask[] = [];
656
+ const serviceTasksByKey = new Map<string, ServiceTask>();
657
+ const serviceIdleWaiters: (() => void)[] = [];
658
+ const serviceRequestSlots: (ServiceTask | null)[] = Array.from({ length: 16 }, () => null);
659
+ let activeService: ServiceTask | null = null;
660
+ let serviceWorker: Worker | null = null;
661
+ let serviceWorkerReady = false;
662
+ let serviceRestart: Promise<void> | null = null;
663
+ let nextServiceId = 1;
664
+ let journalWriter: DevhostJournalWriter | null = null;
665
+
666
+ function releaseServiceSlot(task: ServiceTask): void {
667
+ if (serviceRequestSlots[task.engineIndex] === task) serviceRequestSlots[task.engineIndex] = null;
668
+ }
669
+
670
+ function takeServiceStreamDrops(task: ServiceTask): { pending: number; total: number } {
671
+ const mask = 0xffffffffn;
672
+ for (;;) {
673
+ const current = Atomics.load(task.streamDrops, 0);
674
+ const total = current >> 32n;
675
+ if (Atomics.compareExchange(task.streamDrops, 0, current, total << 32n) === current) {
676
+ return { pending: Number(current & mask), total: Number(total) };
677
+ }
678
+ }
679
+ }
680
+
681
+ function closeServiceChannel(task: ServiceTask): void {
682
+ if (task.channelKey === null || task.channelEvent === null) return;
683
+ if (serviceChannels.has(task.channelKey)) {
684
+ const dropped = takeServiceStreamDrops(task);
685
+ if (journalWriter) { journalWriter.channel(task.channelKey, "closed", new Uint8Array(0), dropped.pending, dropped.total); journalWriter.wake(); }
686
+ dispatch(channelMsg(task.channelEvent, task.channelKey, "closed", new Uint8Array(0), dropped.pending, dropped.total));
687
+ }
688
+ serviceChannels.delete(task.channelKey);
689
+ }
690
+
691
+ function serviceKey(task: ServiceTask): string | null {
692
+ return typeof task.cmd.key === "string" && task.cmd.key.length > 0 ? task.cmd.key : null;
693
+ }
694
+
695
+ function removeServiceKey(task: ServiceTask): void {
696
+ const key = serviceKey(task);
697
+ if (key !== null && serviceTasksByKey.get(key) === task) serviceTasksByKey.delete(key);
698
+ }
699
+
700
+ function settleServiceWaiters(): void {
701
+ if (activeService || serviceQueue.length > 0 || serviceRestart) return;
702
+ for (const resolve of serviceIdleWaiters.splice(0)) resolve();
703
+ }
704
+
705
+ function waitForServicesIdle(): Promise<void> {
706
+ if (!activeService && serviceQueue.length === 0 && !serviceRestart) return Promise.resolve();
707
+ return new Promise((resolve) => serviceIdleWaiters.push(resolve));
708
+ }
709
+
710
+ function serviceFailure(task: ServiceTask, bytes: Uint8Array): void {
711
+ if (task.responseDelivered) return;
712
+ task.responseDelivered = true;
713
+ if (journalWriter) { journalWriter.host(task.engineIndex, false, bytes); journalWriter.wake(); }
714
+ releaseServiceSlot(task);
715
+ removeServiceKey(task);
716
+ dispatch(bytesMsg(task.cmd.errKind as string, bytes));
717
+ }
718
+
719
+ function serviceSuccess(task: ServiceTask, result: unknown): void {
720
+ if (task.responseDelivered) return;
721
+ task.responseDelivered = true;
722
+ const wireResult = task.operation.result.kind === "bytes" ? result as Uint8Array : encodeServiceValue(task.operation.result, result);
723
+ if (journalWriter) { journalWriter.host(task.engineIndex, true, wireResult); journalWriter.wake(); }
724
+ releaseServiceSlot(task);
725
+ removeServiceKey(task);
726
+ if (task.cmd.typedService === true) dispatch(valueMsg(task.cmd.okKind as string, result));
727
+ else dispatch(bytesMsg(
728
+ task.cmd.okKind as string,
729
+ task.operation.result.kind === "bytes" ? result as Uint8Array : encodeServiceValue(task.operation.result, result),
730
+ ));
731
+ }
732
+
733
+ function finishService(task: ServiceTask, message: { type: "result" | "error"; result?: unknown; error?: unknown; elapsed: number }): void {
734
+ if (activeService !== task) return;
735
+ if (task.deadlineTimer) clearTimeout(task.deadlineTimer);
736
+ if (task.hardTimer) clearTimeout(task.hardTimer);
737
+ say(`service ${task.operation.name} ${message.type === "result" ? "ok" : "err"} ${message.elapsed.toFixed(3)}ms`);
738
+ if (task.timedOut) {
739
+ serviceFailure(task, encoder.encode(JSON.stringify({ kind: "timeout", message: "service request timed out" })));
740
+ } else if (!task.cancelled) {
741
+ if (message.type === "result") serviceSuccess(task, message.result);
742
+ else serviceFailure(task, serviceErrorBytes(message.error));
743
+ }
744
+ closeServiceChannel(task);
745
+ removeServiceKey(task);
746
+ activeService = null;
747
+ startNextService();
748
+ }
749
+
750
+ function stopWorkerFor(task: ServiceTask): void {
751
+ if (activeService !== task) return;
752
+ if (task.deadlineTimer) clearTimeout(task.deadlineTimer);
753
+ if (task.hardTimer) clearTimeout(task.hardTimer);
754
+ if (task.timedOut) serviceFailure(task, encoder.encode(JSON.stringify({ kind: "timeout", message: "service request timed out" })));
755
+ closeServiceChannel(task);
756
+ removeServiceKey(task);
757
+ activeService = null;
758
+ const worker = serviceWorker;
759
+ serviceWorker = null;
760
+ serviceWorkerReady = false;
761
+ if (worker) {
762
+ worker.removeAllListeners();
763
+ serviceRestart = worker.terminate().then(() => undefined, () => undefined).finally(() => {
764
+ serviceRestart = null;
765
+ startNextService();
766
+ settleServiceWaiters();
767
+ });
768
+ } else startNextService();
769
+ }
770
+
771
+ function requestServiceStop(task: ServiceTask, timeout: boolean): void {
772
+ if (activeService !== task) return;
773
+ if (timeout) task.timedOut = true;
774
+ else {
775
+ task.cancelled = true;
776
+ releaseServiceSlot(task);
777
+ removeServiceKey(task);
778
+ }
779
+ Atomics.store(task.cancelFlag, 0, 1);
780
+ if (!timeout && task.operation.stream !== null && !task.responseDelivered) {
781
+ serviceFailure(task, encoder.encode("cancelled"));
782
+ closeServiceChannel(task);
783
+ }
784
+ if (!task.hardTimer) task.hardTimer = setTimeout(() => stopWorkerFor(task), cooperativeCancelGraceMs);
785
+ }
786
+
787
+ const portableServiceEnvironment = new Set([
788
+ "PATH", "HOME", "USER", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "LC_CTYPE", "TZ",
789
+ "SSL_CERT_FILE", "SSL_CERT_DIR", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY",
790
+ ]);
791
+ const windowsServiceEnvironment = new Set(["USERPROFILE", "USERNAME", "SYSTEMROOT", "COMSPEC", "PATHEXT"]);
792
+
793
+ function serviceWorkerEnvironment(): Record<string, string> {
794
+ const environment: Record<string, string> = {};
795
+ for (const [name, value] of Object.entries(process.env)) {
796
+ if (value === undefined) continue;
797
+ const comparison = process.platform === "win32" ? name.toUpperCase() : name;
798
+ if (portableServiceEnvironment.has(comparison) || (process.platform === "win32" && windowsServiceEnvironment.has(comparison))) {
799
+ environment[name] = value;
800
+ }
801
+ }
802
+ return environment;
803
+ }
804
+
805
+ function makeServiceWorker(): Worker {
806
+ const appRoot = path.dirname(path.dirname(path.resolve(entry!)));
807
+ const worker = new Worker(new URL("./devhost_service_worker.mjs", import.meta.url), {
808
+ workerData: {
809
+ resolverData,
810
+ operations: serviceContract!.operations.map((operation) => ({
811
+ ...operation,
812
+ absoluteModule: path.resolve(appRoot, operation.module),
813
+ })),
814
+ },
815
+ env: serviceWorkerEnvironment(),
816
+ });
817
+ worker.on("message", (message: { id?: number; type: string; chunk?: unknown; result?: unknown; error?: unknown; elapsed?: number }) => {
818
+ if (message.type === "ready") {
819
+ serviceWorkerReady = true;
820
+ startNextService();
821
+ return;
822
+ }
823
+ const task = activeService;
824
+ if (!task || message.id !== task.id) return;
825
+ if (message.type === "chunk") {
826
+ const dropped = takeServiceStreamDrops(task);
827
+ Atomics.sub(task.streamInFlight, 0, 1);
828
+ if (!task.cancelled && !task.timedOut && task.channelKey !== null && task.channelEvent !== null && serviceChannels.has(task.channelKey)) {
829
+ task.chunks += 1;
830
+ const bytes = encodeServiceValue(task.operation.stream!.chunk, message.chunk);
831
+ if (journalWriter) { journalWriter.channel(task.channelKey, "data", bytes, dropped.pending, dropped.total); journalWriter.wake(); }
832
+ dispatch(channelMsg(task.channelEvent, task.channelKey, "data", bytes, dropped.pending, dropped.total));
833
+ }
834
+ return;
835
+ }
836
+ if (message.type === "result" || message.type === "error") {
837
+ finishService(task, { type: message.type, result: message.result, error: message.error, elapsed: message.elapsed ?? 0 });
838
+ }
839
+ });
840
+ const failed = (): void => {
841
+ const task = activeService ?? serviceQueue.shift() ?? null;
842
+ if (task !== null && activeService === null) activeService = task;
843
+ serviceWorker = null;
844
+ serviceWorkerReady = false;
845
+ if (!task) {
846
+ settleServiceWaiters();
847
+ return;
848
+ }
849
+ if (!task.cancelled && !task.timedOut) serviceFailure(task, encoder.encode(JSON.stringify({ kind: "service_host", message: "service worker exited" })));
850
+ else if (task.timedOut) serviceFailure(task, encoder.encode(JSON.stringify({ kind: "timeout", message: "service request timed out" })));
851
+ closeServiceChannel(task);
852
+ removeServiceKey(task);
853
+ releaseServiceSlot(task);
854
+ activeService = null;
855
+ startNextService();
856
+ };
857
+ worker.once("error", failed);
858
+ // `process.exit(0)` inside an allowed service is still an unexpected host
859
+ // loss when a request is active. Intentional termination removes these
860
+ // listeners first.
861
+ worker.once("exit", () => { if (worker === serviceWorker) failed(); });
862
+ return worker;
863
+ }
864
+
865
+ function startNextService(): void {
866
+ if (activeService || serviceRestart || serviceQueue.length === 0) {
867
+ settleServiceWaiters();
868
+ return;
869
+ }
870
+ if (journalReplayPath) return;
871
+ if (!serviceWorker) serviceWorker = makeServiceWorker();
872
+ if (!serviceWorkerReady) return;
873
+ const task = serviceQueue.shift()!;
874
+ activeService = task;
875
+ if (task.deadlineAt !== null) {
876
+ const remaining = task.deadlineAt - performance.now();
877
+ if (remaining <= 0) {
878
+ task.timedOut = true;
879
+ serviceFailure(task, encoder.encode(JSON.stringify({ kind: "timeout", message: "service request timed out" })));
880
+ closeServiceChannel(task);
881
+ activeService = null;
882
+ startNextService();
883
+ return;
884
+ }
885
+ task.deadlineTimer = setTimeout(() => requestServiceStop(task, true), remaining);
886
+ }
887
+ serviceWorker.postMessage({
888
+ id: task.id,
889
+ name: task.operation.name,
890
+ request: task.request,
891
+ cancelBuffer: task.cancelFlag.buffer,
892
+ streamStateBuffer: task.streamStateBuffer,
893
+ });
894
+ }
895
+
896
+ function enqueueService(cmd: Cmdish, operation: ServiceOperationRuntime, request: unknown, channelKey: number | null, channelEvent: string | null): boolean {
897
+ const key = typeof cmd.key === "string" && cmd.key.length > 0 ? cmd.key : null;
898
+ if (key !== null && serviceTasksByKey.has(key)) {
899
+ dispatch(bytesMsg(cmd.errKind as string, encoder.encode("rejected")));
900
+ return false;
901
+ }
902
+ const engineIndex = serviceRequestSlots.findIndex((slot) => slot === null);
903
+ if (engineIndex < 0) {
904
+ dispatch(bytesMsg(cmd.errKind as string, encoder.encode(JSON.stringify({ kind: "service_host", message: "more than 16 service requests are live" }))));
905
+ return false;
906
+ }
907
+ const streamStateBuffer = new SharedArrayBuffer(16);
908
+ const task: ServiceTask = {
909
+ id: nextServiceId++, cmd, operation, request, channelKey, channelEvent,
910
+ cancelFlag: new Int32Array(new SharedArrayBuffer(4)),
911
+ streamStateBuffer,
912
+ streamInFlight: new Int32Array(streamStateBuffer, 0, 1),
913
+ streamDrops: new BigUint64Array(streamStateBuffer, 8, 1),
914
+ engineIndex,
915
+ deadlineAt: operation.deadline_ms === null ? null : performance.now() + operation.deadline_ms,
916
+ deadlineTimer: null, hardTimer: null, cancelled: false, timedOut: false, responseDelivered: false, chunks: 0,
917
+ };
918
+ serviceRequestSlots[engineIndex] = task;
919
+ if (key !== null) serviceTasksByKey.set(key, task);
920
+ serviceQueue.push(task);
921
+ return true;
922
+ }
923
+
924
+ function cancelService(key: string): boolean {
925
+ const task = serviceTasksByKey.get(key);
926
+ if (!task) return false;
927
+ const queued = serviceQueue.indexOf(task);
928
+ if (queued >= 0) {
929
+ serviceQueue.splice(queued, 1);
930
+ task.cancelled = true;
931
+ if (task.operation.stream !== null) {
932
+ serviceFailure(task, encoder.encode("cancelled"));
933
+ closeServiceChannel(task);
934
+ }
935
+ removeServiceKey(task);
936
+ releaseServiceSlot(task);
937
+ settleServiceWaiters();
938
+ } else requestServiceStop(task, false);
939
+ return true;
940
+ }
941
+
942
+ function emptyMsg(kind: string): unknown {
943
+ return { kind };
944
+ }
945
+
946
+ function storeKeyBytes(key: string, allowEmpty = false): Uint8Array | null {
947
+ const bytes = encoder.encode(key);
948
+ if ((!allowEmpty && bytes.length === 0) || bytes.length > maxStoreKeyBytes) return null;
949
+ return bytes;
950
+ }
951
+
952
+ function storeKeyIdentity(bytes: Uint8Array): string {
953
+ let identity = "";
954
+ for (const byte of bytes) identity += String.fromCharCode(byte);
955
+ return identity;
956
+ }
957
+
958
+ function validStoreKeyBytes(bytes: Uint8Array, allowEmpty = false): Uint8Array | null {
959
+ if ((!allowEmpty && bytes.length === 0) || bytes.length > maxStoreKeyBytes) return null;
960
+ try {
961
+ strictDecoder.decode(bytes);
962
+ } catch {
963
+ return null;
964
+ }
965
+ return bytes;
966
+ }
967
+
968
+ function compareBytes(left: Uint8Array, right: Uint8Array): number {
969
+ const count = Math.min(left.length, right.length);
970
+ for (let i = 0; i < count; i++) {
971
+ if (left[i]! !== right[i]!) return left[i]! - right[i]!;
972
+ }
973
+ return left.length - right.length;
974
+ }
975
+
976
+ function startsWithBytes(value: Uint8Array, prefix: Uint8Array): boolean {
977
+ if (prefix.length > value.length) return false;
978
+ for (let i = 0; i < prefix.length; i++) if (value[i] !== prefix[i]) return false;
979
+ return true;
980
+ }
981
+
982
+ function frameStoreScan(entries: ReadonlyArray<readonly [Uint8Array, Uint8Array]>, next: Uint8Array): Uint8Array {
983
+ let length = 8 + next.length;
984
+ for (const [key, value] of entries) length += 8 + key.length + value.length;
985
+ const output = new Uint8Array(length);
986
+ const view = new DataView(output.buffer);
987
+ let at = 0;
988
+ const writeU32 = (value: number): void => {
989
+ view.setUint32(at, value, true);
990
+ at += 4;
991
+ };
992
+ const writeBytes = (bytes: Uint8Array): void => {
993
+ writeU32(bytes.length);
994
+ output.set(bytes, at);
995
+ at += bytes.length;
996
+ };
997
+ writeU32(entries.length);
998
+ for (const [key, value] of entries) {
999
+ writeBytes(key);
1000
+ writeBytes(value);
1001
+ }
1002
+ writeBytes(next);
1003
+ return output;
1004
+ }
1005
+
1006
+ function queueStoreResult(cmd: Cmdish, ok: boolean, bytes: Uint8Array, okVoid: boolean): void {
1007
+ const routeKey = cmd.key as string;
1008
+ if (routeKey.length > 0) {
1009
+ const replaced = pendingStoreByKey.get(routeKey);
1010
+ if (replaced) replaced.active = false;
1011
+ }
1012
+ const result: PendingStoreResult = {
1013
+ seq: nextEffectResultSeq++,
1014
+ routeKey,
1015
+ okKind: cmd.okKind as string,
1016
+ errKind: cmd.errKind as string,
1017
+ ok,
1018
+ okVoid,
1019
+ bytes,
1020
+ active: true,
1021
+ };
1022
+ pendingStoreResults.push(result);
1023
+ if (routeKey.length > 0) pendingStoreByKey.set(routeKey, result);
1024
+ }
1025
+
1026
+ function cancelPendingStore(routeKey: string): boolean {
1027
+ const pending = pendingStoreByKey.get(routeKey);
1028
+ if (!pending) return false;
1029
+ pending.active = false;
1030
+ pendingStoreByKey.delete(routeKey);
1031
+ return true;
1032
+ }
1033
+
1034
+ function rejectStore(cmd: Cmdish, reason: string): void {
1035
+ say(`cmd ${cmd.op} rejected ${reason}`);
1036
+ queueStoreResult(cmd, false, encoder.encode(reason), false);
1037
+ }
1038
+
1039
+ function performStoreCmd(cmd: Cmdish): void {
1040
+ const routeKey = cmd.key as string;
1041
+ if (!capabilities.has("store")) return rejectStore(cmd, "rejected");
1042
+ switch (cmd.op) {
1043
+ case "store_set": {
1044
+ const key = cmd.storeKey as string;
1045
+ const keyBytes = storeKeyBytes(key);
1046
+ const bytes = cmd.bytes;
1047
+ if (!keyBytes) return rejectStore(cmd, "bad_key");
1048
+ if (!(bytes instanceof Uint8Array) || bytes.length > maxStoreValueBytes) return rejectStore(cmd, "over_bound");
1049
+ recordStore.set(storeKeyIdentity(keyBytes), { key: keyBytes.slice(), value: bytes.slice() });
1050
+ say(`cmd store_set ${routeKey} ${key} (stored in virtual host memory)`);
1051
+ queueStoreResult(cmd, true, new Uint8Array(0), true);
1052
+ return;
1053
+ }
1054
+ case "store_get": {
1055
+ const key = cmd.storeKey as string;
1056
+ const keyBytes = storeKeyBytes(key);
1057
+ if (!keyBytes) return rejectStore(cmd, "bad_key");
1058
+ const value = recordStore.get(storeKeyIdentity(keyBytes))?.value;
1059
+ const result = new Uint8Array(value === undefined ? 1 : value.length + 1);
1060
+ if (value !== undefined) {
1061
+ result[0] = 1;
1062
+ result.set(value, 1);
1063
+ }
1064
+ say(`cmd store_get ${routeKey} ${key} (${value === undefined ? "miss" : "hit"})`);
1065
+ queueStoreResult(cmd, true, result, false);
1066
+ return;
1067
+ }
1068
+ case "store_delete": {
1069
+ const key = cmd.storeKey as string;
1070
+ const keyBytes = storeKeyBytes(key);
1071
+ if (!keyBytes) return rejectStore(cmd, "bad_key");
1072
+ recordStore.delete(storeKeyIdentity(keyBytes));
1073
+ say(`cmd store_delete ${routeKey} ${key} (deleted from virtual host memory)`);
1074
+ queueStoreResult(cmd, true, new Uint8Array(0), true);
1075
+ return;
1076
+ }
1077
+ case "store_scan": {
1078
+ const prefix = cmd.prefix as string;
1079
+ const after = cmd.after as string | Uint8Array;
1080
+ const prefixBytes = storeKeyBytes(prefix, true);
1081
+ const afterBytes = typeof after === "string"
1082
+ ? (after === "" ? new Uint8Array(0) : storeKeyBytes(after))
1083
+ : validStoreKeyBytes(after, true);
1084
+ const requested = cmd.limit as number;
1085
+ const limit = requested === 0 ? 100 : requested;
1086
+ if (!prefixBytes || !afterBytes) return rejectStore(cmd, "bad_key");
1087
+ if (!Number.isInteger(limit) || limit < 1 || limit > maxStoreScanLimit) return rejectStore(cmd, "over_bound");
1088
+ const matches = [...recordStore.values()]
1089
+ .map(({ key, value }) => [key, value] as const)
1090
+ .filter(([key]) => startsWithBytes(key, prefixBytes) && (afterBytes.length === 0 || compareBytes(key, afterBytes) > 0))
1091
+ .sort(([left], [right]) => compareBytes(left, right));
1092
+ const page: Array<readonly [Uint8Array, Uint8Array]> = [];
1093
+ let framedLength = 8;
1094
+ for (const entry of matches) {
1095
+ if (page.length >= limit) break;
1096
+ const rowLength = 8 + entry[0].length + entry[1].length;
1097
+ if (framedLength + rowLength + entry[0].length > maxStoreResultBytes && page.length > 0) break;
1098
+ page.push(entry);
1099
+ framedLength += rowLength;
1100
+ }
1101
+ const hasMore = page.length < matches.length;
1102
+ const next = hasMore ? page.at(-1)![0] : new Uint8Array(0);
1103
+ say(`cmd store_scan ${routeKey} ${prefix} (${page.length} records${hasMore ? ", more" : ""})`);
1104
+ queueStoreResult(cmd, true, frameStoreScan(page, next), false);
1105
+ return;
1106
+ }
1107
+ case "store_set_many": {
1108
+ const entries = cmd.entries as ReadonlyArray<readonly [string, Uint8Array]>;
1109
+ if (!Array.isArray(entries) || entries.length === 0 || entries.length > maxStoreBatchEntries) return rejectStore(cmd, "over_bound");
1110
+ let encodedLength = 8;
1111
+ for (const [key, value] of entries) {
1112
+ const keyBytes = storeKeyBytes(key);
1113
+ if (!keyBytes) return rejectStore(cmd, "bad_key");
1114
+ if (!(value instanceof Uint8Array) || value.length > maxStoreValueBytes) return rejectStore(cmd, "over_bound");
1115
+ encodedLength += 8 + keyBytes.length + value.length;
1116
+ if (encodedLength > maxStoreBatchBytes) return rejectStore(cmd, "over_bound");
1117
+ }
1118
+ for (const [key, value] of entries) {
1119
+ const keyBytes = storeKeyBytes(key)!;
1120
+ recordStore.set(storeKeyIdentity(keyBytes), { key: keyBytes.slice(), value: value.slice() });
1121
+ }
1122
+ say(`cmd store_set_many ${routeKey} (${entries.length} records stored atomically)`);
1123
+ queueStoreResult(cmd, true, new Uint8Array(0), true);
1124
+ return;
1125
+ }
1126
+ }
1127
+ }
1128
+
1129
+ function credentialFields(payload: unknown): Uint8Array[] | null {
1130
+ if (!(payload instanceof Uint8Array)) return null;
1131
+ const fields: Uint8Array[] = [];
1132
+ let at = 0;
1133
+ while (at < payload.length) {
1134
+ if (payload.length - at < 4) return null;
1135
+ const length = new DataView(payload.buffer, payload.byteOffset + at, 4).getUint32(0, true);
1136
+ at += 4;
1137
+ if (length > payload.length - at) return null;
1138
+ fields.push(payload.slice(at, at + length));
1139
+ at += length;
1140
+ }
1141
+ return fields;
1142
+ }
1143
+
1144
+ function rejectCredentials(cmd: Cmdish, outcome: string): void {
1145
+ say(`cmd ${cmd.name} rejected ${outcome}`);
1146
+ queueStoreResult(cmd, false, encoder.encode(outcome), false);
1147
+ }
1148
+
1149
+ function performCredentialsCmd(cmd: Cmdish): void {
1150
+ const name = cmd.name as string;
1151
+ if (!capabilities.has("credentials") || !permissions.has("credentials")) {
1152
+ rejectCredentials(cmd, "denied");
1153
+ return;
1154
+ }
1155
+ const fields = credentialFields(cmd.payload);
1156
+ const expected = name === "core.credentials.set" ? 2 : 1;
1157
+ if (!fields || fields.length !== expected) return rejectCredentials(cmd, "rejected");
1158
+ const keyBytes = fields[0]!;
1159
+ let key: string;
1160
+ try {
1161
+ key = strictDecoder.decode(keyBytes);
1162
+ } catch {
1163
+ return rejectCredentials(cmd, "over_bound");
1164
+ }
1165
+ if (keyBytes.length === 0 || keyBytes.length > 256 || key.includes("\0")) return rejectCredentials(cmd, "over_bound");
1166
+ const identity = `${appId}\0${key}`;
1167
+ if (name === "core.credentials.set") {
1168
+ const secret = fields[1]!;
1169
+ if (secret.length > maxCredentialSecretBytes) return rejectCredentials(cmd, "over_bound");
1170
+ credentialStore.set(identity, secret.slice());
1171
+ say(`cmd ${name} ${cmd.key as string} ${key} (<redacted, ${secret.length} bytes> stored in virtual host memory)`);
1172
+ queueStoreResult(cmd, true, new Uint8Array(0), true);
1173
+ return;
1174
+ }
1175
+ if (name === "core.credentials.get") {
1176
+ const secret = credentialStore.get(identity);
1177
+ say(`cmd ${name} ${cmd.key as string} ${key} (${secret ? `<redacted, ${secret.length} bytes>` : "miss"})`);
1178
+ if (!secret) queueStoreResult(cmd, false, encoder.encode("miss"), false);
1179
+ else queueStoreResult(cmd, true, secret.slice(), false);
1180
+ return;
1181
+ }
1182
+ if (name === "core.credentials.delete") {
1183
+ credentialStore.delete(identity);
1184
+ say(`cmd ${name} ${cmd.key as string} ${key} (deleted from virtual host memory)`);
1185
+ queueStoreResult(cmd, true, new Uint8Array(0), true);
1186
+ return;
1187
+ }
1188
+ rejectCredentials(cmd, "rejected");
1189
+ }
1190
+
1191
+ type DbBindValue = null | bigint | number | string | Uint8Array;
1192
+
1193
+ function validDbSql(value: unknown): value is string {
1194
+ return typeof value === "string" && value.length > 0 && !value.includes("\0") && encoder.encode(value).length <= maxDbSqlBytes;
1195
+ }
1196
+
1197
+ /// Node's SQLite wrapper prepares only the first statement and does not expose
1198
+ /// sqlite3's tail pointer directly. `sourceSQL` is that exact first slice, so
1199
+ /// inspect only its tail for another token. Trigger-body semicolons remain in
1200
+ /// sourceSQL and trailing comments/empty semicolons stay legal.
1201
+ function dbTailHasStatement(sql: string, sourceSQL: string): boolean {
1202
+ const tail = sql.slice(sourceSQL.length);
1203
+ let at = 0;
1204
+ while (at < tail.length) {
1205
+ const char = tail[at]!;
1206
+ if (/\s/.test(char) || char === ";") {
1207
+ at += 1;
1208
+ continue;
1209
+ }
1210
+ if (char === "-" && tail[at + 1] === "-") {
1211
+ const newline = tail.indexOf("\n", at + 2);
1212
+ if (newline < 0) return false;
1213
+ at = newline + 1;
1214
+ continue;
1215
+ }
1216
+ if (char === "/" && tail[at + 1] === "*") {
1217
+ const end = tail.indexOf("*/", at + 2);
1218
+ if (end < 0) return false;
1219
+ at = end + 2;
1220
+ continue;
1221
+ }
1222
+ return true;
1223
+ }
1224
+ return false;
1225
+ }
1226
+
1227
+ function dbParams(value: unknown, byteLimit: number): ReadonlyArray<DbBindValue> | null {
1228
+ if (!Array.isArray(value) || value.length > maxDbParameters) return null;
1229
+ const params: DbBindValue[] = [];
1230
+ let bytes = 0;
1231
+ for (const item of value) {
1232
+ if (item === null) params.push(null);
1233
+ else if (typeof item === "boolean") params.push(item ? 1n : 0n);
1234
+ else if (typeof item === "number" && Number.isFinite(item)) params.push(Number.isSafeInteger(item) ? BigInt(item) : item);
1235
+ else if (typeof item === "object" && item !== null && (item as { __dbText?: unknown }).__dbText === true && Array.isArray((item as { bytes?: unknown }).bytes)) {
1236
+ const rawBytes = (item as { bytes: unknown[] }).bytes;
1237
+ if (!rawBytes.every((byte) => typeof byte === "number" && Number.isInteger(byte) && byte >= 0 && byte <= 255)) return null;
1238
+ const textBytes = Uint8Array.from(rawBytes as number[]);
1239
+ let text: string;
1240
+ try { text = strictDecoder.decode(textBytes); } catch { return null; }
1241
+ bytes += textBytes.length;
1242
+ params.push(text);
1243
+ } else if (typeof item === "string") {
1244
+ bytes += encoder.encode(item).length;
1245
+ params.push(item);
1246
+ } else if (item instanceof Uint8Array) {
1247
+ bytes += item.length;
1248
+ params.push(item);
1249
+ } else return null;
1250
+ if (bytes > byteLimit) return null;
1251
+ }
1252
+ return params;
1253
+ }
1254
+
1255
+ function dbErrorOutcome(reason: unknown): DbOutcome {
1256
+ if (reason !== null && typeof reason === "object") {
1257
+ const error = reason as { readonly errcode?: number; readonly errstr?: string; readonly message?: string };
1258
+ const primary = (error.errcode ?? 0) & 0xff;
1259
+ if (primary === 19 || error.errstr === "constraint failed") return "constraint";
1260
+ if (primary === 5 || primary === 6) return "busy";
1261
+ if (primary === 10) return "io_failed";
1262
+ if (primary === 11 || primary === 26) return "corrupt";
1263
+ if (primary === 23) return "misuse";
1264
+ if ((error.message ?? "").includes("query_only")) return "misuse";
1265
+ }
1266
+ return "misuse";
1267
+ }
1268
+
1269
+ function dbU32(value: number): Uint8Array {
1270
+ const bytes = new Uint8Array(4);
1271
+ new DataView(bytes.buffer).setUint32(0, value, true);
1272
+ return bytes;
1273
+ }
1274
+
1275
+ function dbValue(value: unknown): Uint8Array | null {
1276
+ if (value === null) return new Uint8Array([0]);
1277
+ if (typeof value === "bigint") {
1278
+ const bytes = new Uint8Array(9);
1279
+ bytes[0] = 1;
1280
+ new DataView(bytes.buffer).setBigInt64(1, value, true);
1281
+ return bytes;
1282
+ }
1283
+ if (typeof value === "number") {
1284
+ if (!Number.isFinite(value)) return null;
1285
+ const bytes = new Uint8Array(9);
1286
+ bytes[0] = 2;
1287
+ new DataView(bytes.buffer).setFloat64(1, value, true);
1288
+ return bytes;
1289
+ }
1290
+ if (typeof value === "string" || value instanceof Uint8Array) {
1291
+ const body = typeof value === "string" ? encoder.encode(value) : value;
1292
+ const bytes = new Uint8Array(5 + body.length);
1293
+ bytes[0] = typeof value === "string" ? 3 : 4;
1294
+ new DataView(bytes.buffer).setUint32(1, body.length, true);
1295
+ bytes.set(body, 5);
1296
+ return bytes;
1297
+ }
1298
+ return null;
1299
+ }
1300
+
1301
+ function concatDbParts(parts: ReadonlyArray<Uint8Array>, length: number): Uint8Array {
1302
+ const bytes = new Uint8Array(length);
1303
+ let at = 0;
1304
+ for (const part of parts) {
1305
+ bytes.set(part, at);
1306
+ at += part.length;
1307
+ }
1308
+ return bytes;
1309
+ }
1310
+
1311
+ function dbHeader(columnNames: ReadonlyArray<string>, rowCount: number): Uint8Array | null {
1312
+ const parts: Uint8Array[] = [dbU32(columnNames.length), dbU32(rowCount)];
1313
+ let length = 8;
1314
+ for (const name of columnNames) {
1315
+ const body = encoder.encode(name);
1316
+ length += 4 + body.length;
1317
+ if (length > maxDbPageBytes) return null;
1318
+ parts.push(dbU32(body.length), body);
1319
+ }
1320
+ return concatDbParts(parts, length);
1321
+ }
1322
+
1323
+ type EncodedDbPages =
1324
+ | { readonly outcome: "ok"; readonly pages: ReadonlyArray<Uint8Array>; readonly rowCount: number }
1325
+ | { readonly outcome: "misuse" | "rejected" };
1326
+
1327
+ function encodeDbPages(columnNames: ReadonlyArray<string>, rows: Iterable<ReadonlyArray<unknown>>): EncodedDbPages {
1328
+ const emptyHeader = dbHeader(columnNames, 0);
1329
+ if (!emptyHeader) return { outcome: "misuse" };
1330
+ const pages: Uint8Array[] = [];
1331
+ let members: Uint8Array[] = [];
1332
+ let pageLength = emptyHeader.length;
1333
+ let resultBytes = 0;
1334
+ let rowCount = 0;
1335
+
1336
+ const flush = (): boolean => {
1337
+ const header = dbHeader(columnNames, members.length);
1338
+ if (!header || resultBytes + pageLength > maxDbResultBytes) return false;
1339
+ pages.push(concatDbParts([header, ...members], pageLength));
1340
+ resultBytes += pageLength;
1341
+ members = [];
1342
+ pageLength = emptyHeader.length;
1343
+ return true;
1344
+ };
1345
+
1346
+ for (const row of rows) {
1347
+ if (rowCount === maxDbResultRows) return { outcome: "rejected" };
1348
+ const values: Uint8Array[] = [];
1349
+ let length = 0;
1350
+ for (const value of row) {
1351
+ const bytes = dbValue(value);
1352
+ if (!bytes) return { outcome: "misuse" };
1353
+ length += bytes.length;
1354
+ if (length + emptyHeader.length > maxDbPageBytes) return { outcome: "misuse" };
1355
+ values.push(bytes);
1356
+ }
1357
+ const encoded = concatDbParts(values, length);
1358
+ if (members.length > 0 && (members.length === maxDbPageRows || pageLength + encoded.length > maxDbPageBytes)) {
1359
+ if (!flush()) return { outcome: "rejected" };
1360
+ }
1361
+ members.push(encoded);
1362
+ pageLength += encoded.length;
1363
+ rowCount += 1;
1364
+ }
1365
+ if (members.length > 0 || pages.length === 0) {
1366
+ if (!flush()) return { outcome: "rejected" };
1367
+ }
1368
+ return { outcome: "ok", pages, rowCount };
1369
+ }
1370
+
1371
+ function dbBindArgs(sql: string, params: ReadonlyArray<DbBindValue>): ReadonlyArray<unknown> {
1372
+ const namedIndexes = new Map<string, number>();
1373
+ const positionalIndexes = new Set<number>();
1374
+ let maxIndex = 0;
1375
+ let at = 0;
1376
+ while (at < sql.length) {
1377
+ const char = sql[at]!;
1378
+ if (char === "'" || char === '"' || char === "`") {
1379
+ const quote = char;
1380
+ at += 1;
1381
+ while (at < sql.length) {
1382
+ if (sql[at] !== quote) { at += 1; continue; }
1383
+ if (sql[at + 1] === quote) { at += 2; continue; }
1384
+ at += 1;
1385
+ break;
1386
+ }
1387
+ continue;
1388
+ }
1389
+ if (char === "[") {
1390
+ const end = sql.indexOf("]", at + 1);
1391
+ at = end < 0 ? sql.length : end + 1;
1392
+ continue;
1393
+ }
1394
+ if (char === "-" && sql[at + 1] === "-") {
1395
+ const end = sql.indexOf("\n", at + 2);
1396
+ at = end < 0 ? sql.length : end + 1;
1397
+ continue;
1398
+ }
1399
+ if (char === "/" && sql[at + 1] === "*") {
1400
+ const end = sql.indexOf("*/", at + 2);
1401
+ at = end < 0 ? sql.length : end + 2;
1402
+ continue;
1403
+ }
1404
+ if (char === "?") {
1405
+ let end = at + 1;
1406
+ while (/[0-9]/.test(sql[end] ?? "")) end += 1;
1407
+ const explicit = end > at + 1 ? Number(sql.slice(at + 1, end)) : null;
1408
+ const index = explicit ?? maxIndex + 1;
1409
+ if (!Number.isSafeInteger(index) || index <= 0) throw new Error("SQLite positional parameter index is invalid");
1410
+ maxIndex = Math.max(maxIndex, index);
1411
+ positionalIndexes.add(index);
1412
+ at = end;
1413
+ continue;
1414
+ }
1415
+ if ((char === ":" || char === "@" || char === "$") && /[A-Za-z_]/.test(sql[at + 1] ?? "")) {
1416
+ let end = at + 2;
1417
+ while (/[A-Za-z0-9_]/.test(sql[end] ?? "")) end += 1;
1418
+ const name = sql.slice(at, end);
1419
+ if (!namedIndexes.has(name)) namedIndexes.set(name, ++maxIndex);
1420
+ at = end;
1421
+ continue;
1422
+ }
1423
+ at += 1;
1424
+ }
1425
+ if (maxIndex !== params.length) throw new Error("SQLite parameter count does not match its value array");
1426
+ if (namedIndexes.size === 0) return params;
1427
+ const named: Record<string, DbBindValue> = {};
1428
+ const indexesClaimedByName = new Set<number>();
1429
+ for (const [name, index] of namedIndexes) {
1430
+ named[name] = params[index - 1]!;
1431
+ indexesClaimedByName.add(index);
1432
+ }
1433
+ const positional: DbBindValue[] = [];
1434
+ const lastPositionalIndex = positionalIndexes.size === 0 ? 0 : Math.max(...positionalIndexes);
1435
+ for (let index = 1; index <= maxIndex; index++) {
1436
+ if (indexesClaimedByName.has(index)) continue;
1437
+ // Numbered placeholders can leave holes. Node's SQLite binding API
1438
+ // counts those holes among its anonymous arguments, exactly as the C
1439
+ // API's 1..parameter_count index walk does.
1440
+ if (index <= lastPositionalIndex) positional.push(params[index - 1]!);
1441
+ }
1442
+ return [named, ...positional];
1443
+ }
1444
+
1445
+ function beginDbOperation(cmd: Cmdish, query: boolean): PendingDbOperation | null {
1446
+ const routeKey = cmd.key as string;
1447
+ if (routeKey.length > 0 && liveDbByKey.has(routeKey)) return null;
1448
+ const active = routeKey.length === 0 ? undefined : pendingDbByKey.get(routeKey);
1449
+ if (active) {
1450
+ if (!query) return null;
1451
+ releaseDbOperation(active, true);
1452
+ }
1453
+ const operation: PendingDbOperation = {
1454
+ routeKey,
1455
+ query,
1456
+ live: false,
1457
+ pageKind: query ? cmd.pageKind as string : "",
1458
+ doneKind: query ? cmd.doneKind as string : cmd.okKind as string,
1459
+ errKind: cmd.errKind as string,
1460
+ active: true,
1461
+ };
1462
+ if (activeDbOperations.size === maxDbEffects) return null;
1463
+ activeDbOperations.add(operation);
1464
+ if (routeKey.length > 0) pendingDbByKey.set(routeKey, operation);
1465
+ return operation;
1466
+ }
1467
+
1468
+ function queueDbResult(operation: PendingDbOperation, kind: DbResultKind, outcome: "ok" | DbOutcome, bytes = new Uint8Array(0)): void {
1469
+ pendingDbResults.push({ seq: nextEffectResultSeq++, operation, kind, outcome, bytes });
1470
+ }
1471
+
1472
+ function discardDbResults(operation: PendingDbOperation): void {
1473
+ for (let index = pendingDbResults.length - 1; index >= 0; index--) {
1474
+ if (pendingDbResults[index]!.operation === operation) pendingDbResults.splice(index, 1);
1475
+ }
1476
+ }
1477
+
1478
+ function releaseDbOperation(operation: PendingDbOperation, discardResults: boolean): void {
1479
+ operation.active = false;
1480
+ activeDbOperations.delete(operation);
1481
+ if (discardResults) discardDbResults(operation);
1482
+ }
1483
+
1484
+ function rejectDbOperation(cmd: Cmdish, query: boolean, outcome: DbOutcome, operation?: PendingDbOperation): void {
1485
+ const pending = operation ?? {
1486
+ routeKey: "",
1487
+ query,
1488
+ live: false,
1489
+ pageKind: query ? cmd.pageKind as string : "",
1490
+ doneKind: query ? cmd.doneKind as string : cmd.okKind as string,
1491
+ errKind: cmd.errKind as string,
1492
+ active: true,
1493
+ };
1494
+ say(`cmd ${cmd.op} rejected ${outcome}`);
1495
+ queueDbResult(pending, query ? "done" : "exec", outcome);
1496
+ }
1497
+
1498
+ function runDbQuery(sql: unknown, rawParams: unknown, operation: PendingDbOperation): void {
1499
+ const params = dbParams(rawParams, maxDbParameterBytes);
1500
+ if (!validDbSql(sql) || !params) {
1501
+ rejectDbOperation({ op: operation.live ? "db_live" : "db_query" }, true, "rejected", operation);
1502
+ return;
1503
+ }
1504
+ try {
1505
+ const inspection = inspectRelationalSql(sql, true);
1506
+ if (inspection.error !== null) throw new Error(inspection.error);
1507
+ setRelationalQueryOnly(true);
1508
+ const statement = relationalDb.prepare(sql);
1509
+ if (dbTailHasStatement(sql, statement.sourceSQL)) {
1510
+ rejectDbOperation({ op: operation.live ? "db_live" : "db_query" }, true, "misuse", operation);
1511
+ return;
1512
+ }
1513
+ statement.setReturnArrays(true);
1514
+ statement.setReadBigInts(true);
1515
+ const columns = statement.columns().map((column) => column.name);
1516
+ if (columns.length === 0) {
1517
+ rejectDbOperation({ op: operation.live ? "db_live" : "db_query" }, true, "misuse", operation);
1518
+ return;
1519
+ }
1520
+ const rows = statement.iterate(...dbBindArgs(sql, params)) as Iterable<ReadonlyArray<unknown>>;
1521
+ const encoded = encodeDbPages(columns, rows);
1522
+ if (encoded.outcome !== "ok") {
1523
+ rejectDbOperation({ op: operation.live ? "db_live" : "db_query" }, true, encoded.outcome, operation);
1524
+ return;
1525
+ }
1526
+ say(`${operation.live ? "sub db_live" : "cmd db_query"} ${operation.routeKey} (${encoded.rowCount} rows in ${encoded.pages.length} page${encoded.pages.length === 1 ? "" : "s"})`);
1527
+ for (const page of encoded.pages) queueDbResult(operation, "page", "ok", page);
1528
+ queueDbResult(operation, "done", "ok");
1529
+ } catch (reason) {
1530
+ rejectDbOperation({ op: operation.live ? "db_live" : "db_query" }, true, dbErrorOutcome(reason), operation);
1531
+ } finally {
1532
+ setRelationalQueryOnly(false);
1533
+ }
1534
+ }
1535
+
1536
+ function performDbCmd(cmd: Cmdish): void {
1537
+ const query = cmd.op === "db_query";
1538
+ const operation = beginDbOperation(cmd, query);
1539
+ if (!operation) return rejectDbOperation(cmd, query, "rejected");
1540
+ if (!capabilities.has("sqlite")) return rejectDbOperation(cmd, query, "rejected", operation);
1541
+
1542
+ if (query) {
1543
+ runDbQuery(cmd.sql, cmd.params, operation);
1544
+ return;
1545
+ }
1546
+
1547
+ const statements = cmd.statements;
1548
+ if (!Array.isArray(statements) || statements.length === 0 || statements.length > maxDbExecStatements) {
1549
+ return rejectDbOperation(cmd, false, "rejected", operation);
1550
+ }
1551
+ const validated: Array<readonly [string, ReadonlyArray<DbBindValue>]> = [];
1552
+ let parameterBytes = 0;
1553
+ for (const item of statements) {
1554
+ if (!Array.isArray(item) || item.length !== 2 || !validDbSql(item[0])) return rejectDbOperation(cmd, false, "rejected", operation);
1555
+ const params = dbParams(item[1], maxDbExecParameterBytes - parameterBytes);
1556
+ if (!params) return rejectDbOperation(cmd, false, "rejected", operation);
1557
+ for (const value of params) {
1558
+ if (typeof value === "string") parameterBytes += encoder.encode(value).length;
1559
+ else if (value instanceof Uint8Array) parameterBytes += value.length;
1560
+ }
1561
+ validated.push([item[0], params]);
1562
+ }
1563
+
1564
+ let began = false;
1565
+ try {
1566
+ relationalChangedTables.clear();
1567
+ relationalChangedAllTables = false;
1568
+ relationalTrackWrites = true;
1569
+ relationalTransaction("BEGIN IMMEDIATE;");
1570
+ began = true;
1571
+ for (const [sql, params] of validated) {
1572
+ const inspection = inspectRelationalSql(sql, true);
1573
+ if (inspection.error !== null) throw new Error(inspection.error);
1574
+ const statement = relationalDb.prepare(sql);
1575
+ if (dbTailHasStatement(sql, statement.sourceSQL)) throw new Error("relational exec statement contains stacked SQL");
1576
+ if (statement.columns().length !== 0) throw new Error("relational exec statement yields rows");
1577
+ statement.run(...dbBindArgs(sql, params));
1578
+ if (!relationalAuthorizerAvailable) relationalChangedAllTables = true;
1579
+ }
1580
+ relationalTransaction("COMMIT;");
1581
+ began = false;
1582
+ for (const [key, live] of liveDbByKey) {
1583
+ if (relationalChangedAllTables || live.tables.some((table) => relationalChangedTables.has(table))) dirtyLiveDbKeys.add(key);
1584
+ }
1585
+ say(`cmd db_exec ${operation.routeKey} (${validated.length} statements committed atomically)`);
1586
+ queueDbResult(operation, "exec", "ok");
1587
+ } catch (reason) {
1588
+ if (began) {
1589
+ try { relationalTransaction("ROLLBACK;"); } catch {}
1590
+ }
1591
+ rejectDbOperation(cmd, false, dbErrorOutcome(reason), operation);
1592
+ } finally {
1593
+ relationalTrackWrites = false;
1594
+ }
1595
+ }
1596
+
1597
+ function cancelPendingDb(routeKey: string): boolean {
1598
+ const operation = pendingDbByKey.get(routeKey);
1599
+ if (!operation || !operation.query) return false;
1600
+ releaseDbOperation(operation, true);
1601
+ pendingDbByKey.delete(routeKey);
1602
+ return true;
1603
+ }
1604
+
1605
+ function nextPendingStoreResult(): PendingStoreResult | undefined {
1606
+ while (pendingStoreResults.length > 0) {
1607
+ const result = pendingStoreResults[0];
1608
+ if (result.active && (result.routeKey.length === 0 || pendingStoreByKey.get(result.routeKey) === result)) return result;
1609
+ pendingStoreResults.shift();
1610
+ }
1611
+ return undefined;
1612
+ }
1613
+
1614
+ function nextPendingDbResult(): PendingDbResult | undefined {
1615
+ while (pendingDbResults.length > 0) {
1616
+ const result = pendingDbResults[0];
1617
+ if (result.operation.active) return result;
1618
+ pendingDbResults.shift();
1619
+ }
1620
+ return undefined;
1621
+ }
1622
+
1623
+ function drainEffectResults(): void {
1624
+ if (dispatchDepth !== 0 || drainingEffectResults) return;
1625
+ drainingEffectResults = true;
1626
+ try {
1627
+ while (true) {
1628
+ const storeResult = nextPendingStoreResult();
1629
+ const dbResult = nextPendingDbResult();
1630
+ if (!storeResult && !dbResult) break;
1631
+
1632
+ if (storeResult && (!dbResult || storeResult.seq < dbResult.seq)) {
1633
+ pendingStoreResults.shift();
1634
+ if (storeResult.routeKey.length > 0) pendingStoreByKey.delete(storeResult.routeKey);
1635
+ storeResult.active = false;
1636
+ if (!storeResult.ok) dispatch(bytesMsg(storeResult.errKind, storeResult.bytes));
1637
+ else if (storeResult.okVoid) dispatch(emptyMsg(storeResult.okKind));
1638
+ else dispatch(bytesMsg(storeResult.okKind, storeResult.bytes));
1639
+ continue;
1640
+ }
1641
+
1642
+ const result = pendingDbResults.shift()!;
1643
+ const operation = result.operation;
1644
+ const terminal = result.outcome !== "ok" || result.kind !== "page";
1645
+ if (terminal && !operation.live) {
1646
+ releaseDbOperation(operation, false);
1647
+ if (operation.routeKey.length > 0 && pendingDbByKey.get(operation.routeKey) === operation) {
1648
+ pendingDbByKey.delete(operation.routeKey);
1649
+ }
1650
+ }
1651
+ if (result.outcome !== "ok") dispatch(bytesMsg(operation.errKind, encoder.encode(result.outcome)));
1652
+ else if (result.kind === "page") dispatch(bytesMsg(operation.pageKind, result.bytes));
1653
+ else dispatch(emptyMsg(operation.doneKind));
1654
+ }
1655
+ } finally {
1656
+ drainingEffectResults = false;
1657
+ }
1658
+ }
1659
+
141
1660
  function performCmd(cmd: Cmdish): void {
142
1661
  switch (cmd.op) {
143
1662
  case "none":
@@ -158,13 +1677,121 @@ function performCmd(cmd: Cmdish): void {
158
1677
  }
159
1678
  case "cancel": {
160
1679
  const key = cmd.key as string;
161
- if (delays.delete(key)) {
1680
+ if (cancelPendingStore(key)) {
1681
+ say(`cmd cancel ${key} (store result dropped)`);
1682
+ } else if (cancelPendingDb(key)) {
1683
+ say(`cmd cancel ${key} (database query result dropped)`);
1684
+ } else if (delays.delete(key)) {
162
1685
  say(`cmd cancel ${key} (delay dropped)`);
1686
+ } else if (cancelService(key)) {
1687
+ say(`cmd cancel ${key} (service cancellation requested)`);
163
1688
  } else {
164
- say(`cmd cancel ${key} (not performed here - a live request or named op drops silently; a live spawn ends loudly, err arm "cancelled")`);
1689
+ say(`cmd cancel ${key} (not performed here - a live request or buffered named op drops silently; a live spawn or streaming fetch ends loudly, err arm "cancelled")`);
1690
+ }
1691
+ return;
1692
+ }
1693
+ case "persist":
1694
+ try {
1695
+ persistedModel = structuredClone(model);
1696
+ say("cmd persist (stored in virtual host memory)");
1697
+ } catch {
1698
+ say("cmd persist rejected by virtual host");
1699
+ if (persistErr) dispatch(bytesMsg(persistErr, encoder.encode("rejected")));
1700
+ }
1701
+ return;
1702
+ case "channel_open": {
1703
+ const channelKey = cmd.key as number;
1704
+ const eventKind = cmd.eventKind as string;
1705
+ if (!Number.isSafeInteger(channelKey) || channelKey < 1 || serviceChannels.has(channelKey)) {
1706
+ dispatch(channelMsg(eventKind, Number.isSafeInteger(channelKey) && channelKey >= 1 ? channelKey : 0, "rejected"));
1707
+ return;
1708
+ }
1709
+ serviceChannels.set(channelKey, eventKind);
1710
+ say(`cmd channel_open key=${channelKey} event=${eventKind}`);
1711
+ return;
1712
+ }
1713
+ case "channel_close": {
1714
+ const channelKey = cmd.key as number;
1715
+ const event = serviceChannels.get(channelKey);
1716
+ if (event) dispatch(channelMsg(event, channelKey, "closed"));
1717
+ serviceChannels.delete(channelKey);
1718
+ return;
1719
+ }
1720
+ case "request": {
1721
+ if (typeof cmd.name === "string" && cmd.name.startsWith("core.credentials.")) {
1722
+ performCredentialsCmd(cmd);
1723
+ return;
1724
+ }
1725
+ const operation = serviceOperations.get(cmd.name as string);
1726
+ if (!operation) break;
1727
+ try {
1728
+ const reader = new ServiceReader(cmd.payload as Uint8Array);
1729
+ let channelKey: number | null = null;
1730
+ let channelEvent: string | null = null;
1731
+ if (operation.stream !== null) {
1732
+ channelKey = reader.f64();
1733
+ channelEvent = serviceChannels.get(channelKey) ?? null;
1734
+ if (!channelEvent) throw new Error("streaming service request has no open channel");
1735
+ }
1736
+ const request = operation.request.kind === "none"
1737
+ ? undefined
1738
+ : operation.request.kind === "bytes"
1739
+ ? reader.take(reader.bytes.length - reader.at)
1740
+ : decodeServiceValue(operation.request, reader);
1741
+ if (reader.at !== reader.bytes.length) throw new Error("trailing service request bytes");
1742
+ if (enqueueService(cmd, operation, request, channelKey, channelEvent)) startNextService();
1743
+ } catch (error) {
1744
+ say(`service ${operation.name} err 0.000ms`);
1745
+ dispatch(bytesMsg(cmd.errKind as string, serviceErrorBytes(error)));
1746
+ }
1747
+ return;
1748
+ }
1749
+ case "service_stream_request": {
1750
+ const operation = serviceOperations.get(cmd.name as string);
1751
+ if (!operation || operation.stream === null) break;
1752
+ const eventKind = cmd.eventKind as string;
1753
+ const requestedChannelKey = cmd.channelKey as number;
1754
+ try {
1755
+ const reader = new ServiceReader(cmd.payload as Uint8Array);
1756
+ const payloadChannelKey = reader.f64();
1757
+ const representable = Number.isSafeInteger(requestedChannelKey) && requestedChannelKey >= 1;
1758
+ if (!representable || payloadChannelKey !== requestedChannelKey) {
1759
+ dispatch(channelMsg(eventKind, representable ? requestedChannelKey : 0, "rejected"));
1760
+ dispatch(bytesMsg(cmd.errKind as string, encoder.encode("rejected")));
1761
+ return;
1762
+ }
1763
+ if (serviceChannels.has(requestedChannelKey)) {
1764
+ dispatch(channelMsg(eventKind, requestedChannelKey, "rejected"));
1765
+ dispatch(bytesMsg(cmd.errKind as string, encoder.encode("rejected")));
1766
+ return;
1767
+ }
1768
+ const request = operation.request.kind === "none"
1769
+ ? undefined
1770
+ : operation.request.kind === "bytes"
1771
+ ? reader.take(reader.bytes.length - reader.at)
1772
+ : decodeServiceValue(operation.request, reader);
1773
+ if (reader.at !== reader.bytes.length) throw new Error("trailing service request bytes");
1774
+ if (!enqueueService(cmd, operation, request, requestedChannelKey, eventKind)) return;
1775
+ serviceChannels.set(requestedChannelKey, eventKind);
1776
+ say(`cmd channel_open key=${requestedChannelKey} event=${eventKind}`);
1777
+ startNextService();
1778
+ } catch (error) {
1779
+ say(`service ${operation.name} err 0.000ms`);
1780
+ dispatch(bytesMsg(cmd.errKind as string, serviceErrorBytes(error)));
165
1781
  }
166
1782
  return;
167
1783
  }
1784
+ case "store_set":
1785
+ case "store_get":
1786
+ case "store_delete":
1787
+ case "store_scan":
1788
+ case "store_set_many":
1789
+ performStoreCmd(cmd);
1790
+ return;
1791
+ case "db_query":
1792
+ case "db_exec":
1793
+ performDbCmd(cmd);
1794
+ return;
168
1795
  case "show_notification": {
169
1796
  const details = Object.entries(cmd)
170
1797
  .filter(([k]) => k !== "op")
@@ -189,9 +1816,14 @@ function performCmd(cmd: Cmdish): void {
189
1816
  function reconcileSubs(): void {
190
1817
  if (typeof mod.subscriptions !== "function") return;
191
1818
  const declared = new Map<string, { everyMs: number; msgKind: string }>();
1819
+ const declaredLive = new Map<string, Cmdish>();
192
1820
  const collect = (sub: Cmdish): void => {
193
1821
  if (sub.op === "timer") {
194
1822
  declared.set(sub.key as string, { everyMs: sub.everyMs as number, msgKind: sub.msgKind as string });
1823
+ } else if (sub.op === "db_live") {
1824
+ const key = sub.key as string;
1825
+ if (key.length === 0 || declaredLive.has(key)) throw new Error("a live query requires one unique, non-empty subscription key");
1826
+ declaredLive.set(key, sub);
195
1827
  } else if (sub.op === "batch") {
196
1828
  for (const inner of sub.subs as Cmdish[]) collect(inner);
197
1829
  }
@@ -213,6 +1845,70 @@ function reconcileSubs(): void {
213
1845
  say(`sub cancel ${key}`);
214
1846
  }
215
1847
  }
1848
+
1849
+ // Retire absent live queries before allocating their replacements. Both
1850
+ // sets may fit the shared database family independently even when their
1851
+ // transient union does not (for example, sixteen old keys replaced by one
1852
+ // new key).
1853
+ for (const [key, active] of [...liveDbByKey]) {
1854
+ if (!declaredLive.has(key)) {
1855
+ releaseDbOperation(active.operation, true);
1856
+ liveDbByKey.delete(key);
1857
+ dirtyLiveDbKeys.delete(key);
1858
+ say(`sub cancel db_live ${key}`);
1859
+ }
1860
+ }
1861
+
1862
+ for (const [key, sub] of declaredLive) {
1863
+ const tables = sub.tables;
1864
+ const params = sub.params;
1865
+ if (!Array.isArray(tables) || tables.length === 0 || !tables.every((table) => typeof table === "string" && table.length > 0) || !Array.isArray(params)) {
1866
+ throw new Error(`live query ${key} carries an invalid generated dependency or parameter set`);
1867
+ }
1868
+ if (pendingDbByKey.has(key)) throw new Error(`live-query key ${key} collides with an in-flight database command`);
1869
+ const signature = JSON.stringify([
1870
+ sub.pageKind, sub.doneKind, sub.errKind, sub.sql,
1871
+ jsonable(params), tables,
1872
+ ]);
1873
+ const active = liveDbByKey.get(key);
1874
+ if (active?.signature === signature) continue;
1875
+ if (active) {
1876
+ releaseDbOperation(active.operation, true);
1877
+ }
1878
+ const operation: PendingDbOperation = {
1879
+ routeKey: key,
1880
+ query: true,
1881
+ live: true,
1882
+ pageKind: sub.pageKind as string,
1883
+ doneKind: sub.doneKind as string,
1884
+ errKind: sub.errKind as string,
1885
+ active: true,
1886
+ };
1887
+ if (activeDbOperations.size === maxDbEffects) {
1888
+ throw new Error("more relational commands and live queries are active than the database slot family can hold");
1889
+ }
1890
+ activeDbOperations.add(operation);
1891
+ const live: LiveDbSubscription = {
1892
+ operation,
1893
+ signature,
1894
+ sql: sub.sql as string,
1895
+ params,
1896
+ tables: tables as string[],
1897
+ };
1898
+ liveDbByKey.set(key, live);
1899
+ dirtyLiveDbKeys.delete(key);
1900
+ say(`sub ${active ? "re-arm" : "arm"} db_live ${key}`);
1901
+ if (!capabilities.has("sqlite")) rejectDbOperation(sub, true, "rejected", operation);
1902
+ else runDbQuery(live.sql, live.params, operation);
1903
+ }
1904
+ }
1905
+
1906
+ function flushLiveDbSubscriptions(): void {
1907
+ for (const key of [...dirtyLiveDbKeys]) {
1908
+ dirtyLiveDbKeys.delete(key);
1909
+ const live = liveDbByKey.get(key);
1910
+ if (live?.operation.active) runDbQuery(live.sql, live.params, live.operation);
1911
+ }
216
1912
  }
217
1913
 
218
1914
  function advance(ms: number): void {
@@ -251,24 +1947,52 @@ function advance(ms: number): void {
251
1947
  // ------------------------------------------------------------ the dispatch
252
1948
 
253
1949
  let model: unknown = null;
1950
+ journalWriter = journalRecordPath ? new DevhostJournalWriter(
1951
+ journalRecordPath,
1952
+ appName ?? path.basename(path.dirname(path.dirname(path.resolve(entry)))),
1953
+ canvasLabel,
1954
+ windowWidth,
1955
+ windowHeight,
1956
+ ) : null;
1957
+ if (journalWriter) {
1958
+ journalWriter.appStart();
1959
+ journalWriter.installFrame(canvasLabel, windowWidth, windowHeight);
1960
+ }
254
1961
  boot();
255
1962
 
256
1963
  function boot(): void {
257
1964
  const booted = mod.initialModel();
258
1965
  const [first, cmd] = Array.isArray(booted) ? booted : [booted, null];
259
- say(`model ${JSON.stringify(jsonable(first))}`);
260
- model = first;
261
- if (cmd) performCmd(cmd as Cmdish);
262
- reconcileSubs();
1966
+ const restored = persistedModel !== null;
1967
+ model = restored ? structuredClone(persistedModel) : first;
1968
+ say(`model ${JSON.stringify(jsonable(model))}`);
1969
+ dispatchDepth += 1;
1970
+ try {
1971
+ if (cmd) performCmd(cmd as Cmdish);
1972
+ reconcileSubs();
1973
+ flushLiveDbSubscriptions();
1974
+ } finally {
1975
+ dispatchDepth -= 1;
1976
+ }
1977
+ drainEffectResults();
1978
+ const route = restored ? persistOk : persistNone;
1979
+ if (route) dispatch({ kind: route });
263
1980
  }
264
1981
 
265
1982
  function dispatch(msg: unknown): void {
266
- const result = mod.update(model, msg);
267
- const [next, cmd] = Array.isArray(result) ? result : [result, null];
268
- model = next;
269
- say(`model ${JSON.stringify(jsonable(model))}`);
270
- if (cmd) performCmd(cmd as Cmdish);
271
- reconcileSubs();
1983
+ dispatchDepth += 1;
1984
+ try {
1985
+ const result = mod.update(model, msg);
1986
+ const [next, cmd] = Array.isArray(result) ? result : [result, null];
1987
+ model = next;
1988
+ say(`model ${JSON.stringify(jsonable(model))}`);
1989
+ if (cmd) performCmd(cmd as Cmdish);
1990
+ reconcileSubs();
1991
+ flushLiveDbSubscriptions();
1992
+ } finally {
1993
+ dispatchDepth -= 1;
1994
+ }
1995
+ drainEffectResults();
272
1996
  }
273
1997
 
274
1998
  function handleLine(raw: string): void {
@@ -282,20 +2006,127 @@ function handleLine(raw: string): void {
282
2006
  return;
283
2007
  }
284
2008
  const record = parsed as Record<string, unknown>;
2009
+ if (typeof record.command === "string") {
2010
+ if (typeof mod.commandMsg !== "function") throw new Error("journalable dev-host commands require the core to export commandMsg(name)");
2011
+ const msg = mod.commandMsg(record.command);
2012
+ if (msg === null || msg === undefined) throw new Error(`commandMsg refused ${record.command}`);
2013
+ dispatch(msg);
2014
+ if (journalWriter) journalWriter.menuCommand(record.command);
2015
+ return;
2016
+ }
285
2017
  if (typeof record.advance === "number") {
286
2018
  advance(record.advance);
287
2019
  return;
288
2020
  }
2021
+ if (record.restart === true) {
2022
+ timers.clear();
2023
+ delays.clear();
2024
+ for (const live of liveDbByKey.values()) releaseDbOperation(live.operation, true);
2025
+ liveDbByKey.clear();
2026
+ dirtyLiveDbKeys.clear();
2027
+ say("restart virtual host");
2028
+ boot();
2029
+ return;
2030
+ }
289
2031
  if (typeof record.kind !== "string") {
290
2032
  console.error(`neither a Msg ({"kind": ...}) nor {"advance": ms}: ${line}`);
291
2033
  return;
292
2034
  }
2035
+ if (journalWriter) throw new Error("session recording accepts {\"command\":\"...\"} inputs, not direct Msg values, so the journal can replay through the packaged platform boundary");
293
2036
  dispatch(revive(parsed));
294
2037
  }
295
2038
 
296
- if (script) {
297
- for (const line of fs.readFileSync(script, "utf8").split("\n")) handleLine(line);
2039
+ function replayServiceEffect(effect: { kind: number; key: bigint; payload: Uint8Array; code: number; dropped: number; channelKind: number; channelDroppedTotal: number }): void {
2040
+ if (effect.kind === 9) {
2041
+ const index = Number(effect.key - requestKeyBase);
2042
+ const task = Number.isSafeInteger(index) && index >= 0 && index < serviceRequestSlots.length ? serviceRequestSlots[index] : null;
2043
+ if (!task) throw new Error(`session replay has no pending service request for engine key ${effect.key}`);
2044
+ const queued = serviceQueue.indexOf(task);
2045
+ if (queued >= 0) serviceQueue.splice(queued, 1);
2046
+ if (effect.code === 0) {
2047
+ const result = task.operation.result.kind === "bytes"
2048
+ ? effect.payload
2049
+ : decodeServiceValue(task.operation.result, new ServiceReader(effect.payload));
2050
+ say(`service ${task.operation.name} replay ok`);
2051
+ serviceSuccess(task, result);
2052
+ } else {
2053
+ say(`service ${task.operation.name} replay err`);
2054
+ serviceFailure(task, effect.payload);
2055
+ }
2056
+ removeServiceKey(task);
2057
+ return;
2058
+ }
2059
+ if (effect.kind === 12) {
2060
+ const key = Number(effect.key);
2061
+ const event = serviceChannels.get(key);
2062
+ if (!event) throw new Error(`session replay has no open service channel ${key}`);
2063
+ const state = effect.channelKind === 0 ? "data" : "closed";
2064
+ dispatch({ kind: event, key, state, bytes: effect.payload, droppedPending: effect.dropped, droppedTotal: effect.channelDroppedTotal });
2065
+ if (effect.channelKind !== 0) serviceChannels.delete(key);
2066
+ return;
2067
+ }
2068
+ throw new Error(
2069
+ `native dev --core replays typed-service host/channel records only; this journal contains effect kind ${effect.kind}. Use native automate replay for full-runtime recordings.`,
2070
+ );
2071
+ }
2072
+
2073
+ function replaySession(): void {
2074
+ const pending: { kind: number; key: bigint; payload: Uint8Array; code: number; dropped: number; channelKind: number; channelDroppedTotal: number }[] = [];
2075
+ for (const record of readDevhostJournal(journalReplayPath!)) {
2076
+ if (record.type === "effect") {
2077
+ pending.push(record);
2078
+ continue;
2079
+ }
2080
+ for (const effect of pending.splice(0)) replayServiceEffect(effect);
2081
+ if (record.tag === 14) {
2082
+ if (typeof mod.commandMsg !== "function") throw new Error("this recorded menu command requires the core to export commandMsg(name)");
2083
+ const msg = mod.commandMsg(record.name);
2084
+ if (msg === null || msg === undefined) throw new Error(`commandMsg refused recorded command ${record.name}`);
2085
+ dispatch(msg);
2086
+ }
2087
+ }
2088
+ if (pending.length > 0) throw new Error("session journal ends with undrained effect results");
2089
+ if (serviceQueue.length > 0 || activeService) throw new Error("session journal ended before every service request received its recorded result");
2090
+ }
2091
+
2092
+ async function waitForServiceChunk(): Promise<void> {
2093
+ const deadline = performance.now() + 5_000;
2094
+ while ((!activeService || activeService.chunks === 0) && performance.now() < deadline) {
2095
+ await new Promise((resolve) => setTimeout(resolve, 1));
2096
+ }
2097
+ if (!activeService || activeService.chunks === 0) throw new Error("timed out waiting for a streaming service chunk");
2098
+ }
2099
+
2100
+ if (journalReplayPath) {
2101
+ replaySession();
2102
+ fs.rmSync(devScratch, { recursive: true, force: true });
2103
+ } else if (script) {
2104
+ for (const line of fs.readFileSync(script, "utf8").split("\n")) {
2105
+ const trimmed = line.trim();
2106
+ if (trimmed.length > 0 && !trimmed.startsWith("#")) {
2107
+ const control = JSON.parse(trimmed) as Record<string, unknown>;
2108
+ if (control.settle === true) {
2109
+ await waitForServicesIdle();
2110
+ continue;
2111
+ }
2112
+ if (control.waitForServiceChunk === true) {
2113
+ await waitForServiceChunk();
2114
+ continue;
2115
+ }
2116
+ }
2117
+ handleLine(line);
2118
+ }
2119
+ await waitForServicesIdle();
2120
+ journalWriter?.finish();
2121
+ if (serviceWorker) await serviceWorker.terminate();
2122
+ fs.rmSync(devScratch, { recursive: true, force: true });
298
2123
  } else {
299
2124
  const rl = readline.createInterface({ input: process.stdin });
300
2125
  rl.on("line", handleLine);
2126
+ rl.on("close", async () => {
2127
+ await waitForServicesIdle();
2128
+ journalWriter?.finish();
2129
+ if (serviceWorker) await serviceWorker.terminate();
2130
+ fs.rmSync(devScratch, { recursive: true, force: true });
2131
+ });
301
2132
  }