@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,134 @@
1
+ // Generated by dts-bundle-generator v9.5.1
2
+
3
+ import { AccessProfileGrantHandle, AccessProfileHandle, AgentDeclaration, ComponentManifest, ComponentPresentation, DeclarationHandle, DeclaredComponent, ExternalAppGatewayHandle, JsonObject, KnowledgeConnectorInstanceDeclaration, KnowledgeConnectorInstanceEntityBinding, KnowledgeConnectorInstanceSchedule, KnowledgeEntitySchemaDeclaration, OperationDomainDeclaration, PackageDependency, PortableOperationDeclaration, PortableOperationGatewayContract, SkillDeclaration, ToolBindingApproval } from '@collective-intelligence/extensions-sdk';
4
+
5
+ /**
6
+ * The Payload Declarations File that `payload ci-generate` writes from the
7
+ * site's Payload configuration, as JSON. A JSON import types each string as
8
+ * `string`, so the builder checks the field types and cardinalities.
9
+ */
10
+ export type PayloadDeclarationsFile = Readonly<{
11
+ collections: Readonly<Record<string, Readonly<{
12
+ /** The schema fields; each reads the `remote` field: the field map. */
13
+ fields: Readonly<Record<string, Readonly<{
14
+ options?: readonly string[];
15
+ remote: string;
16
+ /** `boolean`, `number`, `string` or `string_select`. */
17
+ type: string;
18
+ }>>>;
19
+ label: string;
20
+ /** Each relation field and the collection whose items it names. */
21
+ relations: readonly Readonly<{
22
+ /** `one` or `many`. */
23
+ cardinality: string;
24
+ field: string;
25
+ target: string;
26
+ }>[];
27
+ /** The entity schema of the collection in the Gateway manifest (AC-121). */
28
+ schema: JsonObject;
29
+ }>>>;
30
+ }>;
31
+ export type PayloadKnowledgeInput<File extends PayloadDeclarationsFile, Collection extends Extract<keyof File["collections"], string> = Extract<keyof File["collections"], string>> = Readonly<{
32
+ /**
33
+ * The chosen collections, each with the package's binding choices (Q105).
34
+ * Leave a collection out to not choose it: each key gets a schema.
35
+ */
36
+ collections: Readonly<Record<Collection, Readonly<Pick<KnowledgeConnectorInstanceEntityBinding, "draftImport" | "importExclusionRules">>>>;
37
+ domainFqn: string;
38
+ gateway: DeclarationHandle<"externalAppGateway">;
39
+ /** The connector instance; each schema FQN is `<fqn>.<collection>`. */
40
+ manifest: ComponentManifest;
41
+ presentation: ComponentPresentation;
42
+ /** Each schedule runs a full import of every chosen collection (Q18). */
43
+ schedules?: readonly Readonly<Pick<KnowledgeConnectorInstanceSchedule, "cronExpression" | "key">>[];
44
+ }>;
45
+ /**
46
+ * The declared Knowledge of the chosen collections: the schema of each, by
47
+ * collection name, and the connector instance; `components` lists them all.
48
+ */
49
+ export type PayloadKnowledge<Collection extends string = string> = Readonly<{
50
+ components: readonly DeclaredComponent<KnowledgeConnectorInstanceDeclaration | KnowledgeEntitySchemaDeclaration>[];
51
+ connectorInstance: DeclaredComponent<KnowledgeConnectorInstanceDeclaration>;
52
+ schemas: Readonly<Record<Collection, DeclaredComponent<KnowledgeEntitySchemaDeclaration>>>;
53
+ }>;
54
+ /**
55
+ * The package dependencies of a Payload Site's extension package: the
56
+ * connector instance runs on the Knowledge Gateway template of the External
57
+ * Apps package (Q17).
58
+ */
59
+ export declare const payloadPackageDependencies: readonly PackageDependency[];
60
+ /**
61
+ * Declares the Knowledge of the chosen collections from the Payload
62
+ * Declarations File (Q99, Q105, Q17): a relation to a chosen collection fills
63
+ * a relation field through a `reference` rule; a relation to any other
64
+ * collection keeps its `<field>_title` text (Q117).
65
+ */
66
+ export declare const payloadKnowledge: <const File extends PayloadDeclarationsFile, Collection extends Extract<keyof File["collections"], string>>(file: File, input: PayloadKnowledgeInput<File, Collection>) => PayloadKnowledge<Collection>;
67
+ /** The six operations that every Payload Site serves (Q59, Q93). */
68
+ export type PayloadOperationId = "create" | "delete" | "publish" | "read" | "unpublish" | "update";
69
+ /** The Payload Operation Contract; its type keeps each operation id. */
70
+ export type PayloadOperationContract = Omit<PortableOperationGatewayContract, "operationDomains"> & Readonly<{
71
+ operationDomains: readonly OperationDomainDeclaration<PortableOperationDeclaration & Readonly<{
72
+ canonicalReference: string;
73
+ id: PayloadOperationId;
74
+ }>>[];
75
+ }>;
76
+ /**
77
+ * The fixed operation contract of every Payload Site: six operations, each
78
+ * with a plain-text `collection` input. Only an SDK upgrade changes it. An
79
+ * extension package passes it to one `declareExternalAppGateway` call.
80
+ */
81
+ export declare const payloadOperationContract: PayloadOperationContract;
82
+ export type PayloadGatewayInput = Readonly<{
83
+ displayName: string;
84
+ fqn: string;
85
+ version: string;
86
+ }>;
87
+ /** The declared Gateway; `operation(id)` takes a Payload operation id. */
88
+ export type PayloadGateway = ExternalAppGatewayHandle<PayloadOperationContract>;
89
+ /** The Gateway of the site, typed with the Payload Operation Contract (Q17). */
90
+ export declare const payloadGateway: (input: PayloadGatewayInput) => PayloadGateway;
91
+ export type PayloadPageEditorInput = Readonly<{
92
+ agentFqn: string;
93
+ /** The approval of each operation in place of its default. */
94
+ approvals?: Readonly<Partial<Record<PayloadOperationId, ToolBindingApproval>>>;
95
+ gateway: ExternalAppGatewayHandle<PayloadOperationContract>;
96
+ /** The Skill's instruction text in place of the default. */
97
+ instructions?: string;
98
+ skillFqn: string;
99
+ version: string;
100
+ }>;
101
+ export type PayloadPageEditor = Readonly<{
102
+ agent: DeclaredComponent<AgentDeclaration>;
103
+ components: readonly DeclaredComponent<AgentDeclaration | SkillDeclaration>[];
104
+ skill: DeclaredComponent<SkillDeclaration>;
105
+ }>;
106
+ /**
107
+ * The page editor Skill over the six operations of the site's own Gateway,
108
+ * and the Agent that holds it (Q2, Q17). Install refuses an Agent whose held
109
+ * Skill uses a tool that the Agent does not allow, so the Agent binds one
110
+ * operation itself, which allows the Gateway's operation tools (Q94). The
111
+ * Agent's display name is the Gateway's and "page editor", for example
112
+ * "Museum site page editor": the backend refuses a second Organization Agent
113
+ * with the same display name.
114
+ */
115
+ export declare const payloadPageEditor: (input: PayloadPageEditorInput) => PayloadPageEditor;
116
+ export type PayloadGatewayPushGrantInput = Readonly<{
117
+ /** The FQN stem: the profile is `<fqn>.profile`, the grant `<fqn>.grant`. */
118
+ fqn: string;
119
+ gateway: DeclarationHandle<"externalAppGateway">;
120
+ version: string;
121
+ }>;
122
+ export type PayloadGatewayPushGrant = Readonly<{
123
+ components: readonly (AccessProfileGrantHandle | AccessProfileHandle)[];
124
+ grant: AccessProfileGrantHandle;
125
+ profile: AccessProfileHandle;
126
+ }>;
127
+ /**
128
+ * CI makes one External App for the Gateway, `<gateway fqn>.application`.
129
+ * The Push Job signs in as the server of that app, and a push needs
130
+ * Knowledge data at manage (Q17).
131
+ */
132
+ export declare const payloadGatewayPushGrant: (input: PayloadGatewayPushGrantInput) => PayloadGatewayPushGrant;
133
+
134
+ export {};
@@ -0,0 +1,24 @@
1
+ import{declareKnowledgeConnectorInstance,declareKnowledgeEntitySchema,knowledgeRecordSchema}from"@collective-intelligence/extensions-sdk";var stampedFields=new Set(["_status","createdAt","deletedAt","updatedAt"]);var externalAppsPackageFqn="builtin.core.external-apps";var knowledgeGatewayConnectorFqn=`${externalAppsPackageFqn}.connectors.knowledge-gateway`;var payloadPackageDependencies=[{fqn:externalAppsPackageFqn}];var lifecycle={deployMode:"upsert",readonly:false};var displayNameField=[{field:"display_name",scope:"entity"}];var writeBack={outboundStrategy:"remote_first",supportsOutbound:true,updateMode:"partial"};var writeBackSchema={localMutationPolicy:"connector_backed",syncable:true};var readOnlyFields=new Set([...stampedFields,"ciBody","ciPublicationState","ciUrl"]);var fieldTypes=["boolean","number","string","string_select"];var isFieldType=(type)=>fieldTypes.includes(type);var relationCardinality=(cardinality,field)=>{if(cardinality!=="one"&&cardinality!=="many"){throw new TypeError(`The relation "${field}" has the cardinality "${cardinality}": write the Payload Declarations File again with payload ci-generate`)}return cardinality==="one"?"many_to_one":"many_to_many"};var inbound=(op,local,remote)=>({direction:"inbound",local,op,remote,skipIfNull:true});var clearable=(direction,local,remote)=>({direction,local,op:"path",remote,skipIfNull:false});var payloadKnowledge=(file,input)=>{const choices=input.collections;for(const slug of Object.keys(choices)){if(!Object.hasOwn(file.collections,slug)){throw new TypeError(`"${slug}" is not a collection of the Payload Declarations File`)}}const chosen=Object.entries(file.collections).flatMap(([slug,collection])=>{const choice=choices[slug];return choice===undefined?[]:[{choice,collection,slug}]});const fqnOf=(slug)=>`${input.manifest.fqn}.${slug}`;const declared=chosen.map(({choice,collection,slug})=>{const properties={};const fieldMap=[];const body=Object.hasOwn(collection.fields,"ciBody");const fieldSemantics=body?{"/ciBody":{includeInItemEmbedding:true}}:{};for(const[name,{options,remote,type}]of Object.entries(collection.fields)){if(!isFieldType(type)){throw new TypeError(`The field "${name}" of "${slug}" has the type "${type}": write the Payload Declarations File again with payload ci-generate`)}properties[name]=options===undefined?{type}:{options,type};fieldMap.push(readOnlyFields.has(name)?inbound("path",name,remote):clearable("both",name,remote))}for(const{cardinality,field,target}of collection.relations){const relation=relationCardinality(cardinality,field);if(choices[target]===undefined){const title=`${field}_title`;properties[title]={type:"string"};fieldMap.push(clearable("inbound",title,title))}else{fieldSemantics[`/${field}`]={relation:{cardinality:relation,targetSchemaFqn:fqnOf(target)}};fieldMap.push(inbound("reference",field,field))}}return{binding:{...choice,...writeBack,bindingMode:"managed",fieldMap,key:slug,remoteCollectionId:slug,schemaFqn:fqnOf(slug)},schema:declareKnowledgeEntitySchema({definition:{...writeBackSchema,autocompleteConfiguration:{autocompleteFields:displayNameField,defaultAutocompleteFields:displayNameField},displayNameExpression:null,domainFqn:input.domainFqn,embeddingConfig:null,...body&&{displayDefaults:{details:["/ciBody"]},embedEntities:true,fieldPresentation:{"/ciBody":{renderer:"markdown"}}},...Object.keys(fieldSemantics).length>0&&{fieldSemantics},lifecycle,persistFullFieldContributions:false,schema:knowledgeRecordSchema({additionalProperties:false,properties}),usableAsDocumentScope:false,versioningEnabled:null},manifest:{fqn:fqnOf(slug),version:input.manifest.version},presentation:{displayName:collection.label}}),slug}});const connectorInstance=declareKnowledgeConnectorInstance({definition:{connections:{gateway:{gatewayFqn:input.gateway.manifest.fqn}},entityBindings:declared.map(({binding})=>binding),lifecycle,...input.schedules!==undefined&&{pipelines:[{definition:{steps:[{tasks:declared.map(({slug})=>({bindingKey:slug,kind:"entity"}))}]},key:"repair",schedules:input.schedules.map(({cronExpression,key})=>({cronExpression,importMode:"full",key}))}]},templateFqn:knowledgeGatewayConnectorFqn},manifest:input.manifest,presentation:input.presentation});return{components:[...declared.map(({schema})=>schema),connectorInstance],connectorInstance,schemas:Object.fromEntries(declared.map(({schema,slug})=>[slug,schema]))}};var contract={domain:"documents",id:"payload",version:"1.0.0"};var projection=(document)=>({dialect:"https://json-schema.org/draft/2020-12/schema",document,fidelity:"exact"});var object=(properties,optional=[])=>({additionalProperties:false,properties,required:Object.keys(properties).filter((key)=>!optional.includes(key)),type:"object"});var text=(description)=>({description,minLength:1,type:"string"});var flag=(description)=>({description,type:"boolean"});var documentVersion=(description)=>({description,type:["object","null"]});var collection=text("Slug of a Payload collection. The read operation lists the collections.");var id=text("Id of the Payload document.");var revision=text("Revision of the Payload document. An update sends the revision that the read operation returned.");var locale=text("Locale code of the site's Payload localization. Without it, the operation uses the default locale; a read gives no fallback text.");var data={description:"Field values of the document: rich text as Markdown, other fields and blocks as JSON.",type:"object"};var saved=projection(object({id,revision}));var policy=(effects)=>({authorization:{delegatedSubject:"allowed",organization:"required",principalKinds:["service_principal"],scopes:[`documents:${effects}`]},effects,execution:{mode:"synchronous",timeoutMs:30000},limits:{maxRequestBytes:1048576,maxResponseBytes:4194304},retry:{maxAttempts:3,mode:"idempotent_only"},version:contract.version});var operations=[{...policy("write"),description:"Creates a document in a writable collection. A collection with drafts saves it as a draft.",id:"create",idempotency:"requires_key",input:projection(object({collection,data,locale},["locale"])),output:saved,title:"Create a Payload document"},{...policy("write"),description:"Deletes a document of a writable collection. The mode must match whether the collection has trash.",id:"delete",idempotency:"idempotent",input:projection(object({collection,id,mode:{description:"`trash` moves the document to trash; `permanent` deletes it for ever.",enum:["trash","permanent"]}})),output:projection(object({id})),title:"Delete a Payload document"},{...policy("write"),description:"Publishes the newest draft of a document.",id:"publish",idempotency:"idempotent",input:projection(object({collection,id,locale},["locale"])),output:saved,title:"Publish a Payload document"},{...policy("read"),description:"Lists the collections of the site and, for an id, reads the newest draft and the published version of the document.",id:"read",idempotency:"safe",input:projection(object({collection,id,locale},["id","locale"])),output:projection(object({collections:{items:object({drafts:flag("The collection has drafts."),slug:text("Slug of the collection."),trash:flag("The collection has trash."),writable:flag("The operations can write the collection.")}),type:"array"},document:{anyOf:[{type:"null"},object({draft:documentVersion("The draft that is newer than the published version, or null."),id,published:documentVersion("The published version, or null."),revision})],description:"The document, or null when the input has no id."}})),title:"Read a Payload document"},{...policy("write"),description:"Unpublishes a document; its newest version stays as a draft.",id:"unpublish",idempotency:"idempotent",input:projection(object({collection,id,locale},["locale"])),output:saved,title:"Unpublish a Payload document"},{...policy("write"),description:"Saves new field values of a document. In a collection with drafts, it saves a draft. The update fails with a conflict when the document changed after the read.",id:"update",idempotency:"idempotent",input:projection(object({collection,data,id,locale,revision},["locale"])),output:saved,title:"Update a Payload document"}];var payloadOperationContract={capabilities:{resources:false},datasets:[],id:contract.id,knowledge:[],operationDomains:[{description:"The documents of a Payload CMS site.",id:contract.domain,operations:operations.map((operation)=>({...operation,canonicalReference:`${contract.id}/${contract.domain}/${operation.id}@${operation.version}`})),title:"Payload documents"}],organizationBinding:{mode:"installed_organization"},protocolVersion:"2",version:contract.version};import{declareExternalAppGateway}from"@collective-intelligence/extensions-sdk";var payloadGateway=(input)=>declareExternalAppGateway({definition:{expectedContract:payloadOperationContract},manifest:{fqn:input.fqn,version:input.version},presentation:{displayName:input.displayName}});import{bindTool,declareAgent,declareSkill}from"@collective-intelligence/extensions-sdk";var personApproves=(approvalOf,ids)=>{const approved=ids.filter((id)=>approvalOf(id)==="always");return approved.length===0?"":` A person approves each ${approved.join(" and ")}.`};var pageEditorInstructions=(approvalOf)=>`# Page editor
2
+
3
+ Write the pages of the Payload site. Visitors see only published pages. A draft stays on the site until a person publishes it.
4
+
5
+ ## Steps
6
+
7
+ 1. Read the site without an id to get its collections. Write only to a collection with \`writable: true\`. The list also tells if a collection has drafts and trash.
8
+ 2. Before you change a document, read it with its id. Keep its \`revision\`.
9
+ 3. To add a page, create it. In a collection with drafts, a new page is a draft.
10
+ 4. To change a page, update it with the \`revision\` of step 2. In a collection with drafts, the change is a new draft.
11
+ 5. Publish or unpublish a page only when the user asks for it.${personApproves(approvalOf,["publish","unpublish"])}
12
+ 6. Delete a page only when the user asks for it. Set \`mode\` to \`trash\` for a collection with trash, and to \`permanent\` for a collection without trash.${personApproves(approvalOf,["delete"])}
13
+
14
+ ## Field values
15
+
16
+ - Write rich text as Markdown: headings, bullet and numbered lists, quotes, rules (\`---\`), paragraphs, bold, italic, strikethrough, inline code and links. The site keeps as text the Markdown that its editor does not support. Blocks inside rich text, tables and uploads stay text.
17
+ - Write other fields and blocks as JSON.
18
+ - On a site with more than one language, give \`locale\` to read, create, update, publish and unpublish. Without \`locale\`, the site uses its default language. A delete removes the document in all languages.
19
+
20
+ ## Errors
21
+
22
+ - \`conflict\`: the document changed after your read, or an editor has it open. Read it again, make your change on the new version, and try one more time. If it fails again, tell the user.
23
+ - \`invalid_request\`: the message names the collection or the field. Correct that input before you call again.
24
+ `;var operations2=["read","create","update","publish","unpublish","delete"];var defaultApprovals={create:"never",delete:"always",publish:"always",read:"never",unpublish:"always",update:"never"};var lifecycle2={deployMode:"upsert",readonly:true};var payloadPageEditor=(input)=>{const{gateway}=input;const approvalOf=(id)=>input.approvals?.[id]??defaultApprovals[id];const skill=declareSkill({definition:{audience:{organization:true},instructions:input.instructions??pageEditorInstructions(approvalOf),lifecycle:lifecycle2,uses:{tools:operations2.map((id)=>bindTool(gateway.operation(id),{approval:approvalOf(id)}))}},manifest:{fqn:input.skillFqn,version:input.version},presentation:{description:"Write, publish and delete the pages of the Payload site",displayName:"Page editor"}});const agent=declareAgent({definition:{audience:{organization:true},behavioralBoundaries:["Publish, unpublish or delete a page only when the user asks for it"],lifecycle:lifecycle2,objectives:["Keep the pages of the site current"],operatingInstructions:"Load the Page editor Skill before you read or change a page of the site.",responsibility:"Edit the pages of the Payload site for the members",uses:{skills:[skill],tools:[bindTool(gateway.operation("read"),{approval:approvalOf("read"),name:"read-page"})]}},manifest:{fqn:input.agentFqn,version:input.version},presentation:{displayName:`${gateway.manifest.displayName} page editor`}});return{agent,components:[skill,agent],skill}};import{access,coreCapabilities,declareAccessProfile,declareAccessProfileGrant}from"@collective-intelligence/extensions-sdk";var lifecycle3={deployMode:"upsert",readonly:true};var payloadGatewayPushGrant=(input)=>{const profile=declareAccessProfile({definition:{appliesTo:"server",capabilities:[access.allow(coreCapabilities.data.knowledge,"manage")],lifecycle:lifecycle3},manifest:{fqn:`${input.fqn}.profile`,version:input.version},presentation:{displayName:"Payload Gateway push"}});const grant=declareAccessProfileGrant({definition:{grantee:{applicationServer:`${input.gateway.manifest.fqn}.application`},lifecycle:lifecycle3,profile},manifest:{fqn:`${input.fqn}.grant`,version:input.version}});return{components:[profile,grant],grant,profile}};export{payloadGateway,payloadGatewayPushGrant,payloadKnowledge,payloadOperationContract,payloadPackageDependencies,payloadPageEditor};
@@ -0,0 +1,379 @@
1
+ # AI primitives
2
+
3
+ Tools, Skills, Agents, workflows and Studio chat, how they compose, and how audiences, approvals, models, runs and timeouts behave.
4
+
5
+ The `next-effect-app` template ships two AI features. Its Lead qualifier Agent scores how ready a Lead is to convert, and its convert-lead workflow is the smallest workflow that the web app can start. That workflow only sets a workflow variable and writes no Lead record, so it is a starting point for your own steps. Both are built from the same small set of AI primitives, and a new demo feature usually starts as a copy of one of them. This page explains each primitive through those two features and ends with a table that helps you choose between them.
6
+
7
+ ## The building blocks
8
+
9
+ | Building block | What it is | Model inside | How it starts |
10
+ | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
11
+ | Tool | A typed, callable capability, such as a Knowledge query, a message send, a web search or your own package code. Tools are grouped in tool collections. | No | A Skill, an Agent, a workflow node or a chat turn calls it. |
12
+ | Skill | Versioned instructions with model settings, permissions and a bounded set of tools, for one AI task. | Yes | Studio chat, a Studio Skill Form, the public Skill API, MCP, a workflow Skill node, or an Agent that holds it. |
13
+ | Agent | An Organization-owned actor with a Role, held Skills, its own tools and an optional typed output. | Yes | Your server invokes it, a person talks to it in Studio, or an event or a delegation from another Agent starts it. |
14
+ | Workflow | A durable graph of steps with triggers, versions, runs, pauses and approvals. | Only in Prompt and Skill nodes | A trigger fires: webhook, schedule, Knowledge record event, external application, MCP operation or on demand. |
15
+ | Studio chat | The conversation in [Studio](studio.md) in which Organization members use the agents, tools and Skills offered to them. | Yes | A member sends a message. |
16
+
17
+ The template's Lead qualifier composes three of these. A package declares the Lead score tool, a Lead scoring Skill that binds it, and an Agent that holds the Skill and is offered to the external application:
18
+
19
+ ```mermaid
20
+ flowchart LR
21
+ tool["Lead score tool"] -->|is created in| coll["Sales tool collection"]
22
+ skill["Lead scoring Skill"] -->|binds| tool
23
+ agent["Lead qualifier Agent"] -->|holds| skill
24
+ agent -->|lists directly| tool
25
+ agent -->|lists directly| kq["Knowledge query tool"]
26
+ agent -->|offered to| app["External application"]
27
+ ```
28
+
29
+ > **Warning:** A held Skill can use only the tools that its Agent also allows, which is why
30
+ > the Lead qualifier lists the Lead score tool again. When you add a tool to a
31
+ > Skill, add it to the Agent's `tools` list too.
32
+
33
+ ## Tools
34
+
35
+ Put deterministic logic in a tool and let the model orchestrate. The Lead score tool computes the 0 to 100 score from fixed points: 40 for a work email, 30 when the email domain matches the company, 30 when sales has qualified the Lead, and 100 when the Lead is already converted. The Skill tells the model to use that score as is, so the model never produces the number itself.
36
+
37
+ A package tool is a runtime class plus a declaration:
38
+
39
+ ```ts
40
+ export class LeadScoreTool extends PackageTool<LeadScoreInput, LeadScore> {
41
+ override async execute(lead: LeadScoreInput) {
42
+ return await Effect.runPromise(scoreLead(lead));
43
+ }
44
+ }
45
+
46
+ declareTool({
47
+ definition: {
48
+ audience,
49
+ autoActivate: true,
50
+ autoInstantiate: true,
51
+ bindingScopes: ["organization"],
52
+ capabilityType: "read",
53
+ effectKind: "read_only",
54
+ input: effectSchema(leadScoreInputSchema),
55
+ output: effectSchema(leadScoreSchema, { codec: true }),
56
+ toolGuidance: {
57
+ inputRequirementsSummary: "Needs the Lead's company and email, and its status when known.",
58
+ useWhen: "Score how ready one Lead is to convert, from 0 to 100.",
59
+ },
60
+ toolCollectionFqns: [salesToolCollectionFqn],
61
+ usageScopes: ["automation", "chat", "skill"],
62
+ },
63
+ implementation: LeadScoreTool,
64
+ ...
65
+ });
66
+ ```
67
+
68
+ `usageScopes` decides where the tool can appear: in a Skill, in chat, or in automation. The template needs `automation` so that the Lead qualifier Agent can use the tool. When you omit `usageScopes`, the tool appears in all three places, and an explicit empty list makes it unavailable everywhere. The model reads `toolGuidance.useWhen` and `toolGuidance.inputRequirementsSummary` to decide when to call the tool and what to pass, so write both for the model.
69
+
70
+ A package can also bind built-in tools for web search (Exa or Tavily, which need an API key), website scraping, image generation, email, notifications, OCR, speech transcription and synthesis, and report building. External applications can use `publish-run-event`. The [Built-in catalog](../platform/built-ins.md) lists every built-in tool and says which ones are ready after install.
71
+
72
+ ## Skills
73
+
74
+ A Skill's instructions are plain Markdown. The template's Lead scoring Skill uses numbered steps and one rule that stops the model from guessing:
75
+
76
+ ```ts
77
+ const instructions = `# Lead scoring
78
+
79
+ Score one Lead with the Lead score tool. Never guess a score.
80
+
81
+ 1. Read: Take the Lead's company, email, and status from Knowledge.
82
+ 2. Score: Call the Lead score tool once with those fields.
83
+ 3. Report: Use the tool's score as is. Explain it in one sentence from the tool's reasons.
84
+ `
85
+ ```
86
+
87
+ The package passes these instructions to `declareSkill({ definition: { audience, instructions, lifecycle, uses: { tools } } })`, and the template's `uses.tools` list holds only the Lead score tool. CI stores each Skill as a versioned package, and runtime always uses the active approved version.
88
+
89
+ The same Skill can run in Studio chat, in a Studio Skill Form, through the public Skill API (`skills_invoke`, then `runs_get` or `runs_stream`), through MCP `run_skill`, in a workflow Skill node, and inside an Agent that holds it. A Skill version can pin a model. Without a pin, it uses the model that the running Organization sets for Skill turns, which defaults to the `balanced` tier. A pinned model that does not resolve is a configuration error, and CI does not fall back to another model.
90
+
91
+ ## Agents
92
+
93
+ The template declares its Agent like this:
94
+
95
+ ```ts
96
+ declareAgent({
97
+ definition: {
98
+ audience: { applications: [application] },
99
+ behavioralBoundaries: ["Never change a Lead or create an Opportunity"],
100
+ lifecycle: { deployMode: "upsert", readonly: true },
101
+ objectives: ["Score how ready a Lead is to convert, from 0 to 100"],
102
+ operatingInstructions:
103
+ "Read the Lead from Knowledge, score it with the Lead scoring Skill, then submit the score with a one-sentence rationale.",
104
+ output: { schema: effectSchema(leadQualificationSchema, { codec: true }) },
105
+ responsibility: "Qualify Leads for the sales team",
106
+ uses: {
107
+ skills: [skill],
108
+ tools: ["builtin.core.knowledge.tools.query", tool]
109
+ }
110
+ },
111
+ manifest: { fqn: leadQualifierFqn, version },
112
+ presentation: {
113
+ description: "Scores a Lead's readiness to convert.",
114
+ displayName: "Lead qualifier"
115
+ }
116
+ })
117
+ ```
118
+
119
+ CI turns the Role into the run's system message in a fixed order: `responsibility`, `objectives`, `operatingInstructions`, `behavioralBoundaries` and the declared output contract. A catalog of the held Skills follows, with the reference, name and description of each. The task and its context, for example today's date, become the user message.
120
+
121
+ Held Skills load on demand. At first the Agent sees only the catalog. When it calls the CI-owned `load-skill` tool, it receives the Skill's instructions, and only then does CI offer that Skill's tool bindings to the model. A second tool, `read-skill-resource`, returns a reference, asset or script file of a loaded Skill.
122
+
123
+ `output: { schema }` takes a codec, so the app can keep one runtime schema in its contracts package. A succeeded run returns `{ message, output? }`. `message` is the final answer, and `output` is the structured Agent Output, already valid against the schema. `output` is absent when the run saved none, for example when the Agent asked a clarifying question.
124
+
125
+ An Agent without `activity` is idle and runs only when something triggers it: an invoke call, a conversation turn, an event or a delegation. The SDK also accepts `activity: { heartbeat, schedule }`. Before a demo depends on a package Agent that runs on a schedule or a heartbeat, confirm it with one trial run. Every Agent that a package declares is an Organization Agent.
126
+
127
+ FQN string references are not type-checked when you build. Install resolves them and rolls the package back when one is missing: each held Skill must be approved, each Agent or Skill tool must be an enabled tool of the Organization, and each audience reference must exist. Only a person can install a package that declares Agents or Skills; an install with no signed-in user fails.
128
+
129
+ ## Audiences
130
+
131
+ An audience is an allow-list with five keys:
132
+
133
+ - `organization: true` for the whole Organization
134
+ - `groups` for members of the listed Groups, including subgroups unless you set `coverage: "direct"`
135
+ - `profiles` for the listed Access Profiles
136
+ - `applications` for the listed external applications
137
+ - `anonymous` for anonymous visitors of the listed applications
138
+
139
+ An omitted or empty audience offers the item to nobody. Packages never name individual users; an admin adds users in the Dashboard. The template passes `salesMembers = { groups: [salesGroup] }` as the audience of the Sales tools, the Skill and the Studio app, so every Sales member gets them, and offers the Agent to the external application only.
140
+
141
+ A tool collection does not offer its tools to anyone, even when the collection has an audience. Each tool names its own audience, so set `audience` on every tool you declare.
142
+
143
+ Whether an admin's Dashboard edit to an audience survives the next deploy depends on the item. The deploy that creates a tool or tool collection writes its audience once, and later admin edits stay. Agents and Skills follow their `lifecycle`: `upsert` rewrites the declared audience on each deploy, `init_only` keeps admin edits, and `readonly` refuses them.
144
+
145
+ The declaration of an Agent sets the most it can do: its tools, scopes, approval controls and audience. An admin can only narrow that policy, for example by removing a tool or a Skill or by narrowing a binding's settings. These restrictions survive package updates and apply from the next run. [Access](../platform/access.md) explains Groups, Access Profiles and Access Grants.
146
+
147
+ ## Approvals
148
+
149
+ An entry in a `uses.tools` list can be a binding object instead of a bare reference. A binding can rename the tool, give it a Binding Description, set its Binding Settings and choose an approval mode, and you can bind one tool several times under different names:
150
+
151
+ ```ts
152
+ uses: {
153
+ tools: [
154
+ {
155
+ fqn: "builtin.core.knowledge.tools.query",
156
+ name: "lead-query",
157
+ description: "Search the Leads of the CRM",
158
+ settings: {
159
+ // The Knowledge tools' form marks this field "x-fqn-of": "knowledge-entity-schema".
160
+ allowedEntitySchemaIds: [leadSchemaFqn]
161
+ },
162
+ approval: { rule: "Escalations" }
163
+ }
164
+ ]
165
+ }
166
+ ```
167
+
168
+ `name`, `description` and `approval` work the same way for every tool. The model sees the Binding Description in place of the tool's own description. `settings` holds the tool's own options, and the tool's Binding Settings Form defines them, so install fails on a key that the form does not define. A field that the form marks with `x-fqn-of` takes FQNs, and install translates each FQN into the id of the installing Organization's record. Install fails when an FQN names no record of that Organization, and the error names every such FQN of the binding. A binding has no tool-specific property.
169
+
170
+ `approval` has three modes. `"never"` makes no approval request for the binding. `"always"` pauses for an explicit decision by the user who started the call, and that user's eligibility to approve does not approve the call. `{ rule: "<rule name>" }` uses an approval rule of the installing Organization, with that rule's reviewers and expiry. Install fails when no rule has the name, so create the rule in the target Organization before you install a package that uses one.
171
+
172
+ Approval pauses the call and leaves the tool visible. With `"always"`, the model still sees the tool definition and can decide to call it, and the call then waits for a person.
173
+
174
+ ### Approvals by caller
175
+
176
+ The same binding behaves differently for each kind of caller:
177
+
178
+ | Caller | What happens when a call needs approval |
179
+ | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
180
+ | Studio chat or a Skill run | The run pauses until a person decides. |
181
+ | Studio Skill Form | `ask_always` forces approval of every installed tool call, even on `never` bindings. `automatic` skips approval. Other authorization checks still apply. |
182
+ | Agent run | Nobody is there to approve. CI rechecks the binding, and unless the binding is denied, it approves the call by default, records it with the reason `unattended_default`, and runs it once. |
183
+ | Workflow | An Approval node pauses the workflow for a person. Approve and Reject both resume it with the decision data, so a reject branch can continue, for example to send a rejection email with the approver's `comment`. Reviewers see a preview of up to 32 next nodes for each decision. |
184
+
185
+ > **Note:** `"always"` does not stop an autonomous Agent the way it stops a chat user.
186
+ > When a demo must show a person approving, use Studio chat, a Skill Form or a
187
+ > workflow Approval node.
188
+
189
+ ### What approval does not do
190
+
191
+ An approval authorizes one attempt. It does not check the tool input and cannot make the call succeed: an approved Knowledge Query `search` call still fails when it has no `entitySchemaId`.
192
+
193
+ The reviewer never becomes the identity that runs the tool. After approval, the call resumes as the identity that started it, which can be a person, a service principal or an app server. CI rechecks that identity's current Organization authority, so a changed action, a rejection, an expiry or revoked access blocks the call. When the recipients or destination of a send change between approval and send, CI does not send. It opens a fresh approval request under the same identity, and that request needs a new decision. Reviewers see the facts of the pending action in Studio Notifications. CI freezes those facts when the request opens and shows secrets as omitted.
194
+
195
+ ## Models
196
+
197
+ An Organization configures one model for each standard tier: `complex`, `balanced`, `fast` and `super_fast`. Agents, Prompt nodes and other AI operations name a tier, never a vendor model. When the default model of a tier is missing, disabled or archived, every run that needs that tier is unavailable.
198
+
199
+ An Agent uses the tier in its `modelTier`, or `balanced` when it sets none. Its step limit is its `maxSteps`, or else the Organization setting `agentRunMaxSteps` (default 25, maximum 100), and a run that uses all its steps fails with `step_limit_reached`. A Skill's own model and iteration settings never apply inside an Agent run. Agents have no model preset, and CI rejects the old `modelPreset` field.
200
+
201
+ ## Runs are asynchronous
202
+
203
+ The gateway in front of CI cuts a request that stays silent for 120 seconds and caps every response at 10 minutes. Anything that can run longer than about 100 seconds must therefore return an id for the caller to poll, which is why Agent, Skill and workflow invocations all return a run id.
204
+
205
+ Studio chat turns, Skill runs, approval continuations, public Skill runs and MCP `run_skill` never execute inside the HTTP request. The request admits the run and returns its id, and a worker executes the run from a durable command queue. A client follows the run's stream, and a stream that ends cleanly does not mean the run has finished. Reconnect with the last sequence (`Last-Event-ID` or `afterSequence`) until the closing frame arrives.
206
+
207
+ Inside a run, a known tool error returns to the model as a tool result. The other calls in the same batch still run and the model can try again, so a successful Skill run can show failed calls in its trace.
208
+
209
+ ### Timeouts
210
+
211
+ | Limit | Default | Effect |
212
+ | ---------------------------------------------------------- | ------------------------------------------- | ----------------------------------------------------------------------------------------- |
213
+ | AI run deadline, `aiRunDeadlineSeconds` | 300 s, minimum 30 s | The run stops and fails with "The AI run timed out after N seconds." |
214
+ | Model call, `aiLlmCallTimeoutSeconds` | 180 s | Applies to each model call. Tool execution between calls does not count. |
215
+ | Interactive timeout on synchronous routes | 75 s | Failures surface before the 90 s request deadline. |
216
+ | Webhook response, `workflowWebhookResponseDeadlineSeconds` | 25 s, maximum 100 s | The webhook answers 202 with an id to monitor. |
217
+ | `await_result` trigger, `timeoutMs` | Set on each trigger; the template uses 90 s | The caller waits up to this long. Nodes never run inside the request. |
218
+ | Agent steps, `agentRunMaxSteps` | 25, maximum 100 | The run fails with `step_limit_reached`. |
219
+ | Workflow scheduler tick | 30 s | Each node-to-node continuation can wait for the next tick, so plan demo timing around it. |
220
+
221
+ ### Calling an Agent from your server
222
+
223
+ Your server invokes an Agent with `agents.invoke({ agentId, input })`, which returns `{ runId }`. Read the result with `runs.get`, or page through live events with `runs.stream`. The input carries `{ task, context?, attachments }`, with up to five files of 5 MiB each in PNG, JPEG, WebP, GIF, PDF, text, CSV, Markdown or JSON format. CI does not accept Office files.
224
+
225
+ `runs.stream` returns three kinds of event. `agent.tool` gives the tool name and its state (running, completed or failed) without arguments or results. `agent.reasoning` gives the provider's reasoning-summary text in batches, and `agent.context` gives input and output token counts for each model step. A page holds at most 100 events, so keep polling with the last cursor. Filter the reasoning text on your server before you show it to visitors.
226
+
227
+ For a multi-turn chat, use the shared chat. Start a Conversation with the Agent with `ci.chat.createConversation({ organizationId, payload: { agentId } })`, send each message with `createChatClient(ci, { organizationId }).send({ conversationId, message })` from `@collective-intelligence/external-apps-server-sdk/chat`, and read earlier turns with `ci.chat.getTranscript`. Each turn is an ordinary Agent run, and the earlier successful turns, with their saved Agent Output, become the model's conversation history. A message sent while a turn still runs steers that turn and starts no second turn, and a resend with the same message `id` adds nothing.
228
+
229
+ `send` resolves `{ ok: true, value, runId }`: `runId` is the id of the turn's run, which the answer message also carries as `metadata.invocationId`, and `turnRunId(message)` reads it from any answer message. `runs.get`, `runs.stream`, `runs.cancel`, `runs.sources` and `runs.feedback` accept that id like the `runId` of `agents.invoke`. They answer only the caller that owns the Conversation (the member, the app server or the visitor) through the application where the Conversation started, and answer `not_found` to every other caller. As for any run, only a signed-in member reads `runs.sources` and gives `runs.feedback`. `runs.get` gives the status and `result: { message, output? }`, where `output` is the Agent Output that the turn saved. `runs.feedback` also rates a succeeded turn whose answer is only its Agent Output, with the Output's JSON text as the rated answer; a turn with neither text nor Output has no answer to rate and gets `not_found`. The member can also rate and clear the answer with `ci.chat.putAnswerFeedback` and `ci.chat.clearAnswerFeedback` (`params: { invocationId: runId }`); it is the same rating. Each completed Agent turn with an answer to rate (its text or its Agent Output) of `ci.chat.getTranscript` gives that member `feedbackTargetId` (the turn's run id) and `currentUserFeedback`, so the app shows a saved rating again after a reload. `runs.sources` gives the searched Document Versions with their pages and a download link. `runs.stream` pages the turn's events as for `agents.invoke`: `accepted`, the `agent.*` events and the application events that its tools publish, then one terminal event with the `runs.get` result. `runs.cancel` stops the turn. The answer itself streams from `GET /runs/:runId/stream` of the chat mount.
230
+
231
+ Anonymous visitors can chat with an Agent only when its audience has `anonymous: [app]` for that application and the call passes `caller: { kind: "anonymous_visitor", visitor: { issuer, subjectId } }`. Their turns run with the Agent's own bindings, never with the application's grants, and visitors never see each other's conversations.
232
+
233
+ ## Workflows
234
+
235
+ A workflow graph runs from a trigger to a Workflow input node, through action nodes, to a Workflow output node. A trigger connects only to the Workflow input, and the Workflow output receives connections only from actions. The Workflow input and the Workflow output each carry a JSON Schema contract. The template's convert-lead workflow is the smallest useful example:
236
+
237
+ ```mermaid
238
+ flowchart LR
239
+ trigger["External application trigger"] -->|event| input["Workflow input"]
240
+ input --> mark["Set Variable: mark-converted"]
241
+ mark --> output["Workflow output"]
242
+ ```
243
+
244
+ Its one action node sets a fixed patch and declares how it behaves on dry runs, errors and retries:
245
+
246
+ ```ts
247
+ {
248
+ config: {},
249
+ id: "mark-converted",
250
+ inputs: { patch: { mode: "fixed", value: { converted: true } } },
251
+ metadata: {},
252
+ settings: {
253
+ dryRun: { mode: "allow" },
254
+ onError: { mode: "fail_run" },
255
+ retry: { mode: "disabled" },
256
+ },
257
+ templateFqn: "builtin.core.workflows.nodes.actions.set-variable",
258
+ templateVersion: "1.0.0",
259
+ }
260
+ ```
261
+
262
+ A workflow with a trigger needs a run-as service principal, and CI publishes it only with one. The template declares `servicePrincipal({ fqn: convertLeadRunnerFqn, groups: [], name: "Convert lead runner", version })` and selects it with `runIdentity: { mode: "service_principal", servicePrincipal: convertLeadRunnerFqn }` on the workflow.
263
+
264
+ ### Who a run acts as
265
+
266
+ Every tool call in a run uses the current grants of the identity that the run acts as. A workflow's `runIdentity` decides that identity for a person's start. In `triggering_user` mode, the default, the run acts as the person who starts it. In `service_principal` mode, a production run that a person starts from Studio or the Dashboard acts as the workflow's run-as service principal. A test run from the workflow editor always keeps its author's identity. A workflow that runs with no person, from a schedule, an event or an app call in service mode, needs `service_principal` mode, and CI refuses to publish an Organization workflow whose schedule or event trigger has no identity to run as.
267
+
268
+ | How the run starts | The run acts as |
269
+ | --------------------------------------------------------------------------- | ---------------------------------------------- |
270
+ | A Studio trigger form, or Run in the Dashboard, in `triggering_user` mode | The signed-in person |
271
+ | A Studio trigger form, or Run in the Dashboard, in `service_principal` mode | The run-as service principal |
272
+ | A test run from the workflow editor | The author |
273
+ | An external application call with the user's delegated token | The signed-in user |
274
+ | An external application call in service mode or with `runAsApplication` | The run-as service principal |
275
+ | A schedule, a webhook, a Knowledge record event or an MCP operation | The run-as service principal |
276
+ | An Invoke Workflow node (a child workflow) | The identity of the run that started the child |
277
+
278
+ An external application call with a delegated token acts as the user in both modes. The template's web app calls convert-lead with the user's delegated token, so a convert run from the web app acts as the signed-in Sales manager and not as `convertLeadRunner`, although the workflow is in `service_principal` mode. Agents follow the same rule: an Agent run acts as the person or app that started it, and an Agent that delegates to another Agent passes on that identity. An approval reviewer never becomes the identity of a run.
279
+
280
+ A service principal has no user identity in the tool catalog, which means user-scoped tool bindings never match it. Give it a tool through an Organization binding or through a Group it belongs to.
281
+
282
+ Each trigger has an invocation mode: `attach`, `detach`, or `await_result` with a `timeoutMs`. `detach` answers at once with a durable 202, and `await_result` waits up to its timeout. The convert-lead trigger uses `{ mode: "await_result", timeoutMs: 90_000 }`. The web app starts it from its server with `createFixedWorkflowRoute` from `@collective-intelligence/external-apps-server-sdk/next`. The server owns the workflow FQN, and the browser sends only the Lead id:
283
+
284
+ ```ts
285
+ const handle = createFixedWorkflowRoute<{ leadId: string }, { leadId: string }>(
286
+ {
287
+ ...options,
288
+ idempotencyKey: ({ leadId }) => `convert-lead:${leadId}`,
289
+ // The Workflows feature in the user's slice of the app's access; CI decides the run again.
290
+ requirement: convertLeadRequirement,
291
+ resourceId: "leads",
292
+ validate: (body, { leadId }) => {
293
+ const decoded = decodeConvertBody(body)
294
+ if (Option.isNone(decoded) || decoded.value.leadId !== leadId) {
295
+ throw new TypeError("invalid_request")
296
+ }
297
+ return { leadId }
298
+ }
299
+ }
300
+ )
301
+ ```
302
+
303
+ Call a workflow by `workflowId` or `workflowFqn`, never by slug. A package workflow keeps its declaration FQN in every install, while its id differs from one install to the next.
304
+
305
+ The core catalog has these triggers: Entity Created, Entity Updated (with optional watched fields), Entity Deleted, External application, MCP operation, On-demand, Schedule (cron) and Webhook. Its action nodes are Adapter, Approval, Code Block, File Content, File URL, HTTP Request, If, Invoke Workflow, Loop, Merge, Persist Artifact, Prompt, Set Variable, Skill, Stop Error, Stored File Link, Switch and Wait. Other core packages add nodes for Documents, speech and image generation.
306
+
307
+ Two of these action nodes run a model. Prompt generates text or structured JSON with a governed model: `mode` is `"text"` or `"structured"`, `model` optionally names a tier, and `responseSchema` shapes the structured result. It returns `{ kind: "text", text }` or `{ kind: "structured", object }`. The Skill node invokes a governed Skill by `skillId` and passes it an `inputMessage`. For code without a model, Code Block runs restricted JSON-only Python or JavaScript in an approved Docker runtime.
308
+
309
+ A field that is read at runtime can take an expression instead of a fixed value: `{ mode: "expression", languageVersion: 1, source }`. Structural fields stay fixed. Expressions use a closed, Mustache-shaped language that is not JavaScript. `{{ input.customer.email }}` reads the workflow input, and `{{ nodes["Fetch customer"].result.customer.email }}` reads an upstream node. A source that is exactly one interpolation keeps its JSON type, while any text around it makes the result a string. To convert a value, add a pipe such as `{{ input.amount | number }}`. The available pipes are `string`, `number`, `boolean`, `trim`, `lower`, `upper`, `length`, `first`, `last`, `floor`, `ceil` and `datetime`.
310
+
311
+ A package workflow has a `lifecycle` with `deployMode` set to `upsert` or `init_only`, plus `readonly`. The builder shows a readonly workflow as a view and accepts only layout changes. The template uses `init_only` with `readonly: false`, so admins can edit the deployed graph and later releases do not overwrite it.
312
+
313
+ In the builder, Save accepts an incomplete draft. Test and Publish validate the full graph. A full-workflow test needs a trigger and a Workflow input connected to an action, and otherwise fails with `trigger-required`, `input-target-required` or `node-not-found`. You can test a single node without a trigger.
314
+
315
+ ### Webhook triggers
316
+
317
+ A Webhook trigger accepts `POST` requests authenticated with an API key (`authentication: "api_key"`) on a `path` made of letters, digits and `._~-`. It passes the JSON body to the workflow as `event` and answers with JSON. The call waits for the workflow result for up to `workflowWebhookResponseDeadlineSeconds`, 25 seconds by default and 100 at most, and the response depends on the workflow's state at that point:
318
+
319
+ | Workflow state | Response |
320
+ | ----------------------------- | --------------------------------------------- |
321
+ | Completed | 200 with the workflow output JSON |
322
+ | Failed | 500 with `{ error, runId, status }` |
323
+ | Still running at the deadline | 202 with a `runId` or `deliveryId` to monitor |
324
+
325
+ ### Output contracts
326
+
327
+ A workflow's public result contains only what its declared output contract binds. CI never falls back to the output of an intermediate node, and it reports success only after it has validated and stored the declared result. `runs.get` returns `result: { nativeStatus: "completed", output }`. When reading the result fails, read the same `runId` again and do not send the business command a second time.
328
+
329
+ > **Warning:** The template's convert-lead workflow declares an empty output contract (`bindings: []`, `jsonSchema: { type: "object" }`), so it returns no business fields. Add output bindings when your workflow must return data.
330
+
331
+ ## How agents reach Knowledge, Documents and datasets
332
+
333
+ An agent reads data only through the tools it is bound to. The core packages provide these tools:
334
+
335
+ | Source | Tools |
336
+ | ----------- | ----------------------------------------------------------- |
337
+ | Knowledge | `catalog`, `query`, `mutate`, `knowledge-document-read` |
338
+ | Documents | `query` |
339
+ | Information | `advanced-retrieval`, `expand-passage`, `read-source-range` |
340
+ | Datasets | `query` |
341
+
342
+ Knowledge Query has seven intents: `autocomplete`, `search`, `facets`, `facet_values`, `count`, `get` and `relation_members`. `search`, `count` and the two facet intents need an `entitySchemaId`, and `get` needs an `entityId`. A missing id fails with `invalid_input`, so tell the model in the Skill or the Role to find schema ids with Knowledge `catalog` first and never to invent one. When a schema has record or indexed-file embeddings, Query also runs semantic retrieval on PostgreSQL with pgvector, and the model never sees the vectors or the embedding provider.
343
+
344
+ Two settings decide what these tools can read. The Binding Settings of a Knowledge tool narrow it to allowed or excluded domains and entity schemas (`allowedDomainIds`, `excludedDomainIds`, `allowedEntitySchemaIds` and `excludedEntitySchemaIds`), as the `lead-query` binding above does. The Information tools take `allowedEntitySchemaIds` in the same way, and when Advanced Retrieval loads Expand Passage and Read Source Range, they use its Binding Settings. `dataAccess` on `declareAgent`, `declareSkill` or `declareWorkflow` decides, separately for `knowledge`, `documents` and `datasets`, whose permission applies. With `"user"`, the run reads what the acting person can read. With the declaration's own kind (`"agent"`, `"skill"` or `"workflow"`), which is the default, the run reads its configured resources without the caller's permission on the source. `dataAccess` grants no extra tool bindings.
345
+
346
+ ```ts
347
+ const dataAccess = {
348
+ knowledge: "user",
349
+ documents: "agent"
350
+ } satisfies DataAccess<"agent">
351
+ ```
352
+
353
+ [Knowledge](../data/knowledge.md) and [Datasets](../data/datasets.md) explain the data that these tools read.
354
+
355
+ ## Tool, Skill, Agent or workflow
356
+
357
+ | | Tool | Skill | Agent | Workflow |
358
+ | --------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
359
+ | Model inside | No | Yes | Yes | Only in Prompt and Skill nodes |
360
+ | Who decides the steps | Your code | The model, guided by the instructions | The model, guided by the Role and held Skills | The graph you build |
361
+ | How it starts | Another primitive or a chat turn calls it | Chat, Skill Form, API, MCP, workflow node or Agent | Your server, a Studio conversation, an event or a delegation | Webhook, schedule, record event, external application, MCP or on demand |
362
+ | Human approval | Set on its binding | The run pauses for a decision | Approved by default and recorded | Approval node |
363
+ | Output | Typed by its output schema | The run's result | `message` plus typed `output` | The declared output contract |
364
+ | Pick it when | You need one deterministic, typed action such as score, fetch or send | One AI task with a bounded tool set must run in several places | You need a long-lived Role with an audience, typed output, conversation history or unattended runs | The steps are fixed and you need triggers, approvals or a typed result |
365
+
366
+ Most features combine these primitives. The Lead qualifier uses a deterministic tool, a Skill that tells the model how to use it, and an Agent that holds the Skill for the external application. Convert-lead is a workflow because its one step is fixed and the web app waits for the result, so it needs no model. When a workflow step needs AI, use a Prompt or Skill node. [Scenarios](../scenarios/index.md) walks through more demo cases.
367
+
368
+ ## Not covered here
369
+
370
+ This page does not cover Personal Agents (admins create them in the Dashboard), Studio chat Projects, running Skill scripts, or the planned cancel and retry controls for Agent runs.
371
+
372
+ ## Related pages
373
+
374
+ - [Studio](studio.md)
375
+ - [Knowledge](../data/knowledge.md)
376
+ - [Datasets](../data/datasets.md)
377
+ - [Extensions](../develop/extensions.md)
378
+ - [Access](../platform/access.md)
379
+ - [Scenarios](../scenarios/index.md)