@threadedstack/wmd-web 0.1.38 → 0.1.41

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 (68) hide show
  1. package/README.md +239 -2
  2. package/RELEASE.json +97 -53
  3. package/guest/arm64/Image +1 -1
  4. package/guest/arm64/Image-4k +1 -1
  5. package/guest/arm64/initramfs.cpio.gz +0 -0
  6. package/package.json +3 -3
  7. package/src/boot.js +321 -12
  8. package/src/edge/auto.js +77 -0
  9. package/src/edge/base.js +10 -0
  10. package/src/edge/bridge.js +76 -7
  11. package/src/edge/ctl.js +21 -4
  12. package/src/edge/error-kind.js +6 -0
  13. package/src/edge/frame-code.gen.js +6 -0
  14. package/src/edge/frame.js +58 -15
  15. package/src/edge/msg.js +3 -0
  16. package/src/edge/own/adapter.js +208 -19
  17. package/src/edge/own/exit-now.js +62 -0
  18. package/src/edge/own/fs-own-route.js +40 -3
  19. package/src/edge/own/fs-stats.js +11 -0
  20. package/src/edge/own/hub.js +125 -14
  21. package/src/edge/own/loader.js +3 -2
  22. package/src/edge/own/marks.js +158 -0
  23. package/src/edge/own/net-host.js +873 -0
  24. package/src/edge/own/node-globals.js +142 -0
  25. package/src/edge/own/pool.js +30 -1
  26. package/src/edge/own/service-receiver.js +7 -1
  27. package/src/edge/own/shim-post.js +38 -0
  28. package/src/edge/own/worker.js +34 -1
  29. package/src/edge/page.js +448 -25
  30. package/src/edge/pins.gen.js +17 -0
  31. package/src/edge/pins.js +21 -0
  32. package/src/edge/plan.js +45 -9
  33. package/src/edge/python-module.js +18 -0
  34. package/src/edge/python-pins.js +64 -0
  35. package/src/edge/python-plan.js +280 -0
  36. package/src/edge/python-source.js +34 -0
  37. package/src/edge/runtime.js +13 -2
  38. package/src/edge/sbx/cap.js +36 -0
  39. package/src/edge/sbx/common.js +186 -0
  40. package/src/edge/sbx/doc.js +121 -0
  41. package/src/edge/sbx/files.js +112 -0
  42. package/src/edge/sbx/frame.js +126 -0
  43. package/src/edge/sbx/gate.js +115 -0
  44. package/src/edge/sbx/sha256.js +68 -0
  45. package/src/edge/sbx/worker-entry.js +36 -0
  46. package/src/edge/sems.js +113 -0
  47. package/src/edge/service-host.js +57 -5
  48. package/src/edge/service-port.js +79 -5
  49. package/src/edge/setup.js +275 -0
  50. package/src/edge/shim.js +3 -1
  51. package/src/edge/watch.js +101 -0
  52. package/src/edge/worker.js +31 -2
  53. package/src/gowasm/boot-setup.js +175 -0
  54. package/src/gowasm/make-pins-module.mjs +35 -0
  55. package/src/gowasm/pins-data.js +162 -0
  56. package/src/gowasm/setup.js +167 -0
  57. package/src/gowasm/twin-fetch.js +27 -0
  58. package/src/host/chan-service.js +33 -6
  59. package/src/host/chan-services.js +29 -4
  60. package/src/host/ckpt.js +78 -0
  61. package/src/host/csp-reason.js +64 -0
  62. package/src/host/ctl.js +30 -8
  63. package/src/host/edge-go.js +94 -4
  64. package/src/host/edge-host.js +58 -3
  65. package/src/host/gowasm-guard.js +11 -1
  66. package/src/host/gowasm-worker.js +90 -35
  67. package/src/host/pinned-fetch.js +436 -0
  68. package/wmdpack.wasm +0 -0
package/src/host/ckpt.js CHANGED
@@ -106,6 +106,42 @@ export async function bootKeyForLayout(desc, layout) {
106
106
  return { key: await sha256Hex(new TextEncoder().encode(JSON.stringify(d))), desc: d }
107
107
  }
108
108
 
