@collective-intelligence/ai 0.0.0-stage → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/AGENTS.md +52 -0
  2. package/README.md +462 -2
  3. package/dist/api/access-check.d.ts +18 -0
  4. package/dist/api/answer-sources.d.ts +48 -0
  5. package/dist/api/attachments-api.d.ts +187 -0
  6. package/dist/api/catalog-api.d.ts +408 -0
  7. package/dist/api/chat-api.d.ts +2401 -0
  8. package/dist/api/chat-surface-api.d.ts +4186 -0
  9. package/dist/api/compaction.d.ts +52 -0
  10. package/dist/api/conversations.d.ts +107 -0
  11. package/dist/api/errors.d.ts +117 -0
  12. package/dist/api/feedback-api.d.ts +185 -0
  13. package/dist/api/files.d.ts +22 -0
  14. package/dist/api/ids.d.ts +33 -0
  15. package/dist/api/index.d.ts +21 -0
  16. package/dist/api/intents-api.d.ts +65 -0
  17. package/dist/api/place-context.d.ts +34 -0
  18. package/dist/api/projects-api.d.ts +718 -0
  19. package/dist/api/speech-api.d.ts +345 -0
  20. package/dist/api/transcript.d.ts +260 -0
  21. package/dist/api/turns.d.ts +196 -0
  22. package/dist/api.d.ts +21 -0
  23. package/dist/api.js +1 -0
  24. package/dist/domain/access.d.ts +29 -0
  25. package/dist/domain/context-trail.d.ts +65 -0
  26. package/dist/domain/data-parts.d.ts +247 -0
  27. package/dist/domain/errors.d.ts +28 -0
  28. package/dist/domain/index.d.ts +14 -0
  29. package/dist/domain/intents.d.ts +101 -0
  30. package/dist/domain/message.d.ts +173 -0
  31. package/dist/domain/place.d.ts +17 -0
  32. package/dist/domain/runtime-value.d.ts +16 -0
  33. package/dist/domain-50vzrrp9.js +2 -0
  34. package/dist/domain-5fpd4fte.js +1 -0
  35. package/dist/domain-9wzbv87n.js +2 -0
  36. package/dist/domain-g97xs965.js +2 -0
  37. package/dist/domain-hk3yw2m7.js +1 -0
  38. package/dist/domain-qyts6dgz.js +0 -0
  39. package/dist/domain-s07s1ry1.js +2 -0
  40. package/dist/domain.d.ts +14 -0
  41. package/dist/domain.js +1 -0
  42. package/dist/headless/access/access-store.d.ts +28 -0
  43. package/dist/headless/access/visibility.d.ts +24 -0
  44. package/dist/headless/blocked-state.d.ts +21 -0
  45. package/dist/headless/chat-registry.d.ts +63 -0
  46. package/dist/headless/chat-session-provider.d.ts +109 -0
  47. package/dist/headless/chat-surface.d.ts +4210 -0
  48. package/dist/headless/host-ports.d.ts +146 -0
  49. package/dist/headless/index.d.ts +33 -0
  50. package/dist/headless/intents/card-ends.d.ts +22 -0
  51. package/dist/headless/intents/intent-call.d.ts +28 -0
  52. package/dist/headless/intents/intents-provider.d.ts +108 -0
  53. package/dist/headless/intents/page-registry.d.ts +129 -0
  54. package/dist/headless/intents/use-intent-dispatch.d.ts +60 -0
  55. package/dist/headless/intents/use-intents.d.ts +11 -0
  56. package/dist/headless/intents/use-returned-intent-handle.d.ts +11 -0
  57. package/dist/headless/launch/chat-launch.d.ts +42 -0
  58. package/dist/headless/launch/launch-target.d.ts +25 -0
  59. package/dist/headless/launch/submit.d.ts +29 -0
  60. package/dist/headless/run-state.d.ts +16 -0
  61. package/dist/headless/sent-files.d.ts +20 -0
  62. package/dist/headless/server-started-turn-follow.proof.d.ts +26 -0
  63. package/dist/headless/session-machine.d.ts +745 -0
  64. package/dist/headless/trail/buffer.d.ts +48 -0
  65. package/dist/headless/trail/json-ld.d.ts +10 -0
  66. package/dist/headless/trail/switches.d.ts +10 -0
  67. package/dist/headless/trail/trail-provider.d.ts +53 -0
  68. package/dist/headless/transcript-messages.d.ts +26 -0
  69. package/dist/headless.d.ts +33 -0
  70. package/dist/headless.js +2 -0
  71. package/dist/transport/chat-client.d.ts +25 -0
  72. package/dist/transport/chat-transport.d.ts +57 -0
  73. package/dist/transport/index.d.ts +6 -0
  74. package/dist/transport/simulated-chat-transport.d.ts +39 -0
  75. package/dist/transport.d.ts +6 -0
  76. package/dist/transport.js +1 -0
  77. package/dist/views/assistant-sidebar/assistant-sidebar.d.ts +15 -0
  78. package/dist/views/assistant-sidebar/layout.d.ts +47 -0
  79. package/dist/views/assistant-sidebar/toggle.d.ts +14 -0
  80. package/dist/views/assistant-sidebar/use-shortcut.d.ts +11 -0
  81. package/dist/views/blocked/chat-blocked-state.d.ts +15 -0
  82. package/dist/views/chat-operations.d.ts +46 -0
  83. package/dist/views/chat-root.d.ts +14 -0
  84. package/dist/views/chat.d.ts +51 -0
  85. package/dist/views/composer/capability-picker.d.ts +77 -0
  86. package/dist/views/composer/capability-pickers.d.ts +24 -0
  87. package/dist/views/composer/chat-composer.d.ts +15 -0
  88. package/dist/views/composer/composer-picks.d.ts +31 -0
  89. package/dist/views/composer/composer-trail.d.ts +21 -0
  90. package/dist/views/composer/draft-attachments.d.ts +36 -0
  91. package/dist/views/composer/queued-messages.d.ts +9 -0
  92. package/dist/views/composer/send-menu.d.ts +11 -0
  93. package/dist/views/composer/slash-suggestions.d.ts +37 -0
  94. package/dist/views/composer/trail-chips.d.ts +15 -0
  95. package/dist/views/composer/voice-input/microphone.d.ts +14 -0
  96. package/dist/views/composer/voice-input/remote-transcription.d.ts +12 -0
  97. package/dist/views/composer/voice-input/use-voice-input.d.ts +30 -0
  98. package/dist/views/composer/voice-input/voice-input.d.ts +15 -0
  99. package/dist/views/dock/chat-dock.d.ts +57 -0
  100. package/dist/views/dock/dock-session.d.ts +22 -0
  101. package/dist/views/header/chat-header.d.ts +10 -0
  102. package/dist/views/header/compaction-controls.d.ts +17 -0
  103. package/dist/views/header/memory-switch.d.ts +16 -0
  104. package/dist/views/index.d.ts +58 -0
  105. package/dist/views/intents/form-fields.d.ts +38 -0
  106. package/dist/views/intents/intent-card.d.ts +61 -0
  107. package/dist/views/intents/intent-form.d.ts +23 -0
  108. package/dist/views/intents/intent-notices.d.ts +39 -0
  109. package/dist/views/intents/intent-trigger.d.ts +46 -0
  110. package/dist/views/intents/labels.d.ts +23 -0
  111. package/dist/views/labels/en.d.ts +3 -0
  112. package/dist/views/labels/index.d.ts +13 -0
  113. package/dist/views/labels/it.d.ts +3 -0
  114. package/dist/views/labels/types.d.ts +7 -0
  115. package/dist/views/launch/chat-launch-button.d.ts +21 -0
  116. package/dist/views/parts/answer-feedback.d.ts +26 -0
  117. package/dist/views/parts/evidence-part.d.ts +8 -0
  118. package/dist/views/parts/file-part.d.ts +8 -0
  119. package/dist/views/parts/image-generation-part.d.ts +9 -0
  120. package/dist/views/parts/image-generation.d.ts +84 -0
  121. package/dist/views/parts/intent-card-part.d.ts +8 -0
  122. package/dist/views/parts/memory-evidence-part.d.ts +7 -0
  123. package/dist/views/parts/message-parts.d.ts +21 -0
  124. package/dist/views/parts/question-part.d.ts +8 -0
  125. package/dist/views/parts/read-aloud.d.ts +23 -0
  126. package/dist/views/parts/reasoning-part.d.ts +8 -0
  127. package/dist/views/parts/steering-message-part.d.ts +7 -0
  128. package/dist/views/parts/text-part.d.ts +4 -0
  129. package/dist/views/parts/tool-part.d.ts +11 -0
  130. package/dist/views/parts/types.d.ts +103 -0
  131. package/dist/views/parts/use-read-aloud.d.ts +13 -0
  132. package/dist/views/run-trace/message-run.d.ts +17 -0
  133. package/dist/views/run-trace/run-stream.d.ts +128 -0
  134. package/dist/views/run-trace/run-trace-parts.d.ts +26 -0
  135. package/dist/views/run-trace/run-trace.d.ts +31 -0
  136. package/dist/views/sidebar/conversation-dialogs.d.ts +38 -0
  137. package/dist/views/sidebar/conversation-row.d.ts +23 -0
  138. package/dist/views/sidebar/conversation-sidebar.d.ts +10 -0
  139. package/dist/views/sidebar/date-groups.d.ts +12 -0
  140. package/dist/views/sidebar/history-filter.d.ts +57 -0
  141. package/dist/views/sidebar/projects/project-dialogs.d.ts +40 -0
  142. package/dist/views/sidebar/projects/project-files.d.ts +16 -0
  143. package/dist/views/sidebar/projects/project-groups.d.ts +19 -0
  144. package/dist/views/sidebar/projects/project-view.d.ts +21 -0
  145. package/dist/views/sidebar/projects/projects-section.d.ts +21 -0
  146. package/dist/views/sidebar/projects/use-chat-projects.d.ts +32 -0
  147. package/dist/views/slots.d.ts +148 -0
  148. package/dist/views/transcript/chat-transcript.d.ts +13 -0
  149. package/dist/views/transcript/sent-trail.d.ts +13 -0
  150. package/dist/views/transcript/use-image-reload.d.ts +16 -0
  151. package/dist/views.d.ts +58 -0
  152. package/dist/views.js +3 -0
  153. package/docs/guide/ai/index.md +377 -0
  154. package/docs/guide/ai/studio.md +245 -0
  155. package/docs/guide/data/connectors.md +267 -0
  156. package/docs/guide/data/datasets.md +145 -0
  157. package/docs/guide/data/documents.md +235 -0
  158. package/docs/guide/data/index.md +62 -0
  159. package/docs/guide/data/knowledge.md +214 -0
  160. package/docs/guide/develop/extensions.md +299 -0
  161. package/docs/guide/develop/external-apps.md +279 -0
  162. package/docs/guide/develop/infrastructure.md +135 -0
  163. package/docs/guide/develop/sdks.md +233 -0
  164. package/docs/guide/index.md +83 -0
  165. package/docs/guide/platform/access.md +311 -0
  166. package/docs/guide/platform/architecture.md +166 -0
  167. package/docs/guide/platform/built-ins.md +225 -0
  168. package/docs/guide/platform/entrypoints.md +318 -0
  169. package/docs/guide/scenarios/index.md +130 -0
  170. package/docs/guide/template/index.md +295 -0
  171. package/docs/guide/template/state-machines.md +294 -0
  172. package/package.json +123 -4
