@native-sdk/cli 0.8.4 → 0.9.1

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