@niscorp/moss 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/CHANGELOG.md +492 -0
  2. package/DESIGN.md +265 -49
  3. package/DOCS.md +1527 -344
  4. package/README.md +37 -20
  5. package/dist/app-CUnDcXQu.d.ts +143 -0
  6. package/dist/app-CdANzi2q.d.cts +143 -0
  7. package/dist/chunk-3RIWTXGI.cjs +174 -0
  8. package/dist/chunk-3RIWTXGI.cjs.map +1 -0
  9. package/dist/chunk-4ZGAFZGS.js +152 -0
  10. package/dist/chunk-4ZGAFZGS.js.map +1 -0
  11. package/dist/chunk-6QPTMKRE.cjs +53 -0
  12. package/dist/chunk-6QPTMKRE.cjs.map +1 -0
  13. package/dist/chunk-D3YZIAYV.cjs +137 -0
  14. package/dist/chunk-D3YZIAYV.cjs.map +1 -0
  15. package/dist/chunk-IUJ2TRNB.cjs +57 -0
  16. package/dist/chunk-IUJ2TRNB.cjs.map +1 -0
  17. package/dist/chunk-IW3A2YIC.js +49 -0
  18. package/dist/chunk-IW3A2YIC.js.map +1 -0
  19. package/dist/chunk-NRZ3Z2FF.js +61 -0
  20. package/dist/chunk-NRZ3Z2FF.js.map +1 -0
  21. package/dist/chunk-NSK7QSSG.js +26 -0
  22. package/dist/chunk-NSK7QSSG.js.map +1 -0
  23. package/dist/chunk-PWUO4RET.js +374 -0
  24. package/dist/chunk-PWUO4RET.js.map +1 -0
  25. package/dist/chunk-R2YPQHQH.cjs +383 -0
  26. package/dist/chunk-R2YPQHQH.cjs.map +1 -0
  27. package/dist/chunk-R66WUKGC.cjs +2716 -0
  28. package/dist/chunk-R66WUKGC.cjs.map +1 -0
  29. package/dist/chunk-T5BRTFKP.js +53 -0
  30. package/dist/chunk-T5BRTFKP.js.map +1 -0
  31. package/dist/chunk-TGKDS2T7.cjs +330 -0
  32. package/dist/chunk-TGKDS2T7.cjs.map +1 -0
  33. package/dist/chunk-TLNRFAQ6.js +326 -0
  34. package/dist/chunk-TLNRFAQ6.js.map +1 -0
  35. package/dist/chunk-V5YMJL7Z.js +2704 -0
  36. package/dist/chunk-V5YMJL7Z.js.map +1 -0
  37. package/dist/chunk-VBWNHF4H.cjs +30 -0
  38. package/dist/chunk-VBWNHF4H.cjs.map +1 -0
  39. package/dist/chunk-VKQPOZDJ.cjs +72 -0
  40. package/dist/chunk-VKQPOZDJ.cjs.map +1 -0
  41. package/dist/{chunk-U3UR5AOQ.js → chunk-WKBH3UMB.js} +43 -16
  42. package/dist/chunk-WKBH3UMB.js.map +1 -0
  43. package/dist/client/node.cjs.map +1 -1
  44. package/dist/client/node.d.cts +3 -1
  45. package/dist/client/node.d.ts +3 -1
  46. package/dist/client/node.js.map +1 -1
  47. package/dist/client.cjs +14 -302
  48. package/dist/client.cjs.map +1 -1
  49. package/dist/client.d.cts +9 -33
  50. package/dist/client.d.ts +9 -33
  51. package/dist/client.js +2 -2
  52. package/dist/document-D7nroBww.d.cts +169 -0
  53. package/dist/document-DeTPGBil.d.ts +169 -0
  54. package/dist/env-CY8EGWnD.d.cts +24 -0
  55. package/dist/env-DEPqqHEb.d.ts +24 -0
  56. package/dist/index-B411sK9M.d.cts +130 -0
  57. package/dist/index-B411sK9M.d.ts +130 -0
  58. package/dist/index.cjs +45 -3916
  59. package/dist/index.cjs.map +1 -1
  60. package/dist/index.d.cts +46 -100
  61. package/dist/index.d.ts +46 -100
  62. package/dist/index.js +4 -94
  63. package/dist/index.js.map +1 -1
  64. package/dist/integrations.cjs +975 -0
  65. package/dist/integrations.cjs.map +1 -0
  66. package/dist/integrations.d.cts +63 -0
  67. package/dist/integrations.d.ts +63 -0
  68. package/dist/integrations.js +972 -0
  69. package/dist/integrations.js.map +1 -0
  70. package/dist/messages-CSwCJgH3.d.cts +51 -0
  71. package/dist/messages-CSwCJgH3.d.ts +51 -0
  72. package/dist/node.cjs +17 -3455
  73. package/dist/node.cjs.map +1 -1
  74. package/dist/node.d.cts +13 -10
  75. package/dist/node.d.ts +13 -10
  76. package/dist/node.js +5 -3
  77. package/dist/protocol.cjs +24 -0
  78. package/dist/protocol.cjs.map +1 -0
  79. package/dist/protocol.d.cts +11 -0
  80. package/dist/protocol.d.ts +11 -0
  81. package/dist/protocol.js +3 -0
  82. package/dist/protocol.js.map +1 -0
  83. package/dist/slots-96gNc9uH.d.cts +12 -0
  84. package/dist/slots-BX5N0Juv.d.ts +14 -0
  85. package/dist/slots-CU-AbnJg.d.cts +14 -0
  86. package/dist/slots-sLXDrlbG.d.ts +12 -0
  87. package/dist/socket-D90h1xSV.d.cts +24 -0
  88. package/dist/socket-D90h1xSV.d.ts +24 -0
  89. package/dist/targets-DInbLzff.d.cts +9 -0
  90. package/dist/targets-DInbLzff.d.ts +9 -0
  91. package/dist/terminal/dom/index.cjs +8 -3
  92. package/dist/terminal/dom/index.cjs.map +1 -1
  93. package/dist/terminal/dom/index.d.cts +3 -0
  94. package/dist/terminal/dom/index.d.ts +3 -0
  95. package/dist/terminal/dom/index.js +8 -3
  96. package/dist/terminal/dom/index.js.map +1 -1
  97. package/dist/terminal/dom/server.cjs +2 -7
  98. package/dist/terminal/dom/server.cjs.map +1 -1
  99. package/dist/terminal/dom/server.d.cts +3 -5
  100. package/dist/terminal/dom/server.d.ts +3 -5
  101. package/dist/terminal/dom/server.js +2 -7
  102. package/dist/terminal/dom/server.js.map +1 -1
  103. package/dist/terminal/index.cjs +22 -300
  104. package/dist/terminal/index.cjs.map +1 -1
  105. package/dist/terminal/index.d.cts +7 -2
  106. package/dist/terminal/index.d.ts +7 -2
  107. package/dist/terminal/index.js +21 -22
  108. package/dist/terminal/index.js.map +1 -1
  109. package/dist/terminal/ink/index.d.ts +3 -2
  110. package/dist/terminal/ink/index.js +149 -106
  111. package/dist/terminal/ink/index.js.map +1 -1
  112. package/dist/terminal/react/index.cjs +21 -71
  113. package/dist/terminal/react/index.cjs.map +1 -1
  114. package/dist/terminal/react/index.d.cts +5 -2
  115. package/dist/terminal/react/index.d.ts +5 -2
  116. package/dist/terminal/react/index.js +17 -20
  117. package/dist/terminal/react/index.js.map +1 -1
  118. package/dist/terminal/react/server.cjs +4 -68
  119. package/dist/terminal/react/server.cjs.map +1 -1
  120. package/dist/terminal/react/server.d.cts +9 -6
  121. package/dist/terminal/react/server.d.ts +9 -6
  122. package/dist/terminal/react/server.js +3 -18
  123. package/dist/terminal/react/server.js.map +1 -1
  124. package/dist/terminal/tty/index.cjs +147 -130
  125. package/dist/terminal/tty/index.cjs.map +1 -1
  126. package/dist/terminal/tty/index.d.cts +4 -2
  127. package/dist/terminal/tty/index.d.ts +4 -2
  128. package/dist/terminal/tty/index.js +147 -130
  129. package/dist/terminal/tty/index.js.map +1 -1
  130. package/dist/terminal/vue/index.cjs +20 -72
  131. package/dist/terminal/vue/index.cjs.map +1 -1
  132. package/dist/terminal/vue/index.d.cts +8 -12
  133. package/dist/terminal/vue/index.d.ts +8 -12
  134. package/dist/terminal/vue/index.js +45 -1
  135. package/dist/terminal/vue/index.js.map +1 -1
  136. package/dist/terminal/vue/server.cjs +4 -76
  137. package/dist/terminal/vue/server.cjs.map +1 -1
  138. package/dist/terminal/vue/server.d.cts +7 -6
  139. package/dist/terminal/vue/server.d.ts +7 -6
  140. package/dist/terminal/vue/server.js +3 -10
  141. package/dist/terminal/vue/server.js.map +1 -1
  142. package/dist/tide.cjs +41 -0
  143. package/dist/tide.cjs.map +1 -0
  144. package/dist/tide.d.cts +25 -0
  145. package/dist/tide.d.ts +25 -0
  146. package/dist/tide.js +39 -0
  147. package/dist/tide.js.map +1 -0
  148. package/dist/unverified.cjs +12 -0
  149. package/dist/unverified.cjs.map +1 -0
  150. package/dist/unverified.d.cts +7 -0
  151. package/dist/unverified.d.ts +7 -0
  152. package/dist/unverified.js +10 -0
  153. package/dist/unverified.js.map +1 -0
  154. package/dist/vite.cjs +96 -232
  155. package/dist/vite.cjs.map +1 -1
  156. package/dist/vite.d.cts +6 -8
  157. package/dist/vite.d.ts +6 -8
  158. package/dist/vite.js +97 -71
  159. package/dist/vite.js.map +1 -1
  160. package/package.json +52 -9
  161. package/dist/chunk-4T6KAXBP.js +0 -256
  162. package/dist/chunk-4T6KAXBP.js.map +0 -1
  163. package/dist/chunk-EMRDIZLY.js +0 -99
  164. package/dist/chunk-EMRDIZLY.js.map +0 -1
  165. package/dist/chunk-HOZID4EM.js +0 -366
  166. package/dist/chunk-HOZID4EM.js.map +0 -1
  167. package/dist/chunk-R3QMJ3JF.js +0 -3404
  168. package/dist/chunk-R3QMJ3JF.js.map +0 -1
  169. package/dist/chunk-SK4PDGEE.js +0 -55
  170. package/dist/chunk-SK4PDGEE.js.map +0 -1
  171. package/dist/chunk-U3UR5AOQ.js.map +0 -1
  172. package/dist/document-DhWxieUc.d.cts +0 -1024
  173. package/dist/document-DhWxieUc.d.ts +0 -1024
  174. package/dist/slots-Do9ScG7v.d.cts +0 -37
  175. package/dist/slots-Do9ScG7v.d.ts +0 -37
package/DOCS.md CHANGED
@@ -1,17 +1,36 @@
1
1
  # Moss — API Reference
2
2
 