@@ -0,0 +1,299 @@
1
+ # Extensions
2
+
3
+ What a package declares, how the template wires it, how to deploy it with ci deploy, how to read a failed deploy, and the rules its code runs under.
4
+
5
+ A package is a TypeScript module whose default export is `declarePackage({ manifest, components, hostedContributions })`. The `ci` CLI builds that module into a release, which is one immutable published version of the package. An Organization admin then installs the release into one Organization, and the installation records which release that Organization runs.
6
+
7
+ The template's package declares the Lead and Opportunity schemas, the Sales group tree, the external application of the web app, Sales Access Profiles and grants, the Max Privileges of the application's tokens, the convert-lead workflow, the lead qualifier Agent with its Skill and tool, and the Sales desk Studio app. [SDKs](sdks.md) explains which `@collective-intelligence/*` package each part imports.
8
+
9
+ ## What a package can declare
10
+
11
+ | Declaration | What it creates in the Organization |
12
+ | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
13
+ | `declareDomain`, `declareKnowledgeEntitySchema` | A Knowledge domain and the schemas of its records |
14
+ | `declareTool`, `declareToolCollection` | Tools that Agents and workflows call, grouped in collections |
15
+ | `declareSkill`, `declareAgent` | Skills and the Agents that hold them |
16
+ | `declareWorkflow`, `declareWorkflowNode` | Workflows and custom workflow nodes |
17
+ | `declareStudioApp` | A Declared Studio App that CI creates and publishes on install |
18
+ | `declareStudioAppTemplate` | A starting point that a builder copies into a new Studio app |
19
+ | `declareStudioComponent` | A Studio component, such as a widget of category `widget` |
20
+ | `declarePlaceSettings` | The chat settings of a Studio app or External App (history, Projects, memory, voice) |
21
+ | `declareConnection`, `declareConnectionInstance` | Connections to outside systems and their configured instances |
22
+ | `declareKnowledgeConnector`, `declareKnowledgeConnectorInstance` | Knowledge connectors and configured connector instances |
23
+ | `declareDocumentCollection` | One connected document collection, such as a Microsoft 365 drive folder |
24
+ | Dataset parsers, providers and blueprints | The dataset building blocks of the package |
25
+ | `declareOrganizationGroup` | A group tree with subgroups, created empty |
26
+ | `declareAccessCapabilities`, `declareAccessProfile`, `declareAccessProfileGrant` | Capabilities, Access Profiles, and Access Grants of a profile to a group |
27
+ | `declareAccessMaxPrivileges` | The Max Privileges of the application's user tokens |
28
+ | `declareOrganizationSettings` | Identity, branding, authentication, locale and governance settings (at most one per package) |
29
+ | `declareExternalApplication` | The OAuth client of your web app, with origins and redirect URIs |
30
+ | Event listeners, notification channels, email providers, Organization SSO, Organization Instructions | The matching Organization features |
31
+
32
+ Executable kinds also take an `implementation` class from `@collective-intelligence/extensions-sdk-backend`. Domains, schemas, policies, collections and Studio apps carry no class.
33
+
34
+ | Declaration | Class method that CI calls |
35
+ | ---------------------------- | ------------------------------------------- |
36
+ | `declareTool` | `PackageTool.execute` |
37
+ | `declareConnection` | `PackageConnection.test` |
38
+ | `declareKnowledgeConnector` | `pull` and `push` |
39
+ | `declareWorkflowNode` | `execute` |
40
+ | `declareEventListener` | Selectors plus `normalizeWebhook` or `poll` |
41
+ | `declareNotificationChannel` | `deliver` |
42
+
43
+ A component refers to another component of the same package through the handle that its `declare*` call returned. For a built-in component or one from another package, pass the FQN string instead, for example `"builtin.core.knowledge.tools.query"`. TypeScript does not check these strings. Install resolves them and rolls the package back when one does not exist. The [Built-in catalog](../platform/built-ins.md) lists what CI ships, and the template pins the FQNs that it uses in a `bun test` that catches a typo before deploy.
44
+
45
+ A package that declares Agents or Skills needs a person to install it; an install with no signed-in user fails. A package can depend on another package by FQN only, for example `dependencies: [{ fqn: "com.acme.base" }]`, and each install picks the latest eligible release of the dependency by promotion order.
46
+
47
+ ## How the template wires the package
48
+
49
+ ```mermaid
50
+ flowchart TD
51
+ ext["apps/extensions (@acme/extensions)<br/>index.ts: declarePackage, deploy order<br/>studio.ts: loadFrontendCatalog"]
52
+ idci["products/acme/identity/ci<br/>domain, Sales group, external application,<br/>profiles, grants, Studio app"]
53
+ idm["products/acme/identity/model<br/>package identity, VERSION"]
54
+ lead["features/lead/ci<br/>Lead schema, capabilities, policies"]
55
+ opp["features/opportunity/ci<br/>Opportunity schema, capabilities, policies"]
56
+ qual["features/lead-qualification/ci<br/>tool, Skill, Agent, widget"]
57
+ conv["features/lead-conversion/ci<br/>convert-lead workflow"]
58
+ models["model parts<br/>schema FQNs, capability codes, component FQNs"]
59
+ ext --> idci
60
+ ext --> idm
61
+ ext --> lead
62
+ ext --> opp
63
+ ext --> qual
64
+ ext --> conv
65
+ idci --> idm
66
+ idci -->|"grants by name"| models
67
+ lead --> models
68
+ opp --> models
69
+ qual --> models
70
+ ```
71
+
72
+ The template keeps its CI code in three places. `apps/extensions` is the CI Extension Package app and the composition root. It imports the Identity Domain components and the factory of each domain's `ci` part, and lists every component in deploy order. The Identity Domain `products/acme/identity` holds everything the product shares. Its `model` part holds the package identity and `VERSION`. Its `ci` part holds the domain, the Sales Group, the external application, the profiles that grant the package capabilities, their grants and the Max Privileges. Each domain exports a factory from its `ci` part, for example `leadQualificationComponents({ application, audience, version })`. The factory takes the Identity Domain handles and the package version, and returns its components in deploy order. A `features` domain never imports a product, and a `ci` part never imports another domain's `ci` part. It names the resources of other domains by the constants in their `model` parts.
73
+
74
+ This is the whole package entry:
75
+
76
+ ```ts
77
+ import { declarePackage } from "@collective-intelligence/extensions-sdk"
78
+ import { declareFrontendCatalogContribution } from "@collective-intelligence/extensions-sdk-frontend"
79
+ import { leadComponents } from "@packages/features-lead-ci"
80
+ import { convertLeadComponents } from "@packages/features-lead-conversion-ci"
81
+ import { leadQualificationComponents } from "@packages/features-lead-qualification-ci"
82
+ import { leadScoreCardContributionFqn } from "@packages/features-lead-qualification-model"
83
+ import { opportunityComponents } from "@packages/features-opportunity-ci"
84
+ import {
85
+ acmeApplication,
86
+ crmDomain,
87
+ identityComponents,
88
+ salesDeskApp,
89
+ salesMembers
90
+ } from "@packages/products-acme-identity-ci"
91
+ import {
92
+ packageManifest,
93
+ VERSION
94
+ } from "@packages/products-acme-identity-model"
95
+
96
+ export default declarePackage({
97
+ components: [
98
+ crmDomain,
99
+ ...leadComponents({ domain: crmDomain, version: VERSION }),
100
+ ...opportunityComponents({ domain: crmDomain, version: VERSION }),
101
+ ...identityComponents,
102
+ ...convertLeadComponents({
103
+ application: acmeApplication,
104
+ version: VERSION
105
+ }),
106
+ ...leadQualificationComponents({
107
+ application: acmeApplication,
108
+ audience: salesMembers,
109
+ version: VERSION
110
+ }),
111
+ salesDeskApp
112
+ ],
113
+ hostedContributions: [
114
+ declareFrontendCatalogContribution({
115
+ compatibility: { react: "^19.0.0" },
116
+ fqn: leadScoreCardContributionFqn,
117
+ host: "studio",
118
+ load: async () => await import("./studio")
119
+ })
120
+ ],
121
+ manifest: packageManifest
122
+ })
123
+ ```
124
+
125
+ `apps/extensions/src/studio.ts` exports only `loadFrontendCatalog`. That function gathers the Studio renderers of the `ci` parts under the package identity. Only an app may import several `ci` parts, so the catalog lives in `apps/extensions`. `ci package build` resolves a relative `load` import against the declaration file, so the contribution is the one declaration in `apps/extensions`. The build ships every export of that module to the browser, so it exports only the catalog loader.
126
+
127
+ One domain such as `features/lead` keeps each runtime in its own part: the CI schema in `ci`, the BFF code in `server` and the React views in `client`. Each part has one runtime, so `turbo boundaries` keeps React out of the CI release. The `runtime:ci` tag lets a `ci` part import only `ci`, neutral and build packages, and the `part:*` tags stop a part from importing a `server`, `client` or `ci` part.
128
+
129
+ The template names components `acme.app.<kind>.<name>`, for example `acme.app.tools.lead-score` or `acme.app.workflows.convert-lead`, and the package itself is `acme.app.knowledge`. Each domain's `model` part exports its FQN constants, and other code imports the constant instead of typing the string again.
130
+
131
+ A widget needs two declarations. On the backend side, `declareStudioComponent` with `category: "widget"`, a `propsSchema` and a `sourceRef` goes into `components`. On the frontend side, `declareFrontendComponent` with a `load` callback and a `studio_component` target is returned from `loadFrontendCatalog`. The `sourceRef` names the Studio hosted contribution of the package.
132
+
133
+ To add a component to the template:
134
+
135
+ 1. Declare it in the `ci` part of the domain that owns it. Put its FQN constant in the domain's `model` part when other code names it.
136
+ 2. Add it to `components` in `apps/extensions/src/index.ts` after every component it references.
137
+ 3. Bump `VERSION` in `packages/products/acme/identity/model/src/package.ts`. The package and every component share this one version.
138
+
139
+ ## Lifecycle
140
+
141
+ Every content component sets `lifecycle: { deployMode, readonly }`.
142
+
143
+ | Option | Effect |
144
+ | ------------------------- | ------------------------------------------------------------------------------------------------- |
145
+ | `deployMode: "upsert"` | Each deploy brings the definition back in line with the package. |
146
+ | `deployMode: "init_only"` | The first deploy creates the definition. Later deploys leave an Organization admin's edits alone. |
147
+ | `readonly: true` | Nobody can edit the definition by hand. Records of a schema stay editable. |
148
+
149
+ The template uses `upsert` with `readonly: true` for almost everything. The convert-lead workflow and the Sales reps grant use `init_only` with `readonly: false`, so an Organization admin can change them after install and an update keeps that change.
150
+
151
+ ## Package variables
152
+
153
+ `packageVariables` declares values that change between environments and returns one typed handle per variable. You put the handle in a component definition where a value would go. The manifest stores `{ "$variable": "<name>" }` in its place, so the release digest is the same in every environment and CI substitutes the value at deploy.
154
+
155
+ ```ts
156
+ const variables = {
157
+ collection: {
158
+ type: "string",
159
+ default: "customers",
160
+ description: "Remote CRM collection"
161
+ },
162
+ companyDomains: { type: "string[]" },
163
+ crmToken: { type: "secret" }
164
+ } as const satisfies PackageVariablesDeclaration
165
+
166
+ const vars = packageVariables(variables)
167
+ // remoteCollectionId: vars.collection
168
+
169
+ export default declarePackage({ components, manifest, variables })
170
+ ```
171
+
172
+ A variable has a type of `string`, `number`, `boolean`, `string[]`, `json` or `secret`. A variable without a default is required at deploy, and a `secret` cannot have a default. When a deploy provisions a secret without a value, the install still succeeds, but runtime use fails until a Tenant admin sets its value in the Organization variables. An Organization admin can read the variables but cannot change them.
173
+
174
+ A handle cannot go in `fqn`, `version`, `kind`, `lifecycle`, a schema projection, or a reference to another component by FQN such as `schemaFqn` or `templateFqn`. The package FQN cannot be a variable either.
175
+
176
+ Connection slots work the same way at deploy. A component names a `{ setupKey }`, and the Inputs File gives either an existing `connectionId` or a `newConnection` with a name and fields. Installing a connector instance creates no records and starts no import. [Connectors](../data/connectors.md) covers instances and slots in detail.
177
+
178
+ ## Deploy with ci deploy
179
+
180
+ `ci deploy` runs the whole release path for one declaration:
181
+
182
+ 1. Build and validate the declaration.
183
+ 2. Find the exact immutable release that matches the build.
184
+ 3. Publish and promote the release only when CI does not have it yet.
185
+ 4. Install it into the Organization, or update the existing installation.
186
+ 5. Follow every operation until it succeeds.
187
+
188
+ ```bash
189
+ ci deploy --backend-url https://ci.example.com --organization <organization-id> \
190
+ --declaration ./src/package.ts --non-interactive --json
191
+ ```
192
+
193
+ `ci deploy` reads two credentials. `CI_PUBLISHER_TOKEN` publishes and promotes, and `CI_MANAGEMENT_TOKEN` installs and updates in the Organization. If `CI_MANAGEMENT_TOKEN` is an Organization API key (prefix `dpk_`), you can omit `--organization`. `ci deploy --inputs-template` prints every connection slot and variable without contacting the backend.
194
+
195
+ A repeated deploy skips work that is already complete, and a new version updates the existing installation. CI rejects changed bytes under the same version and silent downgrades. Pass `--accept-breaking-changes` to acknowledge a breaking change. The default deadline is 300,000 ms, and `--timeout-ms` changes it.
196
+
197
+ > **Warning:** `--declaration` must start with `./` or be an absolute path, because the CLI
198
+ > resolves a bare `packages/...` like a module name and fails. A package with a
199
+ > Studio contribution waits until a Studio reports ready, and an unattended
200
+ > pipeline has no Studio, so pass `--skip-studio-readiness` there.
201
+
202
+ The long way runs each step by hand:
203
+
204
+ ```bash
205
+ ci package build --declaration ./apps/extensions/src/index.ts --out apps/extensions/dist/release
206
+ ci package validate --archive .../release.tar --manifest .../manifest.json --package-manifest .../package-manifest.json
207
+ ci package publish --backend-url <url> --archive ... --manifest ... --package-manifest ... --idempotency-key <key>
208
+ ci package promote --backend-url <url> --release <release-id> --idempotency-key <key>
209
+ ci package install --backend-url <url> --organization <organization-id> --package acme.app.knowledge --release <release-id> --idempotency-key <key>
210
+ ```
211
+
212
+ `ci package build` writes `release.tar`, `manifest.json`, `package-manifest.json` and `private-source-maps/`. The source maps hold your full source, so keep them off any public origin. Publish, promote and install each return an Operation ID, and the step is done only when the operation reports `succeeded`. `ci package releases`, `update`, `rollback`, `sync` and `operation reconnect` cover the rest of the lifecycle.
213
+
214
+ Install records a Desired Release. CI makes it the Serving Release only after every required Host (Backend, Studio, Dashboard) has prepared it, so the backend and React parts of one package never run different versions. A failed generation never becomes Serving and leaves the previous Serving Release in place.
215
+
216
+ For a fast loop without releases, `ci package dev --backend-url <url> --declaration ./src/package.ts --host-origin <studio-or-dashboard-origin>` starts a Development Session. It serves modules with Vite and rebuilds on save until the command stops. It needs a `CI_MANAGEMENT_TOKEN` with `ai:manage`, and only one live command can own a package at a time.
217
+
218
+ ## When a deploy fails
219
+
220
+ Every `ci` command shows a failure as one block on standard error. A deploy that a hand-made Skill blocks looks like this:
221
+
222
+ ```text
223
+ Error: Skills still use the tool that this change removes.
224
+ Cause: AiToolInstanceRepositoryError (referenced_by_skills); skillIds: <skill-id>; toolFqn: acme.app.tools.lead-score; toolInstanceId: <tool-id>
225
+ Fix: 1. Remove the tool from these skills, or keep it declared in the package.
226
+ 2. Start a new operation after the fix.
227
+ ci deploy --organization <organization-id> --declaration ./src/package.ts
228
+ Retry: terminal (the same command fails again until the Cause is fixed)
229
+ Reference: Operation ID <operation-id>; Diagnostic ID <diagnostic-id>
230
+ ```
231
+
232
+ | Line | What it tells you |
233
+ | ----------- | ------------------------------------------------------------------------------------------------------------ |
234
+ | `Error` | What failed, in one sentence |
235
+ | `Cause` | The error name, its reason code in parentheses, and the IDs, FQNs and names that the error marks |
236
+ | `Fix` | The steps that remove the Cause, in order, with the exact command line under each step that needs one |
237
+ | `Retry` | `retryable` when a later attempt can succeed, `terminal` when the same command fails until you fix the Cause |
238
+ | `Reference` | The Operation ID and the Diagnostic ID of the failure |
239
+
240
+ A terminal failure never tells you to retry, so do the `Fix` steps instead. A step that starts a new operation prints your own command again, with `--idempotency-key <new-key>` in place of the old key and `--declaration <module>` in place of `--resume`. A step that continues the operation prints `ci package operation continue`, and a sign-in failure (HTTP 401) adds a `ci login` step. A block leaves out the `Fix` or `Reference` line when the failure has none.
241
+
242
+ With `--json`, the failure is one record on standard output with `kind: "error"`, `summary`, `cause`, `remedy` (each step with its `command`), `retryClass`, `reference`, `nextAction` and `diagnosticDetail`. `nextAction` is the command of the last fix step that has one. A failed command exits `1` and an interrupted command exits `130` for retryable and terminal failures alike, so a pipeline reads `retryClass` to decide whether a retry can help.
243
+
244
+ `--organization`, `--operation` and `--diagnostic` take UUIDs. The CLI refuses another value before it sends a request, and the error names the option, the value and where to find the right ID.
245
+
246
+ ### Read the Diagnostic Detail
247
+
248
+ The block holds only text that the platform wrote and the identifiers that the error marks. The full failure behind a Diagnostic ID is its Diagnostic Detail: every wrapped error with its fields and message, the stack, and the log annotations. The backend keeps it for 30 days by default and stores at most 64 KiB for each failure.
249
+
250
+ After a failure with a Diagnostic ID, the CLI reads the Diagnostic Detail with your own credential. It prints the detail under the block, or puts it in `diagnosticDetail` with `--json`. When you may not read it, the CLI names who can and prints the command to read it later:
251
+
252
+ ```bash
253
+ ci diagnostics show <diagnostic-id> --organization <organization-id>
254
+ ```
255
+
256
+ Without `--organization`, the command uses the Current Organization of your CLI profile, and an Organization API key reads in its own Organization. `--json` prints the record. A missing or expired record fails as terminal.
257
+
258
+ The origin of the failure decides who can read its Diagnostic Detail. The person whose request failed gets no extra access:
259
+
260
+ | Failure origin | Who can read the Diagnostic Detail |
261
+ | --------------------------------------------------- | ------------------------------------------------------------------ |
262
+ | A package operation, such as a deploy or update | `extensions:manage` in the Organization, or `tenant:manage` |
263
+ | Another request in an Organization | `organization:self_manage` in the Organization, or `tenant:manage` |
264
+ | A tenant route, or a request with no signed-in user | `tenant:manage` |
265
+
266
+ A Host failure keeps its own Diagnostic ID, and `ci package diagnostics trace --organization <organization-id> --diagnostic <diagnostic-id>` reads its trace.
267
+
268
+ ## Runtime rules for backend code
269
+
270
+ Built-in packages ship with each CI version, use FQNs under `builtin.`, and run their backend code inside the CI backend process. Third-party backend code runs in Bun Workers. Each backend process keeps one Worker Pool per package release, and every Organization that uses that release shares it. Workers start on demand and stop after an idle period. Built-in and third-party packages use the same public SDK contracts.
271
+
272
+ > **Warning:** Never keep tenant data in module-level variables. Read the Organization,
273
+ > capabilities and configuration from the per-call `context`, because the next
274
+ > call in the same Worker can belong to a different Organization.
275
+
276
+ Every call gets an `AbortSignal` in `context.signal` and can have a deadline in `context.deadlineAt`. The host does not retry a failed call. A Worker that passes its heap limit is recycled without cutting the calls in flight. CI treats third-party code as trusted code: a valid publisher credential admits it to hosted execution, and Workers do not sandbox it.
277
+
278
+ ## After install
279
+
280
+ Some parts of a package need a person after the first deploy:
281
+
282
+ 1. Write the app's sign-in values. A package-declared application refuses `ci apps enroll`, so run `ci apps env <application-id-or-fqn> --env-file apps/web/.env.local`, which writes the `CI_*` values the server SDK reads.
283
+ 2. Rotate the sign-in secret. A confidential application has no secret after install. An Organization admin runs `ci apps rotate-secret <application-id>` or clicks Rotate secret on the Dashboard External Apps page. CI shows the secret once, and the web app stores it as `CI_CLIENT_SECRET`. This secret signs users in only.
284
+ 3. Create a Server Credential for the app's own server calls with `ci apps credentials upsert <application-id-or-fqn> --name <name> --env-file <file>`. CI refuses the sign-in secret on server calls. [External apps](external-apps.md) explains both secrets.
285
+ 4. Add users to the groups. The package creates groups empty and grants profiles to groups. In the template, an Organization admin adds users to the Sales group or its `managers` subgroup.
286
+ 5. Set every secret variable that the deploy left without a value.
287
+
288
+ The Dashboard Extensions page lists packages on Installed and Available tabs. Install and uninstall show a spinner until the real outcome, and leaving the page does not cancel the operation. A configured Knowledge connector instance, even a disabled one, or a saved connection blocks uninstall, and the Dashboard shows the error next to the package.
289
+
290
+ When a package operation fails, the package card shows the same failure as the CLI: the summary, the Cause, the fix steps and the reference, without the CLI command lines. Show diagnostic reads the Diagnostic Detail as the signed-in person, or names who can read it. The card offers Retry only when a retry can help. After a terminal failure it offers Continue only when a fix step continues the operation, and otherwise only Dismiss.
291
+
292
+ ## Related pages
293
+
294
+ - [SDKs](sdks.md)
295
+ - [External apps](external-apps.md)
296
+ - [Access](../platform/access.md)
297
+ - [Template](../template/index.md)
298
+ - [Knowledge](../data/knowledge.md)
299
+ - [AI](../ai/index.md)
@@ -0,0 +1,279 @@
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. A confidential client that passes its `clientSecret` to `createFederatedAuth` renews them silently: when a token has 30 seconds or less left, the session 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. The session itself lasts `sessionTtlSeconds`, 86400 by default and at most 604800, and never longer than the user's CI session.
114
+
115
+ > **Warning:** If users are logged out after five minutes, the app is a public client. A
116
+ > public client gets no renewal credential, so the session ends when the first
117
+ > access token expires, whatever `sessionTtlSeconds` says.
118
+
119
+ 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".
120
+
121
+ > **Note:** Consent follows the app's `applicationConsent` (`inherit`, `ask` or `skip`),
122
+ > and `inherit` uses the Organization default. If the browser already has a CI
123
+ > session cookie, CI issues the code silently under both `ask` and `skip`, so a
124
+ > tester who is signed in to CI never sees the consent panel.
125
+
126
+ ## The BFF pattern
127
+
128
+ 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:
129
+
130
+ ```mermaid
131
+ sequenceDiagram
132
+ participant B as Browser
133
+ participant F as BFF (app server)
134
+ participant C as CI
135
+ B->>F: GET /api/... with the sealed session cookie
136
+ F->>F: Open session, check the Access Requirement
137
+ F->>C: GET /application/v1/... with the delegated token and x-organization-id
138
+ C->>C: Check grants, Max Privileges and policies per record
139
+ C-->>F: Records the user may see
140
+ F-->>B: JSON, no token
141
+ ```
142
+
143
+ `createExternalApplicationBffNextHandlers` mounts federated auth, the resource proxy, capability forwarding and Realtime in one call:
144
+
145
+ ```ts
146
+ handlers: createExternalApplicationBffNextHandlers({
147
+ auth: ci.auth,
148
+ capabilities: { basePath: "/api", tenantUrl: ci.tenantUrl },
149
+ ciResources: {
150
+ bindings: [
151
+ { definition: leadContract, schemaFqn: leadSchemaFqn },
152
+ { definition: opportunityContract, schemaFqn: opportunitySchemaFqn },
153
+ ],
154
+ invalidate: nextInvalidate,
155
+ organizationId: ci.organizationId,
156
+ tenantUrl: ci.tenantUrl,
157
+ },
158
+ publicOrigin: ci.publicOrigin,
159
+ realtime: { organizationId: ci.organizationId, revalidate: createRealtimeRevalidateHandler,
160
+ secrets: ci.sessionSecrets, tenantUrl: ci.tenantUrl },
161
+ }),
162
+ ```
163
+
164
+ 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/*`.
165
+
166
+ The template mounts three route files:
167
+
168
+ | Route | Handler |
169
+ | ------------------------------------- | ----------------------------------------------------------------------- |
170
+ | `app/api/[...path]/route.ts` | The CI BFF: auth, resources, Realtime ticket |
171
+ | `app/api/leads/[id]/convert/route.ts` | Convert a Lead through a Fixed workflow route |
172
+ | `app/api/app/[[...path]]/route.ts` | The app's own Effect `HttpApi`, with OpenAPI at `/api/app/openapi.json` |
173
+
174
+ 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.
175
+
176
+ ## Reads and writes through the SDK
177
+
178
+ 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.
179
+
180
+ 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 } }`.
181
+
182
+ A business action with side effects goes through a Fixed workflow route. The server owns the workflow target and the browser only sends input:
183
+
184
+ ```ts
185
+ const handle = createFixedWorkflowRoute<{ leadId: string }, { leadId: string }>({
186
+ ...options,
187
+ idempotencyKey: ({ leadId }) => `convert-lead:${leadId}`,
188
+ requirement: convertLeadRequirement,
189
+ resourceId: "leads",
190
+ validate: (body, { leadId }) => { ... },
191
+ });
192
+ ```
193
+
194
+ 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>`.
195
+
196
+ 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`.
197
+
198
+ 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.
199
+
200
+ ## Server cache and invalidation
201
+
202
+ 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:
203
+
204
+ ```ts
205
+ const lead = async (id: string) => {
206
+ "use cache"
207
+ cacheCiRead(getRuntime().service, { id, schema: leadSchemaFqn })
208
+ return await uncached().lead(id)
209
+ }
210
+ ```
211
+
212
+ `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.
213
+
214
+ 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:
215
+
216
+ ```mermaid
217
+ flowchart LR
218
+ W1[Write through the BFF] --> N[nextInvalidate]
219
+ W2[Write outside the BFF] --> RT[Realtime change in an open tab] --> RV[Revalidate route]
220
+ W3[Effect server write] --> L[CacheInvalidation.layerNext on the fiber]
221
+ N --> T[Entity, list and topic tags expire]
222
+ RV --> T
223
+ L --> T
224
+ ```
225
+
226
+ > **Warning:** An Effect `ServerClient` write without `CacheInvalidation` on its fiber
227
+ > expires nothing and logs no error. Providing `layerNext` into
228
+ > `layerServerClient` does not reach the writes; merge it into the runtime
229
+ > instead.
230
+
231
+ 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.
232
+
233
+ ## Realtime
234
+
235
+ 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.
236
+
237
+ 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.
238
+
239
+ 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.
240
+
241
+ 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.
242
+
243
+ > **Warning:** Do not open the stream with a hand-written `EventSource`. It cannot send the
244
+ > `Authorization` and `X-Organization-Id` headers that CI needs, and the failure
245
+ > is silent: the connection opens and no event arrives. The SDK's Realtime
246
+ > client uses tickets instead.
247
+
248
+ ## Effect and NestJS flavors
249
+
250
+ 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.
251
+
252
+ | | Template | Effect demo | NestJS demo |
253
+ | --------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
254
+ | Direction | Outbound | Outbound and inbound | Inbound |
255
+ | 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 |
256
+ | Convert lead | A CI workflow | A Gateway operation that creates one Opportunity and marks the Lead converted, idempotent by `x-idempotency-key` | Not included |
257
+ | CI entry points | BFF routes | BFF and Gateway | One `Greetings` service behind an HTTP route, an operation binding and an AI SDK tool |
258
+
259
+ A Gateway lists exactly what CI may discover:
260
+
261
+ ```ts
262
+ const gateway = defineGateway({
263
+ id: "crm",
264
+ version: "1.0.0",
265
+ knowledge: [{ resource: leadResource, access: "read_write" }],
266
+ datasets: [leadPipeline],
267
+ operationDomains: [crmOperations]
268
+ })
269
+ ```
270
+
271
+ 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.
272
+
273
+ ## Related pages
274
+
275
+ - [Grants and permissions](../platform/access.md)
276
+ - [SDKs](sdks.md)
277
+ - [Extensions](extensions.md)
278
+ - [The template](../template/index.md)
279
+ - [Knowledge](../data/knowledge.md)