@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,151 @@
1
+ # CollabDocument
2
+
3
+ Collaborative documents owned by module records: a Yjs document per record, edited live by people and agents (decisions.md "Kernel contracts"; Stack: Collaboration is Yjs; the ledger's A-052, B-038 to B-041, C-022, C-023).
4
+
5
+ - Kind: kernel service. Version 1.1.0 (1.1.0 added agent autosaves and `collab.revert`).
6
+ - Schema: [`packages/contracts/schema/contracts/CollabDocument.json`](../../packages/contracts/schema/contracts/CollabDocument.json) (source [`CollabDocument.ts`](../../packages/contracts/src/contracts/CollabDocument.ts); the entity declaration `EntityCollab` in [`Module.ts`](../../packages/contracts/src/Module.ts) and its checks, `collabProblems`, in [`Manifest.ts`](../../packages/contracts/src/Manifest.ts)).
7
+ - Implementation: the `Collab` service in [`packages/kernel/src/collab/Collab.ts`](../../packages/kernel/src/collab/Collab.ts), its Yjs handling in [`Ydoc.ts`](../../packages/kernel/src/collab/Ydoc.ts), the transport in [`Socket.ts`](../../packages/kernel/src/collab/Socket.ts), the kernel module `collabModule` ([`module.ts`](../../packages/kernel/src/collab/module.ts)); kernel migrations `0035_collab` and `0185_agent_edit_groups`; the client in [`@eloxiv/client/collab`](../../packages/client/src/Collab.ts) and the Foldkit adapter in [`@eloxiv/client/foldkit`](../../packages/client/src/Foldkit.ts).
8
+ - Kit: `@eloxiv/testing/conformance/CollabDocument` ([source](../../packages/testing/src/conformance/CollabDocument.ts)).
9
+
10
+ ## Declaring that an entity has collaborative documents
11
+
12
+ ```ts
13
+ import { defineEntity } from "@eloxiv/contracts/drizzle"
14
+
15
+ export const note = defineEntity(tables.note, {
16
+ // name, cedarType, policyAttributes (exactly one Eloxiv::Org column) ...
17
+ collab: {
18
+ maxBytes: 2 * 1024 * 1024, // the merged document (default 2 MiB, at most 16 MiB)
19
+ maxUpdateBytes: 256 * 1024, // one update (default 256 KiB, at most maxBytes)
20
+ updatesPerMinute: 1200, // per person per document in any 60 seconds (default 1200, at most 6000)
21
+ text: "content", // the Y.Text agents read and edit when they name none (default "content")
22
+ },
23
+ })
24
+ ```
25
+
26
+ Install the kernel's `collabModule` in `KernelApp.modules`. Who may **read** a record's document (open it, receive its changes, publish presence) is the entity's Cedar `read` policy; who may **change** it (updates, agent edits, restores) is its policy for the kernel's action **`collaborate`**:
27
+
28
+ ```cedar
29
+ permit (principal, action == Notes::Action::"collaborate", resource is Notes::Note)
30
+ when { resource.org == principal.org };
31
+ ```
32
+
33
+ An entity without a `collaborate` policy has read-only documents (fail closed). Startup refuses a `collaborate` policy not tied to the actor (the organisation, a user field equal to the actor, or a sharing grant), as it refuses such an `attach` or `read` policy; `collaborate` is reserved, so no module action may take the name; the entity needs exactly one organisation attribute. Deleting the record deletes its document, in the same transaction (the entity's table is tracked like Search's and Files').
34
+
35
+ ## Guarantees
36
+
37
+ 1. **Ownership: one path, the authority, the record's policy, now.** Every read of a document's state, every update and every presence message is an action of the kernel's `collab` module, so it goes through the one invocation path: identity (a signed-out session, a revoked agent session or API token, a member who left all fail there), the credential's scope (a token scoped to `collab.open` and `collab.pull` reads and cannot write), `Authority.assert` (the credential's chain and the person's membership, each link locked in the global order), policy, audit. Every statement on the document tables requires the capability that assertion returned (`Asserted`, bound to the call's transaction and person: `inCollab` in `Collab.ts`; `authority-transcripts.test.ts` derives the guarded tables from the privacy inventory, where they are marked `guarded`, and fails on any statement on them that is not under the capability or listed with a reason: compaction, expiry, and data-subject requests, the kernel's own). Then the record decides, now, in the caller's organisation: its `read` or `collaborate` policy compiled for the caller and checked against the record as its module's role under row-level security (`records/Access.ts`). A record that does not exist, one of another organisation and one the caller may not use get the same `Forbidden`.
38
+ 2. **Revocation mid-session.** A connection's frames and deliveries are invocations with its credential (below), each asserting its authority again (links before the rows they protect). When a grant, a membership, a session or a token is revoked, the connection's next delivery is refused and the connection closed (close code 4403 or 4401, after a `closed` frame naming the refusal): it receives nothing committed after the revocation took effect, and its later updates are refused. An idle connection re-checks at least every `reauthMs` (15 s by default). A connection authenticated with a person's own session closes at once when the kernel ends that session (sign-out or a revocation, in any kernel process: `Identity.onSessionEnded`), idle or not, with 4401; the person's other sessions' connections stay open ([`session-commit.test.ts`](../../packages/testing/test/session-commit.test.ts)). Every call a connection makes acts in the organisation it opened in.
39
+ 3. **A document never outlives its record.** A change takes the record's lock (the search lock shared, then the record's own, after the authority links and before any row: `search/RecordLock.ts`), then checks the record exists and may be changed, then creates or appends. Deleting a tracked record takes the same lock (`eloxiv.forget_record`, in the deleting transaction) and deletes its document, updates, checkpoints, contributions and presence: a deletion in flight makes a first update wait and then refuses it; a first update in flight makes the deletion wait and then deletes what it wrote.
40
+ 4. **Durable, append-only storage.** Each update is stored (`eloxiv.collab_update`) in the transaction that accepts it, numbered (`seq`) under the document row's lock, with who made it, how (`person`, `agent`, `system`) and its invocation id (the audit record's). A trigger refuses any change to a stored update except an erasure's pseudonym of its author, and the deletion of any update the snapshot does not hold. No module role has any privilege on the kernel's collab tables. Who contributed to which document (`eloxiv.collab_contribution`: updates, bytes, first and last time) is kept beside the updates and never deleted by compaction.
41
+ 5. **Whole reads, and compaction never loses an update.** Every reader (open, pull, the text projection, history, restore, export) reads a document's snapshot and the updates after it in one statement, which sees one snapshot of the database, and checks it holds every update up to the head; readers merge what they read every time, and only writers, under the document row's lock, reuse a cached merged state (matched by the head's id, so an uncommitted write is never matched). Compaction reads the document whole, merges it, and in a short transaction of its own writes the snapshot only if nobody compacted meanwhile and deletes only the updates it merged: an update committed while it ran (a later `seq`) stays. Runners compact documents with 100 or more updates past their snapshot every `sweepMs` (10 s); each compaction keeps a checkpoint (the latest 20).
42
+ 6. **Limits fail closed.** An update larger than `maxUpdateBytes`, one that would make the document larger than `maxBytes`, one past the person's `updatesPerMinute` on the document in the last 60 seconds (a sliding window of their updates' times, by the database's clock; `ActionFailed`, "Too many updates…"), and bytes that are not a Yjs update (`InvalidInput`) are refused, and nothing of them is stored. The transport reads every frame as it arrives (the runtime would otherwise buffer without bound) into a bounded queue: a frame larger than an update can be closes the connection on arrival (1009), more than 32 frames or 4 frame-sizes (at least 1 MiB) waiting to be answered close it (1008), more than 30 presence frames a second or presence for more than 4 clients close it (4429).
43
+ 7. **Convergence.** A client sends what it has and the kernel lacks when it (re)connects (its changes against the kernel's state vector) and receives what it lacks; Yjs merges both ways, so clients converge whatever they edited offline and in whatever order they reconnect. A client whose updates were compacted away while it was offline receives the whole state.
44
+ 8. **Presence is ephemeral, kernel-only and newest-wins.** Presence (any JSON up to 4 KiB: name, cursor, selection) is stamped by the kernel with the person, relayed to the document's readers, and held only while live in a kernel-only, unlogged table (`eloxiv.collab_presence`: never in the write-ahead log, emptied after a crash, no module role granted) with an expiry 30 seconds after its last refresh by the database's clock. Each announcement carries the client's clock; the kernel keeps the newest, and a withdrawal stays as a tombstone for ten minutes, so an older announcement arriving or replayed later loses. A client's presence cannot be taken over by another person. Withdrawn when the connection closes: only what that connection announced last (each client's clock), so a newer announcement made over another connection (the same client reconnected) stays. **Notifications carry nothing**: any database role may `LISTEN` on any channel, so a committed change wakes kernel processes with an empty notification on `eloxiv_collab`, and what changed is a row of the kernel-only `eloxiv.collab_change`, which they read; no document, record, person or presence is ever in a payload or channel name.
45
+ 9. **Version conflicts are explicit.** Yjs merges concurrent changes, which is right for people typing; a write computed from what someone read (an agent's `editText` from a `readText`, a restore chosen from a history) may instead name the sequence number it was made against (`baseSeq`). It applies only if the document is still at that number, checked under the document row's lock; otherwise it is refused, `InvalidInput` with a message starting `Version conflict:` (`COLLAB_CONFLICT`), and nothing is written. Without `baseSeq` the write merges as before.
46
+ 10. **Agents.** `collab.readText` reads a root as text (a Y.Text as is, Y.XmlFragment as its text, maps and arrays as JSON). `collab.editText` applies edits to a text root as Yjs operations computed by the kernel against the head, under the record's and the document's locks, as one update attributed to the person with origin `agent` when an agent calls (audited like every call); it merges with concurrent edits, and connected editors receive it like any update. **Every change an agent makes to a document needs its person's consent, whichever action carries it**: `update` (a raw Yjs update), `editText` and `restore` are consent-marked, so an agent's call (the agent's tools, MCP, an agent session on any surface) waits for its person's consent or a permission they remembered (ActionConsent), and is refused outright in an app without the consent module; a raw update is no way around `editText`'s consent. Reading and presence need none: presence never changes the document.
47
+
48
+ ## Operations
49
+
50
+ All but `compact` and `connect` are actions of the kernel module `collab` (typed client, HTTP `POST /api/actions/collab.<name>`, MCP tools `collab_<name>`, agent tools, the CLI). A record is `{ entity: "<Module>::<Type>", id }`; updates and states are standard base64.
51
+
52
+ | Operation | Action | Input | Output | Needs |
53
+ | --- | --- | --- | --- | --- |
54
+ | `open` | `collab.open` (read-only) | record | `CollabState`: `{ seq, state, stateVector, canWrite, bytes, limits }` | read |
55
+ | `pull` | `collab.pull` (read-only) | record, `after` | `{ seq, updates: [{ seq, update, actorUserId, origin, at }], reset, awareness }` (`reset`: the whole state when the updates after `after` were compacted, are too many, or `after` is not a sequence number the document reached) | read |
56
+ | `update` | `collab.update` | record, `update` | `{ seq, bytes }` | collaborate |
57
+ | `awareness` | `collab.awareness` | record, `clientId`, `clock` (increasing per client), `state` (JSON text or null) | `{}` | read |
58
+ | `readText` | `collab.readText` (read-only) | record, `text?` | `{ seq, name, text, roots: [{ name, kind }] }` | read |
59
+ | `editText` | `collab.editText` | record, `text?`, `edits` (1 to 100: `{ kind: "replace", find, replace, occurrence? }`, `{ kind: "insert", text, at: "start" \| "end" \| { after } }`, `{ kind: "set", text }`), `baseSeq?` | `{ seq, text }` | collaborate |
60
+ | `history` | `collab.history` (read-only) | record | `{ versions: [{ version, seq, bytes, reason, label, at }] }` (`reason`: `compaction` or `snapshot`) | read |
61
+ | `snapshot` | `collab.snapshot` | record, `label?` (at most 200 characters) | one version | collaborate |
62
+ | `restore` | `collab.restore` | record, `version`, `baseSeq?` | `{ seq, text }` | collaborate |
63
+ | `revert` | `collab.revert` | record, `conversationId`, `messageId?` | `{ seq, text, runs }` (`runs`: how many of the group's runs had changed it; 0 writes nothing) | collaborate |
64
+ | `compact` | in process (`CollabHousekeeping.compact`, the runners' sweep) | document id | the sequence number the snapshot holds | the kernel |
65
+ | `connect` | the transport, `GET /collab/socket` | `ClientFrame`s | `ServerFrame`s | as each frame's action |
66
+
67
+ Errors: `Unauthenticated`, `Forbidden`, `InvalidInput`, `ActionFailed` (the rate limit), as every action's.
68
+
69
+ ## The transport
70
+
71
+ **Choice: a WebSocket on the kernel's own HTTP server.** Yjs needs a low-latency, bidirectional, long-lived channel (a person's keystrokes reach others within the write budget, presence moves continuously). The kernel's HTTP server (Effect's platform servers on Bun and on Node both upgrade WebSockets) serves it on the same origin, port and process as every other surface, with nothing new to deploy. Effect RPC was the alternative: its typed request/response would carry `update` well, but the deliveries are a per-connection stream that must re-authorise on every push, which is simpler as a loop over the one invocation path than as an RPC stream. **Zero does not fit**: it replicates rows, and a Yjs document is a merge of binary updates, not rows; storing updates as synced rows would put every keystroke into every replica of the table (and its permission filters) and still need a merge on the client; and presence is ephemeral, which Zero is not. Zero keeps the records; the documents travel beside them.
72
+
73
+ **Frames** (JSON text):
74
+
75
+ - Client to kernel: `{ _tag: "hello", entity, id, token?, orgId? }` first (within 10 s), then `{ _tag: "update", ref, update }` and `{ _tag: "awareness", clientId, clock, state }`.
76
+ - Kernel to client: `{ _tag: "sync", state }` (the `collab.open` result), `{ _tag: "updates", pull }` (a `collab.pull` result, without the connection's own updates and presence), `{ _tag: "ack", ref, seq }`, `{ _tag: "refused", ref, error }`, and `{ _tag: "closed", error }` before the kernel closes the socket over a refusal.
77
+ - Close codes: 4401 unauthenticated, 4403 forbidden (access refused or revoked, the record deleted), 4400 a malformed frame or no hello, 4429 too many presence frames or clients, 1008 too many frames waiting, 1009 a frame too large.
78
+
79
+ **Every frame is an invocation.** `hello`'s credential (a bearer token: a session, an agent session, an API token; or else the upgrade request's own `Authorization`) becomes the connection's request headers; `hello` is `collab.open`; each `update` frame is a `collab.update` call, answered in order; each `awareness` frame a `collab.awareness` call. Deliveries are pulls: a committed update or presence change on the record writes a `collab_change` row and an empty notification on `eloxiv_collab` (in its transaction, so only once it commits); every kernel process listens, reads the new change rows (looking back over ids a slower transaction may commit late), and wakes its connections on those records, and each calls `collab.pull` as its own caller and sends what it returns. So nothing reaches a connection unless its caller may read the record at that moment, and no kernel process shares state with another but through PostgreSQL.
80
+
81
+ **Cookies** authenticate a socket only when its `Origin` is one of the kernel's `trustedOrigins` (or it has none, as a non-browser client): browsers send cookies on cross-site WebSocket requests and CORS does not apply to them, so without the check any page could open a socket as the person. A bearer credential in `hello` works from anywhere.
82
+
83
+ ## Live copies
84
+
85
+ A module that wants a document's text in its own row (to list, search or export it) keeps a **live copy**: its own column, written by its own subscriber, under its own row-level security. The kernel never writes a module's columns; it gives the module two things:
86
+
87
+ - **The event `collab.changed`** (`{ entity, id, seq }`, the collab module's event, `collabChanged` in `@eloxiv/kernel`), written to the outbox in the transaction of every call that changed a document (`collab.update`, over the socket too, `collab.editText`, `collab.restore`): committed with the change, never without it, and never for a refused call. It carries no content.
88
+ - **`ctx.collab.text({ entity, id, root? })`** on a subscriber's context: the text of a root (default the entity's `collab.text`) and the sequence number it holds, or `null` for a record with no document. It answers only for the subscribing module's own entities with documents (anything else is `Forbidden`), and only while the record exists in the event's organisation now: a record deleted or moved to another organisation since the event gives `null`. It never changes the subscriber's role: it is one statement on the subscriber's own connection, as its module role, that reads the document through the platform function `eloxiv_platform.collab_state` (SECURITY DEFINER, executable by module roles only; it answers only during a module's subscriber delivery, for that module's documents, whose Cedar namespace the dispatcher records in the invocation context, kernel migration `0076_subscriber_context`, in the context's organisation) and requires the owning record under the subscriber's row-level security in the same snapshot. So a module never reads another module's document, nor another organisation's, nor a record it no longer has.
89
+
90
+ **Version conflicts.** Deliveries can overlap or repeat, so the copy keeps the sequence number it was made from and a write never replaces a newer one:
91
+
92
+ ```ts
93
+ subscribe("notes.liveCopy", collabChanged, (event, ctx) =>
94
+ Effect.gen(function* () {
95
+ if (event.entity !== "Notes::Note") return
96
+ const copy = yield* ctx.collab.text({ entity: event.entity, id: event.id })
97
+ if (copy === null) return
98
+ yield* ctx.sql`UPDATE notes.note SET body_text = ${copy.text}, body_seq = ${copy.seq}
99
+ WHERE id = ${event.id} AND body_seq < ${copy.seq}`
100
+ }),
101
+ )
102
+ ```
103
+
104
+ **The merge and the derive are bounded tasks.** `ctx.collab.text` reads the document's stored updates and hands them to the [Sandbox](sandbox.md) (QuickJS in a worker thread, at its ceilings: 10 s, 200,000 steps, 64 MiB, 4 MiB of arguments), where a bundled Yjs merges them and projects the root as text, exactly as the kernel's own reads do (`collab/derive/entry.ts`, bundled into `bundle.gen.ts` by `packages/kernel/scripts/bundle-derive.ts`). The kernel's process never merges them for a live copy. Without a Sandbox, or past its limits (a document of more than about 3 MiB, whose updates no longer fit the task's arguments), the read fails (`ActionFailed`) rather than run inline: the delivery is retried and then dead-lettered (the Outbox contract), and the copy stays at the last version it reached.
105
+
106
+ **The document is the only writable source.** The module's own actions must not write the copy's columns, and a copy is the record's content: the module's `dataSubjects` decide what erasure does to it, as for any column.
107
+
108
+ ## Privacy
109
+
110
+ A record's document belongs to its record, so the module's `dataSubjects` decide what happens to it:
111
+
112
+ - **Erasure.** When the module deletes a record about the person, the record's document, its updates and checkpoints go in the same transaction (`eloxiv.forget_record`). When the module keeps or anonymises the record, its document stays with it, and every update the person made, and their entry in the contribution ledger, is attributed to their erasure pseudonym. **What the person wrote in someone else's shared document stays in that document**: it is merged into text others wrote and rely on, it is the record's content (as a file attached to someone else's record is), and cutting it out would rewrite their work; the person's authorship is removed. The person's live presence and rate-window rows are deleted.
113
+ - **Export.** For every record the module exports as about the person, the export holds the record's document (`eloxiv.collab`: every root as text and the sequence number it holds), and the person's contributions to any document, other people's included and whether or not their updates were compacted away (`eloxiv.collab_contribution`: the record, how many updates and bytes, first and last time).
114
+
115
+ The inventory ([privacy.md](privacy.md#the-inventory-of-the-kernels-stores)) lists `collab_document`, `collab_update`, `collab_version`, `collab_contribution`, `collab_rate`, `collab_presence` and `collab_change`.
116
+
117
+ ## Versioning
118
+
119
+ The Versioning contract exists ([versioning.md](versioning.md)): its record history keeps a record's columns, which do not hold the document. Documents follow its rules with checkpoints of their own: every compaction keeps the snapshot as a checkpoint (`collab.history`), and someone who may change the document can keep one when they choose (`collab.snapshot`, with a label; under the `collaborate` policy and the record's lock; an agent needs no consent, since it changes no text). The latest 20 of each kind are kept (kernel migration `0075_collab_snapshots`), so many snapshots never crowd out compaction's checkpoints, nor they the snapshots. Checkpoints are readable exactly when the record is (the record's read policy, as Versioning's rule for history); `collab.restore` brings every text root back to a checkpoint as new Yjs operations, under the `collaborate` policy, recorded and attributed like any update. Roots that hold maps, arrays or XML are not restored (see below).
120
+
121
+ ## Agent autosaves and revert
122
+
123
+ **Autosave.** When an agent run's tool call first changes a document (`update`, `editText`, `restore`, any of them, under the record's and the document's locks), the kernel keeps the document as it was before that change as a checkpoint with reason `agent`, with the run's [edit group](versioning.md#agent-edit-groups) (run, conversation, message) and the person it acted for, and records what each of the run's updates applied (`undo`): the structs it added (the document's state vector's growth) and the structs it deleted that were not deleted before, never the bytes the client sent, so an update that resends the whole document adds nothing but what is new. It also counts the run's updates. A run that changes the document again after it was reverted starts a new autosave. `collab.history` lists autosaves beside the other checkpoints (`agentRunId`), and `collab.restore` can bring a document back to one. The latest 20 autosaves of a document are kept, apart from compaction's checkpoints and people's snapshots.
124
+
125
+ **Revert** (`collab.revert`, the `collaborate` policy, consent-marked like every change an agent makes): undoes one of the caller's edit groups in the document, `{ conversationId, messageId }` for one message's run (with its sub-agents'), `{ conversationId }` for every run of the conversation. Only autosaves of runs that acted for the caller belong to their group. The kernel builds a Yjs document from the group's autosaves and the current state **without garbage collection** (so text a run deleted is there to bring back, even after compaction folded it away), gives a Yjs `UndoManager` one stack item per run (what the run's updates applied: inserted, newly deleted), and undoes them, newest first; the result is appended as one update, attributed and audited like any, and announced (`collab.changed`). Each autosave undone is marked as undone (`undone_at`, under the document row's lock), so reverting the group again finds nothing left and writes nothing; the update the revert appended is recorded beside it (`reverted_seq`) only when it appended one (undoing a run whose updates changed nothing appends nothing), so a record's check for changes from outside the group subtracts only reverts that happened. Every kind of root is reverted (texts, maps, arrays, XML), not only text roots as `restore` is.
126
+
127
+ **What someone changed since stays**, by Yjs's own undo rules: a person's insertion, anywhere, is never removed (also inside text the run wrote: the run's characters go, theirs stay); text the run deleted comes back; a map entry (or an XML attribute) someone set after the run keeps their value, one only the run set goes back. A person who may not change the document now is refused (`Forbidden`) and nothing is written; a group with no autosave of the caller's on the document writes nothing (`runs: 0`).
128
+
129
+ ## Clients
130
+
131
+ - **`@eloxiv/client/collab`**: `connectCollab({ baseUrl, entity, id, token, orgId, doc? })` keeps a `Y.Doc` in sync (any root: texts, maps, arrays, an editor's XML), with `status` (`connecting`, `synced`, `offline`, `closed`), `canWrite`, `peers`, `setPresence`, `whenSynced`, `flush`, `disconnect`/`connect` and `closedWith` (why the kernel closed it; a closed connection never reconnects). `applyTextEdits(doc, name, edits)` applies `editText`'s edit kinds to a live document. Headless: it needs only a `WebSocket` (browsers, Bun, Node 22+), outside the SDK's root entry so React Native bundles are unaffected.
132
+ - **Collaboration helpers** in `@eloxiv/client/collab` ([ClientSDK](client-sdk.md#collaboration-sharing-and-history-controllers)): `followPeer` (follow a collaborator's viewport, published in presence), `localUndo` (undo only this client's own changes, never a collaborator's or an agent's), `recentEdits` (collaborators' recent edits, attributed to the author the kernel stored for each update, exposed by the connection as `remoteAuthor` while it applies one); and `documentHistory` in `@eloxiv/client/history` (checkpoints, snapshots, restore with `baseSeq`).
133
+ - **`@eloxiv/client/foldkit`** (decision 10): `collabDocument({ baseUrl, credentials, document, text, toMessage })` is a Subscription entry: while the Model names a record and a session handle (`CollabTarget`), the document is open and every change arrives as a `CollabSnapshot` Message (text, status, peers, `canWrite`, `closedWith`); when the Model names another record, organisation or session, the connection closes. The `Y.Doc` stays in the runtime, never in the Model. Commands edit it with `editCollabText` (fails `CollabEditRefused` applying nothing, or `CollabUnavailable`) and `setCollabPresence`. The bearer token stays in `Credentials`, out of the Elm state.
134
+
135
+ **Example**: the registry's `notes` module (0.6.0) gives every note a collaborative document (`content`) that the organisation's members write together; [`registry/test/notes-collab.test.ts`](../../registry/test/notes-collab.test.ts) has two people's clients and an agent edit one note at once against a real kernel, and drives the Foldkit adapter.
136
+
137
+ ## How an implementation is checked
138
+
139
+ `collabDocumentConformance(start)` takes a `CollabSubject` ([`CollabSubject.ts`](../../packages/testing/src/conformance/CollabSubject.ts)): a kernel serving the collab conformance app ([`conformance/pad`](../../packages/testing/src/conformance/pad): pages with an owner, a visibility and `read` and `edit` sharing grants, small limits), re-checking idle connections every second, with controls (users, membership, calls on every surface, agent sessions, a browser session's cookie, superuser SQL, audit, compaction with a hook between its read and its write, the housekeeping sweep, a superuser transaction held open, listening on the wake-up channel as any role could, and a second kernel process on the same database). The kit checks every guarantee above by trying to break it: calls on every surface and over the socket audited; private, organisation-visible and shared pages read and changed exactly as the policy says, with the same refusal for a missing record; another organisation, and a member of both acting in the other, refused; a reading token refused writes, over the socket too; a revoked grant, a signed-out session and a member who left closing open connections (an idle one too) before the next edit reaches them, their later updates refused; updates stored and refused any change or deletion even by the database superuser, and unreachable by module roles; an update committed between compaction's read and write kept, and every word of three writers kept under repeated compaction, a returning client converging; every reader (open, pull and the text projection of a second kernel process with nothing cached, and a data-subject export) seeing every word when a compaction commits between its read of the document's row and its read of the updates (forced: the compaction held uncommitted with the updates' table locked until the readers wait on it); a first update and a record deletion, interleaved either way, never leaving a document behind; the update, document and rate limits and malformed bytes refused with nothing stored; offline edits converging; presence relayed with the person, held in one place no module role can read while live and gone once withdrawn, refused to another person and to non-readers, never named in any notification; a withdrawal winning over a captured announcement replayed after it; a closing connection leaving a newer connection's announcement for the same client in place; a flood of frames while calls wait closing the connection (1008) with almost nothing applied; presence for more than a few clients refused; an agent's text read, its edit held for consent (and the same change as a raw update over HTTP held too) and then seen live, merged, attributed and tied to the audit record; checkpoints readable through the policy and restored live; an edit and a restore made against a sequence number the document moved past refused with nothing written; labelled snapshots kept only for those who may change the document, kept apart from compaction's checkpoints; a deleted record taking its document and closing its connections; malformed and cross-site-cookie sockets refused; export holding the person's documents and their contributions to others' documents after compaction, erasure deleting their documents and pseudonymising their contributions to shared ones, the document's text gone from every table. The Eloxiv kernel runs it in [`packages/testing/test/collab-document.test.ts`](../../packages/testing/test/collab-document.test.ts); [`packages/kernel/test/collab-declaration.test.ts`](../../packages/kernel/test/collab-declaration.test.ts) checks the declarations and the Yjs handling.
140
+
141
+ ## Not yet guaranteed
142
+
143
+ - **A copy's columns are protected by the module, not the kernel**: nothing refuses a module's own action that writes them; the kernel provides the event, the read and the version.
144
+ - **Large documents**: a live copy's derive task takes the document's updates as its arguments, so a document past about 3 MiB of updates cannot be copied (its delivery fails and is dead-lettered).
145
+ - **Restore** brings back text roots only; maps, arrays and XML roots (rich-text editors) keep their current content.
146
+ - **Agent edits** apply to text roots; an XML root (a ProseMirror fragment) is read as text but not edited.
147
+ - **Attribution inside a document**: each stored update is attributed by the kernel and the client's `recentEdits` uses that attribution, for updates delivered one by one. Yjs client ids inside updates are chosen by clients, so authorship of text that arrived inside a whole state (a first sync, a reset after compaction) is not established; it is shown as nobody's.
148
+ - **Reverting an agent run**: only the latest 20 autosaves of a document are kept, so a run older than twenty later runs on the same document can no longer be reverted there (`runs` counts what was found). Text a person wrote during the run that the run then deleted comes back only while that person's update is not yet compacted. A person's insertion exactly at the boundary of text the run replaced may land on either side of the restored text (Yjs orders concurrent insertions at one position by client).
149
+ - **Snapshots** are limited by the 20 kept per document, not by a rate of their own: someone who may change a document can replace its older snapshots by keeping new ones.
150
+ - **Wake-ups across processes**: a process whose listener connection dropped reads every change row committed meanwhile when it reconnects; one that falls more than two minutes behind (the change rows' retention) relies on its connections' periodic re-check (`reauthMs`).
151
+ - **Connection counts** are not limited per person or per document beyond the HTTP server's own limits.
@@ -0,0 +1,44 @@
1
+ # Command
2
+
3
+ Command-palette entries modules declare, each running one action or opening one view, registered across every installed module and searched by words. The command menu itself is registry UI; this contract is its data.
4
+
5
+ - Kind: shell contract. Version 1.0.0.
6
+ - Schema: [`packages/contracts/schema/contracts/Command.json`](../../packages/contracts/schema/contracts/Command.json) (source [`Command.ts`](../../packages/contracts/src/contracts/Command.ts)). Declared with the manifest's `commands` ([ModuleManifest](module-manifest.md)).
7
+ - Implementation: `shellRegistry(...).commands()`, `.command(id)` and `.search(query, limit)` in `@eloxiv/shell-core` ([`Navigation.ts`](../../packages/shell-core/src/Navigation.ts)).
8
+ - Kit: `@eloxiv/testing/conformance/Command` ([source](../../packages/testing/src/conformance/Command.ts)).
9
+
10
+ ```ts
11
+ for (const { entry } of shell.search("new card")) {
12
+ if (entry.run.kind === "view") navigate(entry.run.route)
13
+ else await client.call(entry.run.action, inputFromAForm) // the one invocation path: policy, consent, approval
14
+ }
15
+ ```
16
+
17
+ ## Operations
18
+
19
+ | Operation | Input | Output | What it does |
20
+ | --- | --- | --- | --- |
21
+ | `list` | `{}` | `PaletteEntry[]` | Every entry, in module installation order, then by id |
22
+ | `get` | `{ command }` | `PaletteEntry` | One entry; `UnknownCommand` if no module declares it |
23
+ | `search` | `{ query, limit? }` | `PaletteMatch[]` | The entries matching every word of the query, best first, at most `limit` (default 20). An empty query lists every entry in list order |
24
+
25
+ ## Records
26
+
27
+ - **`PaletteEntry`**: `id`, `module`, `title`, `description?`, `keywords`, `run`: `{ kind: "action", action }` or `{ kind: "view", view, route }` (the route resolved from the [View](view.md) registry).
28
+ - **`PaletteMatch`**: `entry`, `score` (higher is better).
29
+ - **Error**: `UnknownCommand { command }`.
30
+
31
+ ## Guarantees
32
+
33
+ 1. **Every word must match** the title, a keyword or the description, case- and accent-insensitively (`CAFE` finds "café").
34
+ 2. **Ranking**: per word, a title prefix ranks above a title word's prefix, above a title substring, above a keyword prefix, above a keyword substring, above a description substring; an entry's score is the sum over the words; ties by title, then id.
35
+ 3. **Running is an ordinary call.** An action-command is run through the typed client like any call, so identity, policy, consent and business approval apply ([Invocation](invocation.md)); the palette grants nothing.
36
+
37
+ ## How an implementation is checked
38
+
39
+ `commandConformance(make)` builds the implementation over the shell fixture ([`atlas/contract.ts`](../../packages/testing/src/conformance/atlas/contract.ts)) and checks the entries and their resolved runs, `UnknownCommand`, the ranking (title over keyword over description, prefix over substring), multi-word matching, case and accents, the limit and the empty query. The Eloxiv implementation runs it in [`shell-navigation.test.ts`](../../packages/testing/test/shell-navigation.test.ts).
40
+
41
+ ## Not yet guaranteed
42
+
43
+ - **No filtering by policy**: the palette lists commands whose action the person may not be allowed to call; the call is refused when run. Hiding them needs a per-person view of the policy on the client.
44
+ - **No fuzzy matching** (typos, subsequences).
@@ -0,0 +1,235 @@
1
+ # Connections
2
+
3
+ The kernel's integration layer: one OAuth grant per (organisation, owner, provider account), with merged scopes, token custody in Secrets, refresh, the 401-versus-403 rule, the owner's membership re-checked on every use, and the OAuth client flow through kernel routes. Connectors (registry items of kind `connector`) implement capability contracts over it without ever handling a token. It does not depend on Nango or any other custody service; `TokenCustody` is the seam for one.
4
+
5
+ - Kind: kernel service. Version 1.4.0 (1.1.0: handlers' declared operations and scheduled external effects; enrolment by granted scopes. 1.2.0: endpoint Connections (`add`, discovered OAuth, secrets by reference, the destination policy), shared Connections and their grants, and the ToolSource and HttpApi actions. 1.3.0: MCP App sessions, `openApp`, `appCall`, `closeApp`. 1.4.0: raw provider requests (`providerApiRequest`, a request's `bounded`), scopes a capability leaves to incremental consent (`incremental`), and requested scopes confined to those the connector declares).
6
+ - Schema: [`packages/contracts/schema/contracts/Connections.json`](../../packages/contracts/schema/contracts/Connections.json) (source [`Connections.ts`](../../packages/contracts/src/contracts/Connections.ts)).
7
+ - Implementation: [`packages/kernel/src/connections/`](../../packages/kernel/src/connections): `Connections.ts` (the service, the consent routes, `TokenCustody`), `Connector.ts` (`defineConnector`, `defineEndpointConnector`), `Destinations.ts` (the outbound destination policy), `ProviderApi.ts` (raw provider requests), `Discovery.ts` (OAuth discovered from an endpoint), `module.ts` (the `connections` kernel module), `Sync.ts` (the sync engine), `Metering.ts` (backpressure, [Metering](metering.md)). Tables `eloxiv.connection`, `eloxiv.connection_flow`, `eloxiv.connection_sync` (kernel migration `0022_connections`), `eloxiv.connection_grant` and the endpoint and shared columns (`0060_endpoint_connections`); tokens in `eloxiv.secret` ([Secrets](secrets.md)).
8
+ - Kit: `@eloxiv/testing/conformance/Connections` ([source](../../packages/testing/src/conformance/Connections.ts)), run by [`packages/testing/test/connections.test.ts`](../../packages/testing/test/connections.test.ts) against the reference `acme` connector over the acme protocol fake. The capability kits re-check the rules through real connectors.
9
+
10
+ ## Installing
11
+
12
+ ```ts
13
+ import { connectionsModule, inboxModules, type KernelApp } from "@eloxiv/kernel"
14
+ import { microsoftGraph } from "./connectors/microsoft-graph/connector.ts"
15
+
16
+ export const app: KernelApp = {
17
+ name: "my-app",
18
+ modules: [...modules, ...inboxModules, connectionsModule],
19
+ connectors: [microsoftGraph],
20
+ }
21
+ ```
22
+
23
+ The kernel refuses to start with connectors but no `connectionsModule`. `inboxModules` is optional; without the notifications module the owner of a Connection that needs reauthorisation is not notified (a warning is logged). A connector's settings come from `ELOXIV_CONNECTOR_<NAME>__<KEY>` (two underscores; `ELOXIV_CONNECTOR_MICROSOFT_GRAPH__CLIENT_ID` is `clientId` of `microsoft-graph`) or `KernelConfig.connectors`. Every provider must have `<ELOXIV_BASE_URL>/connections/callback` registered as its redirect URI.
24
+
25
+ ## The Connection
26
+
27
+ | Field | Meaning |
28
+ | --- | --- |
29
+ | `id` | `conn_<hex>` |
30
+ | `orgId`, `ownerId` | The organisation and the person (or service principal) it belongs to |
31
+ | `provider` | The connector's name |
32
+ | `accountId`, `accountLabel` | The provider's stable id for the account (Entra object id, Google `sub`) and its email |
33
+ | `scopes` | The provider scopes granted, normalised by the connector and merged across every consent |
34
+ | `status` | `active`, `needs-reauth` (with `statusReason`), `disconnected` |
35
+ | `shared` | Owned by the organisation, used through grants (see "Shared Connections"); `ownerId` is who connected it |
36
+ | `endpoint` | An endpoint Connection's endpoint (an MCP server, an API's base URL), or null |
37
+ | `auth` | `oauth` (the connector's OAuth grant, or one discovered for the endpoint), `secret`, `none` |
38
+ | `tools` | For a ToolSource Connection, the only tools it exposes (null: all) |
39
+
40
+ (org, owner, provider, account) is unique: connecting the same account again, with more capabilities or scopes, **upgrades the same Connection** (incremental consent) and merges its scopes. Connecting a different account of the same provider makes a second Connection.
41
+
42
+ ## Operations
43
+
44
+ ### Lifecycle actions (every surface)
45
+
46
+ The kernel's `connections` module projects four actions onto the typed client, HTTP (`POST /api/actions/connections.<name>`), MCP (`connections_connect`, ...), agent tools and the CLI. They go through the one invocation path (identity, policy, consent, approval, idempotency, audit, outbox) and are audited like any action. Their handlers are kernel code (`defineKernelModule`: they run as the kernel's role with the kernel's services, and authorise each Connection themselves); the module owns no tables (its MCP App sessions are a kernel table, `eloxiv.mcp_app_session`). The privilege belongs to the functions the kernel defined, not to the module object: the registry binds each action's handler when it is built (the kernel module's recorded originals), the kernel-provided modules are deep-frozen, an app whose module takes a kernel-provided name without being the kernel's own object is refused at startup, and none of the privileged constructors is exported. A kernel handler's unexpected failure answers `ActionFailed` with a reference to the invocation, never the failure's message. Connector code (`identify`, capability operations) runs without the kernel's services, like every module handler, subscriber and module workflow ([DbTx](db-tx.md)). Registry and app modules, and connectors, are the app's own code: trusted. Running them without the kernel's services protects against mistakes (a handler reaching for `Secrets` because it is there), not against code written to get round it: in-process JavaScript can import what it likes, read the environment and open its own database connection, and a handler can `RESET ROLE` on the kernel's. Untrusted, agent-made (MAKE) modules run in the sandbox (backlog 3); the sandbox is the boundary for untrusted code.
47
+
48
+ | Operation | Action | What |
49
+ | --- | --- | --- |
50
+ | `connect` | `connections.connect` | `{ provider, capabilities?, scopes?, returnTo? }`: records a consent flow for the caller (10 minutes) and returns `{ flowId, authorizeUrl, scopes, expiresAt }`. The scopes are the connector's base scopes, those of each named capability's operations (but those the capability leaves to incremental consent, `incremental`: Gmail's settings scope, for filters), and any given |
51
+ | `reconnect` | `connections.reconnect` | `{ connectionId, capabilities?, scopes?, returnTo? }`: the same for one of the caller's Connections, asking for its current scopes plus the new ones (incremental consent), or recovering one that needs reauthorisation. The callback must sign in the same account. Scopes named in `connect` or `reconnect` must be ones the connector declares (its base scopes and its capabilities', those left to incremental consent included), else `InvalidInput`; an endpoint connector's are its authorization server's |
52
+ | `disconnect` | `connections.disconnect` | `{ connectionId }`: the owner's own, or any in the organisation with `eloxiv.connections.manage`. The status becomes `disconnected`, its tokens are deleted from custody at once, and it is never used again |
53
+ | `list` | `connections.list` | The caller's Connections in the organisation and the shared ones granted to them (all of them with `eloxiv.connections.manage`), never tokens |
54
+ | `add` | `connections.add` | Add or update an endpoint Connection (see "Endpoint Connections"): `{ provider, endpoint, label?, auth, options?, tools?, shared?, returnTo? }`, answering `{ connection, consent }` (`consent` is the ConsentStart to open for `auth.kind: oauth`, else null). Marked `consent: "each-call"`: an agent's every call waits for the person's approval of that exact input, so an agent cannot point the person's secret at an endpoint it picks |
55
+ | `grant`, `revoke`, `grants` | `connections.grant`, `connections.revoke`, `connections.grants` | A shared Connection's grants, with `eloxiv.connections.manage` (see "Shared Connections"); an agent's `grant` and `revoke` wait for the person's consent |
56
+ | `tools`, `callTool` | `connections.tools`, `connections.callTool` | A [ToolSource](tool-source.md) Connection's tools, and a call to one (`consent`: an agent's call waits for the person) |
57
+ | `openApp`, `appCall`, `closeApp` | `connections.openApp`, `connections.appCall`, `connections.closeApp` | MCP App sessions over a ToolSource Connection: a tool's `ui://` view opened for the caller, tool calls from it (the same grant, exposure and consent as `callTool`) and its close (see [ToolSource, "MCP App sessions"](tool-source.md#mcp-app-sessions)) |
58
+ | `apiCatalog`, `apiDescribe`, `apiRead`, `apiWrite` | `connections.apiCatalog`, ... | An [HttpApi](http-api.md) Connection's operations, reads and writes (`apiWrite` needs consent for each agent call) |
59
+ | — | `connections.effects` | `{ ids? }`: the caller's own external effects as the kernel records them, newest first (at most 100): `state`, `attempts`, `waiting` (`reason`, `retryAt`: a rate limit, or a time it was scheduled for), `error`, `reported` (whether the scheduling module was told the outcome: `told`, `refused` when the authority the call was bound to was gone, null not yet), `createdAt`, `finishedAt`. The kernel-owned status a person, an agent or a screen reads for a send a module still shows as in progress; it reads only the caller's own and widens no authority. Also `ctx.connections.effects` in a handler |
60
+
61
+ `connect` and `reconnect` also take `shared: true` (with `eloxiv.connections.manage`): the Connection is the organisation's. The tool and API actions run as the kernel over a Connection the caller may use; a capability error is answered as the action's own (a refusal, or a Connection that needs reauthorisation, is `Forbidden` with the reason in its message; a missing thing `InvalidInput`; the rest `ActionFailed`).
62
+
63
+ `returnTo` must be a path or a URL on the kernel's or a trusted origin (`ELOXIV_TRUSTED_ORIGINS`), otherwise `InvalidInput`. It is resolved against the kernel's base URL with the URL API, as a browser resolves a `Location` (tabs and newlines dropped, backslashes read as slashes, `//host` taken as a host), and its resolved origin is what must be trusted: `/\evil.example`, `//evil.example`, `/<tab>/evil.example`, credentials and non-http schemes are refused. The callback checks it again before redirecting.
64
+
65
+ ### The OAuth client flow (kernel routes)
66
+
67
+ | Operation | Route | What |
68
+ | --- | --- | --- |
69
+ | `authorize` | `GET /connections/authorize?flow=<id>` | Opened in the person's signed-in browser (their Better Auth session; agent sessions and machine credentials are refused). The flow must be theirs, unexpired and unused, and they must still be a member. A fresh `state` (256 bits) is bound to the session (its hash stored with the session's hash) and the browser is redirected to the provider with `response_type=code`, the scopes, `redirect_uri=<base>/connections/callback`, `code_challenge` (S256) and the connector's parameters. The PKCE verifier is an HMAC of the flow and state under the kernel's secret: nothing secret is stored. A connector whose provider refuses PKCE from a confidential client says so (`pkce: false`; only Slack, see "Provider quirks") and the flow then rests on the client secret and the session-bound state |
70
+ | `callback` | `GET /connections/callback?code=&state=` | The state is consumed (single use) only from the session it is bound to; any other session, a replay or an expired flow gets `403` and creates nothing. The code is exchanged with the verifier and the client secret; the connector identifies the account; in one transaction that first holds the person's session again (locked `FOR SHARE`, its expiry read under the lock: after those network calls a sign-out may have committed, and then nothing is saved, `403`; the tokens the provider issued are revoked there, RFC 7009, only when the connector declares that its revocation ends only that token (`OAuthClient.revocation.revokes: "that token"`) and no active Connection holds the same provider account, since revoking at a provider whose revocation ends the whole grant, or whose account another consent already holds, would end a consent the person completed; otherwise they are discarded, and the callback's record says which (`detail.tokens`); one that comes later waits for the save) the Connection is created or upgraded (scopes merged from the token response's `scope`, or the requested ones), its tokens saved, and the callback audited (`connections.callback`). The browser goes to `returnTo` with `connection=<id>`, or sees a minimal page |
71
+
72
+ ### In process (for connectors and the kernel)
73
+
74
+ | Operation | What |
75
+ | --- | --- |
76
+ | `request` | `Connections.http(connectionId, { userId, orgId }, scopes).request(...)`: one HTTP request over the Connection, by its owner. See "Using a Connection" |
77
+ | `refresh` | `Connections.refresh(connectionId)`: refresh now, single-flight. `refreshed: false` when another caller had already refreshed the token observed |
78
+
79
+ `Connections.capability(connectionId, name, owner)` binds a connector's implementation of a capability contract to the Connection: each operation gets a `ProviderHttp` that knows the provider scopes its contract operation needs.
80
+
81
+ ### From a module's handler
82
+
83
+ A handler reaches the caller's own Connections through `ctx.connections` (`HandlerContext`), never the `Connections` service:
84
+
85
+ ```ts
86
+ send: (input, ctx) =>
87
+ Effect.gen(function* () {
88
+ const mail = yield* ctx.connections.capability(input.mailboxId, "mail") // typed: MailProvider's operations
89
+ const sent = yield* mail.sendMessage({ to: input.to, subject: input.subject, body: { contentType: "text", content: input.body } })
90
+ return { providerId: sent.id }
91
+ }),
92
+ ```
93
+
94
+ - `list()`: the Connections the caller may use from this module, in the organisation they act in (never tokens): their own personal ones, and shared ones granted to them and to this module. Never every Connection, even for someone with `eloxiv.connections.manage`.
95
+ - `capability(connectionId, name)`: the capability's operations over one Connection, as the caller, **only those the action declares** (`defineAction({ connections })`); every other answers `Forbidden`. Every rule of "Using a Connection" applies: a Connection that is not the caller's, in the organisation they act in, is refused (`Forbidden`) before anything reaches the provider.
96
+ - An operation others see (`effect: "external"`: `sendMessage`, `createEvent`, `updateEvent`, `deleteEvent`, `respondToEvent`, Messaging's `sendMessage`) is never called directly: `schedule({ connectionId, capability, operation, input, onDone })` records it in the call's transaction and the kernel runs it after commit, at most once; `effect(id)` reads its outcome. The provider's answer (`result`) is kept only while the module may need it: until its `onDone` ran, not at all once the outcome is recorded when it names none, and at most `ELOXIV_EFFECT_ANSWER_RETENTION_DAYS` (default 7) when its callback was refused; an erasure of a person it mentions clears it sooner, and `cleared` says why it is gone (`told`, `no-callback`, `expired`, `erased`). See [Invocation, "External effects"](invocation.md#external-effects).
97
+ - The kernel's code behind direct calls runs with the kernel's context, not the handler's: its statements use a connection of their own, never the call's transaction (where the module's role could not read a Connection anyway), and a provider request holds no transaction open. So what a direct call changes (the account's own data: read state, folders) is not undone when the call then rolls back; a module reconciles through its next sync. Connector code still runs as module code.
98
+
99
+ ## Using a Connection
100
+
101
+ Every request, in order:
102
+
103
+ 1. **Usable now.** The Connection exists and is not disconnected (`NotFound`); it is in the caller's organisation; a personal one only by its owner, while the owner is **still a member** of the organisation, read from the directory on every use, as for any credential (`Forbidden`, "no longer a member", and nothing reaches the provider); a shared one only by a member it is granted to and, from a module's handler, only if it is granted to that module too (see "Shared Connections"); it does not need reauthorisation (`Unauthorized` at once, nothing reaches the provider).
104
+ 2. **Backpressure.** [Metering](metering.md) admits it: a slot of the Connection's concurrency limit, its shared cooldown, its quota. Once admitted, step 1 is checked again and the credential loaded just before the request is sent, so a grant revoked, a member gone or a secret replaced while it waited is honoured.
105
+ 3. **A valid access token.** If it expires within `ELOXIV_CONNECTIONS_REFRESH_SKEW_S` (default 300 s), it is refreshed first. Decrypted tokens are cached per token version (one audited read per version); the version is checked against the row on every use.
106
+ 4. **The answer.**
107
+ - **401** (or what the connector classifies as one): the token is invalid. Refresh **once** and retry. If the refresh fails (`invalid_grant`, a refused client, no refresh token) or the retry is refused again, the Connection is marked `needs-reauth`, audited (`eloxiv.connections.needs-reauth`), its owner notified (category `connections`, "Reconnect ..."), and the call fails with `Unauthorized` (`reauthorize: true`).
108
+ - **403**: never refreshed. The error is `Forbidden` with `missingScopes`: the provider scopes the operation needs that the grant lacks; when the grant appears to hold them but the provider says the scope is insufficient (RFC 6750 `insufficient_scope`, Google's `ACCESS_TOKEN_SCOPE_INSUFFICIENT`, Graph's access-denied codes), all the operation's scopes. With missing scopes, `consent` offers `connections.reconnect` with them. A 403 that is about something else (a Workspace non-administrator) has no missing scopes and no offer.
109
+ - **429, 503** (or a connector's rate-limit classification, such as Google's 403 `userRateLimitExceeded`): Metering's backoff (Retry-After), then retry within the attempt and wait budgets, else `RateLimited` (or `Unavailable` for a 503).
110
+ - 404 `NotFound`, 409/412 `Conflict`, 410 `InvalidCursor` (a connector may say otherwise), 400 `InvalidInput`, other 5xx and network failures `Unavailable`.
111
+
112
+ The token goes only to the origins the connector declares (`apiOrigins`, from the deployment's settings; for an endpoint Connection, its endpoint's origin alone): a request to any other origin is refused (`InvalidInput`) before anything is sent. A connector's request never sets `authorization`, `cookie`, `host`, `proxy-authorization` or the credential's own header: the kernel drops them. Provider requests run in the context the capability was bound in, outside any transaction of the caller's. Redirects are followed by the kernel, at most five, with the token only while they stay on a declared origin (a pre-authenticated download URL elsewhere is fetched without it). What a capability operation answers is checked against the contract's output schema: a malformed answer is refused as `Unavailable`.
113
+
114
+ ### Raw provider requests
115
+
116
+ A capability may offer an escape hatch to its provider's own API for what its operations do not model (CalendarProvider's `apiRead` and `apiWrite`), over the Connection the person already granted: not an endpoint Connection, which is another grant to another destination. The connector names what it opens (`ProviderApiScope`: a base URL on one of its declared origins, the whole-segment path prefixes under it, the methods) and calls `providerApiRequest(http, scope, { method, path, query?, body? })`, kernel code ([`ProviderApi.ts`](../../packages/kernel/src/connections/ProviderApi.ts)) that holds the bounds whatever the caller asks:
117
+
118
+ - **Destination.** The path stays under the base and one of its prefixes: `..` and `.` segments, empty segments (`//`), backslashes, encoded separators, dots and NUL (`%2f`, `%5c`, `%2e`, `%00`), a query or fragment written into the path, spaces and control characters are refused (`InvalidInput`) before anything is sent, and the URL the parser makes is checked again against the base's origin, path and prefixes. Query parameters are given apart and encoded by the kernel. No header of the caller's is sent.
119
+ - **Method.** One the scope allows: reads `GET`; writes `POST`, `PUT`, `PATCH`, `DELETE` (`HEAD`, `OPTIONS`, `TRACE`, `CONNECT` and the rest refused).
120
+ - **Body and answer.** JSON only, at most 64 KiB encoded, none on a `GET`; the answer read as it streams and given up at 1 MiB: a read's as `InvalidInput` ("ask for less"); a write's as `Unavailable` without `dispatched: false`, since the provider answered and so acted (the effect is `unknown`, never repeated). It answers `{ status, body }` for a 2xx or 3xx; failures are the standard capability errors by the rules of "Using a Connection" (404 `NotFound`, 403 `Forbidden` with the missing scopes and the reconnect offer, 429 and 503 backoff, the 401 refresh), redacted of the credential.
121
+ - **No redirect.** Only the URL the scope checked is reached: a 3xx answer is never followed (a redirect could take the request, with the credential still on a declared origin, or a 307's body, to a path the scope does not open). It fails the request with nothing of the target read: a read `InvalidInput`, a write `Unavailable` (it may have acted; never run again).
122
+ - **Transport.** The Connection's ordinary request (step 1 to 4 above: owner and membership, grants, Metering, refresh, the credential only to declared origins and never to the caller), marked `bounded`, so every hop also passes the outbound destination policy (below) and is sent pinned to the addresses its check resolved (`pinnedFetch`), like an endpoint Connection's. A provider's public API passes; an operator's override to a host that is not public (a test's fake, a proxy) must be allowed with `ELOXIV_OUTBOUND_ALLOW`.
123
+ - **Scopes and consent.** The operation's scopes are the capability's read or write scope, which the token carries only if granted: a path that needs more is the provider's 403, reported with the missing scopes. A write is an external effect (scheduled by the module, made at most once, never reconciled), and the module's action asks an agent for the person's consent on every call (`consent: "each-call"`).
124
+
125
+ Proven by [`registry/test/calendar-api.test.ts`](../../registry/test/calendar-api.test.ts) over the Google and Graph protocol fakes (and a redirecting proxy in front of the Google fake): reads on both and a write made after commit with its answer kept; paths outside the API refused with nothing sent (a write's at the kernel, when it would be made); methods outside the list refused; a body past 64 KiB and an answer past 1 MiB refused; another person's Connection refused; 404, a missing scope and an outage mapped; the provider's address refused by the destination policy when the deployment does not allow it; a redirected read refused (into Gmail or another calendar path) and a redirected write's body sent nowhere else; and a made write whose answer is past its bound recorded `unknown`, never `failed`.
126
+
127
+ ## Refresh
128
+
129
+ - **Proactive** before expiry (see above).
130
+ - **Single-flight in the process**: concurrent callers share one refresh per Connection. The refresh runs in its own fiber in the service's scope; every caller, the one that started it too, only awaits its outcome. Interrupting a caller at any point (before the refresh starts, waiting for the lock, during the token request, waiting on another caller's refresh) neither cuts the refresh short (a rotated refresh token is stored or the transaction rolls back) nor leaves the entry behind; a refresh that hangs ends as `Unavailable` after `ELOXIV_CONNECTIONS_REFRESH_TIMEOUT_MS` (default 60 s). The refresh runs in the service's own context, never a caller's: a caller inside a transaction that then rolls back does not take the refresh (and the rotated refresh token the provider issued) with it.
131
+ - **Single-flight across processes**: a refresh runs in a transaction holding `pg_advisory_xact_lock` on the Connection and `FOR UPDATE` on its row. A caller that gets the lock and finds the token version moved past the one it saw uses the new token instead of refreshing again.
132
+ - **Rotation-safe**: a refresh token returned by the provider (Microsoft rotates them) is stored in the same transaction, under the lock, before anyone else can refresh; a provider that returns none (Google) keeps the stored one.
133
+
134
+ ## Custody
135
+
136
+ `TokenCustody` (`load`, `save`, `remove`) is where tokens live. The default keeps them in Secrets as `access_token` and `refresh_token` of scope `connection`. An external custody service (Nango self-hosted, a vault) is another layer passed as `KernelOptions.custody`; nothing else in the contract changes. The kernel never stores a token anywhere else, and never logs one.
137
+
138
+ ## Sync
139
+
140
+ The Connection sync engine runs a capability's delta sync for a Connection as a durable workflow and applies it through the owning module's action:
141
+
142
+ ```ts
143
+ connectionSyncs: [{ name: "mail.inbox", capability: "mail", action: "mail.applyDelta", intervalS: 300, pageSize: 50 }]
144
+ ```
145
+
146
+ - **Enrolment and scheduling.** A runner's sweep (`ELOXIV_CONNECTIONS_SYNC_SWEEP_MS`, default 5 s) records every active Connection whose connector provides the capability in `eloxiv.connection_sync`, and starts each due one as the kernel workflow `eloxiv.connection-sync`, keyed `<connection>:<sync>:<run>`, acting as the Connection's owner. It starts the execution first and advances the run second, so a crash in between joins the same execution. `ConnectionSync.syncNow` starts one at once.
147
+ - **One page per step.** Each step fetches a page from the stored cursor, then in **one transaction** locks the cursor row, checks it has not moved, invokes the module's action (through the invocation path, as the owner, surface `workflow`) with `{ connectionId, reset, changes }` (`ConnectionSyncInput`), and stores the page's cursor. The data and the cursor commit together or not at all: a crash before the commit re-fetches the same page; after it, the next. Two runs for one Connection at once (two processes, or a sweep and `syncNow`) both fetch, but only one commits a page: the other finds the cursor moved under the lock and fetches again.
148
+ - **Full resync.** `InvalidCursor` clears the cursor; the next page is a full sync with `reset: true`, and the module replaces what it holds for the Connection.
149
+ - **Empty pages.** The action is invoked for pages with changes and for a full sync's first page; a sync declared with `everyPage: true` reaches it for every page, empty ones too, for a module with work of its own to retry on every sync (mail checks again the messages whose deletion or fetch was inconclusive, until each is resolved).
150
+ - **Errors** other than InvalidCursor are recorded (`last_error`) and the sync waits for its next interval. That includes the apply action's refusal: a Connection whose owner may not apply pages (a directory Connection of someone without `people.manage`) records `Forbidden` and applies nothing.
151
+ - **Declared by a module.** `defineModule(contract, { connectionSyncs: [...] })` declares a module's own syncs, named `<module>.<name>` in the app (`people.directory`, `mail.inbox`); each must apply pages with one of the module's own actions, or the kernel refuses to start. A module's sync is inert until the app installs a connector providing its capability (an app's own `KernelApp.connectionSyncs` entry without one is refused). An active Connection is enrolled only when it was granted the provider scopes the capability's `delta` needs: one connected for mail alone is never asked for its directory.
152
+
153
+ ## Channels
154
+
155
+ A channel connector's Connection (Slack's) has channels the app's agent answers in, through Ingress ([Ingress, "Replying"](ingress.md#replying-in-the-deliverys-conversation)). Each channel's settings belong to the receiving Connection (`eloxiv.channel_setting`, kernel migration `0166_channel_settings`): `enabled` (whether the agent answers there), `scope` (`act`, or `plan`: the run is in plan mode, it reads and plans but changes nothing), `dailyTokens` (a budget of tokens a day, UTC, for the runs it answers there; null for none) and `memory` (`thread`: a thread's messages from one person continue one agent conversation; `channel`: per channel and person; `none`). A channel with no settings takes the defaults: answered, `act`, no budget, `thread`. `connections.channels` lists them (with the tokens used today) and `connections.setChannel` changes one (only the fields given), for the Connection's owner or any with `eloxiv.connections.manage`; the client SDK's controller is `connectionsOf(...).channels`. They apply in the kernel, to every message a handler sends to the agent with `ctx.ingress.sendToAgent`: a disabled channel, or one past its budget, starts no run; the conversation a thread continues (`eloxiv.channel_conversation`) is the sender's own, and a gone or still-busy one is replaced by a new conversation; what a channel spent is read from the agent's own run records (`agent/Channels.ts`): each admitted message's run with every run it delegated to, settled whether or not anyone waits for the answer (a run that timed out and was cancelled still counts what it spent). Admission is one message at a time per channel (an advisory lock): it counts what the day's messages spent and reserved, and admits a message only below the budget, recording its reservation (`eloxiv.channel_run`) in the same transaction. A message reserves the whole budget until its run is known, then the run's token limit if it has one (`agent.loop`'s `maxTokens`), and an unfinished run counts its spend or its reservation, whichever is more. So concurrent messages cannot exceed the budget by more than one run's reservation; a channel with a budget and runs without a token limit answers one message at a time. A reservation whose send never started a run (its process died) holds nothing after fifteen minutes. Proven against the Slack protocol fake ([`registry/test/slack-agent.test.ts`](../../registry/test/slack-agent.test.ts)).
156
+
157
+ ## Endpoint Connections
158
+
159
+ An endpoint connector (`defineEndpointConnector`: the registry's [`mcp`](../connectors/mcp.md) and [`http-openapi`](../connectors/http-openapi.md)) has no provider of its own: each Connection names its endpoint, added with `connections.add`. (org, owner, connector, endpoint) is unique for a personal one, (org, connector, endpoint) for a shared one: adding the same endpoint again updates it, and changing how it authenticates drops what the old credential held (its tokens, a registered client's secret).
160
+
161
+ **The endpoint** must pass the destination policy (below) when added and on every request; it has no query or fragment. Its account is the endpoint itself, its label the one given (or its host).
162
+
163
+ **How it authenticates** (`auth`), as the connector allows (`endpoint.auth`):
164
+
165
+ | `auth.kind` | What is sent | |
166
+ | --- | --- | --- |
167
+ | `none` | nothing | Active at once. A 401 marks it for reauthorisation (add it again with a credential) |
168
+ | `secret` | `<prefix><value>` in `header` (default `authorization` with prefix `Bearer `) | The secret is **named, never given**: `{ scope, name }`, a secret the person put beforehand through [Secrets](secrets.md) (`POST /kernel/secrets/put`), so its value never passes through an action's input, its audit or idempotency record. A personal Connection sends one of its owner's (`user`), a shared one the organisation's (`org`, with `eloxiv.secrets.manage`). It must exist, and when the secret names its own `allowedOrigins`, the endpoint's origin must be one of them: checked when added and on every request. A header the transport or cookies own cannot carry it. The value is read (audited) once per version. A 401 marks the Connection for reauthorisation and notifies its owner (replace the secret and add it again); a secret that is gone does the same, before anything is sent |
169
+ | `oauth` | a discovered grant's access token | The MCP authorization specification's discovery: the endpoint's protected-resource metadata (RFC 9728, path-suffixed then at the origin; it must name the endpoint as its resource), else the endpoint's origin as its own authorization server; that server's metadata (RFC 8414, then OpenID Connect discovery; its `issuer` must be the one asked, it must offer PKCE S256 when it lists methods, and its authorization and token endpoints must pass the policy without a network check); a client registered dynamically (RFC 7591: a public client for the kernel's callback) unless the person gives `clientId` (and a `clientSecret` named like a secret, which goes to the token endpoint: when the secret names `allowedOrigins`, the token endpoint's origin must be one of them, checked when added and again before every code exchange and refresh). The Connection is recorded needing reauthorisation ("consent pending") and `consent` is a ConsentStart for the kernel's authorize route; the flow is the ordinary one (PKCE S256, session-bound state) and names the endpoint as the `resource` (RFC 8707) in the authorization and every token request. Refresh, the 401 rule and rotation are as for any Connection. A registered client's secret is a secret of the Connection; every discovery, registration and token request is bounded, follows no redirect and passes the policy |
170
+
171
+ **Options** (`options`) are the connector's, checked against its `endpoint.options` schema when added and handed to its implementation with the endpoint (`make(http, settings, { endpoint, options })`); the connector never sees the credential. **`tools`** limits a ToolSource Connection's tools (see [ToolSource](tool-source.md#exposure)).
172
+
173
+ ### Destinations
174
+
175
+ Where the kernel sends a request whose URL someone chose (an endpoint Connection's requests and each redirect they follow, and an authorization server's metadata, registration and token endpoints): **https to a public address only**. Loopback, private (10/8, 172.16/12, 192.168/16), link-local (169.254/16, the cloud metadata service), carrier-grade NAT, documentation, benchmarking, multicast, reserved and unspecified IPv4 ranges, and their IPv6 counterparts (`::1`, `::`, fc00::/7, fe80::/10, ff00::/8, IPv4-mapped, NAT64 and 6to4 forms of a private IPv4 address) are refused, as literals and as any address a name resolves to (one private answer refuses the name), as is `localhost`. Each request is sent **pinned**: the connection's own resolver resolves the name, checks every address and connects to exactly those (the name kept as the `Host` and the TLS server name, so the certificate is verified for it), so a name server cannot answer the check with a public address and the connection with a private one (DNS rebinding); each redirect is checked and pinned the same way (`pinnedFetch`, `guardedFetch` in `Destinations.ts`, over `node:http` and `node:https`, whose resolver hook Bun and Node both honour). Every answer is read while it streams and given up at its bound (an authorization server's metadata at 64 KiB); a redirect's body is never read. A deployment allows hosts that are not public with `ELOXIV_OUTBOUND_ALLOW` (`KernelConfig.connections.outboundAllow`): comma-separated `host` (any port) or `host:port` (IPv6 in brackets), which may then be reached over plain http too. An endpoint Connection's answer is bounded (8 MiB). A provider connector's own origins (`apiOrigins`) are the operator's settings and are not checked.
176
+
177
+ ## Shared Connections
178
+
179
+ A Connection is the organisation's (`shared: true`) when someone with `eloxiv.connections.manage` connects (`connections.connect` or `reconnect` with `shared`) or adds it. It does not depend on who connected it staying: their leaving the organisation does not stop it, and only an administrator reconnects or disconnects it. It is used only through grants (`connections.grant`, `revoke`, `grants`, with the permission):
180
+
181
+ | Grantee | Lets |
182
+ | --- | --- |
183
+ | `{ kind: "org" }` | every member |
184
+ | `{ kind: "user", id }` | one member |
185
+ | `{ kind: "group", id }` | the group's members (as they are on each use) |
186
+ | `{ kind: "module", id }` | that module's handlers (`ctx.connections`), for the members granted |
187
+
188
+ On every use the user must be a member, hold a member grant (themselves, a group of theirs, or everyone), and, from a module's handler, the module must hold a grant too; an administrator is not exempt. A revoked grant stops the next use. The kernel's tool and API actions are the kernel's, not a module's: they need the member grant only. A shared Connection is a link of the user's authority chain like a personal one ([Invocation](invocation.md#authority)): an effect scheduled over it is delivered only while the grant stands. Disconnecting removes its grants.
189
+
190
+ ## Provider quirks
191
+
192
+ A connector's `OAuthClient` and definition adapt the flow and the request loop to a provider that departs from RFC 6749 and RFC 6750, without loosening anything else:
193
+
194
+ | Field | Default | For |
195
+ | --- | --- | --- |
196
+ | `OAuthClient.scopeSeparator` | `" "` | The separator in the authorization request's `scope` and in the token response's `scope` (Slack: `,`) |
197
+ | `OAuthClient.pkce` | `true` | `false` only for a provider that refuses PKCE from a confidential client. Slack accepts PKCE only from apps marked as public clients (a one-way setting, and their refresh tokens then expire after 30 days) and answers `pkce_not_allowed` otherwise |
198
+ | `OAuthClient.tokenError` | none | Reading a token endpoint answer whose status does not say what it means (Slack answers errors `200 { ok: false, error }`): `reauth` (a refresh fails for good: the Connection needs reauthorisation) or `unavailable` (try later) |
199
+ | `classifySuccess` | none | Reading a failure in a 2xx answer's body (Slack's Web API answers every error but a rate limit `200 { ok: false, error }`): the failure is handled exactly as a non-2xx one (`unauthorized` refreshes once, then needs reauthorisation; `insufficient-scope` reports the missing scopes) |
200
+
201
+ **What a provider says is not repeated.** A refused refresh or code exchange is recorded (the Connection's `statusReason`, its audit record, its owner's notification, the caller's error) as a fixed phrase with the error code when the token endpoint named one (`invalid_grant`, a provider's own `invalid_refresh_token`: lower-case letters and underscores only), never the endpoint's own text, which can echo the refresh token or the client's secret. An API's failure answer reaches the caller (a shared Connection's grantees too) only redacted of the credential the request carried and of anything that looks like one. The guarded fetch an endpoint client uses (a model key's `base_url`) refuses a redirect to another origin: a request's credentials and body are its endpoint's alone.
202
+
203
+ ## Guarantees
204
+
205
+ 1. One Connection per (organisation, owner, provider account); more scopes upgrade it and merge its scopes.
206
+ 2. Consent uses authorization code with PKCE S256 (except for a connector that declares its provider refuses PKCE from a confidential client: Slack) and a state bound to the person's session, single use and expiring; nothing secret about the flow is stored.
207
+ 3. Tokens live only in custody (Secrets by default, as ciphertext).
208
+ 4. A 401 refreshes once and retries; a failed refresh or retry marks the Connection for reauthorisation and notifies its owner, and later calls fail fast without reaching the provider.
209
+ 5. A 403 never refreshes and reports the missing scopes with an offer of incremental consent.
210
+ 6. Refresh is proactive and single-flight in the process and across processes, and safe for rotating refresh tokens.
211
+ 7. A Connection is usable only by its owner, only while the owner is a member of its organisation, checked on every use.
212
+ 8. Lifecycle actions are on every surface, authorised and audited; disconnecting deletes the tokens at once.
213
+ 9. A sync page's data and cursor commit in one transaction; a crash resumes from the last committed cursor. The page is applied only while its Connection stands: the Connection is a link of the owner's authority chain ([Invocation](invocation.md#authority)), asserted in that transaction before the cursor it protects (the lock order), so a page fetched before a disconnect (or a reauthorisation) commits is discarded, and a disconnect made while a page applies waits for it ([`registry/test/connection-authority.test.ts`](../../registry/test/connection-authority.test.ts)).
214
+ 10. A Connection's token is sent only to the origins its connector declares, and a connector's answers are checked against the capability contract.
215
+ 11. An endpoint Connection's requests, the redirects they follow and the authorization servers they discover go only to public https addresses unless the deployment allows the host, checked before each is sent, against every address a name resolves to, and each is sent to the addresses that check resolved, never to what a later lookup answers ([`packages/kernel/test/destinations.test.ts`](../../packages/kernel/test/destinations.test.ts), "connects only to the addresses it checked, never to what the name answers on a later lookup", and the ToolSource and HttpApi kits).
216
+ 12. An endpoint Connection's secret is named, never given: it reaches neither connector nor module code, nor any action input, answer or audit record, and goes only to the endpoint's origin and only where the secret's own `allowedOrigins` allow.
217
+ 13. OAuth discovered from an endpoint uses a client registered for the kernel's callback, PKCE S256 and the endpoint as the resource, keeps its tokens only in custody, and follows every rule of guarantees 2 to 6.
218
+ 14. A shared Connection is used only by members it is granted to (and, from a module's handler, only with a grant to the module), re-checked on every use.
219
+ 15. A raw provider request reaches only the base URL and paths its connector opens, follows no redirect, with an allowed method and a bounded body and answer, through the Connection's own rules and the outbound destination policy, pinned; the caller never sees the credential.
220
+
221
+ ## How an implementation is checked
222
+
223
+ `connectionsConformance(subject)` registers: the PKCE S256 flow with the kernel's redirect URI and a state of at least 256 bits; another session's callback refused (and nothing created), the rightful one completing, a replay refused, a forged state and someone else's consent link refused; one Connection with merged scopes after a second consent and an incremental reconnect asking for the union; a reconnect signing in another account refused; no issued token in any kernel table (connection, flows, secrets in three encodings, audit); proactive refresh without a refused request first; single-flight refresh across two kernels on one database (four concurrent requests, one refresh); three rotations in a row with the fake refusing used refresh tokens; 401 refresh-once, then a revoked refresh token marking `needs-reauth`, notifying, auditing and failing fast, and a reconnect restoring the same Connection; 403 with the exact missing scope and offer and no refresh; a member who left refused without any request reaching the provider, and allowed again when re-added; another member refused; the four actions on HTTP, RPC, MCP and agent tools with one audit record per surface; disconnect by the owner or an administrator only, deleting the tokens; `returnTo` confined to trusted origins. `connections.test.ts` also proves the custody seam with an in-memory custody (no secret rows at all).
224
+
225
+ The capability kits (MailProvider, CalendarProvider, DirectoryProvider, DocumentSource) re-run the 401, refresh, 403, rate-limit and merged-scope rules through each connector. The sync engine is proven in [`registry/test/connection-sync.test.ts`](../../registry/test/connection-sync.test.ts): pages applied by the owner on the workflow surface, a fault after the module applied a page rolling back the page and its cursor (the next run applies it exactly once), a kernel disposed while a page's transaction is open and another kernel finishing the durable execution with every change applied once, and a full resync after an expired cursor.
226
+
227
+ ## Not yet guaranteed
228
+
229
+ - **Shared Connections are not synced**: the sync engine enrols personal Connections only (it acts as their owner); a shared mailbox or directory is read by a module's own actions through its grant.
230
+ - **Provider-side revocation on disconnect** is not attempted; the tokens are deleted locally.
231
+ - **Proven against protocol fakes only**: the Microsoft Graph and Google connectors pass the kits against protocol fakes, not the real services, until their live runs have test accounts (Slack's live run has passed against a real workspace) (see [docs/connectors](../connectors)).
232
+ - **Slack's rate limits are per workspace and method**, while Metering's cooldown is per Connection: two people's Connections to one workspace share Slack's limit but not the cooldown, so each learns of a 429 on its own.
233
+ - **The sync engine's schedule** is the kernel's own sweep loop, not the Scheduler contract's schedules; each run is a Workflow execution.
234
+ - **A handler's direct calls are outside its transaction** (see "From a module's handler"); only calls that change the account's own data are allowed directly.
235
+ - **Consent popups and resumable consent in chat** are the client SDK's ([ClientSDK](client-sdk.md#connections)).
@@ -0,0 +1,50 @@
1
+ # ContextAccounting
2
+
3
+ An inventory of everything a model call is sent (instructions, skills, memory, messages, tool results and tool definitions) with token counts per item, budgets per category, eviction and pinning. The inventory, the **context x-ray**, adds up to exactly what the model received.
4
+
5
+ - Kind: kernel service. Version 1.0.0.
6
+ - Schema: [`packages/contracts/schema/contracts/ContextAccounting.json`](../../packages/contracts/schema/contracts/ContextAccounting.json) (source [`ContextAccounting.ts`](../../packages/contracts/src/contracts/ContextAccounting.ts)).
7
+ - Implementation: [`packages/kernel/src/agent/Context.ts`](../../packages/kernel/src/agent/Context.ts) (`assemble`, `countTokens`); inventories stored per model call by the run ([`Run.ts`](../../packages/kernel/src/agent/Run.ts)).
8
+ - Kit: `@eloxiv/testing/conformance/ContextAccounting` ([source](../../packages/testing/src/conformance/ContextAccounting.ts)), run by [`packages/testing/test/agent-context.test.ts`](../../packages/testing/test/agent-context.test.ts).
9
+
10
+ ## Operations
11
+
12
+ | Operation | Input | Output | Errors |
13
+ | --- | --- | --- | --- |
14
+ | `inventory` | `runId`, optional `step` (`GET /agent/runs/<id>/context?step=<n>`) | `ContextInventory` | `Unauthenticated`, `UnknownRun` |
15
+ | `direct` | action `agent.directContext`: `conversationId`, `ref`, `directive` (`pin`, `evict`, `restore`) | `ref`, `directive` | the standard error set |
16
+
17
+ ## Records
18
+
19
+ - **`ContextItem`**: `ref` (stable within a conversation: `instructions:<path>`, `skill:<id>`, `memory:<id>`, `message:<id>`, `tool-result:<assistant message id>:<call>` for a call without a result, `tool:<name>`), `category`, `tokens`, `pinned`, `source` (the resource scope, memory entry, message, or the summary with what it `covers`).
20
+ - **`ContextInventory`**: `runId`, `step`, `items`, `totals` per category, `budgets` per category, `total`, `evicted` (each with `reason`: `budget` or `directive`).
21
+
22
+ ## How a call is assembled
23
+
24
+ Each item renders to exactly one prompt part and is counted from that rendered text, `ceil(characters / 4)` per part (a tool call and a tool definition count their name and their JSON separately), so `total` is what the model is sent. The estimate is deterministic and the same rule the budgets use; a provider's own tokenizer reports its real count in the call's usage.
25
+
26
+ | Category | Items, in order | Over budget |
27
+ | --- | --- | --- |
28
+ | `instructions` | the kernel's (pinned), then personal, organisation and app instructions | the lowest-priority unpinned are left out |
29
+ | `skills` | one line per skill (its description and how to load it); a pinned skill is sent whole | left out, last first |
30
+ | `memory` | entries, newest first | left out, oldest first |
31
+ | `messages` | the compaction summary (if any), then the person's and the agent's messages | never cut: compaction ([Memory](memory.md)) shortens them |
32
+ | `tool-results` | each call's result, after its message: the result of that run's step and call (`<run>:t:<step>:<call>` answers a call of `<run>:m:<step>`), so a call id reused in a later turn never takes another turn's result; a call without one, from a cancelled run, gets "did not run" | replaced by a short placeholder, oldest first |
33
+ | `tools` | each tool's definition | reported only |
34
+
35
+ Default budgets: instructions 4,000, skills 2,000, memory 2,000, messages 24,000, tool results 8,000, tools 24,000 tokens (`KernelApp.agent.budgets`). A directive applies from the next model call: `pin` keeps an item whatever its budget (a skill is then sent whole), `evict` leaves it out (instructions, skills, memory) or replaces it (a tool result), `restore` undoes either. Only the conversation's owner directs it.
36
+
37
+ ## Guarantees
38
+
39
+ 1. An inventory's `total` is the sum of its items, its category totals add up to it, and it equals what the model received.
40
+ 2. Pinned items are kept whatever the budget; evicted items are left out until restored; a category over budget sheds its lowest-priority unpinned items and reports each.
41
+ 3. Inventories are the run owner's alone.
42
+
43
+ ## How an implementation is checked
44
+
45
+ `contextAccountingConformance(start)`, with a memory budget of 60 tokens (`CONTEXT_SUBJECT_SETTINGS`): for each call of a three-step run, the inventory's total equals the input tokens the scripted model counted itself from the prompt it received (`promptTokens` in `@eloxiv/testing`, written independently of the kernel), the categories add up, every system message is an item and every tool offered is a tool item; another person cannot read it; pinning a skill sends it whole, evicting a memory entry leaves it out (reported), restoring brings it back; six memories over the 60-token budget are partly shed and reported. With a real model ([`registry/test/agent-real-model.test.ts`](../../registry/test/agent-real-model.test.ts)): each call's inventory adds up, lists the tools offered, and its estimate is within a factor of the provider's own input count (0.4 to 2.5).
46
+
47
+ ## Not yet guaranteed
48
+
49
+ - Counts are estimates (characters / 4), not the provider's tokenizer.
50
+ - Directives are per conversation; personal defaults across conversations are not built.