@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.
- package/LICENSE +21 -0
- package/README.md +12 -2
- package/dist/AgentSkills.d.ts +51 -0
- package/dist/AgentSkills.d.ts.map +1 -0
- package/dist/AgentSkills.js +264 -0
- package/dist/AgentSkills.js.map +1 -0
- package/dist/AgentWeb.d.ts +83 -0
- package/dist/AgentWeb.d.ts.map +1 -0
- package/dist/AgentWeb.js +436 -0
- package/dist/AgentWeb.js.map +1 -0
- package/dist/App.d.ts +213 -0
- package/dist/App.d.ts.map +1 -0
- package/dist/App.js +357 -0
- package/dist/App.js.map +1 -0
- package/dist/Blueprint.d.ts +47 -0
- package/dist/Blueprint.d.ts.map +1 -0
- package/dist/Blueprint.js +241 -0
- package/dist/Blueprint.js.map +1 -0
- package/dist/Brand.d.ts +42 -0
- package/dist/Brand.d.ts.map +1 -0
- package/dist/Brand.js +370 -0
- package/dist/Brand.js.map +1 -0
- package/dist/Changelog.d.ts +22 -0
- package/dist/Changelog.d.ts.map +1 -0
- package/dist/Changelog.js +117 -0
- package/dist/Changelog.js.map +1 -0
- package/dist/Cli.d.ts +17 -0
- package/dist/Cli.d.ts.map +1 -0
- package/dist/Cli.js +810 -0
- package/dist/Cli.js.map +1 -0
- package/dist/DbAdmin.d.ts +18 -0
- package/dist/DbAdmin.d.ts.map +1 -0
- package/dist/DbAdmin.js +91 -0
- package/dist/DbAdmin.js.map +1 -0
- package/dist/Dependencies.d.ts +53 -0
- package/dist/Dependencies.d.ts.map +1 -0
- package/dist/Dependencies.js +132 -0
- package/dist/Dependencies.js.map +1 -0
- package/dist/Deploy.d.ts +39 -0
- package/dist/Deploy.d.ts.map +1 -0
- package/dist/Deploy.js +458 -0
- package/dist/Deploy.js.map +1 -0
- package/dist/Docs.d.ts +71 -0
- package/dist/Docs.d.ts.map +1 -0
- package/dist/Docs.js +240 -0
- package/dist/Docs.js.map +1 -0
- package/dist/Doctor.d.ts +56 -0
- package/dist/Doctor.d.ts.map +1 -0
- package/dist/Doctor.js +368 -0
- package/dist/Doctor.js.map +1 -0
- package/dist/Dossier.d.ts +23 -0
- package/dist/Dossier.d.ts.map +1 -0
- package/dist/Dossier.js +92 -0
- package/dist/Dossier.js.map +1 -0
- package/dist/Emit.d.ts +26 -0
- package/dist/Emit.d.ts.map +1 -0
- package/dist/Emit.js +51 -0
- package/dist/Emit.js.map +1 -0
- package/dist/Errors.d.ts +26 -0
- package/dist/Errors.d.ts.map +1 -0
- package/dist/Errors.js +17 -0
- package/dist/Errors.js.map +1 -0
- package/dist/Evals.d.ts +52 -0
- package/dist/Evals.d.ts.map +1 -0
- package/dist/Evals.js +126 -0
- package/dist/Evals.js.map +1 -0
- package/dist/Files.d.ts +47 -0
- package/dist/Files.d.ts.map +1 -0
- package/dist/Files.js +145 -0
- package/dist/Files.js.map +1 -0
- package/dist/Generate.d.ts +80 -0
- package/dist/Generate.d.ts.map +1 -0
- package/dist/Generate.js +310 -0
- package/dist/Generate.js.map +1 -0
- package/dist/Guards.d.ts +45 -0
- package/dist/Guards.d.ts.map +1 -0
- package/dist/Guards.js +530 -0
- package/dist/Guards.js.map +1 -0
- package/dist/Inspect.d.ts +125 -0
- package/dist/Inspect.d.ts.map +1 -0
- package/dist/Inspect.js +270 -0
- package/dist/Inspect.js.map +1 -0
- package/dist/Keychain.d.ts +57 -0
- package/dist/Keychain.d.ts.map +1 -0
- package/dist/Keychain.js +73 -0
- package/dist/Keychain.js.map +1 -0
- package/dist/Lock.d.ts +13 -0
- package/dist/Lock.d.ts.map +1 -0
- package/dist/Lock.js +145 -0
- package/dist/Lock.js.map +1 -0
- package/dist/Mcp.d.ts +91 -0
- package/dist/Mcp.d.ts.map +1 -0
- package/dist/Mcp.js +128 -0
- package/dist/Mcp.js.map +1 -0
- package/dist/Merge.d.ts +18 -0
- package/dist/Merge.d.ts.map +1 -0
- package/dist/Merge.js +43 -0
- package/dist/Merge.js.map +1 -0
- package/dist/Migrate.d.ts +78 -0
- package/dist/Migrate.d.ts.map +1 -0
- package/dist/Migrate.js +288 -0
- package/dist/Migrate.js.map +1 -0
- package/dist/Plugins.d.ts +36 -0
- package/dist/Plugins.d.ts.map +1 -0
- package/dist/Plugins.js +304 -0
- package/dist/Plugins.js.map +1 -0
- package/dist/Postgres.d.ts +73 -0
- package/dist/Postgres.d.ts.map +1 -0
- package/dist/Postgres.js +294 -0
- package/dist/Postgres.js.map +1 -0
- package/dist/Publish.d.ts +23 -0
- package/dist/Publish.d.ts.map +1 -0
- package/dist/Publish.js +59 -0
- package/dist/Publish.js.map +1 -0
- package/dist/Registry.d.ts +539 -0
- package/dist/Registry.d.ts.map +1 -0
- package/dist/Registry.js +340 -0
- package/dist/Registry.js.map +1 -0
- package/dist/Remote.d.ts +90 -0
- package/dist/Remote.d.ts.map +1 -0
- package/dist/Remote.js +1006 -0
- package/dist/Remote.js.map +1 -0
- package/dist/Run.d.ts +120 -0
- package/dist/Run.d.ts.map +1 -0
- package/dist/Run.js +477 -0
- package/dist/Run.js.map +1 -0
- package/dist/SyncGen.d.ts +118 -0
- package/dist/SyncGen.d.ts.map +1 -0
- package/dist/SyncGen.js +392 -0
- package/dist/SyncGen.js.map +1 -0
- package/dist/Update.d.ts +301 -0
- package/dist/Update.d.ts.map +1 -0
- package/dist/Update.js +627 -0
- package/dist/Update.js.map +1 -0
- package/dist/bin.d.ts +3 -0
- package/dist/bin.d.ts.map +1 -0
- package/dist/bin.js +42 -0
- package/dist/bin.js.map +1 -0
- package/dist/docs/backlog.md +56 -0
- package/dist/docs/ci.md +277 -0
- package/dist/docs/cli.md +696 -0
- package/dist/docs/connectors/google.md +115 -0
- package/dist/docs/connectors/http-openapi.md +7 -0
- package/dist/docs/connectors/mcp.md +8 -0
- package/dist/docs/connectors/microsoft-graph.md +75 -0
- package/dist/docs/connectors/openai.md +25 -0
- package/dist/docs/connectors/slack.md +162 -0
- package/dist/docs/connectors/workos.md +39 -0
- package/dist/docs/contracts/README.md +173 -0
- package/dist/docs/contracts/action-consent.md +92 -0
- package/dist/docs/contracts/action-registry.md +85 -0
- package/dist/docs/contracts/actor.md +100 -0
- package/dist/docs/contracts/agent-resources.md +90 -0
- package/dist/docs/contracts/agent-runtime.md +257 -0
- package/dist/docs/contracts/approvals.md +126 -0
- package/dist/docs/contracts/audit.md +75 -0
- package/dist/docs/contracts/auth-provider.md +74 -0
- package/dist/docs/contracts/calendar-provider.md +46 -0
- package/dist/docs/contracts/client-sdk.md +245 -0
- package/dist/docs/contracts/collab-document.md +151 -0
- package/dist/docs/contracts/command.md +44 -0
- package/dist/docs/contracts/connections.md +235 -0
- package/dist/docs/contracts/context-accounting.md +50 -0
- package/dist/docs/contracts/daemon.md +243 -0
- package/dist/docs/contracts/db-tx.md +53 -0
- package/dist/docs/contracts/delegation.md +68 -0
- package/dist/docs/contracts/device-control.md +103 -0
- package/dist/docs/contracts/directory-provider.md +36 -0
- package/dist/docs/contracts/directory.md +161 -0
- package/dist/docs/contracts/document-source.md +33 -0
- package/dist/docs/contracts/files.md +115 -0
- package/dist/docs/contracts/flags.md +83 -0
- package/dist/docs/contracts/host.md +68 -0
- package/dist/docs/contracts/http-api.md +43 -0
- package/dist/docs/contracts/ingestion.md +130 -0
- package/dist/docs/contracts/ingress.md +141 -0
- package/dist/docs/contracts/invocation.md +260 -0
- package/dist/docs/contracts/local-client.md +108 -0
- package/dist/docs/contracts/locale.md +56 -0
- package/dist/docs/contracts/machine-identity.md +117 -0
- package/dist/docs/contracts/mail-provider.md +49 -0
- package/dist/docs/contracts/memory.md +53 -0
- package/dist/docs/contracts/messaging.md +40 -0
- package/dist/docs/contracts/metering.md +139 -0
- package/dist/docs/contracts/model-provider.md +84 -0
- package/dist/docs/contracts/module-manifest.md +213 -0
- package/dist/docs/contracts/notification-channel.md +90 -0
- package/dist/docs/contracts/notifications.md +123 -0
- package/dist/docs/contracts/outbox.md +80 -0
- package/dist/docs/contracts/privacy.md +110 -0
- package/dist/docs/contracts/progress.md +52 -0
- package/dist/docs/contracts/query-surface.md +108 -0
- package/dist/docs/contracts/readiness.md +63 -0
- package/dist/docs/contracts/release.md +142 -0
- package/dist/docs/contracts/result-rendering.md +61 -0
- package/dist/docs/contracts/sandbox.md +186 -0
- package/dist/docs/contracts/scheduler.md +148 -0
- package/dist/docs/contracts/screen-context.md +81 -0
- package/dist/docs/contracts/search.md +120 -0
- package/dist/docs/contracts/secrets.md +74 -0
- package/dist/docs/contracts/settings.md +109 -0
- package/dist/docs/contracts/sharing.md +77 -0
- package/dist/docs/contracts/slot.md +48 -0
- package/dist/docs/contracts/space.md +67 -0
- package/dist/docs/contracts/storage-adapter.md +45 -0
- package/dist/docs/contracts/storage-backend.md +56 -0
- package/dist/docs/contracts/sync.md +213 -0
- package/dist/docs/contracts/telemetry.md +80 -0
- package/dist/docs/contracts/theme-tokens.md +50 -0
- package/dist/docs/contracts/tool-source.md +58 -0
- package/dist/docs/contracts/versioning.md +99 -0
- package/dist/docs/contracts/view.md +65 -0
- package/dist/docs/contracts/work-items.md +99 -0
- package/dist/docs/contracts/workflow.md +82 -0
- package/dist/docs/decisions.md +163 -0
- package/dist/docs/example-app.md +192 -0
- package/dist/docs/getting-started.md +927 -0
- package/dist/docs/goal.md +54 -0
- package/dist/docs/parity.md +29 -0
- package/dist/docs/performance.md +129 -0
- package/dist/docs/registry/README.md +74 -0
- package/dist/docs/registry/app.md +38 -0
- package/dist/docs/registry/approvals-ui-foldkit.md +28 -0
- package/dist/docs/registry/calendar-ui-foldkit.md +27 -0
- package/dist/docs/registry/calendar.md +35 -0
- package/dist/docs/registry/chat-ui-foldkit.md +30 -0
- package/dist/docs/registry/desktop-rune.md +49 -0
- package/dist/docs/registry/desktop.md +32 -0
- package/dist/docs/registry/eloxiv-action.md +25 -0
- package/dist/docs/registry/eloxiv-connector.md +25 -0
- package/dist/docs/registry/eloxiv-module.md +25 -0
- package/dist/docs/registry/eloxiv-policy.md +25 -0
- package/dist/docs/registry/eloxiv-view.md +25 -0
- package/dist/docs/registry/hello-ui-foldkit.md +29 -0
- package/dist/docs/registry/hello.md +39 -0
- package/dist/docs/registry/home-ui-foldkit.md +27 -0
- package/dist/docs/registry/home.md +29 -0
- package/dist/docs/registry/inbox-ui-foldkit.md +27 -0
- package/dist/docs/registry/mail-ui-foldkit.md +27 -0
- package/dist/docs/registry/mail.md +34 -0
- package/dist/docs/registry/meeting-prep.md +26 -0
- package/dist/docs/registry/members-ui-foldkit.md +28 -0
- package/dist/docs/registry/mobile.md +37 -0
- package/dist/docs/registry/notes-ui-foldkit.md +27 -0
- package/dist/docs/registry/notes.md +26 -0
- package/dist/docs/registry/people-ui-foldkit.md +28 -0
- package/dist/docs/registry/people.md +38 -0
- package/dist/docs/registry/shell-foldkit.md +34 -0
- package/dist/docs/registry/theme.md +25 -0
- package/dist/docs/registry/ui-conformance.md +30 -0
- package/dist/docs/release.md +100 -0
- package/dist/docs/scaffold.md +826 -0
- package/dist/docs/security/threat-model.md +299 -0
- package/dist/docs/upstream/zero-cache-socket-handoff.md +105 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/package.json +48 -3
- package/src/AgentSkills.ts +329 -0
- package/src/AgentWeb.ts +507 -0
- package/src/App.ts +435 -0
- package/src/Blueprint.ts +276 -0
- package/src/Brand.ts +415 -0
- package/src/Changelog.ts +136 -0
- package/src/Cli.ts +1458 -0
- package/src/DbAdmin.ts +115 -0
- package/src/Dependencies.ts +170 -0
- package/src/Deploy.ts +563 -0
- package/src/Docs.ts +309 -0
- package/src/Doctor.ts +424 -0
- package/src/Dossier.ts +148 -0
- package/src/Emit.ts +68 -0
- package/src/Errors.ts +18 -0
- package/src/Evals.ts +153 -0
- package/src/Files.ts +152 -0
- package/src/Generate.ts +402 -0
- package/src/Guards.ts +541 -0
- package/src/Inspect.ts +358 -0
- package/src/Keychain.ts +107 -0
- package/src/Lock.ts +174 -0
- package/src/Mcp.ts +159 -0
- package/src/Merge.ts +70 -0
- package/src/Migrate.ts +331 -0
- package/src/Plugins.ts +347 -0
- package/src/Postgres.ts +353 -0
- package/src/Publish.ts +64 -0
- package/src/Registry.ts +405 -0
- package/src/Remote.ts +1158 -0
- package/src/Run.ts +541 -0
- package/src/SyncGen.ts +570 -0
- package/src/Update.ts +873 -0
- package/src/bin.ts +46 -0
- package/src/index.ts +7 -0
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# MachineIdentity
|
|
2
|
+
|
|
3
|
+
Identities for software: service principals, API tokens, and the OAuth 2.1 authorisation server MCP and API clients use. Every credential it issues is resolved to an `Actor` by the invocation path's identity step, on every call, so a machine acts through exactly the same identity, policy, approval, idempotency, audit and outbox stages as a person.
|
|
4
|
+
|
|
5
|
+
- Kind: kernel service. Version 1.0.0.
|
|
6
|
+
- Schema: [`packages/contracts/schema/contracts/MachineIdentity.json`](../../packages/contracts/schema/contracts/MachineIdentity.json) (source [`MachineIdentity.ts`](../../packages/contracts/src/contracts/MachineIdentity.ts)).
|
|
7
|
+
- Implementation: [`packages/kernel/src/machine/`](../../packages/kernel/src/machine): `MachineIdentity.ts` (principals and tokens), `OAuth.ts` (the authorisation server), `Pages.ts` (its pages), `Tokens.ts` (credential material); resolution in [`Identity.ts`](../../packages/kernel/src/Identity.ts) (`authenticateCall`). Tables: `eloxiv.service_principal`, `eloxiv.api_token`, `eloxiv.oauth_*` (kernel migration `0014_machine_identity`).
|
|
8
|
+
- Kit: `@eloxiv/testing/conformance/MachineIdentity` ([source](../../packages/testing/src/conformance/MachineIdentity.ts)), against the desk fixture ([`conformance/desk`](../../packages/testing/src/conformance/desk)).
|
|
9
|
+
|
|
10
|
+
Better Auth 1.7.15 was checked first: it ships a device-authorization plugin but no OAuth provider or MCP plugin (those moved to a separate package), and its device plugin issues a full user session as the access token, with no organisation, audience, scope or refresh rotation. So the server is built on the kernel's own tables. Better Auth stays the sign-in for people: the OAuth pages sign users in through it, and Better Auth sessions remain a credential on every surface.
|
|
11
|
+
|
|
12
|
+
## Credentials
|
|
13
|
+
|
|
14
|
+
| Credential | Format | Stored | Lifetime | Accepted on |
|
|
15
|
+
| --- | --- | --- | --- | --- |
|
|
16
|
+
| Better Auth session | Better Auth's token (bearer or cookie) | Better Auth | Better Auth's | every surface; the only credential management operations and sync accept |
|
|
17
|
+
| API token | `elxk_` + 43 base64url characters (256 random bits) | SHA-256 hash; a display prefix (`elxk_` + 6) | `expiresInSeconds`, default 90 days, at most 366 | HTTP, RPC, MCP, CLI (and the in-process surfaces) |
|
|
18
|
+
| OAuth access token | `elxa_` + 43 | SHA-256 hash, in its grant | 1 hour (`accessTokenTtlS`) | only the surface of its resource: `<base>/mcp` for MCP, `<base>/api` for HTTP, RPC and CLI |
|
|
19
|
+
| OAuth refresh token | `elxr_` + 43 | SHA-256 hash | 30 days; single use (rotated) | the token endpoint |
|
|
20
|
+
| Authorisation code | `elxc_` + 43 | SHA-256 hash | 60 s (`codeTtlS`); single use | the token endpoint |
|
|
21
|
+
| Device code / user code | `elxd_` + 43 / `XXXX-XXXX` (20 letters, no look-alikes) | SHA-256 hashes | 10 minutes | the token endpoint / the device page |
|
|
22
|
+
| Client secret (confidential clients) | `elxs_` + 43 | SHA-256 hash | the client's | the token and revocation endpoints |
|
|
23
|
+
|
|
24
|
+
The prefixes make leaked credentials recognisable to secret scanners. Secrets are random, so a fast hash is enough and lookups stay indexed; comparisons of secrets that are not looked up by hash are constant-time.
|
|
25
|
+
|
|
26
|
+
**Every use re-checks** (`Identity.authenticateCall`): the token exists, is neither revoked nor expired (nor its grant revoked); an OAuth token's audience is the surface's resource; `x-eloxiv-org`, if given, names the credential's own organisation (otherwise `Forbidden`); and the user or service principal is still a member of that organisation, with roles, groups and permissions read afresh (a service principal must also be enabled). Removing a membership, disabling a principal or revoking a token therefore refuses the very next call.
|
|
27
|
+
|
|
28
|
+
**Scopes narrow, never grant.** A credential's scope is a list of `actions` (everything the actor's policy allows; the default), `action:<name>` or `permission:<id>` (the actions that permission of the vocabulary names). The invocation path refuses an action outside the scope as `Forbidden` right after identity, and the action's policy still applies to whatever the scope lets through. Listings follow the same checks ([Invocation](invocation.md#reach)): MCP `tools/list` shows a token only the actions its scope and the policy let it reach. An MCP host asks for the scopes the protected resource metadata names (`scopes_supported: ["actions"]`); a narrower scope is asked for explicitly (`scope` at the authorisation endpoint).
|
|
29
|
+
|
|
30
|
+
## Service principals
|
|
31
|
+
|
|
32
|
+
An organisation-scoped actor for software: a row in `eloxiv.service_principal` (id `sp_<hex>`, a name unique in the organisation) and a **membership** of its organisation, so Directory roles, groups and permissions, Cedar policies (`principal == Eloxiv::User::"sp_..."`) and the row-level security functions apply to it unchanged. It has no email, no password and no session: it acts only through API tokens issued for it.
|
|
33
|
+
|
|
34
|
+
## Operations
|
|
35
|
+
|
|
36
|
+
Management operations need a **signed-in person** (a Better Auth session), never a machine credential, so a leaked token cannot mint more tokens or widen anyone's authority. They act in the caller's organisation, hold the caller's session inside their transaction, reads as well as changes (its row locked `FOR SHARE` before anything else and its expiry read again once the lock is held, so a sign-out waits for an operation in flight, or committed first and refuses it: [Invocation](invocation.md#authority)), are authorised against the live directory there, and are audited as `eloxiv.machine.<operation>` (`succeeded`, or `denied`/`failed` after rollback). In process: `MachineIdentity.as(headers)`; over HTTP: `POST /kernel/machine-identity/<operation>` with a JSON body, answered with the output or `{ _tag, message }` (401, 403, 400).
|
|
37
|
+
|
|
38
|
+
| Operation | Who | What |
|
|
39
|
+
| --- | --- | --- |
|
|
40
|
+
| `createServicePrincipal` | `eloxiv.machine.manage` | `name`, `description?`, `roles?` (default `member`) → `{ id }`. The roles may grant only permissions the caller holds (no escalation through principals) |
|
|
41
|
+
| `listServicePrincipals` | any member | the organisation's principals with their roles and whether they are disabled |
|
|
42
|
+
| `disableServicePrincipal` / `enableServicePrincipal` | `eloxiv.machine.manage` | a disabled principal's tokens are refused (`Forbidden`) from the next call |
|
|
43
|
+
| `deleteServicePrincipal` | `eloxiv.machine.manage` | deletes it with its membership, roles, group memberships, tokens and linked identities. Under the organisation's directory lock and the directory's rule: a principal that is the last holder of `eloxiv.directory.manage` is not deleted (`InvalidInput`) |
|
|
44
|
+
| `createToken` | any member (personal); `eloxiv.machine.manage` for a principal | `name`, `principalId?`, `actions?`, `permissions?`, `expiresInSeconds?` → `{ id, token, prefix, expiresAt }`. The token is shown **once** |
|
|
45
|
+
| `listTokens` | any member: their personal tokens; `eloxiv.machine.manage`: all of the organisation's | `ApiTokenInfo` (prefix, subject, scope, created, expires, revoked, **last used**), never the token |
|
|
46
|
+
| `revokeToken` | the owner of a personal token; `eloxiv.machine.manage` for any | sets `revokedAt`; the next call is refused |
|
|
47
|
+
| `resolve` | the identity step | a bearer credential on a surface → `ResolvedCredential` (actor and scope), as described above |
|
|
48
|
+
|
|
49
|
+
`eloxiv.machine.manage` is a kernel permission; every organisation's built-in `admin` role grants it (migration `0010` adds it to existing ones). Last use is recorded at most once a minute per token.
|
|
50
|
+
|
|
51
|
+
### The OAuth authorisation server
|
|
52
|
+
|
|
53
|
+
The kernel's base URL is the issuer. Endpoints (each also an operation in the schema):
|
|
54
|
+
|
|
55
|
+
| Operation | Endpoint | Notes |
|
|
56
|
+
| --- | --- | --- |
|
|
57
|
+
| `authorizationServerMetadata` | `GET /.well-known/oauth-authorization-server` | RFC 8414. `code_challenge_methods_supported: ["S256"]`, grants `authorization_code`, `refresh_token`, `urn:ietf:params:oauth:grant-type:device_code`, client authentication `none`, `client_secret_post`, `client_secret_basic`, `authorization_response_iss_parameter_supported` |
|
|
58
|
+
| `protectedResourceMetadata` | `GET /.well-known/oauth-protected-resource/mcp` (and `/api`) | RFC 9728: `resource` is `<base>/mcp` (or `<base>/api`), `authorization_servers: [<base>]`. Every request to `/mcp` without a valid credential is answered `401` with `WWW-Authenticate: Bearer resource_metadata="<base>/.well-known/oauth-protected-resource/mcp"` (plus `error="invalid_token"` when a token was sent), as the MCP authorisation specification requires; a refused `tools/call` is audited like any refused call |
|
|
59
|
+
| `register` | `POST /oauth/register` | RFC 7591, a JSON object naming each member once. Redirect URIs must be `https`, `http` on a loopback host, or a private-use scheme containing a dot (RFC 8252), without fragments; at most 10; `token_endpoint_auth_method` defaults to `client_secret_basic` (a secret is issued) or `none` for public clients. **Abuse limits:** 16 KiB bodies, 200-character names, `registrationLimit` registrations per source address per `registrationWindowS` (default 20 per hour, `429` with `Retry-After`), and registrations never used within a day are deleted |
|
|
60
|
+
| `authorize` | `GET /oauth/authorize` | Authorisation code with PKCE, **S256 only**; `resource` (RFC 8707) is required and must be one of the kernel's resources; `scope` defaults to `actions`. An unknown client or an unregistered redirect URI, or a `client_id` or `redirect_uri` given twice, is shown an error page and never redirected; other errors are redirected with `error`, `state` and `iss` (any other parameter given twice is `invalid_request`, without `state` if that was the one). On success the browser goes to the consent page |
|
|
61
|
+
| `token` | `POST /oauth/token` | Form or JSON. **Code:** single use (any presentation spends it, so a wrong verifier burns it), within its lifetime, the PKCE verifier, the same `redirect_uri` if sent (OAuth 2.1 drops it from the token request; PKCE binds the code to its client), the same `resource` if sent, and the user still a member; a **reused** code revokes the grant its first exchange created. **Refresh:** rotated on every use; presenting a used refresh token is reuse, and **the whole grant is revoked** (every access and refresh token in it); the scope cannot be narrowed. **Device:** `authorization_pending`, `slow_down` (polling faster than the interval adds 5 s), `access_denied`, `expired_token`. Responses carry `Cache-Control: no-store` |
|
|
62
|
+
| `revoke` | `POST /oauth/revoke` | RFC 7009. A refresh token revokes its grant; an access token itself. Unknown tokens, and other clients' tokens, are answered `200` and left alone |
|
|
63
|
+
| `deviceAuthorization` | `POST /oauth/device_authorization` | RFC 8628, for CLIs and headless agents: `device_code`, `user_code`, `verification_uri` (`<base>/oauth/device`), `verification_uri_complete`, `expires_in`, `interval` |
|
|
64
|
+
|
|
65
|
+
A **grant** is one client's access for one user in one organisation, to one resource, with one scope: every token issued from a code or device approval and its refreshes. Revoking it (reuse, revocation) ends all of them.
|
|
66
|
+
|
|
67
|
+
**Requests.** Every endpoint and page refuses a parameter given more than once (a repeated query or form parameter, or a JSON member named twice) as `invalid_request` (RFC 6749 section 3.1), rather than picking one of its values. A repeated `resource` alone asks for several resources at once, which RFC 8707 allows a server to refuse: a grant is bound to exactly one, so it is `invalid_target` at the authorisation, device and token endpoints. Client credentials in `client_secret_basic` are form-urlencoded (RFC 6749 section 2.3.1); a malformed escape fails client authentication (`401 invalid_client`). Bodies are read with a running byte count and refused as soon as they pass 16 KiB (`413`), or when they do not arrive within `http.bodyTimeoutMs` (`408`).
|
|
68
|
+
|
|
69
|
+
### The pages
|
|
70
|
+
|
|
71
|
+
OAuth needs a few HTML pages, so the kernel serves them: minimal, unstyled, no scripts, `Content-Security-Policy: default-src 'none'; frame-ancestors 'none'`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, `no-store`. They are the defaults of `KernelApp.oauthPages`; an app replaces any of them with functions returning an HTML document (`OAuthPages` in [`Pages.ts`](../../packages/kernel/src/machine/Pages.ts)). A replacement must post the same fields to the same paths; the kernel validates every field again, so a page changes how things look, never what is authorised.
|
|
72
|
+
|
|
73
|
+
| Page | Shown at | Posts |
|
|
74
|
+
| --- | --- | --- |
|
|
75
|
+
| `signIn` | any page when not signed in | `POST /oauth/sign-in`: `email`, `password`, `return_to` (only `/oauth/consent?…` or `/oauth/device?…`). Signs in through Better Auth's HTTP handler, exactly as `/auth/sign-in/email` is reached, and sets its session cookie. So Better Auth's protections apply, its rate limiter above all: the form and `/auth/sign-in/email` share one bucket per client address (by default 3 attempts per 10 s, in every environment; over it, `429` with `Retry-After`, and the password is not checked) |
|
|
76
|
+
| `consent` | `GET /oauth/consent?request=<id>` | `POST /oauth/consent`: `request`, `csrf`, `org` (one of the user's organisations), `decision` (`approve` or `deny`) |
|
|
77
|
+
| `deviceEntry` | `GET /oauth/device` | a GET form with `user_code` |
|
|
78
|
+
| `deviceConfirm` | `GET /oauth/device?user_code=<code>` | `POST /oauth/device`: `user_code`, `csrf`, `org`, `decision` |
|
|
79
|
+
| `message` | outcomes and errors | nothing |
|
|
80
|
+
|
|
81
|
+
**Client addresses.** Every per-address limit (registrations, user codes, Better Auth's sign-in limiter) keys on the connection's peer address; behind proxies (`trustProxy`), on the `x-forwarded-for` entry the outermost trusted proxy appended: `trustedProxyHops` entries from the end (default 1, the last: one load balancer; 2 for a CDN in front of one). Earlier entries are whatever the client sent; with fewer entries than hops, the earliest. Every per-address count groups an IPv6 address by its /64 (and an IPv4-mapped one as IPv4), as Better Auth does. The kernel states the address to Better Auth in its own header, `x-eloxiv-client-address`, set on every request it hands Better Auth and dropped from anything a client sends, so `x-forwarded-for` as a client sent it never chooses a bucket. Better Auth's limiter is on in every environment (its own default is production only) and keeps its counts in the database (`auth."rateLimit"`), so every kernel process on one database spends one budget. `KernelConfig.authLimits` sets it: `windowS` and `max` for any of Better Auth's routes (default 100 per 10 s), `signInWindowS` and `signInMax` for password sign-in and sign-up (default 3 per 10 s); environment `ELOXIV_AUTH_RATE_LIMIT_WINDOW_S`, `ELOXIV_AUTH_RATE_LIMIT_MAX`, `ELOXIV_SIGN_IN_LIMIT_WINDOW_S`, `ELOXIV_SIGN_IN_LIMIT`. The same settings hold `signOutWaitMs` (`ELOXIV_SIGN_OUT_WAIT_MS`, default 5 s: how long sign-out waits for work holding the session before it revokes the session, [Invocation](invocation.md#authority)) and `anonymousDenialsPerMinute` (`ELOXIV_ANONYMOUS_DENIALS_PER_MINUTE`, default 30: the bound on audit records of refusals of callers not identified, [Audit](audit.md)). Test kernels raise the limits through this configuration; nothing turns the limiter off.
|
|
82
|
+
|
|
83
|
+
The `csrf` value is an HMAC of the request (or user code) and the Better Auth session id; form posts with a foreign `Origin` or `Sec-Fetch-Site: cross-site` are refused. The pending authorisation request is stored server-side (10 minutes) and consumed by the decision. A decision (the code it issues, the device it approves or denies) is recorded in a transaction that holds the person's session first (`FOR SHARE`, its expiry read again under the lock): a sign-out either waits for the decision to commit, or commits first and the decision records nothing (the sign-in page, 401; the authorisation request stays pending) ([`session-hold.test.ts`](../../packages/testing/test/session-hold.test.ts)). Wrong user codes count against the source address (`userCodeLimit` per 10 minutes); an address over the limit gets no lookups at all. Each lookup first takes a slot in one atomic statement and a lookup that finds its code gives it back, so guesses arriving at once cannot all pass a count read before any of them was added.
|
|
84
|
+
|
|
85
|
+
### Settings
|
|
86
|
+
|
|
87
|
+
`KernelConfig.machine` (`MachineConfig`): `accessTokenTtlS`, `refreshTokenTtlS`, `codeTtlS`, `deviceCodeTtlS`, `deviceIntervalS`, `registrationLimit`, `registrationWindowS`, `userCodeLimit`, `trustProxy` (read the client address from `x-forwarded-for`; only behind proxies that append to it), `trustedProxyHops` (how many do, default 1).
|
|
88
|
+
|
|
89
|
+
`KernelConfig.http` (`HttpConfig`), for the whole HTTP server: `maxBodyBytes` (default 4 MiB; every body any route reads, counted as it arrives, `413` past it; routes set smaller limits of their own), `bodyTimeoutMs` (default 30 s; every body any route reads, by the kernel itself or by Effect's RPC and HTTP API transports, must arrive within it of the read starting, or the request is answered `408` and its connection closed; on Node the whole request must also arrive within it plus the header allowance), `idleTimeoutS` (default 120, at most 255; a connection silent that long while the kernel owes it nothing is closed, on Bun and Node alike: idle between keep-alive requests, or while a response is written that the client stopped reading, so a quiet response stream must send keep-alives; never while a request's handler is still working on its answer, however long that takes. On Node it also closes a connection whose request headers stop arriving; Bun's server does not time a connection before its headers are complete). Environment: `ELOXIV_HTTP_MAX_BODY_BYTES`, `ELOXIV_HTTP_BODY_TIMEOUT_MS`, `ELOXIV_HTTP_IDLE_TIMEOUT_S`. Environment: `ELOXIV_OAUTH_CODE_TTL_S`, `ELOXIV_OAUTH_ACCESS_TTL_S`, `ELOXIV_OAUTH_DEVICE_INTERVAL_S`, `ELOXIV_OAUTH_REGISTRATION_LIMIT`, `ELOXIV_TRUST_PROXY`, `ELOXIV_TRUSTED_PROXY_HOPS`. The resources are derived from `ELOXIV_BASE_URL`, which must be the URL clients use. It may carry a path: see [Release, "Under a base path"](release.md#under-a-base-path) for where discovery is served then.
|
|
90
|
+
|
|
91
|
+
## Errors
|
|
92
|
+
|
|
93
|
+
Management operations fail with the standard `Unauthenticated` (no session, or a machine credential), `Forbidden` (missing permission, escalation) and `InvalidInput`. Credential resolution fails with `Unauthenticated` (unknown, revoked, expired, wrong audience) or `Forbidden` (not a member, disabled principal, another organisation). The OAuth endpoints answer RFC 6749 error objects (`invalid_request`, `invalid_client`, `invalid_grant`, `unauthorized_client`, `unsupported_grant_type`, `invalid_scope`, `invalid_target`, `invalid_redirect_uri`, `invalid_client_metadata`, `authorization_pending`, `slow_down`, `access_denied`, `expired_token`).
|
|
94
|
+
|
|
95
|
+
## Guarantees
|
|
96
|
+
|
|
97
|
+
1. Every credential is resolved on every call through the invocation path; nothing caches an actor between calls.
|
|
98
|
+
2. A credential acts only in its organisation and, for OAuth, only at its resource.
|
|
99
|
+
3. A scope never widens what the actor's policy allows.
|
|
100
|
+
4. Secrets are stored only as hashes and shown once.
|
|
101
|
+
5. Codes, refresh tokens and device codes work once; reusing a code or refresh token revokes its grant.
|
|
102
|
+
6. Management needs a signed-in person, is authorised against the live directory and audited; principals cannot be given permissions their creator lacks.
|
|
103
|
+
7. Unauthenticated MCP requests get the RFC 9728 challenge.
|
|
104
|
+
|
|
105
|
+
## How an implementation is checked
|
|
106
|
+
|
|
107
|
+
`machineIdentityConformance(harness)` registers, over HTTP against the desk fixture: metadata and the MCP challenge; **a real MCP client** (`@modelcontextprotocol/sdk` 1.32.2) that registers dynamically, is sent to the authorisation endpoint, is approved through the pages, exchanges the code, then lists and calls tools (audited as `mcp`); a wrong PKCE verifier (and the spent code); a code exchanged without `redirect_uri` (OAuth 2.1); repeated parameters at the authorisation endpoint (a repeated client or redirect URI not redirected), the token, device and revocation endpoints, and in JSON bodies and registrations; plain PKCE, a missing challenge and a missing resource; an unregistered redirect URI (no redirect) and a mismatched one at the token endpoint; an expired code; a reused code (its tokens revoked); refresh rotation and reuse (the whole grant revoked); revocation of access and refresh tokens, and not by another client; membership removal refusing the next call for OAuth and API tokens and the next refresh; a token scoped to one action (or one permission, or an OAuth scope) refused another while the same user may call it; audience and organisation binding; the device flow with pending, slow down, approval, a single issue and denial; service principals (only admins create, disable, enable and delete them, no escalation, acting as themselves through the invocation path, unable to manage themselves, audited); API tokens (shown once, listed by prefix, last use, revocation by the owner only, expiry, organisation binding); registration limits and unsafe redirect URIs.
|
|
108
|
+
|
|
109
|
+
The Eloxiv kernel runs it in [`packages/testing/test/machine-identity.test.ts`](../../packages/testing/test/machine-identity.test.ts), which also checks that no stored row contains any issued secret. [`packages/testing/test/sign-in-limit.test.ts`](../../packages/testing/test/sign-in-limit.test.ts) configures production-like limits (nothing turns the limiter on) and checks that the sign-in page is limited like `/auth/sign-in/email`, even for the right password, in one shared bucket, that neither `x-forwarded-for` nor `x-eloxiv-client-address` picks another, and that a second kernel process on the same database spends the same budget. [`registry/test/mcp-oauth.test.ts`](../../registry/test/mcp-oauth.test.ts) is the external agent's journey end to end: the MCP TypeScript SDK's client, with the OAuth provider an MCP host implements (`McpOAuthProvider` in `@eloxiv/testing/conformance/OAuthClient`), against the example app's own kernel process (`examples/headless-app`): it discovers the server from the 401 challenge, registers, authorises with S256 PKCE for `<base>/mcp` through the pages, and exchanges the code; its token (`actions` scope) is refused at `/api`; `tools/list` equals the person's reach (the OpenAPI document for their session); a call is audited as the person on the `mcp` surface with its outbox event, and the action's policy still refuses what it forbids; revoking the grant answers its next call with the `invalid_token` challenge and refuses its refresh. Against the desk fixture's kernel: a member's listing omits the action the policy hides from them (`desk_stamp`), a call to it is refused and audited as `denied`, and a token asked for with a narrower scope (`action:desk.write`) lists and calls only that. [`registry/test/cli-surface.test.ts`](../../registry/test/cli-surface.test.ts) runs `eloxiv login` through the device flow end to end, three `eloxiv call`s that refresh one expired sign-in at once (a single refresh; the grant survives), and a `logout` whose revocation fails (the credentials are kept, exit `2`).
|
|
110
|
+
|
|
111
|
+
## Not yet guaranteed
|
|
112
|
+
|
|
113
|
+
- **Install links and client-specific connect guides** for MCP hosts (ledger A-080) are not provided.
|
|
114
|
+
- **Token lists for OAuth grants** (a user reviewing and revoking the clients they authorised) have no management operation yet; revocation works through `/oauth/revoke` only.
|
|
115
|
+
- **Narrowing the scope on refresh** is refused rather than supported.
|
|
116
|
+
- **Rate limits** cover registration, user-code guessing and password sign-in (per address, Better Auth's limiter, counted in the database and shared by every kernel process); there is no per-account limit on password guesses spread over many addresses, on either sign-in path; the token endpoint is not limited per client (codes, refresh tokens and device codes are single use and high-entropy).
|
|
117
|
+
- **Signed (JWT) access tokens** are not issued: tokens are opaque, so every resource server must ask the kernel (which is the resource server today).
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# MailProvider
|
|
2
|
+
|
|
3
|
+
A person's mailbox at a provider (Outlook through Microsoft Graph, Gmail), over a kernel [Connection](connections.md). Not system email: that is [NotificationChannel](notification-channel.md).
|
|
4
|
+
|
|
5
|
+
- Kind: capability. Version 1.6.0 (1.1.0 adds `archive` to `updateMessage`; 1.2.0 adds `clientId` to `sendMessage` and `findSent`, and marks sending external; 1.3.0 adds `MailMessage.version`; 1.4.0 adds `sentAfter` to `findSent`; 1.5.0 adds `listAliases` and `from` to `sendMessage`; 1.6.0 adds the provider's own filters, `listFilters`, `createFilter` and `deleteFilter`, the scope `mail.settings` and the flag `filters`).
|
|
6
|
+
- Schema: [`packages/contracts/schema/contracts/MailProvider.json`](../../packages/contracts/schema/contracts/MailProvider.json) (source [`MailProvider.ts`](../../packages/contracts/src/contracts/MailProvider.ts); shared parts in [`Capability.ts`](../../packages/contracts/src/contracts/Capability.ts)).
|
|
7
|
+
- Implementations: the [`microsoft-graph`](../connectors/microsoft-graph.md) and [`google`](../connectors/google.md) connectors.
|
|
8
|
+
- Kit: `@eloxiv/testing/conformance/MailProvider` ([source](../../packages/testing/src/conformance/MailProvider.ts)), run by [`registry/test/connector-microsoft-graph.test.ts`](../../registry/test/connector-microsoft-graph.test.ts) and [`registry/test/connector-google.test.ts`](../../registry/test/connector-google.test.ts) against protocol fakes, and by [`registry/test/connector-live.test.ts`](../../registry/test/connector-live.test.ts) against real accounts when configured.
|
|
9
|
+
|
|
10
|
+
What every capability contract shares (the standard error set, delta sync, scopes, flags, the kit's harness) is described in [Capability contracts](README.md#capability-contracts).
|
|
11
|
+
|
|
12
|
+
## Records
|
|
13
|
+
|
|
14
|
+
- `MailFolder`: `id`, `name`, `kind` (`inbox`, `sent`, `drafts`, `trash`, `archive`, `spam`, `other`). Gmail's labels are folders; its system labels map to kinds.
|
|
15
|
+
- `MailMessage`: `id`, `threadId`, `folderIds` (one for Graph, the labels for Gmail), `subject`, `from`, `to`, `cc`, `receivedAt` (ISO UTC), `snippet`, `body` (`{ contentType: "text" | "html", content }`, only from `getMessage`), `isRead`, `isDraft`, `hasAttachments`, and `version` (optional): the provider's marker of the message's current state. Graph: the item's `changeKey`, which changes on any change to the item (its body, read state, flags, folder). Gmail: the message's `historyId`, which moves with its labels; a Gmail message's content never changes (an edited message is a new message with a new id, and the old one is deleted), so content is followed there by the message's id and its deletion. Absent or null when the provider gives none: a module must then treat the message as possibly changed whenever it sees it (mail fetches its body again each time, and submits it as a new version only if it differs).
|
|
16
|
+
- `MailFilter`: one of the provider's own server-side filters (Gmail's `users.settings.filters`): `id`, `criteria` (`from`, `to`, `subject`, `query` and `negatedQuery` in the provider's search syntax, `hasAttachment`, `excludeChats`, `size` with `sizeComparison` `larger` or `smaller`; all given must match) and `action` (`addLabelIds`, `removeLabelIds`: archive is removing `INBOX`, mark read removing `UNREAD`, delete adding `TRASH`; `forward` only as listed, for a filter made elsewhere). Not a module's triage rules, which the module applies itself.
|
|
17
|
+
- `MailFlags`: `threads`, `attachments`, `drafts`, `labels` (a message in several folders at once), `pushNotifications`, `filters` (optional: the provider's own filters work; absent or false, their operations answer `InvalidInput`).
|
|
18
|
+
|
|
19
|
+
## Operations
|
|
20
|
+
|
|
21
|
+
| Operation | Scopes | What |
|
|
22
|
+
| --- | --- | --- |
|
|
23
|
+
| `listFolders` | `mail.read` | The mailbox's folders or labels |
|
|
24
|
+
| `listMessages` | `mail.read` | Summaries in a folder (default the inbox), newest first, paged (`pageToken`, `pageSize`) |
|
|
25
|
+
| `getMessage` | `mail.read` | One message with its body |
|
|
26
|
+
| `sendMessage` | `mail.send` | Send `{ to, cc?, subject, body, clientId?, from? }`. `from` sends it as one of the account's aliases (absent: the default): an address it may not send as is refused before anything is sent (Gmail: `InvalidInput` after reading `listAliases`, since Gmail would quietly send from the primary address instead; that read needs `mail.read` too, and a 5xx on it leaves a scheduled send `unknown`, backlog 34) or by the provider (Graph: 403 `ErrorSendAsDenied`, `Forbidden`, without Exchange's send-as permission). `id` is the sent message's id when the provider reports it (Gmail), else null (Graph's `sendMail` answers 202). `clientId` (letters, digits, `.`, `_`, `-`) travels with the message however the provider keeps and searches it: Gmail, a custom `X-Eloxiv-Client-Id` header (Gmail replaces a sender's `Message-ID`; [google](../connectors/google.md)); Graph, a custom `x-eloxiv-client-id` header and a string extended property (not yet verified against the real service; [microsoft-graph](../connectors/microsoft-graph.md)). External: a module only schedules it ([Invocation](invocation.md#external-effects)) |
|
|
27
|
+
| `listAliases` | `mail.read` | The addresses the account may send as (`address`, `name`, `isDefault`): Gmail, the primary address and the verified send-as aliases (`settings/sendAs`, verification `accepted`); Graph, the mailbox's own address (`/me`, under the connector's base scope `User.Read`), since Graph lists no send-as permissions a user holds on other mailboxes |
|
|
28
|
+
| `findSent` | `mail.read` | `{ clientId, sentAfter? }`: whether a message sent with that client id is in the mailbox (any folder), and its id (Graph: the extended property, in the sent items; Gmail: the header, read from the newest sent messages, since Gmail's search indexes no custom header). `sentAfter` (an ISO instant with its offset) is when the message cannot have been sent before, by the caller's clock; the kernel's reconciliation passes when the effect was scheduled. A connector that has to read through the sent messages stops at those older than it, allowing for the provider's clock (Gmail: a minute), so a lookup right after a send reads one or two messages; one that can search (Graph) may ignore it. How a send whose answer was lost is reconciled; `found: false` does not prove it was never sent |
|
|
29
|
+
| `createDraft` | `mail.write` | Save a draft (flag `drafts`) |
|
|
30
|
+
| `updateMessage` | `mail.write` | Mark read or unread (`isRead`), move to a folder (`folderId`), or archive (`archive: true`): out of the inbox without going anywhere else a person files mail (Graph: the Archive folder; Gmail: the `INBOX` label removed); it leaves the inbox's delta scope and is not deleted |
|
|
31
|
+
| `deleteMessage` | `mail.write` | Move to the provider's deleted items or trash; the message leaves the folder's delta scope |
|
|
32
|
+
| `listFilters` | `mail.read` | The account's own server-side filters (flag `filters`: Gmail's) |
|
|
33
|
+
| `createFilter` | `mail.settings` | `{ criteria, action }`: a filter the provider applies to incoming mail itself, at least one criterion and one label change (else `InvalidInput`, before the provider is asked). A filter that forwards is not made: forwarding sends the person's mail out of the account and needs a verified address and Gmail's sharing scope. `mail.settings` is Gmail's `gmail.settings.basic`, which the connector asks for by incremental consent only (`incremental`: connecting mail does not ask for it; the first `createFilter` without it is refused with it as the missing scope and the offer of `connections.reconnect`) |
|
|
34
|
+
| `deleteFilter` | `mail.settings` | One of the account's filters, by id (`NotFound` when it is not one) |
|
|
35
|
+
| `delta` | `mail.read` | Changes to a folder (default the inbox) since `cursor`: an upsert for each message added to or changed in it, a delete for each that left it or was deleted |
|
|
36
|
+
|
|
37
|
+
## Guarantees
|
|
38
|
+
|
|
39
|
+
The [capability guarantees](README.md#capability-contracts), and: a message keeps its id when it moves (Graph connectors ask for immutable ids); "delete" in delta means the message is no longer in the folder, whatever happened to it.
|
|
40
|
+
|
|
41
|
+
## How an implementation is checked
|
|
42
|
+
|
|
43
|
+
`mailProviderConformance(harness)` registers: folders including the inbox, the sent items and the trash; the account's own address among `listAliases`, the default, and a send as an address that is not an alias refused (`InvalidInput` or `Forbidden`); a message sent to the account's own address found in the inbox, read with its body, marked read, a draft saved (when claimed), deleted (gone from the inbox; in the trash or NotFound); a seeded message archived (out of the inbox and not in the trash, still readable); the message's `version`, when reported, moving once it is marked read; a message sent with a client id found by `findSent` (with `sentAfter` taken before the send, and without it), and an unknown client id not found (with that `sentAfter`); NotFound for an unknown id; the shared delta checks over the inbox (full sync with reset, exactly the changes since the cursor including deletes, resume after a crash compared with an uninterrupted sync, InvalidCursor and recovery); and the shared Connection checks probing `listMessages` (401 refresh-once, single-flight, failed refresh to `needs-reauth` with notification and fail-fast, 403 with missing scopes and the consent offer, 429 and 503 Retry-After and the shared cooldown, merged scopes with Calendar). Every output is checked against the contract's schema.
|
|
44
|
+
|
|
45
|
+
## Not yet guaranteed
|
|
46
|
+
|
|
47
|
+
- Attachments' content, threads as a listing, search queries, and push subscriptions (flag `pushNotifications` says the provider can; no Ingress source subscribes yet).
|
|
48
|
+
- Outlook's inbox rules (Graph's `messageRules`): Graph answers the filter operations `InvalidInput` (flag `filters: false`). The filters are proven over the Google protocol fake by the mail module ([`registry/test/mail-filters.test.ts`](../../registry/test/mail-filters.test.ts)), not by the kit.
|
|
49
|
+
- Proven against protocol fakes, not the real services, until real test accounts run the kit.
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# Memory
|
|
2
|
+
|
|
3
|
+
Durable memory entries scoped to a person or an organisation, written and removed through actions (so policy, consent, idempotency and audit apply, also when the agent calls them as tools), and given to the agent in every conversation within the memory budget. And **compaction**: a long conversation's older turns are replaced, in what later model calls are sent, by a summary that keeps their provenance.
|
|
4
|
+
|
|
5
|
+
- Kind: kernel service. Version 1.2.0 (1.2.0: a team's memory; 1.1.0: compaction in three tiers: recent raw messages, observations, reflections).
|
|
6
|
+
- Schema: [`packages/contracts/schema/contracts/Memory.json`](../../packages/contracts/schema/contracts/Memory.json) (source [`Memory.ts`](../../packages/contracts/src/contracts/Memory.ts)).
|
|
7
|
+
- Implementation: the `agent` module's `memory` records and actions ([`module.ts`](../../packages/kernel/src/agent/module.ts)); recall in [`Resources.ts`](../../packages/kernel/src/agent/Resources.ts); compaction (`compactConversation`) in [`Run.ts`](../../packages/kernel/src/agent/Run.ts).
|
|
8
|
+
- Kit: `@eloxiv/testing/conformance/Memory` ([source](../../packages/testing/src/conformance/Memory.ts)), run by [`packages/testing/test/agent-memory.test.ts`](../../packages/testing/test/agent-memory.test.ts).
|
|
9
|
+
|
|
10
|
+
## Operations
|
|
11
|
+
|
|
12
|
+
| Operation | Input | Output | Errors |
|
|
13
|
+
| --- | --- | --- | --- |
|
|
14
|
+
| `remember` | action `agent.remember`: `scope` (`user`, `team` with `team`, `org`), `key`, `content` | `id` | the standard error set (`Forbidden` for the organisation's without `eloxiv.agent.manage`, and a team's for anyone but its leads and those with it) |
|
|
15
|
+
| `forget` | action `agent.forget`: `id` | `id` | the standard error set |
|
|
16
|
+
| `recall` | none (`GET /agent/memory`) | the entries the caller may read | `Unauthenticated` |
|
|
17
|
+
| `compact` | `conversationId` (`AgentRuntime.compact` in process; automatic in runs) | `CompactionSummary` or null | `Unauthenticated`, `Forbidden` |
|
|
18
|
+
|
|
19
|
+
The agent calls `remember` and `forget` as tools (`agent_remember`, `agent_forget`), agent-originated; a person calls them on any surface. Writing a key again replaces the entry (your own, or the organisation's). Each entry records where it came from (`source`: the call's origin and invocation).
|
|
20
|
+
|
|
21
|
+
## Records
|
|
22
|
+
|
|
23
|
+
- **`MemoryEntry`**: `id`, `orgId`, `scope`, `userId` (the owner of a `user` entry; null for the organisation's), `key`, `content`, `source`.
|
|
24
|
+
- **`CompactionSummary`**: `id`, `conversationId`, `covers` (the message ids it replaced), `content`, `tokensBefore`, `tokensAfter`. Stored as a `summary` message (its `content` also says its `tier`, `observation` or `reflection`, and an observation the time it spans, `from` and `to`); the covered messages stay, with `coveredBy` set to it.
|
|
25
|
+
|
|
26
|
+
## Compaction
|
|
27
|
+
|
|
28
|
+
A conversation's memory has three tiers, as in agent-native's observational memory:
|
|
29
|
+
|
|
30
|
+
| Tier | What it is | When it is made |
|
|
31
|
+
| --- | --- | --- |
|
|
32
|
+
| **Recent raw messages** | The last `keepRecentMessages` (default 6) messages, verbatim, never folded (the kept window starts at a person's message, so no tool call is parted from its result) | always |
|
|
33
|
+
| **Observations** | Dense, dated records, each folding one stretch of older raw messages; they accumulate, one per fold | before a model call, when the conversation's messages and tool results pass the `messages` budget ([ContextAccounting](context-accounting.md)) and there is something older than the recent window |
|
|
34
|
+
| **Reflections** | The long-arc summary, condensing the observations (and an earlier reflection) | after an observation, once the observations not yet reflected pass `reflectAbove` tokens (`KernelApp.agent.reflectAbove`, default half the `messages` budget) |
|
|
35
|
+
|
|
36
|
+
Each fold is a model call of the organisation's model, with instructions to keep names, numbers, identifiers, dates, decisions, tool outcomes and anything the person asked to remember verbatim. It is metered like any model call (its worst case reserved first, [Metering](metering.md)), and written, with its covered marks and its announcement (`compacted`, with its `tier`), in one transaction, under the run's (or the person's) authority, asserted again there. Later calls are sent the reflection, then the observations after it, each as one system message saying what it is and replaces, then the recent raw messages. In a run, folds are the run's model calls: they count in its `steps`, `usage` and limits; an observation is made only when it and the call after it fit the steps left, a reflection only with one more call to spare, and each only when its worst case fits the tokens left. A budget that refuses a fold, or a run without room for it, leaves the conversation as it is (the run's own call then decides). **Provenance**: every fold lists what it covers (raw messages for an observation, observations for a reflection), which stay, marked covered by it. **Restart safety**: a fold's id is derived from the last thing it covers, so a step made again after a crash finds what it folded already and folds nothing twice (a fold's call whose answer was lost is metered as abandoned, as every model call). **Per participant**: a run folds only its own person's messages; in a shared conversation another participant's stay as they are.
|
|
37
|
+
|
|
38
|
+
## Guarantees
|
|
39
|
+
|
|
40
|
+
1. Memory changes go through the invocation path: policy-checked, audited, agent-originated when the agent makes them.
|
|
41
|
+
2. A person's entries are theirs alone: another person's agent is never given them and cannot change or remove them. Organisation entries are written by members with `eloxiv.agent.manage` and given to every member.
|
|
42
|
+
3. Compaction keeps each model call's conversation within its budget (with the recent window's margin), keeps the facts it folds in what the model is sent, and keeps provenance: each fold lists what it covers and nothing covered is deleted.
|
|
43
|
+
4. The recent raw messages are always sent verbatim; older ones are folded into observations, and observations past the threshold into a reflection; each tier covers only what the tier below it held, and a crash never folds the same thing twice.
|
|
44
|
+
|
|
45
|
+
## How an implementation is checked
|
|
46
|
+
|
|
47
|
+
`memoryConformance(start)`, with a subject whose `messages` budget is 900 tokens and `keepRecentMessages` 2 (`MEMORY_SUBJECT_SETTINGS`): the agent remembers through a tool (audited on the `agent` surface) and a new conversation is given the entry; another person's agent never sees it, cannot forget it, and writing the same key writes its own; organisation memory only for administrators, given to every member; a conversation of eight turns with a fact in its first is compacted, every call stays within budget, a later question is answered from the summary, and the summary covers the kept messages. With a real model ([`registry/test/agent-real-model.test.ts`](../../registry/test/agent-real-model.test.ts)): asked to remember a fact, the model calls `agent_remember` itself (audited on the `agent` surface), a new conversation answers from the memory, and another person's agent is not given it.
|
|
48
|
+
|
|
49
|
+
## Not yet guaranteed
|
|
50
|
+
|
|
51
|
+
- Folds are as good as the organisation's model, and they are made before a call, not in the background after a turn.
|
|
52
|
+
- Memory recall is everything readable, newest first, cut by the memory budget: no relevance ranking or search.
|
|
53
|
+
- Compaction happens before a call, not in the background after a turn.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Messaging
|
|
2
|
+
|
|
3
|
+
A chat platform (Slack, Teams) as a channel to and from the app: sending over a kernel [Connection](connections.md) (the workspace's grant), receiving through [Ingress](ingress.md), whose verified deliveries a connector parses into messages and whose linked identities map a platform user to an actor. An unlinked sender never acts.
|
|
4
|
+
|
|
5
|
+
- Kind: capability. Version 1.1.0 (1.1.0 marks `sendMessage` external: a module schedules it, after commit).
|
|
6
|
+
- Schema: [`packages/contracts/schema/contracts/Messaging.json`](../../packages/contracts/schema/contracts/Messaging.json) (source [`Messaging.ts`](../../packages/contracts/src/contracts/Messaging.ts)).
|
|
7
|
+
- Implementations: the [`slack`](../connectors/slack.md) registry connector ([`registry/app/connectors/slack`](../../registry/app/connectors/slack)). The kit also runs against the reference `acme` connector ([`conformance/acme/connector.ts`](../../packages/testing/src/conformance/acme/connector.ts)) over the acme protocol fake.
|
|
8
|
+
- Kit: `@eloxiv/testing/conformance/Messaging` ([source](../../packages/testing/src/conformance/Messaging.ts)), run by [`packages/testing/test/messaging.test.ts`](../../packages/testing/test/messaging.test.ts) (acme), [`registry/test/connector-slack.test.ts`](../../registry/test/connector-slack.test.ts) (Slack over the Slack protocol fake) and [`registry/test/connector-slack-live.test.ts`](../../registry/test/connector-slack-live.test.ts) (a real Slack workspace, when configured).
|
|
9
|
+
|
|
10
|
+
Shared parts: [Capability contracts](README.md#capability-contracts).
|
|
11
|
+
|
|
12
|
+
## Records
|
|
13
|
+
|
|
14
|
+
- `MessagingChannel`: `id`, `name`, `kind` (`channel`, `private`, `direct`, `group`), `isMember`.
|
|
15
|
+
- `ChannelIdentity`: `platform`, `externalId` (the id Ingress links; for Slack `<team>:<user>`), `name`.
|
|
16
|
+
- `PlatformMessage`: `id`, `channelId`, `threadId` (the thread's root message, or null), `sender`, `text`, `sentAt`.
|
|
17
|
+
- `InboundDelivery`: what Ingress hands a handler: `source`, `deliveryId`, `body`, `headers`.
|
|
18
|
+
- `MessagingFlags`: `threads`, `directMessages`, `editing`, `reactions`.
|
|
19
|
+
|
|
20
|
+
## Operations
|
|
21
|
+
|
|
22
|
+
| Operation | Scopes | What |
|
|
23
|
+
| --- | --- | --- |
|
|
24
|
+
| `listChannels` | `messaging.read` | Channels and conversations the Connection sees |
|
|
25
|
+
| `sendMessage` | `messaging.write` | Post to a channel, or reply in a thread (`threadId`) |
|
|
26
|
+
| `listMessages` | `messaging.read` | A channel's messages, or a thread's (root first). Each page is oldest first; a channel's pages may walk back from its most recent messages (Slack's history has no forward order), so the next page holds older messages. A channel's messages leave thread replies in their thread |
|
|
27
|
+
| `receive` | none | Parse a verified Ingress delivery into a message, or null (URL verification, the app's own posts, unsupported events). Pure: no Connection |
|
|
28
|
+
|
|
29
|
+
## Receiving
|
|
30
|
+
|
|
31
|
+
A module declares an Ingress source for the platform whose identity mapping is the connector's `receive`: the sender's `externalId` is the platform identity, a `link <code>` message completes a link ([Ingress](ingress.md#linked-identities)), and the handler action runs as the linked actor through the invocation path (surface `ingress`). The reference wiring is the [`chatlog`](../../packages/testing/src/conformance/acme/chatlog.ts) fixture module.
|
|
32
|
+
|
|
33
|
+
## How an implementation is checked
|
|
34
|
+
|
|
35
|
+
`messagingConformance(subject)` registers, in the channel the subject names: the channel listed with the app as a member, a message posted, a reply in its thread, the thread read back in order, and the channel's messages including the root but not the reply; NotFound for an unknown channel; a delivery parsed into a message naming its sender's platform identity, and a URL verification parsed into null; a person linking their platform identity with a one-time code sent from the platform, then their reply in a thread the app started recorded by their actor through Ingress, while an unlinked sender's message, the link message and the app's own post are recorded by nobody. The subject delivers a platform user's message the way the platform does: a signed POST (acme), the Slack protocol fake's Events API delivery, or the test user posting in a real workspace.
|
|
36
|
+
|
|
37
|
+
## Not yet guaranteed
|
|
38
|
+
|
|
39
|
+
- **One real workspace**: the Slack connector passes the kit against the Slack protocol fake and against one real workspace (the live run, 2026-11-09; [docs/connectors/slack.md](../connectors/slack.md)), not Enterprise Grid or Slack Connect partners for real. No Teams connector.
|
|
40
|
+
- Editing, reactions, files, rich blocks, and proactive replies by the agent.
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# Metering
|
|
2
|
+
|
|
3
|
+
Quotas, budgets and rate limits, in two parts: the agent's **token and cost budgets per person and organisation**, reserved before every model call and settled after it, so concurrent calls never pass a hard budget; and **per-connection backpressure** on every provider request a connector makes over a Connection (a slot per process, a cooldown from Retry-After shared by every process, an optional quota per window).
|
|
4
|
+
|
|
5
|
+
- Kind: kernel service. Version 1.3.0 (1.0.0 had the agent budgets only; 1.1.0 added the per-connection part; 1.2.0 storage quotas; 1.3.0 alert thresholds, usage insights and run drilldown).
|
|
6
|
+
- Schema: [`packages/contracts/schema/contracts/Metering.json`](../../packages/contracts/schema/contracts/Metering.json) (source [`Metering.ts`](../../packages/contracts/src/contracts/Metering.ts)).
|
|
7
|
+
- Implementation: two kernel services over their own state. Agent budgets: [`packages/kernel/src/agent/Metering.ts`](../../packages/kernel/src/agent/Metering.ts) (`Metering`); budgets and usage are the `agent` module's records. Per connection: [`packages/kernel/src/connections/Metering.ts`](../../packages/kernel/src/connections/Metering.ts) (`ConnectionMetering`); tables `eloxiv.connection_cooldown`, `eloxiv.connection_usage` (kernel migration `0022_connections`).
|
|
8
|
+
- Kit: `@eloxiv/testing/conformance/Metering` ([source](../../packages/testing/src/conformance/Metering.ts)), `meteringConformance({ agent, connections })`, each part on its own subject: run by [`packages/testing/test/agent-metering.test.ts`](../../packages/testing/test/agent-metering.test.ts) (agent budgets) and [`packages/testing/test/metering.test.ts`](../../packages/testing/test/metering.test.ts) (per connection, against the reference acme connector over the acme protocol fake).
|
|
9
|
+
|
|
10
|
+
## Agent budgets
|
|
11
|
+
|
|
12
|
+
### Operations
|
|
13
|
+
|
|
14
|
+
| Operation | Input | Output | Errors |
|
|
15
|
+
| --- | --- | --- | --- |
|
|
16
|
+
| `check` | `orgId`, `userId`, `amounts` per meter (counting what calls in progress hold) | nothing | `BudgetExceeded` |
|
|
17
|
+
| `reserve` | `orgId`, `userId`, `runId`, `kind` (`run`, `compaction`, `completion`), `inputTokens`, `maxOutputTokens` | the started call's `id` | `BudgetExceeded` |
|
|
18
|
+
| `settle` | the call's `id`, its `inputTokens` and `outputTokens` | nothing | none |
|
|
19
|
+
| `release` | the call's `id` | nothing | none |
|
|
20
|
+
| `record` | `UsageRecord`: `orgId`, `userId`, `runId`, `provider`, `model`, `inputTokens`, `outputTokens`, `costMicros` | nothing | none |
|
|
21
|
+
| `usage` | `scope` (`user`, `org`), `period` (`GET /agent/usage?scope=&period=`) | usage per meter | `Unauthenticated`, `Forbidden` (organisation usage needs `eloxiv.agent.manage`) |
|
|
22
|
+
| `setBudget` | action `agent.setBudget`: `scope`, optional `userId`, `meter`, `period`, `limit` (null clears), optional `alertAt` (1 to 100 percent of the limit; null clears, absent keeps) | `id` | the standard error set |
|
|
23
|
+
| `budgets` | none (`GET /agent/budgets`) | the budgets that apply to the caller, with their `alertAt` | `Unauthenticated` |
|
|
24
|
+
| `insights` | `scope`, `period`, `by` (`model`, `day`, `run`, `member`) (`GET /agent/usage/insights?scope=&period=&by=`) | `UsageInsights`: per group (`key`: `provider:model`, the UTC date, the run id, the member's id) its metered calls, input and output tokens and cost, largest cost first, at most 100 | `Unauthenticated`, `Forbidden` (organisation scope needs `eloxiv.agent.manage`), `InvalidInput` (`by: member` is the organisation's only) |
|
|
25
|
+
| `runUsage` | a run's id (`GET /agent/runs/<id>/usage`) | `RunUsage`: its metered calls in order (`step`, `kind`, provider, model, tokens, cost, `estimated`, `at`) and their totals | `Unauthenticated`, the run's own refusal for anyone but its owner |
|
|
26
|
+
| `alert` | in process, after every metered call: `orgId`, `userId` | nothing | none (best effort; a failure is logged) |
|
|
27
|
+
|
|
28
|
+
The client SDK reads these as `agentClient(...).usage()`, `.insights({ by })`, `.runUsage(runId)` and `.budgets()`.
|
|
29
|
+
|
|
30
|
+
A run on a paired device ([Daemon](daemon.md#integrating-with-the-agent-runtime)) records its turn's usage with provider `device:<harness>` (once per turn): it is the person's own subscription, so no budget counts it.
|
|
31
|
+
|
|
32
|
+
Meters: `agent.tokens` (input plus output tokens) and `agent.cost` (millionths of the currency unit, from the provider's pricing per million tokens). Periods: the current UTC `day`, the current UTC `month`, or `total`.
|
|
33
|
+
|
|
34
|
+
### Which budgets apply
|
|
35
|
+
|
|
36
|
+
To a call by a person in an organisation: the organisation's (`scope: org`, all of the organisation's usage), and the person's own (`scope: user`, `userId` = them) or, without one, the default for every member (`scope: user` without `userId`). Only members with `eloxiv.agent.manage` set budgets.
|
|
37
|
+
|
|
38
|
+
### When it is enforced
|
|
39
|
+
|
|
40
|
+
Every model call (a run's, a compaction's, a one-shot completion's) goes through three moves:
|
|
41
|
+
|
|
42
|
+
1. **Reserve, before the call.** In one transaction: the budget rows that apply are locked (`FOR UPDATE`, in id order), and the call is admitted only if, for each, the usage recorded in its period, plus what calls in progress have reserved, plus this call's **worst case** fits the limit. The worst case is the call's counted input (its assembled context, as [ContextAccounting](context-accounting.md) counts it) plus `maxOutputTokens` (`KernelApp.agent.maxOutputTokens`, default 8,192, which the call is sent as its limit), and their cost. The call is recorded as `started` (`eloxiv_agent.model_call`) with that reservation in the same transaction. Concurrent callers queue on the budget row's lock and each sees the others' reservations, so together they never pass a hard budget. A refused run stops (`stopped`, `stopReason: budget`) with a message naming the budget, its limit, what was used or held and what the call needed; a refused completion fails with `BudgetExceeded` (HTTP 429).
|
|
43
|
+
2. **Settle, after it.** Its usage record, from what the provider reported, with its cost, and the call `settled`, in one transaction (for a run, the same one that stores its response). The reservation is replaced by the actual usage, which is at most the reservation's output.
|
|
44
|
+
3. **Release, if it failed.** The reservation is dropped (`released`); nothing is recorded.
|
|
45
|
+
|
|
46
|
+
**A call whose answer was lost** (the process died between the provider's answer and the settle) stays `started`, holding its reservation. It is then `abandoned` and its usage recorded at what it reserved, marked `estimated`: by its run's step, which runs again and calls the model again ([AgentRuntime](agent-runtime.md)), or, for a call outside a run, once it has been open for `modelCallTimeoutMs` (default 10 minutes, after which a call is cut off) plus five minutes. A lost call is therefore never unmetered, and never counted twice (one usage record per call).
|
|
47
|
+
|
|
48
|
+
### Alerts
|
|
49
|
+
|
|
50
|
+
A budget may carry a **soft threshold**, `alertAt`, in percent of its limit (agent module migration `0004_budget_alert`). After every metered call (a run's model step, a compaction, a one-shot completion), each budget that applies to the person and has one is compared with its usage in its period (what is used, plus what calls in progress hold, as the hard check counts it); when it has reached the threshold, its people get a notification ([Notifications](notifications.md), category `agent.budget`: in-app, and by email where their preferences include it): a member's own budget, or the members' default, notifies that member; the organisation's budget notifies every member who manages the agent (`eloxiv.agent.manage`). **Once per budget, person (or organisation) and period**: the notification's idempotency key names the budget, whom it concerns and the UTC day, month or `total`, so further calls in the period do not repeat it and the next period alerts again. The hard limit is unchanged by the threshold.
|
|
51
|
+
|
|
52
|
+
### Records
|
|
53
|
+
|
|
54
|
+
- **`Budget`**: `id`, `orgId`, `scope`, `userId` (null for the organisation's or the members' default), `meter`, `period`, `limit`.
|
|
55
|
+
- **`UsageRecord`** as above; one per model call (stored with the call's id and `estimated`, true for a lost call recorded at its reservation).
|
|
56
|
+
- **`ModelCall`** (`eloxiv_agent.model_call`, readable by its owner and administrators): `runId`, `step`, `kind`, `provider`, `model`, the reservation (`reservedInputTokens`, `reservedOutputTokens`, `reservedCostMicros`), `status` (`started`, `settled`, `released`, `abandoned`), `startedAt`, `finishedAt`.
|
|
57
|
+
- **`BudgetExceeded`**: `scope`, `meter`, `limit`, `used`, `requested`, `message`.
|
|
58
|
+
|
|
59
|
+
### Guarantees
|
|
60
|
+
|
|
61
|
+
1. No model call is made that would pass an applicable budget, counting what concurrent calls hold: calls made at the same time never pass a hard budget together (as far as the counted input matches the provider's own count, see below).
|
|
62
|
+
2. Every model call's usage and cost are recorded once, against the person, the organisation and the run; a call whose answer was lost is recorded at its worst case.
|
|
63
|
+
3. Only administrators set budgets; a person's own budget replaces the members' default; organisation usage is for administrators.
|
|
64
|
+
4. A budget's alert threshold notifies its people (the member, or the organisation's managers, and no one else) once per period when its usage reaches it; insights and run drilldowns show a person only their own usage, and the organisation's (by member) only to its managers. ([`agent-usage-insights.test.ts`](../../packages/testing/test/agent-usage-insights.test.ts))
|
|
65
|
+
|
|
66
|
+
### How an implementation is checked
|
|
67
|
+
|
|
68
|
+
`meteringConformance({ agent })`: a run's usage rows equal its steps and its tokens and cost (from the scripted model's pricing); a member cannot set a budget; with Ben's daily token budget almost spent his next run stops before the model is called (no call reaches the model, nothing recorded) and a completion is refused with `BudgetExceeded`, while Ada is unaffected; an organisation cost budget of 0 stops everyone until cleared; organisation usage only for administrators.
|
|
69
|
+
|
|
70
|
+
### Not yet guaranteed
|
|
71
|
+
|
|
72
|
+
- The input of the worst case is the kernel's count (`ceil(characters / 4)` per part); a provider whose own count is higher can take usage past a budget by the difference. Output is bounded by `maxOutputTokens`, which the provider enforces.
|
|
73
|
+
- The kernel's own stress test: [`agent-concurrency.test.ts`](../../packages/testing/test/agent-concurrency.test.ts) (ten concurrent completions and six concurrent runs against an organisation budget; a failed call's reservation released).
|
|
74
|
+
- Rate limits and quotas on other resources.
|
|
75
|
+
- An alert is checked after each metered call, so it arrives with the call that reached the threshold; usage recorded without a model call (`record`) is checked at the person's next call.
|
|
76
|
+
|
|
77
|
+
## Per connection
|
|
78
|
+
|
|
79
|
+
Ported from agent-native's provider quota governor (ledger A-158: per-credential serialisation, shared cooldowns, Retry-After, named quota-exhausted results), with the cooldown and quota state in the kernel's database rather than an optional store.
|
|
80
|
+
|
|
81
|
+
### Limits per connection
|
|
82
|
+
|
|
83
|
+
`ConnectionLimits`, a connector's defaults (`defineConnector({ limits })`) over the kernel's (`defaultConnectionLimits`):
|
|
84
|
+
|
|
85
|
+
| Field | Default | Meaning |
|
|
86
|
+
| --- | --- | --- |
|
|
87
|
+
| `maxConcurrent` | 4 | Requests of one Connection in flight at once in one process; 1 serialises them. Microsoft Graph and Google use 4 (Outlook's documented per-mailbox limit) |
|
|
88
|
+
| `maxAttempts` | 3 | Attempts of one request through 429 and 503 answers |
|
|
89
|
+
| `maxWaitMs` | 30 000 | The longest a request waits for a cooldown or a quota window before failing with `RateLimited` |
|
|
90
|
+
| `quota` | none | `{ requests, windowS }`: requests per fixed window, counted across processes. Windows are aligned to the Unix epoch (an hour's window starts on the hour), so up to twice `requests` can pass in the moments around a window's end |
|
|
91
|
+
|
|
92
|
+
### Operations
|
|
93
|
+
|
|
94
|
+
| Operation | What |
|
|
95
|
+
| --- | --- |
|
|
96
|
+
| `admit` | Before each request: a slot of the Connection's semaphore (per process), then its shared cooldown (wait if it ends within the deadline, else `RateLimited` reason `cooldown` without calling the provider; after every wait the cooldown is read again, so one extended meanwhile by another caller or process is waited out too, or fails the request if it now ends after the deadline), then its quota (count the request in the current window; when spent, wait for the next window if it starts within the deadline, else `RateLimited` reason `quota`), then the cooldown once more (one set while it waited for the quota) |
|
|
97
|
+
| `backoff` | After a 429 or 503 (or a connector's rate-limit classification): the cooldown becomes now plus `Retry-After` (delta seconds or an HTTP date) or, without one, 1 s, 2 s, 4 s, ... capped at 30 s; it is stored with the status and never shortened by a later, shorter one |
|
|
98
|
+
| `cooldown` | The Connection's current cooldown (until, status, reason) |
|
|
99
|
+
| `connectionUsage` | The Connection's count in the current quota window |
|
|
100
|
+
|
|
101
|
+
The Connections request loop calls `admit`, sends, and on 429/503 calls `backoff` and tries again; after `maxAttempts` the request fails with `RateLimited` (reason `max-attempts`, or `Unavailable` for a 503), naming when to retry.
|
|
102
|
+
|
|
103
|
+
### Guarantees
|
|
104
|
+
|
|
105
|
+
1. No more than `maxConcurrent` requests of a Connection are in flight in a process.
|
|
106
|
+
2. A provider's Retry-After (429 and 503, seconds or HTTP date) is honoured before the next request of the Connection, by every process: the cooldown is in the database.
|
|
107
|
+
3. A request never waits past `maxWaitMs`; beyond it, it fails with `RateLimited` and `retryAfterMs`/`retryAt`, without calling the provider.
|
|
108
|
+
4. A quota is counted across processes; a spent quota refuses requests without calling the provider.
|
|
109
|
+
|
|
110
|
+
### How an implementation is checked
|
|
111
|
+
|
|
112
|
+
`meteringConformance({ connections })` registers, against kernels started with the limits each check needs: at most one request in flight with `maxConcurrent: 1` and exactly two with `maxConcurrent: 2` (the fake measures concurrency with slowed answers); a 429 with `Retry-After: 1` and a 503 with an HTTP date waited out; a run of 429s stopped after three attempts with `RateLimited` (`max-attempts`) and exactly three requests; a 429 with `Retry-After: 60` failing at once, and a second kernel on the same database refused with `RateLimited` (`cooldown`) in under two seconds with no request reaching the provider; a cooldown ending within the budget waited out; a quota of three counted across two kernels in one window (one that ends a day after the kit starts, so no run crosses a window's end), the fourth and fifth refused (`quota`) on both without a request.
|
|
113
|
+
|
|
114
|
+
### Not yet guaranteed
|
|
115
|
+
|
|
116
|
+
- **Concurrency limits are per process**; across processes only cooldowns and quotas are shared.
|
|
117
|
+
- **In-flight deduplication** of identical GETs (upstream's request keys) is not done.
|
|
118
|
+
- **Per-source rate limits for Ingress** are not part of this version.
|
|
119
|
+
|
|
120
|
+
## Storage quotas
|
|
121
|
+
|
|
122
|
+
Each organisation's stored bytes (the [Files](files.md) contract) are held to its quota: the one an administrator with `eloxiv.files.manage` set (`files.setQuota`), else the deployment's default (`files.defaultQuotaBytes`, none by default). Served by the `Files` service ([`files/Files.ts`](../../packages/kernel/src/files/Files.ts)); quotas are kept in `eloxiv.storage_quota`.
|
|
123
|
+
|
|
124
|
+
### Operations
|
|
125
|
+
|
|
126
|
+
| Operation | What it does |
|
|
127
|
+
| --- | --- |
|
|
128
|
+
| `reserveStorage` | In process (`Files.reserve`, in the caller's transaction): admit `bytes` more only if every file not deleted (uploads in progress included, reserved when they begin) plus these bytes fit the quota, else `StorageQuotaExceeded` (on surfaces, `Forbidden` naming the quota and what is used). Taken under a transaction lock on the organisation, so concurrent reservations queue and each sees the others' |
|
|
129
|
+
| `storageUsage` | The organisation's used bytes and quota (action `files.usage`) |
|
|
130
|
+
| `setStorageQuota` | Set or clear (null) the organisation's quota (action `files.setQuota`) |
|
|
131
|
+
|
|
132
|
+
### Guarantees
|
|
133
|
+
|
|
134
|
+
1. Concurrent uploads never pass the quota together; a deleted or abandoned file's bytes stop counting at once.
|
|
135
|
+
2. One organisation's quota never limits another's.
|
|
136
|
+
|
|
137
|
+
### How an implementation is checked
|
|
138
|
+
|
|
139
|
+
The Files kit's "holds each organisation to its storage quota, also when uploads race" ([`Files.ts`](../../packages/testing/src/conformance/Files.ts)): eight concurrent uploads against room for three admit exactly three; another organisation's upload is unaffected.
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# ModelProvider
|
|
2
|
+
|
|
3
|
+
Language models behind one provider-neutral interface, over the Vercel AI SDK: text and structured generation, tool calls, streaming and token usage. Providers are configured per deployment and per organisation; credentials stay behind the provider's credential source. Real providers (Anthropic, OpenAI, a gateway, a local model) are **registry connectors**: the kernel knows none of them.
|
|
4
|
+
|
|
5
|
+
- Kind: capability contract. Version 1.2.0 (1.1.0: `ModelUnavailable` carries a `reason`; 1.2.0: `embed`, a provider's optional `embeddingModel`).
|
|
6
|
+
- Schema: [`packages/contracts/schema/contracts/ModelProvider.json`](../../packages/contracts/schema/contracts/ModelProvider.json) (source [`ModelProvider.ts`](../../packages/contracts/src/contracts/ModelProvider.ts)).
|
|
7
|
+
- Implementation: [`packages/kernel/src/agent/Models.ts`](../../packages/kernel/src/agent/Models.ts) (`ModelProviders`, `ModelProviderImpl`, `ModelCredentials`); the scripted provider in [`packages/testing/src/Agent.ts`](../../packages/testing/src/Agent.ts).
|
|
8
|
+
- Kit: `@eloxiv/testing/conformance/ModelProvider` ([source](../../packages/testing/src/conformance/ModelProvider.ts)), run by [`packages/testing/test/model-provider.test.ts`](../../packages/testing/test/model-provider.test.ts) (the scripted provider) and by [`registry/test/agent-real-model.test.ts`](../../registry/test/agent-real-model.test.ts) (the registry's `openai` connector against OpenAI's API).
|
|
9
|
+
- A real provider: the registry's [`openai` connector](../connectors/openai.md) (`@ai-sdk/openai`; OpenAI or any OpenAI-compatible endpoint).
|
|
10
|
+
|
|
11
|
+
## A provider
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
interface ModelProviderImpl {
|
|
15
|
+
readonly id: string // unique in the deployment: "anthropic", "gateway", "scripted"
|
|
16
|
+
readonly models: ReadonlyArray<{ id: string; pricing?: { inputPerMillionMicros: number; outputPerMillionMicros: number } }>
|
|
17
|
+
readonly languageModel: (model: string, credentials: Record<string, Redacted>) => LanguageModel // an AI SDK model
|
|
18
|
+
readonly embeddingModel?: (model: string, credentials: Record<string, Redacted>) => EmbeddingModel // optional
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`embeddingModel`, when a provider has one, builds the AI SDK embedding model for those of its `models` that embed; hybrid search ([Search](search.md#hybrid-search)) uses it.
|
|
23
|
+
|
|
24
|
+
`languageModel` may throw when it cannot build a model it could call (the `openai` connector throws when the organisation has no `api_key`, rather than letting the SDK fall back to `OPENAI_API_KEY`): the call then fails with `ModelUnavailable` (reason `unavailable`), and a run ends `failed` (`model-error`), never with a kernel defect.
|
|
25
|
+
|
|
26
|
+
**Errors clients see.** A provider's error text can echo keys or configuration, so none of it reaches a client. A provider's failure, building the model or calling it, is a `ModelUnavailable` with a `reason` and a fixed message ending in a reference: `unavailable` (not configured for the organisation, or the provider failed), `rate-limited` (HTTP 429), `refused` (401 or 403: credentials or access), `timeout` (408, 504, or the kernel's own `modelCallTimeoutMs`), `invalid-request` (another 4xx). The kernel logs the detail (the error's message and the provider's response body) under the reference, as a warning, with the call's credential values and anything that looks like a secret (`sk-…` keys, bearer tokens, `key=value` pairs naming a key, token, secret or password, URL user information) replaced by `[redacted]`. The same error is what `complete` answers, what a run stores as its `error` and what its events carry. Failures the kernel decides itself (no such provider or model, none configured) keep their own words, which name no secret.
|
|
27
|
+
|
|
28
|
+
A connector returns one; the app lists it in `KernelApp.agent.providers`. Credentials come from `KernelApp.agent.credentials` (a `ModelCredentials`: `resolve({ provider, orgId })`), by default from `ELOXIV_MODEL_<PROVIDER>_<NAME>` environment variables. The Secrets contract will implement `ModelCredentials` per organisation; a provider never reads secrets itself.
|
|
29
|
+
|
|
30
|
+
## Operations
|
|
31
|
+
|
|
32
|
+
| Operation | Input | Output | Errors |
|
|
33
|
+
| --- | --- | --- | --- |
|
|
34
|
+
| `models` | `provider` | the models with their pricing | `ModelUnavailable` |
|
|
35
|
+
| `generateText` | `model` (`provider`, `model`), `messages`, optional `tools`, `maxOutputTokens` | `text`, `toolCalls`, `finishReason`, `usage` | `ModelUnavailable` |
|
|
36
|
+
| `generateObject` | `model`, `messages`, `schema` (JSON Schema) | `object`, `usage` | `ModelUnavailable` |
|
|
37
|
+
| `streamText` | as `generateText` | text deltas as they arrive, then the result | `ModelUnavailable` |
|
|
38
|
+
| `embed` | `orgId`, `model`, `values` (texts) | `embeddings` (one vector per text, in order), `tokens` | `ModelUnavailable` (also for a provider with no `embeddingModel`) |
|
|
39
|
+
| `resolve` | `orgId` | the organisation's `ModelChoice` | `ModelUnavailable` |
|
|
40
|
+
|
|
41
|
+
Tools are never executed by the provider or the SDK: the agent runtime executes them as journalled steps through the invocation path. In the kernel, `ModelProviders.generate` uses the provider's streaming API when given an `onDelta`, and `generateText` otherwise.
|
|
42
|
+
|
|
43
|
+
**Resolution.** An organisation's model is its administrator's choice (action `agent.configureModel`, `eloxiv.agent.manage`), else the deployment's default: `ELOXIV_AGENT_MODEL=<provider>:<model>`, then `KernelApp.agent.defaultModel`, then the first provider's first model. A choice naming a provider or model the deployment does not offer fails the call with `ModelUnavailable` (a run ends `failed`, `model-error`).
|
|
44
|
+
|
|
45
|
+
## Model setup
|
|
46
|
+
|
|
47
|
+
Keys, policy and choices, through kernel routes for a signed-in person's own session (`packages/kernel/src/agent/ModelSetup.ts`; agent sessions and machine credentials are refused, so no agent changes the models it runs on). A key's values never pass through an action.
|
|
48
|
+
|
|
49
|
+
| Route | What |
|
|
50
|
+
| --- | --- |
|
|
51
|
+
| `GET /agent/models` | The catalogue: each provider's models with whether the organisation allows them, where credentials exist for the caller (`user`, `org`, `deployment`), whether the provider can check a key, the policy, and the caller's, the organisation's and the effective choice with its `source` |
|
|
52
|
+
| `POST /agent/models/keys` | `{ provider, scope: "user" \| "org", values, check?, setDefault? }`: the values (`api_key`, `base_url`, ...) become secrets `model.<provider>.<name>` of that scope, managed by `agent.models` (the generic Secrets management cannot replace or delete them). Checked first (`check: false` skips it): nothing is saved unless the provider accepts the key, and the answer tells `refused` (401, 403) from `unreachable` (no answer it could judge). An organisation key needs `eloxiv.agent.manage`; a personal one, the organisation's policy allowing personal keys. `setDefault` (organisation scope) makes one of the models the key reaches the organisation's model (`agent.configureModel`, through the invocation path as the person) |
|
|
53
|
+
| `POST /agent/models/keys/remove` | `{ provider, scope }` |
|
|
54
|
+
| `POST /agent/models/check` | `{ provider, scope? }`: a check of the stored credentials at one scope, or of those a call would use |
|
|
55
|
+
| `POST /agent/models/choose` | `{ provider, model }` or `{ clear: true }`: the caller's own model, allowed by the policy and reached by the credentials that would serve them (checked when the provider can list its models; `checked_at` records it) |
|
|
56
|
+
| `POST /agent/models/policy` | `{ personalKeys, allowedModels }` (`eloxiv.agent.manage`): whether members may use keys of their own, and the `provider:model` ids they may choose (null: any the deployment offers) |
|
|
57
|
+
|
|
58
|
+
**The model-key namespace is reserved**: the generic Secrets management can neither create nor change a secret named `model.…` ([Secrets](secrets.md)), and a call is served only by fields model setup itself saved (managed by `agent.models`), so no one can plant a `base_url` beside the organisation's key. **A stored key's own endpoint** (`base_url`) must pass the Connections' [outbound destination policy](connections.md#destinations): when the key is saved (before its check), and before every check and call made with it, which go through the kernel's guarded fetch (each request and redirect checked; a provider must use the `fetch` it is handed). The deployment's own credentials (`KernelApp.agent.credentials`) are the operator's and are not checked. **Saving a key** re-checks, once the provider has answered, that the person is still signed in, a member and allowed, and commits the key's secrets and audit record in one transaction that holds their session.
|
|
59
|
+
|
|
60
|
+
**Which credentials serve a call** (`ModelProviders.credentialsFor`): the person's own keys while the organisation allows personal keys (turning them off ignores the stored ones at once), else the organisation's, else the app's `KernelApp.agent.credentials` (the deployment's, from the environment by default). **Which model** (`resolveFor`): the person's choice while the policy allows it and the deployment offers it, else the organisation's, else the deployment's default. Agent runs and `complete` resolve both for the person they serve.
|
|
61
|
+
|
|
62
|
+
**A key check** (`ModelProviderImpl.listModels`, optional): a provider lists the model ids credentials reach, throwing as the AI SDK does; the kernel keeps the ids the deployment offers, reports `refused`, `unreachable`, `missing` or `unsupported`, and logs the provider's text only redacted, under a reference. Tables `eloxiv.model_policy` and `eloxiv.model_choice` (kernel migration `0061_model_setup`). A reasoning effort is the connector's per-model configuration ([openai](../connectors/openai.md)), not the kernel's.
|
|
63
|
+
|
|
64
|
+
## Guarantees
|
|
65
|
+
|
|
66
|
+
1. Text, tool calls (returned, not executed), streamed text whose deltas make up the final text, and objects matching a JSON Schema, each with token usage.
|
|
67
|
+
2. A provider receives only the credentials resolved for the organisation making the call, and nothing a provider says in an error reaches a client: clients see a typed reason, a fixed message and a reference.
|
|
68
|
+
3. An organisation's model is its administrator's choice or the deployment's default; an unknown provider fails clearly.
|
|
69
|
+
|
|
70
|
+
## How an implementation is checked
|
|
71
|
+
|
|
72
|
+
`modelProviderConformance({ provider, model, credentials?, subject? })`: the provider offers the model; text with usage; one tool call returned unexecuted; streamed deltas that make up the text; an object matching a JSON Schema. Its prompts (`MODEL_PROVIDER_PROMPTS`) are explicit, so a real model passes them as the scripted one does. With an agent `subject`, the kernel's resolution: the deployment's default, an administrator's (and only an administrator's) choice, and a clear failure for an unknown provider, on a run and on `complete`.
|
|
73
|
+
|
|
74
|
+
`registry/test/model-openai.test.ts` checks the errors against an OpenAI-compatible fake whose error bodies echo the key and a configuration secret, and a provider whose model cannot be built: the reason for each (401, 400, 429, a constructor failure), and no canary in `complete`'s answer, the run, its events, its messages, the organisation's audit records or the kernel's output.
|
|
75
|
+
|
|
76
|
+
To check a real provider, run the kit with its connector, as `registry/test/agent-real-model.test.ts` does for `openai`: `modelProviderConformance({ provider: () => openaiProvider(), model: "gpt-5-mini", credentials: { api_key: process.env.ELOXIV_MODEL_OPENAI_API_KEY } })`. That file then runs the agent runtime on the real model (see [AgentRuntime](agent-runtime.md#a-real-model)).
|
|
77
|
+
|
|
78
|
+
## Not yet guaranteed
|
|
79
|
+
|
|
80
|
+
- The real-provider checks run only where a key is configured: locally, and in the `model live` workflow (`.github/workflows/model-live.yml`, on pushes to main and build/** only, never on pull requests), which reads the repository secret `ELOXIV_MODEL_OPENAI_API_KEY`. Without a key, `registry/test/model-openai.test.ts` checks the connector against an OpenAI-compatible fake.
|
|
81
|
+
- Provider backpressure (Retry-After, cooldowns per credential) belongs to Metering's per-connection meters, later.
|
|
82
|
+
- Speech, images and model catalogues with personal keys are not covered. Embeddings are proven with a deterministic fake embedding model ([`Embedder.ts`](../../packages/testing/src/Embedder.ts), [`search-hybrid.test.ts`](../../packages/testing/test/search-hybrid.test.ts)); the registry's `openai` connector does not offer one yet.
|
|
83
|
+
- Speech, images and embeddings (service providers beyond language models) are not covered.
|
|
84
|
+
- **The openai connector does not list its models yet** (`listModels`), so its keys are saved unchecked (`unsupported`) until it does; the kernel side is proven with a stand-in provider ([`model-setup.test.ts`](../../packages/testing/test/model-setup.test.ts)).
|