@collective-intelligence/external-apps-server-sdk-payload 0.0.0-stage → 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 +121 -2
  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 +79 -4
@@ -0,0 +1,890 @@
1
+ # Payload connector
2
+
3
+ Connect a Payload Site to CI for AI website search. The Payload Plugin
4
+ (`ciPayloadPlugin` from the root of the Payload SDK) serves the chosen
5
+ Payload Collections through a Gateway, and its Push Job sends each change to
6
+ CI. In CI, the Knowledge Gateway connector imports the collections into
7
+ Knowledge, and a visitor Agent searches them with Advanced Information
8
+ Retrieval.
9
+
10
+ Two setup paths use the same plugin:
11
+
12
+ | Path | Who connects the site | CI side |
13
+ | ---------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
14
+ | Code-first | A developer, with `ci deploy` of an extension package | The package calls the Payload Package Helpers, and declares the policies and the Agent |
15
+ | Dashboard | An administrator, with the existing Gateway setup screens | The administrator registers the Gateway and makes the schemas and bindings in the Dashboard |
16
+
17
+ The Dashboard has no Payload-specific screen.
18
+
19
+ ## Set up the site
20
+
21
+ Do these steps on the site for both paths. Deploy the site before the CI
22
+ side (see [Deploy order](#deploy-order)).
23
+
24
+ ### 1. Add the plugin
25
+
26
+ Install the Payload SDK with its peers. The site's extension package uses
27
+ the same extensions SDK copy:
28
+
29
+ ```sh
30
+ npm install @collective-intelligence/external-apps-server-sdk-payload \
31
+ @collective-intelligence/extensions-sdk payload effect
32
+ ```
33
+
34
+ Add `ciPayloadPlugin` to the `plugins` of `payload.config.ts`. This is the
35
+ configuration of the CI test site, shortened (database adapter, migrations
36
+ and the `users` and `authors` collections left out):
37
+
38
+ ```ts
39
+ import type { CollectionConfig } from "payload"
40
+
41
+ import { ciPayloadPlugin } from "@collective-intelligence/external-apps-server-sdk-payload"
42
+ import { buildConfig } from "payload"
43
+
44
+ const environment = process.env
45
+
46
+ // The site's Public URL of a document.
47
+ const urlOf =
48
+ (collection: string) =>
49
+ (document: Readonly<Record<string, unknown>>): string =>
50
+ `https://museum.example/${collection}/${String(document.id)}`
51
+
52
+ const pages: CollectionConfig = {
53
+ admin: { useAsTitle: "title" },
54
+ fields: [
55
+ { name: "title", required: true, type: "text" },
56
+ { name: "body", type: "textarea" }
57
+ ],
58
+ slug: "pages",
59
+ versions: { drafts: true }
60
+ }
61
+
62
+ // The CI trust exists only at run time: a build or `payload ci-generate` has none.
63
+ const ci =
64
+ environment.CI_TENANT_URL === undefined
65
+ ? undefined
66
+ : {
67
+ allowedPackages: [
68
+ {
69
+ gatewayFqn: environment.CI_GATEWAY_FQN ?? "",
70
+ organizationId: environment.CI_ORGANIZATION_ID ?? "",
71
+ packageFqn: environment.CI_PACKAGE_FQN ?? ""
72
+ }
73
+ ],
74
+ audience: environment.CI_GATEWAY_URL ?? "",
75
+ trustedIssuers: [
76
+ {
77
+ issuer: environment.CI_TENANT_URL,
78
+ tenantUrl: environment.CI_TENANT_URL
79
+ }
80
+ ]
81
+ }
82
+
83
+ export default buildConfig({
84
+ collections: [users, authors, pages, posts],
85
+ // The Push Job runs on the `ci-gateway` queue; this site runs it every second.
86
+ jobs: { autoRun: [{ cron: "* * * * * *", queue: "ci-gateway" }] },
87
+ plugins: [
88
+ ciPayloadPlugin({
89
+ ...(ci === undefined ? {} : { ci }),
90
+ collections: {
91
+ pages: { urlRule: urlOf("pages") },
92
+ posts: { urlRule: urlOf("posts") }
93
+ },
94
+ // The first user of the site, which the journey registers.
95
+ integrationUser: { collection: users.slug, id: 1 }
96
+ })
97
+ ]
98
+ })
99
+ ```
100
+
101
+ The options:
102
+
103
+ - `collections`: the exposed Payload Collections, by slug. Each one needs a
104
+ URL Rule (`urlRule`): the function that gives the Public URL of a
105
+ document. For a collection with localized fields, the rule gets the
106
+ document as read in the item's language, with the language in
107
+ `ciLanguage`, so that each language has its own URL, for example
108
+ `` (page) => `https://museum.example/${String(page.ciLanguage)}/pages/${String(page.id)}` ``.
109
+ `bodyExclude` lists the field paths that the Document Body
110
+ skips. `writable: true` lets the page operations and the Knowledge
111
+ write-back write the collection (see
112
+ [Edit pages with an Agent](#edit-pages-with-an-agent)). Payload globals
113
+ are never imported.
114
+ - `integrationUser`: the Integration User. The plugin reads and writes as
115
+ this Payload user, with the site's access rules on, so this user must read
116
+ every exposed document, drafts included.
117
+ - `ci`: the CI trust. Without it, the Gateway refuses every CI call.
118
+ - `audience`: the Gateway URL. CI signs its caller tokens for this URL.
119
+ - `trustedIssuers`: the CI tenants that the site trusts. `issuer` and
120
+ `tenantUrl` are the HTTPS public URL of CI.
121
+ - `allowedPackages`: for the code-first path, the Organization, package
122
+ and Gateway FQN that can enroll the Gateway.
123
+ - `dashboard`: for the Dashboard path; see
124
+ [Connect the site in the Dashboard](#connect-the-site-in-the-dashboard).
125
+ - `fetch`: replaces `fetch` for the calls from the site to CI.
126
+
127
+ `ci` needs `allowedPackages`, `dashboard`, or both. With neither, the
128
+ configuration fails at start.
129
+
130
+ The Gateway answers under the site's Payload API route: `/api/ci-gateway`
131
+ with the default `routes.api`. The Gateway URL is the site origin plus that
132
+ path, for example `https://www.example.com/api/ci-gateway`.
133
+
134
+ The Gateway manifest lists each relationship of an exposed collection as a
135
+ relation, also one to a collection that is not exposed. With each relation,
136
+ the plugin sends `<field>_title`: the related document's `admin.useAsTitle`
137
+ value, as text. For a has-many relation, the titles are joined with `", "`.
138
+ A published item takes a related title only from the related document's
139
+ published version, so a document that was never published gives no title.
140
+ A relationship or upload inside a block, group, named tab or array, and a
141
+ join field, holds only the related document's id.
142
+
143
+ A collection with `timestamps: false` pushes no update time, so CI cannot
144
+ put its late pushes in order.
145
+
146
+ ### 2. Make the site migration
147
+
148
+ The plugin adds two hidden collections, `ci-gateway-grants` and
149
+ `ci-gateway-replays`, and the Push Job uses the Payload job tables. Make a
150
+ migration after you add the plugin, and run it like each other site
151
+ migration:
152
+
153
+ ```sh
154
+ payload migrate:create ci-gateway
155
+ ```
156
+
157
+ A collection with `writable: true` gets three hidden fields: `ciCreateKey`,
158
+ the key of each CI create, with a unique index; `ciUpdateKey`, the key of
159
+ the CI update that saved the newest version; and `ciEditor`, the CI Editor
160
+ field. Make a new migration each time you mark a collection
161
+ `writable: true`. A site that made its migration with an earlier build of
162
+ this SDK release has a plain index on `ci_create_key` and no
163
+ `ci_update_key` column: make a new migration, which replaces the index
164
+ with a unique index and adds the column. Remove the documents with a
165
+ duplicate `ci_create_key` first, else the migration fails.
166
+
167
+ Only a signed-in user of the site's admin user collection (`admin.user`)
168
+ reads `ciEditor`, in the document and in its version history. The site's
169
+ REST and GraphQL API give it to no visitor or other user, and the `read`
170
+ operation leaves it out. Values that the site stored before keep their
171
+ place: this read rule needs no migration.
172
+
173
+ `ci-gateway-grants` keeps each Gateway Connection with the client secret
174
+ that the Push Job signs in with, in plain text. Treat the site database as
175
+ secret storage.
176
+
177
+ ### 3. Run the job runner
178
+
179
+ Each publish, unpublish, manual draft save, move to trash or delete of an
180
+ exposed document queues one Push Job (task `ciGatewayPush`, queue
181
+ `ci-gateway`) in the transaction of the change. A rollback removes the job
182
+ with the change. An autosave queues no Push Job. Payload's Local API
183
+ `create` has no autosave, so each Local API create queues one.
184
+
185
+ The site must run the jobs of the `ci-gateway` queue, else no change gets
186
+ to CI. Run them every minute:
187
+
188
+ - **On Vercel**: a cron on Payload's job run route, every minute. Vercel
189
+ sends `Authorization: Bearer <CRON_SECRET>`; let that token run jobs.
190
+
191
+ ```json
192
+ {
193
+ "crons": [
194
+ {
195
+ "path": "/api/payload-jobs/run?queue=ci-gateway",
196
+ "schedule": "* * * * *"
197
+ }
198
+ ]
199
+ }
200
+ ```
201
+
202
+ ```ts
203
+ jobs: {
204
+ access: {
205
+ run: ({ req }) => {
206
+ if (req.user) {
207
+ return true
208
+ }
209
+ return (
210
+ req.headers.get("authorization") ===
211
+ `Bearer ${process.env.CRON_SECRET}`
212
+ )
213
+ }
214
+ }
215
+ }
216
+ ```
217
+
218
+ - **On a server** (a long-running Node process): a continuous runner in the
219
+ site process.
220
+
221
+ ```ts
222
+ jobs: {
223
+ autoRun: [{ cron: "* * * * *", queue: "ci-gateway" }]
224
+ }
225
+ ```
226
+
227
+ A failed push retries 5 times, with a wait that doubles from one minute:
228
+ about 31 minutes in all. The scheduled CI repair run catches up after a
229
+ longer outage. The push to each Gateway Connection is a step of its own: a
230
+ retry pushes again only to the connections whose push failed. A push that
231
+ CI does not answer in 30 seconds fails.
232
+
233
+ Two Push Jobs of one document can run at the same time, and their pushes
234
+ can reach CI in either order. Each item carries the document's update
235
+ time, and each delete carries the time the job runs as its revision and
236
+ update time. CI ignores a record that is older than the last record it
237
+ took for the same item: a late push of a page from before an unpublish
238
+ does not bring the page back, and a late delete does not remove a page
239
+ that a newer push brought back.
240
+
241
+ A new enrollment replaces the Gateway Connection that CI replaced, and the
242
+ plugin deletes its grant:
243
+
244
+ - **Package**: a new install of the site package. The enrollment deletes
245
+ the other grants of the same CI issuer, Organization, package FQN and
246
+ Gateway FQN. CI keeps one installation of a package per Organization.
247
+ - **Dashboard**: a new registration of the Gateway. The enrollment deletes
248
+ the other Dashboard grants of the same CI issuer and Organization.
249
+
250
+ The Push Job then stops pushing to the old connection, and CI can no longer
251
+ call the site through it.
252
+
253
+ ### 4. Write the Payload Declarations File
254
+
255
+ The code-first path reads the site's collections from the Payload
256
+ Declarations File: the schema fields, field map and relationships of each
257
+ exposed collection. The plugin adds the `payload ci-generate` bin script.
258
+ Run it in the site's code base, with the site's own configuration:
259
+
260
+ ```sh
261
+ payload ci-generate --out ci-package/payload-declarations.json
262
+ ```
263
+
264
+ Commit the file with the package. Add `--check` to the site build: it fails
265
+ when the file does not match the configuration.
266
+
267
+ ```sh
268
+ payload ci-generate --out ci-package/payload-declarations.json --check
269
+ ```
270
+
271
+ ## Declare the site package
272
+
273
+ On the code-first path, one extension package declares the CI side. The
274
+ Payload Package Helpers of `/package` declare the parts that every Payload
275
+ Site needs, with the site's own extensions SDK copy, and return finished
276
+ components. `/package` imports no Payload module, so the package build does
277
+ not load Payload. This is the package of the CI test site
278
+ (`testing/e2e/fixtures/payload-site/ci-package/package.ts` in the CI
279
+ repository), shortened:
280
+
281
+ ```ts
282
+ import {
283
+ declareDomain,
284
+ declarePackage
285
+ } from "@collective-intelligence/extensions-sdk"
286
+ import {
287
+ payloadGateway,
288
+ payloadGatewayPushGrant,
289
+ payloadKnowledge,
290
+ payloadPackageDependencies,
291
+ payloadPageEditor
292
+ } from "@collective-intelligence/external-apps-server-sdk-payload/package"
293
+
294
+ import declarations from "./payload-declarations.json" with { type: "json" }
295
+
296
+ const lifecycle = { deployMode: "upsert", readonly: true } as const
297
+ const domain = declareDomain({
298
+ definition: { lifecycle, versioningEnabled: null },
299
+ manifest: { fqn: domainFqn, version },
300
+ presentation: { displayName: "Website" }
301
+ })
302
+ const gateway = payloadGateway({
303
+ displayName: "Museum site",
304
+ fqn: names.gateway,
305
+ version
306
+ })
307
+ // Pages keep their drafts in CI, so the visitor Data Policy is what hides them.
308
+ const knowledge = payloadKnowledge(declarations, {
309
+ collections: { pages: { draftImport: "published_and_drafts" }, posts: {} },
310
+ domainFqn,
311
+ gateway,
312
+ manifest: { fqn: names.knowledge, version },
313
+ presentation: { displayName: "Museum site content" },
314
+ // A full import each night repairs the pushes that the site missed.
315
+ schedules: [{ cronExpression: "0 3 * * *", key: "nightly" }]
316
+ })
317
+ const { pages, posts } = knowledge.schemas
318
+
319
+ return declarePackage({
320
+ components: [
321
+ domain,
322
+ gateway,
323
+ ...knowledge.components,
324
+ // The Gateway's own app signs the site's pushes: it manages Knowledge.
325
+ ...payloadGatewayPushGrant({
326
+ fqn: `${input.fqn}.gateway-push`,
327
+ gateway,
328
+ version
329
+ }).components,
330
+ // The capabilities, the visitor and member policies, the site app, its
331
+ // Access Profiles and grants, and the site search Agent (see Website search).
332
+ ...payloadPageEditor({
333
+ agentFqn: `${input.fqn}.agents.page-editor`,
334
+ gateway,
335
+ skillFqn: `${input.fqn}.skills.page-editor`,
336
+ version
337
+ }).components
338
+ ],
339
+ // The connector instance runs on the Knowledge Gateway template of the
340
+ // External Apps package.
341
+ manifest: {
342
+ dependencies: payloadPackageDependencies,
343
+ fqn: input.fqn,
344
+ name: "Museum site",
345
+ version
346
+ }
347
+ })
348
+ ```
349
+
350
+ The helpers:
351
+
352
+ | Helper | What it declares |
353
+ | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
354
+ | `payloadGateway` | The Gateway, with the Payload Operation Contract. `gateway.operation(id)` takes a Payload operation id. |
355
+ | `payloadKnowledge` | One entity schema for each chosen collection (`schemas`, by collection name) and the connector instance (`connectorInstance`); `components` lists them all |
356
+ | `payloadGatewayPushGrant` | The server Access Profile `<fqn>.profile` and its Access Grant `<fqn>.grant`, which let the Gateway's app push (see the push grant below) |
357
+ | `payloadPageEditor` | The page editor Skill and the Agent that holds it (see the page editor guide below) |
358
+ | `payloadPackageDependencies` | Not a function: the manifest `dependencies` entry `builtin.core.external-apps` |
359
+
360
+ [Payload page editor Skill](payload-page-editor-skill.md) explains
361
+ `payloadPageEditor`. A finished component does not change. To change one,
362
+ declare it again from its `manifest` (see
363
+ [Import the files of an upload field](#import-the-files-of-an-upload-field)).
364
+
365
+ ### The Knowledge of the chosen collections
366
+
367
+ `payloadKnowledge` takes the Payload Declarations File, the Gateway and the
368
+ chosen collections. A collection that the file does not have fails at
369
+ declaration. Each schema FQN is `<knowledge fqn>.<collection>`. For each
370
+ collection:
371
+
372
+ - `draftImport`: the Draft Import setting. `published` (the default)
373
+ imports Published Documents only. `published_and_drafts` also imports the
374
+ drafts, with Publication State `draft`.
375
+ - `importExclusionRules`: Import Exclusion Rules. A matching rule keeps the
376
+ document out of CI and removes the item that CI already holds.
377
+
378
+ `schedules` gives the connector instance one pipeline, `repair`: each
379
+ schedule runs a full import of every chosen collection. Without `schedules`,
380
+ the connector instance has no pipeline, and no full import repairs a missed
381
+ push. `schedules: []` gives the `repair` pipeline with no schedule.
382
+
383
+ The helper keeps a relation rule only between chosen collections. A
384
+ relation to a collection that the package does not choose stays the text
385
+ field `<field>_title`.
386
+
387
+ The helper declares the Document Body `ciBody` of each schema as an
388
+ ordinary string field. It goes into the item embedding (`embedEntities:
389
+ true`, and `includeInItemEmbedding` in `fieldSemantics["/ciBody"]`), and CI
390
+ displays it as Markdown (`renderer: "markdown"` in
391
+ `fieldPresentation["/ciBody"]`) among the item's detail fields
392
+ (`displayDefaults.details`), in the Dashboard item view and the Studio item
393
+ detail. The package adds no mark of its own.
394
+
395
+ Each binding that the helper makes writes Knowledge edits back to Payload
396
+ through the Remote-first write, for a collection that the plugin marks
397
+ `writable: true`. An edit of a field mapped one to one from a Payload field
398
+ changes that field in Payload. CI refuses an edit of the Document Body, the
399
+ Public URL, the Publication State, a Payload timestamp or a relation before
400
+ it calls the site. When an editor clears a field in Payload, the next push or
401
+ import clears it in CI. On the Dashboard path, an administrator sets this in
402
+ the binding settings: the update mode **partial**, the outbound strategy
403
+ **Remote-first** and a two-way rule for each field mapped one to one.
404
+
405
+ A Knowledge write follows the state of the Payload Document:
406
+
407
+ - An edit of a published item publishes it on the site. An edit of a draft
408
+ item saves the draft. An edit of a published item that has a newer draft
409
+ fails with `conflict`.
410
+ - A Knowledge delete moves the Payload Document to trash. A Knowledge delete
411
+ never deletes a document for ever. CI refuses a delete in a collection
412
+ without trash, a delete of a draft item, and a delete of a published item
413
+ that has a newer draft.
414
+ - On a binding with the Draft Import setting `published`, CI refuses a
415
+ Knowledge create in a collection with drafts
416
+ (`draft_create_not_imported`): the site would save a draft that the
417
+ binding does not import.
418
+ - A writable collection declares `access: "read_write"` in the Gateway
419
+ manifest. When you mark a collection `writable: true` on a site that CI
420
+ already imports, CI gets one Knowledge manifest refresh.
421
+
422
+ ### The parts that a site must not forget
423
+
424
+ Each of these parts prevents a setup trap. The helpers declare the first
425
+ three; the package declares the last one itself:
426
+
427
+ - **The External Apps dependency.** The connector instance runs on the
428
+ Knowledge Gateway template of `builtin.core.external-apps`.
429
+ `payloadPackageDependencies` names that package. Without it, install
430
+ answers 409 `Required Knowledge template ... knowledge-gateway is absent
431
+ from the exact graph`.
432
+ - **A repair schedule.** Give `schedules` to `payloadKnowledge`, so that a
433
+ full import repairs missed pushes.
434
+ - **The push grant.** CI makes one External App for the Gateway,
435
+ `<gateway fqn>.application`. The Push Job signs in as the server of that
436
+ app, and a push needs Knowledge data at `manage`.
437
+ `payloadGatewayPushGrant` grants it. Without it, each push answers 403
438
+ `scope_denied`. The push credential is a Server Credential of that app:
439
+ enrollment issues it and sends it to the site. An administrator cannot
440
+ create or rotate it.
441
+ - **The visitor Data Policy, the member policy and the visitor Agent.** No
442
+ helper declares them; see [Website search](#website-search).
443
+
444
+ ## Deploy order
445
+
446
+ Deploy the site first, then the package release. Install reads the site's
447
+ Gateway manifest once. It checks the operations against the Payload
448
+ Operation Contract, and the collection of each declared binding against
449
+ the site's Knowledge resources. A binding whose collection the site does
450
+ not serve fails the install with an error that names the binding and the
451
+ collection.
452
+
453
+ Use the same order for each upgrade: deploy a site that serves a new
454
+ collection before the release that binds it.
455
+
456
+ Deploy the package with its Gateway URL:
457
+
458
+ ```sh
459
+ CI_MANAGEMENT_TOKEN=<token> CI_PUBLISHER_TOKEN=<publisher secret> \
460
+ ci deploy --backend-url <ci-url> --organization <organization-id> \
461
+ --declaration ./ci-package/package.ts \
462
+ --gateway-url <gateway fqn>=https://www.example.com/api/ci-gateway \
463
+ --install-dependencies
464
+ ```
465
+
466
+ `--install-dependencies` installs a required dependency release without a
467
+ prompt. An Organization that was set up with its standard packages holds
468
+ `builtin.core.external-apps` without a release pin. Without the flag, the
469
+ deploy then stops with 409 `manual_prerequisite`, and the message
470
+ `'<package>' requires 'builtin.core.external-apps' release <release>, which
471
+ this Organization has not installed. Install it first: ci package install
472
+ ...`.
473
+
474
+ Install creates the Gateway Connection, the tools, the schemas, the
475
+ connector instance and its bindings, and enrolls the Gateway: the site
476
+ stores the grant and the push credential in `ci-gateway-grants`. After an
477
+ SDK upgrade that changes the enrollment, a Gateway enrolls again on the
478
+ next deploy.
479
+
480
+ ## First import
481
+
482
+ Install starts no import. Until the first full import, CI holds only the
483
+ documents that the site pushes after a change. A push before the first pull
484
+ of a Dashboard binding imports nothing: CI answers 202 and imports the
485
+ records after the first run. The first full import runs on the declared
486
+ schedule. To start it now, open the binding in the Dashboard (Knowledge >
487
+ Connectors > the connector > the binding), select **Run now**, and set
488
+ **Run mode** to **Full**.
489
+
490
+ A later change of the Draft Import setting or of the Import Exclusion Rules
491
+ of a binding starts one full run of that binding, from a package release
492
+ or from a save in the binding settings.
493
+
494
+ ## Website search
495
+
496
+ A visitor Agent searches the imported schemas as the visitor, so the
497
+ visitor's Knowledge Data Policy decides which items it finds.
498
+
499
+ ### Keep drafts out with a visitor Data Policy
500
+
501
+ With `published_and_drafts`, CI also holds the `draft` items. The visitor
502
+ Data Policy keeps only `published` items in public search. The same
503
+ `where` can hide flagged items, such as `membersOnly`:
504
+
505
+ ```ts
506
+ const capabilities = declareAccessCapabilities({
507
+ definition: { lifecycle, nodes: { content: { kind: "readManage" } } },
508
+ manifest: { fqn: `${input.fqn}.capabilities`, version }
509
+ })
510
+ const published = eq(resource("ciPublicationState"), "published")
511
+ // A visitor reads published items only, and no members-only post.
512
+ const visitorPolicy = (
513
+ name: string,
514
+ target: typeof pages,
515
+ where: ReturnType<typeof and>
516
+ ) =>
517
+ declareAccessKnowledgeDataPolicy({
518
+ definition: {
519
+ capability: requires(capabilities.content, "read"),
520
+ lifecycle,
521
+ operation: "read",
522
+ target,
523
+ where
524
+ },
525
+ manifest: { fqn: `${input.fqn}.policies.${name}`, version }
526
+ })
527
+
528
+ visitorPolicy("pages", pages, and(published)),
529
+ visitorPolicy(
530
+ "posts",
531
+ posts,
532
+ and(published, not(eq(resource("membersOnly"), true)))
533
+ ),
534
+ ```
535
+
536
+ The visitors get `capabilities.content` from the anonymous Access Profile
537
+ of the site app:
538
+
539
+ ```ts
540
+ // A visitor chats with the site Agent and reads what its answers cite.
541
+ profile("visitor", "anonymous", [
542
+ allow(core.platform.agents),
543
+ allow(core.platform.conversations),
544
+ allow(core.platform.knowledge),
545
+ allow(capabilities.content, "read")
546
+ ]),
547
+ grant("visitor", { applicationVisitors: app }),
548
+ ```
549
+
550
+ A visitor chat needs `core.platform.conversations`. Without it, the chat
551
+ answers 403 `capability_missing`.
552
+
553
+ ### Give members their own policy
554
+
555
+ A package `access` policy on a schema replaces the core default policy
556
+ (`data.knowledge` at `read`) for each caller of that schema, administrators
557
+ included. With only the visitor policy, members read none of its items, and
558
+ the admin Knowledge API cannot read them. Declare a member policy next to
559
+ the visitor policy:
560
+
561
+ ```ts
562
+ declareAccessKnowledgeDataPolicy({
563
+ definition: {
564
+ capability: requires(core.data.knowledge, "read"),
565
+ lifecycle,
566
+ operation: "read",
567
+ target: pages
568
+ },
569
+ manifest: { fqn: `${input.fqn}.policies.pages-members`, version }
570
+ })
571
+ ```
572
+
573
+ Policies on one schema and operation combine with OR: a visitor gets the
574
+ published items, and a member gets each item.
575
+
576
+ ### Read as the visitor in the Agent
577
+
578
+ Give the visitor Agent `dataAccess: { knowledge: "user" }`. A data source
579
+ that `dataAccess` does not name runs in the Agent's own mode and reads
580
+ everything. Without this line, the Agent finds the `draft` items and the
581
+ members-only items for each visitor.
582
+
583
+ ```ts
584
+ // The visitor's Agent reads Knowledge with the visitor's own access.
585
+ declareAgent({
586
+ definition: {
587
+ audience: { anonymous: [app] },
588
+ behavioralBoundaries: [],
589
+ dataAccess: { knowledge: "user" },
590
+ lifecycle,
591
+ objectives: ["Answer visitors from the published site content"],
592
+ operatingInstructions:
593
+ "Search the site content with Advanced Information Retrieval and answer with what it finds.",
594
+ responsibility: "Answer the questions of website visitors",
595
+ uses: { tools: ["builtin.core.information.tools.advanced-retrieval"] }
596
+ },
597
+ manifest: { fqn: names.agent, version },
598
+ presentation: { displayName: "Site search" }
599
+ })
600
+ ```
601
+
602
+ ### Offer the search tool to the visitors
603
+
604
+ CI offers the Advanced Information Retrieval tool to Organization members
605
+ only. After install, add the anonymous visitors of the site app to its
606
+ audience:
607
+
608
+ ```http
609
+ PUT /admin/ai/tool-instances/<tool instance id>/audience
610
+ x-organization-id: <organization id>
611
+
612
+ { "entries": [{ "kind": "organization" }, { "kind": "anonymous", "applicationId": "<site app id>" }] }
613
+ ```
614
+
615
+ The **Permissions** tab of the tool in the Dashboard keeps this entry when
616
+ it saves, but it cannot add it.
617
+
618
+ ## Choose the imported languages
619
+
620
+ A collection with localized fields gives one item for each language, with
621
+ the language in `ciLanguage`. To import only some languages, add an Import
622
+ Exclusion Rule on `ciLanguage`:
623
+
624
+ ```ts
625
+ collections: {
626
+ pages: {
627
+ importExclusionRules: [
628
+ {
629
+ conditions: [
630
+ { field: "ciLanguage", operator: "not_in", values: ["en", "it"] }
631
+ ]
632
+ }
633
+ ]
634
+ }
635
+ }
636
+ ```
637
+
638
+ On the Dashboard path, add the same rule in the binding settings
639
+ (**Import Exclusion Rules**).
640
+
641
+ ## Import the files of an upload field
642
+
643
+ The import is text only by default. CI imports and indexes a file only when
644
+ the binding maps its upload field to a Knowledge File field.
645
+ `payloadKnowledge` and a new Dashboard binding map no upload field, and the
646
+ Payload SDK has no helper input for a file field yet.
647
+
648
+ An upload field of an exposed collection holds a connector file source for
649
+ each file that the Integration User can read: `filename`, `source_id`
650
+ (`<upload collection>:<document id>`), `external_hash`,
651
+ `external_modified_at`, `url` and `url_expires_at`. A has-many upload field
652
+ holds a list. The `url` is a signed link of the Gateway's file route,
653
+ `<Gateway URL>/files`. For one hour, it serves the stored file as Payload
654
+ does, as the Integration User, with the site's access rules on. After that,
655
+ CI reads the record again for a new link. The site signs the link with a key
656
+ that it derives from the Payload `secret`.
657
+
658
+ On the code-first path, the components that `payloadKnowledge` returns do
659
+ not change. Declare the schema and the connector instance again from their
660
+ manifests: add a File field to the schema and a rule to its binding. For an
661
+ `image` upload field of `pages`:
662
+
663
+ ```ts
664
+ import {
665
+ declareKnowledgeConnectorInstance,
666
+ declareKnowledgeEntitySchema,
667
+ definePackageSchema
668
+ } from "@collective-intelligence/extensions-sdk"
669
+
670
+ const {
671
+ displayName,
672
+ fqn,
673
+ kind: _kind,
674
+ schema: projection,
675
+ version: schemaVersion,
676
+ ...pagesDefinition
677
+ } = knowledge.schemas.pages.manifest
678
+ const pagesWithImage = declareKnowledgeEntitySchema({
679
+ definition: {
680
+ ...pagesDefinition,
681
+ // CI indexes the text of the image file.
682
+ fieldSemantics: {
683
+ ...pagesDefinition.fieldSemantics,
684
+ "/image": { indexContent: true }
685
+ },
686
+ fileFields: { image: { accepts: ["image/*"], multiple: false } },
687
+ // The same record schema, from its declared projection.
688
+ schema: definePackageSchema({
689
+ native: projection.document,
690
+ projections: { input: projection },
691
+ provider: "knowledge_record",
692
+ validate: (value) => ({ value })
693
+ })
694
+ },
695
+ manifest: { fqn, version: schemaVersion },
696
+ presentation: { displayName }
697
+ })
698
+
699
+ const {
700
+ displayName: connectorName,
701
+ fqn: connectorFqn,
702
+ kind: _connectorKind,
703
+ version: connectorVersion,
704
+ ...connectorDefinition
705
+ } = knowledge.connectorInstance.manifest
706
+ const connectorInstance = declareKnowledgeConnectorInstance({
707
+ definition: {
708
+ ...connectorDefinition,
709
+ entityBindings: (connectorDefinition.entityBindings ?? []).map((binding) =>
710
+ binding.key === "pages"
711
+ ? {
712
+ ...binding,
713
+ fieldMap: [
714
+ ...(binding.fieldMap ?? []),
715
+ {
716
+ direction: "inbound",
717
+ local: "image",
718
+ op: "path",
719
+ remote: "image",
720
+ skipIfNull: true
721
+ }
722
+ ]
723
+ }
724
+ : binding
725
+ )
726
+ },
727
+ manifest: { fqn: connectorFqn, version: connectorVersion },
728
+ presentation: { displayName: connectorName }
729
+ })
730
+ ```
731
+
732
+ Put `pagesWithImage`, the other schemas (`knowledge.schemas.posts`) and
733
+ `connectorInstance` into `declarePackage`, in place of
734
+ `...knowledge.components`. A file field is read-only in CI: a Knowledge edit
735
+ never writes it to Payload.
736
+
737
+ On the Dashboard path, add a File field to the schema and map the upload
738
+ field to it in the **Field map** tab of the binding.
739
+
740
+ ## Connect the site in the Dashboard
741
+
742
+ An administrator connects the site with the existing Gateway setup screens.
743
+ The import needs no package on this path. A Knowledge Data Policy still
744
+ comes only from a package.
745
+
746
+ 1. Register a confidential External App for the site, and issue a Server
747
+ Credential of it. The **Connect an app** dialog of **Apps > External**
748
+ shows the CLI commands; add `--type confidential`:
749
+
750
+ ```sh
751
+ ci apps enroll --fqn <app fqn> --redirect-uri <site callback URL> \
752
+ --type confidential --enable --env-file .env.local
753
+ ci apps credentials upsert <app fqn> --name site-push --env-file .env.push
754
+ ```
755
+
756
+ The Push Job signs in with the Server Credential: `CI_CLIENT_ID` and
757
+ `CI_CLIENT_SECRET` of `.env.push`. The client secret of the registration
758
+ (`CI_CLIENT_SECRET` of `.env.local`) cannot push.
759
+
760
+ 2. Let the app's server push. In **Organization > Access > Roles**, create a
761
+ role that is given to **App server**, with **Knowledge data**
762
+ (`data.knowledge`) at **Manage**. The grant editor of the Dashboard
763
+ cannot give a role to an app server, so give it with the admin API:
764
+
765
+ ```http
766
+ POST /admin/access/grants
767
+ x-organization-id: <organization id>
768
+
769
+ { "grantee": { "applicationServer": "<app fqn>" }, "profile": { "id": "<role id>" } }
770
+ ```
771
+
772
+ 3. Make a setup credential: a long random secret. In **Organization >
773
+ Developers > Variables**, keep it in a secret Organization variable, and
774
+ give the same value to the site.
775
+
776
+ 4. Start the site with `ci.dashboard`:
777
+
778
+ ```ts
779
+ ci: {
780
+ audience: process.env.CI_GATEWAY_URL ?? "",
781
+ dashboard: {
782
+ app: {
783
+ clientId: process.env.CI_PUSH_CLIENT_ID ?? "",
784
+ clientSecret: process.env.CI_PUSH_CLIENT_SECRET ?? ""
785
+ },
786
+ setupCredentials: [process.env.CI_GATEWAY_SETUP_CREDENTIAL ?? ""]
787
+ },
788
+ trustedIssuers: [
789
+ {
790
+ issuer: process.env.CI_TENANT_URL ?? "",
791
+ tenantUrl: process.env.CI_TENANT_URL ?? ""
792
+ }
793
+ ]
794
+ }
795
+ ```
796
+
797
+ 5. In **Knowledge > Connectors > Templates**, create a **Knowledge gateway**
798
+ connector:
799
+ - **baseUrl**: the Gateway URL.
800
+ - **credential**: the variable reference
801
+ `organization-variable://<VARIABLE KEY>`. A bare variable key fails
802
+ with "Could not register Gateway connection."
803
+ - **Authorized application**: the External App of step 1.
804
+ - **proposalApprovalMode**: `automatic` accepts compatible changes of the
805
+ site's manifest; `review_required` waits for an administrator.
806
+
807
+ **Create & test** reads the manifest with the setup credential and
808
+ enrolls the Gateway Connection; later calls use signed CI tokens.
809
+ Select **Finalize**.
810
+
811
+ 6. In **Configure bindings** of the connector, each exposed collection shows
812
+ as a remote table. **Refresh configuration** reads the site's manifest
813
+ again, for example after the site exposes another collection.
814
+
815
+ 7. Bind each collection to a schema: choose a local schema, or **Create new
816
+ schema…**, then **Bind**. The binding settings show **Draft Import** for
817
+ a collection with drafts, and **Import Exclusion Rules**. Map the fields
818
+ in the **Field map** tab. The Gateway's remote fields show no type, and a
819
+ new schema proposes text fields. Set the type of each field that a policy
820
+ or a rule compares: for example, a checkbox such as `membersOnly` must be
821
+ a boolean field for a policy that compares it with `true`. Mark the
822
+ Document Body `ciBody` yourself: select **Include in item embedding** for
823
+ it, set its display renderer to **Markdown**, and add it to the schema's
824
+ **Display > Detail fields**. On this path, CI does not mark it.
825
+
826
+ The Knowledge Setup wizard (**Knowledge > Setup**) proposes the schemas
827
+ and the field maps. It shows only where the Knowledge Setup feature is on
828
+ for the tenant, and it needs an AI model. It proposes a relation
829
+ rule when the target collection is in the same setup, and a
830
+ `<field>_title` text field when it is not, also when the site does not
831
+ expose the target collection. Accept or remove each proposed relation
832
+ rule.
833
+
834
+ 8. Run the first import (see [First import](#first-import)).
835
+
836
+ A connection that existed before an SDK upgrade gets new resource metadata,
837
+ such as the Draft Import option and the relation proposals, only after
838
+ **Refresh configuration**.
839
+
840
+ On the Dashboard path, make the entity schemas before the package that
841
+ declares the visitor Data Policy installs. The package names each schema by
842
+ its FQN in `target`. Install refuses a policy whose schema does not exist
843
+ (`schema_unknown`). The policy's `where` uses the field keys of the CI
844
+ schema, which can differ from the Payload field names (for example
845
+ `ci_publication_state`).
846
+
847
+ ## Edit pages with an Agent
848
+
849
+ An Agent writes the pages of a writable collection with the six operations
850
+ of the Payload Operation Contract. `payloadPageEditor` declares a page editor
851
+ Skill that binds them with their approvals, and the Agent that holds it: see
852
+ [Payload page editor Skill](payload-page-editor-skill.md).
853
+
854
+ ## Traps
855
+
856
+ - No job runner for `ci-gateway`: no change gets to CI until the next
857
+ repair run.
858
+ - No new site migration after `writable: true`: the site database has no
859
+ columns for the `ciCreateKey`, `ciUpdateKey` and `ciEditor` fields.
860
+ - `never` on a Knowledge Mutate binding that reaches a Payload schema: an
861
+ Agent publishes a Knowledge edit with no person.
862
+ - A package Skill or Agent that binds Knowledge Mutate before an
863
+ administrator enables it: install refuses it as a reference to an
864
+ unavailable tool, `builtin.core.knowledge.tools.mutate`. Knowledge Mutate
865
+ ships disabled (see
866
+ [Knowledge Mutate on Payload schemas](payload-page-editor-skill.md#knowledge-mutate-on-payload-schemas)).
867
+ - No `payloadPackageDependencies` in the manifest `dependencies`: install
868
+ fails with 409.
869
+ - No `schedules` for `payloadKnowledge`: no full import repairs a missed
870
+ push.
871
+ - No `--install-dependencies` on an Organization set up with its standard
872
+ packages: deploy fails with 409 `manual_prerequisite`.
873
+ - No `payloadGatewayPushGrant` components in the package: each push fails
874
+ with 403 `scope_denied`.
875
+ - A schema or binding changed on the result of `payloadKnowledge`: a
876
+ finished component does not change. Declare it again from its `manifest`.
877
+ - A package `access` policy without a member policy: members and
878
+ administrators read none of the schema's items.
879
+ - A visitor Agent without `dataAccess: { knowledge: "user" }`: visitors
880
+ find drafts and members-only items.
881
+ - The package before the site: install fails for each collection that the
882
+ site does not serve yet.
883
+ - On the Dashboard path, the policy package before the schemas: install
884
+ refuses the policy.
885
+ - The site's CI trust (`issuer`, `tenantUrl`) must be the HTTPS public URL
886
+ of CI. A site in Docker Desktop that calls a local CI needs a
887
+ certificate that it trusts.
888
+ - A Gateway URL with a private or loopback address: CI imports the item but
889
+ does not download its files, because CI downloads only from public
890
+ addresses.