@eloxiv/cli 0.0.0-stage → 0.1.1
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 +110 -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 +50 -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 +35 -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,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)).
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
# ModuleManifest
|
|
2
|
+
|
|
3
|
+
Kind: kernel service. Version 1.6.0 (1.1.0: entities publish their storage, sync, unique keys and relationships; 1.2.0: actions publish their optimistic effect; 1.3.0: entities publish their collaborative documents, `collab`; 1.4.0: actions publish `consentEachCall` and the capability operations they declare, `connections`; 1.5.0: actions publish `exposure` when a surface does not offer them; 1.6.0: actions publish `title`, what people see them called (one line, at most 80 characters), and an optimistic effect may be `custom`, the module's own prediction). Schema: [`packages/contracts/schema/contracts/ModuleManifest.json`](../../packages/contracts/schema/contracts/ModuleManifest.json). Source: [`packages/contracts/src/Module.ts`](../../packages/contracts/src/Module.ts), [`Manifest.ts`](../../packages/contracts/src/Manifest.ts), [`contracts/ModuleManifest.ts`](../../packages/contracts/src/contracts/ModuleManifest.ts).
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
A module manifest is the declarative description of a module: what it stores, what it lets callers do, what it emits, and how it plugs into the rest of an app. It is data, written as Effect Schema in TypeScript and published as JSON Schema, so tools in any language can read a module without running its code.
|
|
8
|
+
|
|
9
|
+
An implementation of this contract does two things with manifests: it **emits** each one as language-neutral JSON, and it **loads** an app's manifests together, refusing to start the app if any declaration is wrong. The Eloxiv kernel loads manifests when it builds its registry at startup.
|
|
10
|
+
|
|
11
|
+
## What a manifest declares
|
|
12
|
+
|
|
13
|
+
Declare a module with `defineModuleContract` (`@eloxiv/contracts`). Every declaration id is namespaced by the module: `<module>.<name>`, where the name is lower camel or kebab case (`hello.defaultVisibility`, `hello.greeting-panel`).
|
|
14
|
+
|
|
15
|
+
| Field | Declares |
|
|
16
|
+
| --- | --- |
|
|
17
|
+
| `entities` | Records the module stores, each over its Drizzle table (see [Entities](#entities)): Cedar type, table (in the module's own schema), primary key, row schema, columns, each field's storage (column, transport type, nullability, enum), the policy attributes the compiler may use, and what syncs. |
|
|
18
|
+
| `actions` | What callers can do: `title`, what people see the action called (a short verb phrase, "Send an email", shown in consent and approval prompts, notifications and chat cards; `defineAction({ title })`, one line of at most 80 characters (`ACTION_TITLE_MAX`; `defineAction` throws on a longer title or one with a line break or control character), or when omitted the action's readable name, `readableActionName`: the local part in words, sentence-cased, with the module in parentheses, `mail.send` is "Send (mail)", never the raw id; a manifest from before 1.6.0 has none and is read the same way), input and output schemas, the entity it `writes`, its `target`, further entities it `actsOn`, `organisationWide`, `bestEffort`, hints, and `consent` (an agent acting for a person needs their consent for each call; defaults to `hints.destructive`, see [ActionConsent](action-consent.md); `"each-call"`: no remembered permission covers a call), `connections`, the capability operations its handler may call through its Connections (an external one only scheduled, and only with consent; see [Invocation](invocation.md#external-effects)), `optimistic`: the change a client's replica predicts before the server answers, declared or the module's own (see [Optimistic effects](#optimistic-effects)), and `exposure`: the surfaces that offer it (`agent`, `mcp`, `api`, each true by default; see [ActionRegistry](action-registry.md#exposure)). An action's policy reaches only the tables of the entities it declares (`writes`, `target`, `actsOn`): on every other table it grants nothing, so an action declaring none reads only what `read` allows. `organisationWide: true` lets its policy leave the resource unconstrained; the kernel then confines it to records of the acting organisation. An action hinted `readOnly` runs its handler where the database refuses writes. The Cedar actions `read` and `share` are the kernel's own (reading records; who may share them, see [Sharing](sharing.md)): no module action may be named `<module>.read` or `<module>.share`. |
|
|
19
|
+
| `events` | What the module emits through the outbox, with payload schemas. An event may name the record it is about (`defineEvent(type, payload, { record: { entity, id } })`: one of the module's entities and the payload field holding its id); only such events can start members' event automations, and each automation sees one only while its owner may read that record ([Scheduler](scheduler.md#event-automations)). |
|
|
20
|
+
| `permissions` | The **permission vocabulary**: named permissions an organisation grants through roles (see [Directory](directory.md)). Each names the module's actions (or `read`) whose policy tests it. Policies test them as `principal.permissions.contains("<id>")`. |
|
|
21
|
+
| `settings` | Scoped values: `scope` is `user`, `org`, `app` or `module`; `schema` is the value's schema; `default` is the encoded (JSON) default. Read by key ([Settings](settings.md)). A schema marked sensitive is refused: secrets never go in settings. |
|
|
22
|
+
| `flags` | Feature flags: a `description` and a boolean `default` ([Flags](flags.md)). |
|
|
23
|
+
| `skills` | Agent skill documents the module ships: `content` is `{ text }` or `{ path }`, a path relative to the module's directory; optional `evals: { path }`, the skill's eval cases (a `SkillEvals` JSON file; see [AgentRuntime](agent-runtime.md), "Evals"); optional `audience`: `runtime`, `development` (for coding agents and tooling building the app; never given to the app's agent) or `both` (the default). Skills are the agent's app-scope resources ([AgentResources](agent-resources.md)). |
|
|
24
|
+
| `views` | Named shell views: `title`, `route` (unique across the app), and what it `shows`: one of the module's entities or one of its published query views. No UI code. |
|
|
25
|
+
| `slots` | Named extension points the module exposes; each `accepts` views or commands. |
|
|
26
|
+
| `contributions` | Views or commands this module contributes to a slot of any installed module. In the shell, a screen names the slots it shows: a contributed view whose screen is installed appears beside it as a panel, a contributed view command as a link (hello's screen shows `hello.greetingPanel`, to which notes contributes `notes.notes`). |
|
|
27
|
+
| `commands` | Palette commands: `run` is `{ action }` (any installed action) or `{ view }` (any installed view). |
|
|
28
|
+
| `workItemSources` | How the module feeds the unified inbox (decision 3): the `entity`, the field holding the item's `title`, the `state` (a field whose values map to `open`, `waiting` or `done`, or a constant state), the `assignee` field (or `null`) and the `link` view. |
|
|
29
|
+
| `entityResolvers` | Keyed by entity name: how another module turns a reference `{ module, entity, id }` into a title (the `title` field) and a link (a view), through the entity's read policy and never by reading the module's tables. |
|
|
30
|
+
| `queryViews` | Published query views (decision 6): one plain `SELECT` over the module's own tables, the `entity` whose read policy filters each row, and the `row` schema (one field per output column, which must include the entity's primary-key column; a field's `description` annotation describes the column to the agent). On the query surface ([QuerySurface](query-surface.md)) the view `<module>.<view>` is the relation `<module>_<view>`. |
|
|
31
|
+
| `dataSubjects` | The Privacy contract's declarations, by entity: `{ fields, erase }` (the fields holding a person's user id; erasure `delete`, `anonymise` with fixed values, or `retain` with a reason; optional `export`) or `{ none: reason }` for an entity about nobody. Checked here: the entity exists, its fields exist and are not the primary key, it has one organisation attribute, an anonymisation covers every subject field. Completeness (every entity declared) is enforced when the kernel's privacy module is installed. |
|
|
32
|
+
| `toolGroups` | Agent tool groups (`<module>.<name>`): a `description` and the module's own `actions` in it. Every action is also in its module's group (the module's name). An app disables groups for agents with `KernelApp.agentTools.disabledGroups`: their actions are hidden from every agent and refused to every agent-originated call, on every surface ([Invocation](invocation.md#reach)). Emitted as declared. |
|
|
33
|
+
| `approvalRules` | Business approval rules ([Approvals](approvals.md)): the `action` (any installed action), a declarative condition on its input (`when`), who may approve (`approvers`: a permission, role or group), `quorum`, `allowSelfApproval` and `expiresAfterMs`. Emitted with their defaults filled in. |
|
|
34
|
+
|
|
35
|
+
`jobs` (Scheduler) is added to the manifest by the Scheduler contract.
|
|
36
|
+
|
|
37
|
+
## Entities
|
|
38
|
+
|
|
39
|
+
Decision 9: **a module declares each field once, in its Drizzle table.** An entity is a thin layer over that table, defined with `defineEntity` from `@eloxiv/contracts/drizzle` (the TypeScript authoring entry point; the root `@eloxiv/contracts` stays free of Drizzle, and what the manifest publishes is the language-neutral `EntityContract` below). It references the table's **column objects**, never column-name strings:
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
// schema.ts: the fields, once (drizzle-kit generates the migrations from it)
|
|
43
|
+
export const greeting = pgSchema("hello").table("greeting", {
|
|
44
|
+
id: text("id").primaryKey(),
|
|
45
|
+
orgId: text("org_id").notNull(),
|
|
46
|
+
ownerId: text("owner_id").notNull(),
|
|
47
|
+
visibility: text("visibility", { enum: ["private", "org"] }).notNull().default("org"),
|
|
48
|
+
createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(),
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
// contract.ts: what policy and sync need, by reference
|
|
52
|
+
export const greeting = defineEntity(tables.greeting, {
|
|
53
|
+
name: "greeting",
|
|
54
|
+
cedarType: "Hello::Greeting",
|
|
55
|
+
policyAttributes: {
|
|
56
|
+
owner: { column: tables.greeting.ownerId, entity: "Eloxiv::User" },
|
|
57
|
+
org: { column: tables.greeting.orgId, entity: "Eloxiv::Org" },
|
|
58
|
+
visibility: { column: tables.greeting.visibility }, // a String: the column's type
|
|
59
|
+
sharedWith: { sharing: "read" },
|
|
60
|
+
},
|
|
61
|
+
// sync: false | { name?: "...", omit?: [tables.greeting.someColumn] } (default: every column syncs)
|
|
62
|
+
// relations: greetingRelations (Drizzle relations, for related())
|
|
63
|
+
// primaryKey: tables.greeting.id (default: the table's one-column key)
|
|
64
|
+
})
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Everything else is derived from the table: the Postgres location (the table's `pgSchema`), the primary key, each field's database column, its transport type (`string`, `number`, `boolean`, `json`; a timestamp is epoch milliseconds, as sync delivers it), its nullability (`notNull` absent) and enum values, the row schema (`Schema.NullOr` for a nullable field, `Schema.Literals` for an enum) and from it the entity's JSON Schema in the manifest. A column policy attribute's Cedar type is the column's (a string column is a `String`, an integer column a `Long`, a boolean a `Boolean`) or the entity type it names. A column that belongs to another table is refused when the entity is defined. Cedar and sync compare strings exactly, so a policy attribute is never stored where PostgreSQL compares otherwise: a `character(n)` (padded) or `uuid` (read in any case or spelling) column as a policy attribute is refused where policies are validated (`policyScopeProblems`, at the kernel's start and a MAKE install), and setup refuses a policy attribute's column under a non-deterministic collation; store such attributes as `text`.
|
|
68
|
+
|
|
69
|
+
The published entity (`moduleToJson`) carries `table`, `primaryKey`, `columns`, `policyAttributes` and `row` (JSON Schema) as before, plus `storage` (per field: `column`, `type` (`null` when the type is not on the [sync type allowlist](sync.md#sync-types)), `nullable`, `enum` (an enum array's labels too), `sqlType` (an enum as `schema.name`, Drizzle's bare `char()` as `character(1)`), `guard` (the range check sync needs for the type: `safe-integer`, `finite-double`, `instant`, `instant-ms`, `date`, `json-doubles` or `plain-array`, see [Sync types](sync.md#sync-types)), `generated` for a generated column, which never syncs), `sync` (`false`, or the Zero table's `name` and synced `fields`), `uniqueKeys` (field names) and `relationships` (the Drizzle relations it names: `one` with its `fields`, `references` and `relationName`, `many` with the table it is the other side of and its `relationName`, which pairs it with its `one`). A Cedar attribute's type does not depend on sync: an exact 64-bit integer (`bigint({ mode: "bigint" })`) is a `Long` whether or not it syncs. A sync name must be a JavaScript identifier the kernel does not reserve (`shareGrant`, `eloxivSyncOrg`, ...). Action inputs and outputs, events and query-view rows stay their own Effect Schemas: they rarely match a table's shape.
|
|
70
|
+
|
|
71
|
+
**Setup checks the table against the database** its migrations built (`entityColumnProblems`): a missing table, another primary key, a field whose column is missing, has another Postgres type than the table declares (compared by type OID and modifier, so exactly: an integer for a timestamp, `jsonb` for a `text[]`, a timestamp without a time zone for one with, `varchar(20)` for `varchar(10)`, a domain or a same-named type of another schema for the declared one), admits NULL where the table declares `notNull`, or is a Postgres enum with a value the table does not declare stops setup, so the row schema, the manifest and sync never promise what the database does not hold. The database may have columns the table does not declare; Eloxiv does not see them.
|
|
72
|
+
|
|
73
|
+
### Writing a module
|
|
74
|
+
|
|
75
|
+
A module is a directory under `modules/<name>/` (registry items are laid out exactly as they land in an app):
|
|
76
|
+
|
|
77
|
+
| File | Holds |
|
|
78
|
+
| --- | --- |
|
|
79
|
+
| `schema.ts` | The Drizzle tables, in `pgSchema("<name>")`: the only declaration of the module's fields. `drizzle.config.ts` and `drizzle-kit generate` write `migrations/` from it |
|
|
80
|
+
| `contract.ts` | `defineModuleContract`: entities (`defineEntity` over the tables), actions and events with their own Effect Schemas, and the other declarations above |
|
|
81
|
+
| `server.ts` | `defineModule(contract, { policy, migrationsDir, handlers })` from `@eloxiv/kernel` |
|
|
82
|
+
| `policy.cedar` | The Cedar policy: actions and `read` (and `share` for entities with sharing attributes) |
|
|
83
|
+
| `sync.gen.ts` | Generated by `eloxiv generate`: the module's Zero tables, its schema, `zql` and `defineQuery`. Do not edit |
|
|
84
|
+
| `sync.ts` | Only the named queries, over `sync.gen.ts`'s `zql`; imports nothing from `@rocicorp/zero` |
|
|
85
|
+
|
|
86
|
+
After changing `schema.ts` or an entity: `drizzle-kit generate` (the migration), then `eloxiv generate` (the sync tables and the app's composition). UI for the module is a separate item (`<name>-ui-foldkit`): a screen in the web shell that reads the replica and writes optimistically through the Foldkit adapter, `@eloxiv/client/foldkit` ([ClientSDK](client-sdk.md#ui-bindings)). A module the app writes itself is listed in `eloxiv.json` ([the app's own modules](../cli.md#the-apps-own-modules)); [Getting started](../getting-started.md#5-a-module-of-your-own) builds one. The [Sync](sync.md#generated-tables) contract describes what the generated tables hold.
|
|
87
|
+
|
|
88
|
+
## Optimistic effects
|
|
89
|
+
|
|
90
|
+
An action may declare the change it predicts on a client's replica (decision "Data"; criterion 6), with the builders `optimistic` exports from `@eloxiv/contracts`. The declaration is derived from the action's own `writes` and `target`:
|
|
91
|
+
|
|
92
|
+
| Effect | Predicts | Declares |
|
|
93
|
+
| --- | --- | --- |
|
|
94
|
+
| `optimistic.insert({ key, values })` | a new record of the `writes` entity | `key`: the input field naming the record's key (the primary key is `recordKey` of it, [Invocation](invocation.md)); `values`: every synced field but the primary key that cannot be empty |
|
|
95
|
+
| `optimistic.update({ set })` | the `target` record (or each one of a target set) with these fields set | `set`: fields of the target's entity |
|
|
96
|
+
| `optimistic.delete()` | the `target` record (or each one) removed | |
|
|
97
|
+
| `optimistic.custom()` | whatever the module's own prediction writes: several rows, a computed field, a counter, a move between parents | nothing more; the module's `predictions.ts` exports a function named like the action, which may write only the synced tables of the entities the action declares (`writes`, `target`, `actsOn`) ([Sync](sync.md#custom-predictions)) |
|
|
98
|
+
|
|
99
|
+
A field's value is `optimistic.input(field, fallback?)` (the input field's encoded value), `optimistic.actor("userId" \| "orgId")`, `optimistic.now()` (epoch milliseconds, as sync carries instants) or `optimistic.value(json)`.
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
export const greet = defineAction({
|
|
103
|
+
name: "hello.greet",
|
|
104
|
+
input: Schema.Struct({ message: Schema.String, visibility: Schema.optional(Visibility), key: Schema.optional(Schema.String) }),
|
|
105
|
+
output: Schema.Struct({ id: Schema.String, message: Schema.String, visibility: Visibility }),
|
|
106
|
+
writes: "greeting",
|
|
107
|
+
optimistic: optimistic.insert({
|
|
108
|
+
key: "key",
|
|
109
|
+
values: {
|
|
110
|
+
orgId: optimistic.actor("orgId"),
|
|
111
|
+
ownerId: optimistic.actor("userId"),
|
|
112
|
+
message: optimistic.input("message"),
|
|
113
|
+
visibility: optimistic.input("visibility", "org"),
|
|
114
|
+
createdAt: optimistic.now(),
|
|
115
|
+
},
|
|
116
|
+
}),
|
|
117
|
+
})
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
`load` refuses an effect that cannot predict what it says (`optimisticProblems`): an insert without `writes` or an update or delete without `target`; an entity that does not sync; a field it sets that the entity does not sync, or its primary key; an insert that leaves out a field that cannot be empty; an input field the input does not have; `now()` for a field that is not a number; a custom prediction for an action that declares no entity, or only entities that do not sync; a read-only action. `eloxiv generate` writes each module's mutators from these declarations into its `sync.gen.ts` ([Sync](sync.md#optimistic-writes)), wiring in the module's own prediction for a custom one ([Sync](sync.md#custom-predictions)); the prediction runs only on the replica. The server runs the action's handler, as for any call, and the replica keeps the server's answer.
|
|
121
|
+
|
|
122
|
+
## App configuration
|
|
123
|
+
|
|
124
|
+
What an app's own server code needs from the deployment (an endpoint, a switch, a key for a service of its own) is declared once, beside its modules, with `defineAppConfig` (`@eloxiv/kernel`) and given to the kernel as `KernelApp.config`:
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
export const config = defineAppConfig({
|
|
128
|
+
searchUrl: { description: "the search service's URL", schema: Schema.String, env: ["APP_SEARCH_URL", "SEARCH_URL"] },
|
|
129
|
+
pageSize: { description: "a number", schema: Schema.FiniteFromString, env: ["APP_PAGE_SIZE"], default: 25 },
|
|
130
|
+
searchKey: { description: "the search service's key", schema: Schema.String, env: ["APP_SEARCH_KEY"], secret: true },
|
|
131
|
+
})
|
|
132
|
+
// in app code: const { searchUrl, pageSize, searchKey } = yield* appConfig(config)
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
- Each field is read from the first of its variables that is set (non-empty), so a renamed variable keeps working under its old name as an alias; its schema decodes the string; with none set it takes its default, and a field without a default is required. Two fields may not read the same variable.
|
|
136
|
+
- It is resolved once, as the kernel starts. A required field not set, or a value its schema refuses, stops the start with every problem at once, each naming the field and its variables, never a value. A `secret` field's value is `Redacted`.
|
|
137
|
+
- App code reads the values with `appConfig(definition)` (the `AppConfig` service), typed by the declaration; asking with another definition than the app was started with is a defect. `resolveAppConfig(definition, env)` resolves without a kernel (for a script or a test) and also says where each value came from (`sources`: a variable, the default, or missing).
|
|
138
|
+
- The kernel's own configuration (`ELOXIV_*`) is separate. Modules' scoped values are [Settings](settings.md), declared in their manifests; the app's configuration is the deployment's, not changed at run time.
|
|
139
|
+
|
|
140
|
+
`packages/kernel/test/app-config.test.ts` proves aliases, defaults, decoding, redaction, the problems that stop a start and typed access.
|
|
141
|
+
|
|
142
|
+
## Operations
|
|
143
|
+
|
|
144
|
+
### `emit`
|
|
145
|
+
|
|
146
|
+
Input `{ module }`, output the module's `ModuleManifest` document. In TypeScript this is `moduleToJson(contract)`. Every schema-typed field (action input, output and result, event payloads, entity rows, setting schemas, query-view rows) is a JSON Schema (draft 2020-12) document. A published query view also gives `view`, the database view the kernel creates for it (`<schema>.qv_<name>`). Unknown keys are allowed, so later declarations extend the document compatibly.
|
|
147
|
+
|
|
148
|
+
### `load`
|
|
149
|
+
|
|
150
|
+
Input: the manifests of every module of one app. Output: the loaded module names, or the error `InvalidManifest` with `problems`, every problem found, each naming the module and the declaration. In the kernel this is `Registry.layer(modules)`; a refusal stops the kernel at startup with a message such as:
|
|
151
|
+
|
|
152
|
+
```
|
|
153
|
+
InvalidManifest: The app's module manifests are invalid:
|
|
154
|
+
- notes: contribution notes.besideGreetings contributes to slot hello.toolbar, which does not exist
|
|
155
|
+
- hello: query view hello.greetings is not a plain SELECT over schema hello: it reads notes.note, outside the module's schema hello
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
The kernel also refuses an app's durable work before setup or any service starts (`checkApp`, the same `InvalidManifest` listing every problem together with the manifest problems above): workflow names (the kernel's built-ins, the app's and its modules') must be unique, and every event trigger (the app's, and its modules' namespaced `<module>.<id>`) must have a unique id, start a workflow the app defines and listen for an event type an installed module declares. A module's workflows are named `<module>.<name>`, and its triggers and ingress sources start only its own workflows: a module's work runs, and reports progress, as its module.
|
|
159
|
+
|
|
160
|
+
The checks (`manifestProblems` in `@eloxiv/contracts`, plus the kernel's own):
|
|
161
|
+
|
|
162
|
+
- module names, Cedar namespaces, entity types, tables, action names and view routes are unique across the app;
|
|
163
|
+
- a module's name is a lower-case identifier of at most 52 characters (its database roles, `eloxiv_mod_<name>` and `eloxiv_own_<name>`, stay within PostgreSQL's 63 bytes), and not `eloxiv`, `eloxiv_*` or `pg_*`; in the kernel, its schema (by default its name) is one no other module uses, never PostgreSQL's (`pg_*`, `information_schema`), `public`, Better Auth's `auth` or the kernel's (`eloxiv`, `eloxiv_*`; only the kernel's own modules have `eloxiv_<name>`), nor zero-cache's (`<app id>` and `<app id>_<n>` for the app id zero-cache runs with, `ELOXIV_ZERO_APP_ID`, default `zero`; setup refuses an app id that names the kernel's schemas, `auth`, `public` or PostgreSQL's, where zero-cache would put its own objects), and every entity's table is in it ([Release](release.md), guarantee 2);
|
|
164
|
+
- every declaration id is namespaced by its module;
|
|
165
|
+
- every reference resolves: an action's `writes`, `target` and `actsOn` entities, a permission's actions, a view's entity or query view, a contribution's slot, view or command (and the slot accepts that kind), a command's action or view, a work-item source's entity, fields and view, a resolver's entity, field and view, a query view's entity;
|
|
166
|
+
- a best-effort action has a target and the completion fields in its output; an organisation-wide action declares an entity;
|
|
167
|
+
- no policy reaches further than its action's declared entities (kernel): for every action, on each entity it declares, for `read` on every entity, and for `share` on every entity with a sharing attribute, the compiled filter must tie every record it admits to the actor, through the actor's organisation (`resource.org == principal.org`), a user field equal to the actor (`resource.owner == principal`), a sharing grant to the actor, or a grant to one named user (`principal == Eloxiv::User::"x"`). A filter that some record of another organisation, owned by someone else and shared with no one, could satisfy (an unconstrained resource, or one constrained only by group, role or permission tests, by membership of a group a record names, or by literals) is refused, unless the action is `organisationWide`, which needs the entity to have an organisation column;
|
|
168
|
+
- an approval rule applies to an installed action, its comparisons are well formed (`gt`, `gte`, `lt`, `lte` against numbers, `in` against a list, `exists` against a boolean, non-empty field paths) and its id is namespaced; the kernel also requires the inbox modules when there are rules or consent-marked actions, and refuses rules on the decisions themselves (`approvals.*`, `consent.*`);
|
|
169
|
+
- a setting's scope is known, its default is JSON that decodes against its schema, and its schema is not marked sensitive (annotated `sensitive: true` or `writeOnly: true`, a `password` format, or an Effect `Redacted`, anywhere inside it);
|
|
170
|
+
- a flag has a description and a boolean default;
|
|
171
|
+
- every published query view's relation on the query surface (`<module>_<view>`) is unique across the app and does not start with `pg_`; no module is named `eloxiv` (the kernel's own name);
|
|
172
|
+
- a skill has exactly one of text or path, and a path (and its evals path) stays inside the module's directory; the kernel also checks the file exists; its `audience`, if given, is `runtime`, `development` or `both`;
|
|
173
|
+
- every entity's table is in the module's own schema (kernel);
|
|
174
|
+
- every action has a handler (kernel);
|
|
175
|
+
- every permission a policy tests with `principal.permissions.contains(...)` is declared by some module or the kernel (kernel);
|
|
176
|
+
- the policies validate against the Cedar schema generated from the manifests, in strict mode (kernel);
|
|
177
|
+
- a job (the Scheduler contract's `jobs`) has a description, a cron or interval schedule the scheduler can evaluate (kernel), a known catch-up policy and the `system` identity, and invokes an installed action with input that action decodes;
|
|
178
|
+
- the ids durable work is recorded under are unique (kernel): module names, subscription ids (which may not start with `trigger:`), and job ids (non-empty, no `:`);
|
|
179
|
+
- a published query view is one plain `SELECT` over the module's schema: one statement, no comments, no `WITH`, `INTO`, `FOR` (locking) or data-changing keyword, every table written as `<schema>.<table>` in the module's schema (including comma joins and subqueries), subqueries only as `(SELECT ...)` or `(VALUES ...)`, no schema-qualified or quoted function names and no functions with side effects or that run SQL from text (`set_config`, `pg_*`, `nextval`, `query_to_xml`, ...). This lexical check is only a first filter and is conservative: it refuses some valid SQL (`IS DISTINCT FROM`, `EXTRACT(x FROM y)`, `SUBSTRING(x FOR n)`) rather than risk accepting something unsafe. Setup then checks what the created view really calls (see Guarantees). Its row must include the entity's primary-key column.
|
|
180
|
+
|
|
181
|
+
## Records
|
|
182
|
+
|
|
183
|
+
All in the published schema's `types`: `ModuleManifest`, `Entity`, `Action`, `Event`, `Permission`, `Setting`, `Flag`, `Skill`, `View`, `Slot`, `Contribution`, `Command`, `WorkItemSource`, `EntityResolver`, `QueryView`, `ApprovalRule`.
|
|
184
|
+
|
|
185
|
+
## Errors
|
|
186
|
+
|
|
187
|
+
`InvalidManifest { problems: string[] }` from `load`. `emit` does not fail.
|
|
188
|
+
|
|
189
|
+
## Guarantees
|
|
190
|
+
|
|
191
|
+
- An app whose manifests have any problem does not start: the kernel never serves a registry with a dangling reference.
|
|
192
|
+
- The JSON a manifest emits decodes against the published `ModuleManifest` schema.
|
|
193
|
+
- Published query views are created by setup as `security_invoker` views owned by the module's owner role, readable (`SELECT` only) by its runtime role, so the tables' row-level security, including the entity's read policy, applies to every reader. Setup checks Postgres's own record of each view as well: it may read only tables of the module's schema (including the entity's table; never another view, a materialised view or a foreign table, whose own query or source this check does not see) and must return exactly the declared columns; every value it produces or reads (each expression's result, every column it reads and the fields of every row type) must be of an allowed type: a built-in on the type allowlist (booleans, text, numbers, dates and times, `uuid`, `json`, `jsonb`, `bytea` and their arrays), `record` or `unknown`, or an enum or table row type of the module's schema, made only of allowed types, that no cast involves. Postgres converts values by type where the query tree shows no call (`to_json` and `to_jsonb` use a cast to `json` for a type that is not built in; `format`, `||` and record and array output call each element's output function), so a module type with a cast of its own could otherwise run the module's code; domains (whose checks run on conversion), ranges, other schemas' types and other composite types are refused. Every callable in the view's stored query tree (`pg_rewrite`, where quoted, schema-qualified and upper-case names, casts, operators, `IN`, `IS DISTINCT FROM`, sorting and grouping, and calls inside subqueries and CTEs are all resolved to the function they run) must be on an allowlist: `pg_catalog` functions that are immutable or stable and named on a list of side-effect-free built-ins (comparison, string, numeric, date and time, JSON and array helpers, aggregates, window functions), built-in casts between allowed types, `pg_catalog` operators whose functions are immutable or stable built-ins, and text coercions to allowed types. Anything else is refused, including every `pg_catalog` function not on the list (`set_config`, `current_setting`, `query_to_xml` and the other SQL-from-text functions, `pg_*` administration functions), volatile functions, functions and operators outside `pg_catalog`, and XML, SQL/JSON, domain-coercion, sequence, table-sample and row-locking nodes. Any failure stops setup ([`QueryViewCheck.ts`](../../packages/kernel/src/db/QueryViewCheck.ts)). Independently of views, setup refuses a module whose migrations leave a cast to or from a type of its schema, or through one of its functions (Postgres would run it wherever it converts such a value, including inside the kernel's own functions: the write log runs `to_jsonb` on every written row), a foreign table, a base type with its own input and output functions, or default privileges. A module's migrations run on a session that logs in as its owner role, so they cannot gain any privilege beyond it; setup's checks run again on its own session, which no migration touched, and read the catalogue by qualified names with `pg_temp` last on the search path (see [Release](release.md), guarantee 2). Views are dropped before module migrations run and created again after hardening, so migrations can change the tables they read.
|
|
194
|
+
- Views are read in a read-only scope: `QueryViews.read` (the kernel's reader for callers) and a handler's `ctx.queryView` select as the module's runtime role inside a savepoint where the transaction is read-only, rolled back afterwards, so even an allowlisted function cannot write and any setting a read changed is undone. A handler that selects from a view with plain SQL in a read-write action runs in the action's transaction; the setup allowlist is what keeps the view free of side effects there.
|
|
195
|
+
|
|
196
|
+
## Implementing it
|
|
197
|
+
|
|
198
|
+
Another implementation (for example a manifest checker in another language, or a different kernel) reads manifests in the JSON form above and applies the checks listed under `load`. It must refuse each class of invalid manifest the conformance kit exercises and accept the kit's valid app.
|
|
199
|
+
|
|
200
|
+
## Running the conformance kit
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
import { moduleManifestConformance } from "@eloxiv/testing/conformance/ModuleManifest"
|
|
204
|
+
|
|
205
|
+
moduleManifestConformance({
|
|
206
|
+
// Resolve if the app is accepted; reject with an error naming the problem if it is refused.
|
|
207
|
+
load: async (modules) => { /* build your registry from `modules` */ },
|
|
208
|
+
// The module's manifest as JSON.
|
|
209
|
+
emit: (module) => moduleToJson(module.contract),
|
|
210
|
+
})
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
The kit supplies a valid two-module app that uses every declaration and one mutation of it per class of invalid manifest, and checks each refusal names what is wrong. The kernel runs it in [`packages/testing/test/conformance-manifest.test.ts`](../../packages/testing/test/conformance-manifest.test.ts).
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# NotificationChannel
|
|
2
|
+
|
|
3
|
+
How a notification reaches a person outside the app: a channel delivers one rendered message to one recipient and says whether a failure is worth retrying. [Notifications](notifications.md) decides which channels a notification goes to, records every attempt in the delivery log and retries through the outbox.
|
|
4
|
+
|
|
5
|
+
- Kind: kernel service. Version 1.1.0 (1.1.0: the kernel's push channel over APNs and FCM; `PushMessage` gains the notification's organisation, id, category, record link and an optional decision; `ChannelError.retryAfterMs`).
|
|
6
|
+
- Schema: [`packages/contracts/schema/contracts/NotificationChannel.json`](../../packages/contracts/schema/contracts/NotificationChannel.json) (source [`NotificationChannel.ts`](../../packages/contracts/src/contracts/NotificationChannel.ts)).
|
|
7
|
+
- Implementation: `NotificationChannelImpl` and `emailChannel` in [`packages/kernel/src/Notifications.ts`](../../packages/kernel/src/Notifications.ts); the SMTP client in [`notifications/Smtp.ts`](../../packages/kernel/src/notifications/Smtp.ts); the push channel in [`notifications/Push.ts`](../../packages/kernel/src/notifications/Push.ts) over the APNs and FCM clients in [`notifications/Providers.ts`](../../packages/kernel/src/notifications/Providers.ts).
|
|
8
|
+
- Kit: `@eloxiv/testing/conformance/NotificationChannel` ([source](../../packages/testing/src/conformance/NotificationChannel.ts)): `emailChannelConformance`, run by [`packages/testing/test/notification-channel.test.ts`](../../packages/testing/test/notification-channel.test.ts) against a real SMTP server on a local port, and `pushConformance` ([source](../../packages/testing/src/conformance/Push.ts)), run by [`packages/testing/test/push.test.ts`](../../packages/testing/test/push.test.ts) against the APNs and FCM protocol fakes ([`ApnsFake.ts`](../../packages/testing/src/fakes/ApnsFake.ts), [`FcmFake.ts`](../../packages/testing/src/fakes/FcmFake.ts)).
|
|
9
|
+
|
|
10
|
+
## Kinds
|
|
11
|
+
|
|
12
|
+
| Kind | Provided by | Message |
|
|
13
|
+
| --- | --- | --- |
|
|
14
|
+
| `in-app` | the notification record itself (no delivery) | the `Notification` |
|
|
15
|
+
| `email` | the kernel, over SMTP (`ELOXIV_SMTP_URL`) | `EmailMessage`: `messageId`, `from`, `to`, `subject`, `text`, `html`, `unsubscribeUrl`, `headers` |
|
|
16
|
+
| `push` | the kernel, over APNs and FCM HTTP v1 (`ELOXIV_APNS_*`, `ELOXIV_FCM_*`), to the installations people register ([Notifications](notifications.md#push)) | `PushMessage`: `messageId`, `userId`, `orgId`, `notificationId`, `category`, `title`, `body`, `url`, `link` (a [View](view.md) `DeepLink` or null), `decision?` (`kind`, `requestId`, `verdicts`, `expiresAt`) |
|
|
17
|
+
| `chat` | Messaging (contract only) | `ChatMessage`: `messageId`, `destination`, `text`, `url` |
|
|
18
|
+
|
|
19
|
+
A host registers a channel with `KernelOptions.channels` (`{ kind, deliver }`); a registered `email` or `push` channel replaces the kernel's. Only the kernel's push channel mints decision tokens.
|
|
20
|
+
|
|
21
|
+
## Operation
|
|
22
|
+
|
|
23
|
+
### `deliver`
|
|
24
|
+
|
|
25
|
+
| | |
|
|
26
|
+
| --- | --- |
|
|
27
|
+
| Input | `ChannelMessage` (one of the kinds above) |
|
|
28
|
+
| Output | `Delivered`: `providerId` (the server's queue id, a push ticket), or null |
|
|
29
|
+
| Errors | `ChannelError`: `channel`, `retryable`, `message`, `retryAfterMs?` (the provider's `Retry-After`) |
|
|
30
|
+
|
|
31
|
+
Succeeds once the channel accepted the message (for push: at least one installation accepted it and none waits for a retry). The same `messageId` may be delivered again after a crash; channels pass it on (`Message-ID` for email, `apns-id` for APNs) so the receiving side can drop duplicates. A retryable failure with `retryAfterMs` is retried no sooner than that, counted from the outbox's clock after the attempt (the outbox's backoff or the advice, whichever is later; at most a day). The push channel computes it from the time each provider allowed, read when its answer arrived, never shortened; when a provider asks one installation to wait longer than a day, the push channel ends that installation's send (`failed`, saying so) rather than send before the provider allows, and the delivery is decided by the other installations' answers (an acceptance still counts; with none, a permanent failure).
|
|
32
|
+
|
|
33
|
+
## The email channel
|
|
34
|
+
|
|
35
|
+
One SMTP connection per message: greeting, `EHLO`, optional `AUTH PLAIN`, `MAIL FROM`, `RCPT TO`, `DATA` (dot-stuffed, CRLF), `QUIT`, over TCP (`smtp://`) or implicit TLS (`smtps://`). The message is MIME: `From`, `To`, `Subject` (RFC 2047 encoded when not ASCII), `Date`, `Message-ID`, `List-Unsubscribe` and `List-Unsubscribe-Post` when there is an unsubscribe URL, the message's extra headers, and a base64 `text/plain` part (with a `text/html` alternative when there is HTML).
|
|
36
|
+
|
|
37
|
+
Failures: a connection that cannot be made, a timeout or a 4xx reply is retryable; a 5xx reply (a refused recipient, a rejected message) is permanent; a message of another kind is permanent.
|
|
38
|
+
|
|
39
|
+
Nothing a caller supplies reaches the protocol or the header block unchecked; what fails a check is refused, permanently, before any connection is made:
|
|
40
|
+
|
|
41
|
+
- **Envelope addresses** (the `From` and `To` addresses, also given as `Name <address>`) must be RFC 5321 mailboxes: printable ASCII only (no CR, LF, NUL or other controls; no SMTPUTF8), a dot-string or quoted-string local part of at most 64 octets, a domain of valid labels (at most 63 octets each, 255 in all) or an IPv4/IPv6 address literal, and at most 254 octets in all. A display name with controls is refused; one with specials is quoted, a non-ASCII one encoded.
|
|
42
|
+
- **Extra headers** need RFC 5322 field names (printable ASCII without `:`) and may not add a header the channel writes itself (`From`, `To`, `Cc`, `Bcc`, `Reply-To`, `Sender`, `Subject`, `Date`, `Message-ID`, `MIME-Version`, `Content-Type`, `Content-Transfer-Encoding`). Values lose line breaks (to spaces) and other controls; non-ASCII values and subjects are RFC 2047 encoded words of at most 75 characters, folded, and no line exceeds 998 characters. The `Message-ID` must be printable ASCII without `<`, `>` or spaces.
|
|
43
|
+
- **Bodies** are base64, so their content never reaches the protocol; the DATA section is dot-stuffed with CRLF endings. The `EHLO` name must be a domain; `AUTH PLAIN` credentials are base64.
|
|
44
|
+
|
|
45
|
+
## The push channel
|
|
46
|
+
|
|
47
|
+
Installed when the deployment configures a provider: APNs with `ELOXIV_APNS_KEY` (the `.p8` key's PEM; `\n` in a one-line value is read as a line break), `ELOXIV_APNS_KEY_ID` and `ELOXIV_APNS_TEAM_ID` (optionally `ELOXIV_APNS_ENDPOINT`, default `https://api.push.apple.com`, and `ELOXIV_APNS_SANDBOX_ENDPOINT` for installations registered as `sandbox`, default `https://api.sandbox.push.apple.com`); FCM with `ELOXIV_FCM_SERVICE_ACCOUNT` (the service account's JSON key; optionally `ELOXIV_FCM_PROJECT_ID`, default the key's `project_id`, `ELOXIV_FCM_ENDPOINT` and `ELOXIV_FCM_TOKEN_ENDPOINT`). Or `KernelConfig.push` (`{ apns?, fcm? }`; `apns.ca` trusts a further CA, for a test or a proxy). A provider without configuration is not installed: installations of it are skipped and logged.
|
|
48
|
+
|
|
49
|
+
One `deliver` sends the notification to every live installation of the recipient (registered from a session still in force, its token not reported dead), up to four at a time. Each send is claimed just before it goes out, in a transaction of its own that reads the installation again: still the recipient's, the same registration (`generation`), its session valid and not revoked, the recipient still a member of the notification's organisation. It records the attempt (`sending`) and the decision token's hash, bound to that session and generation. A send that no longer stands is skipped: a device signed out, reassigned to another person, or registered again while the delivery waited gets nothing. What a provider has accepted is past the kernel's reach. Neither client follows a redirect (a redirect is a configuration failure, retried); concurrent sends share one provider-token signing (APNs) or access-token exchange (FCM).
|
|
50
|
+
|
|
51
|
+
- **APNs**: HTTP/2 over TLS (`node:http2`), one connection per endpoint, reused; a GOAWAY, an error or a closed connection opens a new one. `POST /3/device/<token>` with `authorization: bearer <provider token>` (ES256 JWT: `kid` the key id, `iss` the team id, `iat`; reused for 50 minutes, signed again sooner when APNs says it expired), `apns-topic` (the installation's app id), `apns-push-type: alert`, `apns-priority: 10`, `apns-id` (a UUID derived from the delivery and installation, the same on every retry), `apns-collapse-id` (the notification's id). Body: `{ aps: { alert: { title, body }, category? }, eloxiv: { notificationId, orgId, userId, installationId, category, link, decision? } }`; `aps.category` is `eloxiv.decision` when a decision is offered.
|
|
52
|
+
- **FCM HTTP v1**: `POST /v1/projects/<project>/messages:send` with an access token the service account's RS256 assertion (`iss` the account, `scope` `https://www.googleapis.com/auth/firebase.messaging`, `aud` the token endpoint, an hour at most) is exchanged for (`grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer`), kept until a minute before it expires. Body: a data-only message at high priority, `{ message: { token, android: { priority: "high" }, data: { tag, title, message, body, channelId, categoryId?, eloxiv } } }`, in the fields expo-notifications reads from a data message (its custom-provider format), so the app draws the notification itself, also in the background, with the decision category's Approve and Reject buttons (a `notification` message is drawn by the system tray, without buttons): `title`, `message` (the text), `body` (`{ "eloxiv": <the same object> }` as JSON, which becomes the notification's data in the app), `channelId` (`default`, the Android channel the registry's Expo host makes), `categoryId` (`eloxiv.decision`, only when a decision is offered) and `eloxiv` (the same object, JSON, for a receiver that reads the data as it comes). Every value is a string. The notification's id is its `tag` (expo-notifications' notification identifier: a copy sent again, after an uncertain answer, replaces the one still shown). There is no `collapse_key`: FCM keeps at most four collapse keys per device while it is offline, so a key per notification would drop distinct requests.
|
|
53
|
+
|
|
54
|
+
Both payloads' `eloxiv` names the recipient (`userId`) and the installation it was sent to (`installationId`, the app's own id as it registered), so the app opens or decides it only for that person signed in on that install. `eloxiv.decision` is `{ kind, requestId, verdicts, token? }`. `token` is sent to **APNs installations only**: an FCM payload's data reaches the posted Android notification's extras (readable by apps with notification access) and debug logs, so an Android app's Approve and Reject open the app, which decides through the person's own session; no token is minted for an FCM installation. An APNs installation's token is its single-use token for the notification's decision (an HMAC of the delivery, the installation and its registration's generation under the deployment's secret, so a retry to the same registration sends the same one; stored only as its SHA-256), redeemed at `POST /api/notifications/decide` ([Notifications](notifications.md#decisions-from-a-notification)). Only the kernel's own approval and consent producers offer a decision, and its title and body come from the request (`Approval needed: <title>`, `<requester> asked for your approval.`; `Your agent wants to: <title>`, where `<title>` is what people see the action called, as recorded with the request when the call was held; "Open the app to review the details."), never from what a notification's sender wrote. The body is at most 1,000 characters; a consent request's body is the fixed text "Open the app to review the details." (never the call's input). Each provider payload is fitted to 4,096 bytes of JSON: the body is shortened first (whole characters), then the title; when no text fits, the link and then the category are left out and the text fitted again; a payload that still does not fit is never sent (that installation's send is refused, the reason recorded); a record id longer than a `DeepLink`'s 500 characters gets no link.
|
|
55
|
+
|
|
56
|
+
Each installation's answer is recorded at once, on a connection of its own (`eloxiv.push_delivery`: `sending` before the request, then `sent`, `failed`, `retrying` or `uncertain`, attempts, the reason). A retry of the delivery sends only to installations with no state, or with `retrying`, `uncertain` or `sending` (the answer was lost, or the process stopped mid-send). It never sends to one that accepted (`sent`) or was refused for good (`failed`):
|
|
57
|
+
|
|
58
|
+
| Answer | Classified | Effect |
|
|
59
|
+
| --- | --- | --- |
|
|
60
|
+
| APNs `200`; FCM `200` naming the message completely (`projects/<p>/messages/<id>`) | accepted | the provider's id (`apns-id`, the message `name`) |
|
|
61
|
+
| APNs `410`, `400 BadDeviceToken`/`DeviceTokenNotForTopic`; FCM's structured `UNREGISTERED` with its `404` | dead token | only the registration that was sent (the same generation) is invalidated; after an APNs `410` only if its `timestamp` is newer than that registration (written by the clock after its lock waits, a first registration too); an answer with no usable date (FCM's, an APNs `410` without a `timestamp` or with a malformed one) only while that registration is unwritten since it was sent (registered again, even unchanged, it stays) |
|
|
62
|
+
| APNs `403` (provider token), FCM `401` (whatever its body) or `403` other than `SENDER_ID_MISMATCH`, the token endpoint refusing | the deployment's credentials | retryable (a new provider or access token next time), after the token endpoint's `Retry-After`; the device is not blamed |
|
|
63
|
+
| `429`, `5xx`, a connection that could not be made, GOAWAY | throttling, outage | retryable, after `Retry-After`; an FCM `429` without one after a minute (FCM's minimum back-off); read from the status and headers, whatever the body |
|
|
64
|
+
| a timeout or a stream lost after the request was sent; FCM `200` not naming a message | uncertain | retried: sent again, at least once |
|
|
65
|
+
| an FCM answer that is not FCM's structured error (a wrong endpoint's or a proxy's page, a generic `404`), FCM's structured `404` naming no device (`UNREGISTERED`), a redirect | endpoint or protocol failure | retryable; the installation stays active |
|
|
66
|
+
| any other `4xx` (a refused payload, `SENDER_ID_MISMATCH`, `INVALID_ARGUMENT`) | refused | permanent for that installation, not invalidated |
|
|
67
|
+
|
|
68
|
+
An answer sent again after it was lost is a second copy for the provider: APNs collapses copies with the same `apns-collapse-id` (the notification's id); an FCM copy replaces a visible one by its `tag`, and a client that presents notifications itself drops a `notificationId` it already showed (a copy the person already dismissed can show again while the app is in the background). The delivery then fails retryably while any installation is to be retried, no sooner than the latest time a provider allowed. It succeeds when at least one installation accepted, in this attempt or an earlier one (also if the others are gone by the retry). It fails permanently when the recipient has no installation, none uses a configured provider, or every one refused it. What the records keep is the kernel's own text: a provider's documented code (APNs's `reason`, FCM's `FcmError` code or status) or the HTTP status alone, never the provider's free-form text or a transport's or the database's message. Nothing a message or log carries includes a device token or a credential.
|
|
69
|
+
|
|
70
|
+
## Records
|
|
71
|
+
|
|
72
|
+
`ChannelKind`, `EmailMessage`, `DecisionVerdict` (`approve`, `reject`), `DecisionKind` (`approval`, `consent`), `PushDecision`, `PushMessage`, `ChatMessage`, `ChannelMessage`, `Delivered`, `ChannelError`, and the delivery log's `DeliveryRecord` (`id`, `orgId`, `notificationId`, `recipientId`, `channel`, `address`, `status` (`pending`, `sent`, `failed`, `suppressed`), `attempts`, `lastError`, `providerId`, `createdAt`, `sentAt`).
|
|
73
|
+
|
|
74
|
+
## How an implementation is checked
|
|
75
|
+
|
|
76
|
+
`emailChannelConformance(start)` takes a subject that delivers through the channel to an SMTP server it controls: a message arrives with its envelope, every header (including a non-ASCII subject), and both bodies intact; a text-only message keeps lines that start with a dot and has no unsubscribe header; a temporary failure (451) is retryable and the retry arrives; a refused recipient (550) is permanent; an unreachable server is retryable; a push message given to the email channel is refused, permanently.
|
|
77
|
+
|
|
78
|
+
The kernel runs it in `packages/testing/test/notification-channel.test.ts` with [`startSmtpSink`](../../packages/testing/src/SmtpSink.ts), a real SMTP server over `node:net` (on Bun and Node).
|
|
79
|
+
|
|
80
|
+
`pushConformance(start)` (also exported from the NotificationChannel kit) takes a kernel subject whose push channel points at the APNs fake (a real `node:http2` TLS server with a certificate from an in-memory test CA, verifying each provider token's ES256 signature, key id, team and age, the topic and the payload's size) and the FCM fake (verifying the service account's RS256 assertion and issuing access tokens; `messages:send` with FCM's structured errors). It checks, besides the installations ([Notifications](notifications.md)): the APNs payload and headers exactly, with the record's link chosen from the installed views and none when no view shows it, one provider token for several sends; the FCM message (data-only, high priority, no collapse key, expo-notifications' fields, `data.eloxiv` and `data.body`, the recipient and installation) and the decision category on a consent push, one access token; push added to a person's channels without replacing them (`setPreference` with `add`); a consent request's input never in the payload; a retry after a `503` and a `500` sends again only to the installation that failed (the other got one copy); a `429` with `Retry-After: 2` is retried no sooner than two seconds later; APNs `500`/`503` and FCM `429` retried, the device not blamed; APNs `ExpiredProviderToken` and revoked FCM access tokens retried with new credentials; dead tokens (APNs `410`, FCM `UNREGISTERED`) invalidate their installations, which get nothing more; an installation whose token changed while APNs answered for the old one is not invalidated; a refused payload fails only that installation, without invalidating it, and is not sent to it again while another installation retries; an earlier acceptance stands when the other installations are gone by the retry; a provider asking one installation to wait longer than a day fails only that installation, and another's acceptance delivers; a GOAWAY moves the next request to a new connection. It also checks that each send is recorded (`sending`) before the provider answers; that an installation signed out while earlier sends of the delivery waited gets nothing, nor does a recipient who left the organisation before a retry; that a `Retry-After` counts from when a slow answer arrived, and the token endpoint's is honoured; that a provider's free-form text naming a device token reaches no record; that an APNs `410` older than the registration, about a first registration whose write waited for a lock (dated after the verdict), or about a registration the app corrected meanwhile, invalidates nothing, nor does one without a usable `timestamp` about a registration made again meanwhile; that a payload is fitted to 4 KiB and an over-long record id gets no link; that many people registering one token at once all succeed and one row holds it; and that a 4,096-character token registers. Run by `packages/testing/test/push.test.ts` on Bun and Node. The clients alone are checked by `packages/testing/test/push-providers.test.ts`: no redirect is followed (the OAuth assertion and the message never reach the redirect's target), an FCM page that is not FCM's answer neither invalidates nor counts as accepted, an FCM quota refusal waits a minute (a plain `429` too) and a plain `503` keeps its `Retry-After`, a `401` of any body fetches a new access token, only a complete message name is accepted and a `404` naming no device is retried, provider codes are recorded only as the kernel's constants, concurrent first sends share one credential, and a payload whose category alone passes 4 KiB is sent without it (one that cannot fit is not sent). These are protocol fakes, not Apple's or Google's services.
|
|
81
|
+
|
|
82
|
+
## Not yet guaranteed
|
|
83
|
+
|
|
84
|
+
- **STARTTLS** is not supported (use `smtps://` or a local relay); only `AUTH PLAIN`.
|
|
85
|
+
- Chat has no implementation in the kernel; its kit will run against Messaging's.
|
|
86
|
+
- Push is proven against protocol fakes; delivery through Apple's and Google's services with real credentials is the deployment's to check. Web Push (a browser's subscription) has no sender: the push channel delivers to APNs and FCM installations only.
|
|
87
|
+
- Payloads are fitted to 4,096 bytes of the payload's JSON, which is at least what either provider counts (FCM counts keys and values only).
|
|
88
|
+
- A send whose answer was lost is sent again (at least once): deduplicated by APNs's collapse id; an FCM copy replaces a visible one by its tag, and clients that present notifications themselves drop a repeat (a copy dismissed in the background can show again).
|
|
89
|
+
- Android gets no decision token: its Approve and Reject open the app, which decides through the person's session. One-press decisions from the lock screen are iOS only.
|
|
90
|
+
- One connection per message (no pooling).
|