3
- Fourteen entry points: `@niscorp/moss` (the server), `@niscorp/moss/node` (the
3
+ Eighteen entry points: `@niscorp/moss` (the server), `@niscorp/moss/node` (the
4
4
  Node listener and the built site), `@niscorp/moss/vite` (the dev plugin),
5
+ `@niscorp/moss/integrations` (a feature: services that add screens),
6
+ `@niscorp/moss/tide` (a feature: a write minted into tide as a fact),
7
+ `@niscorp/moss/protocol` (the names of code that speaks the wire itself),
8
+ `@niscorp/moss/unverified` (the whole shell of a session),
5
9
  `@niscorp/moss/client` and `@niscorp/moss/client/node` (the wire and its Node
6
10
  host), `@niscorp/moss/terminal` (the terminal), and the render targets:
7
11
  `terminal/react`, `terminal/vue`, `terminal/dom` (each with a `/server` entry
8
12
  that draws to a string), `terminal/tty` and `terminal/ink`. The version is below 1.0 and
9
13
  the package is live on npm all the same: what is documented here keeps working
10
14
  from one release to the next, and what should go is deprecated, not removed.
11
-
12
- The nisc packages (`charter`, `nova`, `prism`, `strata`, `tide`, `vex`) and
13
- `zod` are required peers. `react`/`react-dom`, `vue`, `ink` and `vite` are
14
- optional peers, needed only by the entry that names them. `hono`,
15
+ 0.5.0 is the one release that did not keep to that, with the maintainer's
16
+ approval: moss was rebuilt as modules and its entries were cut to what an app
17
+ calls. Its entry in `CHANGELOG.md` says what an app changes.
18
+
19
+ **What is exported is a file.** Every name an entry point exports is one line
20
+ of `packages/moss/api.txt` in the repository (it is not in the published
21
+ package): the entry point and the name (`. MossServer`). `pnpm check:api`
22
+ fails when the file and the entry points differ. What the file does not record
23
+ is a member or a signature: a member whose type changes moves no line.
24
+ Each exported name is documented below, under its entry point. Where this
25
+ document names a type, a constant or a file that no entry exports, it says
26
+ so: the name is there so a shape can be read, and an app reaches the shape
27
+ through the exported type that carries it (`NiscRuntime['fabric']`,
28
+ `Awaited<ReturnType<ShellHost['session']>>`).
29
+
30
+ The nisc packages (`charter`, `nova`, `prism`, `strata`, `vex`) and
31
+ `zod` are required peers. `react`/`react-dom`, `vue`, `ink`, `vite` and
32
+ `@niscorp/tide` are optional peers, needed only by the entry that names them
33
+ (tide: `@niscorp/moss/tide`). `hono`,
15
34
  `@hono/node-server` and `ws` are moss's own dependencies.
16
35
 
17
36
  ## `@niscorp/moss`
@@ -20,8 +39,10 @@ optional peers, needed only by the entry that names them. `hono`,
20
39
 
21
40
  #### `defineApp(app: NiscApp): NiscApp`
22
41
 
23
- Identity today, a validation seam tomorrow. The one name an app file needs
24
- besides its artifacts.
42
+ Returns its argument: the one name an app file needs besides its artifacts.
43
+ The manifest is read by a schema, and then frozen, where it is handed over:
44
+ in [`createServer`](#createserverapp-runtime-promisemossserver). Until then an
45
+ app may go on assembling it.
25
46
 
26
47
  #### `NiscApp`
27
48
 
@@ -47,33 +68,28 @@ type NiscApp = {
47
68
  onSession?: (session: FunctionSession) => void;
48
69
  runs?: RunSink;
49
70
  reactions?: readonly { table; op?; run }[]; // see "Reacting to writes"
50
- facts?: { tide; identity; chain? }; // see "Reacting to writes"
51
- // integrations (see "Integrations")
52
- installedIntegrations?: (principal: string | null) => readonly string[] | Promise<readonly string[]>; // deprecated, never called
53
- integrationActor?: (integration: string, actsFor: string) => string | null | Promise<string | null>;
54
- attachable?: Record<string, Record<string, string>>;
55
- menuSlots?: readonly string[];
56
- assistantTools?: readonly string[];
57
- publishChecks?: readonly string[];
58
- editorRegions?: readonly string[];
59
- placementNames?: Readonly<Record<string, string>>;
60
- storePress?: StorePress;
71
+ // what is added to moss that is not its core (see "Features"); `Feature` is not exported
72
+ features?: readonly Feature[];
61
73
  };
62
74
  ```
63
75
 
64
76
  Every field is an artifact (authored data) except the code seams — `scope`,
65
- `identity`, `phrases`, `functions`, `onSession`, `runs`, a reaction's `run`,
66
- `facts`, and the integration hooks. Absent `shell`, the app serves data only
77
+ `identity`, `phrases`, `functions`, `onSession`, `runs`, a reaction's `run`
78
+ — and `features`. Absent `shell`, the app serves data only
67
79
  (no server shells). Absent `functions`, `fn:` endpoints fail loudly.
68
80
 
69
81
  - `assignments` is optional: an app that declares `identity` answers roles per
70
82
  principal and never builds the map. `wearable` declares the role
71
83
  combinations the boot gates check; absent, they are derived from
72
- `assignments` (`wearableOf`).
84
+ `assignments`, one per distinct combination.
73
85
  - `scope(principal, identity?)` — what a principal is beyond its id (a tenant,
74
- an org). Moss always injects `{ userId }`; this contributes the rest, merged
86
+ an org). Moss always injects `{ userId }` (the principal; `'anonymous'` for
87
+ nobody signed in); this contributes the rest, merged
75
88
  server-side and asked per request, so a value derived from the clock is
76
- never held for a session. Synchronous.
89
+ never held for a session. Synchronous. `identity` is the record
90
+ `identity.resolve` answered: absent for nobody signed in, and in an app with
91
+ no `identity` seam. What `scope` answers is merged over that record's
92
+ `scope`, the values that are held for the session.
77
93
  - `identity.resolve(principal, read)` — who a principal is, resolved once per
78
94
  session and cached by moss (bounded by `runtime.identityMax` /
79
95
  `identityIdleMs`, re-resolved every `sessionRevalidateMs`). Returns an
@@ -82,6 +98,10 @@ Every field is an artifact (authored data) except the code seams — `scope`,
82
98
  the policy of the charter role `identity.as` names (it throws when `as` is
83
99
  unset). Moss never reads inside the record's `scope`. Absent, `assignments`
84
100
  and `scope` answer, and every registered integration is live for everybody.
101
+ - `functions(session)` — the handlers behind `fn:` endpoints. Called once for
102
+ each shell that is built: the app's, a page's, and the one a reset builds.
103
+ Like `onSession`, it runs before the shell finishes building, so it must
104
+ not touch `session.shell` synchronously.
85
105
  - `onSession(session)` — called once per living app shell, for session code
86
106
  that is not an endpoint (an observer, a roster). It runs before the shell
87
107
  finishes building, so it must not touch `session.shell` synchronously. Its
@@ -92,6 +112,17 @@ Every field is an artifact (authored data) except the code seams — `scope`,
92
112
  `agentPath`, `label`, `provider`, `model`, the token counts, `reported`,
93
113
  `steps`, `elapsedMs`, `outcome`, and optionally `turns: RunTurn[]` (the whole
94
114
  exchange; a tool call and its result are two turns) and `response`.
115
+ - `at` is when the run was recorded, in epoch milliseconds. `agentPath` is
116
+ the agent's lineage when one agent runs inside another, and `label` is the
117
+ app's own name for the way in that produced the run.
118
+ - `reported` is `false` when any step's tokens were counted and not
119
+ reported by the provider. `outcome` is `'ok'` or `'failed'`.
120
+ - A `RunTurn` is `{ role, content, calls?, name? }`. `calls` is what the
121
+ model asked for on that turn, each `{ name, args }` with `args` the JSON
122
+ text as the provider sent it; `name` is the tool a `'tool'` turn is the
123
+ answer from.
124
+ - `session` is the session that recorded the run, so a sink can write the
125
+ record through `session.wire`, as the caller.
95
126
  - `grammars` — strata sequences for documents only this app defines the shape
96
127
  of (its kit's component props). See "Documents are read in this code's
97
128
  grammars" below.
@@ -99,7 +130,9 @@ Every field is an artifact (authored data) except the code seams — `scope`,
99
130
  A `LayoutVariant` is `{ action: string; layout: LayoutNode }` — ring 2: the
100
131
  charter's `layouts` section selects who is granted which variant id, and moss
101
132
  substitutes the granted variant's layout onto the definition at shell build. The
102
- base is the floor; variants enrich upward as grants.
133
+ base is the floor; variants enrich upward as grants. A role, or a combination
134
+ of roles somebody may wear, that holds two variants of one action refuses the
135
+ boot, and so does a variant of an action the app does not have.
103
136
 
104
137
  #### `ShellManifest`
105
138
 
@@ -122,7 +155,20 @@ session's governed `wire`. `inputs` derives boot **data** (nav flags, user
122
155
  chips), merged over each canvas's static seed. `seeds` derives boot
123
156
  **instances**: by canvas id, the actions to push, in order, ring-1-filtered
124
157
  like every other mount — a seed the principal is not granted does not mount.
125
- A `CanvasSeed` is an action id or `{ action, input?, with? }`.
158
+ A `CanvasSeed` is an action id or `{ action, input?, with? }`, and a
159
+ `ShellCanvas` is nova's canvas config with `initial` widened to one seed or a
160
+ list of candidates. Neither type is exported by name: `ShellManifest['canvases']`
161
+ carries both. Of a list of candidates, the first action the principal holds
162
+ mounts; a canvas none of whose candidates they hold starts empty.
163
+
164
+ `components` is the kit as the server knows it: each component's name, with
165
+ its `meta` (a `description`, and `propsSchema`, the zod schema of its props).
166
+ A name listed there is registered in the shell whether or not a layout of the
167
+ app uses it. The `components` of the app's own `shell` are also the kit a
168
+ bundle's layouts are held to at intake, and the one the integrations'
169
+ contract lists ([`@niscorp/moss/integrations`](#niscorpmossintegrations)): a
170
+ bundle's layout that uses a component not listed there is refused, and where
171
+ a component's `propsSchema` is a zod object, so is a prop it has no place for.
126
172
 
127
173
  #### `PageManifest` — `app.pages`
128
174
 
@@ -154,10 +200,12 @@ go. It is the same machinery with the keeping taken out:
154
200
  A path matches a page when both have the same number of segments and every
155
201
  literal one is equal; nothing else (no wildcards, no order). Two pages that
156
202
  could both answer one path are refused at boot, as is a `params` canvas the page
157
- does not have. Any path no page answers is the app's.
203
+ does not have, and a path that names one parameter twice (`/docs/:id/versions/:id`:
204
+ the parameters are handed over by name). Any path no page answers is the app's.
205
+ A page with no `params` hands its path's parameters to no canvas.
158
206
 
159
207
  Whether a page may be kept by a cache, or written to a file, is not a property
160
- of the page: see [`documentHeaders`](#the-document).
208
+ of the page: see [who may keep a page](#who-may-keep-a-page).
161
209
 
162
210
  #### `phrases` / `phraseKeys` — the words a shell wears
163
211
 
@@ -195,24 +243,83 @@ What the manifest's in-process functions close over:
195
243
 
196
244
  ```typescript
197
245
  type FunctionSession = {
198
- shell: Shell; // the session's living, durable shell (a getter — a reset replaces it)
246
+ shell: Shell; // the session's living, durable shell (a getter — a reset replaces it); nine members throw
199
247
  principal: string | null;
200
248
  roles: readonly string[];
201
249
  identity: Record<string, unknown>; // the scope half of the resolved identity
202
250
  actions: readonly string[]; // the session's granted action ids, installs filtered
203
251
  wire: FetchFn; // the server's own surfaces, as this session
204
- runtime: NiscRuntime;
205
- policy: ScopePolicy; // the caller's compiled scope policy
206
252
  grant: (token: string) => void; // session GRANT (login): send it down, reconnect
207
253
  revoke: () => Promise<void>; // session REVOKE (sign-out): close 4403, evict
254
+ answerIntent: ( // a query written for an intent, as this principal
255
+ writers: { generateDsl: GenerateDsl; mapToShape: MapToShape },
256
+ asked: { intent: string; shape: unknown; context?: Record<string, unknown> },
257
+ ) => Promise<QueryResponse>;
208
258
  recordRun: (run: Omit<RunRecord, 'at' | 'principal' | 'shellId'>) => void;
209
259
  };
210
260
  ```
211
261
 
212
262
  `revoke` settles when the credential is gone: under `session: 'sessions'` it
213
- deletes every session the principal has (`revokeAllFor`). `recordRun` is a
263
+ deletes every session the principal has (`revokeAllFor`). It need not be
264
+ awaited: a failure is logged. `recordRun` is a
214
265
  no-op when the manifest declares no `runs` sink.
215
266
 
267
+ **`shell` refuses the nine members that change what a shell is made of**:
268
+ `registerAction`, `removeAction`, `registerFragment`, `addCanvas`,
269
+ `removeCanvas`, `setCanvasLayout`, `setLayout`, `setPhrases` and `dispose`
270
+ throw. An action, a fragment, a canvas, a layout and the phrases reach a shell
271
+ through moss, which verifies them and decides who holds them; added on the
272
+ shell directly they are not verified, are in nobody's catalog and are gone
273
+ when the shell is rebuilt. Everything else (reads, navigation, `dispatch`,
274
+ `publish`, the observers) works as on nova's `Shell`, which is still the
275
+ type. Code that goes around moss anyway takes the whole shell from
276
+ `@niscorp/moss/unverified`, so the file that does it says so in its imports.
277
+ The shell of what `server.shells.session(…)` answers is the same shell.
278
+
279
+ ```typescript
280
+ import type { FunctionSession } from '@niscorp/moss';
281
+ import { unverifiedShell } from '@niscorp/moss/unverified';
282
+ import type { ActionDefinition } from '@niscorp/nova';
283
+
284
+ const register = (session: FunctionSession, definition: ActionDefinition): void => unverifiedShell(session).registerAction(definition);
285
+ ```
286
+
287
+ **A session says who is calling and holds no key.** It carries no `runtime`
288
+ (the database pool, the operator key) and no `policy` (the
289
+ object the routes enforce for everybody holding those roles). What app code
290
+ needs of either has a call:
291
+
292
+ - **A read or a write as the caller**: `session.wire`, the routes, enforced.
293
+ - **A query written for an intent**: `session.answerIntent(writers, asked)`.
294
+ The routes replay stored queries and write none. An app that lets a model
295
+ write one hands over vex's two writers (`generateDsl`, `mapToShape`), the
296
+ intent and the shape. The query is written, compiled and run under the
297
+ policy and the scope values the routes serve this principal under, resolved
298
+ when it is asked: the writer is shown only the tables they may read, and a
299
+ query that reaches past their policy is refused. It is kept in the cache the
300
+ routes replay from, so `answer.meta.cache.fingerprint` replays over
301
+ `session.wire` afterwards, for whoever the policy lets. Moss keeps one
302
+ engine for each `writers` object: hand over the same object each time. It
303
+ rejects with what vex throws (`code: 'unsatisfiable'`, `'scope_denied'`).
304
+ - **What the caller's roles may read and write**, for code that chooses what
305
+ to offer: `server.policyForRoles(session.roles)`. A copy compiled for the
306
+ asking, the asker's own.
307
+ - **The app's own database**, for machinery no caller's policy describes
308
+ (minting a session for somebody else, a sync, a refresh): the runtime the app
309
+ created and handed to `createServer`, closed over where the app builds its
310
+ manifest. Moss does not hand it back.
311
+
312
+ The run sink, with what a record carries:
313
+
314
+ ```typescript
315
+ import type { RunSink, RunTurn } from '@niscorp/moss';
316
+
317
+ const runs: RunSink = (record) => {
318
+ const turns: readonly RunTurn[] = record.turns ?? [];
319
+ console.log(record.agentId, record.totalTokens, turns.length);
320
+ };
321
+ ```
322
+
216
323
  ### The environment
217
324
 
218
325
  #### `NiscRuntime`
@@ -224,66 +331,196 @@ type NiscRuntime = {
224
331
  cache?: CacheBackend; // defaults to vex's postgres cache on `pool`
225
332
  vexConfig?: QueryEngineConfig['config']; // the query engine's settings (limits, read timeout); default vex's own
226
333
  session: SessionVerifier | 'sessions' | 'dev-open'; // REQUIRED — no default
334
+ origins?: readonly string[]; // origins that are the app's own page, beside the host a request names (a proxy that rewrites `Host`)
227
335
  migrations?: 'apply' | 'verify'; // the boot's ledgered run; default 'apply'
228
336
  tables?: readonly Sequence[]; // the app's own table sequences, in that same run
229
337
  shellIdleMs?: number; // idle shell eviction; default 30 min, `0` disables
230
- endpointTimeoutMs?: number; // a server shell's endpoint call; default nova's, 30s
338
+ anonymousShellMax?: number; // shells for nobody signed in alive at once; default 1,000, `Infinity` is no limit
339
+ endpointTimeoutMs?: number; // a server shell's endpoint call, and the build of a shell; default nova's, 30s
231
340
  sessionRevalidateMs?: number; // live-socket re-verify; default 60s, `0` disables
232
- identityMax?: number; // resident identity records; default 10,000
341
+ identityMax?: number; // resident identity records; default 10,000; 0 or less refuses the boot
233
342
  identityIdleMs?: number; // drop an unread identity record; default 30 min, `0` disables
234
343
  shellFrameDelta?: boolean; // send changed canvases as deltas; default off
235
344
  socketCompression?: boolean | Record<string, unknown>; // permessage-deflate; default on
345
+ socketMaxMessageBytes?: number; // the largest message a connection may send; default 256 KiB
236
346
  operatorKey?: string; // enables `/operator/*`; absent, every route there is 404
237
347
  operatorGate?: (c: Context, next: Next) => Response | void | Promise<Response | void>;
238
348
  fabric?: Fabric; // cross-process invalidations and nudges; default off
239
349
  telemetry?: Telemetry; // one span sink; default off
240
- signingSeed?: string; // dev only: a stable assertion signing keypair
241
350
  };
242
351
  ```
243
352
 
244
- `SessionVerifier` is `(token: string) => string | null | Promise<string | null>`.
353
+ `SessionVerifier` is `(token: string) => string | null | Promise<string | null>`:
354
+ the function form of `session`. The type is not exported by name.
355
+
356
+ `socketCompression` and `socketMaxMessageBytes` are settings of the Node
357
+ transport. The server reads them, once, and the socket it hands out
358
+ (`server.socket`) carries them to whichever transport is handed it. So they
359
+ hold wherever that socket is attached: under `serve`, `nisc start`, the dev
360
+ plugin (`nisc dev`), and a host of the app's own that calls
361
+ `attachSocket(httpServer, server.socket)`. No host says them again.
362
+
363
+ `vexConfig` is handed to the app's query engine. A list of tables given there
364
+ (`entities`) cuts down what that engine knows: the entries the app serves, and
365
+ the `data` universe its charter is resolved over. It says nothing about moss's
366
+ own reads and writes. The generation counter and a feature's own entries (the
367
+ integrations' registry) read the tables that are theirs off the database
368
+ whatever the list names, and know no other table.
245
369
 
246
370
  `session` is required, deliberately — authentication is the one door that must
247
371
  not default open, and it used to. Three answers: `'sessions'` uses moss's own
248
372
  stored credential (below); `'dev-open'` trusts every well-formed token and says
249
373
  so at boot — harnesses and demo floors; a function is the app's own identity
250
374
  provider — return `null` for a token that has expired or been revoked. moss
251
- never learns what expiry means — it only asks again, on both surfaces.
375
+ never learns what expiry means — it only asks again, on both surfaces. A
376
+ function is named at boot too, in one line (`[moss] session: a function the app
377
+ supplied (…) decides who a token is.`): moss cannot tell an identity provider
378
+ from a stub that trusts whatever it is shown, so the choice is in the log.
379
+
380
+ `endpointTimeoutMs` is how long an endpoint call of a server shell waits for
381
+ its reply before it fails to the action's `onError`. An endpoint that names a
382
+ `timeoutMs` of its own waits that long instead. The build of a shell is
383
+ bounded by this number alone.
384
+
385
+ `sessionRevalidateMs` is one clock for three things: a live socket's token is
386
+ asked about again, an identity record older than it is resolved again when it
387
+ is next read, and the generation pointer is polled
388
+ ([Many processes](#many-processes)). `0` turns off all three, and so does
389
+ `Infinity` or any interval above 2^31 − 1 ms (24.8 days), the longest a timer
390
+ of Node's holds: a process then follows no `refresh`, `replaceActions` or
391
+ approval of an integration that another process made.
392
+
393
+ `operatorKey` is what a request under `/operator` presents as
394
+ `x-operator-key`. A request with a wrong key is answered `404`, as every
395
+ request is when the key is unset. `operatorGate` is a gate of the app's own
396
+ over the whole prefix: its own authentication, a rate limit, an audit. It
397
+ runs before the key check. Returning a `Response` refuses the request.
398
+ `await next()` lets it on to the key check and the routes, and `c.res` is
399
+ then what they answered, so an audit records the outcome and not only the
400
+ attempt. A gate adds a lock and removes none: the key check runs on every
401
+ request it lets through. A gate that returns nothing has not refused: the
402
+ request goes on to the key check, whether or not the gate called `next()`.
403
+
404
+ `anonymousShellMax` — how many shells for nobody signed in may be alive at
405
+ once. Somebody signed in has one shell however many terminals they open; nobody
406
+ signed in has one for each connection, and opening a connection takes no
407
+ account and no token. A connection over the limit is sent
408
+ `{ type: 'error', code: 'at_capacity' }` and closed with `4503`; no shell is
409
+ built for it, and its terminal tries again later, as after any other close.
410
+ Somebody signed in is served whatever the count is, and a shell one of the
411
+ manifest's pages builds for somebody signed in takes no place.
412
+
413
+ **What the limit is, exactly.** One count, for everybody with nobody signed
414
+ in, in one process. It bounds what that process holds in memory for them, and
415
+ it does nothing else:
416
+
417
+ - It is not a limit for each visitor. Whoever holds the places holds them:
418
+ one client that opens `anonymousShellMax` connections and keeps them open
419
+ has every place, and every other visitor with nobody signed in is sent
420
+ `at_capacity` until one of those closes. People who are signed in go on
421
+ being served.
422
+ - It is counted by the process that takes the connection. A deployment of N
423
+ processes holds up to N times the limit.
424
+ - Moss builds no limit for each address, because the address is not moss's
425
+ to know: behind a proxy every connection comes from the proxy, and which
426
+ header says where the visitor is, is the proxy's to say.
427
+
428
+ **A deployment that faces the internet** limits how many connections one
429
+ address may hold where the address is known: at its proxy or load balancer,
430
+ on the socket's path (`/socket`). With that in place, `anonymousShellMax` is
431
+ what it is sized for here, memory. What an app can do on its own: a first
432
+ screen for nobody that is a page which is not live opens no socket and takes
433
+ no place (`nisc build` says which pages are live, and why).
434
+
435
+ The default is from a measurement (2026-10-10, Node 24): lyceum's real boot,
436
+ 2,000 connections for nobody opened through `server.socket` and held, the heap
437
+ read after a forced collection before and after, with a transport that drops
438
+ what it is sent.
439
+
440
+ | | for each shell for nobody |
441
+ | --- | --- |
442
+ | heap used, lyceum (its lock screen: 6.7 KB as JSON) | 52.5 KB |
443
+ | resident size, lyceum | about 110 KB |
444
+ | heap used, an app of one canvas and one action | 26.7 KB |
445
+ | the Node transport, compression on (below) | about 260 KB resident more |
446
+
447
+ At 1,000 that is about 53 MB of heap, and about 370 MB resident with the
448
+ transport's compression: the largest round number that still fits a process
449
+ given 512 MB. A deployment with a public screen and more visitors at once than
450
+ that raises it from those numbers and its own memory, and turns compression off
451
+ or down first.
252
452
 
253
- #### `mintSession(pool, principal, ttlMs)` / `sessionOf(pool, token)` / `revokeSession(pool, token)` / `revokeAllFor(pool, principal)`
453
+ #### `mintSession(pool, principal, ttlMs)` / `revokeAllFor(pool, principal)`
254
454
 
255
455
  The stored credential behind `session: 'sessions'` — the integration key's
256
456
  standard, one table over: 256 bits behind an `st_` prefix, the row keeps only
257
457
  the hash, `expires_at` is enforced on every read, and revocation is deleting
258
- the row (one token, or every token a principal holds). The app mints at its
259
- own door after its own identity check and hands the token to the terminal;
260
- its table (`SESSIONS_SEQUENCE`) rides `createServer` boot automatically under
261
- `'sessions'`. Expired rows are swept on every mint — no timer to run.
262
- `sessionVerifierOf(runtime)` resolves the three-way `session` choice to a
263
- `SessionVerifier`, and throws when the field is unset.
458
+ the row.
459
+
460
+ - `mintSession` answers the token, once. The app mints at its own door after
461
+ its own identity check and hands the token to the terminal (or sets it as
462
+ the browser's cookie, [`sessionCookies`](#sessioncookiespage-token-options)).
463
+ Expired rows are swept on every mint — no timer to run.
464
+ - `revokeAllFor` deletes every token a principal holds: signed out everywhere.
465
+ `session.revoke()` in a function calls it for the session's own principal;
466
+ this is for signing out somebody else (an owner removes a member).
467
+ No exported call deletes one token and leaves the principal's others.
468
+ - Who a token is, is asked of the server: `server.principalOf(token)`. The
469
+ table is made by `createServer`, and by `migrateTables`, under
470
+ `session: 'sessions'` and only then. Nothing else is exported of the stored
471
+ credential.
472
+ - **They are for a deployment whose `session` is `'sessions'`, and for no
473
+ other.** The stored sessions are what that verifier reads, and nothing else
474
+ reads them.
475
+ - **An app whose `session` is a verifier of its own keeps its own
476
+ credential.** It mints its tokens, stores what it needs to recognise one,
477
+ and answers `null` for one that expired or was revoked: none of that is
478
+ moss's, and there is no stored session of moss's for it to consult
479
+ (`server.principalOf(token)` asks the app's own verifier, so calling it
480
+ from inside that verifier is the verifier asking itself). `session.revoke()`
481
+ in a function closes that principal's terminals and disposes their shell,
482
+ and forgets nothing: the app deletes its own credential where it signs
483
+ somebody out. An app that wants moss's stored sessions and a rule of its
484
+ own on top (a member who was removed, an account on hold) sets
485
+ `session: 'sessions'` and puts the rule where it belongs: `revokeAllFor`
486
+ when the member is removed, or `identity.resolve` answering
487
+ `{ roles: ['public'], scope: {} }` for somebody who may hold nothing.
488
+
489
+ ```typescript
490
+ // the app's own door: who they are is the app's to establish, then a session
491
+ const token = await mintSession(runtime.pool, 'usr_ada', 30 * 24 * 60 * 60 * 1000);
492
+ // ...and an owner removing a member signs them out everywhere
493
+ await revokeAllFor(runtime.pool, 'usr_ada');
494
+ ```
264
495
 
265
496
  **Tables go through a ledger.** moss creates no table on its own: its tables are
266
- [strata](../strata/README.md) sequences — `MOSS_SEQUENCE` (integrations, their
267
- actions, the generation pointer), `SESSIONS_SEQUENCE`, `TIDE_SEQUENCE` for the
268
- tide store — and `createServer` applies them with the vex cache's sequence in
497
+ [strata](../strata/README.md) sequences — `MOSS_SEQUENCE` (`nisc.moss`:
498
+ integrations, their actions, the generation pointer) and the sessions table's
499
+ (`nisc.moss.sessions`; the sequence itself is not exported) — and
500
+ `createServer` applies them with the vex cache's sequence in
269
501
  one ledgered run before introspection: once, recorded in `strata_ledger`, and
270
502
  refused if the ledger was edited or written by newer code. `migrations` on the
271
503
  runtime picks the posture: `'apply'` (default) runs what is pending; `'verify'`
272
504
  refuses to boot if anything is, for a deployment that migrates as a deploy step.
273
- `initIntegrations` and `initSessions` remain for hosts that are not moss's
274
- server, and go through the same ledger.
505
+
506
+ The run's order is: `MOSS_SEQUENCE`, the sessions table's under
507
+ `session: 'sessions'`, the vex cache's, the tables the app's features keep (in
508
+ the order the app named the features), then `runtime.tables`.
275
509
 
276
510
  `tables` on the runtime hands over the app's own table sequences. They join
277
- that run after moss's — one transaction, one lock, one posture, so `'verify'`
511
+ that run last — one transaction, one lock, one posture, so `'verify'`
278
512
  covers them. Absent, the app migrates its own tables itself, as before. Another
279
- owner's tables the app keeps go in the same list (`TIDE_SEQUENCE`), and a
513
+ owner's tables the app keeps go in the same list (tide's: `TIDE_SEQUENCE`,
514
+ from `@niscorp/tide/postgres`), and a
280
515
  runtime that hands tables over does not also migrate them itself.
281
516
 
282
- #### `migrateTables(runtime, app, { dryRun? }): Promise<TablesReport>`
517
+ #### `migrateTables(runtime, app, { dryRun? })`
283
518
 
284
519
  The step that changes tables, for a deployment that migrates before it starts
285
520
  (`nisc migrate` calls it). It applies everything pending in the one run,
286
- whatever `runtime.migrations` says, and before the run may commit it asks
521
+ whatever `runtime.migrations` says — the tables the app's features keep
522
+ included, read off `app.features` as the server reads them — and before the
523
+ run may commit it asks
287
524
  whether `app`'s entries fit what it leaves: every read is resolved against the
288
525
  schema as the transaction sees it, every write is put to the gate vex puts it
289
526
  to before it runs (`mutationMisfits`: its table, the columns it writes, its
@@ -297,7 +534,7 @@ One kind of entry is said and not refused: one that already did not fit before
297
534
  the run and that the database already holds seeded exactly as it is. That is an
298
535
  old fault, not this run's. A new or changed entry gets no such pass.
299
536
 
300
- `TablesReport` is strata's `{ applied, plan }` plus `removed` (tables and
537
+ What it answers is strata's `{ applied, plan }` plus `removed` (tables and
301
538
  columns the run takes away), `retyped` (columns whose type it changes, as
302
539
  `table.column (was → now)`) and `alreadyBroken`. `dryRun` does all of it and
303
540
  rolls it back.
@@ -306,7 +543,7 @@ It sees entries and nothing else: not SQL written by hand, not a column a scope
306
543
  rule stamps, not what a value means.
307
544
 
308
545
  **Documents are read in this code's grammars.** Stored integration actions
309
- carry a `grammar` stamp (`INTEGRATION_ACTIONS_STORE`). At boot, after the
546
+ carry a `grammar` stamp. At boot, after the
310
547
  tables, moss upgrades every stored action that is behind — through nova's and
311
548
  Prism's grammar sequences plus the app's own (`NiscApp.grammars`: sequences
312
549
  whose document steps are Prism configs, e.g. a kit renaming a component's
@@ -323,12 +560,21 @@ environment settings, not manifest ones — an operational decision about a
323
560
  deployment, never something an application is written against. See
324
561
  [Wire size](#wire-size).
325
562
 
326
- #### `mintDevToken(sub, claims?) : string` / `devSession(token) : string | null`
563
+ ```typescript
564
+ import { migrateTables } from '@niscorp/moss';
565
+
566
+ // what a run would apply, and nothing applied
567
+ const report = await migrateTables(runtime, app, { dryRun: true });
568
+ console.log(report.applied.length, report.removed, report.retyped);
569
+ ```
570
+
571
+ #### `mintDevToken(sub, claims?) : string`
327
572
 
328
- The dev token pair — base64url JSON, `sub` is the principal, no signature and
329
- no expiry. Reachable only through `session: 'dev-open'`, never by default:
330
- anybody who can spell a principal's id can be them, which is a property a
331
- harness wants and a deployment must opt into out loud.
573
+ Mints a dev token — base64url JSON, `sub` is the principal, no signature and
574
+ no expiry. The verifier that trusts one is not exported: it is reachable only
575
+ through `session: 'dev-open'`, never by default. Anybody who can spell a
576
+ principal's id can be them, which is a property a harness wants and a
577
+ deployment must opt into out loud.
332
578
 
333
579
  ### The server
334
580
 
@@ -344,6 +590,67 @@ findings land in the report's `perRole[].issues`, which boot does not read. A
344
590
  role granted an action that pushes one it is not granted boots, and the press
345
591
  does nothing. Returns a Hono app extended with the `MossServer` members below.
346
592
 
593
+ `createServer` wires, and answers no question of its own (`src/server/`). In
594
+ order: the manifest is read and frozen; who a token is is resolved
595
+ (`runtime.session`; unset, the boot is refused here, before a table exists);
596
+ the tables are migrated and the data module stands; the running manifest is
597
+ created, which is the boot check, and the entries it holds are seeded where
598
+ vex replays from; identity; the server's own routes (the
599
+ authentication, `/catalog`, vex); the shell hosts, the app's and each page's;
600
+ what crosses processes; the features, each started with seams made for it; the
601
+ operator prefix; the app's reactions hear a write; the generation pointer is
602
+ watched; the socket.
603
+ A step that refuses is the boot's refusal.
604
+
605
+ **Where the app's entries are held.** In two places while a server runs. The
606
+ running manifest holds the list the app shipped and is their source: the boot
607
+ check reads it, and a shell is told of the reads on its screens from it. That
608
+ list is copied once, at boot, into the cache vex replays from (`vex_cache`,
609
+ or the cache `runtime.cache` hands over). The cache is what runs them: a
610
+ request's fingerprint, and the list of fingerprints a feature or the operator
611
+ is told of, resolve there, and the manifest is not asked. The cache also
612
+ holds what the list does not: a query `session.answerIntent` wrote while the
613
+ app runs, and any row it held before this boot (seeding writes each entry of
614
+ the list and takes none out, so in a database that outlives the process an
615
+ entry the app no longer ships is still there, protected). As in 0.4.0. Which
616
+ of the two decides what a fingerprint resolves to is what the next piece of
617
+ work changes, and nothing here has moved it.
618
+
619
+ **The manifest is read first.** Before a table is created or a row is read,
620
+ `createServer` parses the manifest with a schema, and a manifest that does not
621
+ parse refuses the boot:
622
+
623
+ ```
624
+ The manifest does not parse — refusing to serve:
625
+ actions.home: Unrecognized key: "tittle"
626
+ shell.inputs: expected a function
627
+ ```
628
+
629
+ Each line is a place and what was expected there. An action, a fragment and a
630
+ layout (a layout variant's, a canvas's, the frame's, the layout store's) are
631
+ read by nova's schemas; an entry's `dsl` and `mutation` by vex's and its
632
+ `mapping` by Prism's; `grammars` by strata's. Every other data field is held to
633
+ the shape `NiscApp` gives it, and a field `NiscApp` does not have is refused.
634
+ A code seam is held to being a function. A component's contract
635
+ (`shell.components`) is the kit's own record and may carry more than moss
636
+ names. The charter and `behaviors` are held to being objects; the charter is
637
+ verified by the check below and `behaviors` by vex when a policy is compiled.
638
+
639
+ **Then it is frozen**, every level of it, in place. Once `createServer` has
640
+ returned, an edit to the manifest throws a `TypeError` where it is written:
641
+ `app.actions.x = …`, `delete app.actions.x`, `app.actions = …`,
642
+ `app.charter.role = …`, `app.entries.push(…)`, a write to a definition, a
643
+ layout node, a canvas, a variant. A function, and an instance of a class (a
644
+ zod schema handed over as a component's `propsSchema`), is not frozen and not
645
+ looked inside. An object the app shares between its manifest and its own code
646
+ is frozen for both.
647
+
648
+ What an app consists of changes in one way while a server runs: a set of
649
+ actions is handed over with `server.replaceActions(source, actions)`, which
650
+ verifies before it switches. A charter, a layout variant, an entry, a behavior
651
+ and the shell do not change under a running server; they change in the manifest
652
+ the next server is created with.
653
+
347
654
  What the server answers over HTTP:
348
655
 
349
656
  | Path | What |
@@ -351,29 +658,43 @@ What the server answers over HTTP:
351
658
  | `GET /catalog` | `{ principal, actions, hash }` — the application, resolved for the caller |
352
659
  | `/api/vex` | the vex surface over the full schema: locked (replay-only), scoped per principal |
353
660
  | `/api/<resource>/vex` | the same, over one of `app.resources`' entity subgraphs |
354
- | `/api/integrations/*` | `GET contract` (`?id=`, `?format=md`), `GET verify-key`, `POST frame` (mint a frame grant) |
355
- | `/integrations/:id/*` | the proxy to an approved integration, as the signed-in caller; plus `frame/:token` (and `frame/:token/:call`) and `hook/*`, which take no session |
356
- | `/operator/integrations` | list, register (`POST`), `:id/approve`, `:id/probe`, `DELETE :id` — keyed by `x-operator-key` |
661
+ | `/operator/*` | nothing of the server's own; a feature's operator routes and the app's, behind `x-operator-key` and `runtime.operatorGate` |
662
+
663
+ A feature the app names in `features` adds its own routes to these (see
664
+ [`@niscorp/moss/integrations`](#niscorpmossintegrations) for the ones that
665
+ feature serves).
357
666
 
358
667
  The socket is not a Hono route: `server.socket` is fed by the runtime's
359
668
  transport (`/socket` under `serve` and `attachSocket`). Every request is
360
669
  identified once, from `Authorization: Bearer <token>`: a session token goes
361
- through the `session` verifier (`401` when it does not resolve); a token with
362
- the `ik_` prefix is an integration key, resolved with `x-nisc-acts-for`
363
- through `app.integrationActor` (`401` unknown key, `403` no actor); no header
364
- is the anonymous principal. There is no `/fns` surface.
670
+ through the `session` verifier (`401` when it does not resolve); a token
671
+ whose prefix a feature registered is that feature's to read (the integrations
672
+ read `ik_`, an integration key); no header is the anonymous principal. There
673
+ is no `/fns` surface.
674
+
675
+ A token that is nobody's is a failed sign-in: `401`, `invalid_token`. A
676
+ failure to *find out* who is calling is not: the verifier throwing, the
677
+ identity seam throwing, an identity record that does not parse, a feature's
678
+ credential that cannot be read. That is answered `500`
679
+ `{ error: 'identity_failed', message }` and the error is in the server's log;
680
+ none of its text is sent. A client that drops its session on a `401` does not
681
+ drop it over a fault of the server's. An app whose `identity.resolve` does not
682
+ know a principal answers a record for nobody (`{ roles: ['public'], scope: {} }`)
683
+ and does not throw.
365
684
 
366
685
  #### `MossServer`
367
686
 
368
- `Hono<Env> & { socket: SocketAccept; shells?: ShellHost; principalOf; page; pages;
369
- refresh; charterReport; invalidateIdentity; invalidateTenant; identity; executeAs;
370
- callIntegration; nudge; generation; close; identities? }`.
687
+ `Hono<Env> & { socket; shells?: ShellHost; principalOf; page; pages;
688
+ refresh; replaceActions; actions; catalogOf;
689
+ policyForRoles; charterReport; invalidateIdentity; invalidateTag; identity;
690
+ executeAs; nudge; close; identities? }`.
371
691
  It's a Hono app — mount it, extend it, or hand it to a listener.
372
692
 
373
693
  - `principalOf(token): Promise<string | null>` — the deployment's own session
374
- verifier, the one every surface already asks. For an app's route that receives
375
- a credential some other way than a Bearer header (a page request carries a
376
- cookie). `null` is a refusal.
694
+ verifier, the one every surface already asks. For an app's own code that is
695
+ handed a token some other way than a Bearer header (a link it is redeeming,
696
+ a terminal that is not a page). `null` is a refusal. It is what
697
+ `renderDocument` asks for the session a page request carries.
377
698
  - `pages: readonly { name, path }[]` — every page the manifest declares, with
378
699
  the path it is drawn at: what a build walks to know which paths exist besides
379
700
  the app's own.
@@ -381,14 +702,64 @@ It's a Hono app — mount it, extend it, or hand it to a listener.
381
702
  (its name, the `ShellHost` that draws it, the input its path carries), or
382
703
  `undefined` for a path that is the app's. The document route and the socket
383
704
  ask the same question here.
384
- - `refresh(): void` — artifacts changed at runtime (actions loaded from rows):
385
- re-run the boot gates, drop every per-principal memo and identity record,
386
- and have living shells adopt their re-resolved definitions in place. Throws
387
- on an incoherent charter or variant set, and the old resolution keeps
388
- serving. It also moves the generation pointer, so every other process on the
389
- same database does the same within one poll.
705
+ - `refresh(): void` — something the server derived its answers from changed
706
+ where it cannot see (a role, an install): run the check boot runs over what
707
+ is in force (the charter, every entry's reach, the layout variants), drop
708
+ every per-principal memo and identity record, and have every living shell
709
+ adopt: it is brought level with what its principal holds now, in place
710
+ ("A change is the server's", under `shells` below). Every living shell is
711
+ the one kept for each signed-in person, the one built for each connection
712
+ of nobody signed in, and the one a page built for each connection. It also
713
+ moves the generation
714
+ pointer, and every other process on the same database follows it within
715
+ one poll: it reads again the sets of actions it has a loader for, runs the
716
+ same check, drops what it derived and has its living shells adopt (see
717
+ [Many processes](#many-processes)).
718
+ It ships nothing: the manifest that was handed over cannot be edited, and
719
+ `replaceActions` is how actions arrive.
720
+ - `replaceActions(source, actions): void` — hand over a set of actions that
721
+ arrived while the app runs (an app that loads actions from its own tables).
722
+ `source` names the set: handing the same name over again puts the new set in
723
+ place of the old, so an action it no longer names leaves. The actions in
724
+ force are what the app shipped, then each set. What the app would then
725
+ consist of is verified first: refused, it throws (`Refresh refused — …`,
726
+ with what the check found) and nothing changed; accepted, it does what
727
+ `refresh` does in this process, and the set is frozen as the manifest was,
728
+ so a set is changed by handing over another of the same name.
729
+ **The set is handed to this process, and no other process is handed it.**
730
+ Another process follows the pointer the call moved, as after a `refresh`,
731
+ and goes on serving the set of that name it was last handed itself, or
732
+ none. An app that runs several processes hands the set to each of them
733
+ ([Many processes](#many-processes), "The pointer carries no set"). Every definition of the
734
+ set is read by nova's schema first: one nova does not read refuses the set
735
+ (`Refresh refused — actions nova does not read:`, naming the action and what
736
+ is wrong with it). **A set has one writer.** Each feature the app names
737
+ keeps a set of its own under its own name (`'integrations'` is the
738
+ integrations feature's, read from its tables) and is the only one that
739
+ replaces it: handing a set over under a feature's name throws (`moss: the
740
+ set of actions "integrations" is the feature "integrations"'s, and only its
741
+ owner replaces it. …`).
742
+ - `actions(): Readonly<Record<string, ActionDefinition>>` — the actions in
743
+ force now, by id: what the app shipped, then each set handed over. To read;
744
+ a set changes through `replaceActions`.
745
+ - `catalogOf(principal): Promise<{ ids, hash }>` — what a principal holds of the
746
+ actions in force: `{ ids, hash }`, the granted action ids sorted, with a
747
+ content-hash version token (equal hash, equal application). The principal is
748
+ resolved the way a request resolves it (the `identity` seam, or
749
+ `assignments`), so an integration's actions are there only where it is
750
+ installed. `null` is nobody signed in.
751
+ There is no asking by a list of roles: what somebody holds depends on who
752
+ they are resolved to be, installs included, and the server resolves it.
753
+ - `policyForRoles(roles): ScopePolicy` — what a set of roles may read and
754
+ write: the vex policy a request by somebody holding exactly these roles is
755
+ served under, compiled from the charter and `behaviors` over every table the
756
+ database has. **One policy per role, merged** — a person may wear several (an
757
+ instructor who also trains here), and reach belongs to the role rather than
758
+ to the person; the merge is a union, broadest wins. For a check or a tool
759
+ that reads the rules (`policy.entities['bookings']`): nothing is queried, and
760
+ the answer is compiled for the asking, so it is the caller's own.
390
761
  - `charterReport(): VerifyReport` — the report `verifyCharter` gave this server:
391
- boot's, then that of each `refresh` that passed. `{ errors, warnings,
762
+ boot's, then that of each change that passed. `{ errors, warnings,
392
763
  perRole }`, over the universes boot resolved against. Boot and `refresh` read
393
764
  `errors` alone and print nothing of the rest, so this is where a host reads
394
765
  it, to draw, log or hold a deploy on: `warnings` (an action no role grants, an
@@ -396,34 +767,56 @@ It's a Hono app — mount it, extend it, or hand it to a listener.
396
767
  always empty here. A push whose target is a binding (`@event.payload`,
397
768
  `$.target`) is listed among the `issues` as "not in the catalog", though it is
398
769
  resolved when the step runs; a `{{…}}` target is not listed.
399
- - `generation(): number` — the generation this process last observed (`-1`
400
- before the first read).
401
770
  - `invalidateIdentity(principal): boolean` — forget one principal's identity
402
- record and reset their shell (a role change). `false` = no record was held.
403
- - `invalidateTenant(tag): number` — forget every identity record wearing the
771
+ record and reset every living shell of theirs (a role change): the one the
772
+ app keeps for them, and the one a page built for each connection of theirs.
773
+ `false` = no record was held.
774
+ - `invalidateTag(tag): number` — forget every identity record wearing the
404
775
  tag the app put on it (`IdentityRecord.tag`); answers how many. Forgets, does
405
776
  not reset shells.
406
- - `identity(principal): Promise<IdentityRecord>` — the resolved record for one
407
- principal, through the same cache the request path uses.
408
- - `identities?: { list(): IdentityReport[]; meter() }` — the resident identity
777
+ - `identity(principal): Promise<IdentityRecord>` — who one principal is,
778
+ resolved the way a request resolves it: `{ roles, scope, installed? }`,
779
+ through the same cache the request path uses. `null` is nobody signed in.
780
+ With no `identity` seam the roles are the ones `assignments` names, and
781
+ `scope` is empty.
782
+ - `identities?: { list(); meter() }` — the resident identity
409
783
  roster (`{ principal, since, lastSeen }`) and what the cache costs
410
784
  (`{ size, max, resolved, evicted, expired }`). Present only when the app
411
- declares `identity`.
785
+ declares `identity`. `since` is when a record was resolved and `lastSeen`
786
+ when it was last read, both in epoch milliseconds. `evicted` counts the
787
+ records dropped at `runtime.identityMax` or for sitting unread, and
788
+ `expired` the ones found older than `sessionRevalidateMs` and resolved
789
+ again.
412
790
  - `executeAs(role, fingerprint, context, scope?): Promise<unknown>` — execute a
413
791
  seeded entry as a declared charter role, for surfaces with no principal by
414
792
  nature. In-process only, replay-only, policy compiled from that role, scope
415
- values supplied by server code.
416
- - `callIntegration(id, path, { principal, method?, body?, scope? }):
417
- Promise<Response>` — call an installed integration when nobody is driving;
418
- throws unless it is approved and installed for the principal's tenant.
419
- - `nudge(principal, channel): void` — publish, payload-less, onto one
420
- principal's living shell, in whichever process holds it (local `deliver`,
421
- then the fabric).
793
+ values supplied by server code. Its type is exported as `ExecuteAs`, for
794
+ code that is handed the function and no server. It answers the entry's
795
+ result. An execution vex refuses is logged and answers `undefined`.
796
+ - `nudge(principal, channel): void` — tell one principal's screens that a
797
+ channel changed. It is published, payload-less, onto every living shell of
798
+ theirs: the one the app keeps for them, and the one a page built for each
799
+ connection they have to it; in this process, and over the fabric in every
800
+ other. What is mounted and listening reads again. It answers nothing.
801
+ This is the way for server code to say "something they are looking at
802
+ changed". `shells.deliver` is a different thing (below): a message with a
803
+ payload, into the shell the app's own host keeps, in this process alone.
422
804
  - `close(): void` — stop every timer the server started (the generation poll,
423
805
  the identity sweep, socket revalidation, the shell idle sweeps). For a host
424
806
  that retires a server in-process; every timer is unref'd, so a process that
425
807
  boots once needs none of it.
426
808
 
809
+ `executeAs`, for machinery that has no principal (its type is `ExecuteAs`):
810
+
811
+ ```typescript
812
+ import type { ExecuteAs } from '@niscorp/moss';
813
+
814
+ const dueReminders = (executeAs: ExecuteAs, studioId: string): Promise<unknown> =>
815
+ executeAs('automation', 'reminders/due', {}, { studioId });
816
+
817
+ await dueReminders(server.executeAs, 'st_north');
818
+ ```
819
+
427
820
  ### The document
428
821
 
429
822
  A page request is answered with the screen the socket would have streamed a
@@ -467,7 +860,7 @@ the attached connections' baseline is untouched.
467
860
  - `options.inputs` — input for canvas seeds, by canvas id, merged over the
468
861
  manifest's `inputs`. A page's path parameters arrive here.
469
862
 
470
- #### `live`, and `shellNeedOf(definition, entries): ShellNeed`
863
+ #### `live` — can anything on this screen still happen
471
864
 
472
865
  `live` is asked of the instances actually mounted for this principal. A screen
473
866
  is live when something on it can still happen:
@@ -483,8 +876,13 @@ is live when something on it can still happen:
483
876
  A read made while the action opened is **finished**: its answer is in the tree
484
877
  (and listed in `drawnWith`). The app's own shell is always live for a signed-in
485
878
  principal — it is the thing that is kept. nova supplies the facts
486
- (`livenessOf`, `@niscorp/nova/reflect`); moss composes the verdict, because it
487
- holds the entries behind each fingerprint.
879
+ (`livenessOf`, `@niscorp/nova/reflect`); moss composes the verdict, because
880
+ the running manifest holds the entries the app shipped, by fingerprint
881
+ (`src/shells/snapshot.ts`; the function is not exported, its answer is
882
+ `live`, `why` and `drawnWith` on the snapshot). It reads that list and not
883
+ the cache a replay resolves in, which can hold more: a fingerprint the
884
+ manifest does not carry (a query written by `answerIntent`, a row an earlier
885
+ boot seeded) is the last line of the table.
488
886
 
489
887
  When `live` is false the trees are the whole of the screen, and the terminal
490
888
  opens no socket.
@@ -493,7 +891,7 @@ opens no socket.
493
891
 
494
892
  ```typescript
495
893
  const page = await renderDocument({
496
- server, // the MossServer
894
+ server, // the MossServer, or anything with its `principalOf`, `page` and `shells`
497
895
  template, // the app's index.html, as it would go out undrawn
498
896
  request: { path, cookie }, // what the request named and carried
499
897
  draw: (snapshot) => renderSnapshot({ snapshot, registry, slotWrapper }),
@@ -503,6 +901,8 @@ const page = await renderDocument({
503
901
  // → { html, headers, drawn, principal, page?, head?, live?, why?, drawnWith?, settled? }
504
902
  ```
505
903
 
904
+ What it is handed is `DocumentConfig`, and what it answers is `DrawnDocument`.
905
+
506
906
  - **Which shell**: the page `server.page(path)` names, else the app's.
507
907
  - **For whom**: the principal behind the browser's session cookie for the
508
908
  wire's token key (`tokenKey`, default `nisc.token`), or nobody. The cookie's
@@ -536,7 +936,25 @@ const page = await renderDocument({
536
936
  Without it the template's is left as it is.
537
937
  - **`template`** must hold the empty root (`root`, default
538
938
  `<div id="root"></div>`). The screen goes inside it, the snapshot element
539
- straight after.
939
+ straight after. `root` is an empty element written as it stands in the
940
+ template, its opening tag and at once its closing tag: any element
941
+ (`<main id="app"></main>`), not only a `div`. A template that does not hold
942
+ the root, or a root that is not an empty element (an opening tag alone, one
943
+ that holds something, one closed in its own tag), has no place for a screen:
944
+ the page goes out undrawn (`drawn: false`), and the second case is logged.
945
+ - **`server`** is asked three things, and its type says so
946
+ (`DocumentConfig['server']`): `principalOf(token)`, `page(path)` and
947
+ `shells`, and of each shell host only `snapshot`. A `MossServer` is one.
948
+ With no `shells` (the app declares no shell), a path that is not a page
949
+ goes out undrawn.
950
+ - **`waitMs`** is how long the screen may take to settle before it is drawn
951
+ as it stands: `shells.snapshot`'s `waitMs`, in milliseconds, default 300.
952
+ - **What it answers.** `drawn` says whether the screen is in the page.
953
+ `principal` is who it was drawn for, and `page` the name of the page the
954
+ path led to (absent: the app's own). `live`, `why`, `drawnWith` and
955
+ `settled` are the snapshot's, and are there when the page is drawn. An
956
+ undrawn page answers `principal: null` and the headers of a page for
957
+ nobody, whoever asked.
540
958
  - **Nothing here can fail a page.** A kit component that throws, a shell that
541
959
  will not build: the answer is the template as it is (`drawn: false`), and the
542
960
  terminal paints it the way it did before any of this existed.
@@ -546,7 +964,10 @@ The route is the app's own — in production `mountSite` from `@niscorp/moss/nod
546
964
  `index.html` through `transformIndexHtml` first so the drawn page still carries
547
965
  vite's client.
548
966
 
549
- #### `documentHeaders(principal)` — who may keep a page
967
+ #### Who may keep a page
968
+
969
+ `renderDocument` answers the headers its page goes out with (`page.headers`),
970
+ and they follow from who it was drawn for:
550
971
 
551
972
  | Drawn for | `Cache-Control` | `Vary` |
552
973
  |---|---|---|
@@ -562,7 +983,10 @@ somebody is theirs. No page declares which it is.
562
983
  The same draw, for nobody, once per path in `config.paths` — what a static host
563
984
  serves. There is no credential to pass and no way to pass one: a file is the
564
985
  page as nobody in particular sees it, which is the only page that may be kept.
565
- Each result carries `{ path, html, page?, drawn, live, why, drawnWith, settled }`.
986
+ `config` is `DocumentConfig` without its `request`, and `paths`. Each result
987
+ (`ExportedDocument`) carries `{ path, html, page?, head?, drawn, live, why, drawnWith, settled }`.
988
+ A path that could not be drawn is not taken to be finished: it is reported
989
+ `drawn: false`, `live: true`, with `why` saying that it could not be drawn.
566
990
  A page that is `live` is still written, and says why — its file is a true first
567
991
  screen and its terminal will look for a socket. Whether that is acceptable (a
568
992
  server stands beside the files) or a mistake (there is none) is the build's to
@@ -570,13 +994,24 @@ decide, from the report. Writing the files, and listing a parameterised page's
570
994
  paths (`server.executeAs` runs a seeded read as a charter role), are the
571
995
  caller's.
572
996
 
573
- #### `embedSnapshot(snapshot, principal, path?)`, `tokenFromCookie(header, tokenKey?)`
574
-
575
- The two halves `renderDocument` is made of, for a host that assembles its own
576
- page. `embedSnapshot` writes the snapshot as a
997
+ `renderDocument` is the one way a page is drawn, and its parts are not
998
+ exported. It reads the session the browser holds off the request's cookie, and
999
+ it writes the snapshot into the page as a
577
1000
  `<script type="application/json" id="nisc-snapshot">` element with every `<`
578
- (and U+2028/2029) escaped: a tree carries what people typed, and nothing in it
579
- can close the element or open another.
1001
+ (and U+2028/2029) escaped: a tree carries what people typed, and a path is
1002
+ whatever was asked for, and nothing in either can close the element or open
1003
+ another.
1004
+
1005
+ One page drawn for whoever asks, and the same pages written out for nobody:
1006
+
1007
+ ```typescript
1008
+ import { exportDocuments, renderDocument } from '@niscorp/moss';
1009
+ import type { DocumentConfig, DrawnDocument, ExportedDocument } from '@niscorp/moss';
1010
+
1011
+ const drawing: Pick<DocumentConfig, 'server' | 'template' | 'draw' | 'site'> = { server, template, draw, site: 'https://app.example' };
1012
+ const page: DrawnDocument = await renderDocument({ ...drawing, request: { path: '/docs/intro', cookie, host: 'app.example' } });
1013
+ const files: ExportedDocument[] = await exportDocuments({ ...drawing, paths: ['/', '/docs/intro'] });
1014
+ ```
580
1015
 
581
1016
  #### `sessionCookies(page, token, options?)`
582
1017
 
@@ -600,16 +1035,18 @@ server.get('/login', async (c) => {
600
1035
  browser closes. A sign-in made over the socket (`session.grant`) needs none of
601
1036
  this: the answer to the terminal's next upgrade writes the same cookie.
602
1037
 
603
- #### `createPageRouter(pages): PageRouter`
604
-
605
- `{ match(path): { name, params } | undefined }` — the matching rule above, for a
606
- tool that needs it without a server.
607
-
608
1038
  ### Reacting to writes
609
1039
 
610
1040
  Vex is the choke point every application write passes through, so its write
611
- observer is where a host learns about all of them. Moss subscribes once and
612
- splits the news down two lanes with deliberately different privileges.
1041
+ observer is where a host learns about all of them. Moss hears it once and
1042
+ offers each write down two lanes with deliberately different privileges: the
1043
+ app's reactions, which are part of the manifest and are handed no row, and a
1044
+ feature that hears writes, which is handed them. The one feature that does is
1045
+ the tide lane, `createTideFacts`. Features
1046
+ are told first, in the order the app named them, then the reactions, and each
1047
+ on its own: a listener that throws (an app's `identity`, say) is logged, and
1048
+ the others still hear of that write. The write was committed before any is
1049
+ told.
613
1050
 
614
1051
  #### `app.reactions` — the app's lane, row-less
615
1052
 
@@ -625,7 +1062,10 @@ Interest is **declared**, not discovered: moss routes each committed statement
625
1062
  to the reactions whose `table` (and optional `op`) match, so app code never
626
1063
  hears about writes it did not ask for and never string-matches a fingerprint
627
1064
  to work out what happened. `deliver(principal, channel, payload?)` publishes
628
- onto a principal's live durable shell over the socket the shells already run.
1065
+ onto every living shell of a principal in this process, the one the app keeps
1066
+ and each one a page built for them, with the payload; every other process is
1067
+ nudged on the same channel, without it. `false`: no shell of theirs lives
1068
+ here.
629
1069
 
630
1070
  Two rules hold this lane honest:
631
1071
 
@@ -641,16 +1081,26 @@ A reaction naming a table nothing writes is not an error anywhere — it simply
641
1081
  never fires. Derive the names from `mutationEffect` over your own entries and
642
1082
  assert them in a check.
643
1083
 
644
- #### `app.facts` — the tide lane, rows and all
1084
+ #### `createTideFacts` — the tide lane, rows and all
645
1085
 
646
1086
  ```ts
647
- facts: {
648
- tide: () => driver, // the waking intake
649
- identity: (scope) => `automation@${scope['studioId']}`,
650
- chain: (scope, hints) => (isRobot(scope) ? hints : undefined),
651
- }
1087
+ import { createTideFacts } from '@niscorp/moss/tide';
1088
+
1089
+ features: [
1090
+ createTideFacts({
1091
+ tide: () => driver, // the waking intake
1092
+ identity: (scope) => `automation@${scope['studioId']}`,
1093
+ chain: (scope, hints) => (isRobot(scope) ? hints : undefined),
1094
+ }),
1095
+ ]
652
1096
  ```
653
1097
 
1098
+ A feature, from an entry point of its own (`@niscorp/moss/tide`), and not a
1099
+ field of the manifest: an app that runs no tide names none, and moss's core
1100
+ imports nothing of tide. `@niscorp/tide` is an optional peer, installed by an
1101
+ app that names this feature. A manifest that still carries `facts`, where
1102
+ these three functions used to be, is refused at boot.
1103
+
654
1104
  Each committed row becomes one `{ kind: 'write', entity, op, row }` fact.
655
1105
  Rows travel here because tide has the fence that makes it safe: `identity`
656
1106
  stamps each fact from the **write's own scope**, and tide offers a fact only
@@ -659,190 +1109,415 @@ who may be woken by it. Returning `undefined` mints nothing (an operator
659
1109
  surface, a write with no tenant).
660
1110
 
661
1111
  `chain` is the causality gate. A tide effect writing back through vex names
662
- its chain position in `x-tide-cause` / `x-tide-depth`; this decides whether
1112
+ its chain position in `x-tide-cause` / `x-tide-depth`. The two headers are
1113
+ this feature's: the core's routes read no header by name, and hand whoever
1114
+ hears a write what its request said. `chain` decides whether
663
1115
  that caller's word is good, so the chain-depth ceiling survives the trip
664
1116
  through the database. Absent = hints are always dropped, which is the safe
665
- default: a forged depth could park an innocent chain.
666
-
667
- #### `createTideDriver({ tide, janitorMs?, retention? }) : TideDriver`
668
-
669
- Tide reads no clocks and paces nothing; this is the thing that does.
670
-
671
- - **Wake** — `ingest` and `fire` advance the engine immediately, to
672
- quiescence: a chain advances one committed hop per step, so the driver
673
- loops until a step reports nothing moved. `wake()` returns the promise of
674
- that drain, so a "run it now" button can await a settled world.
675
- - **Sleep** — after quiescence, `tide.nextDue(now)` names the next instant
676
- worth waking for and one timer sleeps until exactly then, preempted by any
677
- ingest. No beat, no polling for work.
678
- - **Janitor** — a slow fallback wake plus the retention sweep. It finds
679
- nothing when nothing is broken; it exists because a durable multi-worker
680
- design needs the scan that notices work committed by a process that died
681
- before its own wake ran. It is how work is *recovered*, never how it moves.
682
-
683
- Hand `app.facts.tide` the **driver**, not bare tide, so a minted fact wakes
684
- the engine instead of waiting for somebody's beat. The driver is `{ ingest,
685
- fire, wake, stop }`; `stop()` resolves once nothing it started still touches
686
- the store. `config.now` replaces the clock; `janitorMs` defaults to 5 minutes;
687
- absent `retention`, nothing is swept.
688
-
689
- #### `createTideStore(pool, options?)` / `TIDE_SEQUENCE`
690
-
691
- The Postgres store tide runs on, as a strata sequence (`TIDE_SEQUENCE`, tables
692
- `TIDE_TABLES`). Returns a tide `TideStore` plus `ready: Promise<void>`.
693
- `mintWrites` is the bridge the fact lane uses.
694
-
695
- ### Integrations
696
-
697
- A separate service registered with the deployment, whose actions join the
698
- manifest once an operator approves them. The HTTP surfaces are listed under
699
- [`createServer`](#createserverapp-runtime-promisemossserver); the operator seam
700
- exists only when `runtime.operatorKey` is set.
701
-
702
- - Manifest hooks: `installedIntegrations(principal)` (deprecated and never called — the
703
- install list moss filters by is `IdentityRecord.installed`; absent = all), `integrationActor(integration,
704
- actsFor)` (the principal a keyed call acts as; `null` refuses), `attachable`
705
- and `menuSlots` (where an integration's actions may appear), `assistantTools`,
706
- `publishChecks`, `editorRegions` (the names a bundle's declarations may use),
707
- `placementNames`, `storePress` (where a bundle's listing images land).
708
- - `runIntake(payload, ctx): IntakeResult` — validate a bundle:
709
- `{ ok: true, bundle } | { ok: false, reasons }`.
710
- - `initIntegrations(pool)`, `MOSS_SEQUENCE`, `listIntegrations(pool)`,
711
- `loadIntegrationActions(pool, upgrader?)`, `integrationByKey(pool, key)`,
712
- `listAttachments(pool, hostAction)`, `listPlacements(pool)` — the stored rows.
713
- - `integrationOfAction(id)`, `filterInstalled(ids, installed)` — which
714
- integration an action id belongs to, and the catalog filter.
715
- - `buildContract(app, integrationId)`, `contractAsMarkdown(contract,
716
- fingerprints)` — what `/api/integrations/contract` serves.
717
- `describePlacements(bundle, names?)` — the placement sentence stored with an
718
- integration's row at registration.
719
- - `copyPress`, `callIntegrationWith` — the press copy at intake and the
720
- machinery behind `server.callIntegration`.
721
- - `createAssertionSigner(seed?)`, `verifyAssertion(token, verifyKey, now?)` —
722
- the ed25519 assertion the proxy signs and an integration verifies.
723
- `mintIntegrationKey()` (`ik_…`) and `hashIntegrationKey(key)` — the
724
- integration's own credential, stored hashed.
1117
+ default: a forged depth could park an innocent chain. A position is a cause
1118
+ that is not empty and a depth written as `String(depth)` writes a whole number
1119
+ that is not negative: digits and nothing else. Anything else (an empty depth,
1120
+ `0x2`, `1e1`, `+2`, a number too large to be exact) is no position, and `chain`
1121
+ is not asked.
1122
+
1123
+ Hand `tide` the **driver** (`createTideDriver`, from `@niscorp/tide`), not
1124
+ bare tide, so a minted fact wakes the engine instead of waiting for somebody's
1125
+ beat. It is a getter because the driver stands up after the server does: while
1126
+ it answers `undefined`, nothing is minted.
1127
+
1128
+ #### The driver and the store are tide's
1129
+
1130
+ `createTideDriver` and the type `TideDriver` are exported by `@niscorp/tide`.
1131
+ `createTideStore(pool, options?)`, `TIDE_SEQUENCE`, `TIDE_TABLES` and
1132
+ `TIDE_DDL` are exported by `@niscorp/tide/postgres`. They were moss's, and do
1133
+ what they did: see tide's [DOCS.md](../tide/DOCS.md), "The driver" and "The
1134
+ Postgres store". `createTideStore(runtime.pool)` takes the pool the runtime
1135
+ holds, and its tables are ordinary tables to moss: introspected, grantable,
1136
+ and scoped by a behavior like any other.
1137
+
1138
+ ### Features
1139
+
1140
+ A feature is something moss adds to its core and keeps apart from it: it owns
1141
+ none of what the core answers (who is calling, what exists for them, what they
1142
+ may read and write, what they are looking at, how it reaches them). It ships
1143
+ from an entry point of its own, and the core never imports it. There are two,
1144
+ [`@niscorp/moss/integrations`](#niscorpmossintegrations) and
1145
+ [`@niscorp/moss/tide`](#niscorpmosstide), and they are moss's own: an app
1146
+ cannot write one, and `Feature` and `FeatureSeams`, the types moss and its
1147
+ features meet at, are not exported. An app creates the ones it wants and names
1148
+ them in `features: [createIntegrations(...), createTideFacts(...)]`.
1149
+
1150
+ `createServer` starts each one, in order, once its core stands and before
1151
+ anything is served; one that throws refuses the boot. No two features of an
1152
+ app share a name. What a feature routes, keeps and serves is documented under
1153
+ its entry point.
1154
+
1155
+ A feature names the tables that are its own and the strata sequences that make
1156
+ them. The sequences are migrated in the one ledgered run, before the feature
1157
+ starts, and `migrateTables` runs them too. A feature reads and writes those
1158
+ tables through vex, as an app does, with entries of its own: they are seeded into a
1159
+ cache of their own, held by an engine no route is handed, so `/api/vex`
1160
+ answers `cache_miss` for one of them whatever the charter grants whoever asks,
1161
+ and no surface lists it. They run under a policy that admits the tables the
1162
+ feature named as its own and no other, and asks for no principal. An entry
1163
+ that reads or writes any other table refuses the boot (`moss: the feature "…"
1164
+ handed over an entry that reads or writes a table that is not its own: "…"`).
1165
+ What another table holds, a feature reads as the app does: through the app's
1166
+ entries, under the charter. A write by a feature tells the app's engine which
1167
+ tables changed, so a reactive read over one of them answers again.
725
1168
 
726
1169
  ### Many processes
727
1170
 
728
- - `runtime.fabric: Fabric` — `{ publish(message), subscribe(apply) }`, the
729
- host's transport (Postgres `LISTEN/NOTIFY` is the expected one). It carries
1171
+ - `runtime.fabric` — `{ publish(message), subscribe(apply) }`, the
1172
+ host's transport (Postgres `LISTEN/NOTIFY` is the expected one; the type is
1173
+ `NiscRuntime['fabric']`, and is not exported by a name of its own). A
1174
+ message is one of the three signals below with `origin`, the process that
1175
+ sent it, which moss stamps and checks. It carries
730
1176
  three signals to the other processes: `invalidate-identity`,
731
- `invalidate-tenant` and `nudge` — what `server.invalidateIdentity`,
732
- `invalidateTenant` and `nudge` publish after applying locally. Best-effort:
1177
+ `invalidate-tag` and `nudge` — what `server.invalidateIdentity`,
1178
+ `invalidateTag` and `nudge` publish after applying locally. Best-effort:
733
1179
  each targets state that heals on its own clock. Unset, every path behaves as
734
- in one process. `wireFabric(fabric, origin, apply)` is the wiring, exported
735
- for hosts that are not moss's server.
736
- - `createGeneration(pool, { onMoved, everyMs? }): Generation` — the persistent
737
- pointer `server.refresh()` moves (`moss_generation`, part of
738
- `MOSS_SEQUENCE`). Each process polls it (`DEFAULT_GENERATION_POLL_MS`, 60s;
739
- the server polls on `sessionRevalidateMs`) and drops its derivations when it
740
- moves.
741
- - `createIdentityCache(ctx): IdentityCache` — the cache behind `app.identity`:
742
- `{ get, invalidate, invalidateAll, invalidateTag, list, meter, stop }`.
743
- Defaults `DEFAULT_IDENTITY_MAX` and `DEFAULT_IDENTITY_IDLE_MS`.
1180
+ in one process. The wiring is `src/server/signals.ts`; it is the server's
1181
+ own and is not exported.
1182
+ `subscribe` is called once, while the server boots, with the function the
1183
+ transport hands each message it receives to. `publish` is never awaited,
1184
+ and a throw from it is caught and logged: a transport that is slow or down
1185
+ costs nothing to the call that published. A transport may hand a process
1186
+ its own messages back (`LISTEN/NOTIFY` does): moss drops them by `origin`.
1187
+ **What the transport hands to `apply` is read by a schema** before anything
1188
+ of it is used: the object moss published, with exactly its fields. `apply`
1189
+ takes whatever the transport read off its wire (`unknown`), so a transport
1190
+ hands over what `JSON.parse` answered and casts nothing. What does not parse
1191
+ (text that was not parsed, a field of the wrong type, a field no message
1192
+ has, a `kind` this process does not know) is dropped, and the first one is
1193
+ logged with what was wrong with it and nothing it carried
1194
+ (`[moss:fabric] the transport handed over what is not a message…`); the ones
1195
+ after it are dropped without a line.
1196
+ - The generation pointer — the persistent counter `server.refresh()` and
1197
+ `server.replaceActions()` move (`moss_generation`, one row, part of
1198
+ `MOSS_SEQUENCE`). Each process polls it (on `sessionRevalidateMs`; 60s when
1199
+ that is unset), and when it has moved it reads again every set of actions
1200
+ it has a loader for, runs the check boot runs over what it would then
1201
+ serve, drops what it derived (what each set of roles holds, the compiled
1202
+ policies, the identity records) and has its living shells adopt.
1203
+ **The pointer carries no set.** It says that something changed, and a
1204
+ process learns what by reading rows. The only set that has a loader is the
1205
+ integrations feature's (`'integrations'`). A set handed to
1206
+ `server.replaceActions` in one process is in that process's memory: every
1207
+ other process reaches the same generation and goes on serving the set of
1208
+ that name it was last handed itself, or none. So an app that runs several
1209
+ processes hands the set to each of them with `server.replaceActions`, on a
1210
+ signal of its own. Each call moves the pointer once more, and the others drop
1211
+ what they derived and adopt again.
1212
+ The row is read and moved through vex, by two
1213
+ entries of moss's own that no route serves (`src/data/own-entries.ts`);
1214
+ `src/manifest/generation.ts` holds the clock and no SQL. A move is a compare
1215
+ and a set: the next number is written where the counter is still what was
1216
+ read, and read again where it is not. A move a process could not follow is
1217
+ tried again at every poll until it is followed, and logged when that is
1218
+ news: when it first fails (`[moss:generation] the generation pointer moved
1219
+ (3 → 4) and this process could not follow it: …`), again when the pointer
1220
+ has moved on or the reload fails another way, and once when it is followed
1221
+ (`followed the generation pointer to 4, after 12 looks that failed`). A
1222
+ reload that fails the same way for an hour is one line, not sixty.
1223
+ - The identity cache — what holds the records `app.identity` resolves. It is
1224
+ the server's own (`src/identity/cache.ts`) and is not exported. Its limits
1225
+ are `runtime.identityMax` (default 10,000) and `runtime.identityIdleMs`
1226
+ (default 30 minutes). At `identityMax` the least recently read record is
1227
+ dropped to make room, and whoever it was is resolved again on their next
1228
+ request. A record is forgotten with `server.invalidateIdentity`,
1229
+ `invalidateTag` and `refresh`, and what is held is read through
1230
+ `server.identities`.
744
1231
 
745
1232
  ### Telemetry
746
1233
 
747
- `runtime.telemetry: { emit(span) }` — one sink, off by default. A
748
- `TelemetrySpan` is `{ name, startUnixNano, endUnixNano, status: 'ok' | 'error' |
749
- 'refused', attributes, traceId?, spanId?, parentSpanId? }`. Moss emits one per
750
- vex execution, fn call, integration call, shell build, and socket upgrade and
751
- close. `emitterOf(telemetry)` wraps a sink so a throwing one costs the caller
752
- nothing (`undefined` when there is none); `spanClock()` stamps a start and
753
- measures the end.
1234
+ `runtime.telemetry` is a `Telemetry`, `{ emit(span) }` — one sink, off by
1235
+ default. A `TelemetrySpan` is `{ name, startUnixNano, endUnixNano, status: 'ok'
1236
+ | 'error' | 'refused', attributes, traceId?, spanId?, parentSpanId? }`. Moss
1237
+ emits one per vex execution, fn call, integration call, shell build, and socket
1238
+ upgrade and close: `name` is `vex.execute`, `fn.call`, `integration.call`,
1239
+ `shell.build`, `socket.upgrade` or `socket.close`.
1240
+ A vex execution is a request's replay, one `executeAs`
1241
+ makes, and one a feature makes of its own entries: the integrations'
1242
+ registry reads and writes are `vex.execute` spans whose `fingerprint` starts
1243
+ with `integrations/` and whose `hasPrincipal` is `false`. The generation
1244
+ counter's poll emits none. A `socket.upgrade` is `ok` (admitted), `refused` (the token
1245
+ offered is nobody's, or no place is left for a shell for nobody) or
1246
+ `error` (the session could not be opened: the verifier
1247
+ threw, what somebody holds could not be asked, their shell could not be built).
1248
+ A `socket.close` span runs from the upgrade to the close.
1249
+ `emit` is never awaited, and a sink that throws costs the caller nothing: the
1250
+ throw is caught where the span is emitted, and logged.
1251
+
1252
+ `refused` is a no the server gave (a policy, a limit, an integration that is
1253
+ not installed): an outcome, and not a fault. `attributes` holds identifiers
1254
+ and measurements (a fingerprint, a count, a status) and never a payload, a
1255
+ row or who a principal is: a principal is there only as `hasPrincipal`. Moss
1256
+ sets none of `traceId`, `spanId` and `parentSpanId`.
1257
+
1258
+ ```typescript
1259
+ import type { Telemetry, TelemetrySpan } from '@niscorp/moss';
1260
+
1261
+ const spans: TelemetrySpan[] = [];
1262
+ const telemetry: Telemetry = { emit: (span) => void spans.push(span) };
1263
+ // ...and `telemetry` on the runtime handed to createServer
1264
+ ```
1265
+
1266
+ ### Resolution
754
1267
 
755
- ### Resolution (exposed for tools)
1268
+ Who somebody is, what they hold and what they may read and write are asked of
1269
+ the server, which resolves a principal the way a request does (the `identity`
1270
+ seam, or `assignments`): `(await server.identity(principal)).roles`,
1271
+ `server.catalogOf(principal)`, `server.policyForRoles(roles)`. Nothing is
1272
+ exported that answers them from a manifest alone: three functions did, read
1273
+ `assignments` and nothing else, and so answered `public` for everybody in an
1274
+ app that resolves people through `identity`.
756
1275
 
757
- - `resolveRoles(app, principal): readonly string[]` — assignment rows; anonymous/
758
- unassigned wears `['public']`. The name is fixed, and the charter has to
1276
+ - Nobody signed in, and a signed-in principal with no role, wears
1277
+ `['public']`. The name is fixed, and the charter has to
759
1278
  define it (`public: []` grants nothing). Where it does not, the server still
760
1279
  boots and nothing is said; then every request with no session, and every
761
1280
  signed-in principal with no assignment, fails with `Unknown role "public"` —
762
1281
  a 500, a socket closed `4500`, a page served undrawn.
763
- - `resolvePolicy(app, grants, principal): ScopePolicy` — the compiled vex policy
764
- this principal reads and writes under. **One policy per role, merged** — a
1282
+ - A policy is compiled **one per role, merged** — a
765
1283
  person may wear several (an instructor who also trains here), and reach belongs
766
1284
  to the role rather than to the person. The merge is a union: broadest wins.
767
- - `resolvePolicyAtReach(app, grants, principal, reach): ScopePolicy` — the same
768
- principal's grants recompiled under a named profile, for entries that declare
769
- a `reach` (vex). Wired into the vex surfaces automatically; narrows rows,
770
- never widens verbs.
771
- - `resolveCatalog(app, principal): Catalog` — `{ ids, hash }`, granted action ids
772
- sorted, with a content-hash version token (equal hash, equal application).
773
- - `resolveVariants(app, principal): ReadonlyMap<string, LayoutNode>` — action id →
774
- the granted variant's layout (ring 2; empty map = every action serves its base).
775
- - `resolveCatalogForRoles(app, roles, installed)`, `resolveVariantsForRoles(app,
776
- roles)`, `resolvePolicyForRoles(app, grants, roles)` — the same resolutions,
777
- given roles rather than a principal, for a caller that already resolved who
778
- somebody is (the `identity` seam). `resolveRoles`, `resolveCatalog` and the
779
- other principal-taking forms read `assignments` only.
780
- - `wearableOf(app): readonly (readonly string[])[]` — the role combinations the
781
- app can produce: `app.wearable`, else derived from `assignments`, deduplicated.
782
- - `memoKeyOf(app, principal): string` — the key the per-principal memos depend
783
- on (roles + installed set), from `assignments` with no install list.
784
- - `verifyVariants(app): string[]` — the ring-2 boot gate: every variant reshapes a
785
- shipped action, and no wearable role combination is granted two variants of
786
- one action. Non-empty = refuse to boot.
787
- - `createDataLayer(runtime, entries?): Promise<DataLayer>` — `{ engine, schema,
788
- grants }`, stood up from what's present.
789
- - `createShellHost(ctx): ShellHost` — the durable per-principal shell host.
790
- `ctx.idleMs` bounds how long a shell may sit unattached (default
791
- `DEFAULT_IDLE_MS`, 30 minutes; `0` disables the sweep).
792
- - `ShellHost` — `{ session, snapshot, adopt, deliver, list, reset, stop }`.
793
- - `session(token, principal, options?)` — `options = { seed?, inputs? }`
794
- (`ShellOpening`); `snapshot` is described under [The document](#the-document).
795
- - `adopt()` — every living durable shell re-registers its freshly resolved
796
- granted definitions in place (what `server.refresh()` calls).
797
- - `deliver(principal, channel, payload?): boolean` — publish into one
798
- principal's living durable shell. `false` = they have no living shell;
799
- nothing is built.
800
- - `list(): ShellReport[]` — every durable shell alive right now:
1285
+ - An entry that declares a `reach` (vex) is served under the same roles'
1286
+ grants recompiled at that named profile. The vex surfaces and `executeAs` do
1287
+ it themselves; it narrows rows, never widens verbs.
1288
+ - A layout variant a set of roles holds (ring 2) is put in place of its
1289
+ action's layout where a shell is built. Nothing answers the variants by
1290
+ themselves.
1291
+ - `verifyApp(app, grants)` — the check boot runs, for an app
1292
+ that is not booted (a check, a build step): the charter with each role's
1293
+ closure audited, every entry's reach, the layout variants. It reads `charter`,
1294
+ `actions`, `layouts`, `wearable`, `assignments`, `entries` and `behaviors`
1295
+ of what it is handed, so a check may hand it those alone. `grants` is every
1296
+ `<table>.<verb>` the database can carry (vex's `scopeGrants(tables)`). The
1297
+ report is `{ errors, said, charter }`: `errors` is `{ check, detail }[]`,
1298
+ `check` one of `'actions'` (a definition nova's schema does not read),
1299
+ `'charter'`, `'reach'` and `'variants'`; `said` is what a boot only says (a
1300
+ chain of steps that never ends), and `charter` is the charter engine's whole
1301
+ report. A boot refuses on `errors`. A running server answers for what is in
1302
+ force with `server.charterReport()`. It verifies and does nothing else: what
1303
+ it is handed is not read by the manifest's schema and is not frozen.
1304
+
1305
+ A charter check that boots no server builds the universe a boot resolves
1306
+ `data` over (the app's tables and the engine's own, AGENTS.md rule 10a) and
1307
+ asks `verifyApp`:
1308
+
1309
+ ```typescript
1310
+ import { PGlite } from '@electric-sql/pglite';
1311
+ import { MOSS_SEQUENCE, verifyApp } from '@niscorp/moss';
1312
+ import { migrate } from '@niscorp/strata/postgres';
1313
+ import { createPostgresCache, scopeGrants } from '@niscorp/vex';
1314
+ import { createPglitePool } from '@niscorp/vex/pglite';
1315
+
1316
+ const scratch = createPglitePool(new PGlite());
1317
+ await migrate(scratch, [MOSS_SEQUENCE, createPostgresCache({ pool: scratch }).sequence]);
1318
+ const { rows } = await scratch.query(`SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'`);
1319
+ const report = verifyApp(app, scopeGrants([...tables, ...rows.map((row) => String(row['table_name']))]));
1320
+ for (const error of report.errors) console.error(`${error.check}: ${error.detail}`);
1321
+ ```
1322
+
1323
+ ### The shell host
1324
+
1325
+ - `ShellHost` — `{ session, snapshot, deliver, list, reset }`:
1326
+ the durable per-principal shell host, as `server.shells` and
1327
+ `server.page(path).host`. The server creates it (`src/shells/`; the factory
1328
+ is not exported). It is handed no manifest and no
1329
+ runtime, but a typed object of what it needs: one function that answers what
1330
+ a principal's shell is made of (who they are, the action definitions they
1331
+ hold with their roles' layout variant in place, the canvases, the frame, the
1332
+ layout store's seed, the fragments, the entries, the component names), the
1333
+ app's code a shell calls (`inputs`, `seeds`, `phrases`, `functions`,
1334
+ `onSession`, `runs`), the wire for a token, and its limits. Everything in
1335
+ that answer but who somebody is comes from the running manifest, which is
1336
+ asked once for each build and once for each adopt
1337
+ (`src/manifest/artifacts.ts`): an action, a layout, a fragment and an entry
1338
+ reach a shell through that one answer, and the server's wiring reads none
1339
+ of them off the app. For an entry that is what a shell is told of the reads
1340
+ on its screens. What a read replays is not in the answer: the entries have
1341
+ two holders (see "Where the app's entries are held", under `createServer`).
1342
+ A kept shell may sit unattached for
1343
+ `runtime.shellIdleMs` (default 30 minutes; `0` disables the sweep). A shell
1344
+ that is not kept (nobody signed in; any shell of a page's host) ends when
1345
+ its last terminal leaves, and the host holds nothing of a shell that has
1346
+ ended.
1347
+ - `session(token, principal, options?)` — `options = { seed?, inputs? }`;
1348
+ `snapshot` is described under [The document](#the-document), and what it
1349
+ answers is exported as `ShellSnapshot`.
1350
+ Two first arrivals for one principal in the same moment are handed one
1351
+ shell: one is built.
1352
+ A build is bounded by `runtime.endpointTimeoutMs` (30 seconds when
1353
+ unset). It runs the app's code (`identity`, `inputs`, `phrases`), and
1354
+ code that hangs for one call costs that call: a build that has not
1355
+ landed by then fails, `session` and `snapshot` reject for whoever waited
1356
+ on it, and the next arrival builds afresh. What the app's code answers
1357
+ after that is not used: the build stops there, calls none of
1358
+ `functions`, `onSession` and `seeds`, and makes no shell.
1359
+ A session whose shell is not kept is the host's until that shell ends,
1360
+ so that a change can reach it. The socket ends it when the connection
1361
+ closes. Code that opens one in process and attaches nothing ends it
1362
+ itself, with `session.detach(connection)` (any connection: none was
1363
+ attached); until then the host holds the shell.
1364
+ - A host has no `adopt` and no `stop`. Each was a second way, for one
1365
+ host, to something a server does for all of them at once.
1366
+ **A change is the server's.** When what the app consists of changes
1367
+ (`server.refresh()`, `server.replaceActions()`, an integration approved
1368
+ or removed, a change another process made), every living shell of every
1369
+ host adopts: it is brought level with what its principal holds now, in
1370
+ place. Every living shell: the ones a host keeps, and the ones it built
1371
+ for one connection, which for the app's host is each visitor's and for a
1372
+ page's host is everybody's. Definitions that arrived or changed are
1373
+ registered and mounted instances keep their state; one that left, or is no
1374
+ longer granted, is removed and its instances unmounted. The shell's own
1375
+ layouts are taken from the same answer: the frame, each `{ ref }` of the
1376
+ layout store and each fragment that is answered differently from the last
1377
+ time is put in place, and every attached terminal is sent the frame. One
1378
+ that is answered as it was is left alone, so a ref the shell's own code
1379
+ set since (`shell.setLayout`) stands through a change that did not touch
1380
+ it. What a shell's canvases are, and what is mounted on them, is the
1381
+ shell's own state and is not taken again: a reset builds that afresh. A
1382
+ shell that cannot adopt is logged and keeps what it held; the rest go on.
1383
+ Each shell adopts on its own: one whose principal is never answered (an
1384
+ `identity` that hangs for them) holds up no other. So a change asks about
1385
+ every living shell in the same moment, and an app's `identity` runs at
1386
+ once for every signed-in principal whose record is not held.
1387
+ A shell whose build was under way adopts when it lands, and so does one a
1388
+ reset was replacing; no change waits for a build, or for another change.
1389
+ One built for the length of a `snapshot` is read and ended, and adopts
1390
+ nothing.
1391
+ **So is stopping.** `server.close()` stops every host's idle sweep, with
1392
+ everything else the server started.
1393
+ - `deliver(principal, channel, payload?): boolean` — publish a message,
1394
+ with what it carries, into every living shell this host has for one
1395
+ principal. `server.shells` is the app's own host, which keeps one shell
1396
+ for a principal: that one. (A page's host keeps none and reaches the one
1397
+ it built for each of their connections.) `false` = they have no living
1398
+ shell in this host; nothing is built. This host, in this process: it
1399
+ reaches no page's shell and no other process. To tell somebody's screens
1400
+ that something changed, wherever they live, a server calls `nudge`.
1401
+ - `list()` — every durable shell alive right now, each as
801
1402
  `{ principal, connections, since, idleSince, canvases }`. moss owns the map,
802
1403
  so moss enumerates it; an app keeping its own note beside it can only drift.
1404
+ `connections` is how many terminals are attached now. `since` is when the
1405
+ shell was built: a reset builds another, and moves it. `idleSince` is
1406
+ since when no terminal has been attached, and `null` while one is. Both
1407
+ are epoch milliseconds. `canvases` is each canvas with something mounted,
1408
+ as `{ id, actions }`: the ids of the actions on its stack, the top one
1409
+ first.
803
1410
  - `reset(principal): boolean` — dispose that principal's shell and stand its
804
1411
  replacement in the same slot, carrying the attached connections across.
805
- `false` = they hold no shell, which is an answer, not an error.
806
- - `stop()` — stop the idle sweep (the timer is unref'd, so a plain process
807
- needn't call it).
808
- - `ShellSession` — what `ShellHost.session(token, principal)` returns:
1412
+ Every living shell of theirs on this host: the one it keeps for them, or,
1413
+ on a host that keeps none (a page's), the one built for each of their
1414
+ connections, each replaced for itself.
1415
+ `false` = they hold no shell, which is an answer, not an error. The
1416
+ replacement is built from what the shell was opened with (for a page's,
1417
+ the inputs of its path and its id seed), and a shell's resets run one
1418
+ after another. A reset whose build throws, or has not landed within
1419
+ `runtime.endpointTimeoutMs`, is logged and leaves the shell that stood;
1420
+ the reset after it goes ahead.
1421
+ - What `ShellHost.session(token, principal)` returns (a type that is not
1422
+ exported by name: `Awaited<ReturnType<ShellHost['session']>>`):
809
1423
  `{ shell, attach, detach, resync, dispatch, publish, back, popTo, reset }`. The living nova `Shell`,
810
1424
  for in-process hosts (dev checks, embedded tools) that drive it directly;
811
- remote clients ride `attach`/`dispatch`. `shell` is a **getter** — `reset`
1425
+ remote clients ride `attach`/`dispatch`. Nine members of `shell` throw, as
1426
+ on [`FunctionSession`](#functionsession): the whole shell is
1427
+ `unverifiedShell(session)`. `shell` is a **getter** — `reset`
812
1428
  replaces the shell under a session already held, so a snapshot of the field
813
1429
  would go on addressing the disposed one.
814
- - `auditClosure(definitions, variants?): ClosureAuditor` — nova's action audit as
815
- the charter's injected closure hook (cross-action wiring breaks only), over each
816
- role's effective definitions (granted variants substituted).
1430
+ `dispatch(canvas, event)` holds what a terminal sent to the shell: the
1431
+ canvas must be one the shell has, an `origin` the event names must be an
1432
+ instance on that canvas (with none, the canvas's active instance is
1433
+ stamped), and the event must parse as one of nova's (`NovaEventSchema`:
1434
+ `ui:click`, `ui:submit`, `ui:input`, `ui:focus`, `ui:blur`, `ui:model`,
1435
+ `ui:key`, `ui:drop`, with their fields and no others). One that fails any
1436
+ of the three is dropped.
1437
+ `attach(connection, { delta? })` takes anything with `send(text)` and
1438
+ `close(code?, reason?)`. `delta: true` says the connection can apply frame
1439
+ deltas, which it is then sent where `runtime.shellFrameDelta` is on; absent,
1440
+ it is sent whole frames. `resync(connection)`, `back()`, `popTo(canvas,
1441
+ instance)` and `reset()` do what the message of the same name does
1442
+ ([The socket protocol](#the-socket-protocol)). `back()` answers `false`
1443
+ when there was nothing left to undo. After `reset()` the session object is
1444
+ still good: the attached connections are carried across and sent a fresh
1445
+ frame.
1446
+
1447
+ A check that connects in process hands the socket a `Connection` of its own,
1448
+ and reaches the app's shell host as `server.shells`:
1449
+
1450
+ ```typescript
1451
+ import { mintDevToken } from '@niscorp/moss';
1452
+ import type { ShellHost } from '@niscorp/moss';
1453
+ import { PROTOCOL, offerToken } from '@niscorp/moss/protocol';
1454
+ import type { Connection } from '@niscorp/moss/protocol';
1455
+
1456
+ const frames: string[] = [];
1457
+ const connection: Connection = {
1458
+ send: (text) => void frames.push(text),
1459
+ close: () => undefined,
1460
+ onMessage: () => undefined,
1461
+ onClose: () => undefined,
1462
+ // who is asking, as a transport reads it off the upgrade (`session: 'dev-open'`)
1463
+ upgrade: { offered: offerToken(mintDevToken('usr_ada')) },
1464
+ };
1465
+ await server.socket(`/socket?protocol=${PROTOCOL}`, connection);
1466
+ const shells: ShellHost | undefined = server.shells;
1467
+ // a message with a payload, into the shell this process keeps for her
1468
+ const shown: boolean = shells?.deliver('usr_ada', 'notify', { text: 'Saved.' }) ?? false;
1469
+ // "her notes changed": every shell of hers, in every process, reads again
1470
+ server.nudge('usr_ada', 'notes-changed');
1471
+ ```
817
1472
 
818
1473
  ### The socket protocol
819
1474
 
820
- - `createSocket(ctx): SocketAccept` — `ctx = { session, catalog, shells?, page?,
821
- revalidateMs?, telemetry? }`. One `accept(url, connection)` per connection; `accept.stop()`
822
- ends revalidation (the timer is unref'd, so a plain process needn't call it).
823
- - **Identity is asked twice.** At upgrade, and then every `revalidateMs`
824
- (default `DEFAULT_REVALIDATE_MS`, 60s; `0` disables) for as long as the
825
- connection lives. A token that stops resolving — or starts resolving to
1475
+ - `server.socket` is called once for each connection, by the runtime's
1476
+ transport: `server.socket(url, connection)`. `server.socket.stop()` ends
1477
+ revalidation (the timer is unref'd, so a plain process needn't call it).
1478
+ `createServer` builds it (`src/socket/`), handed who a token is, what
1479
+ somebody holds, and where a session comes from for the app and for each
1480
+ page. Neither its factory nor its type is exported by name: the type is
1481
+ `MossServer['socket']`.
1482
+ - **Identity is asked twice.** At upgrade, and then every
1483
+ `runtime.sessionRevalidateMs` (default 60 seconds; `0` disables) for as long
1484
+ as the connection lives. A token that stops resolving — or starts resolving to
826
1485
  somebody else — gets an `invalid_token` error frame and a `4401` close, which
827
1486
  is the recovery the terminal already performs: drop the token, reconnect
828
1487
  anonymous, land on the served lock screen.
829
1488
  - Anonymous connections are never revalidated: nothing they hold can expire.
830
1489
  - A verifier that **throws** is a fault, not a sign-out — the connection is
831
1490
  left alone and asked again next pass, so a database blip cannot become an
832
- outage. Only an explicit `null` (or a changed principal) closes.
1491
+ outage. Only an explicit `null` (or a changed principal) closes. That it
1492
+ threw is logged, once for a pass: how many connections could not be asked
1493
+ about, and the first error.
1494
+ - One pass at a time: a pass asks about every connection in turn, and one
1495
+ that is due while another is still asking is skipped. A slow verifier is
1496
+ not asked more the slower it gets.
833
1497
  - Without this the socket was the asymmetry: the HTTP surfaces re-ask on
834
1498
  every request, so an expired credential left the socket open and rendering
835
1499
  while every endpoint the server shell called came back 401 — a live
836
1500
  interface whose every load silently fails.
837
- - `Connection` — the transport seam: `{ send, close, onMessage, onClose }`.
838
- - `ServerMessage` — `hello | catalog | frame | render | render-delta | session | error`.
839
- - `ClientMessage` — `event | publish | resync | reset | back | popTo`.
1501
+ - `Connection` (`@niscorp/moss/protocol`) — the transport seam: `{ send, close, onMessage, onClose }`.
1502
+ `onClose` is called once, as soon as who is asking is decided and before
1503
+ `hello`: a connection that closes while its session is being opened (its
1504
+ catalog asked, its shell built) is not attached to a shell, so a kept shell
1505
+ idles and one built for that connection alone is disposed. The type also
1506
+ has `upgrade` (below) and `seal`. `seal` is set by the socket, on a
1507
+ connection whose browser holds a seal: a transport leaves it out.
1508
+ - `ServerMessage` (`@niscorp/moss/protocol`) — what the server sends: `hello | catalog | frame | render |
1509
+ render-delta | session | error`.
1510
+ - What a terminal sends is `event | publish | resync | reset | back | popTo`,
1511
+ each with exactly the fields the protocol names (`src/protocol/messages.ts`;
1512
+ the type of these is not exported, a terminal written by hand sends the
1513
+ object).
840
1514
  - **A message a terminal sends is at most 256 KB**, counted as it is once
841
1515
  inflated. One over that closes the connection with `1009` — the transport's
842
1516
  own close, not one of moss's — and what it carried did not arrive: the
843
1517
  terminal reconnects as after any other close, and a signed-in person's shell
844
- is as it was. The limit is the Node transport's (`attachSocket`'s
845
- `maxMessageBytes`, below), and it is a bound on memory, not on speed: the
1518
+ is as it was. The limit is the Node transport's, set by
1519
+ `runtime.socketMaxMessageBytes` wherever the server's socket is attached,
1520
+ and it is a bound on memory, not on speed: the
846
1521
  server keeps what a message carried — the value in the shell, and again in
847
1522
  the last frame it sent — and sends it back down in every later frame of that
848
1523
  canvas. An event is a press, a typed value, a row handed back. A file never
@@ -872,15 +1547,31 @@ measures the end.
872
1547
  - `popTo` names a canvas and an instance already on its stack
873
1548
  (`{ type: 'popTo', canvas, instance }`): unmount everything above it, in one
874
1549
  step — a breadcrumb's jump, which several `back`s would race.
875
- - `CLOSE_INVALID_TOKEN = 4401`, `CLOSE_SIGNED_OUT = 4403`,
876
- `CLOSE_SHELL_FAILED = 4500`, `CLOSE_PROTOCOL_MISMATCH = 4426`. `4500` means
877
- the server could not open a session for this connection (commonly a
878
- definition failing validation): a `session_failed` error frame naming the
879
- failing definitions, then the close. The refusal is that terminal's alone,
880
- and reconnecting later is reasonable.
881
- - `error` codes: `invalid_token`, `session_failed`, `client_too_old`,
882
- `server_too_old`, `no_shell` (the app serves no shell), `invalid_message`,
883
- `seal_not_kept` (a sealed sign-in came back with no seal to open it).
1550
+ - **The close codes.** Two are exported, by `@niscorp/moss/protocol`, because
1551
+ they are the two a terminal recovers from by dropping its token:
1552
+ `CLOSE_INVALID_TOKEN = 4401` and
1553
+ `CLOSE_SIGNED_OUT = 4403`. Three more are numbers a terminal written by hand
1554
+ names itself (their constants are in `src/protocol/connection.ts` and are
1555
+ not exported):
1556
+ - `4500`: the server could not open a session for this connection (commonly
1557
+ a definition failing validation). A `session_failed` error frame, then the
1558
+ close. The frame names the failing definitions when that is the cause; of
1559
+ any other cause it says nothing, and the error is in the server's log. The
1560
+ refusal is that terminal's alone, and reconnecting later is reasonable.
1561
+ - `4503`: the server is serving as many terminals with nobody signed in as
1562
+ `runtime.anonymousShellMax` allows, and built no shell for this one. An
1563
+ `at_capacity` error frame, then the close. Not a recovery: the terminal
1564
+ keeps what it holds and reconnects with its usual backoff, which grows
1565
+ for as long as it is refused.
1566
+ - `4426`: the two ends speak protocols the other cannot (below).
1567
+ - `error` codes: `invalid_token`, `session_failed`, `at_capacity`,
1568
+ `client_too_old`, `server_too_old`, `no_shell` (the app serves no shell),
1569
+ `invalid_message`
1570
+ (what was sent is not JSON, not one of the messages above, or one of them
1571
+ with a field it does not have: nothing of it is acted on), `message_failed`
1572
+ (the server threw acting on a message it could read; why is in its log, and
1573
+ the connection stays open), `seal_not_kept` (a sealed sign-in came back with
1574
+ no seal to open it).
884
1575
  - **Who a terminal is** is decided on the upgrade request, from a header of
885
1576
  it — never from its address, which is what every proxy on the way writes
886
1577
  into its log. A terminal offers the subprotocol `nisc`, and beside it its
@@ -929,9 +1620,9 @@ measures the end.
929
1620
  a message changes shape; raise `PROTOCOL_MIN` only when the server stops
930
1621
  speaking an old one. Both are `2` today: at `1` the token rode the address,
931
1622
  and a server that went on reading it there would keep that open. `PROTOCOL`
932
- and `offerToken` are exported from the package root, for a terminal written
933
- by hand; `PROTOCOL_MIN` and `CLOSE_PROTOCOL_MISMATCH` are defined in
934
- `src/socket.ts` and are not.
1623
+ and `offerToken` are exported from `@niscorp/moss/protocol`, for a terminal
1624
+ written by hand; `PROTOCOL_MIN` and `CLOSE_PROTOCOL_MISMATCH` are defined in
1625
+ `src/protocol/connection.ts` and are not.
935
1626
  - **`?path=`** — the path the terminal is on. A path that leads to a page is
936
1627
  served that page's shell, built for this connection alone and seeded with the
937
1628
  path's parameters; any other path (and no path) is the app's shell. A
@@ -947,6 +1638,23 @@ measures the end.
947
1638
  `ActionSlot` is a boundary, not content — visibility is decided by what's
948
1639
  inside it.
949
1640
 
1641
+ A terminal written by hand, with the four things it takes from this entry:
1642
+
1643
+ ```typescript
1644
+ import { CLOSE_INVALID_TOKEN, CLOSE_SIGNED_OUT, PROTOCOL, offerToken } from '@niscorp/moss/protocol';
1645
+ import type { ServerMessage } from '@niscorp/moss/protocol';
1646
+
1647
+ const socket = new WebSocket(`wss://app.example/socket?protocol=${PROTOCOL}`, offerToken(token));
1648
+ socket.addEventListener('message', (event) => {
1649
+ const message: ServerMessage = JSON.parse(String(event.data));
1650
+ if (message.type === 'render') show(message.canvas, message.tree);
1651
+ });
1652
+ socket.addEventListener('close', (event) => {
1653
+ // the token is nobody's, or its session ended: do not offer it again
1654
+ if (event.code === CLOSE_INVALID_TOKEN || event.code === CLOSE_SIGNED_OUT) forgetToken();
1655
+ });
1656
+ ```
1657
+
950
1658
  ### Wire size
951
1659
 
952
1660
  Two independent reductions, both optional, both invisible to an application.
@@ -972,6 +1680,10 @@ served. Turn it off — or tune `zlibDeflateOptions.memLevel` / `windowBits`
972
1680
  through the object form — when connection count matters more than bandwidth.
973
1681
  An object is handed to `ws` verbatim; see its `perMessageDeflate` options.
974
1682
 
1683
+ The setting is the Node transport's, and the server's socket carries it there
1684
+ from the runtime: it holds under `serve`, `nisc start`, the dev plugin, and a
1685
+ host that attaches `server.socket` itself.
1686
+
975
1687
  #### Frame deltas — `runtime.shellFrameDelta`, default **off**
976
1688
 
977
1689
  A changed canvas, described against the frame that connection already holds:
@@ -1014,33 +1726,43 @@ Correctness, which matters more than the saving:
1014
1726
  - Bases are dropped on every reconnect: attaching is served whole frames, so a
1015
1727
  base carried across a reconnect is one the server never assumed.
1016
1728
  - A `reset` carries the capability across to the replacement shell.
1017
- - `src/delta.ts` is the whole implementation — `encodeDelta`, `applyDelta`,
1018
- `frameHash` — with no dependency, small enough to read in full. A delta layer
1019
- that cannot be audited is a desync you cannot diagnose.
1729
+ - `src/protocol/delta.ts` is the whole implementation — `encodeDelta`, `applyDelta`,
1730
+ `frameHash`, none of them exported — with no dependency, small enough to
1731
+ read in full. A delta layer that cannot be audited is a desync you cannot
1732
+ diagnose.
1020
1733
 
1021
1734
  ## `@niscorp/moss/node`
1022
1735
 
1023
1736
  - `serve(app, runtime & { port? }): Promise<MossServer>` — boots and listens:
1024
1737
  `createServer` runs inside (boot refusal included), then HTTP + the socket
1025
- in one process. `port` defaults to 8787.
1026
- - `attachSocket(httpServer, accept, path?, options?)` — embed the socket on an
1027
- existing server (raw `ws`, `noServer`, path-matched — coexists with vite
1028
- HMR). `path` defaults to `/socket`. `options = { compression?,
1029
- maxMessageBytes? }`. `compression` is the same value as
1030
- `runtime.socketCompression` and defaults to `true`; `serve()` passes the
1031
- runtime's through for you, so only a host running its own listener (a vite
1032
- plugin, a dev check) ever needs it. `maxMessageBytes` is the largest message
1033
- a connection may send, in bytes, and defaults to 256 KB (`256 * 1024`); a
1034
- message over it closes that connection with `1009`. It is handed to `ws` as
1035
- `maxPayload`, whose own default was 100 MiB. Only a host that calls
1036
- `attachSocket` itself can raise it: `serve()`, `nisc start` and the dev
1037
- plugin take the default.
1738
+ in one process. `port` defaults to 8787. **`close()`
1739
+ on the server it returns stops what `serve` started**: moss's own timers,
1740
+ then every connection (closed `1001`), then the listener. `serve` hands back
1741
+ neither the listener nor the transport, so that is the one way to stop them.
1742
+ - `attachSocket(httpServer, accept, path?, options?): { close }` — embed the
1743
+ socket on an existing server (raw `ws`, `noServer`, path-matched — coexists
1744
+ with vite HMR). `path` defaults to `/socket`. **A host that attaches a
1745
+ server's socket passes no options**: `server.socket` says how it is to be
1746
+ attached (`runtime.socketCompression`, `runtime.socketMaxMessageBytes`), and
1747
+ the transport reads that off it. `serve`, `nisc start` and the dev plugin
1748
+ all attach it that way. `options = { compression?, maxMessageBytes? }` is
1749
+ for a host that means otherwise, and for an accept of its own that says
1750
+ nothing; a setting named there wins, and one that is not named stays what
1751
+ the socket says. What neither says is the default: `compression` `true`,
1752
+ and `maxMessageBytes` 256 KB (`256 * 1024`), the largest message a
1753
+ connection may send, in bytes; a message over it closes that connection
1754
+ with `1009`. It is handed to `ws` as `maxPayload`, whose own default was
1755
+ 100 MiB. What it answers is how
1756
+ the transport is retired: `close()` ends every connection it opened (`1001`)
1757
+ and takes no more, for a host that stops its listener while the process goes
1758
+ on.
1038
1759
  - A frame the transport refuses — malformed, not UTF-8, over the limit — ends
1039
1760
  that connection (`1002`, `1007`, `1009`) and logs one line; no other
1040
1761
  connection is touched.
1041
1762
 
1042
1763
  - `mountSite(server, { dist, draw, htmlAttributes?, site?, tokenKey?, waitMs?, owned? })`
1043
- — the built terminal, served by the same process as the app. Every GET that
1764
+ — the built terminal, served by the same process as the app (the second
1765
+ argument is `SiteConfig`). Every GET that
1044
1766
  nothing registered earlier answers is a file from `dist`, or a page:
1045
1767
  `index.html` with the caller's screen drawn into it (`renderDocument`) — the
1046
1768
  app's own for `/`, one of the manifest's pages for a path that leads to one.
@@ -1059,34 +1781,442 @@ Correctness, which matters more than the saving:
1059
1781
  `/^\/(api|catalog|socket|operator|integrations)(\/|$)/`. The default `owned`
1060
1782
  here and in the dev plugin.
1061
1783
 
1784
+ A host with a listener of its own does by hand what `serve` does:
1785
+
1786
+ ```typescript
1787
+ import { serve as listen } from '@hono/node-server';
1788
+ import { MOSS_PATHS, attachSocket, mountSite } from '@niscorp/moss/node';
1789
+ import type { SiteConfig } from '@niscorp/moss/node';
1790
+
1791
+ const site: SiteConfig = { dist: 'dist', draw };
1792
+ mountSite(server, site);
1793
+ const httpServer = listen({ fetch: server.fetch, port: 8787 });
1794
+ const sockets = attachSocket(httpServer, server.socket);
1795
+ // ...and to stop: server.close(); sockets.close(); httpServer.close();
1796
+
1797
+ // is a path one the app server answers itself?
1798
+ MOSS_PATHS.test('/api/vex');
1799
+ ```
1800
+
1062
1801
  ## `@niscorp/moss/vite`
1063
1802
 
1064
1803
  Requires the optional `vite` peer.
1065
1804
 
1066
- - `mossDev(options): Plugin` — the app server inside vite's dev process
1067
- (serve only): no proxy and no second process. The socket is attached once to
1068
- vite's own http server; `/` and any path a page answers go out as
1805
+ - `mossDev(options: MossDevOptions): Plugin` — the app server inside vite's
1806
+ dev process (serve only): no proxy and no second process. The socket is
1807
+ heard once on vite's own http server, and each upgrade is answered by the
1808
+ transport of the app that is booted then: one for each app, set as its
1809
+ runtime says (`socketCompression`, `socketMaxMessageBytes`). An upgrade that
1810
+ arrives during a boot waits for it; one that meets an app that did not boot
1811
+ is refused with `503`. `/` and any path a page answers go out as
1069
1812
  `index.html` through `transformIndexHtml` with the screen drawn in
1070
1813
  (`renderDocument`); `MOSS_PATHS` go to the app server; the rest is vite's.
1071
1814
  An edit under a watched path re-boots the whole app and reloads the page;
1072
1815
  the outgoing server answers until the new one is up, and a failed re-boot
1073
- keeps it.
1816
+ keeps it. The connections of an app that is let go are closed (`1001`), so
1817
+ a terminal that is not a page connects again, to the app that is booted.
1074
1818
  - `options.app(load): Promise<DevApp>` — stand the app up. `load` is vite's
1075
1819
  `ssrLoadModule`. `DevApp = { server, close?, draw?, htmlAttributes?,
1076
1820
  site?, tokenKey?, signIn? }`; absent `draw`, pages go out undrawn.
1821
+ `close` is how the app is let go (default: `server.close()`).
1077
1822
  - `signIn(who)` enables `/dev/as/<who>`: it puts the returned token in the
1078
1823
  browser's session cookie and goes to `/`. `null` is nobody of that name.
1824
+ **It answers requests from this machine only**: the address at the other
1825
+ end of the request's socket is loopback (`127.0.0.0/8`, `::1`, or either
1826
+ written as an IPv4-mapped IPv6 address). Any other request is answered
1827
+ `403` with a sentence that says why, and the app is not asked. What a
1828
+ header says of where a request came from (`X-Forwarded-For`) is not read;
1829
+ behind a proxy on the same machine every request is the proxy's, and is
1830
+ this machine's.
1831
+ - `signInFromNetwork?: boolean` (default `false`) answers the sign-in to
1832
+ every device that can reach the dev server, for trying a signed-in screen
1833
+ on a phone. It hands out a session for whoever the address names: with it
1834
+ on and vite listening on a network (`--host`), anybody on that network
1835
+ signs in as anybody. Turn it on for as long as the phone needs it, on a
1836
+ network you trust, and not while browsing elsewhere.
1079
1837
  - `watch?: RegExp` (default: `src/app`, `src/server`, `src/db`, `src/ui` and
1080
1838
  the nisc config), `index?` (default `index.html`), `owned?` (default
1081
- `MOSS_PATHS`), `label?` (default `moss`).
1839
+ `MOSS_PATHS`), `label?` (default `moss`). `index` is the page template,
1840
+ relative to vite's root, and `label` the name in vite's log. `owned` is
1841
+ the paths that go to the app server, and a path it does not match is
1842
+ vite's. It takes the place of `MOSS_PATHS`: an app with a route of its
1843
+ own under another prefix names moss's prefixes and its own there.
1844
+
1845
+ ```typescript
1846
+ import { mintDevToken } from '@niscorp/moss';
1847
+ import type { MossServer } from '@niscorp/moss';
1848
+ import { mossDev } from '@niscorp/moss/vite';
1849
+ import type { DevApp, MossDevOptions } from '@niscorp/moss/vite';
1850
+
1851
+ const app: MossDevOptions['app'] = async (load): Promise<DevApp> => {
1852
+ const { boot } = await load('/src/server/boot.ts');
1853
+ if (typeof boot !== 'function') throw new Error('src/server/boot.ts exports no boot');
1854
+ const server: MossServer = await boot();
1855
+ return { server, signIn: (who) => mintDevToken(who) };
1856
+ };
1857
+
1858
+ export const plugins = [mossDev({ app })];
1859
+ ```
1860
+
1861
+ ## `@niscorp/moss/integrations`
1862
+
1863
+ An integration is a separate service registered with the deployment, whose
1864
+ actions join the manifest once an operator approves them. It is a feature: an
1865
+ app that wants integrations creates it and names it in `features`.
1866
+
1867
+ ```typescript
1868
+ import { z } from 'zod';
1869
+ import { createIntegrations } from '@niscorp/moss/integrations';
1870
+
1871
+ // What this app lets a bundle say beyond nisc's own fields.
1872
+ const Listing = z.object({ title: z.string(), placedUnder: z.string().optional() }).strict();
1873
+
1874
+ const integrations = createIntegrations({
1875
+ integrationActor: (integration, actsFor) => `ig_${integration}@${actsFor}`,
1876
+ extension: {
1877
+ schema: Listing,
1878
+ check: (listing) => (listing.placedUnder === undefined || listing.placedUnder === 'hub.people' ? [] : [`placedUnder: "${listing.placedUnder}" is not a hub of this app`]),
1879
+ contract: { title: 'the store tile’s title', placedUnder: ['hub.people'] },
1880
+ },
1881
+ });
1882
+ const app = defineApp({ charter, actions, features: [integrations] });
1883
+ const server = await createServer(app, runtime);
1884
+
1885
+ const registered = await integrations.listIntegrations();
1886
+ const titles = registered.map((integration) => integration.extension?.title);
1887
+ ```
1888
+
1889
+ **A bundle** is what an integration publishes at `<url>/bundle`. Five fields
1890
+ are nisc's own, and moss reads them; a sixth is the host app's.
1891
+
1892
+ | Field | What |
1893
+ |---|---|
1894
+ | `integration` | its id |
1895
+ | `grants` | `{ actions, data }`: what it asks to be allowed. The operator's approval grants it |
1896
+ | `grammar` | the grammar stamps its documents are written at (optional) |
1897
+ | `actions` | its action definitions, by id |
1898
+ | `phrasebook` | its phrases, by language (`de`, never `de-AT`) |
1899
+ | `extension` | whatever the host app's own vocabulary is (optional). Moss does not read inside it |
1900
+
1901
+ The schema is strict. Any other top-level key refuses the bundle: `"meta" is
1902
+ not a field of a bundle. What belongs to the host app’s own vocabulary goes
1903
+ under `extension`.` A store listing, where a screen is placed, a setting a
1904
+ person may change, a capability, a document a person edits: each is one app's
1905
+ vocabulary, and the app that has it defines it.
1906
+
1907
+ #### `createIntegrations(config?: IntegrationsConfig<Extension>): Integrations<Extension>`
1908
+
1909
+ `IntegrationsConfig`, every field optional:
1910
+
1911
+ - `integrationActor(integration, actsFor): string | null | Promise<string | null>`
1912
+ — the principal a call made with an integration's key acts as; `actsFor` is
1913
+ the request's `x-nisc-acts-for`. `null`, or absent, refuses (`403`).
1914
+ - `extension: ExtensionConfig<Extension>` — the app's own vocabulary for a
1915
+ bundle. Absent, a bundle that carries an `extension` is refused. Its four
1916
+ members:
1917
+ - `schema: z.ZodType<Extension>` — what a bundle's `extension` may be. It
1918
+ reads whatever the bundle carries there, a bundle that carries nothing
1919
+ included: a schema that takes `undefined` (`.optional()`, `.prefault({})`)
1920
+ makes the extension optional. Each place it does not read is a reason
1921
+ under `extension`. It also reads back what was stored, so it takes what it
1922
+ answers.
1923
+ - `check(extension, bundle): string[]` — the reasons the app refuses an
1924
+ extension the schema read, each a sentence. They are reported with moss's
1925
+ own, and any one refuses the bundle.
1926
+ - `prepare(extension, bundle): Extension | Promise<Extension>` — run once
1927
+ for an import that passed every check, before the row is written: what it
1928
+ answers is what is stored. For what must not depend on the vendor's
1929
+ service being reachable later (an image copied to the app's own store).
1930
+ Throwing refuses the bundle whole. Not called for an extension that reads
1931
+ as `undefined`.
1932
+ - `contract: unknown` — what the app tells vendors about its vocabulary: a
1933
+ plain value, served with the contract as it is.
1934
+
1935
+ `check` and `prepare` are handed, as `bundle` (`ExtensionContext`), what moss
1936
+ knows of the bundle: `integration` (its id), `url` (where its service
1937
+ lives), `actions` (its action definitions, each already held to its
1938
+ namespace, its endpoints and the kit), `fingerprints` (the ones the app
1939
+ serves), and `layoutMisfits(layout)` (each place a layout does not fit the
1940
+ app's kit, for a vocabulary that lets a bundle carry one).
1941
+ - `signingSeed: string` — a fixed seed for the keypair assertions are signed
1942
+ with: 32 bytes, as base64 (`node -e
1943
+ "console.log(require('node:crypto').randomBytes(32).toString('base64'))"`).
1944
+ With none, a keypair is made when the feature starts and kept nowhere, so
1945
+ each boot and each process has its own. Give one where an integration's
1946
+ service holds the public half in its environment, or where a deployment
1947
+ runs more than one process: the same seed is the same key everywhere. It is
1948
+ this feature's setting and no other feature is handed it. One that decodes
1949
+ to fewer than 32 bytes refuses the boot.
1950
+ - `outboundTimeoutMs: number` — how long a call out to an integration's
1951
+ service may take, its answer and its body together. Default `30000`, nova's
1952
+ default wait for an endpoint's reply. A whole number of milliseconds from 1
1953
+ to 2^31 − 1: anything else, `Infinity` included, throws where
1954
+ `createIntegrations` is called. It bounds every call: a screen's
1955
+ through the proxy, a vendor's webhook, `callIntegration`, the bundle fetched
1956
+ at registration, and the operator's probe. A call that is given up on reads
1957
+ as a service that is unreachable: `502` from the proxy, the webhook and a
1958
+ registration whose bundle did not arrive; `callIntegration` rejects; the
1959
+ probe answers `status: 0`. The shorter of this and an action's own
1960
+ `timeoutMs` ends a call, so an integration whose endpoint is slow by nature
1961
+ needs this raised as well; an answer that streams for longer than this is
1962
+ cut.
1963
+
1964
+ An integration's id is lower-case letters, digits and hyphens, starting with a
1965
+ letter: it is a segment of every path the integration is served under and a
1966
+ part of every action it ships. A registration under any other id is a `400`,
1967
+ and a bundle that calls itself anything else is refused at intake.
1968
+
1969
+ `Integrations` is a feature that also carries the calls an app makes. They
1970
+ work once a server has started the feature, and reject with a sentence before
1971
+ that:
1972
+
1973
+ - `listIntegrations(): Promise<RegisteredIntegration<Extension>[]>` — every
1974
+ registered integration, in the order of the ids: `{ id, status, url,
1975
+ extension }`. `status` is `'pending'` or `'approved'`; `extension` is what
1976
+ the row holds, read by the app's schema and so typed by it (`undefined`: the
1977
+ bundle carried none, the app supplied no schema, or the schema no longer
1978
+ reads what was stored, which is logged with the integration's id). An app
1979
+ builds its placements, its listing and anything else from this.
1980
+ - `callIntegration(id, path, { principal, method?, body?, scope? }):
1981
+ Promise<Response>` — call an installed integration when
1982
+ nobody is driving; throws unless it is approved and installed for the
1983
+ principal's tenant. It is not held to the integration's reach: an app calls
1984
+ an endpoint its own vocabulary names (a preview, a page it mounts on a route
1985
+ of its own) with this. `principal` is who the call is made for, and who the
1986
+ assertion names. `method` defaults to `POST`; `body` is sent as JSON;
1987
+ `scope` is merged over the principal's scope values in the assertion. What
1988
+ the integration answers comes back whatever its status: only a refusal and
1989
+ a service that cannot be reached throw. So a call that must still reach an
1990
+ integration that is being uninstalled (an erase) is made before the
1991
+ uninstall.
1992
+ - `integrationByKey(key): Promise<string | undefined>` — the approved
1993
+ integration a presented key belongs to.
1994
+ - `integrationOfAction(actionId): string | undefined` — which integration an
1995
+ `ext.<audience>.<integration>.<name>` action belongs to. It reads nothing,
1996
+ and answers before a server has started the feature.
1997
+
1998
+ Which integrations are live for a principal is `installed` on the record the
1999
+ app's `identity.resolve` answers; absent, every approved integration is live
2000
+ for everybody, and an empty list is none.
2001
+ The rule that reads it is this feature's (an
2002
+ `ext.<audience>.<integration>.<name>` action is there for somebody only where
2003
+ that integration is in their list), and it is laid when the feature starts:
2004
+ an app that names no feature has no such rule, and holds an `ext.…` action
2005
+ of its own wherever the charter grants it.
2006
+
2007
+ What the feature serves once it is started:
2008
+
2009
+ | Path | What |
2010
+ |---|---|
2011
+ | `/api/integrations/*` | `GET contract` (`?id=`, `?format=md`), `GET verify-key` |
2012
+ | `/integrations/:id/*` | the proxy to an approved integration, as the signed-in caller; plus `hook/*`, which takes no session |
2013
+ | `/operator/integrations` | list, register (`POST`), `:id/approve`, `:id/probe`, `DELETE :id` — keyed by `x-operator-key`, so only when `runtime.operatorKey` is set |
2014
+
2015
+ A bearer token with the `ik_` prefix is an integration key: it is resolved to
2016
+ the integration it was issued to and, through `integrationActor`, to a
2017
+ principal (`401` unknown key, `403` no actor). No two integrations hold the
2018
+ hash of one key (a unique index on `integrations.key_hash`).
2019
+
2020
+ **What intake holds a bundle to**, before any of it is kept. It is upgraded by
2021
+ its grammar stamps and read by the bundle's schema. Each action is named
2022
+ `ext.<audience>.<integration>.<name>` under the integration's own id; each of
2023
+ its endpoints is a fingerprint the app serves or a URL under
2024
+ `/integrations/<id>/` (and not under `hook/`, the door that asks for no
2025
+ session), and none is `fn:`; its layout composes what the app's kit has; and no
2026
+ chain of its steps, laid over the app's own actions, runs for ever. Then
2027
+ `extension` is read by the app's schema and held to the app's `check`. Every
2028
+ reason, moss's and the app's, is reported together, and any one refuses the
2029
+ bundle whole: the last good import keeps serving.
2030
+
2031
+ **What the routes do, in order.**
2032
+
2033
+ - *Register* (`POST /operator/integrations`, `{ id, url }`) fetches the
2034
+ bundle, runs intake, runs the app's `prepare`, and for an integration that
2035
+ is already approved asks whether the app could be served with the new
2036
+ actions. Then the bundle lands in one transaction: the integration's row,
2037
+ its actions in place of the ones it shipped before, and the hash of its key
2038
+ on the import a key is issued with. It lands whole, or the import before it
2039
+ is still there, whole. The answer carries `key` once, on the registration
2040
+ whose key the row holds: the hash is written where the row holds none, so of
2041
+ two registrations of one new integration in the same moment one is answered
2042
+ the key and the other is answered as a later import is, with none.
2043
+ - *Approve* (`POST /operator/integrations/:id/approve`) reads what the
2044
+ integration shipped, asks whether the app could be served with it, and only
2045
+ then writes the approval. Refused, it answers `422` with the reason and
2046
+ nothing is written. Written, its actions are read from the rows and handed
2047
+ to the running app; if the app does not take them all the same (something
2048
+ else changed what it consists of in between), the approval is taken back:
2049
+ the row is pending again with the reason in `lastError`, and the answer is
2050
+ the same `422`.
2051
+ - *The list* (`GET /operator/integrations`) answers each integration as `{ id,
2052
+ url, status, requestedActions, requestedData, approvedData, extension,
2053
+ lastImportAt, lastError, actionCount }`. `extension` is the stored value,
2054
+ as it is (`null`: none).
2055
+ - *The contract* (`GET /api/integrations/contract`) carries the kit's
2056
+ components with their props, the audiences the charter drew an `ext.` fence
2057
+ for, the namespace, the key assertions are verified with, and, under
2058
+ `fingerprints`, the reads and writes the caller's own policy lets them
2059
+ replay: an integration asking with its key reads what its actor's rung
2060
+ reaches, and nobody signed in reads what `public` reaches. Under `extension`
2061
+ it carries the app's `extension.contract`, as the app handed it over; the
2062
+ key is absent when the app handed none.
2063
+ - *The proxy* (`/integrations/:id/*`) forwards a signed-in caller's call to an
2064
+ approved integration that is installed for them, with an assertion that
2065
+ says who they are. It forwards the paths the integration's actions declare
2066
+ as endpoints, each for whoever holds an action that declares it, and
2067
+ answers `404` for any other path.
2068
+ - *A webhook* (`POST /integrations/:id/hook/*`) takes no session and no
2069
+ assertion is minted for it: the body goes on to the integration's service
2070
+ byte for byte, with the vendor's headers but `authorization` and `host`,
2071
+ and the integration checks the vendor's signature itself. An integration
2072
+ that is unknown or not approved answers `404`. **The door has a limit, and
2073
+ it is a limit per process**: 240 calls a minute for each integration,
2074
+ counted in the memory of the process that takes them, in windows of a minute
2075
+ that start at a window's first call. Past it the answer is `429`
2076
+ `{ message: 'Too many.' }` and nothing is forwarded. With several processes
2077
+ behind one address a vendor is let through up
2078
+ to that many times 240 a minute, however the balancer splits its calls, and
2079
+ a process that restarts counts from nothing. It is not a ceiling for the
2080
+ deployment, and neither number is a setting: a deployment that needs one
2081
+ ceiling across its processes sets it where they meet, at its proxy.
2082
+
2083
+ **A vendor's own page inside the app** is the app's to mount. Moss frames
2084
+ none: an app that wants one serves a route of its own (`routes(server)` in
2085
+ `nisc.config.ts`), decides there who may open it, and fetches the page from the
2086
+ integration's service with `callIntegration`, which signs the call as the
2087
+ person looking.
2088
+
2089
+ **Its tables.** `integrations` and `integration_actions` are part of
2090
+ `MOSS_SEQUENCE` (`@niscorp/moss`), and the feature names both as its own. They
2091
+ are tables like any other in the charter's `data` universe: a role granted a
2092
+ data wildcard denies them (`integrations.*`, `integration_actions.*`). An
2093
+ app's own vex entry reads `integrations.extension` as it reads any column.
2094
+
2095
+ | Column of `integrations` | What |
2096
+ |---|---|
2097
+ | `id`, `url`, `status` | which it is, where its service lives, `pending` or `approved` |
2098
+ | `key_hash` | the hash of the key it was issued; never the key |
2099
+ | `requested_actions`, `requested_data`, `approved_data` | what it asked to be allowed, and what the approval granted |
2100
+ | `reach` | every path the proxy forwards, with the actions that declare it |
2101
+ | `phrasebook` | its phrases, by language |
2102
+ | `extension` | what its bundle said in the app's own vocabulary, as the app's `prepare` answered it |
2103
+ | `last_import_at`, `last_error` | when the last good import landed, and why the last one did not |
2104
+
2105
+ `integration_actions` holds one row for each action: `integration_id`,
2106
+ `action_id`, `definition`, and `grammar`, the stamps the definition is written
2107
+ at.
2108
+
2109
+ The feature reads and writes them through vex, with entries of its own that no
2110
+ route serves (see [Features](#features)); it holds no SQL. Landing a bundle is
2111
+ a batch, so `runtime.db` has to have `transaction`, as it does for any batch an
2112
+ app writes.
2113
+
2114
+ The configuration, built apart from the call:
2115
+
2116
+ ```typescript
2117
+ import { z } from 'zod';
2118
+ import { createIntegrations } from '@niscorp/moss/integrations';
2119
+ import type { ExtensionConfig, Integrations, IntegrationsConfig, RegisteredIntegration } from '@niscorp/moss/integrations';
2120
+
2121
+ const Listing = z.object({ title: z.string(), press: z.array(z.string()).default([]) }).strict();
2122
+ type Listing = z.infer<typeof Listing>;
2123
+
2124
+ const extension: ExtensionConfig<Listing> = {
2125
+ schema: Listing,
2126
+ // A press image is a path of the integration's own.
2127
+ check: (listing, bundle) => listing.press.filter((path) => !path.startsWith(`/integrations/${bundle.integration}/`)).map((path) => `press "${path}": not under this integration's own prefix`),
2128
+ // Copied once, at import: the listing never depends on the vendor's service again.
2129
+ prepare: async (listing, bundle) => ({ ...listing, press: await Promise.all(listing.press.map((path) => copyToOwnStore(bundle.url, path))) }),
2130
+ };
2131
+ const config: IntegrationsConfig<Listing> = { extension, signingSeed: process.env['SIGNING_SEED'] };
2132
+ const integrations: Integrations<Listing> = createIntegrations(config);
2133
+ const approved = async (): Promise<RegisteredIntegration<Listing>[]> => (await integrations.listIntegrations()).filter((integration) => integration.status === 'approved');
2134
+ ```
2135
+
2136
+ #### `createAssertionSigner(seed?)`
2137
+
2138
+ `{ verifyKey, mint(claims, ttlMs?) }` — the ed25519 assertion the feature signs
2139
+ every call to an integration with, for a check or a service in the same
2140
+ workspace that wants to mint or hold one. An integration verifies it against
2141
+ `GET /api/integrations/verify-key`.
2142
+
2143
+ `seed` is 32 bytes as base64, and makes the same keypair wherever it is given:
2144
+ it is what the feature is given as `signingSeed`. With no seed (absent, or
2145
+ the empty string) a keypair is generated and kept nowhere. **A seed that is
2146
+ given and decodes to fewer than 32 bytes throws**, when the signer is made,
2147
+ which for a server is while it boots: `moss: the signing seed decodes to 13
2148
+ bytes, and a signing key is 32. …` The sentence says the length and never the
2149
+ seed. It used to be dropped without a word and a random key made in its place.
2150
+ A seed longer than 32 bytes is its first 32.
2151
+
2152
+ ```typescript
2153
+ import { createAssertionSigner } from '@niscorp/moss/integrations';
2154
+
2155
+ // a check of an integration's own service: it is given the public half, and
2156
+ // is then called with what a deployment would have signed
2157
+ const signer = createAssertionSigner();
2158
+ process.env['VERIFY_KEY'] = signer.verifyKey;
2159
+ const assertion = signer.mint({ integration: 'belts', principal: 'usr_ada', scope: { studioId: 'st_north' } });
2160
+ ```
2161
+
2162
+ ## `@niscorp/moss/tide`
2163
+
2164
+ A committed write, minted into [tide](../tide/README.md) as a fact. A feature:
2165
+ an app that runs tide creates it and names it in `features`. It is what moss
2166
+ keeps of hosting tide; the store and the driver are tide's own.
2167
+
2168
+ ```typescript
2169
+ import { createTideFacts } from '@niscorp/moss/tide';
2170
+
2171
+ const app = defineApp({ charter, actions, features: [createTideFacts({ tide: () => driver, identity, chain })] });
2172
+ ```
2173
+
2174
+ - `createTideFacts(config: TideFactsConfig)` — the feature an app names in
2175
+ `features`. The server starts it; it hears each committed write, and keeps no
2176
+ table.
2177
+ - `TideFactsConfig` — `{ tide: () => Pick<Tide, 'ingest'> | undefined;
2178
+ identity: (scope) => string | undefined; chain?: (scope, hints) => hints |
2179
+ undefined }`. What each is asked, and when, is under
2180
+ [Reacting to writes](#reacting-to-writes). `ingest` is the one verb the
2181
+ feature calls: a `Tide` and a `TideDriver` each have it.
2182
+
2183
+ `@niscorp/tide` is an optional peer of moss, and this entry is the only one
2184
+ that names it, as a type: an app that imports this entry has tide installed.
2185
+
2186
+ ```typescript
2187
+ import { createTideFacts } from '@niscorp/moss/tide';
2188
+ import type { TideFactsConfig } from '@niscorp/moss/tide';
2189
+
2190
+ const facts: TideFactsConfig = {
2191
+ tide: () => driver,
2192
+ identity: (scope) => (typeof scope['studioId'] === 'string' ? `automation@${scope['studioId']}` : undefined),
2193
+ };
2194
+ const app = defineApp({ charter, actions, features: [createTideFacts(facts)] });
2195
+ ```
2196
+
2197
+ ## `@niscorp/moss/protocol`
2198
+
2199
+ For code that speaks the wire itself: a client written by hand (a check that
2200
+ opens a socket and reads frames), or a transport other than the one in
2201
+ `@niscorp/moss/node`. A terminal uses `@niscorp/moss/client`, and an app
2202
+ served by `nisc` or `serve` needs none of this. It exports `PROTOCOL`,
2203
+ `offerToken`, `CLOSE_INVALID_TOKEN`, `CLOSE_SIGNED_OUT` and the types
2204
+ `ServerMessage` and `Connection`, each described under
2205
+ [The socket protocol](#the-socket-protocol).
2206
+
2207
+ ## `@niscorp/moss/unverified`
2208
+
2209
+ `unverifiedShell(session)` — the whole nova `Shell` of a session, for code that
2210
+ goes around moss: see [`FunctionSession`](#functionsession).
1082
2211
 
1083
2212
  ## `@niscorp/moss/client`
1084
2213
 
1085
- - `createWire(config?): Wire` — the app end of the socket. `config = { url?,
1086
- env?, delta?, initial?, path? }`. Plain TypeScript, no React, no globals — everything
2214
+ - `createWire(config?): Wire` — the app end of the socket. `config` is a
2215
+ `WireConfig`: `{ url?, env?, delta?, initial?, path? }`. Plain TypeScript, no React, no globals — everything
1087
2216
  host-shaped comes in as a `WireEnv`. `delta` (default `false`) advertises
1088
2217
  that this terminal can rebuild frame deltas; the snapshot it produces is
1089
- identical either way. See [Wire size](#wire-size).
2218
+ identical either way. See [Wire size](#wire-size). `env` defaults to
2219
+ `browserEnv()`, and `url` (the socket's address) to `env.defaultUrl()`.
1090
2220
  - `WireEnv` — the host seam: `{ tokens: { load, save, clear, held?, key? },
1091
2221
  socket({ url, offered }), defaultUrl() }`. The socket API is WHATWG-standard
1092
2222
  in every host (browser, Node ≥22, Bun); an env only constructs it —
@@ -1123,14 +2253,18 @@ Requires the optional `vite` peer.
1123
2253
  is `false`, the wire does not connect and `status()` is `'static'`. `reset()`,
1124
2254
  or a token arriving, connects after all.
1125
2255
  - `Wire` — `{ subscribe, snapshot, status, dispatch(canvas, event), publish,
1126
- reset, back, popTo(canvas, instance), dispose }`. `snapshot()` is `{ frame, trees }`; `status()` is
1127
- `'connecting' | 'open' | 'closed' | 'incompatible' | 'static'` and changes notify subscribers like
2256
+ reset, back, popTo(canvas, instance), dispose }`. `snapshot()` is a
2257
+ `WireSnapshot`, `{ frame, trees }`, where `trees` is a map from a canvas's id
2258
+ to its tree. `status()` is a `WireStatus`,
2259
+ `'connecting' | 'open' | 'closed' | 'incompatible' | 'static'`, and changes notify subscribers like
1128
2260
  snapshot changes do (a renderer must be able to tell a dead socket from an
1129
2261
  empty app). Hand it to a renderer.
1130
2262
 
1131
2263
  Reconnect is exponential backoff with jitter, capped at 30s, reset when a
1132
- connection opens and on any principal change (a session grant or a close-code
1133
- recovery starts the backoff clean). Two close codes are recoveries, not retries: `4403`
2264
+ connection is served its first frame and on any principal change (a session
2265
+ grant or a close-code recovery starts the backoff clean). Not when the socket
2266
+ opens: a server opens a connection before it refuses it (`4503`, `4500`), so
2267
+ a terminal that is refused each time waits longer each time. Two close codes are recoveries, not retries: `4403`
1134
2268
  (signed out) and `4401` (invalid token) both drop the stored token and
1135
2269
  reconnect anonymous — retrying with a stale token would loop forever. A
1136
2270
  `4426` (protocol mismatch, either direction) is neither: the wire stops and
@@ -1145,7 +2279,15 @@ you a throwaway anonymous shell and signing back in reattaches to the same
1145
2279
  wreck. On an open socket it sends `{ type: 'reset' }` and the fresh frame
1146
2280
  arrives on that same socket — same session, same token, nothing signed out. On
1147
2281
  a dead one it reconnects immediately instead of waiting out the backoff, which
1148
- is the same recovery a layer down.
2282
+ is the same recovery a layer down. It is also the way out of `incompatible`,
2283
+ once the server has been updated: the connection it makes is found compatible
2284
+ or not on its own account, and is retried like any other when it drops.
2285
+
2286
+ **The wire holds one socket at a time.** Before it makes one it lets go of the
2287
+ one it had: its handlers come off and it is closed. That one may have closed
2288
+ already, may have carried another principal, or may be a connect still in
2289
+ flight when `reset()` was called; whichever, nothing it says afterwards is
2290
+ heard, and its closing schedules nothing.
1149
2291
 
1150
2292
  **Nothing is sent on a socket that is not open, and nothing is queued.**
1151
2293
  `dispatch` and `publish` are dropped unless `status()` is `'open'` — the posture
@@ -1192,10 +2334,11 @@ in the subpaths.
1192
2334
  events back.
1193
2335
  - `mountTerminal(config): { swap, reset, back, destroy }` — the switcher:
1194
2336
  hot-swaps render targets over ONE wire, so the socket, session, and current
1195
- trees survive the swap. `config = { targets, swapKey?, resetKey?, trapBack?,
1196
- initial?, wire?, url? }` — targets by name, cycled in insertion order;
2337
+ trees survive the swap. `config` is a `MountTerminalConfig`: `{ targets,
2338
+ swapKey?, resetKey?, trapBack?, initial?, wire?, url? }` — targets by name, cycled in insertion order;
1197
2339
  `swapKey` (e.g. `"ctrl+shift+y"`) binds the hotkey, and `swap` is returned for
1198
- a host's own control. Omit `wire` and the terminal makes (and owns) one; `url`
2340
+ a host's own control. `initial` names the target that is mounted first
2341
+ (default: the first). Omit `wire` and the terminal makes (and owns) one; `url`
1199
2342
  seeds it. `resetKey` binds `wire.reset()` — the escape hatch, on a keystroke
1200
2343
  because it has to work when every surface on screen is dead. Both hotkeys are
1201
2344
  browser-only (they listen on `window`); a TTY or Node host binds `swap` and
@@ -1215,14 +2358,37 @@ in the subpaths.
1215
2358
  come, are a projection of the shell's own location — and the gesture is
1216
2359
  already here.
1217
2360
  - `TerminalApi` — what a target renders against: nova core's `RenderApi`
1218
- (`frame`, `canvasTree`, `dispatch`, `publish`), aliased not redeclared — the
1219
- DOM adapter, the React adapter, and the conductor share one contract. A
1220
- target never touches the wire directly.
2361
+ (`frame`, `canvasTree`, `dispatch`, `publish`), not redeclared — the DOM
2362
+ adapter, the React adapter, and the conductor share one contract — and
2363
+ beside it `status(): WireStatus`, the connection's status. A target never
2364
+ touches the wire directly.
1221
2365
  - `Target` — `(api) => TerminalMount` where `TerminalMount = { update,
1222
2366
  destroy }`. The render surface (a DOM root, a stdio pair) is construction
1223
2367
  config on the concrete target, never part of the contract — the conductor
1224
2368
  is surface-blind and runs anywhere the wire does. Renders once on mount;
1225
- the conductor calls `update` on every wire change.
2369
+ the conductor calls `update` on every wire change: a frame, a tree, the
2370
+ status.
2371
+
2372
+ **The connection's status reaches every target, the same way.** When a
2373
+ connection drops, the trees the terminal holds stay on screen: a reconnect
2374
+ re-sends the current ones, and blanking in between would show a working app as
2375
+ an empty one. So a screen left up by a dead socket looks exactly like a live
2376
+ one, and every target is told which it is: `api.status()` is `'connecting' |
2377
+ 'open' | 'closed' | 'incompatible' | 'static'`, pulled like the frame and the
2378
+ trees, and a change of it is an `update`. What a target does with it:
2379
+
2380
+ | Target | What it does |
2381
+ |---|---|
2382
+ | `terminal/react`, `terminal/vue`, `terminal/dom` | Says it on its root element, `data-wire-status="closed"`, from mount to destroy. Draws nothing. |
2383
+ | `terminal/tty` | Prints a line for each real change: `… connecting`, `✓ connected`, `× connection lost — retrying`. |
2384
+ | `terminal/ink` | Shows a line above the screen for as long as it is not open. |
2385
+ | a target of the app's own | Reads `api.status()` where it paints. |
2386
+
2387
+ What a lost connection LOOKS like in a browser is the app's: its kit's
2388
+ stylesheet (`[data-wire-status='closed'] { … }`), or a component of its kit
2389
+ that reads the status from what the target provides (`TerminalApiContext`,
2390
+ `TerminalApiKey`, below) and is drawn again when it changes. Nothing in an
2391
+ action or a layout knows there is a connection.
1226
2392
 
1227
2393
  ```typescript
1228
2394
  import { mountTerminal } from '@niscorp/moss/terminal';
@@ -1245,14 +2411,15 @@ Requires the optional `react`/`react-dom` peers.
1245
2411
  component registry bound to the wire via nova's React adapter, rendered
1246
2412
  into `root`. Registers wire-backed `CanvasSlot` and `ActionSlot` (the
1247
2413
  terminal has no shell for nova's shell-backed ones).
1248
- - `registerWireSlots(registry, { slotWrapper?, fallback?, textWrapper?,
1249
- errorMarker?, canvasProvider?, instanceProvider? })` + `TerminalApiContext` — the wire-backed
1250
- slots themselves, shared by every react-shaped target (`terminal/ink`
1251
- imports them); a custom react-shaped target starts here.
2414
+ - `TerminalApiContext` — the `TerminalApi` the target renders against, for a
2415
+ kit component that needs the wire itself:
2416
+ `useContext(TerminalApiContext)?.status()` is the connection's status, and
2417
+ the component is drawn again on every update.
1252
2418
  - `TerminalSlotWrapper` — an app component wrapping each action instance at
1253
2419
  the `ActionSlot` boundary; the terminal twin of nova's client-shell
1254
- SlotWrapper. Served trees carry identity only, so the props are
1255
- `{ canvasId, instanceId, definitionId }` — `definitionId`, not `action`.
2420
+ SlotWrapper. Served trees carry identity only, so its props
2421
+ (`TerminalSlotWrapperProps`) are `{ canvasId, instanceId, definitionId }`
2422
+ and the content as `children` — `definitionId`, not `action`.
1256
2423
  - **Adoption.** A `root` that already holds elements, on a wire that has a
1257
2424
  frame, was drawn on the server from the snapshot the wire started from: the
1258
2425
  target adopts those elements (`hydrateRoot`) instead of replacing them. An
@@ -1262,9 +2429,15 @@ Requires the optional `react`/`react-dom` peers.
1262
2429
  ### `@niscorp/moss/terminal/react/server`
1263
2430
 
1264
2431
  - `renderSnapshot({ snapshot, registry, slotWrapper? }): string` — the React
1265
- target, drawing to a string: the same registry, the same wire slots and the
1266
- same tree as the browser's target, so what a server writes is what the browser
2432
+ target, drawing to a string (its argument is this entry's
2433
+ `RenderSnapshotConfig`): the same registry, the same wire slots and the
2434
+ same frame as the browser's target, so what a server writes is what the browser
1267
2435
  adopts. Its own entry, so a browser bundle never carries `react-dom/server`.
2436
+ `snapshot` is `{ frame, trees, live? }` — what `shells.snapshot` answers is
2437
+ one. It is drawn with the status the page's terminal starts in: `'static'`
2438
+ when `live` is `false` (no socket is opened for that page), `'connecting'`
2439
+ otherwise. So a kit component that draws the status draws the same thing on
2440
+ both sides. The same holds for the Vue entry below.
1268
2441
 
1269
2442
  **What a kit owes a server-drawn page.** The first pass in the browser must
1270
2443
  draw exactly what the server drew, so nothing that differs between the two may
@@ -1286,7 +2459,8 @@ wire and target, and assert React said nothing (atrium's and lyra's `ssr-check`)
1286
2459
  Requires the optional `vue` peer.
1287
2460
 
1288
2461
  - `vueTarget({ root, registry, slotWrapper? }): Target` — the app's Vue
1289
- component registry bound to the wire via nova's Vue adapter, mounted on
2462
+ component registry bound to the wire via nova's Vue adapter (its argument is
2463
+ `VueTargetConfig`), mounted on
1290
2464
  `root` with `createApp`. Registers wire-backed `CanvasSlot` and
1291
2465
  `ActionSlot` — the same origin rule as the react target (an event from
1292
2466
  inside an instance boundary carries that instance as `origin` unless it
@@ -1294,21 +2468,20 @@ Requires the optional `vue` peer.
1294
2468
  depend on a revision the conductor bumps, so only the frame and the canvas
1295
2469
  slots re-render and Vue patches in place — focus and input drafts survive.
1296
2470
  - `TerminalApiKey` — the injection key of the live `TerminalApi` (a kit
1297
- component reading `frame()` / `canvasTree()` in its render re-renders on
1298
- wire updates).
2471
+ component reading `frame()` / `canvasTree()` / `status()` in its render
2472
+ re-renders on wire updates).
1299
2473
  - `TerminalSlotWrapper` — a Vue component wrapping each action instance at
1300
2474
  the `ActionSlot` boundary, handed `{ canvasId, instanceId, definitionId }`
1301
- as props and the content as its default slot.
2475
+ as props (`TerminalSlotWrapperProps`) and the content as its default slot.
1302
2476
  - **Adoption**, as the react target: a root that holds server-drawn elements,
1303
2477
  on a wire with a frame, is mounted with `createSSRApp` and adopted.
1304
- - `registerWireSlots(registry, slotWrapper)`, `terminalFrame(api, registry)` —
1305
- the wire slots and the frame component, shared with the server entry.
1306
2478
 
1307
2479
  ### `@niscorp/moss/terminal/vue/server`
1308
2480
 
1309
2481
  - `renderSnapshot({ snapshot, registry, slotWrapper? }): Promise<string>` — the
1310
2482
  Vue target, drawing to a string through Vue's own server renderer (which is
1311
- asynchronous, so this is).
2483
+ asynchronous, so this is). Its argument is this entry's
2484
+ `RenderSnapshotConfig`.
1312
2485
 
1313
2486
  ## `@niscorp/moss/terminal/dom`
1314
2487
 
@@ -1326,25 +2499,29 @@ Requires the optional `vue` peer.
1326
2499
  ### `@niscorp/moss/terminal/dom/server`
1327
2500
 
1328
2501
  - `renderSnapshot({ snapshot, registry?, window }): string` — the DOM target,
1329
- drawing to a string. A DOM kit builds real elements, so the host hands in a
2502
+ drawing to a string (its argument is this entry's `RenderSnapshotConfig`). A DOM kit builds real elements, so the host hands in a
1330
2503
  DOM to build them in (`window`: jsdom, happy-dom, linkedom — moss depends on
1331
- none). A kit's components name `document` as a global, so for the length of
2504
+ none). Omit `registry` for nova's default kit, as on `domTarget`.
2505
+ A kit's components name `document` as a global, so for the length of
1332
2506
  one draw — synchronous, start to end — the window's names are lent to the
1333
2507
  global scope and taken back whatever happens.
1334
2508
 
1335
2509
  ## `@niscorp/moss/terminal/tty`
1336
2510
 
1337
- - `ttyTarget({ input, output, registry?, fallback?, onQuit?, status?,
1338
- debounceMs?, prompt? }): Target` — the line-terminal target: a REPL over
1339
- the wire. Pass `status: wire.status` and the REPL reports connection
1340
- transitions (`… connecting`, `✓ connected`, `× connection lost — retrying`)
1341
- — once per real transition, never the backoff flap.
2511
+ - `ttyTarget({ input, output, registry?, fallback?, onQuit?, debounceMs?,
2512
+ prompt? }): Target` — the line-terminal target: a REPL over the wire (its
2513
+ argument is `TtyTargetConfig`). It
2514
+ reports the connection's status (`… connecting`, `✓ connected`,
2515
+ `× connection lost — retrying`) — once per real transition, never the
2516
+ backoff flap.
1342
2517
  nova's TTY adapter renders each served frame to text with numbered `[n]`
1343
2518
  markers; commands map onto them with the same event vocabulary every other
1344
2519
  target dispatches. Runs on any Readable/Writable pair — a real TTY, a
1345
2520
  test's PassThrough, a pipe. `onQuit` fires on `quit`/EOF (the host owns
1346
2521
  the wire and the process); `debounceMs` (default 80) coalesces a burst of
1347
- wire updates into one repaint.
2522
+ wire updates into one repaint, and `0` paints at once. Omit `registry` for
2523
+ nova's default TTY kit; `fallback` draws a component the kit has no entry
2524
+ for (default: nova's). `prompt` defaults to `› `.
1348
2525
 
1349
2526
  Typing IS the input scheme — numbers act, words fill: a bare number taps
1350
2527
  `[n]` (click a button or row, flip a toggle, focus an input — the next line
@@ -1365,26 +2542,32 @@ createTerminal({ target: ttyTarget({ input: process.stdin, output: process.stdou
1365
2542
 
1366
2543
  ## `@niscorp/moss/terminal/ink`
1367
2544
 
1368
- - `inkTarget({ registry?, slotWrapper?, stdin?, stdout?, status?, onQuit?, patchConsole? }):
1369
- Target` — the full-screen terminal target: nova's Ink kit
2545
+ - `inkTarget({ registry?, slotWrapper?, stdin?, stdout?, onQuit?, patchConsole? }):
2546
+ Target` — the full-screen terminal target (its argument is
2547
+ `InkTargetConfig`, every field optional): nova's Ink kit
1370
2548
  (`@niscorp/nova/adapters/ink`) on the React adapter's walker, mounted with
1371
- ink's renderer. Interaction is the TTY REPL's numbered addressing plus
2549
+ ink's renderer. `registry` puts the app's own Ink kit in its place.
2550
+ Interaction is the TTY REPL's numbered addressing plus
1372
2551
  live focus: every interactive shows a `[n]` marker (the numbering is the
1373
2552
  TTY walker run over the same served trees — `[7]` is the same thing in
1374
2553
  the REPL and the TUI), and typed digits act on it — buttons and rows
1375
2554
  click, toggles flip, an input takes focus and typing types (a focused
1376
2555
  input claims digits as text; multi-digit numbers accumulate for a beat,
1377
- unambiguous ones act at once). Tab/Shift+Tab and ↑/↓ still walk the focus
1378
- ring; Enter activates; Ctrl+C leaves (`onQuit` fires). Inputs are
1379
- draft-preserving and `debounce`-honoring (ADAPTER.md §6). `status:
1380
- wire.status` renders a dim connection line while the socket is not open.
1381
- The wire-backed slots are shared with `terminal/react` — same seam,
1382
- different renderer. `patchConsole` (default on) routes the process's
2556
+ unambiguous ones act at once, and digits that arrive together are the
2557
+ number they spell). Tab/Shift+Tab and ↑/↓ still walk the focus ring; Enter
2558
+ activates; Ctrl+C leaves. Inputs are draft-preserving and
2559
+ `debounce`-honoring (ADAPTER.md §6). A line above the screen says the
2560
+ connection's status while the socket is not open. The wire-backed slots
2561
+ are shared with `terminal/react` — same seam, different renderer.
2562
+ `onQuit` is the terminal ending, and the host's to act on (it owns the wire
2563
+ and the process): the person left, or a component of the kit threw and ink
2564
+ ended the app, which is logged and ends that one terminal. It is not called
2565
+ for a `destroy`, which is the host's own doing. `patchConsole` (default on) routes the process's
1383
2566
  console above the frame; a host rendering several targets in one process
1384
2567
  (an SSH server, one per connection) turns it off, so its own logs never
1385
2568
  reach whoever is connected. ESM-only, like ink.
1386
2569
 
1387
2570
  ```typescript
1388
2571
  import { inkTarget } from '@niscorp/moss/terminal/ink';
1389
- createTerminal({ target: inkTarget({ status: wire.status }), wire });
2572
+ createTerminal({ target: inkTarget(), wire });
1390
2573
  ```