109
+ /**
110
+ * X6 default part 4: which of these texts of one file did the checkpoint's boot have? `texts` is {name: text} (text: a string or bytes) for the file `path`
111
+ * of service number `index` (the 9P service whose port is `port`); the answer is the name whose sample key (the one bootKeyOf records) is the key the
112
+ * header's boot description holds for that file, or null: no description (a checkpoint from before bootDesc existed), no such service or port, no such
113
+ * file, or a text that is none of them. It is the only thing read of the header: a feature that adds mounts to the container's spec (the Go twin, the
114
+ * node edge of X5) makes the spec text in each variant it can run in and asks this which one the checkpoint had; the checks of the restore (the whole key,
115
+ * the packs) stay as they are. Two names with the same text answer the first.
116
+ */
117
+ export async function specChoice(h, index, port, path, texts) {
118
+ const s = h && typeof h === 'object' && h.bootDesc && typeof h.bootDesc === 'object' && Array.isArray(h.bootDesc.services) ? h.bootDesc.services[index] : null
119
+ const rec = s && typeof s === 'object' && s.port === port && s.bundle && typeof s.bundle === 'object' ? s.bundle[path] : null
120
+ if (typeof rec !== 'string' || !texts || typeof texts !== 'object') return null
121
+ for (const [name, text] of Object.entries(texts)) {
122
+ if (typeof text !== 'string' && !(text instanceof Uint8Array)) continue
123
+ if ((await sampleKey(typeof text === 'string' ? new TextEncoder().encode(text) : text)) === rec) return name
124
+ }
125
+ return null
126
+ }
127
+
128
+ /**
129
+ * X6 default part 4: the key and description of the boot that `desc` describes with other texts of some services' files: `keys` is {serviceIndex:
130
+ * {path: sampleKey}} or, for the Go twin's one file, {serviceIndex: sampleKey of bundle/config/config.json}; the RAM layout is bootKeyForLayout's. No file
131
+ * is read again (a restore that keeps its boot files, and the preflight of vm.restore()).
132
+ */
133
+ export async function bootKeyForChoice(desc, layout, keys) {
134
+ const base = bootDescForLayout(desc, layout)
135
+ const services = (base.services || []).map((s, i) => {
136
+ const k = keys && keys[i]
137
+ if (k === undefined || k === null) return s
138
+ const set = typeof k === 'string' ? { 'bundle/config/config.json': k } : k
139
+ return { ...s, bundle: { ...s.bundle, ...set } }
140
+ })
141
+ const d = { ...base, services }
142
+ return { key: await sha256Hex(new TextEncoder().encode(JSON.stringify(d))), desc: d }
143
+ }
144
+
109
145
  /** The ports a resume writes for the guest (vm_resume_args), from the command line. */
