@eloxiv/cli 0.0.0-stage → 0.1.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 (294) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/AgentSkills.d.ts +51 -0
  4. package/dist/AgentSkills.d.ts.map +1 -0
  5. package/dist/AgentSkills.js +264 -0
  6. package/dist/AgentSkills.js.map +1 -0
  7. package/dist/AgentWeb.d.ts +83 -0
  8. package/dist/AgentWeb.d.ts.map +1 -0
  9. package/dist/AgentWeb.js +436 -0
  10. package/dist/AgentWeb.js.map +1 -0
  11. package/dist/App.d.ts +213 -0
  12. package/dist/App.d.ts.map +1 -0
  13. package/dist/App.js +357 -0
  14. package/dist/App.js.map +1 -0
  15. package/dist/Blueprint.d.ts +47 -0
  16. package/dist/Blueprint.d.ts.map +1 -0
  17. package/dist/Blueprint.js +241 -0
  18. package/dist/Blueprint.js.map +1 -0
  19. package/dist/Brand.d.ts +42 -0
  20. package/dist/Brand.d.ts.map +1 -0
  21. package/dist/Brand.js +370 -0
  22. package/dist/Brand.js.map +1 -0
  23. package/dist/Changelog.d.ts +22 -0
  24. package/dist/Changelog.d.ts.map +1 -0
  25. package/dist/Changelog.js +117 -0
  26. package/dist/Changelog.js.map +1 -0
  27. package/dist/Cli.d.ts +17 -0
  28. package/dist/Cli.d.ts.map +1 -0
  29. package/dist/Cli.js +810 -0
  30. package/dist/Cli.js.map +1 -0
  31. package/dist/DbAdmin.d.ts +18 -0
  32. package/dist/DbAdmin.d.ts.map +1 -0
  33. package/dist/DbAdmin.js +91 -0
  34. package/dist/DbAdmin.js.map +1 -0
  35. package/dist/Dependencies.d.ts +53 -0
  36. package/dist/Dependencies.d.ts.map +1 -0
  37. package/dist/Dependencies.js +132 -0
  38. package/dist/Dependencies.js.map +1 -0
  39. package/dist/Deploy.d.ts +39 -0
  40. package/dist/Deploy.d.ts.map +1 -0
  41. package/dist/Deploy.js +458 -0
  42. package/dist/Deploy.js.map +1 -0
  43. package/dist/Docs.d.ts +71 -0
  44. package/dist/Docs.d.ts.map +1 -0
  45. package/dist/Docs.js +240 -0
  46. package/dist/Docs.js.map +1 -0
  47. package/dist/Doctor.d.ts +56 -0
  48. package/dist/Doctor.d.ts.map +1 -0
  49. package/dist/Doctor.js +368 -0
  50. package/dist/Doctor.js.map +1 -0
  51. package/dist/Dossier.d.ts +23 -0
  52. package/dist/Dossier.d.ts.map +1 -0
  53. package/dist/Dossier.js +92 -0
  54. package/dist/Dossier.js.map +1 -0
  55. package/dist/Emit.d.ts +26 -0
  56. package/dist/Emit.d.ts.map +1 -0
  57. package/dist/Emit.js +51 -0
  58. package/dist/Emit.js.map +1 -0
  59. package/dist/Errors.d.ts +26 -0
  60. package/dist/Errors.d.ts.map +1 -0
  61. package/dist/Errors.js +17 -0
  62. package/dist/Errors.js.map +1 -0
  63. package/dist/Evals.d.ts +52 -0
  64. package/dist/Evals.d.ts.map +1 -0
  65. package/dist/Evals.js +126 -0
  66. package/dist/Evals.js.map +1 -0
  67. package/dist/Files.d.ts +47 -0
  68. package/dist/Files.d.ts.map +1 -0
  69. package/dist/Files.js +145 -0
  70. package/dist/Files.js.map +1 -0
  71. package/dist/Generate.d.ts +80 -0
  72. package/dist/Generate.d.ts.map +1 -0
  73. package/dist/Generate.js +310 -0
  74. package/dist/Generate.js.map +1 -0
  75. package/dist/Guards.d.ts +45 -0
  76. package/dist/Guards.d.ts.map +1 -0
  77. package/dist/Guards.js +530 -0
  78. package/dist/Guards.js.map +1 -0
  79. package/dist/Inspect.d.ts +125 -0
  80. package/dist/Inspect.d.ts.map +1 -0
  81. package/dist/Inspect.js +270 -0
  82. package/dist/Inspect.js.map +1 -0
  83. package/dist/Keychain.d.ts +57 -0
  84. package/dist/Keychain.d.ts.map +1 -0
  85. package/dist/Keychain.js +73 -0
  86. package/dist/Keychain.js.map +1 -0
  87. package/dist/Lock.d.ts +13 -0
  88. package/dist/Lock.d.ts.map +1 -0
  89. package/dist/Lock.js +145 -0
  90. package/dist/Lock.js.map +1 -0
  91. package/dist/Mcp.d.ts +91 -0
  92. package/dist/Mcp.d.ts.map +1 -0
  93. package/dist/Mcp.js +128 -0
  94. package/dist/Mcp.js.map +1 -0
  95. package/dist/Merge.d.ts +18 -0
  96. package/dist/Merge.d.ts.map +1 -0
  97. package/dist/Merge.js +43 -0
  98. package/dist/Merge.js.map +1 -0
  99. package/dist/Migrate.d.ts +78 -0
  100. package/dist/Migrate.d.ts.map +1 -0
  101. package/dist/Migrate.js +288 -0
  102. package/dist/Migrate.js.map +1 -0
  103. package/dist/Plugins.d.ts +36 -0
  104. package/dist/Plugins.d.ts.map +1 -0
  105. package/dist/Plugins.js +304 -0
  106. package/dist/Plugins.js.map +1 -0
  107. package/dist/Postgres.d.ts +73 -0
  108. package/dist/Postgres.d.ts.map +1 -0
  109. package/dist/Postgres.js +294 -0
  110. package/dist/Postgres.js.map +1 -0
  111. package/dist/Publish.d.ts +23 -0
  112. package/dist/Publish.d.ts.map +1 -0
  113. package/dist/Publish.js +59 -0
  114. package/dist/Publish.js.map +1 -0
  115. package/dist/Registry.d.ts +539 -0
  116. package/dist/Registry.d.ts.map +1 -0
  117. package/dist/Registry.js +340 -0
  118. package/dist/Registry.js.map +1 -0
  119. package/dist/Remote.d.ts +90 -0
  120. package/dist/Remote.d.ts.map +1 -0
  121. package/dist/Remote.js +1006 -0
  122. package/dist/Remote.js.map +1 -0
  123. package/dist/Run.d.ts +120 -0
  124. package/dist/Run.d.ts.map +1 -0
  125. package/dist/Run.js +477 -0
  126. package/dist/Run.js.map +1 -0
  127. package/dist/SyncGen.d.ts +118 -0
  128. package/dist/SyncGen.d.ts.map +1 -0
  129. package/dist/SyncGen.js +392 -0
  130. package/dist/SyncGen.js.map +1 -0
  131. package/dist/Update.d.ts +301 -0
  132. package/dist/Update.d.ts.map +1 -0
  133. package/dist/Update.js +627 -0
  134. package/dist/Update.js.map +1 -0
  135. package/dist/bin.d.ts +3 -0
  136. package/dist/bin.d.ts.map +1 -0
  137. package/dist/bin.js +42 -0
  138. package/dist/bin.js.map +1 -0
  139. package/dist/docs/backlog.md +56 -0
  140. package/dist/docs/ci.md +277 -0
  141. package/dist/docs/cli.md +696 -0
  142. package/dist/docs/connectors/google.md +115 -0
  143. package/dist/docs/connectors/http-openapi.md +7 -0
  144. package/dist/docs/connectors/mcp.md +8 -0
  145. package/dist/docs/connectors/microsoft-graph.md +75 -0
  146. package/dist/docs/connectors/openai.md +25 -0
  147. package/dist/docs/connectors/slack.md +162 -0
  148. package/dist/docs/connectors/workos.md +39 -0
  149. package/dist/docs/contracts/README.md +173 -0
  150. package/dist/docs/contracts/action-consent.md +92 -0
  151. package/dist/docs/contracts/action-registry.md +85 -0
  152. package/dist/docs/contracts/actor.md +100 -0
  153. package/dist/docs/contracts/agent-resources.md +90 -0
  154. package/dist/docs/contracts/agent-runtime.md +257 -0
  155. package/dist/docs/contracts/approvals.md +126 -0
  156. package/dist/docs/contracts/audit.md +75 -0
  157. package/dist/docs/contracts/auth-provider.md +74 -0
  158. package/dist/docs/contracts/calendar-provider.md +46 -0
  159. package/dist/docs/contracts/client-sdk.md +245 -0
  160. package/dist/docs/contracts/collab-document.md +151 -0
  161. package/dist/docs/contracts/command.md +44 -0
  162. package/dist/docs/contracts/connections.md +235 -0
  163. package/dist/docs/contracts/context-accounting.md +50 -0
  164. package/dist/docs/contracts/daemon.md +243 -0
  165. package/dist/docs/contracts/db-tx.md +53 -0
  166. package/dist/docs/contracts/delegation.md +68 -0
  167. package/dist/docs/contracts/device-control.md +103 -0
  168. package/dist/docs/contracts/directory-provider.md +36 -0
  169. package/dist/docs/contracts/directory.md +161 -0
  170. package/dist/docs/contracts/document-source.md +33 -0
  171. package/dist/docs/contracts/files.md +115 -0
  172. package/dist/docs/contracts/flags.md +83 -0
  173. package/dist/docs/contracts/host.md +68 -0
  174. package/dist/docs/contracts/http-api.md +43 -0
  175. package/dist/docs/contracts/ingestion.md +130 -0
  176. package/dist/docs/contracts/ingress.md +141 -0
  177. package/dist/docs/contracts/invocation.md +260 -0
  178. package/dist/docs/contracts/local-client.md +108 -0
  179. package/dist/docs/contracts/locale.md +56 -0
  180. package/dist/docs/contracts/machine-identity.md +117 -0
  181. package/dist/docs/contracts/mail-provider.md +49 -0
  182. package/dist/docs/contracts/memory.md +53 -0
  183. package/dist/docs/contracts/messaging.md +40 -0
  184. package/dist/docs/contracts/metering.md +139 -0
  185. package/dist/docs/contracts/model-provider.md +84 -0
  186. package/dist/docs/contracts/module-manifest.md +213 -0
  187. package/dist/docs/contracts/notification-channel.md +90 -0
  188. package/dist/docs/contracts/notifications.md +123 -0
  189. package/dist/docs/contracts/outbox.md +80 -0
  190. package/dist/docs/contracts/privacy.md +110 -0
  191. package/dist/docs/contracts/progress.md +52 -0
  192. package/dist/docs/contracts/query-surface.md +108 -0
  193. package/dist/docs/contracts/readiness.md +63 -0
  194. package/dist/docs/contracts/release.md +142 -0
  195. package/dist/docs/contracts/result-rendering.md +61 -0
  196. package/dist/docs/contracts/sandbox.md +186 -0
  197. package/dist/docs/contracts/scheduler.md +148 -0
  198. package/dist/docs/contracts/screen-context.md +81 -0
  199. package/dist/docs/contracts/search.md +120 -0
  200. package/dist/docs/contracts/secrets.md +74 -0
  201. package/dist/docs/contracts/settings.md +109 -0
  202. package/dist/docs/contracts/sharing.md +77 -0
  203. package/dist/docs/contracts/slot.md +48 -0
  204. package/dist/docs/contracts/space.md +67 -0
  205. package/dist/docs/contracts/storage-adapter.md +45 -0
  206. package/dist/docs/contracts/storage-backend.md +56 -0
  207. package/dist/docs/contracts/sync.md +213 -0
  208. package/dist/docs/contracts/telemetry.md +80 -0
  209. package/dist/docs/contracts/theme-tokens.md +50 -0
  210. package/dist/docs/contracts/tool-source.md +58 -0
  211. package/dist/docs/contracts/versioning.md +99 -0
  212. package/dist/docs/contracts/view.md +65 -0
  213. package/dist/docs/contracts/work-items.md +99 -0
  214. package/dist/docs/contracts/workflow.md +82 -0
  215. package/dist/docs/decisions.md +163 -0
  216. package/dist/docs/example-app.md +192 -0
  217. package/dist/docs/getting-started.md +927 -0
  218. package/dist/docs/goal.md +54 -0
  219. package/dist/docs/parity.md +29 -0
  220. package/dist/docs/performance.md +129 -0
  221. package/dist/docs/registry/README.md +74 -0
  222. package/dist/docs/registry/app.md +38 -0
  223. package/dist/docs/registry/approvals-ui-foldkit.md +28 -0
  224. package/dist/docs/registry/calendar-ui-foldkit.md +27 -0
  225. package/dist/docs/registry/calendar.md +35 -0
  226. package/dist/docs/registry/chat-ui-foldkit.md +30 -0
  227. package/dist/docs/registry/desktop-rune.md +49 -0
  228. package/dist/docs/registry/desktop.md +32 -0
  229. package/dist/docs/registry/eloxiv-action.md +25 -0
  230. package/dist/docs/registry/eloxiv-connector.md +25 -0
  231. package/dist/docs/registry/eloxiv-module.md +25 -0
  232. package/dist/docs/registry/eloxiv-policy.md +25 -0
  233. package/dist/docs/registry/eloxiv-view.md +25 -0
  234. package/dist/docs/registry/hello-ui-foldkit.md +29 -0
  235. package/dist/docs/registry/hello.md +39 -0
  236. package/dist/docs/registry/home-ui-foldkit.md +27 -0
  237. package/dist/docs/registry/home.md +29 -0
  238. package/dist/docs/registry/inbox-ui-foldkit.md +27 -0
  239. package/dist/docs/registry/mail-ui-foldkit.md +27 -0
  240. package/dist/docs/registry/mail.md +34 -0
  241. package/dist/docs/registry/meeting-prep.md +26 -0
  242. package/dist/docs/registry/members-ui-foldkit.md +28 -0
  243. package/dist/docs/registry/mobile.md +37 -0
  244. package/dist/docs/registry/notes-ui-foldkit.md +27 -0
  245. package/dist/docs/registry/notes.md +26 -0
  246. package/dist/docs/registry/people-ui-foldkit.md +28 -0
  247. package/dist/docs/registry/people.md +38 -0
  248. package/dist/docs/registry/shell-foldkit.md +34 -0
  249. package/dist/docs/registry/theme.md +25 -0
  250. package/dist/docs/registry/ui-conformance.md +30 -0
  251. package/dist/docs/release.md +100 -0
  252. package/dist/docs/scaffold.md +826 -0
  253. package/dist/docs/security/threat-model.md +299 -0
  254. package/dist/docs/upstream/zero-cache-socket-handoff.md +105 -0
  255. package/dist/index.d.ts +8 -0
  256. package/dist/index.d.ts.map +1 -0
  257. package/dist/index.js +8 -0
  258. package/dist/index.js.map +1 -0
  259. package/package.json +48 -3
  260. package/src/AgentSkills.ts +329 -0
  261. package/src/AgentWeb.ts +507 -0
  262. package/src/App.ts +435 -0
  263. package/src/Blueprint.ts +276 -0
  264. package/src/Brand.ts +415 -0
  265. package/src/Changelog.ts +136 -0
  266. package/src/Cli.ts +1458 -0
  267. package/src/DbAdmin.ts +115 -0
  268. package/src/Dependencies.ts +170 -0
  269. package/src/Deploy.ts +563 -0
  270. package/src/Docs.ts +309 -0
  271. package/src/Doctor.ts +424 -0
  272. package/src/Dossier.ts +148 -0
  273. package/src/Emit.ts +68 -0
  274. package/src/Errors.ts +18 -0
  275. package/src/Evals.ts +153 -0
  276. package/src/Files.ts +152 -0
  277. package/src/Generate.ts +402 -0
  278. package/src/Guards.ts +541 -0
  279. package/src/Inspect.ts +358 -0
  280. package/src/Keychain.ts +107 -0
  281. package/src/Lock.ts +174 -0
  282. package/src/Mcp.ts +159 -0
  283. package/src/Merge.ts +70 -0
  284. package/src/Migrate.ts +331 -0
  285. package/src/Plugins.ts +347 -0
  286. package/src/Postgres.ts +353 -0
  287. package/src/Publish.ts +64 -0
  288. package/src/Registry.ts +405 -0
  289. package/src/Remote.ts +1158 -0
  290. package/src/Run.ts +541 -0
  291. package/src/SyncGen.ts +570 -0
  292. package/src/Update.ts +873 -0
  293. package/src/bin.ts +46 -0
  294. package/src/index.ts +7 -0
