@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.
Files changed (61) hide show
  1. package/AGENTS.md +49 -0
  2. package/README.md +122 -0
  3. package/dist/ci-generate/declarations/ci-generate/generate.d.ts +10 -0
  4. package/dist/ci-generate/declarations/entrypoints/ci-generate.d.ts +6 -0
  5. package/dist/ci-generate/declarations/knowledge/body.d.ts +32 -0
  6. package/dist/ci-generate/declarations/knowledge/files.d.ts +42 -0
  7. package/dist/ci-generate/declarations/knowledge/manifest.d.ts +19 -0
  8. package/dist/ci-generate/declarations/package/builder.d.ts +63 -0
  9. package/dist/ci-generate/declarations/package/contract.d.ts +16 -0
  10. package/dist/ci-generate/declarations/package/stamped-fields.d.ts +7 -0
  11. package/dist/ci-generate/declarations/plugin/editor-field.d.ts +20 -0
  12. package/dist/ci-generate/declarations/plugin/integration-user.d.ts +11 -0
  13. package/dist/ci-generate/declarations/plugin/parts.d.ts +81 -0
  14. package/dist/ci-generate.d.ts +1 -0
  15. package/dist/ci-generate.js +2 -0
  16. package/dist/index/declarations/ci-generate/generate.d.ts +10 -0
  17. package/dist/index/declarations/entrypoints/index.d.ts +6 -0
  18. package/dist/index/declarations/knowledge/body.d.ts +32 -0
  19. package/dist/index/declarations/knowledge/files.d.ts +42 -0
  20. package/dist/index/declarations/knowledge/identity.d.ts +27 -0
  21. package/dist/index/declarations/knowledge/manifest.d.ts +19 -0
  22. package/dist/index/declarations/knowledge/push-job.d.ts +8 -0
  23. package/dist/index/declarations/knowledge/source.d.ts +24 -0
  24. package/dist/index/declarations/operations/conflict.d.ts +22 -0
  25. package/dist/index/declarations/operations/markdown.d.ts +25 -0
  26. package/dist/index/declarations/operations/operations.d.ts +30 -0
  27. package/dist/index/declarations/operations/write-back.d.ts +8 -0
  28. package/dist/index/declarations/package/builder.d.ts +63 -0
  29. package/dist/index/declarations/package/contract.d.ts +16 -0
  30. package/dist/index/declarations/package/stamped-fields.d.ts +7 -0
  31. package/dist/index/declarations/plugin/editor-field.d.ts +20 -0
  32. package/dist/index/declarations/plugin/grant-store.d.ts +21 -0
  33. package/dist/index/declarations/plugin/integration-user.d.ts +11 -0
  34. package/dist/index/declarations/plugin/parts.d.ts +81 -0
  35. package/dist/index/declarations/plugin/plugin.d.ts +10 -0
  36. package/dist/index.d.ts +1 -0
  37. package/dist/index.js +7 -0
  38. package/dist/package.d.ts +134 -0
  39. package/dist/package.js +24 -0
  40. package/docs/guide/ai/index.md +379 -0
  41. package/docs/guide/ai/studio.md +245 -0
  42. package/docs/guide/data/connectors.md +267 -0
  43. package/docs/guide/data/datasets.md +145 -0
  44. package/docs/guide/data/documents.md +235 -0
  45. package/docs/guide/data/index.md +62 -0
  46. package/docs/guide/data/knowledge.md +214 -0
  47. package/docs/guide/develop/extensions.md +299 -0
  48. package/docs/guide/develop/external-apps.md +289 -0
  49. package/docs/guide/develop/infrastructure.md +135 -0
  50. package/docs/guide/develop/sdks.md +252 -0
  51. package/docs/guide/index.md +83 -0
  52. package/docs/guide/platform/access.md +311 -0
  53. package/docs/guide/platform/architecture.md +166 -0
  54. package/docs/guide/platform/built-ins.md +225 -0
  55. package/docs/guide/platform/entrypoints.md +320 -0
  56. package/docs/guide/scenarios/index.md +130 -0
  57. package/docs/guide/template/index.md +295 -0
  58. package/docs/guide/template/state-machines.md +294 -0
  59. package/docs/payload-connector.md +890 -0
  60. package/docs/payload-page-editor-skill.md +284 -0
  61. package/package.json +76 -8
