@collective-intelligence/external-apps-server-sdk-payload 0.0.0-placeholder.0 → 0.13.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/AGENTS.md +49 -0
- package/README.md +122 -0
- package/dist/ci-generate/declarations/ci-generate/generate.d.ts +10 -0
- package/dist/ci-generate/declarations/entrypoints/ci-generate.d.ts +6 -0
- package/dist/ci-generate/declarations/knowledge/body.d.ts +32 -0
- package/dist/ci-generate/declarations/knowledge/files.d.ts +42 -0
- package/dist/ci-generate/declarations/knowledge/manifest.d.ts +19 -0
- package/dist/ci-generate/declarations/package/builder.d.ts +63 -0
- package/dist/ci-generate/declarations/package/contract.d.ts +16 -0
- package/dist/ci-generate/declarations/package/stamped-fields.d.ts +7 -0
- package/dist/ci-generate/declarations/plugin/editor-field.d.ts +20 -0
- package/dist/ci-generate/declarations/plugin/integration-user.d.ts +11 -0
- package/dist/ci-generate/declarations/plugin/parts.d.ts +81 -0
- package/dist/ci-generate.d.ts +1 -0
- package/dist/ci-generate.js +2 -0
- package/dist/index/declarations/ci-generate/generate.d.ts +10 -0
- package/dist/index/declarations/entrypoints/index.d.ts +6 -0
- package/dist/index/declarations/knowledge/body.d.ts +32 -0
- package/dist/index/declarations/knowledge/files.d.ts +42 -0
- package/dist/index/declarations/knowledge/identity.d.ts +27 -0
- package/dist/index/declarations/knowledge/manifest.d.ts +19 -0
- package/dist/index/declarations/knowledge/push-job.d.ts +8 -0
- package/dist/index/declarations/knowledge/source.d.ts +24 -0
- package/dist/index/declarations/operations/conflict.d.ts +22 -0
- package/dist/index/declarations/operations/markdown.d.ts +25 -0
- package/dist/index/declarations/operations/operations.d.ts +30 -0
- package/dist/index/declarations/operations/write-back.d.ts +8 -0
- package/dist/index/declarations/package/builder.d.ts +63 -0
- package/dist/index/declarations/package/contract.d.ts +16 -0
- package/dist/index/declarations/package/stamped-fields.d.ts +7 -0
- package/dist/index/declarations/plugin/editor-field.d.ts +20 -0
- package/dist/index/declarations/plugin/grant-store.d.ts +21 -0
- package/dist/index/declarations/plugin/integration-user.d.ts +11 -0
- package/dist/index/declarations/plugin/parts.d.ts +81 -0
- package/dist/index/declarations/plugin/plugin.d.ts +10 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +7 -0
- package/dist/package.d.ts +134 -0
- package/dist/package.js +24 -0
- package/docs/guide/ai/index.md +379 -0
- package/docs/guide/ai/studio.md +245 -0
- package/docs/guide/data/connectors.md +267 -0
- package/docs/guide/data/datasets.md +145 -0
- package/docs/guide/data/documents.md +235 -0
- package/docs/guide/data/index.md +62 -0
- package/docs/guide/data/knowledge.md +214 -0
- package/docs/guide/develop/extensions.md +299 -0
- package/docs/guide/develop/external-apps.md +289 -0
- package/docs/guide/develop/infrastructure.md +135 -0
- package/docs/guide/develop/sdks.md +252 -0
- package/docs/guide/index.md +83 -0
- package/docs/guide/platform/access.md +311 -0
- package/docs/guide/platform/architecture.md +166 -0
- package/docs/guide/platform/built-ins.md +225 -0
- package/docs/guide/platform/entrypoints.md +320 -0
- package/docs/guide/scenarios/index.md +130 -0
- package/docs/guide/template/index.md +295 -0
- package/docs/guide/template/state-machines.md +294 -0
- package/docs/payload-connector.md +890 -0
- package/docs/payload-page-editor-skill.md +284 -0
- package/package.json +76 -8
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
# External apps
|
|
2
|
+
|
|
3
|
+
Sign users in with CI, read and write their data through a BFF, cache shared reads and stay live with Realtime.
|
|
4
|
+
|
|
5
|
+
An external app is an application that runs outside CI and talks to it. The template's `apps/web` is one: a Next.js app with its own routes and API, plus a server-side BFF (backend-for-frontend) that signs users in with CI and forwards their Lead and Opportunity calls.
|
|
6
|
+
|
|
7
|
+
Traffic between an app and CI can flow in two directions. Outbound, the browser calls the app's BFF and the BFF calls CI under `/application/v1/`, to proxy records, use CI capabilities and start workflows. Inbound, CI calls a Gateway that the app hosts, to reach the app's own resources, datasets and operations. The template is outbound only, and most demos need nothing more.
|
|
8
|
+
|
|
9
|
+
## When a demo needs an external app
|
|
10
|
+
|
|
11
|
+
You need one when the demo has its own UI outside Studio and the Dashboard, or when CI must reach data and actions that live in the customer's system. Pick the SDK path by what each screen or action needs:
|
|
12
|
+
|
|
13
|
+
| The demo needs | Use |
|
|
14
|
+
| ---------------------------------------------------- | ------------------------------------------------------- |
|
|
15
|
+
| Data that differs per user | BFF resource proxy (`ciResources`) and the entity hooks |
|
|
16
|
+
| The same data for every user, rendered on the server | The Read Port with `"use cache"` |
|
|
17
|
+
| A business action with side effects in CI | A Fixed workflow route |
|
|
18
|
+
| CI reaching your data or actions | A Gateway |
|
|
19
|
+
| Your own logic with your own store | The app API under `/api/app` |
|
|
20
|
+
|
|
21
|
+
## Put it in the app or in CI
|
|
22
|
+
|
|
23
|
+
Before you write a screen, decide where each piece of its data and logic lives. [Platform architecture](../platform/architecture.md) gives the first question: who owns the records. The same question also places rules, access decisions and UI state:
|
|
24
|
+
|
|
25
|
+
| Question | Put it in CI | Keep it in the external app |
|
|
26
|
+
| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
|
|
27
|
+
| Do people in Studio, agents or workflows use these records? | A [Knowledge](../data/knowledge.md) schema. The app reads and writes the records through the BFF. | |
|
|
28
|
+
| Does the customer's database stay the source of truth? | Only what CI must read or act on, exposed through a Gateway | The records, in the app's database |
|
|
29
|
+
| Must agents, workflows and the app apply one business rule the same way? | A tool or a workflow in the package. The app starts it and does not write the rule again. | A rule that already runs in the customer's backend, exposed as a Gateway operation |
|
|
30
|
+
| Who may see or change a record? | Capabilities, Knowledge data policies and Access Grants | Only the choice to hide a control |
|
|
31
|
+
| Is it UI state, such as form steps, filters and drafts, or app-only data? | | State machines, query state and the app API store |
|
|
32
|
+
|
|
33
|
+
Records go to Knowledge when more than the app uses them. In the template, the Sales desk Studio app lists Leads and the lead qualifier agent reads them, so Leads live in Knowledge and the web app keeps no Lead table of its own. The template's lead score is a tool that the agent and a Skill call, and the convert-lead workflow is a package declaration that the app only starts through a [Fixed workflow route](external-apps.md#reads-and-writes-through-the-sdk).
|
|
34
|
+
|
|
35
|
+
Access stays in CI even when the app shows the screen. The BFF checks an Access Requirement before it calls CI, and CI then checks each record again. A page can use the same requirement to hide a button, but the server check makes the decision.
|
|
36
|
+
|
|
37
|
+
Data that no CI user, Studio page or agent reads stays in the app. The template's intake form keeps its requests in an in-memory store behind the app API, and you replace that store with a database. When the customer's database must stay the source of truth, the records stay there too. A Gateway then exposes only what CI needs: remote resources that an Organization admin maps onto a Knowledge schema through a [connector](../data/connectors.md), dataset queries, and business operations that agents call as tools. When agents need only a few fields, keep personal data in the app and put only the needed fields into Knowledge.
|
|
38
|
+
|
|
39
|
+
Secrets stay on the app's server. The browser gets no CI token and no client secret, and in the template `NEXT_PUBLIC_APPLICATION_ID` is the only value it sees. The sign-in secret, the session secrets and the Server Credential live in the server's environment. Deploy and management tokens never reach the web app. A secret that code inside CI needs, such as an API key for a third-party service, is a `secret` package variable that a Tenant admin sets in the Organization variables after deploy, as [Extensions](extensions.md) describes. An Organization admin can read the variables but cannot change them.
|
|
40
|
+
|
|
41
|
+
## Declare the app
|
|
42
|
+
|
|
43
|
+
A package declares the app as an OAuth client with `declareExternalApplication`. The template's declaration, with a placeholder origin:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
export const acmeApplication = declareExternalApplication({
|
|
47
|
+
definition: {
|
|
48
|
+
allowedOrigins: ["https://app.example.com"],
|
|
49
|
+
applicationType: "confidential",
|
|
50
|
+
audience: "https://app.example.com",
|
|
51
|
+
lifecycle: { deployMode: "upsert", readonly: true },
|
|
52
|
+
postLogoutRedirectUris: ["https://app.example.com/signed-out"],
|
|
53
|
+
// No OAuth scopes: `access.ts` grants the app gate and caps the tokens.
|
|
54
|
+
redirectUris: ["https://app.example.com/api/auth/callback"],
|
|
55
|
+
},
|
|
56
|
+
manifest: { fqn: applicationFqn, version: VERSION },
|
|
57
|
+
...
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The declaration has no `scopes` field. What a user may do through the app comes from grants that hold the app gate and from the Max Privileges declared for the app's user tokens, both described on [Grants and permissions](../platform/access.md).
|
|
62
|
+
|
|
63
|
+
The CLI writes the app's connection values into an env file: `CI_ISSUER`, `CI_AUDIENCE`, `CI_APPLICATION_ID`, `CI_CLIENT_ID`, `CI_ORGANIZATION_ID`, `CI_JWKS_URL` and, when a secret is known, `CI_CLIENT_SECRET`. Server code reads them with `readApplicationEnrollment(process.env)` and never names them one by one. Two commands write these values, and the right one depends on who created the app:
|
|
64
|
+
|
|
65
|
+
| The app was created by | Command | Client secret |
|
|
66
|
+
| -------------------------- | ----------------------------------------------------- | ----------------------------------------------------------------- |
|
|
67
|
+
| A package, as the template | `ci apps env <application> --env-file <path>` | Left out; issue one with `ci apps rotate-secret <application-id>` |
|
|
68
|
+
| The CLI | `ci apps enroll --fqn <fqn> --redirect-uri <url> ...` | Written by the first confidential create or by `--rotate-secret` |
|
|
69
|
+
|
|
70
|
+
`ci apps env` accepts an Application Id or an FQN and changes nothing in CI. `ci apps enroll` creates or replaces an app by FQN, so it refuses an app that a package declared. The Application Id is the registration id (the `app_id` claim), and the Client Id is the OAuth `client_id`. They are different values, and every CLI output names both.
|
|
71
|
+
|
|
72
|
+
Next to the enrollment, the template reads `APP_ORIGIN` (the public HTTPS origin), `CI_TENANT_URL`, `SESSION_SECRETS` (comma-separated, current secret first, so you can rotate) and `NEXT_PUBLIC_APPLICATION_ID`, the only value the browser sees.
|
|
73
|
+
|
|
74
|
+
## After install
|
|
75
|
+
|
|
76
|
+
Installing the package registers the app as a confidential client with no secret. Users can sign in and see data only after the first five steps below; the sixth gives refused users a readable page. Run the CLI steps as an Organization admin, signed in with `ci login <api-url> --organization <organization-id>`.
|
|
77
|
+
|
|
78
|
+
1. Write the connection values with `ci apps env <application> --env-file apps/web/.env.local`. The command leaves out the client secret and prints the Application Id that the next step needs.
|
|
79
|
+
2. Rotate the sign-in secret with `ci apps rotate-secret <application-id>`, or with "Rotate secret" on the Dashboard External Apps page. CI shows the secret once, so store it as `CI_CLIENT_SECRET` at once. Each rotation ends the previous secret. Run `ci apps env` first: when the env file holds a secret for a different Client Id, `ci apps env` refuses to write the file.
|
|
80
|
+
3. Create a Server Credential for the app's server with `ci apps credentials upsert <application> --name <name> --env-file <server-env-file>`. Use a separate env file, because this file also stores its secret as `CI_CLIENT_SECRET`.
|
|
81
|
+
4. Add users to the Group whose grant holds the app gate. In the template that is Sales or Sales managers. The package declares the Groups and leaves them empty.
|
|
82
|
+
5. Give the app server read access to Leads. The template's Read Port reads with the server's own credential, and the package declares no grant for it.
|
|
83
|
+
6. Set `errorPath` on the federated auth so that a refused sign-in lands on a page instead of a JSON answer. The callback reports `access_denied`, `authorization_failed`, `invalid_state`, `invalid_request`, `invalid_identity` or `user_auth_unavailable`.
|
|
84
|
+
|
|
85
|
+
The app holds two different secrets. The sign-in secret from step 2 belongs to the OAuth client and only signs users in. The Server Credential from step 3, whose secret starts with `dsc_`, authenticates the server's own calls in service mode and acts with the Access Grants given to the app's server. CI refuses the sign-in secret on a server call, so a server that reads without a user needs the Server Credential.
|
|
86
|
+
|
|
87
|
+
> **Warning:** `ci apps enroll`, `ci apps redirect-uris` and `ci apps origins` refuse an app
|
|
88
|
+
> that a package declared. Change its redirect URIs and origins in
|
|
89
|
+
> `declareExternalApplication` and deploy a new package release.
|
|
90
|
+
|
|
91
|
+
## Sessions
|
|
92
|
+
|
|
93
|
+
Each deployment picks one session mode:
|
|
94
|
+
|
|
95
|
+
| Mode | Who owns the login | Where the session lives |
|
|
96
|
+
| ------------------------ | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------- |
|
|
97
|
+
| Local | The app, with Better Auth email and password. A local user is not a CI member and gets no CI access. | The app |
|
|
98
|
+
| Federated, sealed cookie | CI | An encrypted, signed cookie. The template uses this mode. |
|
|
99
|
+
| Federated, session store | CI | Rows in the app's database |
|
|
100
|
+
|
|
101
|
+
The whole sign-in setup of the template is one call:
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
const auth = createFederatedAuth({
|
|
105
|
+
...enrollment,
|
|
106
|
+
applicationOrigin: env.APP_ORIGIN,
|
|
107
|
+
session: { kind: "sealed_cookie", secrets: env.SESSION_SECRETS }
|
|
108
|
+
})
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`createFederatedAuth` handles the PKCE login, the callback, session reads and logout under `/api/auth`. Register `<origin>/api/auth/callback` as a redirect URI and the origin as an allowed origin. A package-declared app lists both in its declaration; an app created with the CLI adds them with `ci apps redirect-uris add` and `ci apps origins add`. The session cookie is `__Host-ci-federated` with `Secure`, `HttpOnly` and `SameSite=Lax`, which is why `APP_ORIGIN` must use HTTPS. On a laptop without a TLS proxy, `allowLoopbackHttp: true` lets `http://localhost:3000` work with a cookie named `ci-federated` and no `Secure` flag. Keep that option off in production.
|
|
112
|
+
|
|
113
|
+
Access tokens always live 300 seconds, and every setup renews them with no redirect. A confidential client that passes its `clientSecret` to `createFederatedAuth` renews in each session lookup: when a token has 30 seconds or less left, the lookup gets a new one first. The renewed token stays in process memory and the cookie is written once at sign-in, so a server restart only triggers another renewal. A public client renews too: with the session store in each lookup, and with the sealed cookie only in the session route and the Renew route.
|
|
114
|
+
|
|
115
|
+
CI ends the user's sign-in to the app at the Idle limit, 14 days after the last renewal, and never after the user's CI session. So a user who comes back within 14 days stays signed in. `sessionTtlSeconds` is optional. Leave it out and the session follows that rule; set it, from 300 to 2592000 seconds (30 days), for a shorter limit counted from sign-in.
|
|
116
|
+
|
|
117
|
+
> **Warning:** A public client with the sealed cookie cannot renew in a session lookup,
|
|
118
|
+
> because a lookup cannot rewrite the cookie. After the access token expires,
|
|
119
|
+
> `getSession`, `getAccessToken` and `getEntityContext` throw
|
|
120
|
+
> `RenewalRequiredError`. A page sends the browser to `error.renewUrl`, the
|
|
121
|
+
> Renew route, which renews and comes back to the page. An app route answers
|
|
122
|
+
> `401` with the nested `renewal_required` body, as the SDK routes do; the
|
|
123
|
+
> client SDK runtime `fetch` then reads the session and repeats the call once.
|
|
124
|
+
> The client SDK also renews an open page on a timer. A confidential client and
|
|
125
|
+
> the session store need none of this.
|
|
126
|
+
|
|
127
|
+
After each start, the first signed-in request also reads CI's token key set. Call `auth.warm?.()` at boot, for example in Next.js `instrumentation.ts` `register`, without waiting for it before the server starts. It reads the key set into the SDK's cache, never rejects, and resolves `{ ok: false, error }` when CI does not answer; the first request then reads the key set itself, as without a warm-up.
|
|
128
|
+
|
|
129
|
+
A revoked grant reaches the app at the next renewal, so within 300 seconds. It reaches the app at once when a forwarded CI answer is a `401` or carries a changed `x-access-version`, which `auth.observeCiResponse` watches for. A user who signs in without a grant that holds the app gate does not bounce straight back with `access_denied`. CI first shows its own access-denied page with "Switch account" and "Back to the application".
|
|
130
|
+
|
|
131
|
+
> **Note:** Consent follows the app's `applicationConsent` (`inherit`, `ask` or `skip`),
|
|
132
|
+
> and `inherit` uses the Organization default. If the browser already has a CI
|
|
133
|
+
> session cookie, CI issues the code silently under both `ask` and `skip`, so a
|
|
134
|
+
> tester who is signed in to CI never sees the consent panel.
|
|
135
|
+
|
|
136
|
+
## The BFF pattern
|
|
137
|
+
|
|
138
|
+
The browser never holds a CI token. It calls same-origin `/api/*` routes, and the app's server keeps the session and calls CI with the user's delegated token:
|
|
139
|
+
|
|
140
|
+
```mermaid
|
|
141
|
+
sequenceDiagram
|
|
142
|
+
participant B as Browser
|
|
143
|
+
participant F as BFF (app server)
|
|
144
|
+
participant C as CI
|
|
145
|
+
B->>F: GET /api/... with the sealed session cookie
|
|
146
|
+
F->>F: Open session, check the Access Requirement
|
|
147
|
+
F->>C: GET /application/v1/... with the delegated token and x-organization-id
|
|
148
|
+
C->>C: Check grants, Max Privileges and policies per record
|
|
149
|
+
C-->>F: Records the user may see
|
|
150
|
+
F-->>B: JSON, no token
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
`createExternalApplicationBffNextHandlers` mounts federated auth, the resource proxy, capability forwarding and Realtime in one call:
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
handlers: createExternalApplicationBffNextHandlers({
|
|
157
|
+
auth: ci.auth,
|
|
158
|
+
capabilities: { basePath: "/api", tenantUrl: ci.tenantUrl },
|
|
159
|
+
ciResources: {
|
|
160
|
+
bindings: [
|
|
161
|
+
{ definition: leadContract, schemaFqn: leadSchemaFqn },
|
|
162
|
+
{ definition: opportunityContract, schemaFqn: opportunitySchemaFqn },
|
|
163
|
+
],
|
|
164
|
+
invalidate: nextInvalidate,
|
|
165
|
+
organizationId: ci.organizationId,
|
|
166
|
+
tenantUrl: ci.tenantUrl,
|
|
167
|
+
},
|
|
168
|
+
publicOrigin: ci.publicOrigin,
|
|
169
|
+
realtime: { organizationId: ci.organizationId, revalidate: createRealtimeRevalidateHandler,
|
|
170
|
+
secrets: ci.sessionSecrets, tenantUrl: ci.tenantUrl },
|
|
171
|
+
}),
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Each `ciResources` binding mounts one resource proxy for an entity contract. The BFF checks a `read` and a `write` Access Requirement against the app's slice of the user's access, `core.platform.knowledge` for both by default, and CI then checks each record again. Capability forwarding covers `context`, `knowledge`, `agents`, `conversations`, `skills`, `workflows` and `runs/*`.
|
|
175
|
+
|
|
176
|
+
The template mounts three route files:
|
|
177
|
+
|
|
178
|
+
| Route | Handler |
|
|
179
|
+
| ------------------------------------- | ----------------------------------------------------------------------- |
|
|
180
|
+
| `app/api/[...path]/route.ts` | The CI BFF: auth, resources, Realtime ticket |
|
|
181
|
+
| `app/api/leads/[id]/convert/route.ts` | Convert a Lead through a Fixed workflow route |
|
|
182
|
+
| `app/api/app/[[...path]]/route.ts` | The app's own Effect `HttpApi`, with OpenAPI at `/api/app/openapi.json` |
|
|
183
|
+
|
|
184
|
+
A server call to CI uses one of three identities. A delegated call, the default, uses the signed-in user's token, and the template's convert route works this way. `runAsApplication` switches one call to the app's confidential credentials and needs an audit subject. A service-mode client (`createServerClient({ authentication: { mode: "service", credentials } })`) always uses the app's Server Credential and gets the same answer for every user, which is what the template's Read Port does.
|
|
185
|
+
|
|
186
|
+
## Reads and writes through the SDK
|
|
187
|
+
|
|
188
|
+
In the browser, the entity hooks of `external-apps-client-sdk-react` read and write through the BFF. Writes are optimistic by default: every view shows the new value at once, and a refused write rolls back and calls `onWriteFailed`, which `ciWriteFailedToast()` from `ui-react` turns into a toast. Pass `optimistic: false` to a hook to opt out. A write in the `uncertain` state was sent without an answer, so CI may have saved it. `resubmit()` sends the same action with the same idempotency key, and a new `submit()` starts a new action.
|
|
189
|
+
|
|
190
|
+
File uploads skip the BFF. The BFF asks CI for an upload slot, the browser sends the bytes straight to storage, and the record write then references `{ attachment: { upload } }`.
|
|
191
|
+
|
|
192
|
+
A business action with side effects goes through a Fixed workflow route. The server owns the workflow target and the browser only sends input:
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
const handle = createFixedWorkflowRoute<{ leadId: string }, { leadId: string }>({
|
|
196
|
+
...options,
|
|
197
|
+
idempotencyKey: ({ leadId }) => `convert-lead:${leadId}`,
|
|
198
|
+
requirement: convertLeadRequirement,
|
|
199
|
+
resourceId: "leads",
|
|
200
|
+
validate: (body, { leadId }) => { ... },
|
|
201
|
+
});
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
The route rejects any `workflowId` or `workflowFqn` in the browser input, checks the Access Requirement, stamps `x-organization-id` from the session and returns `{ runId }`. The template's tests prove each refusal: an injected `workflowId` gets 400, no session gets 401, a missing capability gets 403, and two clicks reuse the idempotency key `convert-lead:<id>`.
|
|
205
|
+
|
|
206
|
+
The workflow must have an External application trigger bound to the app and an audience that includes it (`audience: { applications: [application] }`). A run acts as the identity that started it. A delegated call runs the workflow as the signed-in user. A call in service mode or with `runAsApplication` has no person, so the run uses the workflow's run-as service principal. CI publishes a triggered workflow only when it names one, which is why the template ships `convertLeadRunner`.
|
|
207
|
+
|
|
208
|
+
A run returns its `runId` at once. The template's `convertLeadTask` posts the convert route, follows the run with `runs.follow({ runId })` until it ends (10 minutes by default), and then invalidates the entity reads so every view reloads.
|
|
209
|
+
|
|
210
|
+
## Server cache and invalidation
|
|
211
|
+
|
|
212
|
+
The SDK ships no cached read. The app writes the `"use cache"` directive itself, and `cacheCiRead(client, { schema, id?, filter?, life? })` adds the cache tags and a lifetime (by default stale 60, revalidate 60 and expire 86400 seconds). The template's Read Port is the one place that uses it:
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
const lead = async (id: string) => {
|
|
216
|
+
"use cache"
|
|
217
|
+
cacheCiRead(getRuntime().service, { id, schema: leadSchemaFqn })
|
|
218
|
+
return await uncached().lead(id)
|
|
219
|
+
}
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
`cacheCiRead` only type-checks with a service-mode client, so a user-session client does not compile. A shared cache must never hold one user's view, and user-scoped reads stay in TanStack Query in the browser. For the same reason the Read Port ignores each user's visibility, so give it only data that every signed-in user may see.
|
|
223
|
+
|
|
224
|
+
Tags cover all CI reads, a schema, a list, one entity and one Realtime topic. A write expires the record's entity tag and the list tag, and leaves cached reads of other records alone. The cache learns about a change in one of three ways:
|
|
225
|
+
|
|
226
|
+
```mermaid
|
|
227
|
+
flowchart LR
|
|
228
|
+
W1[Write through the BFF] --> N[nextInvalidate]
|
|
229
|
+
W2[Write outside the BFF] --> RT[Realtime change in an open tab] --> RV[Revalidate route]
|
|
230
|
+
W3[Effect server write] --> L[CacheInvalidation.layerNext on the fiber]
|
|
231
|
+
N --> T[Entity, list and topic tags expire]
|
|
232
|
+
RV --> T
|
|
233
|
+
L --> T
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
> **Warning:** An Effect `ServerClient` write without `CacheInvalidation` on its fiber
|
|
237
|
+
> expires nothing and logs no error. Providing `layerNext` into
|
|
238
|
+
> `layerServerClient` does not reach the writes; merge it into the runtime
|
|
239
|
+
> instead.
|
|
240
|
+
|
|
241
|
+
Next's built-in cache store is in memory, so an invalidation reaches only the instance that received it. Other instances serve old data until the lifetime ends. Configure a shared cache store if the demo runs on more than one instance.
|
|
242
|
+
|
|
243
|
+
## Realtime
|
|
244
|
+
|
|
245
|
+
Realtime keeps open pages current without polling. The browser asks the BFF for a ticket with `POST /api/realtime/ticket`, the BFF gets it from CI with the user's delegated token, and the browser opens the event stream with that single-use ticket. The user's token never reaches the browser.
|
|
246
|
+
|
|
247
|
+
A topic is one entity schema, optionally filtered by one field: `{ schema, filter?: { field, eq } }`. Events carry ids only, and the page refetches. One connection per tab carries all of its topics. A `reset` event means the client missed too much and must refetch everything; the first open of a connection also resyncs once, so expect one extra refetch per page load. Pass `onReset`, or a change can be lost. `onAccessChanged` fires when the user's access changes.
|
|
248
|
+
|
|
249
|
+
When the BFF has `secrets`, each ticket answer includes a sealed topic grant, valid for 10 minutes and bound to the session. The revalidate route `POST /api/realtime/revalidate` accepts changes only on topics in that grant, which is how a change written outside the BFF expires the server cache. The client renews the ticket after 8 minutes.
|
|
250
|
+
|
|
251
|
+
To show this in a demo, open `/crm` in two windows and edit a Lead as a Sales manager in one of them. The other window updates without a reload.
|
|
252
|
+
|
|
253
|
+
> **Warning:** Do not open the stream with a hand-written `EventSource`. It cannot send the
|
|
254
|
+
> `Authorization` and `X-Organization-Id` headers that CI needs, and the failure
|
|
255
|
+
> is silent: the connection opens and no event arrives. The SDK's Realtime
|
|
256
|
+
> client uses tickets instead.
|
|
257
|
+
|
|
258
|
+
## Effect and NestJS flavors
|
|
259
|
+
|
|
260
|
+
Every SDK has a Promise facade at its root import and an Effect API at `/effect`. In the Effect API, CI errors are typed failures instead of `{ ok: false }` values. `effect` is a peer dependency, so the app holds one copy. In the template, the server SDK's `./next` entry is imported only in `apps/web/src/server`; packages use `./effect` and stay independent of the host.
|
|
261
|
+
|
|
262
|
+
| | Template | Effect demo | NestJS demo |
|
|
263
|
+
| --------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
|
|
264
|
+
| Direction | Outbound | Outbound and inbound | Inbound |
|
|
265
|
+
| UI and login | Next.js, federated sealed cookie | React client, federated session store; the same Lead views run over local SQL, CI through the server, or CI direct | None |
|
|
266
|
+
| Convert lead | A CI workflow | A Gateway operation that creates one Opportunity and marks the Lead converted, idempotent by `x-idempotency-key` | Not included |
|
|
267
|
+
| CI entry points | BFF routes | BFF and Gateway | One `Greetings` service behind an HTTP route, an operation binding and an AI SDK tool |
|
|
268
|
+
|
|
269
|
+
A Gateway lists exactly what CI may discover:
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
const gateway = defineGateway({
|
|
273
|
+
id: "crm",
|
|
274
|
+
version: "1.0.0",
|
|
275
|
+
knowledge: [{ resource: leadResource, access: "read_write" }],
|
|
276
|
+
datasets: [leadPipeline],
|
|
277
|
+
operationDomains: [crmOperations]
|
|
278
|
+
})
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
Adapters for Next, Web Fetch, Express and Nest serve the same gateway kernel. A gateway exposes remote resources and never creates CI schemas: an Organization admin connects them through a Knowledge connector and maps fields onto an Organization schema. In NestJS, `bindNestOperation` binds an existing service method without decorators, and the CI entry point does not inherit your HTTP guards, pipes or interceptors, so each entry point keeps its own checks. Start Nest with `NestFactory.create(AppModule, { bodyParser: false })` so the SDK parses bounded JSON, and keep a global prefix off the gateway's `/v1/*` routes.
|
|
282
|
+
|
|
283
|
+
## Related pages
|
|
284
|
+
|
|
285
|
+
- [Grants and permissions](../platform/access.md)
|
|
286
|
+
- [SDKs](sdks.md)
|
|
287
|
+
- [Extensions](extensions.md)
|
|
288
|
+
- [The template](../template/index.md)
|
|
289
|
+
- [Knowledge](../data/knowledge.md)
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# Infrastructure
|
|
2
|
+
|
|
3
|
+
The resources that a CI deployment runs, what each one is for, and how the Amazon EKS blueprint maps them to AWS services.
|
|
4
|
+
|
|
5
|
+
The CI deployment that your demo connects to provides every resource on this page. You do not provision or run any of them. This page explains what runs where, so that you know what sits behind the API when your package or your web app calls CI. The [Platform architecture](../platform/architecture.md) page introduces the same parts from the builder's side.
|
|
6
|
+
|
|
7
|
+
## Runtime resources
|
|
8
|
+
|
|
9
|
+
```mermaid
|
|
10
|
+
flowchart LR
|
|
11
|
+
subgraph outside["Outside the CI deployment"]
|
|
12
|
+
browser["Browser"]
|
|
13
|
+
studio["Studio desktop app"]
|
|
14
|
+
webapp["Your web app (BFF)"]
|
|
15
|
+
end
|
|
16
|
+
subgraph deployment["CI deployment"]
|
|
17
|
+
gateway["Gateway"]
|
|
18
|
+
dashboard["Dashboard and Studio install page"]
|
|
19
|
+
api["Backend API"]
|
|
20
|
+
workers["Background and interactive workers"]
|
|
21
|
+
compute["Compute"]
|
|
22
|
+
media["Media"]
|
|
23
|
+
pg[("PostgreSQL with pgvector")]
|
|
24
|
+
broker["Message broker"]
|
|
25
|
+
storage[("Object storage")]
|
|
26
|
+
end
|
|
27
|
+
ai["AI model providers"]
|
|
28
|
+
browser --> gateway
|
|
29
|
+
studio --> gateway
|
|
30
|
+
webapp -->|"Application API"| gateway
|
|
31
|
+
gateway --> dashboard
|
|
32
|
+
gateway --> api
|
|
33
|
+
gateway --> media
|
|
34
|
+
api --> pg
|
|
35
|
+
workers --> pg
|
|
36
|
+
api -->|"wake signals"| broker
|
|
37
|
+
broker --> workers
|
|
38
|
+
broker -->|"Compute jobs"| compute
|
|
39
|
+
compute -->|"results"| api
|
|
40
|
+
compute -->|"presigned URLs"| storage
|
|
41
|
+
browser -->|"signed upload"| storage
|
|
42
|
+
media -->|"signed source links"| storage
|
|
43
|
+
workers --> ai
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
| Resource | What it is for |
|
|
47
|
+
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
48
|
+
| Gateway | Receives all HTTP traffic and routes it to the Dashboard, the backend API and Media. |
|
|
49
|
+
| Dashboard | A static web app that calls the backend API for all its data. It also serves the public Studio install page of each Organization, where people download Studio and connect it with one button. |
|
|
50
|
+
| Backend API | Serves every HTTP route that the Dashboard, Studio, the CLI and your app call. It stores long work and returns at once; workers run that work. |
|
|
51
|
+
| Workers | Background workers run long jobs, and interactive workers run the agent and tool work that users wait for. |
|
|
52
|
+
| Compute | Runs transcription, transcoding and conversion from a queue. Each capability has its own slots, so a long transcode does not block transcription. |
|
|
53
|
+
| Media | Serves file bytes and image transforms from URLs that the backend signs. No file byte passes through a backend endpoint. |
|
|
54
|
+
| PostgreSQL | Holds the authoritative data in two databases: one for application data, Knowledge and queued work, and one for datasets. The pgvector extension stores embeddings for semantic search. |
|
|
55
|
+
| Message broker | Carries wake signals from the API to the workers, broadcast events between backend processes, and the job queues of Compute. A wake signal is only a hint: workers find their work in PostgreSQL. |
|
|
56
|
+
| Object storage | Holds every file. Studio installers and updates, and archived rows, have their own stores next to the store for application files. |
|
|
57
|
+
| Cache | There is no separate cache service. Each backend process keeps hot reads, such as schemas, policies and settings, in memory, and broadcast events clear stale entries in every process. |
|
|
58
|
+
| Email provider | Sends platform email. Every message goes through a durable queue in PostgreSQL before the provider receives it. |
|
|
59
|
+
| AI model providers | External model services that agents, Skills and embeddings call. A Tenant admin chooses the available models; the blueprints do not provision them. |
|
|
60
|
+
| Logs | Every backend process and Compute write structured logs, and the CI deployment forwards them to a log service. |
|
|
61
|
+
|
|
62
|
+
## What this means for your code
|
|
63
|
+
|
|
64
|
+
File uploads go straight from the browser to object storage. Your BFF asks CI for an upload slot, and the browser sends the bytes with one signed PUT. A Knowledge file field accepts a file up to its `maxBytes`, and never above the limit of the CI deployment, which is 1 GiB by default and at most 2 GiB. The browser must send the URL, the method and every header that CI returns. Your BFF never streams file bytes. The [External apps](external-apps.md) page shows the flow in the template.
|
|
65
|
+
|
|
66
|
+
Event streams, such as a chat answer, stay open through a heartbeat. The gateway closes a request that sends no bytes for 120 seconds and caps every response at 10 minutes. The backend sends a comment line on every event stream each 20 seconds, so a slow model does not cut the stream. If your BFF forwards a stream, pass each chunk on as it arrives so the heartbeat reaches the browser.
|
|
67
|
+
|
|
68
|
+
Long work is asynchronous. When your app starts an agent run or a workflow, the API stores the run and returns, and a worker runs it. A slow broker delays work, because workers always read their work from PostgreSQL.
|
|
69
|
+
|
|
70
|
+
Configuration changes reach every backend process. When a schema, a policy or a setting changes, a broadcast event clears the cached copy in each process after the write commits. If that event is lost, the cached copy still expires after a short time limit.
|
|
71
|
+
|
|
72
|
+
## The Amazon EKS blueprint
|
|
73
|
+
|
|
74
|
+
A blueprint is the infrastructure code and the deployment configuration that turn the resources above into cloud services. Running CI deployments use the Amazon Elastic Kubernetes Service (EKS) blueprint. Blueprints also exist for Azure Kubernetes Service (AKS) and Azure Container Apps (ACA).
|
|
75
|
+
|
|
76
|
+
The EKS blueprint has three layers. Infrastructure as code creates the AWS foundation: the network, the cluster, the image registry, DNS, and the managed databases and buckets of each CI deployment. Helm charts describe the workloads, and Argo CD keeps the cluster in line with them. Release pins name the exact image of each service, so a new CI release is a change of pins that Argo CD rolls out.
|
|
77
|
+
|
|
78
|
+
```mermaid
|
|
79
|
+
flowchart LR
|
|
80
|
+
users["Browser, Studio and your web app"]
|
|
81
|
+
cdn["Amazon CloudFront"]
|
|
82
|
+
nlb["Network Load Balancer"]
|
|
83
|
+
subgraph eks["Amazon EKS cluster"]
|
|
84
|
+
gateway["Envoy Gateway"]
|
|
85
|
+
dashboard["Dashboard"]
|
|
86
|
+
api["Backend API"]
|
|
87
|
+
workers["Workers"]
|
|
88
|
+
compute["Compute"]
|
|
89
|
+
media["Media"]
|
|
90
|
+
rabbit["RabbitMQ"]
|
|
91
|
+
end
|
|
92
|
+
rds[("Amazon RDS for PostgreSQL or CloudNativePG")]
|
|
93
|
+
s3[("Amazon S3")]
|
|
94
|
+
ses["Amazon SES"]
|
|
95
|
+
secrets["AWS Secrets Manager"]
|
|
96
|
+
ecr["Amazon ECR"]
|
|
97
|
+
users --> nlb
|
|
98
|
+
users -->|"media URLs"| cdn
|
|
99
|
+
cdn --> nlb
|
|
100
|
+
nlb --> gateway
|
|
101
|
+
gateway --> dashboard
|
|
102
|
+
gateway --> api
|
|
103
|
+
gateway --> media
|
|
104
|
+
api --> rds
|
|
105
|
+
workers --> rds
|
|
106
|
+
api --> rabbit
|
|
107
|
+
rabbit --> workers
|
|
108
|
+
rabbit --> compute
|
|
109
|
+
compute --> s3
|
|
110
|
+
media --> s3
|
|
111
|
+
eks -->|"email"| ses
|
|
112
|
+
secrets -.->|"credentials"| eks
|
|
113
|
+
ecr -.->|"images"| eks
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
| Resource | AWS service |
|
|
117
|
+
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
118
|
+
| Containers | Amazon EKS with a managed node group. Images come from Amazon Elastic Container Registry (ECR). |
|
|
119
|
+
| Gateway | Envoy Gateway behind a Network Load Balancer. Amazon Route 53 holds the DNS records, and cert-manager issues the certificates. |
|
|
120
|
+
| PostgreSQL | Amazon Relational Database Service (RDS) for PostgreSQL in private subnets, or CloudNativePG in the cluster on encrypted Amazon Elastic Block Store (EBS) volumes. Each CI deployment chooses one. |
|
|
121
|
+
| Message broker | RabbitMQ in the cluster. |
|
|
122
|
+
| Object storage | Amazon Simple Storage Service (S3) buckets for the files and the archive of each CI deployment, and shared buckets for Studio releases. |
|
|
123
|
+
| Media CDN | Amazon CloudFront in front of Media. |
|
|
124
|
+
| Email | Amazon Simple Email Service (SES). |
|
|
125
|
+
| Secrets | AWS Secrets Manager. External Secrets copies the values into the cluster. |
|
|
126
|
+
| Workload identity | EKS Pod Identity, so pods reach S3 and Secrets Manager without stored keys. |
|
|
127
|
+
| Logs and metrics | Datadog receives the logs. Amazon CloudWatch Container Insights collects the cluster metrics. |
|
|
128
|
+
|
|
129
|
+
One EKS cluster can host several CI deployments. Each CI deployment has its own Kubernetes namespace with its own backend, Compute, database, message broker and storage, and it can hold several Organizations. All CI deployments on the cluster share the gateway and Media.
|
|
130
|
+
|
|
131
|
+
## Next pages
|
|
132
|
+
|
|
133
|
+
- [Platform architecture](../platform/architecture.md): Tenants, Organizations, surfaces and the three integration models.
|
|
134
|
+
- [External apps](external-apps.md): Build the web app that calls CI, including direct uploads.
|
|
135
|
+
- [Knowledge](../data/knowledge.md): Records, schemas and semantic search on PostgreSQL.
|