@@ -0,0 +1,75 @@
1
+ # Audit
2
+
3
+ One record per invocation: who called which action, from which surface, in which organisation, with what input (by hash), and how it ended.
4
+
5
+ - Kind: kernel service. Version 1.3.0 (1.1.0: surface `sync`, optimistic writes pushed from replicas; 1.3.0: lineage, change summaries, and the organisation's reads and exports, `records` and `export`).
6
+ - Schema: [`packages/contracts/schema/contracts/Audit.json`](../../packages/contracts/schema/contracts/Audit.json) (source [`Audit.ts`](../../packages/contracts/src/contracts/Audit.ts)); the record alone is also [`schema/AuditRecord.json`](../../packages/contracts/schema/AuditRecord.json).
7
+ - Implementation: the `Audit` service in [`packages/kernel/src/Audit.ts`](../../packages/kernel/src/Audit.ts), table `eloxiv.audit_log`; written by [`Invocation.ts`](../../packages/kernel/src/Invocation.ts); read by the kernel module `auditModule` ([`audit/module.ts`](../../packages/kernel/src/audit/module.ts): actions `audit.records` and `audit.export`).
8
+ - Kit: `@eloxiv/testing/conformance/Audit` ([source](../../packages/testing/src/conformance/Audit.ts)).
9
+
10
+ ## Operations
11
+
12
+ ### `record`
13
+
14
+ Append a record (`AuditEntry`) in the current transaction. The invocation path is its only writer; modules cannot reach the log (their roles have no access to the `eloxiv` schema). No typed errors.
15
+
16
+ ### `list`
17
+
18
+ Records matching every given field of `AuditFilter` (`invocationId`, `action`, `idempotencyKey`, `outcome`), oldest first, across organisations. No typed errors. In the Eloxiv kernel it is an in-process service for the kernel and its tooling; there is no action or HTTP endpoint for it (an organisation reads its own log with `records`).
19
+
20
+ ### `records`
21
+
22
+ The action `audit.records` (install `auditModule`): one page of **the acting organisation's** records, oldest first (by time, then id), matching every given field of `AuditQuery`: `from` (inclusive) and `to` (exclusive) as ISO 8601 times, `action`, `actorUserId`, `outcome`, `surface`, `invocationId`; `limit` (1 to 1000, default 100); `after`, the previous page's `next`. Output `AuditPage`: `{ records, next }`, `next` null when there are no more now. The organisation is the caller's, never an input; a record that names no organisation (a refusal of a caller the kernel could not identify) is in no organisation's log. Needs the kernel permission `eloxiv.audit.read` in the organisation (the built-in `admin` role holds it; migration `0110_audit_lineage` grants it to existing administrators): the policy requires it and the handler checks it again. Errors: `Unauthenticated`, `Forbidden`, `InvalidInput` (a time that does not parse, a cursor this log did not issue). Each read is itself an invocation, so it is audited.
23
+
24
+ ### `export`
25
+
26
+ The action `audit.export`: the same query and page, as text a SIEM ingests (`AuditExportRequest`: the query plus `format`). Output `AuditExport`: `{ format, contentType, content, count, next }`.
27
+
28
+ - `csv` (`text/csv`): a header row of `AUDIT_CSV_COLUMNS`, then one row per record (RFC 4180 quoting, CRLF line ends). The lineage is flattened into its own columns (`origin`, `credential`, `agentRunId`, `approval`, `consentRequest`, `consentPermission`, `clientVersion`); `authority`, `changes` and `detail` are JSON in their cells. A cell starting with `=`, `+`, `-`, `@`, a tab or a carriage return is prefixed with `'`, so a spreadsheet never evaluates it as a formula.
29
+ - `ocsf` (`application/x-ndjson`): one [OCSF](https://schema.ocsf.io) 1.3.0 **API Activity** event (class 6003, category 6) per line: `activity_id` from what the call changed (1 Create, 3 Update, 4 Delete, else 99 Other; `type_uid` is 600300 plus it), `status_id` 1 for `succeeded` and `replayed` and 2 otherwise (`status_code` the outcome, `status_detail` the error tag), `severity_id` 1, 2 for `approval-required`, 3 for refusals and failures, `time` in epoch milliseconds, `metadata.uid` the record's id and `metadata.correlation_uid` its invocation id, `actor.user.uid` and `actor.invoked_by` (the origin), `api.operation` the action, `src_endpoint.svc_name` the surface, and the rest (organisation, input hash, idempotency key, completion, lineage, changes, detail) under `unmapped`.
30
+
31
+ A SIEM pulls with a service principal's API token whose role holds `eloxiv.audit.read` (HTTP `POST /api/actions/audit.export`), page by page with `after`.
32
+
33
+ ## Records
34
+
35
+ **`AuditRecord`** (`AuditEntry` plus `id` and `at`):
36
+
37
+ | Field | Meaning |
38
+ | --- | --- |
39
+ | `id`, `at` | the record's id and time (ISO 8601, UTC) |
40
+ | `invocationId` | the call's id; its outbox events carry the same id |
41
+ | `action`, `surface` | the action name as called, and `rpc`, `http`, `mcp`, `agent`, `internal`, `workflow`, `scheduler`, `cli` or `ingress`. Kernel operations audit under kernel names: `eloxiv.directory.<op>`, `eloxiv.machine.<op>` and `eloxiv.ingress.<op>` for management, `eloxiv.ingress.<source>` for refused webhook deliveries |
42
+ | `actorUserId`, `orgId` | who acted, where; `null` when the call failed before identity resolved (unauthenticated, not a member, unknown action, undecodable input) |
43
+ | `outcome` | `succeeded`, `replayed`, `denied` (`Unauthenticated`, `Forbidden`), `approval-required` or `failed` (every other error) |
44
+ | `inputHash` | sha256 of the canonical JSON (sorted keys) of the encoded input; of the raw input when it did not decode |
45
+ | `idempotencyKey` | the key the caller supplied, or `null` |
46
+ | `errorTag` | the standard error's tag, `null` on success |
47
+ | `affected`, `requested`, `completion` | for calls with declared targets: how many were affected, how many declared, `complete` or `partial`; a replay repeats the original's for best-effort actions; `null` otherwise |
48
+ | `detail` | for successful directory writes: `{ subject, before, after }`, the changed member's, role's or group's state just before and after the change (see [Directory](directory.md)); `null` otherwise |
49
+ | `lineage` | once the caller's identity resolved (`AuditLineage`; absent before, and on records written before 1.3.0): `origin` (`person`, `agent`, `system`, as the kernel decided it), `credential` (`session`, `agent-session`, `api-token`, `oauth`, `device`, or `identity` for an internal caller's execution identity), `authority` (the links the call acted under, `{ kind, id }`: an agent session, an API token, an OAuth grant, a device, a schedule, a consent, a linked identity; never the person's sign-in session, never their membership), `agentRun` (`{ runId, conversationId, step, toolCallId }` for an agent's tool call), `approval` (the business-approval request the call executed), `consent` (`{ request, permission }`: the one-time consent or remembered permission that let an agent's call through) and `clientVersion` (the version the caller declared, at most 64 characters) |
50
+ | `changes` | for a success that wrote records (`AuditChange[]`; absent otherwise): per entity (its Cedar type), how many records it inserted, updated and deleted, and their ids (at most `AUDIT_CHANGED_IDS`, 100, with `truncated`); never a value. A MAKE action's writes, committed in its module's own transaction, are not summarised |
51
+
52
+ ## Guarantees
53
+
54
+ 1. **Exactly one record per invocation** that reaches the invocation path, from any surface. The exceptions are interruption (a call whose fiber is interrupted before its transaction commits, for example when the kernel shuts down mid-call, is rolled back and leaves no record) and a flood of refusals of callers the kernel could not identify (guarantee 9).
55
+ 2. **A success's record commits with its effects.** It is written inside the call's transaction, so it exists exactly when the call's writes and outbox events do, and they share its `invocationId`. If the transaction fails at commit, after the record and events were written, none of them survives and the call is recorded as a failure. A replay writes its `replayed` record in the transaction that checks the key.
56
+ 3. **A failure is recorded once, after the rollback.** Whatever failed (action lookup, decoding, identity, policy, approval, idempotency, the handler, the record checks, the commit, a defect), the call's transaction, if it had begun, is rolled back with any record it held. Then one failure record is written in a transaction of its own. Nothing else of the call survives, with one exception: a call blocked at the approval stage keeps what that stage recorded before any transaction began: the business-approval request ([Approvals](approvals.md), with its outbox event) or the held consent ([ActionConsent](action-consent.md), with the person's work item and notification). Both outcomes are `approval-required`, with error tag `ApprovalRequired` or `ConsentRequired`.
57
+ 4. **The input is identified, not stored.** The hash is stable across key order and differs for different input.
58
+ 5. **Modules cannot read or write the log.**
59
+ 6. **Calls executed for someone name them.** An approved call runs as its requester (surface `workflow`): its record names the requester even when resolving them is refused because they left the organisation. Following an email's unsubscribe link is recorded too (`notifications.unsubscribe`, surface `http`).
60
+ 7. **Each record says what the call acted under** (`lineage`): the agent run, step and tool call an agent's call came from, the consent it ran under, the approval it executed, the credential and the authority links, decided by the kernel and never by the caller (only the declared client version is the caller's, bounded). A success's record summarises what it changed (`changes`) without any value. ([`audit-export.test.ts`](../../packages/testing/test/audit-export.test.ts))
61
+ 8. **An organisation's log is its own.** `records` and `export` read only the acting organisation's records, for a caller holding `eloxiv.audit.read` there; another organisation's records, and records that name none, never appear, whoever asks. ([`audit-export.test.ts`](../../packages/testing/test/audit-export.test.ts))
62
+ 9. **Refusals outside the invocation path are recorded as refusals on it are** (`denied`, with the error tag): the cookie guard's (`reason: "cookie-request-forgery"`, as the request's canonical action: `notebook.write` for `/api/actions/notebook.write`, `eloxiv.secrets.put` for `/kernel/secrets/put`, `POST <route>` otherwise), and a management operation's or a secret's refused for its authentication, its session's hold or its check at commit, reads included. A refusal of a caller the kernel could not identify (no credential that authenticates), here, on the invocation path, or in the directory's and dead letters' in-process operations, is bounded per action and client address: at most `authLimits.anonymousDenialsPerMinute` records a minute (`ELOXIV_ANONYMOUS_DENIALS_PER_MINUTE`, default 30), then one whose detail says the rest of the minute is only counted (`suppressed`); the count is in `eloxiv.rate_limit` (bucket `audit-denied:<what>:<address bucket>`, swept after a day). What it counts under is never a name the caller chose: a registered action's name, a route pattern for the guard's refusals (`POST /api/actions/*`, one name for every path the kernel does not list), and one name for every action the kernel does not have; the address is its bucket (an IPv6 address by its /64). The bound is the audit writer's (`Audit.record`): every record of a caller the kernel could not identify, whatever its outcome and whichever path writes it (the invocation path's failures of unidentified callers, an unknown action or input that does not decode; a management operation's input that does not decode, written before the caller is identified; MCP's refused tool calls, a request of many counting each), is bounded the same way, counted under the bucket its writer names (a registered name or a route pattern) or, when it names none, one bucket per surface; only the kernel's own records of work no caller asked for over a surface (an operator's settings, in process) are not. A path whose escapes do not decode is refused (400) and recorded the same way. A refusal of a caller the kernel identified is always recorded. [`session-commit.test.ts`](../../packages/testing/test/session-commit.test.ts) sends malformed input from no one to every route the kernel registers (each management operation of a wildcard route by name), more of it than the bound, and finds at most the bound and the note a minute for each. ([`session-commit.test.ts`](../../packages/testing/test/session-commit.test.ts))
63
+
64
+ ## How an implementation is checked
65
+
66
+ `auditConformance(start)` registers, against the fixture app: a success's single record and its fields (validated against the published schema); its outbox events share its invocation id; a call whose transaction fails at commit (a deferred constraint trigger the kit installs on the fixture's documents) leaves exactly one failure record, no success record, no row and no event; canonical input hashing; completion counts for best-effort and exact targeted calls; `succeeded`, `replayed` and an `IdempotencyConflict` failure under one key; one record for each failure (unauthenticated, unknown action, invalid input, not a member, uncompilable policy, approval required, a write the database refuses, a defect after writing) with the actor recorded once identity resolved; nothing of a failed call but its record; no access for module roles to the table the subject names as the log (`privateTables.auditLog`); one record per call under concurrent load.
67
+
68
+ The Eloxiv kernel runs it in `packages/testing/test/audit.test.ts`. `registry/test/surfaces.test.ts` proves the same record (apart from the surface) for the same call on every surface, and audited denials and invalid input on every surface.
69
+
70
+ ## Not yet guaranteed
71
+
72
+ - **Subscriber work is not audited**: outbox deliveries write no audit record; the event's `invocationId` links them to the call that caused them.
73
+ - **No retention or tamper evidence**: the log is a plain table with no retention policy and no hash chain. An export is pulled page by page; nothing pushes records to a SIEM.
74
+ - **Erasure scrubs, it does not delete**: a data-subject erasure clears the details, lineage and change summaries of the person's records and of records naming them (change summaries hold record ids, which can embed a person's id), and pseudonymises them as the actor ([Privacy](privacy.md)).
75
+ - **Calls that never reach the invocation path** (for example an HTTP request to an action route that does not exist) are answered by the surface and not audited.
@@ -0,0 +1,74 @@
1
+ # AuthProvider
2
+
3
+ Kind: kernel seam (in process, TypeScript). Source: [`packages/kernel/src/auth/AuthProvider.ts`](../../packages/kernel/src/auth/AuthProvider.ts). The default implementation is Better Auth, [`packages/kernel/src/auth/BetterAuthProvider.ts`](../../packages/kernel/src/auth/BetterAuthProvider.ts) (`betterAuthProvider`), the only kernel file that imports Better Auth. A second implementation, for tests and for apps behind a trusted proxy, is [`packages/testing/src/auth/TrustedProxyAuth.ts`](../../packages/testing/src/auth/TrustedProxyAuth.ts) (`@eloxiv/testing/auth/TrustedProxyAuth`).
4
+
5
+ ## Purpose
6
+
7
+ People sign in somehow: a password, a link, an identity provider, a proxy that already authenticated them. The kernel does not care how; it cares that every person's session lives where its rules can reach it. This seam is where the two meet. An app chooses its provider with `KernelApp.auth` (left out: Better Auth). Setup creates the provider's identity store; the kernel serves the provider's routes under `/auth/*`.
8
+
9
+ The split:
10
+
11
+ - **The kernel owns the identity store and judges every session.** People are rows of `auth."user"`, their sessions rows of `auth.session` (the Directory, sync facts, row-level security's verified email and the fences read these tables). Whether a session is in force is the kernel's verdict: unexpired by the database's clock, not revoked (`eloxiv.session_revocation`), admitted (its sign-in method recorded in `eloxiv.session_method`), and, in each organisation, signed in by a method the organisation admits. Holds while work runs, sign-out, endings within a bound, the sliding refresh and the housekeeping are the kernel's ([Actor](actor.md), [Invocation](invocation.md)).
12
+ - **The provider owns authentication.** Its routes (sign-in, sign-up, its account flows), how a request's credential names a session, how a session and a person are written into the store, and its browser cookie.
13
+
14
+ **A trusted, in-process seam.** A provider is app code running in the kernel's process with the kernel's privileges: its pools connect as the kernel's database role, so it is not isolated from the kernel's tables by SQL privileges, as a module is. Choose a provider as you would any dependency of the kernel; the guarantees below are what the kernel holds a correct provider to, not a sandbox.
15
+
16
+ ## The interface
17
+
18
+ `AuthProviderFactory = (context: AuthProviderContext) => AuthProviderInstance`, called once per kernel process and once for setup's migrations.
19
+
20
+ ### What the kernel gives a provider (`AuthProviderContext`)
21
+
22
+ | Member | What it is |
23
+ | --- | --- |
24
+ | `config` | The kernel's configuration. |
25
+ | `pools.requests`, `pools.lookups`, `pools.endings` | The connections to write and read the store on, each lane its own pool (search path `auth`): the provider's routes and session issuance, resolving credentials on every call, and the lookups of sign-out and the routes that end sessions. Every connection is told the request its statements run for (below). A provider touches the store on these only. |
26
+ | `signOutWaitMs` | How long an ending waits for the requests that hold a session. |
27
+ | `mail` | Account mail (`account.verify-email`, `account.reset-password`, `account.confirm-email-change`, `account.magic-link`), queued on the kernel's durable path (backlog 43); undefined without system email, when a provider refuses the flows that send mail. |
28
+ | `validateSchema` | False for setup's instance: the store may not exist yet. |
29
+ | `endingPlugin(lane)` | For a provider that writes through Kysely: turns its `DELETE FROM session …` into the kernel's set-based ending. A provider that ends sessions any other way asks the kernel (`Identity.endSessions`). |
30
+ | `storedToken(token)` | What the store keeps of a session token, and what a lookup by token matches. A provider stores and matches this, never anything else. |
31
+
32
+ ### What a provider gives the kernel (`AuthProviderInstance`)
33
+
34
+ | Member | Must |
35
+ | --- | --- |
36
+ | `name` | Name it (`better-auth`, `trusted-proxy`). |
37
+ | `handle(request)` | Answer its routes under `/auth/*`, once the kernel has done its part in front (below). |
38
+ | `routes.methods` | List the sign-in methods it offers (`password`, `magic-link`, `oauth:<id>`, a provider's own): an organisation admits a subset (Directory `setSignInMethods`). |
39
+ | `routes.signsIn(route)`, `routes.completes(route)` | Say how a route signs someone in (or completes a sign-in another began, a second factor): the session it issues is recorded with that method. |
40
+ | `routes.issuedTokens(response, text)` | Name every session token a response hands out. A token not named would leave unadmitted (so refused) sessions; nothing more. |
41
+ | `routes.ending` | List its routes that end sessions, as their purpose or as a consequence. |
42
+ | `routes.prepare`, `routes.present`, `routes.verification`, `routes.addressChangeRequested` | Optional: its request and answer shapes (a two-factor challenge for a client without cookies), its verification links (which never mint a session), and a change of address (bound to the asking session). |
43
+ | `resolve(headers, lane)` | Name the session a credential carries (the `Authorization` header when present, else its cookie), with its person's address and whether it is verified, or null. No verdict: the kernel judges. |
44
+ | `createSession(userId, meta)` | Write a session on `pools.requests` (so the credential fence checks it). |
45
+ | `createUser(user)` | Write a person; `emailVerified` only when the caller says the address is proven. |
46
+ | `sessionTerms()` | How long a session lasts, and how close to its end use extends it. |
47
+ | `cookies` | Optional (a provider whose credential is never a cookie leaves it out): its session cookie's name, its serialisation (signed as it reads it), the cookies sign-out clears, whether a request carries it (by its own parser), and whether it is a session-only cookie. |
48
+ | `pendingMigrations()` | The SQL that creates or upgrades the store, applied by setup as the kernel role in its transaction, before the kernel's own migrations (which watch the store's tables). |
49
+
50
+ ## The store
51
+
52
+ A provider's store has at least what the kernel reads, under Better Auth's names (so a store either provider made serves the other):
53
+
54
+ - `"user"`: `id` (text, primary key), `name`, `email` (unique), `"emailVerified"`, `image`, `"twoFactorEnabled"`, `"createdAt"`, `"updatedAt"`;
55
+ - `session`: `id` (text, primary key), `token` (unique, holding `storedToken(token)`), `"userId"` (references `"user"`), `"expiresAt"`, `"ipAddress"`, `"userAgent"`, `"createdAt"`, `"updatedAt"`;
56
+ - `account` (`"userId"`, `"providerId"`, `password`), `verification` (`identifier`, `value`, `"expiresAt"`) and `"twoFactor"` (`"userId"`): the credential fence and the account-write fence watch them, whether or not the provider uses them.
57
+
58
+ ## Guarantees the kernel gives every provider
59
+
60
+ - **Sessions are issued under the credential fence.** Before the provider's handler runs for a request that presents no session (a sign-in), the kernel takes a database snapshot and tells the provider's connections; a session the provider writes is checked at its commit and refused (`EA001`, answered `401`) if the person's credentials changed since by another request (kernel migration `0200_credential_fence`). The kernel's own issuance (`Identity.issueSession`: the desktop exchange, federated sign-in) does the same.
61
+ - **Account writes hold their session.** A request that presents a session in force is held while the handler runs; a write the provider makes for it to the store commits only while that session is in force (`0201_account_write_fence`), and no credential leaves once it ended meanwhile.
62
+ - **Admission.** A session is in force only once the kernel recorded how it was signed in (after the provider answers, from `routes.signsIn`); one signed in by a method none of the person's organisations admits is ended before any credential leaves (`403`), and an organisation's methods bind each call there.
63
+ - **Revocation and sign-out are the kernel's**, whatever the provider: `POST /auth/sign-out` ends the presented session within the bound, and `Identity.endSessions` ends any.
64
+ - **No listing hands out tokens**: a response that lists sessions goes out without their tokens.
65
+
66
+ ## Running the conformance
67
+
68
+ The [Actor kit](actor.md#running-the-conformance-kit) is the conformance for a provider: run it against a kernel that signs in with it, with its `sessions` member (the method, a second sign-in, sign-out, an ending, an organisation's methods). The kernel runs it against Better Auth in [`conformance-directory.test.ts`](../../packages/testing/test/conformance-directory.test.ts) and against the trusted proxy in [`auth-provider.test.ts`](../../packages/testing/test/auth-provider.test.ts), which also proves the credential fence binds the second provider's sign-in, its sessions record its method, setup builds its store without Better Auth's, and the kernel imports Better Auth only in its provider.
69
+
70
+ ## Limits
71
+
72
+ - **One provider per app.** Federated sign-in through WorkOS ([Directory](directory.md#enterprise-sign-in-and-provisioning)) is the kernel's own and works beside any provider, since it issues sessions through the seam.
73
+ - **The store's names are Better Auth's.** A provider with a different schema maps onto these tables; the kernel does not read another.
74
+ - **The trusted proxy trusts its proxy.** `trustedProxyAuth(secret)` is used only when the app selects it explicitly (`KernelApp.auth`), and needs the HMAC secret it shares with the proxy. It must sit behind a proxy that authenticates people itself and strips any `x-eloxiv-proxy-user` and `x-eloxiv-proxy-signature` headers a client sends, then signs the address it vouches for; anyone holding the secret can sign anyone in.
@@ -0,0 +1,46 @@
1
+ # CalendarProvider
2
+
3
+ A person's calendars at a provider (Outlook through Microsoft Graph, Google Calendar), over a kernel [Connection](connections.md): listing and querying as well as booking-side writes (ledger C-113, C-120: agent-native's scheduling provider had no event listing).
4
+
5
+ - Kind: capability. Version 1.4.0 (1.1.0 adds `respondToEvent`, and marks the writes external; 1.2.0 adds `CalendarEvent.selfResponse`; 1.3.0 adds `freeBusy`; 1.4.0 adds the raw requests `apiRead` and `apiWrite`).
6
+ - Schema: [`packages/contracts/schema/contracts/CalendarProvider.json`](../../packages/contracts/schema/contracts/CalendarProvider.json) (source [`CalendarProvider.ts`](../../packages/contracts/src/contracts/CalendarProvider.ts)).
7
+ - Implementations: the [`microsoft-graph`](../connectors/microsoft-graph.md) and [`google`](../connectors/google.md) connectors.
8
+ - Kit: `@eloxiv/testing/conformance/CalendarProvider` ([source](../../packages/testing/src/conformance/CalendarProvider.ts)), run by the connector tests in [`registry/test`](../../registry/test).
9
+
10
+ Shared parts: [Capability contracts](README.md#capability-contracts).
11
+
12
+ ## Records
13
+
14
+ - `Calendar`: `id`, `name`, `isPrimary`, `canEdit`.
15
+ - `CalendarEvent`: `id`, `calendarId`, `title`, `description`, `location`, `start` and `end` (ISO instants in UTC; for all-day events, dates with the end exclusive), `allDay`, `attendees` (`name`, `address`, `response`: `none`, `accepted`, `declined`, `tentative`), `organizer`, `status` (`confirmed`, `tentative`, `cancelled`), `seriesId`, and `selfResponse` (optional): the account's own part as the provider records it for the account, never matched by address (Graph's `responseStatus`; Google's entries marked `self: true`): `organizer`, or its answer (`none`, `accepted`, `declined`, `tentative`); null when the provider says the account has no part; absent when the connector cannot tell. Reconciling an answer reads it, and a module takes the owner's part from it before falling back to addresses.
16
+ - `Schedule` (`freeBusy`): `address`, `known` (false when the provider will not tell about the address: outside the organisation, no access, unknown; its `busy` is then empty, never taken as free by a caller that reads `known`), `busy`: `BusyBlock`s (`start`, `end` as ISO instants in UTC, `show` `busy` or `tentative`; Google reports only `busy`). Times only, never what the events are.
17
+ - `CalendarFlags`: `recurrence`, `attendees`, `pushNotifications`, `deltaWindow` (`{ pastDays, futureDays }` when the provider's delta covers only a window around now, as Graph's calendar view delta does; null when it covers the whole calendar, as Google's sync tokens do).
18
+
19
+ ## Operations
20
+
21
+ | Operation | Scopes | What |
22
+ | --- | --- | --- |
23
+ | `listCalendars` | `calendar.read` | The account's calendars |
24
+ | `listEvents` | `calendar.read` | Events overlapping `[start, end)` in a calendar (default the primary), occurrences of series expanded, paged |
25
+ | `freeBusy` | `calendar.read` | When people are busy in `[start, end)`, by address (1 to 50, the account's own included), as the provider shares it with the account (Graph's `POST /me/calendar/getSchedule`, out-of-office and working-elsewhere counted as busy; Google's `POST /freeBusy`). A read, though both are POSTs. An address the provider will not tell about is `known: false`, never a refusal |
26
+ | `getEvent` | `calendar.read` | One event |
27
+ | `createEvent` | `calendar.write` | Create an event |
28
+ | `updateEvent` | `calendar.write` | Change the given fields |
29
+ | `deleteEvent` | `calendar.write` | Delete (cancel) an event |
30
+ | `respondToEvent` | `calendar.write` | Answer an invitation as the account: `response` `accepted`, `declined` or `tentative`, optional `comment`; the organiser is told (Graph's `accept`, `decline`, `tentativelyAccept` with `sendResponse`; Google's own attendee entry, `self: true`, with `sendUpdates=all`). `InvalidInput` when the account is not an attendee (an organiser does not answer their own event) |
31
+ | `delta` | `calendar.read` | Changes since `cursor`: upserts for created and changed events, deletes for deleted or cancelled ones |
32
+ | `apiRead` | `calendar.read` | A raw GET to the provider's calendar API, for what the rest does not model: `{ path, query? }`, answering `{ status, body }` (the parsed JSON, else the text, else null). Only the paths the connector opens (Google: everything under `<calendar endpoint>/calendar/v3`; Graph: `/v1.0/me` and under it only `/calendar`, `/calendars`, `/calendarGroups`, `/calendarView`, `/events`, `/findMeetingTimes`), within the bounds of [raw provider requests](connections.md#raw-provider-requests): the answer at most 1 MiB (`InvalidInput` beyond) |
33
+ | `apiWrite` | `calendar.write` | A raw `POST`, `PUT`, `PATCH` or `DELETE` (any other method is refused) to the same paths, with a JSON `body` of at most 64 KiB. External: what it does is the provider's, and it may invite or tell others; never reconciled (an uncertain run is `unknown`) |
34
+
35
+ Creating, updating, deleting and answering are external (attendees or the organiser are told): a module only schedules them, and the kernel makes each at most once, reconciling an uncertain one by reading the event back ([Invocation](invocation.md#external-effects)). So is `apiWrite`, which nothing reconciles.
36
+
37
+ ## How an implementation is checked
38
+
39
+ `calendarProviderConformance(harness)` registers: one primary calendar; an event created, read, found in its range and not outside it, renamed, deleted (NotFound or cancelled, and gone from its range); the account's own busy time by its address covering an event it made, with nothing of the event's title; an invitation from someone else (the harness's `invite` seed) answered `accepted`, then `declined` with a comment, each read back as the account's own response (`selfResponse`) and its attendee entry, and an organiser's own event refused (`InvalidInput`; skipped against a real account, which has no `invite` seed); the shared delta and Connection checks (probe `listCalendars`, merged scopes with Mail).
40
+
41
+ ## Not yet guaranteed
42
+
43
+ - Recurrence rules on create, and online meetings. `freeBusy` is checked for the account's own address only (what any real account can answer); other addresses are proven against the protocol fakes (`registry/test/calendar-find-time.test.ts`).
44
+ - The raw requests are proven over the protocol fakes by the calendar module ([`registry/test/calendar-api.test.ts`](../../registry/test/calendar-api.test.ts)), not by the kit.
45
+ - Graph's delta covers its window (default 90 days back, 365 ahead): an event outside it is not reported.
46
+ - Proven against protocol fakes, not the real services.
@@ -0,0 +1,245 @@
1
+ # ClientSDK
2
+
3
+ The headless client SDK every app's UI, and every headless app, is built on: sign-in, typed action calls, a policy-scoped local replica, the agent client, organisation switching and version skew. It uses only web-standard APIs, so the same SDK runs in browsers, Tauri, Bun, Node and React Native (decision 8).
4
+
5
+ - Kind: shell contract. Version 1.4.0 (1.4.0: the client core's offline start, a `SessionStore` that remembers the context last open with its token (`recall`, `remember`, `forgetContext`), the first check's `offlineProbeMs` deadline (also bounding a remembered session's first organisation listing), `SignOutNotSaved`, `refuse`, `isRefused`, `dispose`, `signOut(known?)` and `sessionStatus().error`; the chat SDK's `PendingConsent.title`, `ApprovalItem.title` read through `approvalLabel`, `actionLabel`, and `decisionLabel` and `makeDecisionLabel` (a MAKE action's decision named from its id: `mk_todos: Urgent`), and a tool's activity line prefers the event's title; 1.3.0: magic links and the desktop sign-in exchange; 1.1.0: the chat SDK drops the streamed text of a reply the kernel discarded, `reply-discarded`; 1.2.0: the account, Directory, avatar and session clients).
6
+ - Schema: [`packages/contracts/schema/contracts/ClientSDK.json`](../../packages/contracts/schema/contracts/ClientSDK.json) (source [`ClientSDK.ts`](../../packages/contracts/src/contracts/ClientSDK.ts)): the SDK's functions as language-neutral records.
7
+ - Implementation: `@eloxiv/client` ([`packages/client`](../../packages/client)): `signIn`, `signUp`, `signOut`, `listOrganizations`, `listMembers` ([`Auth.ts`](../../packages/client/src/Auth.ts)); `makeClient`, `isReplay`, `fetchRelease`, `isClientOutdated` ([`Client.ts`](../../packages/client/src/Client.ts)); `connectSync` ([`Sync.ts`](../../packages/client/src/Sync.ts)); `agentClient` ([`Agent.ts`](../../packages/client/src/Agent.ts)); the replica's storage adapters in `@eloxiv/client/storage` ([StorageAdapter](storage-adapter.md)); the kernel's sync tables in `@eloxiv/client/sync`.
8
+ - Kit: `@eloxiv/testing/conformance/ClientSDK` ([source](../../packages/testing/src/conformance/ClientSDK.ts)), against a real kernel and sync server.
9
+
10
+ ```ts
11
+ const session = await signIn(baseUrl, { email, password })
12
+ const orgs = await listOrganizations(baseUrl, session.token)
13
+ let org = orgs[0]!.orgId
14
+ const client = makeClient({ baseUrl, modules: contracts, token: () => session.token, orgId: () => org, clientVersion })
15
+ const result = await client.call("hello.greet", { message: "Hi", visibility: "org" }) // { kind: "output", output }
16
+ const zero = connectSync({ server: zeroUrl, schema, userId: session.user.id, token: session.token, orgId: org })
17
+ const agent = agentClient({ baseUrl, token: () => session.token, orgId: () => org })
18
+ await agent.send({ text: "What changed today?" })
19
+ ```
20
+
21
+ ## Operations
22
+
23
+ | Operation | SDK function | What it does |
24
+ | --- | --- | --- |
25
+ | `signIn` | `signIn` | Email and password to a session (`token`, `user`); `AuthError` (status 401) for wrong credentials |
26
+ | `signUp` | `signUp` | Creates an account and signs in |
27
+ | `signOut` | `signOut` | Revokes the session on the server: the token stops authenticating everywhere at once |
28
+ | `organizations` | `listOrganizations` | The person's organisations, oldest membership first, with their roles |
29
+ | `members` | `listMembers(baseUrl, token, orgId)` | An organisation's members with their roles and groups (Directory `listMembers`, `GET /api/org/members`); the caller must be one of them |
30
+ | `call` | `makeClient(...).call` | An action by name, with typed input and output projected from the action registry (no hand-written glue), in the selected organisation (`x-eloxiv-org`), sending the build's version (`x-eloxiv-client-version`) and an optional idempotency key. Returns the result envelope (`{ kind: "output" }`, or `{ kind: "replay", receipt }`, `isReplay`); rejects with the standard error. `callEffect(action, input, { token, orgId })` is the same call as an Effect in the caller's fiber, for Effect programs (interrupting it aborts the request) |
31
+ | `sync` | `connectSync` | The local replica for the person in an organisation, a store per person and organisation, kept live by zero-cache, holding only what policy lets them read. The kernel records its client group as the person's from its queries' transforms, so the person's erasure purges zero-cache's records of their queries at once ([Privacy](privacy.md)); it pushes only the person's writes |
32
+ | `agentSend` | `agentClient(...).send` | A message to the person's agent (with an optional [ScreenContext](screen-context.md) snapshot), and the run to follow (`events`, `follow`, `run`, `cancel`, `context`, `complete`) |
33
+ | `account` | `requestPasswordReset`, `resetPassword`, `sendVerificationEmail`, `verifyEmail`, `getAccount`, `updateProfile`, `changeEmail`, `changePassword`, `enableTwoFactor`, `confirmTwoFactor`, `disableTwoFactor`, `regenerateBackupCodes`, `verifyTwoFactor`, `oauthSignInUrl` ([`Account.ts`](../../packages/client/src/Account.ts)) | The person's own account: see [Account, profile and session](#account-profile-and-session) |
34
+ | `directory` | `directoryClient(...).call(operation, input)` ([`Directory.ts`](../../packages/client/src/Directory.ts)) | A [Directory](directory.md) operation, typed from its contract |
35
+ | `avatar` | `avatarClient(...)` ([`Avatars.ts`](../../packages/client/src/Avatars.ts)): `get`, `subscribe`, `invalidate`, `upload`, `remove` | People's photos |
36
+ | `session` | `sessionController(...)`, `safeReturnPath`, `signInPath` ([`Session.ts`](../../packages/client/src/Session.ts)) | The shared session state every view reads |
37
+ | | `mcpServerIdentity` | The kernel's MCP server identity (`GET /.well-known/mcp.json`, public): the canonical name every connect flow lists it under (the app's name, anything but letters, digits and `._-` as `-`), its endpoint, OAuth resource and protected resource metadata ([`mcp-identity.test.ts`](../../packages/testing/test/mcp-identity.test.ts)) |
38
+ | `release` | `fetchRelease` | The kernel's release (`GET /release`), including the oldest client version it accepts writes from |
39
+ | | `makeClient(...).read` | A read-only action's result, typed like `call`, sent in a read batch with the other reads of the same window ([Transport](#transport)) |
40
+ | | `makeClient(...).send` | An action over plain HTTP, for a timeout, an abort signal, `keepalive` and retries under an idempotency key |
41
+ | | `makeClient(...).status`, `onStatus` | Whether there is a backend: `available`, `disabled` by the host (with why), or `unavailable` while the failure circuit is open |
42
+ | | `poll`, `makeProbe`, `sessionProbe`, `engineProbe` | Polling and shared status probes ([Polling, probes and tabs](#polling-probes-and-tabs)) |
43
+ | | `tabIdentity`, `isOwnPublication` | A browser tab's id per app, kept across a reload |
44
+ | | `skewRecovery`, `fetchFreshRelease` | A write refused as from an outdated build (`ClientOutdated`) is kept and a reload offered; declined, an explicit `retry()` reads the release afresh (past any cache) and sends the kept writes again, under their keys, only once this build is accepted ([`Skew.ts`](../../packages/client/src/Skew.ts), [`client-skew.test.ts`](../../packages/testing/test/client-skew.test.ts)) |
45
+ | | `uploadFile` | A file through the Files contract's resumable upload as one call with its status (`starting`, `uploading` with bytes sent, `completing`, `processing`, `failed`): a part whose answer was lost is resumed (`files.resumeUpload`), an abort abandons the upload; it returns the file's id, the durable reference to attach or hand the agent, never the bytes ([`Upload.ts`](../../packages/client/src/Upload.ts), [`client-upload.test.ts`](../../packages/testing/test/client-upload.test.ts)) |
46
+ | | `registerWebMcp`, `defineClientAction` | The app's actions and the page's own client actions as tools for a browser agent ([WebMCP](#webmcp)) |
47
+ | | `appStateClient`, `commandConsumer`, `consumeCommands` | Durable app state, the published screen and the agent's screen commands ([ScreenContext](screen-context.md#durable-state-and-agent-commands)) |
48
+
49
+ ## Guarantees
50
+
51
+ 1. **Web-standard only.** No DOM or Node API: the client compiles without their types, a fallow rule pack refuses Node built-ins, UI bindings and DOM globals ([`portable-client.json`](../../tools/fallow/portable-client.json)), a neutral bundle runs in a bare VM ([`registry/test/sync.test.ts`](../../registry/test/sync.test.ts)), and CI runs it on Hermes ([Mobile guard](../scaffold.md#desktop-and-react-native-in-ci)).
52
+ 2. **Typed calls through the one invocation path**, enveloped, idempotent with a key; invalid input never runs (the typed client refuses to encode it, or the kernel answers `InvalidInput`).
53
+ 3. **Organisation switching**: calls act in the organisation `orgId` names when they are made; each (person, organisation) has its own replica; a person cannot act in an organisation they do not belong to.
54
+ 4. **The replica holds only what its person may read** in its organisation, and receives other clients' writes live.
55
+ 5. **Version skew**: a build older than the kernel's minimum has its writes refused with `ClientOutdated` (`isClientOutdated`), naming the minimum; its replica keeps reading.
56
+ 6. **Sign-out revokes** the session on the server.
57
+
58
+ ## Transport
59
+
60
+ Every HTTP request the SDK makes for actions follows the same rules ([`Transport.ts`](../../packages/client/src/Transport.ts), [`Reader.ts`](../../packages/client/src/Reader.ts)):
61
+
62
+ - **No backend on purpose.** `makeClient({ ..., backend: { disabled: "why" } })` (a static or standalone build, a preview): every `call`, `read` and `send` is refused before anything is sent, with `RequestError` `BackendDisabled` and the reason, and `status()` is `{ state: "disabled", reason }`, so a hosted surface can say why it has no data.
63
+ - **Failure classes.** `failureClass(status)`: `retry` (no answer, a timeout, 408, 429, 502, 503, 504: nothing definitive came back), `server` (another 5xx), `auth` (401) and `final` (any other 4xx: the kernel's refusal). Only `retry` is retried, and only when asked (`retries`), backing off; a write is retried only under an idempotency key (asking for retries without one is refused unsent).
64
+ - **A failure circuit** (`makeCircuit`, one per client unless one is passed to share): `threshold` (5) failures of class `retry` or `server` in a row open it; while open, requests are refused at once (`BackendUnavailable`, with `retryAt`) and `status()` is `unavailable`; after the cooldown (15 s) one request goes out, and its success closes the circuit. A refusal never counts, so a not-found or forbidden read never opens it, and is never retried.
65
+ - **Read batches.** `read` queues the call; reads made in the same window (`batch.windowMs`, default 0: the same turn) acting as the same person in the same organisation go out as one `POST /api/batch` ([Invocation](invocation.md)), at most 25 distinct reads, the same read once; each answers on its own, typed and decoded like `call`, or rejects with its own refusal. A credential answered 401 is not sent again: every read with that token is refused unsent until the token changes, so a session revoked elsewhere causes one request, not a storm.
66
+ - **One call's options.** `call(action, input, { idempotencyKey, timeoutMs, signal })`; `send(action, input, { idempotencyKey, timeoutMs, signal, keepalive, retries })`. A timeout rejects with `Timeout` (status 0: the call may still have run); `keepalive` lets state published while the page goes away arrive (browsers cap its body at 64 KiB).
67
+
68
+ Uploads are the Files contract's (its own multipart route); the transport carries JSON. Tested against a stubbed `fetch` ([`client-transport.test.ts`](../../packages/testing/test/client-transport.test.ts)) and against a kernel ([`read-batch.test.ts`](../../packages/testing/test/read-batch.test.ts)).
69
+
70
+ ## Polling, probes and tabs
71
+
72
+ Runtime-neutral helpers ([`Poll.ts`](../../packages/client/src/Poll.ts), [`Tab.ts`](../../packages/client/src/Tab.ts)); a browser host gives them its environment through `@eloxiv/shell-core/web` (`webVisibility()`, `webTabEnvironment()`), so the root SDK touches no DOM:
73
+
74
+ - **`poll(attempt, { intervalMs, hiddenIntervalMs, timeoutMs, visibility, onResult, onError })`**: one attempt at a time, each given an abort signal and aborted at its timeout (reported as `Timeout`); paused while hidden (`hiddenIntervalMs: "pause"`, the default) or slowed, and run at once when shown again; `now()` polls at once, or right after the attempt in flight; `stop()` aborts it.
75
+ - **`makeProbe(load, { ttlMs, unavailableTtlMs, timeoutMs })`**: a status read shared by its callers: one request in flight, its answer kept for `ttlMs`. A failure is `{ status: "unavailable", reason }`, never a value. `sessionProbe(baseUrl, token)` answers `signedIn: false` only when the kernel says so (401, or no session), and `unavailable` when it could not be reached, so a network failure is never shown as a sign-out; `engineProbe(baseUrl)` gives the kernel's readiness report (ready, degraded or not ready) or `unavailable`.
76
+ - **`tabIdentity(app, environment)`**: the tab's id for an app, kept in the tab's `sessionStorage` across a reload and a back or forward navigation, new for any other navigation and in a new tab; decide it once per page load. App state a tab writes carries it, and `isOwnPublication` tells a tab its own echo.
77
+
78
+ Tested in [`client-poll.test.ts`](../../packages/testing/test/client-poll.test.ts).
79
+
80
+ ## WebMCP
81
+
82
+ A browser agent working in the page (WebMCP, `navigator.modelContext`) gets the app's actions and the page's own client actions as tools ([`WebMcp.ts`](../../packages/client/src/WebMcp.ts)). The host passes the model context in (`webModelContext()` from `@eloxiv/shell-core/web`; undefined where the browser has none), registers once the person is signed in and an organisation chosen, and calls `stop()` at sign-out or a switch:
83
+
84
+ ```ts
85
+ const context = webModelContext()
86
+ const webmcp = context && (await registerWebMcp({ modelContext: context, baseUrl, token, orgId, clientActions, approve }))
87
+ ```
88
+
89
+ - **The app's actions are the agent's, never the person's.** The person's own session asks the kernel for a fifteen-minute agent session for the browser agent (`POST /api/webmcp/session`; an API token, an OAuth grant, an agent session or a device is refused); the tools are what that agent session reaches (`GET /api/webmcp/tools`, the compatibility manifest: name, description, input JSON Schema, read-only, destructive and consent hints, HTTP route; a person's session is refused, since what a person reaches is not what their agent may call), and each is called on its HTTP route (`POST /api/actions/<action>`) with that session. So the kernel's admission holds: ActionConsent holds what needs consent (the tool answers `{ held: "ConsentRequired", consentId, ... }`, decided in the app's consent prompt as any), agent tool groups the app disabled are neither listed nor callable, an action not offered to agents (`exposure.agent: false`, such as `consent.get`) is not listed, and person-only actions (deciding consent or an approval) are refused. `stop()` unregisters every tool and revokes the session (`POST /api/webmcp/session/revoke`).
90
+ - **Client actions run in the page** (`defineClientAction({ name, description, input, readOnly?, consent?, run })`): the input is checked against its Effect Schema (whose JSON Schema the agent is shown) before `run`; one marked `consent` runs only after the host's `approve` answers yes, and asking for consent with no `approve` refuses the registration. They never reach the kernel; what they do is the page's.
91
+ - **Bounded:** at most `maxTools` (100) tools, names of `[A-Za-z0-9_.-]`, inputs up to `maxInputChars` (500 000).
92
+
93
+ Tested against the agent conformance kernel ([`webmcp.test.ts`](../../packages/testing/test/webmcp.test.ts)). The reference shell (shell-foldkit 0.5.0) registers it by default where the browser has a model context, while the person is signed in with an organisation chosen, and stops it (its agent session revoked) on a sign-out, a refused session or a switch (`ShellConfig.webMcp`, `false` to turn it off). Not yet: the browser agent's session is not tied to the person's session, so a sign-out elsewhere leaves it working until it expires (at most fifteen minutes) unless the page stops it.
94
+
95
+ ## Account, profile and session
96
+
97
+ Every function is one request to the kernel; what needs mail goes through the deployment's system email and is refused where it has none (see [Actor](actor.md#signing-in)).
98
+
99
+ - **Sign-in with a second factor.** `signIn` of an account with two-factor authentication rejects with `TwoFactorRequired` (an `AuthError`, 401) carrying a `challenge`; `verifyTwoFactor(baseUrl, { challenge, code, method? })` (`totp`, or `backup-code`, each good once) answers the session. The password alone never yields a credential. The challenge lasts ten minutes and allows a few wrong codes. Clients that keep no cookies send it in `x-eloxiv-two-factor` (`TWO_FACTOR_CHALLENGE_HEADER`); a browser also has Better Auth's cookie.
100
+ - **Enrollment.** `enableTwoFactor(token, { password })` answers the authenticator's `totpURI` and backup codes; nothing is required at sign-in until `confirmTwoFactor(token, { code })` proves a first code. `disableTwoFactor` and `regenerateBackupCodes` need the password. Routes that rotate the session (`confirmTwoFactor`, `disableTwoFactor`, `changePassword`) answer the `token` to use from then on.
101
+ - **Recovery.** `requestPasswordReset({ email, redirectTo })` mails a link (and answers the same whether or not the address has an account); the link lands on `redirectTo` with `?token=`; `resetPassword({ token, newPassword })` sets it once and ends every session of the account.
102
+ - **The address.** `sendVerificationEmail` and `verifyEmail(token, session?)`; `changeEmail(token, { newEmail })` changes a verified address only after a link mailed to it confirms the change and the new address is verified (an unverified one is verified at the new address). A change's links act only when opened in the session that asked for it, while it lasts, each once (`verifyEmail(linkToken, session)`, or the link in the browser signed in with that session); they never sign anyone in. `getAccount` and `updateProfile({ name })` read and change the profile.
103
+ - **Magic links.** `requestMagicLink({ email, callbackURL? })` (answers alike for every address) and `verifyMagicLink(token)`, the session; see [Actor](actor.md#signing-in) for what a link may sign in.
104
+ - **Desktop sign-in.** `beginDesktopSignIn({ redirectUri })` (the verifier the app keeps, its challenge, a state and the `query` for the app's web sign-in page), `approveDesktopSignIn(baseUrl, token, { challenge, redirectUri, state })` on that page (answers the redirect to follow), `completeDesktopSignIn(baseUrl, login, { code, state })` (refuses a state it did not send) and `desktopSignIn(controller, { baseUrl, redirectUri, signInPage, open, receive })`, the desktop identity bootstrap: the whole journey into the session controller.
105
+ - **OAuth sign-in.** `oauthSignInUrl({ provider, callbackURL, errorCallbackURL? })` answers the provider's page for a browser to open; it returns to `callbackURL` (a trusted origin) signed in with the session cookie. It joins an existing account only when the provider verified the same address and the account's own address is verified; otherwise it lands on `errorCallbackURL?error=account_not_linked`.
106
+ - **Avatars.** `avatarClient({ baseUrl, token, userId, compress? })`: `get(userId)` shares one lookup between every view asking at once and keeps the photo until its ETag changes; `subscribe(userId, listener)` hears of a new photo (or its removal) the moment this client uploads it; `upload({ contentType, bytes })` applies the app's `compress` (the SDK has no image codec: a browser passes a canvas-based one) and refuses anything but PNG, JPEG, WebP or GIF of at most 256 KiB before sending. The kernel shows a photo only to its person and to people sharing an organisation with them.
107
+ - **The session.** `sessionController({ baseUrl, store })` holds `loading`, `authenticated` (`token`, `account`), `unauthenticated`, `unavailable` or `signing-out`, for every view (`subscribe`). `start`, `refresh` and `invalidate` (after a 401) share one check in flight; a stored token is reported authenticated only once the kernel accepts it, forgotten when it refuses it, and kept as `unavailable` when the kernel cannot be reached (retried with backoff). `signIn`, `completeTwoFactor` and `adopt` check the new session's account before storing it; an adoption overtaken by a sign-out or another adoption (or abandoned through `adopt(session, { current })`), or whose check fails, stores nothing and revokes that session (one whose `current` is already false when it is called overtakes no adoption in progress), unless something else holds its token (the current or stored session, or another adoption of it running or accepted). Checks, adoptions and sign-out change the store and the state one at a time: a check that began before a session was adopted or a sign-out began publishes and forgets nothing, and checks during a sign-out answer without reading. A session is forgotten only while the store still holds it: a store with `clearIf(token)` does that atomically, so another writer of the same store keeps its token; without it the controller compares and clears, atomic only with its own writes. `signOut` stops `token()` before the revocation is sent, forgets the revoked session only once the kernel confirms it, and keeps a session adopted after it began unless it is the one being revoked (an adoption of that token, such as a changed password's unrotated token, resolves `false` from before the revocation is sent). **A durable sign-out** (`revocations`: a `RevocationStore`, a browser's storage) keeps the revocation in that store (read back) and forgets the stored session before reporting `unauthenticated`, so an interruption at any instant after the signed-out state shows (a reload, a closed tab) finds the revocation, never the session; the kernel's confirmation follows in the background (`revocationStatus`: `revoking`, `pending`, `confirmed`; `retryRevocations`, each attempt bounded by `revocationTimeoutMs`), and a revocation leaves the store only once the kernel confirms it (revoked now, or refused already). Where the store will not keep it, the token stays in memory, the stored session stays (a reload finds a session the kernel still accepts, never a token nobody holds) with its remembered context forgotten (`forgetContext`, so an offline restart reopens nothing for it; when that cannot be saved either, `signOut` rejects with `SignOutNotSaved`, stays `signing-out`, and is reported `unauthenticated` once the kernel confirms the revocation), this controller never reports that session again, and `signIn`, `completeTwoFactor` and `adopt` are refused with `UnsavedSignOut` (before the kernel is asked) until it is stored or confirmed. A stored session whose token the revocation store holds pending (its slot survived the sign-out: its removal failed or was interrupted) is never checked or reported by any controller over that store, and its slot is forgotten. A revocation the kernel confirms leaves the revocation store only after the session's slot is cleared (or, failing that, its remembered context forgotten); while neither succeeds it stays pending and is retried, and a `SignOutNotSaved` sign-out is reported `unauthenticated` only then. A slot that cannot be read at sign-out is a failure (`SignOutNotSaved`), never "nobody signed in", unless the caller passes the token it holds (`signOut(known)`: the client core passes an offline start's); a sign-out that failed keeps its token, so calling it again revokes the same one. **A refused session** (a 401 on the check, a late answer to the launch's bounded check, or `refuse(token)` for a 401 heard elsewhere, such as the organisation listing) is reported `unauthenticated` first, in a new generation (a check still in flight cannot replace it), and its slot is cleared afterwards in the background, retried with backoff until it succeeds or `dispose` (its remembered context forgotten meanwhile). The refused token is remembered in memory for the store object it came from for the life of the process (`isRefused`): no controller over that store reports it or lets the core reopen it offline again, even while the store still holds it. Limit (accepted): when the secure store can neither clear the slot nor forget its context, nothing durable records the refusal, so a restart of the app can reopen that context offline until the kernel is reached and refuses it again. A store may also keep the context last open with its token (`remember(token, { user, organization })`, `recall(token)`: the person and the organisation with its name and roles, never a credential), answering only for that token and forgetting it with the session (`clear`, `clearIf`, or another token saved); `memorySessionStore` does, and the client core uses it for an offline start (below). `safeReturnPath(candidate, origin)` and `signInPath(signIn, returnTo, origin)` keep a return after sign-in on the app's own origin.
108
+
109
+ Proven in [`packages/testing/test/account-security.test.ts`](../../packages/testing/test/account-security.test.ts) (with a real SMTP server and an OAuth provider fake), [`packages/testing/test/profile-session.test.ts`](../../packages/testing/test/profile-session.test.ts) and [`packages/testing/test/directory-admin.test.ts`](../../packages/testing/test/directory-admin.test.ts).
110
+
111
+ ## The client core
112
+
113
+ `@eloxiv/client/runtime` ([`Runtime.ts`](../../packages/client/src/Runtime.ts), decision 14) is the portable, framework-free client core: `makeClientRuntime({ kernelUrl, zeroUrl, schema, queries, mutators, modules, sessionStore, storage?, revocations?, initialOrg? })`. It owns what every client needs and none should implement twice: the session (`sessionController`, with desktop sign-in: `beginSignIn(redirectUri)`, `completeSignIn(login, { code, state })`), the selected organisation with a **generation** (`initialOrg`'s choice once signed in, by default the organisation selected before when the same person's session is adopted again, else the first membership; `selectOrg`), the replica of one person, organisation and session (`connectSync`, the storage injected), live named queries (`subscribe({ query, args?, id? }, owner)`: full snapshots tagged with their generation), optimistic writes through the generated mutators (`write({ mutator, input, id? }, owner)`: `predicted`, then `confirmed`, `rejected` with the typed error after the rollback, or `notConfirmed`), non-optimistic calls (`call(action, input, idempotencyKey?)`: the typed client for the app's actions; the kernel's, `make.*` and MAKE modules' actions over HTTP), an agent run's events (`followRun({ runId, after?, id? }, owner)`: the chat SDK's `chatClient.events` inside the core, reconnecting from the last stored event, each stored event emitted once, ending after `run-finished` or with the kernel's refusal; `unfollowRun`, `unfollowAll`) and the agent's readiness (`agentReadiness()`, the chat SDK's `readiness`), and teardown: an organisation change, a sign-out or `needs-auth` destroys every view, stops every followed run and closes the replica before the `context` event, then sends the `session` of the new generation (never before its `context`), and nothing of an older generation is emitted after it. Its events (`onEvent`) are [LocalClient](local-client.md)'s, without the stream's `seq`; the daemon serves it unchanged to native hosts. It follows the root SDK's portability rules.
114
+
115
+ **An offline start.** When the stored session cannot be checked because the kernel cannot be reached (`unavailable`) and the session store remembers a context for that token (`recall`), the core reports that person signed in, in that organisation alone (`organizations` holds only it), and opens their replica of it from its storage at once, so the last synced rows show and writes go to the replica as they do when the connection drops while running; `sessionStatus()` stays `unavailable` meanwhile (how a host marks it offline), switching organisation is refused (`ActionFailed`), and the check goes on every `recheckMs`. Nothing opens for another token, a store without `recall`, or a token a sign-out left pending (or a revocation store that cannot be read). The launch's first check of a token with a remembered context waits `offlineProbeMs` (3 s) for the kernel, in one attempt: a stalled connection or a network failure opens the offline context then, the check goes on in the background, and an answer that comes late is acted on at once (a refusal tears it down). When the kernel accepts the token, the core lists the person's organisations and keeps the same generation and replica while they still belong to the remembered organisation (else one is chosen in a new context); when it refuses it (on the check, or with a 401 on the organisation listing), everything is torn down as for any refused session (`needsAuth`: views destroyed, the replica closed, then the stored session and its context forgotten), whatever the store does: the teardown never waits for the store, a store that fails to clear the session has its context forgotten (`forgetContext`) and the clearing retried until it succeeds, and the refused token is not reopened again in this process. When the kernel accepts a remembered session at once but does not list its organisations within `offlineProbeMs`, the remembered organisation opens (`organizationsStatus()` `unavailable` until the listing comes), and the late listing reconciles it as a reconnect does. When another person signs in over an offline start (or over any open context), the first person's context is closed in a new generation (`signOut` reason) before the new person's organisations are listed. A selection (`selectOrg`) whose listing no longer has the open organisation resets it before refusing the selection (`Forbidden`). Whenever the kernel's listing of the person's organisations (at an online start, on reconnecting from an offline start, or listed again after a failure) selects none, the context remembered for the session is forgotten (`forgetContext`, the session kept) before the new context is announced, so a later offline start does not reopen an organisation the person was removed from; a newly selected organisation replaces it (`remember`, awaited, or forgotten when that fails). A sign-out while offline forgets the context with the session. The core remembers the context each time one opens for a checked session (`remember`), and an online start of the same stored session returns to the remembered organisation (as `previous`, before `initialOrg`).
116
+
117
+ An in-process host (a JavaScript client: the web shell) has entries the protocol does not carry:
118
+
119
+ - **Sign-in methods.** `signInWithPassword({ email, password })` and `completeTwoFactor({ challenge, code })` adopt the session as the current sign-in attempt (one abandoned while it completes, by a sign-out or `close`, adopts nothing and is revoked); the kernel's errors reach the caller as they are (`AuthError`, `TwoFactorRequired`, `UnsavedSignOut`). `changePassword(input)` adopts the rotated session: the same person's organisation stays selected, in a new generation; a rotation answered after the session it rotates ended (a sign-out, `close`) adopts nothing, rejects with `SignInFailed` and its rotated session is revoked. `selectOrg(orgId)` whose session ended while it ran (a sign-out, another person's sign-in, `close`) changes nothing and is refused with `StaleGeneration`; a late organisation listing never replaces the next person's memberships.
120
+ - **A durable sign-out** (`revocations`, `revocationTimeoutMs`, `revocationRetryMs`): `signOut` resolves once the revocation is kept and the person is signed out; pending revocations are retried at `start`, every `revocationRetryMs` (15 s) and on `retryRevocations()`; `revocation()` and `onRevocation(listener)` report where the last one stands.
121
+ - **Session details.** `token()` (for the host's own requests, never in an event), `sessionStatus()` (`loading` before the stored session is checked; `unavailable` and why, while the kernel cannot be reached to check it), `organizationsStatus()` (`listed`, or `unavailable` and why: the person's organisations could not be listed, so the session's empty `organizations` are unknown, not none; they are listed again every `recheckMs` (5 s) and by `start`, and once they come an organisation is selected in a new context, announced as usual). LocalClient's session event does not carry it yet: a native host sees the empty list until the listing succeeds.
122
+ - **Generation guards.** `subscribe`, `write` and `call` take `generation` (the last two also over LocalClient): refused (`StaleGeneration` naming the current generation, nothing predicted, sent or run) unless the context is still that generation, so a request made for one organisation never lands in the next.
123
+
124
+ Checked against a real kernel and zero-cache in [`registry/test/client-runtime.test.ts`](../../registry/test/client-runtime.test.ts) and LocalClient's conformance; the in-process entries against a stubbed kernel in [`packages/testing/test/client-runtime-sign-in.test.ts`](../../packages/testing/test/client-runtime-sign-in.test.ts) and [`client-runtime-races.test.ts`](../../packages/testing/test/client-runtime-races.test.ts), the offline start in [`client-runtime-offline.test.ts`](../../packages/testing/test/client-runtime-offline.test.ts). The web shell (`shell-foldkit` 0.7.1, which shows organisations the core could not list as unavailable) runs on one in-process runtime (IndexedDB replicas, the browser's storage for the session and pending revocations) through the Foldkit adapter's `runtimeReplica` and `runtimeEvents`.
125
+
126
+ ## UI bindings
127
+
128
+ The root SDK loads no UI framework. Its UI bindings are separate entries, each a fallow zone of its own that the portable rule pack lets import its framework, and that the root may not import (`tools/done/test/kernel-headless.test.ts` proves both rules fire):
129
+
130
+ - `@eloxiv/client/foldkit` ([`Foldkit.ts`](../../packages/client/src/Foldkit.ts), decision 10): a thin bridge between the client core and a Foldkit program (The Elm Architecture), with no second entity cache: the runtime's events become Messages, its operations Commands, its replica of a generation a ManagedResource. The shell (`shell-foldkit`) is built on it. `foldkit` (0.170.0) is an optional peer dependency.
131
+ - `@eloxiv/client/react`: Zero's React provider and hooks, re-exported. **Deprecated**: it served the React shell, retired at its last version (`shell` 0.4.0, decision 10), and stays only so an app still on that version keeps building; nothing on the default path loads React.
132
+
133
+ | Export | Foldkit primitive | What it does |
134
+ | --- | --- | --- |
135
+ | `makeCredentials()` | outside the Elm state | Bearer tokens kept out of the program: `keep(token)` returns an opaque handle the Model, Messages and Command arguments carry instead; Commands and the replica resolve it (`token(handle)`) only when they run; `forget(handle)` drops it. DevTools, traces and diagnostics never see a token |
136
+ | `runtimeReplica({ runtime, requirements, onOpened, onClosed, onFailed, owner? })` | ManagedResource | The client core's replica, in the generation `requirements(model)` names (`RuntimeReplicaRequirements`: user, organisation, generation, as the runtime announced them): the runtime opens and closes the replica itself on its context changes; this names the context Commands and Subscriptions act in, through `ReplicaService` as before. `onOpened` receives its `ReplicaKey`, whose `opening` is the generation |
137
+ | `runtimeEvents({ runtime, initial, toMessage, onRevocation? })` | Subscription entry | The runtime's session, context and connection events (and a durable sign-out's revocation status) as Messages, the current state first (`initial`); rows and writes are left to `liveQuery` and `writeOptimistic` |
138
+ | `runtimeSessionHandle(runtime, credentials)` | outside the Elm state | The runtime's session token behind a handle in `credentials`: a new handle for each token, the last one forgotten, so a Command still holding it reads no token once the session ends |
139
+ | `replicaResources({ requirements, credentials, onOpened, onClosed, onFailed, ... })` (**deprecated**: a second implementation of the replica's lifetime; use `runtimeReplica`) | ManagedResource | The replica is open exactly while `requirements(model)` names a user, organisation and session handle (`ReplicaRequirements`); the handle is resolved through `credentials` when it opens (a forgotten session opens nothing). A change releases the old replica (Zero closed, its WebSocket with it) before the next opens. `onOpened` receives the replica's `ReplicaKey` (user, organisation and an opening number; never the token) |
140
+ | `liveQuery({ replica, query, toMessage })` | Subscription entry | While the Model holds an open replica's key, a named query's results arrive as `Snapshot` Messages carrying that key, rows copied out of the view; a key that is not the open replica yields nothing. Over `runtimeReplica`, the query runs through `runtime.subscribe` in that generation and only its own `rows` events are taken |
141
+ | `QueryState(entity.row)`, `receive`, `rowsOf`, `isSettled` | Model | A query's place in the Model; `receive` keeps a snapshot only from the replica the Model holds, so a late snapshot from a closed replica is never shown. Rows are checked by the entity's row schema and typed by the generated sync table's row type, so no field is declared twice (decision 9) |
142
+ | `rowsFrom(replica, snapshot)` | Model | For a handler that keeps rows rather than a `QueryState`: the snapshot's rows only when it comes from `replica` (user, organisation and opening alike), none otherwise. The shell's chat and approval screens take every snapshot through it |
143
+ | `settledRowsFrom(replica, snapshot)` | Model | `rowsFrom`, once the server has answered: none while the replica has only what it held before asking (`unknown`), so a screen never reports an empty first sync as the query's answer. The example app's reference screens take their snapshots through it |
144
+ | `connectionState({ replica, toMessage })` | Subscription entry | The open replica's connection state (`connecting`, `connected`, `needs-auth`, `error`, ...) as Messages |
145
+ | `writeOptimistic(key, mutators.<module>.<action>(input))` | Effect for a Command | The generated mutator's prediction is applied to the replica `key` names (any other is refused with `ReplicaUnavailable`, writing nothing); succeeds when the server ran the action, fails with the invocation's typed error (`WriteError`: `Forbidden`, `InvalidInput`, ...) once the replica dropped the prediction, or `WriteNotConfirmed` when the replica closes first. Over `runtimeReplica`, it writes through `runtime.write` in that generation (refused for another) and ends as the runtime's `write` events say, or `WriteNotConfirmed` once the context changes |
146
+ | `callAction(client, action, input, { token, orgId, idempotencyKey })` | Effect for a Command | The typed client's call in the calling fiber (`makeClient(...).callEffect`), acting with the session and organisation the Command names |
147
+
148
+ Cancellation is explicit: interrupting a Command stops its wait and aborts an action call's request; it never takes back a write the replica has already queued, which the server still runs once (or refuses) and the replica still reconciles. The adapter is checked against a real kernel and zero-cache in [`registry/test/foldkit-adapter.test.ts`](../../registry/test/foldkit-adapter.test.ts), over the runtime in [`registry/test/foldkit-runtime-bridge.test.ts`](../../registry/test/foldkit-runtime-bridge.test.ts), and in the browser through the Foldkit shell ([`e2e/foldkit.spec.ts`](../../e2e/foldkit.spec.ts)).
149
+
150
+ ## Connections
151
+
152
+ `@eloxiv/client` also carries the Connection lifecycle headlessly ([`Connections.ts`](../../packages/client/src/Connections.ts)); screens bind to it, and none ships:
153
+
154
+ - **`connectionsOf(client, { baseUrl })`**: the `connections.*` actions (`list`, `add`, `disconnect`, `reconnect`, `tools`, `callTool`, and `apps.open`, `apps.call`, `apps.close`: headless MCP App sessions, whose `ui://` resource the app renders in a sandbox of its own; [ToolSource, "MCP App sessions"](tool-source.md#mcp-app-sessions)) and the [Secrets](secrets.md) routes (`secrets.put`, `inventory`, `previewRemoval`, `delete`): a secret is put there and only ever named afterwards, so its value never passes through an action. `add` answers what happened: `active`, `consent` (open it), `rejected` (`address`: the destination policy refused the endpoint; `input`: a missing secret, a bad option), or `forbidden`. `servers(provider = "mcp")` is the state a remote-servers screen renders (`idle`, `loading`, `ready`, `error`, the servers) with `refresh`, `create`, `remove`, `reconnect` and `test`, whose answer tells `ok` (the tools), `pending` (consent started, not finished), `needs-reauth` and `load-failed` apart. The servers' backend is the client given: an app hosting its own passes any object with `call` and `headers`.
155
+ - **`connectionsOf(...).channels`**: a channel Connection's channels (Slack's): `list(connectionId)` (the settings set, each with the tokens used today; a channel not listed takes the defaults) and `set(connectionId, channelId, change)` (`enabled`, `scope` `act` or `plan`, `dailyTokens`, `memory` `thread`, `channel` or `none`), over `connections.channels` and `connections.setChannel`. The Connection's owner's, or any with `eloxiv.connections.manage`; others are refused (`Forbidden`). Checked by [`registry/test/slack-agent.test.ts`](../../registry/test/slack-agent.test.ts) ([Connections, "Channels"](connections.md#channels)).
156
+ - **`consentInPopup({ open, start, appOrigin })`**: OAuth consent in a popup. Called from the person's gesture, it opens the window at once on a waiting page (so it is not blocked), asks `start` for the consent with a `returnTo` on the app's origin carrying a fresh nonce, and sends the window to the kernel's authorize URL. It completes only when the window comes back to `appOrigin` with that nonce and a `connection` id (another attempt's return, another origin, or the provider's pages complete nothing); closing the window cancels (`ConsentCancelled`), a blocked window is `PopupBlocked`, and it times out with the kernel's consent lifetime. `appOrigin` must be one of the kernel's trusted origins.
157
+ - **`authorizationResume({ storage })`**: a request blocked on a Connection's authorisation (an agent's tool call the server refused for want of consent) recorded before consent (in `storage`, such as `localStorage`, so a reload keeps it), consumed once after it, and `resume(connectionId, request, authorize, run)` running it again exactly once.
158
+
159
+ Checked by [`registry/test/client-connections.test.ts`](../../registry/test/client-connections.test.ts): the servers controller against a kernel and the MCP protocol fake (each outcome), the Secrets routes with usages and a removal preview, a tool call blocked on consent resumed once after the person consents; an MCP App session opened on a tool's view, called through and closed; the popup driven by a scripted window (opened before anything is awaited; only this attempt's return on the app's origin completes it; closed and blocked windows); a pending request surviving a reload and consumed once.
160
+
161
+ ## Model setup
162
+
163
+ `modelSetupOf(client, { baseUrl })` ([`Models.ts`](../../packages/client/src/Models.ts)) wraps [model setup](model-provider.md#model-setup): `catalogue`, `saveKey` (checked first; `setDefault`), `removeKey`, `check` (a refusal told from no answer), `choose`, `setPolicy`. `catalogueState()` is the state a model picker binds to (`idle`, `loading`, `ready`, `error`, the catalogue), reloaded after a choice and keeping a refused choice's error; `usableModels(catalogue)` lists what a picker may offer (allowed models of providers with credentials for the person). Checked by [`model-setup.test.ts`](../../packages/testing/test/model-setup.test.ts).
164
+
165
+ ## The chat SDK
166
+
167
+ `@eloxiv/client/chat` ([`Chat.ts`](../../packages/client/src/Chat.ts), decision 11) is the headless layer of a chat, its approval and consent prompts and an inbox: the state a UI keeps and renders, and the operations it runs, with no view code. The shell's reference chat screen (`chat-ui-foldkit`) wires it to Foldkit; any other UI uses it the same way. The state is a value (`ChatState`, a Schema, so a Foldkit Model can hold it): a UI feeds it what the replica delivers (`withMessages`, `withRuns` over `agent.messages` and `agent.runs`) and the active run's events (`withEvent`), and renders what it derives (`transcript`, `activeRun`, `canSend`, `engineBlocked`, the pending `consents`, `approvals(rows, userId)` over `approvals.requests`, `openItems` over `inbox.items`: the items still to act on, open, in progress or waiting, newest first, each an `InboxItem` with its source, the record it links to and the view that shows it, its assignee and due date; `stepsFor(item, userId)`, the steps the person may take on it).
168
+
169
+ | Operation (`chatClient({ baseUrl, token, orgId, sendTimeout?, reconnect? })`) | What it does |
170
+ | --- | --- |
171
+ | `send({ text, conversationId, idempotencyKey })` | `agent.send` under the key: `{ kind: "sent", conversationId, runId }`, or for a retry of a send already made `{ kind: "replayed" }` (the kernel runs it once). No answer within `sendTimeout` (30 s) fails with `Timeout` |
172
+ | `events(runId, after)` | The run's events after a sequence number, as they happen, ending after `run-finished` (a Stream). Every event names the run; streamed text (`text-delta`, which the kernel writes with neither) gets the run and `seq: -1`, and names its model step (`data.step`) and the model call of that step (`data.attempt`). A connection that drops or fails without a definitive answer is followed by another (backing off from `reconnect.base`, 0.5 s, to `reconnect.max`, 10 s) from the last stored event delivered; a refusal fails the stream. Interrupting it aborts its request at once, even while it is silent |
173
+ | `lookup(idempotencyKey)` | Whether the person's send under that key ran: `{ ran: true }` when its receipt is in the kernel's receipt store (`GET /agent/messages/<key>`), `{ ran: false }` when none has committed yet (which does not mean none will: a send still in flight commits its receipt with it) |
174
+ | `cancel(runId)` | `agent.cancel`, under the run's key (`cancel:<runId>`) |
175
+ | `readiness()` | Whether the person's agent can answer ([AgentRuntime](agent-runtime.md) `readiness`), for `withEngine`: the kernel's `configured`, `missing` or `unavailable`, or `unknown` when it could not be asked (no answer, a timeout, a gateway's error), never `missing` for a failed probe; a refused caller fails |
176
+ | `decideConsent(id, "approve" \| "reject", remember?)` | `consent.approve` or `consent.reject`, under the decision's key (`consent:<id>:<decision>:<remember>`) |
177
+ | `decideApproval(id, "approve" \| "reject", comment?)` | `approvals.approve` or `approvals.reject`, under the decision's key (`approval:<id>:<decision>`) |
178
+ | `workItem(id, "claim" \| "complete" \| "dismiss")` | `inbox.claim`, `inbox.complete` or `inbox.dismiss` on a work item, under the step's key (`inbox:<id>:<step>`): a retry acts once |
179
+
180
+ **Context, references and intents** (pure, over the state): `stageContext(state, { name, text, reference? })` stages named context for the next send (an item of the same name replaced; at most 10 items and 16 000 characters, else `staged: false` with why), `unstageContext` takes one back, and the send carries each under its name below the text (`[Context: deal (crm.deal "d-1")]`), then clears them; `insertReference(state, reference, label?)` puts a record's reference into the draft as the agent reads one. Another surface (a screen's "ask about this", a command, a deep link) asks through `applyIntent(state, { id, kind: "prefill" | "submit" | "open" | "stage", ... })`, which answers with its outcome for the sender (`{ id, applied, reason? }`): a prefill never replaces what the person is typing unless `replace`, and a submit is applied only while the composer may send (`submit: true` tells the UI to send now), so nothing is sent twice.
181
+
182
+ **Words for people:** `chatErrorMessage(error, catalog?)` and `toolActivity(events, { labels?, catalog? })` (a run's tool calls with their state, `running`, `done`, `failed`, `consent` or `delegated`, and words; a delegation is one line with its task, not a tool running; a call is named by the app's label for the tool, else the action's title from its events (for a MAKE action always `decisionLabel` of its id, whatever title an event carries), kept from an earlier event of the same call when a later one omits it, else the action's readable name for an older kernel's events, else the tool's name) take the app's locale catalogue over the English defaults (`CHAT_CATALOG_EN`). Tested in [`chat-context.test.ts`](../../packages/testing/test/chat-context.test.ts).
183
+
184
+ Every failure is a `ChatError` (`_tag`, `message`, `status`, 0 when there was no answer, and `approvalId` or `consentId` for work held); `isDefinitive(error)` says whether the kernel answered with a refusal (a 4xx but 408; `ApprovalRequired` and `ConsentRequired` are work stored, not refusals) or the answer was lost (no answer, a timeout, a 408, a gateway's or the server's 5xx: it may have run). Guarantees, each proven as pure transitions, against a stub server (lost and missing answers, dropped and silent streams), through the shell's chat screen, and against the agent conformance kernel, on its wire format (`registry/test/chat-sdk.test.ts`, `registry/test/chat-sdk-review.test.ts`, `registry/test/chat-sends.test.ts`):
185
+
186
+ 1. **One conversation, its own rows.** The transcript holds the conversation's stored messages in order (an answer with no text, a tool call, is not a line) and the active run's streamed text; another conversation's rows never appear.
187
+ 2. **Streamed text by model step, never twice.** A run's model steps each store one answer, in order; each step's streamed text shows until the replica holds that step's answer, which replaces it, and the text of a step's model call made again (after a restart, its first call's answer lost) replaces the earlier call's (`data.attempt`). An earlier step's stored answer never hides a later step's text, and a later step's text that arrives before the earlier step's stored event (streamed text is pushed at once; stored events are read from the database) is kept. A step's `model-step` event puts its stored text in place of whatever of it streamed, and its `reply-discarded` event (the reply arrived after the run's cancellation committed, so it is never the run's) removes what of it streamed.
188
+ 3. **Events only from the run they belong to.** Only the conversation's active run changes the state; a stored event counts once (by sequence number), so a reconnect's replay changes nothing; the stream's `run-finished` ends the run at once, even one the replica still reports running (`ChatState.ended`); a run the replica reports ended takes its streamed text and pending consents with it.
189
+ 4. **A send is one send, and its identity outlives any screen.** Only a non-empty draft, only with nothing in flight and no run going (the run a send started counts from the kernel's answer, before the replica has it). Each send carries an idempotency key, its identity. It is recorded before its request leaves (`submit` returns the `send` to record) in an **outstanding store** (`outstandingStore(storage)`: per person and organisation, in this page's memory and in a web `Storage` when given, `localStorage` in the shell; only text, conversation and key, never a credential; one list for every tab), and whoever made the request records its outcome there, whether or not the screen still exists; a state takes the store's sends (`withOutstanding`), so navigating away and back, an organisation switch and back, a reload and a sign-out (for the same person's next sign-in) all find them. A send leaves only on a **definitive outcome for its key**: an answer, a replay of its receipt, its receipt found by `lookup` (`lookedUp`), or a refusal of its first and only attempt. Its answer lost, it is `uncertain` (an attempt an earlier screen or page made without hearing back counts too), and the next send from its conversation resends it under its own key (`unresolvedSend`). Refused after that (before the kernel looked at the key: a policy or credential change), it is `unconfirmed`, shown as possibly sent, looked up by its key, and kept until its receipt is found or the person discards it (`discard`). `ApprovalRequired` and `ConsentRequired` keep it `awaiting-approval` or `awaiting-consent`, with the request it waits on. An answer (`sent`, `replayed`, `sendFailed`, each given the key) changes what is shown only for the state's own request and only if it came from the conversation shown; a refusal is kept typed, with the draft, under the conversation it came from.
190
+ 5. **Consent and approval are the person's.** Pending consent comes only from `consent-required` and leaves on `consent-decided` or the run's end; deciding is the kernel's action, which refuses an agent; the SDK never decides on its own. Every decision, and a cancel, carries a key of its own (`decisionKey`), the same on a retry, so a retry after a lost answer decides once.
191
+ 6. **Nothing of a conversation outlives the session or organisation, but the person's outstanding sends.** The state is a value a UI drops with the session or organisation (the shell discards its screens); its event stream's connection closes as soon as it is interrupted; the token is read only when a request is made. The outstanding sends are kept on purpose (guarantee 4): on a shared device, a send's text stays in `localStorage` until it is settled or discarded, under the person's id.
192
+ 7. **Drafting before setup, sending once set up.** While the kernel says the agent's model is `missing` or `unavailable` (`withEngine` with `readiness()`'s answer; `engineBlocked`), the composer keeps its draft, across conversations too, and does not send (`canSend` is false, `submit` makes no request); a screen shows `engine.detail`. `unknown` (not asked yet, or the probe failed) holds nothing back: the kernel answers the send itself (`packages/testing/test/agent-readiness.test.ts`).
193
+
194
+ ## Consent and the agent's usage
195
+
196
+ - `consentController({ baseUrl, region?, fetch? })`: a visitor's consent before sign-in (their choices on their visit, the touch that brought them, kept only with marketing consent), the scripts the app loads per category (`register({ category, load, unload })`), every new state to a banner or a consent-mode adapter (`subscribe`), and the visit claimed at sign-in (`claim(token)`). See [Privacy](privacy.md#visitors-before-they-sign-in).
197
+ - The agent client reads the person's usage (`usage`, `insights`, `runUsage`, `budgets`; [Metering](metering.md)) and their runs' traces and feedback (`trace`, `feedback`, `feedbackList`; [AgentRuntime](agent-runtime.md)).
198
+
199
+ ## Collaboration, sharing and history controllers
200
+
201
+ Headless controllers for what a share dialog, an access screen, a history panel and an editor's collaboration chrome need, with no view code (decision 11). Each keeps client-side state an app renders (`state`, `subscribe`, `dispose`) and changes things only through the kernel's actions, so the record's own policy decides every change, an agent's grant or restore waits for its person's consent, and every call is audited. They take `call`: an `EloxivClient`'s `call` as `actionCall(client)` gives it, answering with the result envelope (`{ kind: "output", output }`) or rejecting with the typed error. One adapter (`outputOf`, `outputs`) reads every answer; a replay (`{ kind: "replay", receipt }`, which they never ask for, since they send no idempotency key) carries no output and is refused (`ActionReplayed`), as is anything that is not an envelope.
202
+
203
+ | Entry | Export | What it does |
204
+ | --- | --- | --- |
205
+ | `@eloxiv/client/collab` ([`CollabTools.ts`](../../packages/client/src/CollabTools.ts)) | `followPeer(connection, { onViewport, key })` | Follow a collaborator's viewport (`CollabViewport`: view, scroll, zoom, cursor, published in their presence under `viewport`; `withViewport` builds it, `readViewport` checks one). Each change arrives once; a malformed viewport never does. Following stops when asked, when the collaborator leaves, when their client id is announced by another person, and when the connection closes |
206
+ | | `localUndo(doc, { scope, origins, captureTimeoutMs })` | Undo and redo of this client's own changes only (Yjs `UndoManager` over the local origins; the remote origin is never tracked): a collaborator's and an agent's edits stay. An undo is sent like any change, and refused like any, when the caller may not change the document |
207
+ | | `recentEdits(connection, { text, ttlMs, max })` | Collaborators' recent insertions and deletions in a text, attributed to the person **the kernel recorded** for each update (`connection.remoteAuthor`: user, origin `person`/`agent`/`system`, sequence number), never to what a client says of itself; positions follow later edits |
208
+ | `@eloxiv/client/sharing` ([`Sharing.ts`](../../packages/client/src/Sharing.ts)) | `shareController({ call, record, needsConfirmation })` | A record's grants (`sharing.list`) for someone who may share it, changed optimistically: a grant shows at once as `adding` and a revocation as `removing`; the kernel's answer reconciles them, a refusal rolls back with the typed error. A load that started earlier never overwrites a later one. A link's token is in `share`'s result only, never in the state. Someone who may not share sees nothing (`canManage: false`) and changes nothing |
209
+ | | the same, `state.held`, `confirm`, `cancel` | A grant that widens access (by default, to the whole organisation when no unexpired grant already shares it that way; an expired grant still listed never counts) is **held, nothing saved**, until `confirm`; `cancel`, `dispose`, losing the right to share, or the record being shared that way elsewhere drop it (`SharingNotSaved("dropped")`), and it is never saved; a confirmed save that fails stays held with its error, to retry |
210
+ | | `wideningTransition({ current, needsConfirmation, apply, canChange })` | The same confirmation rule for any change that widens access, a module's own visibility action included (`private` to `org`): held until confirmed, dropped if the value moves under it or changing is no longer allowed; narrowing saves at once |
211
+ | | `accessGate({ call, record, onAccessGranted, pollMs })` | The gate in front of a record someone was sent to (`sharing.access`): `allowed`, `unavailable` (no such record, another organisation's, or not readable: the kernel never says which), `signed-out`, `failed`; their own latest access request; `requestAccess(permission, message)`. While their request is pending it checks again every `pollMs` (30 s) and calls `onAccessGranted` once the record opens. It is `allowed` only when the kernel just said so |
212
+ | | `decideAccessRequest(call, id, "approve" \| "deny")` | Decide a request; one that can no longer be decided (decided already, or the decider lost the right to share) comes back `stale` |
213
+ | `@eloxiv/client/history` ([`History.ts`](../../packages/client/src/History.ts)) | `documentHistory({ call, record })` | A collaborative document's checkpoints (`collab.history`), `snapshot(label)` (`collab.snapshot`) and `restore(version, { baseSeq })` (`collab.restore`; with the sequence number the person looked at, refused as a version conflict if the document changed since) |
214
+ | | `recordHistory({ call, entity, id, restore })` | A record's versions (`versioning.history`, `versioning.version`); restore through the module's own action, which the app passes |
215
+ | | `agentEdits({ call, conversationId, messageId, revertRecord })` | What the person's agent changed in one of their conversations (`versioning.agentEdits`: one message's run, or every run back to the start of the chat) and `revert()`: each document through `collab.revert`, each record through the module's revert action the app passes per entity (`{ "journal.entry": (input) => client.call("journal.revert", input) }`), item by item, with each item's outcome (`done` with what it did, `failed` with the refusal, `skipped` without an action); later edits by people stay ([Versioning](versioning.md#agent-edit-groups)) |
216
+
217
+ What the record's policy hides, these show nothing of: a history or a share list the caller may not read is `unavailable` or `canManage: false`, the same for a record that does not exist. Proven against a real kernel in [`packages/testing/test/collab-access-client.test.ts`](../../packages/testing/test/collab-access-client.test.ts).
218
+
219
+ ## Diagnostics and analytics helpers
220
+
221
+ - `chatIntegrity({ surface, report })` (`@eloxiv/client/chat`, [`ChatIntegrity.ts`](../../packages/client/src/ChatIntegrity.ts)), opt-in: fed what a chat screen feeds its state (`observe(event)` beside `withEvent`, `ended(runId)` when a run's stream closes or the replica says it ended, `recorded(key)` and `settled(key)` with the outstanding store, `audit(outstandingSends(state))`), it reports ordering gaps, duplicates and reordering of a run's stored events, a run that ended without `run-finished` (also one whose stream ended before any stored event), and sends that left the outstanding store without a definitive outcome. Each report names the surface and is redacted: run ids, sequence numbers and event types, never an event's data, a message's text or a send's key. ([`chat-integrity.test.ts`](../../packages/testing/test/chat-integrity.test.ts))
222
+ - `browserAnalytics({ track, consent, routes, actions })`: pageviews by route name, lifecycle and action timing as declared `client.*` events, only with analytics consent ([Telemetry](telemetry.md)).
223
+
224
+ ## Agent resources
225
+
226
+ `@eloxiv/client/resources` ([`Resources.ts`](../../packages/client/src/Resources.ts)) is the headless layer of an agent-resources screen (AgentResources, Memory): `agentResources({ baseUrl, token, orgId, call })` reads the person's effective resources, each scope's own (`GET /agent/resources`) and their memory (`GET /agent/memory`) as state (`effective`, `scopes`, `layered`: every (kind, path) with the resource in effect and the farther scopes' it overrides, `memory`), draws them as a folder tree by their paths (`tree(kind?)`; `layerResources` and `resourceTree` are pure), and changes them through the agent's actions (`put`, `remove`, `remember`, `forget`, `exportPack`, `importPack`), loading again after each. `call` is an `EloxivClient`'s (`actionCall(client)`), read through the same envelope adapter as the sharing controllers (`outputOf`: the output, a replay refused). A load that started earlier never overwrites a later one; a refusal is kept as `error`. Proven against a real kernel in [`packages/testing/test/resources-client.test.ts`](../../packages/testing/test/resources-client.test.ts).
227
+
228
+ ## React Native
229
+
230
+ The root SDK, its sync storage for SQLite (`@eloxiv/client/expo-sqlite`), optimistic writes, the collaborative-document client (`@eloxiv/client/collab`) and the chat SDK (`@eloxiv/client/chat`) run on React Native's Hermes; the [Mobile guard](../scaffold.md#desktop-and-react-native-in-ci) proves each on an Android emulator in CI. The Foldkit adapter is for the browser (decision 10). What an app on React Native provides:
231
+
232
+ - **The replica's store:** `connectSync({ ..., storage: expoSQLiteStoreProvider() })` (`expo-sqlite`), so the replica is on disk.
233
+ - **A random source for Yjs**, if it uses collaborative documents: Hermes has no `crypto`, and Yjs's lib0 loads `isomorphic-webcrypto` on React Native. Resolve that module (`isomorphic-webcrypto/src/react-native`) to one exporting `{ ensureSecure, subtle, getRandomValues }` over a native source, as the guard does with `expo-crypto` ([`webcrypto.ts`](../../tools/react-native/webcrypto.ts), [`metro.config.js`](../../tools/react-native/metro.config.js)).
234
+ - **Effect from the same copy the SDK uses**, if the app runs the chat SDK's Effects itself (`Effect.runPromise`): one `effect` package in the bundle.
235
+
236
+ The SDK itself uses no ES2023 array copying methods (`toSorted` and the like) and no `btoa`/`atob`, which Hermes or React Native's type definitions lack. Where a platform's `fetch` has no streaming body, the agent and chat clients read each event-stream connection whole once it ends (and the chat reconnects from the last event it saw), so streamed text arrives in batches rather than as it is written; the guard's chat, consent included, runs either way.
237
+
238
+ ## How an implementation is checked
239
+
240
+ `clientSdkConformance(start)` takes a running kernel (with a minimum client version) and zero-cache serving an app with a synced, policy-filtered write, the SDK under test, and optionally an agent: sign-in and refused credentials, organisations, the envelope and replay receipt, invalid input and an unknown credential refused, another client's write synced and a private one withheld, switching organisations for calls and replicas (and refusal outside one's organisations), `ClientOutdated` with the replica still reading and the release's minimum, sign-out, and an agent message whose run finishes. Eloxiv's SDK runs it in [`registry/test/client-sdk.test.ts`](../../registry/test/client-sdk.test.ts) against the registry app (kernel and zero-cache as processes) and the agent conformance kernel.
241
+
242
+ ## Not yet guaranteed
243
+
244
+ - **Sync re-exports** (the query builder, hooks, `@eloxiv/client/react`) are being reworked under decision 9; this contract names `connectSync` and the named queries.
245
+ - **No offline write queue** beyond the replica's optimistic state.