@@ -0,0 +1,214 @@
1
+ # Knowledge
2
+
3
+ Declare schemas, store typed records, query them, and read and watch them from an external app.
4
+
5
+ Knowledge holds structured business records, such as Leads and Opportunities, and relation fields link records to each other. A schema defines the fields that a record type can have, and a record is one instance that matches that schema. Schemas live in a Knowledge domain, a named group of related schemas that the Organization owns. In the template, the extension package `acme.app.knowledge` declares the Acme CRM domain with a Lead schema and an Opportunity schema, and the template's web app reads and writes Lead and Opportunity records through the SDKs.
6
+
7
+ A domain holds schemas and never records. It can set a default for record versioning that its schemas use when they set none. Access policies target schemas, so a domain does not grant or limit access. The [Data resources](index.md) page compares Knowledge with Datasets and Documents.
8
+
9
+ ```mermaid
10
+ flowchart LR
11
+ P[Extension package] --> D[Knowledge domain]
12
+ D --> L[Lead schema]
13
+ D --> O[Opportunity schema]
14
+ L --> LRec[Lead records]
15
+ O --> ORec[Opportunity records]
16
+ ```
17
+
18
+ Schemas that a package or a CLI deploy creates have the definition type `custom`, and a custom schema can point a relation field at one of the platform's `builtin` schemas.
19
+
20
+ ## Field kinds
21
+
22
+ A schema combines ordinary value fields with three special kinds. Each special kind has its own declaration block, and the platform generates its value schema.
23
+
24
+ | Kind | Declared in | Stored value | Use it for |
25
+ | -------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
26
+ | Value field | `schema` properties | `string`, `number` (with `numberKind: "integer"` for whole numbers), `datetime`, `string_select` with `options` | Names, amounts, dates, status values |
27
+ | Relation field | `fieldSemantics["/<key>"].relation` | One record ID or an array of record IDs | Links between records, such as Opportunity to Lead |
28
+ | User field | `userFields` | One user ID or an ordered list of user IDs | Owners, reviewers, the users who act for a record |
29
+ | File field | `fileFields` | A File value with `id`, `url`, `filename`, `mimeType`, `size` and `source` | Attachments such as a signed PDF |
30
+
31
+ ## Declare a schema in a package
32
+
33
+ A customer solution declares its schemas in code, inside its extension package. This is the template's Lead schema, shortened:
34
+
35
+ ```ts
36
+ declareKnowledgeEntitySchema({
37
+ definition: {
38
+ domainFqn: domain.manifest.fqn,
39
+ fileFields: {
40
+ attachment: {
41
+ accepts: ["application/pdf", "image/jpeg", "image/png"],
42
+ maxBytes: 5 * 1024 * 1024,
43
+ multiple: false,
44
+ visibility: "private"
45
+ }
46
+ },
47
+ lifecycle: { deployMode: "upsert", readonly: true },
48
+ schema: knowledgeRecordSchema({
49
+ additionalProperties: false,
50
+ properties: {
51
+ company: { required: true, type: "string" },
52
+ email: { required: true, type: "string" },
53
+ name: { minLength: 1, required: true, type: "string" },
54
+ score: { numberKind: "integer", type: "number" },
55
+ status: {
56
+ options: ["converted", "open", "qualified"],
57
+ type: "string_select"
58
+ },
59
+ createdAt: { type: "datetime" }
60
+ }
61
+ })
62
+ },
63
+ manifest: { fqn: "acme.app.schemas.lead", version },
64
+ presentation: {
65
+ displayName: "Lead",
66
+ description: "A prospective Acme customer."
67
+ }
68
+ })
69
+ ```
70
+
71
+ Each declared item needs a `lifecycle`. With `deployMode: "upsert"`, every deploy reconciles the schema with the code, and `init_only` creates the schema once and then leaves it alone. With `readonly: true`, an Organization admin cannot edit the definition in the Dashboard, so the code stays the only source of truth. Choose `readonly: true` when the package code owns the schema and you redeploy to change it, and `readonly: false` when the customer's Organization admin should keep editing the schema in the Dashboard after the deploy.
72
+
73
+ The template also has a Lead entity contract in `domain/lead.ts`. That contract types the resource for the web app (its capabilities, the fields you can filter, sort and search on, and the create and update shapes) and never reaches CI. CI receives only the schema above, so when you add a field, change both files.
74
+
75
+ The CLI puts the schema into an Organization in five steps: `ci package build`, `validate`, `publish`, `promote` and `install --organization <id>`. The [Extensions](../develop/extensions.md) page shows the full commands.
76
+
77
+ ## Relation fields
78
+
79
+ A relation field holds references to records of exactly one target schema. Declare it under `fieldSemantics` with a target schema and a cardinality, and leave the property out of the value schema because the platform generates its value schema:
80
+
81
+ ```ts
82
+ fieldSemantics: {
83
+ "/companies": {
84
+ relation: {
85
+ targetSchemaFqn: "core.schemas.crm.company",
86
+ cardinality: "many_to_many",
87
+ onDelete: "restrict",
88
+ },
89
+ },
90
+ }
91
+ ```
92
+
93
+ Cardinality reads from the source record to the target record. "One" means at most one, so a link is never required.
94
+
95
+ | Cardinality | Targets per source | Sources per target |
96
+ | -------------- | ------------------ | ------------------ |
97
+ | `one_to_one` | At most one | At most one |
98
+ | `one_to_many` | Many | At most one |
99
+ | `many_to_one` | At most one | Many |
100
+ | `many_to_many` | Many | Many |
101
+
102
+ To show the same links from the other side, declare an inverse field on the target schema with `inverseOf: { schemaFqn, field }`. An inverse field is read-only, and a write to it fails, even a write of `null` or an empty array. `onDelete` controls what happens when someone physically deletes a target record: `clear` (the default) removes the reference, and `restrict` refuses the delete. A logical delete keeps the references.
103
+
104
+ > **Warning:** If you declare `Company.contacts` and `Contact.company` as two forward fields,
105
+ > you get two separate relationships that do not stay in sync. Declare one
106
+ > forward field and make the other side its inverse.
107
+
108
+ In the template, Opportunity stores `leadId` as a plain required string. That is enough to display the ID. If your demo needs to navigate from an Opportunity to its Lead, expand the Lead in one query, or filter on `lead.company`, replace `leadId` with a `many_to_one` relation field that targets the Lead schema.
109
+
110
+ ## User fields and file fields
111
+
112
+ A User field stores the ID of one Organization member or External App User, or an ordered list of them. The platform resolves names, emails and avatars when it displays the field and never stores them. Selecting a user in the field does not assign work, send a notification or grant access.
113
+
114
+ ```ts
115
+ userFields: {
116
+ owner: { multiple: false },
117
+ reviewers: { multiple: true },
118
+ }
119
+ ```
120
+
121
+ One User field per schema can set `accounts: true`. The users in that field act for the record, and access rules can test it with `isMe("accounts")` or `includesMe("accounts")`, for example to let a user write only the records that list them. The platform owns this field: package policies, app users and agent tools cannot change it, but a workflow `add-account` step can. The [Access](../platform/access.md) page explains the rules that read it.
122
+
123
+ A file field stores files. Its read value is `{ id, url, filename, mimeType, size, source }`, where `source` is `managed` when CI stores the bytes and `external_url` when the file stays at a remote URL. To upload, the app asks CI for an upload slot. The slot is single use and belongs to one file field. CI refuses an upload larger than `maxBytes`, and the template also checks the size in the browser so that it sends nothing too large. To update the Lead attachment, the template sends `{ upload }` for a new file, `{ id }` to keep the current file, or `null` to remove it.
124
+
125
+ ## Query records
126
+
127
+ Field filters narrow records with `{ field, operator, value }` and operators such as `eq`, `in`, `exists` and `is_empty`, and text search matches plain text. Semantic search ranks records by embeddings, so it works only on a schema with embeddings enabled, and each result carries its `match.semantic_score`.
128
+
129
+ The schema controls embeddings. `embedEntities` turns on one combined vector per record, `fieldSemantics["/field"].includeInItemEmbedding` selects the fields that go into that vector, and `fieldSemantics["/field"].embedded` gives a long text field its own passage vectors. When you change these settings through a deploy or an edit in the Dashboard, CI reprocesses the existing records automatically. You do not need a new import or an Organization reset.
130
+
131
+ > **Warning:** `embedEntities` alone gives no semantic search over records. Select at least
132
+ > one field with `includeInItemEmbedding`, or the schema has no record vector
133
+ > and shows a configuration status instead.
134
+
135
+ A filter path such as `company.industry` follows declared relation fields for at most three hops, and `include` returns the related records in an `included` tree beside the references. Includes go at most three levels deep and return at most 100 readable records per field, with a `truncated` marker when they stop. Each included record passes the same read check as a direct read, so `include` never shows a record that the caller cannot read. Relevance-ranked search rejects filters on relation fields.
136
+
137
+ > **Note:** Knowledge has no graph database and no graph traversal. Older material that
138
+ > describes graph edges or relation bindings refers to a retired model. Relation
139
+ > paths and `include` follow the relation fields that the schema declares.
140
+
141
+ ## Retrieval for agents
142
+
143
+ Agents and workflows read Knowledge through built-in tools. Knowledge Query (`builtin.core.knowledge.tools.query`) reads Knowledge only, and Documents Query (`builtin.core.documents.tools.query`) searches Documents only. Advanced Information Retrieval (`builtin.core.information.tools.advanced-retrieval`) is the only tool that searches both, and it does so by default.
144
+
145
+ ```mermaid
146
+ flowchart LR
147
+ K[Knowledge Query] --> KP[Knowledge policy and record filters]
148
+ D[Documents Query] --> DP[Documents policy and collection paths]
149
+ A[Advanced Information Retrieval] --> KP
150
+ A --> DP
151
+ KP --> R[PostgreSQL ranking]
152
+ DP --> R
153
+ R --> C[Live authorization recheck]
154
+ C --> E[Results]
155
+ ```
156
+
157
+ PostgreSQL holds the source of truth and runs semantic search with pgvector. The tool input has no field for a provider, a vector or a ranking setting, so an agent cannot change how CI routes the query. Before CI returns a result, it checks the current policies again, which means that a revoked grant takes effect on the next query. The [AI](../ai/index.md) page covers tools and Skills.
158
+
159
+ ## Documents and Knowledge
160
+
161
+ Knowledge and Documents share storage and processing. A Knowledge file field stores its file through Documents, in an internal collection that Documents browse and search do not show. A reader reaches that file through the Knowledge record, and Advanced Information Retrieval returns it when the reader can read the record. Both kinds also use one extraction and embedding pipeline, and CI reuses one processing result when the same bytes appear twice in an Organization. The [Documents](documents.md) page covers Document Collections, sync and indexing.
162
+
163
+ ## Read and write from an app
164
+
165
+ An external app reaches records in two ways, and the template uses both.
166
+
167
+ | | Browser | Server |
168
+ | ----------- | ----------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
169
+ | API | Entity hooks from `defineEntity({ contract, config })` in `@collective-intelligence/external-apps-client-sdk-react/resources` | `ServerClient.records` from `@collective-intelligence/external-apps-server-sdk/effect` |
170
+ | Acts as | The signed-in user | A Server Credential, with the Access Grants of the app's server |
171
+ | Operations | Whatever the entity contract allows: create, get, search, update, delete, upload | `create`, `get`, `search`, `update`, `delete` |
172
+ | Typical use | Forms, lists and tables | Server routes and the template's Read Port |
173
+
174
+ The server client takes the Organization and the schema on each call, and the schema FQN works as `schemaId`. A missing record fails with the `CiError` code `not_found`. This is the template's server read, without the wrapper that turns `not_found` into an empty result:
175
+
176
+ ```ts
177
+ const record =
178
+ yield *
179
+ client.records.get({
180
+ id,
181
+ organizationId: options.organizationId,
182
+ schemaId: leadSchemaFqn
183
+ })
184
+ const fields = yield * decodeLead(record.value)
185
+ return { ...fields, id: record.id }
186
+ ```
187
+
188
+ `records.search` accepts a filter, text search, sort, pagination and `include`. App filtering goes through `POST /application/v1/resources/:schemaId/search`, and relation field pickers use `POST /application/v1/knowledge/autocomplete`. The SDKs do not wrap semantic search; agents use the retrieval tools for that.
189
+
190
+ > **Warning:** Server calls need a Server Credential (`dsc_`), and CI refuses the enrollment
191
+ > client secret on server calls because that secret only signs users in. Create
192
+ > one with `ci apps credentials upsert <app> --name <name> --env-file <file>`.
193
+ > The Server Credential acts with the Access Grants of the app's server, so
194
+ > those grants need read access to Leads. CI accepts a user's token only when
195
+ > the user holds the application gate. See [Access](../platform/access.md).
196
+
197
+ ## Change events
198
+
199
+ Every write to a record produces a change event, whether the write comes from an external app, Studio, an agent or a workflow. Database triggers write a change log entry for each changed record, with one entry per record per transaction. A sync that changes nothing writes no entry.
200
+
201
+ An app subscribes to a topic per schema, for example `{ schema: "acme.app.schemas.lead" }`. `useRealtimeTopic(topic, changes => ...)` receives batches of changes that carry record IDs only, and `useEntityChanges(contract)` gives a function that refreshes the entity reads for those IDs. CI checks read access for each change before it sends it. When CI cannot decide whether a reader may see a delete, it sends that reader a `reset` instead of the ID, and the client must then refetch.
202
+
203
+ To see this in the template, open `/crm` in two browser windows and edit a Lead in one of them as a Sales manager. The other window shows the change without a reload, and it does the same when the change comes from Studio, an agent or a workflow that writes the Lead.
204
+
205
+ ## Related pages
206
+
207
+ - [Data resources](index.md)
208
+ - [Datasets](datasets.md)
209
+ - [Documents](documents.md)
210
+ - [Connectors](connectors.md)
211
+ - [Access](../platform/access.md)
212
+ - [SDKs](../develop/sdks.md)
213
+ - [Extensions](../develop/extensions.md)
214
+ - [AI](../ai/index.md)
@@ -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)