110
146
  export function resumePorts(args) {
111
147
  const get = name => {
@@ -320,6 +356,41 @@ export function bootDescLayoutOnly(a, b) {
320
356
  return JSON.stringify(a) !== JSON.stringify(b) && rest(a) === rest(b)
321
357
  }
322
358
 
359
+ // a boot description as bootKeyOf writes it is 5 levels deep (desc, services, a service, its bundle, a key's value)
360
+ const DESC_MAX_DEPTH = 32
361
+ /** Whether `v` holds an object nested `max` levels or more below it (walked without recursion: the input is untrusted). */
362
+ function deeperThan(v, max) {
363
+ const todo = [[v, 0]]
364
+ while (todo.length) {
365
+ const [x, depth] = todo.pop()
366
+ if (!x || typeof x !== 'object') continue
367
+ if (depth >= max) return true
368
+ for (const k of Object.keys(x)) todo.push([x[k], depth + 1])
369
+ }
370
+ return false
371
+ }
372
+
373
+ /**
374
+ * Fix 10 (F2): whether a boot description that a header carries is not the shape bootKeyOf writes: not a plain object, `services` not a list, a service that is
375
+ * not a plain object or whose `bundle` is not one, or objects nested deeper than any boot writes. A missing description (a checkpoint from before bootDesc existed) is not damaged, it is old.
376
+ */
377
+ export function bootDescDamaged(d) {
378
+ if (d === undefined) return false
379
+ if (!d || typeof d !== 'object' || Array.isArray(d)) return true
380
+ if (!Array.isArray(d.services)) return true
381
+ if (deeperThan(d, DESC_MAX_DEPTH)) return true // (the comparisons below walk it by recursion: a header nested without end must not reach them)
382
+ return d.services.some(s => !s || typeof s !== 'object' || Array.isArray(s) || (s.bundle !== undefined && (!s.bundle || typeof s.bundle !== 'object' || Array.isArray(s.bundle))))
383
+ }
384
+
385
+ /** X6 part 4: whether two boot descriptions differ only in a service's bundle/config/config.json key (the container's spec text). */
386
+ export function bootDescSpecOnly(a, b) {
387
+ if (bootDescDamaged(a) || bootDescDamaged(b)) return false
388
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object' || !Array.isArray(a.services) || a.services.length !== (b.services || []).length) return false
389
+ // a header is untrusted: a service that is not an object, or whose bundle is not one, is kept as it is (the two then differ and the answer is false)
390
+ const strip = d => JSON.stringify({ ...d, services: d.services.map(s => (s && typeof s === 'object' && !Array.isArray(s) ? { ...s, bundle: { ...(s.bundle && typeof s.bundle === 'object' ? s.bundle : {}), 'bundle/config/config.json': 0 } } : s)) })
391
+ return JSON.stringify(a) !== JSON.stringify(b) && strip(a) === strip(b)
392
+ }
393
+
323
394
  /** The part of the fit check that needs only vm.wasm's key: a snapshot from another vm.wasm is refused before anything else is read of it. */
324
395
  export function checkVmKeyFits(h, vmKey) {
325
396
  if (h.format !== FORMAT_VERSION) throw new CheckpointError('version', `checkpoint format ${h.format}; this build restores format ${FORMAT_VERSION}`)
@@ -334,11 +405,18 @@ export function checkCheckpointFits(h, { vmKey, bootKey, bootDesc, maxPages, ram
334
405
  throw new CheckpointError('stale', `this checkpoint was taken with a different vm.wasm (${String(h.vmKey).slice(0, 12)}, this boot has ${String(vmKey).slice(0, 12)}): its memory image is the old emulator's and cannot be restored; take a new one`)
335
406
  }
336
407
  if (h.bootKey !== bootKey) {
408
+ // a header is untrusted input: a boot description of another shape than bootKeyOf writes is a damaged header, said as such (and read no further)
409
+ if (bootDescDamaged(h.bootDesc)) throw new CheckpointError('stale', "this checkpoint's header holds a damaged boot description (not the shape a boot writes), so it cannot be the one this boot made: take a new checkpoint")
337
410
  const diff = bootDescDiff(h.bootDesc, bootDesc)
338
411
  // X24: only the RAM layout differs (memory 0 or a memory of its own, or the memory maximum): say so, not "a different kernel ..."
339
412
  if (diff && bootDescLayoutOnly(h.bootDesc, bootDesc)) {
340
413
  throw new CheckpointError('stale', `this checkpoint was taken with a different RAM layout than this boot (the guest's RAM in memory 0 or in a memory of its own, or another memory maximum); restore it only with the same layout: the same ramInMemory0, flatRam and allowLargeRam settings as when it was taken (differs: ${diff})`)
341
414
  }
415
+ // the container's spec text (bundle/config/config.json) is the only difference: say what is known, and nothing about why (a changed command or environment, a
416
+ // volume, or a boot that adds or leaves out stub mounts of a helper: this function cannot tell which)
417
+ if (diff && bootDescSpecOnly(h.bootDesc, bootDesc)) {
418
+ throw new CheckpointError('stale', "this checkpoint was taken with a different container spec than this boot has (bundle/config/config.json is not the one the checkpoint was taken with, and nothing else differs): restore it only with the same spec, or take a new checkpoint")
419
+ }
342
420
  throw new CheckpointError('stale', `this checkpoint was taken by a boot with a different kernel, initramfs, command line, environment, image layers or bundle files than this one; restore it only into the same configuration${diff ? ` (differs: ${diff})` : ''}`)
343
421
  }
344
422
  if (h.memPages > maxPages) throw new CheckpointError('stale', `this checkpoint's memory is ${h.memPages} pages and this boot's maximum is ${maxPages}`)
@@ -0,0 +1,64 @@
1
+ // X6 fix 10 (F4): the reason of a source that the page's Content-Security-Policy blocked. A blocked fetch rejects with the same TypeError ("Failed to fetch")
2
+ // as a dead network, so the text says nothing; the browser tells the policy's side through a `securitypolicyviolation` event. cspWatch listens for it in the
3
+ // scope that fetches (the Worker's global scope; the page's document forwards its own events with add(), for a browser that fires it there) and explains a
4
+ // source that threw: the policy blocked it, which directive, which origin to add, or that the app can name a source of its own. It changes no event type.
5
+
6
+ const MAX = 32
7
+ // the directives that govern a fetch (connect-src; default-src where an engine names the fallback it applied)
8
+ const FETCH_DIRECTIVES = new Set(['connect-src', 'default-src'])
9
+ // the event is queued as a task by the browser: it may arrive after the fetch has rejected, so a network error waits for it up to this long (a dead network pays it once per source)
10
+ const EVENT_WAIT_MS = 40
11
+
12
+ /**
13
+ * @param {{addEventListener: Function}|null} scope where the violations fire (self in a Worker); null: none is listened for
14
+ * @param {{origin?: string}} [o] the scope's own origin (a source of it is never a policy block)
15
+ */
16
+ export function cspWatch(scope, o = {}) {
17
+ const seen = []
18
+ const own = o.origin ?? (typeof self !== 'undefined' && self.location && self.location.origin) ?? ''
19
+ const add = e => {
20
+ if (!e || typeof e !== 'object' || typeof e.blockedURI !== 'string' || e.disposition === 'report') return
21
+ // only what governs a fetch: the app's own violations of other directives (an image, a script of the same origin) say nothing about a source's request,
22
+ // and they do not push a source's violation out of the list
23
+ const directive = String(e.effectiveDirective || e.violatedDirective || 'connect-src').split(' ')[0]
24
+ if (!FETCH_DIRECTIVES.has(directive)) return
25
+ if (seen.length >= MAX) seen.shift()
26
+ seen.push({ blocked: e.blockedURI, directive })
27
+ }
28
+ try {
29
+ scope?.addEventListener?.('securitypolicyviolation', add)
30
+ } catch {
31
+ // a scope that cannot be listened to: only the plain hint is left
32
+ }
33
+ const originOf = u => {
34
+ try {
35
+ const x = new URL(u)
36
+ return x.origin === 'null' ? '' : x.origin
37
+ } catch {
38
+ return ''
39
+ }
40
+ }
41
+ return {
42
+ add,
43
+ count: () => seen.length,
44
+ /** The reason text for a source (`url`) whose fetch threw `err`, or null when this says nothing more than the error does. */
45
+ async explain(url, err) {
46
+ const origin = originOf(url)
47
+ const find = () => origin && seen.find(v => v.blocked === url || originOf(v.blocked) === origin)
48
+ let hit = find()
49
+ if (!hit && origin && err instanceof TypeError) {
50
+ for (let waited = 0; !hit && waited < (o.waitMs ?? EVENT_WAIT_MS); waited += 5) {
51
+ await new Promise(r => setTimeout(r, 5))
52
+ hit = find()
53
+ }
54
+ }
55
+ if (hit) {
56
+ return `the page's Content-Security-Policy blocked it (${hit.directive}): add ${origin} to ${hit.directive} in the page's policy, or name a source of your own that the policy allows (gowasm: { sources: [...] })`
57
+ }
58
+ if (origin && own && origin !== own && err instanceof TypeError) {
59
+ return `could not be fetched: ${err.message} (a network error: if the page has a Content-Security-Policy, its connect-src must list ${origin}, or the app names a source of its own)`
60
+ }
61
+ return null
62
+ },
63
+ }
64
+ }
package/src/host/ctl.js CHANGED
@@ -765,6 +765,35 @@ function defaultMounts() {
765
765
  ]
766
766
  }
767
767
 
768
+ /**
769
+ * X6: the mounts that put the guest's edge stub over each tool of `tools` ({name, path}): the stub folder (once: with the page switch edge=1 and the twin together X5's
770
+ * mounts already have it), the real binary bound into it, and the stub over the tool's own path. Returns a new list; a mount that is already there (the same
771
+ * destination and source) is not added again, so adding twice changes nothing. They go after the bundle's /etc files, where containerBundle puts them, and
772
+ * before the caller's volumes. The twin's setup in bootWmd (src/gowasm/boot-setup.js) calls this with the spec read from the 9P service's files.
773
+ */
774
+ export function addEdgeToolMounts(mounts, tools) {
775
+ const out = [...mounts]
776
+ let at = out.length
777
+ for (let i = out.length - 1; i >= 0; i--) {
778
+ if (typeof out[i].source === 'string' && out[i].source.startsWith(`${GUEST_9P_MOUNT}/bundle/etc/`)) {
779
+ at = i + 1
780
+ break
781
+ }
782
+ }
783
+ const add = []
784
+ const has = m => out.some(x => x.destination === m.destination && x.source === m.source) || add.some(x => x.destination === m.destination && x.source === m.source)
785
+ const put = m => {
786
+ if (!has(m)) add.push(m)
787
+ }
788
+ if (!out.some(m => m.destination === EDGE_CONTAINER_DIR)) put({ destination: EDGE_CONTAINER_DIR, type: 'bind', source: EDGE_GUEST_DIR, options: ['rbind', 'rw'] })
789
+ for (const t of tools) {
790
+ put({ destination: `${EDGE_CONTAINER_DIR}/${t.name}`, type: 'bind', source: `${GUEST_9P_MOUNT}/rootfs${t.path}`, options: ['bind', 'ro'] })
791
+ put({ destination: t.path, type: 'bind', source: EDGE_STUB, options: ['bind', 'ro'] })
792
+ }
793
+ out.splice(at, 0, ...add)
794
+ return out
795
+ }
796
+
768
797
  /**
769
798
  * The 9P tree's files for a container (paths relative to the share root, beside the
770
799
  * rootfs/ the packs give): bundle/config/config.json, bundle/config/imageconfig.json,
@@ -838,14 +867,7 @@ export function containerBundle(o) {
838
867
  for (const name of ETC_FILES) {
839
868
  spec.mounts.push({ destination: `/etc/${name}`, type: 'bind', source: `${GUEST_9P_MOUNT}/bundle/etc/${name}`, options: ['rbind', 'rprivate', 'rw'] })
840
869
  }
841
- if (o.edge?.tools?.length) {
842
- // the stub folder once: with edge=1 and gowasm=1 together X5's mounts above already have it
843
- if (!spec.mounts.some(m => m.destination === EDGE_CONTAINER_DIR)) spec.mounts.push({ destination: EDGE_CONTAINER_DIR, type: 'bind', source: EDGE_GUEST_DIR, options: ['rbind', 'rw'] })
844
- for (const t of o.edge.tools) {
845
- spec.mounts.push({ destination: `${EDGE_CONTAINER_DIR}/${t.name}`, type: 'bind', source: `${GUEST_9P_MOUNT}/rootfs${t.path}`, options: ['bind', 'ro'] })
846
- spec.mounts.push({ destination: t.path, type: 'bind', source: EDGE_STUB, options: ['bind', 'ro'] })
847
- }
848
- }
870
+ if (o.edge?.tools?.length) spec.mounts = addEdgeToolMounts(spec.mounts, o.edge.tools)
849
871
  const files = {}
850
872
  ;(o.mounts || []).forEach((m, i) => {
851
873
  const share = `vol${i}`
@@ -277,7 +277,7 @@ export function mountPoints(list) {
277
277
  * early, run, and then sent to the guest by a late fallback frame without writing its outputs. Needs a stub that says late_fallback.
278
278
  */
279
279
  export class GoEdge {
280
- constructor({ fs, root = 'rootfs', tools, post, restart = null, stop = null, onRecord = null, onEvent = null, now = () => performance.now(), maxReruns = 2, maxInputBytes = 256 << 20, earlyReply = false, lateFallbackAt = 0, mounts = null, beatLimitMs = BEAT_LIMIT_MS, readyLimitMs = READY_LIMIT_MS, runLimitMs = RUN_LIMIT_MS }) {
280
+ constructor({ fs, root = 'rootfs', tools, post, restart = null, stop = null, onRecord = null, onEvent = null, now = () => performance.now(), maxReruns = 2, maxInputBytes = 256 << 20, earlyReply = false, lateFallbackAt = 0, mounts = null, beatLimitMs = BEAT_LIMIT_MS, readyLimitMs = READY_LIMIT_MS, runLimitMs = RUN_LIMIT_MS, off = '' }) {
281
281
  this.mounts = mounts ? mountPoints(mounts.filter(m => m)) : null
282
282
  this.earlyReply = earlyReply
283
283
  this.lateFallbackAt = lateFallbackAt
@@ -297,6 +297,13 @@ export class GoEdge {
297
297
  this.ruleWhy = {} // rule -> the reason text of the first time
298
298
  this.offWhy = null // fix 11 (F-N): the reason it is off, once it is
299
299
  this.off = false // turned off for the machine (FAIL_LIMIT failures in a row, or a module that is not the one tools.json names)
300
+ // X6 default part 6: off from the start. A machine restored from a checkpoint taken with the twin, in a boot that has the twin off: the stub mounts are in the
301
+ // guest's memory, no twin Worker exists, and the stub is answered by the very guard a twin that went off during the machine's life meets (#serve: the compile
302
+ // goes back to the guest as a fallback). The page said why once when it chose, so no event is raised here.
303
+ if (off) {
304
+ this.off = true
305
+ this.offWhy = String(off)
306
+ }
300
307
  this.lastBeat = 0
301
308
  this.watch = null // the timer of the watchdog, there while a run is out or the Worker has not said ready
302
309
  this.readyBy = now() + readyLimitMs // the Worker must say ready by then
@@ -305,11 +312,13 @@ export class GoEdge {
305
312
  this.maxReruns = maxReruns
306
313
  this.maxInputBytes = maxInputBytes
307
314
  this.known = new Map() // tool path -> {key, res}
315
+ this.loadingFor = new Map() // X6 default part 5: module key (the run's `module`, '' for the first) -> the Worker's sha256, while that module is still loading
316
+ this.loadInfo = null // the last {t:'loaded'} the Worker sent (bytes, fetchMs, compileMs)
308
317
  this.sent = new Map() // path -> key: what the twin holds (its cache, as it last said)
309
318
  this.queue = []
310
319
  this.busy = null
311
320
  this.ready = false
312
- this.dead = false
321
+ this.dead = !!off
313
322
  this.open = new Set() // jobs whose stub is waiting for an answer (a checkpoint must not be taken meanwhile)
314
323
  this.jobs = new Set() // jobs whose stub has said hello and whose stream is not closed yet
315
324
  this.live = new Set() // the guest init's streams for stubs that are connected (from the request line until the stub is gone)
@@ -629,10 +638,59 @@ export class GoEdge {
629
638
  }
630
639
  }
631
640
  if (!dropped) return { kept, dropped }
641
+ this.#cut(spec, file, drop, dropReal, kept)
642
+ return { kept, dropped }
643
+ }
644
+
645
+ /** Takes the stub mounts of the paths in `drop` (and the real binaries' mounts in `dropReal`) out of the spec and writes it back. */
646
+ #cut(spec, file, drop, dropReal, kept) {
632
647
  spec.mounts = spec.mounts.filter(m => !drop.has(m.destination) && !dropReal.some(d => d.dest === m.destination && typeof m.source === 'string' && m.source.endsWith(d.src)))
633
648
  // the stub folder goes with the last thing in it. Another stub may live there: with the page switch edge=1 (X5) the image's node does
634
649
  if (!kept && !spec.mounts.some(m => typeof m.destination === 'string' && m.destination.startsWith(`${EDGE_DIR}/`))) spec.mounts = spec.mounts.filter(m => m.destination !== EDGE_DIR)
635
650
  this.fs.writeFile(file, JSON.stringify(spec, null, 2) + '\n')
651
+ }
652
+
653
+
654
+ /**
655
+ * X6 default part 3: the second half of the image deciding. pruneBundle takes out the stubs of tools the image does not have; this takes out
656
+ * those of tools it has that are no tool the twin stands for (a Go release the pins do not name, an architecture they do not carry): such a
657
+ * compile would be handed to the page and given back to the guest at every run, so the guest is left to run it alone from the start, and
658
+ * ONE calm event (rule `unpinned`) says why. The file is hashed here, once, instead of at the first compile (the answer is kept, #recognize
659
+ * reads the same cache). A file that cannot be read or hashed keeps its mounts: only a hash that is no known tool drops them. Awaited by
660
+ * the channel service before the guest reads the spec.
661
+ */
662
+ async pruneUnpinned() {
663
+ const file = 'bundle/config/config.json'
664
+ let spec
665
+ try {
666
+ spec = JSON.parse(new TextDecoder().decode(this.fs.readFile(file)))
667
+ } catch {
668
+ return { kept: 0, dropped: 0 }
669
+ }
670
+ if (!spec || !Array.isArray(spec.mounts)) return { kept: 0, dropped: 0 }
671
+ let kept = 0
672
+ let dropped = 0
673
+ const drop = new Set()
674
+ const dropReal = []
675
+ const seen = new Set()
676
+ let why = ''
677
+ for (const t of Object.values(this.tools)) {
678
+ if (!t || typeof t.path !== 'string' || !spec.mounts.some(m => m.destination === t.path) || seen.has(t.path)) continue
679
+ seen.add(t.path)
680
+ let res = null
681
+ try {
682
+ res = await this.#recognize(t.path)
683
+ } catch {}
684
+ if (res && res.unpinned) {
685
+ dropped++
686
+ drop.add(t.path)
687
+ dropReal.push({ dest: `${EDGE_DIR}/${t.name}`, src: `rootfs${t.path}` })
688
+ why = why || res.fallback
689
+ } else kept++
690
+ }
691
+ if (!dropped) return { kept, dropped }
692
+ this.#cut(spec, file, drop, dropReal, kept)
693
+ this.#note('unpinned', why)
636
694
  return { kept, dropped }
637
695
  }
638
696
 
@@ -654,7 +712,7 @@ export class GoEdge {
654
712
  // a copy: the bytes may sit in shared memory, which digest refuses
655
713
  const sha = hex(await crypto.subtle.digest('SHA-256', this.fs.read(r.node, 0, a.size).slice()))
656
714
  const t = this.tools[sha]
657
- const res = t ? { ok: true, name: t.name, sha256: sha, arch: toolArch(t), module: t.wasmSha256 } : { fallback: `${path}: sha256 ${sha.slice(0, 12)} is not a tool the twin stands for` }
715
+ const res = t ? { ok: true, name: t.name, sha256: sha, arch: toolArch(t), module: t.wasmSha256 } : { fallback: `${path}: sha256 ${sha.slice(0, 12)} is not a tool the twin stands for`, unpinned: true }
658
716
  this.known.set(path, { key, res })
659
717
  return res
660
718
  }
@@ -854,7 +912,11 @@ export class GoEdge {
854
912
  async #serveChecked(job, h, parsed, rec, ctx) {
855
913
  const tool = await this.#recognize(h.argv[0])
856
914
  if (job.done) return
857
- if (!tool.ok) return this.#toGuest(job, tool.fallback)
915
+ if (!tool.ok) {
916
+ // X6 part 3: a compile the pins do not know (a Go release with no pin): the image is fine, the twin simply has no module for it. One calm event, once
917
+ if (tool.unpinned) this.#note('unpinned', tool.fallback)
918
+ return this.#toGuest(job, tool.fallback)
919
+ }
858
920
  rec.tool = tool.name
859
921
 
860
922
  const cwd = h.cwd || '/'
@@ -916,8 +978,11 @@ export class GoEdge {
916
978
  }
917
979
  let reruns = 0
918
980
  for (;;) {
981
+ // X6 default part 5: the module is still loading (the Worker said so): nothing is posted, the guest compiles
982
+ if (this.loadingFor.has(tool.module ?? '')) return this.#toGuest(job, 'the twin is still loading', { reruns })
919
983
  const r = await this.#toTwin(job, { argv: h.argv, env, cwd, want, rec, ctx, module: tool.module })
920
984
  if (job.done || job.cancelled) return
985
+ if (r.loading) return this.#toGuest(job, 'the twin is still loading', { reruns })
921
986
  if (r.infra) return this.#toGuest(job, r.infra, { reruns })
922
987
  // a file the compile looked for and the container has: send it and run again (a fresh instance)
923
988
  const asked = []
@@ -1052,6 +1117,14 @@ export class GoEdge {
1052
1117
  this.dead = false
1053
1118
  this.readyInfo = m
1054
1119
  this.#pump()
1120
+ } else if (m.t === 'loading') {
1121
+ // X6 default part 5: the Worker is downloading the module: that is life for a run that waits for it
1122
+ if (this.busy) this.lastBeat = this.now()
1123
+ this.loadBytes = m.bytes
1124
+ } else if (m.t === 'loaded') {
1125
+ for (const [k, v] of [...this.loadingFor]) if (v === m.sha) this.loadingFor.delete(k)
1126
+ this.loadInfo = { sha: m.sha, wasmBytes: m.wasmBytes, fetchMs: m.fetchMs, compileMs: m.compileMs }
1127
+ this.onEvent?.({ t: 'gowasm-loaded', sha: String(m.sha).slice(0, 12), wasmBytes: m.wasmBytes, fetchMs: Math.round(m.fetchMs || 0), compileMs: Math.round(m.compileMs || 0) }) // calm: the numbers of the load
1055
1128
  } else if (m.t === 'beat') {
1056
1129
  const q = this.busy
1057
1130
  if (!q || q.id !== m.id) return // a beat of a run that was cancelled
@@ -1074,6 +1147,20 @@ export class GoEdge {
1074
1147
  this.sent.clear()
1075
1148
  for (const [p, k] of m.held) this.sent.set(p, k)
1076
1149
  }
1150
+ if (m.loading) {
1151
+ // X6 default part 5: the module is still loading. Not a failure (nothing is counted, nothing restarts): this compile and every one queued behind it
1152
+ // for the same module go to the guest, and so does every later one until the Worker says `loaded`
1153
+ const k = q.module ?? ''
1154
+ this.loadingFor.set(k, m.module)
1155
+ q.resolve({ loading: true })
1156
+ for (const w of this.queue.filter(x => (x.module ?? '') === k)) {
1157
+ this.queue.splice(this.queue.indexOf(w), 1)
1158
+ w.job.queued = false
1159
+ w.resolve({ loading: true })
1160
+ }
1161
+ this.#pump()
1162
+ return
1163
+ }
1077
1164
  if (!m.infra) this.failures = 0 // a compile the twin ran to its end: the failures before it no longer count
1078
1165
  q.resolve(m.infra ? { infra: m.infra } : m)
1079
1166
  this.#pump()
@@ -1098,6 +1185,7 @@ export class GoEdge {
1098
1185
  this.ready = false
1099
1186
  this.dead = true
1100
1187
  this.sent.clear()
1188
+ this.loadingFor.clear() // the Worker is replaced: its download goes with it
1101
1189
  const q = this.busy
1102
1190
  this.busy = null
1103
1191
  if (q) {
@@ -1118,6 +1206,7 @@ export class GoEdge {
1118
1206
  #turnOff(why) {
1119
1207
  if (this.off) return
1120
1208
  this.off = true
1209
+ this.loadingFor.clear()
1121
1210
  this.offWhy = why // fix 11 (F-N): the counters say why, not only the event
1122
1211
  this.ready = false
1123
1212
  this.dead = true
@@ -1143,6 +1232,7 @@ export class GoEdge {
1143
1232
  this.dead = false
1144
1233
  this.ready = false
1145
1234
  this.sent.clear()
1235
+ this.loadingFor.clear()
1146
1236
  this.readyBy = this.now() + this.readyLimitMs
1147
1237
  this.#arm()
1148
1238
  }
@@ -58,6 +58,9 @@ export function helloRefusal(h) {
58
58
  const tz = (h.env || []).findLast(kv => kv.startsWith('TZ='))
59
59
  if (tz !== undefined && !isUtcZone(tz.slice(3))) return `${tz}: the frame's clock zone is UTC`
60
60
  const base = String((h.argv || [])[0] || '').split('/').pop()
61
+ // X25 gate 2: a python start is the owner's to decide (src/edge/service-host.js, src/edge/python-plan.js): the stub stands over python only when the page's
62
+ // plan took the image's python, and the owner answers the cases of the command line, the tree and the environment with a fallback and its reason
63
+ if (/^python/.test(base)) return ''
61
64
  if (!/^node/.test(base)) return `${base || 'no program'} is not node`
62
65
  return ''
63
66
  }
@@ -79,10 +82,17 @@ export class EdgeHost {
79
82
  this.start = start
80
83
  this.startTimeoutMs = startTimeoutMs
81
84
  this.log = log
82
- this.stats = { streams: 0, notEdge: 0, fallbacks: 0, runs: 0, exits: 0, badFrames: 0, outBytes: { stdout: 0, stderr: 0 }, outEnded: 0, fallbackWhy: Object.create(null) } // null prototype: the names are the frame's (check5 F4)
85
+ this.stats = { streams: 0, notEdge: 0, fallbacks: 0, runs: 0, exits: 0, badFrames: 0, outBytes: { stdout: 0, stderr: 0 }, outEnded: 0, fallbackWhy: Object.create(null), trips: [] } // null prototype: the names are the frame's (check5 F4)
86
+ this.txWait = [] // [trip, field] stamps that wait for the flush that puts the bytes just queued into the guest's ring (flushed())
83
87
  this.stubs = new Set() // the stubs connected now: from the guest's stream until the stub's end (hello, reply and the whole run included)
84
88
  }
85
89
 
90
+ /** The channel service put what was queued for the guest into its ring at `t` (page clock): the stamps that waited for it get it. */
91
+ flushed(t = at()) {
92
+ for (const [trip, k] of this.txWait) if (trip[k] === undefined) trip[k] = t
93
+ this.txWait.length = 0
94
+ }
95
+
86
96
  /** How many stubs are connected. A stub that waits for a reply, or whose program runs here, cannot be carried over a checkpoint. */
87
97
  openStubs() {
88
98
  return this.stubs.size
@@ -108,6 +118,7 @@ class OuterConn {
108
118
  this.buf = new Uint8Array(0)
109
119
  this.nested = null
110
120
  st.onData = u8 => {
121
+ if (this.first === undefined) host.lastOf = this.first = at()
111
122
  st.consume(u8.length)
112
123
  if (this.nested) return this.nested.feed(u8)
113
124
  const b = new Uint8Array(this.buf.length + u8.length)
@@ -202,6 +213,10 @@ export function execStream(session) {
202
213
  }
203
214
  }
204
215
 
216
+ // X25 gate 2e: the page's clock every Worker shares (timeOrigin + now); the stamps of one stub's start are kept in stats.trips (the last 64)
217
+ const at = () => performance.timeOrigin + performance.now()
218
+ const TRIPS_KEPT = 64
219
+
205
220
  class EdgeConn {
206
221
  constructor(host, st, hold, session = null) {
207
222
  this.host = host
@@ -210,6 +225,8 @@ class EdgeConn {
210
225
  this.hold = hold
211
226
  this.buf = new Uint8Array(0)
212
227
  this.phase = 'hello' // hello -> wait -> run
228
+ this.trip = null // {of, hi, rp, ex}: the stamps of this start on the page's clock
229
+ this.of = host.lastOf // the first bytes of the outer stream this stub came by
213
230
  this.runner = null
214
231
  this.ended = false
215
232
  st.onData = u8 => {
@@ -241,6 +258,9 @@ class EdgeConn {
241
258
  const p = this.buf.slice(5, 5 + n)
242
259
  this.buf = this.buf.subarray(5 + n)
243
260
  if (this.phase === 'hello') {
261
+ // X5 net: a stream the stub opened for a connection its listener took is not a hello: its header says `accepted` and what follows is the
262
+ // connection's bytes. The run's network host (set by its start, ctx.setAccepted) takes it; with none, or when it refuses, the stream is reset.
263
+ if (type === FRAME_HDR && this.session && p.length < 512 && this.#accepted(p)) return
244
264
  if (type !== FRAME_HDR) {
245
265
  this.host.stats.badFrames++
246
266
  return this.st.abort('no hello')
@@ -253,7 +273,35 @@ class EdgeConn {
253
273
  }
254
274
  }
255
275
 
276
+ /** True when `p` is an `accepted` header and the stream was handled (taken by the run's network host or reset). */
277
+ #accepted(p) {
278
+ let h
279
+ try {
280
+ h = JSON.parse(dec.decode(p))
281
+ } catch {
282
+ return false
283
+ }
284
+ if (!h || h.kind !== 'accepted') return false
285
+ const st = this.st
286
+ const rest = this.buf
287
+ this.buf = new Uint8Array(0)
288
+ this.ended = true // this connection object does nothing more with the stream
289
+ this.host.stats.accepted = (this.host.stats.accepted || 0) + 1
290
+ let ok = false
291
+ try {
292
+ ok = typeof this.session.accepted === 'function' && this.session.accepted(st, h, rest) !== false
293
+ } catch {
294
+ ok = false
295
+ }
296
+ if (!ok && !st.closed) st.abort('no listener for this stream')
297
+ return true
298
+ }
299
+
256
300
  #reply(r) {
301
+ if (this.trip) {
302
+ this.trip.rp = at()
303
+ this.host.txWait.push([this.trip, 'rw'])
304
+ }
257
305
  if (!this.ended) this.st.write(frame(FRAME_REPLY, r))
258
306
  }
259
307
 
@@ -266,6 +314,9 @@ class EdgeConn {
266
314
  }
267
315
 
268
316
  async #hello(p) {
317
+ const trips = this.host.stats.trips
318
+ trips.push((this.trip = { of: this.of ?? at(), hi: at() }))
319
+ if (trips.length > TRIPS_KEPT) trips.splice(0, trips.length - TRIPS_KEPT)
269
320
  let h
270
321
  try {
271
322
  h = JSON.parse(dec.decode(p))
@@ -281,7 +332,7 @@ class EdgeConn {
281
332
  // an owner that never answers (a page that lost its frame, a machine that ended) must not hold the stub for ever
282
333
  let timer
283
334
  let late = false
284
- const started = Promise.resolve(this.host.start(h, { openExec: () => execStream(this.session) }))
335
+ const started = Promise.resolve(this.host.start(h, { openExec: () => execStream(this.session), openStream: () => this.session.open(), setAccepted: fn => (this.session.accepted = fn) }))
285
336
  started.then(x => late && x && x.runner?.gone?.(), () => {}) // a start that comes after the timeout is let go at once
286
337
  r = await Promise.race([
287
338
  started,
@@ -302,7 +353,11 @@ class EdgeConn {
302
353
  r.runner.onExit = e => {
303
354
  if (this.ended) return
304
355
  this.host.stats.exits++
305
- this.st.write(frame(FRAME_EXIT, e.signal ? { code: e.code, signal: e.signal } : { code: e.code }))
356
+ if (this.trip) {
357
+ this.trip.ex = at()
358
+ this.host.txWait.push([this.trip, 'ew'])
359
+ }
360
+ this.st.write(frame(FRAME_EXIT, e.signal ? { code: e.code, signal: e.signal } : e.clean === true ? { code: e.code, clean: true } : { code: e.code }))
306
361
  this.st.closeWrite()
307
362
  }
308
363
  this.#reply({ ok: true })
@@ -90,7 +90,7 @@ export function normalizeTable(t) {
90
90
  for (const [k, x] of entries) {
91
91
  const url = x.wasmUrl ?? t.wasmUrl
92
92
  const sha256 = (x.wasmSha256 ?? t.wasmSha256).toLowerCase()
93
- if (!modules.has(sha256)) modules.set(sha256, { url, sha256 })
93
+ if (!modules.has(sha256)) modules.set(sha256, { url, sha256, ...(Number.isInteger(x.wasmSize) && x.wasmSize > 0 ? { size: x.wasmSize } : {}), ...(typeof x.wasmPath === 'string' && x.wasmPath ? { path: x.wasmPath } : {}), ...(x.wasmPkg && typeof x.wasmPkg === 'object' ? { pkg: x.wasmPkg } : {}) })
94
94
  tools[k.toLowerCase()] = { ...x, wasmUrl: url, wasmSha256: sha256 }
95
95
  }
96
96
  return { legacy: false, modules: [...modules.values()], preload: modules.size === 1 ? [...modules.keys()] : [], tools }
@@ -160,3 +160,13 @@ export function makeBeat({ post, id, intervalMs = 200, now = () => performance.n
160
160
  stats: () => ({ beats, calls, maxCallGapMs }),
161
161
  }
162
162
  }
163
+
164
+ /**
165
+ * X6 default part 5: the longest a compile waits for the twin's module to be loaded (ms). Past it the compile goes to the guest (a calm answer, not a failure) and
166
+ * the download goes on in the background. 10 s, from counted runs on a fast local link (docs/research/browser-speed-2026-11/x6/default1/part5/part5.md): the
167
+ * 41.1 MB module took 93 to 396 ms to fetch and 19 to 232 ms to compile in the three browsers, so 10 s is more than 15 times the slowest of those and also
168
+ * covers a link of about 4.1 MB/s (33 Mbit/s); a slower link costs a build this wait ONCE (every other compile queued behind it is answered at once, later ones go
169
+ * to the guest without being posted), against a guest-alone build of 245 to 560 s in the same runs, so at most about 4 %. It stays far below the heartbeat
170
+ * limit (the Worker beats while it waits).
171
+ */
172
+ export const TWIN_WAIT_MS = 10_000