@salsita-ai/sdk 0.50.0-develop.514d19d58c → 0.50.0-develop.98e8b1502f

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 (148) hide show
  1. package/README.md +19 -11
  2. package/dist/application-spec/errors/diagnostic-codes.d.ts +6 -0
  3. package/dist/application-spec/errors/diagnostic-codes.js +1 -1
  4. package/dist/application-spec/errors/diagnostic-messages.d.ts +6 -0
  5. package/dist/application-spec/errors/diagnostic-messages.js +1 -1
  6. package/dist/application-spec/generate-application/code/domain-runtime-files.js +1 -1
  7. package/dist/application-spec/generate-application/code/templates/application-types.js +6 -6
  8. package/dist/application-spec/generate-application/code/templates/configurator-domain-code.d.ts +1 -0
  9. package/dist/application-spec/generate-application/code/templates/configurator-domain-code.js +11 -8
  10. package/dist/application-spec/generate-application/code/templates/domain-spec/generate-domain-block.d.ts +3 -1
  11. package/dist/application-spec/generate-application/code/templates/domain-spec/generate-domain-block.js +70 -66
  12. package/dist/application-spec/generate-application/code/templates/domain-spec/generate-phx-globals.js +3 -0
  13. package/dist/application-spec/generate-application/code/templates/domain-spec.js +5 -5
  14. package/dist/application-spec/generate-application/code/templates/domain.js +2 -2
  15. package/dist/application-spec/generate-application/code/templates/global-definition/generate-action-types.d.ts +11 -0
  16. package/dist/application-spec/generate-application/code/templates/global-definition/generate-action-types.js +8 -0
  17. package/dist/application-spec/generate-application/code/templates/global-definition/index.d.ts +1 -0
  18. package/dist/application-spec/generate-application/code/templates/global-definition/index.js +1 -1
  19. package/dist/application-spec/generate-application/code/templates/globals.js +1 -0
  20. package/dist/application-spec/generate-application/code/templates/skills/phoenix-create-configurator-skill.js +3 -1
  21. package/dist/application-spec/generate-application/code/templates/skills/phoenix-feedback-skill.js +39 -16
  22. package/dist/application-spec/generate-application/code/templates/skills/phoenix-review-skill.js +4 -2
  23. package/dist/application-spec/generate-application/code/templates/skills/sdk-content.d.ts +3 -1
  24. package/dist/application-spec/generate-application/code/templates/skills/sdk-content.js +2 -2
  25. package/dist/application-spec/generate-application/runtime/configurator-runtime/configurator-runtime.d.ts +2 -0
  26. package/dist/application-spec/generate-application/runtime/configurator-runtime/configurator-runtime.js +1 -1
  27. package/dist/application-spec/generate-application/runtime/sections/actions-runtime.d.ts +14 -0
  28. package/dist/application-spec/generate-application/runtime/sections/actions-runtime.js +1 -0
  29. package/dist/application-spec/generate-application/runtime/sections/index.d.ts +1 -0
  30. package/dist/application-spec/generate-application/runtime/sections/index.js +1 -1
  31. package/dist/application-spec/parse-application-files/categorize/categorize-files.d.ts +3 -1
  32. package/dist/application-spec/parse-application-files/categorize/categorize-files.js +1 -1
  33. package/dist/application-spec/parse-application-files/merge/index.d.ts +1 -0
  34. package/dist/application-spec/parse-application-files/merge/index.js +1 -1
  35. package/dist/application-spec/parse-application-files/merge/merged-actions.d.ts +11 -0
  36. package/dist/application-spec/parse-application-files/merge/merged-actions.js +1 -0
  37. package/dist/application-spec/parse-application-files/merge/merged-spec.d.ts +2 -0
  38. package/dist/application-spec/parse-application-files/merge/merged-spec.js +1 -1
  39. package/dist/application-spec/parse-application-files/raw-spec/index.d.ts +1 -0
  40. package/dist/application-spec/parse-application-files/raw-spec/index.js +1 -1
  41. package/dist/application-spec/parse-application-files/raw-spec/raw-actions.d.ts +18 -0
  42. package/dist/application-spec/parse-application-files/raw-spec/raw-actions.js +1 -0
  43. package/dist/application-spec/parse-application-files/raw-spec/raw-assistant.d.ts +14 -2
  44. package/dist/application-spec/parse-application-files/raw-spec/raw-assistant.js +1 -1
  45. package/dist/application-spec/parse-application-files/raw-spec/raw-spec-file.d.ts +2 -0
  46. package/dist/application-spec/parse-application-files/raw-spec/raw-spec-file.js +1 -1
  47. package/dist/application-spec/parse-application-files/resolve/resolve-import-modules.js +1 -1
  48. package/dist/application-spec/parse-application-files/spec/application/application-spec.js +1 -1
  49. package/dist/application-spec/parse-application-files/spec/application/configurator-spec/configurator-spec.d.ts +4 -2
  50. package/dist/application-spec/parse-application-files/spec/application/configurator-spec/configurator-spec.js +1 -1
  51. package/dist/application-spec/parse-application-files/spec/common/index.d.ts +1 -0
  52. package/dist/application-spec/parse-application-files/spec/common/index.js +1 -1
  53. package/dist/application-spec/parse-application-files/spec/common/schema-ref-resolver.d.ts +23 -0
  54. package/dist/application-spec/parse-application-files/spec/common/schema-ref-resolver.js +1 -0
  55. package/dist/application-spec/parse-application-files/spec/model/names/action-name.d.ts +10 -0
  56. package/dist/application-spec/parse-application-files/spec/model/names/action-name.js +1 -0
  57. package/dist/application-spec/parse-application-files/spec/model/names/index.d.ts +1 -0
  58. package/dist/application-spec/parse-application-files/spec/model/names/index.js +1 -1
  59. package/dist/application-spec/parse-application-files/spec/sections/actions.d.ts +35 -0
  60. package/dist/application-spec/parse-application-files/spec/sections/actions.js +1 -0
  61. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-field-type.d.ts +3 -14
  62. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-field-type.js +1 -1
  63. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.d.ts +12 -3
  64. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.js +1 -1
  65. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant.d.ts +5 -3
  66. package/dist/application-spec/parse-application-files/spec/sections/index.d.ts +1 -0
  67. package/dist/application-spec/parse-application-files/spec/sections/index.js +1 -1
  68. package/dist/configurator/application-runtime/extensions/configurator-extension-systems.d.ts +2 -1
  69. package/dist/configurator/application-runtime/extensions/configurator-extension-systems.js +1 -1
  70. package/dist/configurator/application-runtime/extensions/selectors.d.ts +2 -1
  71. package/dist/configurator/application-runtime/extensions/selectors.js +1 -1
  72. package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.d.ts +35 -0
  73. package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.js +1 -0
  74. package/dist/configurator/{assistant → application-runtime/extensions/systems/assistant-system}/browser-details.d.ts +1 -1
  75. package/dist/configurator/application-runtime/extensions/systems/assistant-system/browser-details.js +1 -0
  76. package/dist/configurator/{assistant → application-runtime/extensions/systems/assistant-system}/graphql-tools.d.ts +13 -14
  77. package/dist/configurator/application-runtime/extensions/systems/assistant-system/graphql-tools.js +1 -0
  78. package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.js +1 -1
  79. package/dist/configurator/application-runtime/extensions/systems/index.d.ts +1 -0
  80. package/dist/configurator/application-runtime/extensions/systems/index.js +1 -1
  81. package/dist/configurator/assistant/use-assistant-chat.js +1 -1
  82. package/dist/docs/index.json +12 -2
  83. package/dist/docs/other-features/domain-actions.mdx +418 -0
  84. package/dist/docs/phoenix/admin.mdx +2 -2
  85. package/dist/docs/phoenix/best-practices.mdx +1 -0
  86. package/dist/docs/phoenix/finalization.mdx +1 -1
  87. package/dist/docs/phoenix/integration/headless-mode-external.mdx +5 -5
  88. package/dist/docs/phoenix/integration/widget-mode-external.mdx +5 -5
  89. package/dist/docs/phoenix/phoenix-cli.mdx +59 -19
  90. package/dist/docs/phoenix/project-structure.mdx +4 -1
  91. package/dist/docs/phoenix/sdk-builder-workflow.mdx +5 -4
  92. package/dist/domain/actions/action-factory.d.ts +10 -0
  93. package/dist/domain/actions/action-factory.js +1 -0
  94. package/dist/domain/actions/prepare-action-implementations.d.ts +15 -0
  95. package/dist/domain/actions/prepare-action-implementations.js +5 -0
  96. package/dist/domain/application/application-config.d.ts +3 -1
  97. package/dist/domain/application/assistant-mutations.d.ts +15 -14
  98. package/dist/domain/application/assistant-mutations.js +1 -1
  99. package/dist/domain/core/action.d.ts +67 -0
  100. package/dist/domain/core/action.js +1 -0
  101. package/dist/domain/core/domain-factory.d.ts +4 -0
  102. package/dist/domain/core/index.d.ts +1 -0
  103. package/dist/domain/domain-builder.d.ts +7 -0
  104. package/dist/domain/domain-builder.js +1 -1
  105. package/dist/domain/domain-context/action-system/action-system.d.ts +40 -0
  106. package/dist/domain/domain-context/action-system/action-system.js +1 -0
  107. package/dist/domain/domain-context/domain-context-systems.d.ts +5 -2
  108. package/dist/domain/domain-context/index.d.ts +1 -0
  109. package/dist/domain/domain-context/index.js +1 -1
  110. package/dist/domain/domain-runtime/domain-context/domain-context.js +1 -1
  111. package/dist/domain/domain-runtime/domain-context/selectors.d.ts +4 -0
  112. package/dist/domain/domain-runtime/domain-context/selectors.js +1 -1
  113. package/dist/domain/domain-runtime/domain-runtime.d.ts +12 -0
  114. package/dist/domain/domain-runtime/spec/initialize.js +1 -1
  115. package/dist/domain/domain-runtime/spec/types.d.ts +15 -1
  116. package/dist/domain/index.d.ts +2 -0
  117. package/dist/domain/index.js +1 -1
  118. package/dist/domain/mocks/create-mock-domain-runtime.d.ts +6 -0
  119. package/dist/editor/domain-editors/DomainSpecContext.js +1 -1
  120. package/dist/editor/domain-editors/apply-spec-update.js +1 -1
  121. package/dist/editor/domain-editors/use-implementation-files.d.ts +7 -3
  122. package/dist/editor/domain-editors/use-implementation-files.js +1 -1
  123. package/dist/phoenix/application-spec/generate-assistant-prompt.d.ts +2 -2
  124. package/dist/phoenix/application-spec/generate-assistant-prompt.js +1 -1
  125. package/dist/phoenix/cli.js +1 -1
  126. package/dist/phoenix/commands/build.d.ts +5 -0
  127. package/dist/phoenix/commands/build.js +1 -1
  128. package/dist/phoenix/commands/feedback.d.ts +2 -1
  129. package/dist/phoenix/commands/feedback.js +1 -1
  130. package/dist/phoenix/commands/login.d.ts +24 -6
  131. package/dist/phoenix/commands/login.js +2 -2
  132. package/dist/phoenix/services/index.d.ts +1 -0
  133. package/dist/phoenix/services/index.js +1 -1
  134. package/dist/phoenix/services/phx-banner-plugin.d.ts +32 -0
  135. package/dist/phoenix/services/phx-banner-plugin.js +1 -0
  136. package/dist/phoenix/services/phx-licenses-plugin.d.ts +55 -0
  137. package/dist/phoenix/services/phx-licenses-plugin.js +8 -0
  138. package/dist/phoenix/services/vite-config.d.ts +2 -0
  139. package/dist/phoenix/services/vite-config.js +1 -1
  140. package/dist/phoenix/utils/index.d.ts +1 -0
  141. package/dist/phoenix/utils/index.js +1 -1
  142. package/dist/phoenix/utils/read-git-commit.d.ts +14 -0
  143. package/dist/phoenix/utils/read-git-commit.js +1 -0
  144. package/dist/react-sdk/application-runtime/runtime/create-application-runtime.d.ts +12 -0
  145. package/dist/react-sdk/domain-context/common-hooks/use-domain-context.d.ts +3 -0
  146. package/package.json +3 -3
  147. package/dist/configurator/assistant/browser-details.js +0 -1
  148. package/dist/configurator/assistant/graphql-tools.js +0 -1
@@ -4,6 +4,7 @@ import { type RawAssistant } from '../../../raw-spec/index.js';
4
4
  import type { Components } from '../../components/index.js';
5
5
  import type { Expressions } from '../../expressions/index.js';
6
6
  import type { EntityTypeName, ModelVersion } from '../../model/index.js';
7
+ import type { Actions } from '../actions.js';
7
8
  /**
8
9
  * The field sources of every entity object type: GraphQL object type name → GraphQL field name →
9
10
  * its {@link AssistantFieldSource}. Only entity object types appear, since values always resolve on
@@ -27,11 +28,16 @@ export type AssistantRecipeGroups = Readonly<Record<string, readonly AssistantRe
27
28
  * aliases expanded to their members.
28
29
  */
29
30
  export type AssistantFieldOptionsByType = Readonly<Record<string, readonly AssistantFieldOptions[]>>;
31
+ /**
32
+ * The custom mutations the manifest exposes: `Mutation` field name → the declared action it runs,
33
+ * in manifest order. Empty when the manifest exposes no action.
34
+ */
35
+ export type AssistantActions = Readonly<Record<string, string>>;
30
36
  /**
31
37
  * The printed assistant GraphQL schema, the field sources its runtime resolvers read through, the
32
38
  * entity types `deleteEntity` may delete, the fields the `modify<Type>` mutations may write, the
33
- * recipe groups `addChild` may add from, the ones `replaceEntity` may replace by and the options edges
34
- * of writable fields, aliases expanded,
39
+ * recipe groups `addChild` may add from, the ones `replaceEntity` may replace by, the options edges
40
+ * of writable fields, aliases expanded, and the actions the custom mutations run,
35
41
  * so the runtime checks the same sets the schema describes.
36
42
  */
37
43
  export interface AssistantSchema {
@@ -42,6 +48,7 @@ export interface AssistantSchema {
42
48
  readonly childRecipes: AssistantRecipeGroups;
43
49
  readonly replaceRecipes: AssistantRecipeGroups;
44
50
  readonly fieldOptions: AssistantFieldOptionsByType;
51
+ readonly actions: AssistantActions;
45
52
  }
46
53
  /** What the assistant schema is built from, besides the manifest. */
47
54
  export interface AssistantSchemaInput {
@@ -53,6 +60,8 @@ export interface AssistantSchemaInput {
53
60
  readonly expressions: Expressions;
54
61
  /** The parsed components, whose instances recipe group entries and the `options` of writable fields name. */
55
62
  readonly components: Components;
63
+ /** The declared actions, which `actions` manifest entries expose as custom mutations. */
64
+ readonly actions: Actions;
56
65
  }
57
66
  /** The declared UI state values: each non-empty kind becomes a `Navigation` field listing its values. */
58
67
  export interface AssistantStates {
@@ -67,4 +76,4 @@ export interface AssistantStates {
67
76
  * selection and navigation entry points. Returns `undefined` after reporting diagnostics when the
68
77
  * manifest does not fit the model or the generated schema is not valid GraphQL.
69
78
  */
70
- export declare const createAssistantSchema: (manifest: RawAssistant, { model, states, phxDefinitions, expressions, components }: AssistantSchemaInput, ctx: ParseContext) => AssistantSchema | undefined;
79
+ export declare const createAssistantSchema: (manifest: RawAssistant, { model, states, phxDefinitions, expressions, components, actions }: AssistantSchemaInput, ctx: ParseContext) => AssistantSchema | undefined;
@@ -1 +1 @@
1
- import{GraphQLBoolean as e,GraphQLID as t,GraphQLInputObjectType as n,GraphQLInterfaceType as i,GraphQLList as r,GraphQLNonNull as o,GraphQLObjectType as s,GraphQLSchema as a,GraphQLString as p,getNullableType as d,isInputType as l,printSchema as c,validateSchema as h}from"graphql";import{DiagnosticCode as f,diagnosticMessages as y}from"../../../../errors/index.js";import{ASSISTANT_HINTS as u}from"../../../raw-spec/index.js";import{GraphQLJSON as g,assistantFieldType as m,createAssistantRefResolver as S}from"./assistant-field-type.js";let w="AnyDomainEntity",T="RootEntity",N="RecipeGroup",E="Recipe",A="DryRun",I="DryRunError",_="FieldOption",v={section:"childRecipes",component:"childEntityRecipes",mutation:"addChild"},O={section:"replaceRecipes",component:"replaceEntityRecipes",mutation:"replaceEntity"},b=new Set(["id","type","meta"]),R=new Set(["Query","Mutation","Navigation",N,E,A,I,_,"JSON","String","Int","Float","Boolean","ID"]),$=(e,t)=>{if(!t||0===t.length)return e;let n=`One of: ${t.map(e=>`"${e}"`).join(", ")}.`;return e?/[.!?]$/.test(e)?`${e} ${n}`:`${e}. ${n}`:n},D=new Set(["id","type"]),M="The raw stored value: a string, a message descriptor or a multilingual object.",j=(e,t)=>Object.entries(e).find(([e])=>e===t)?.[1],P=(e,t,{model:n,components:i})=>{let r=new Set([e,...[...n.aliases].filter(([,t])=>t.includes(e)).map(([e])=>e)]);return i.filter(({componentName:e,typeOrAlias:n})=>e===t&&r.has(n)).map(({instanceName:e})=>String(e))},U=(...e)=>u.filter(t=>e.some(e=>e?.includes(t))),C=(e,t,n,i)=>{let{model:r}=n,o=new Map,s=new Map;for(let[a,{groups:p,hints:d}]of Object.entries(e)){let e=r.entityTypes.find(e=>e===a),l=e?[e]:[...r.aliases].find(([e])=>e===a)?.[1];if(!l){i.at(a).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE(t.section,a));continue}for(let[e,r]of(l.forEach(e=>s.set(e,U(s.get(e),d))),Object.entries(p))){let s=i.at(a,"groups",e),p=`${a}.groups.${e}`,d={groupId:r?.as??e,instanceName:e,...r?.description===void 0?{}:{description:r.description},dryRuns:r?.allowDryRuns??!0};for(let i of l){let r=P(i,t.component,n),l=o.get(i)??[],c=l.find(e=>e.group.groupId===d.groupId);r.includes(e)?c?s.error(f.ASSISTANT_DUPLICATE_RECIPE_GROUP,y.ASSISTANT_DUPLICATE_RECIPE_GROUP(t,i,d.groupId,[c.entry,p])):o.set(i,[...l,{group:d,entry:p,entryCtx:s}]):s.error(f.ASSISTANT_UNKNOWN_RECIPE_GROUP,y.ASSISTANT_UNKNOWN_RECIPE_GROUP(t,a,e,i,r))}}}let a=r.entityTypes.flatMap(e=>{let t=o.get(e);return t?[{entityType:e,groups:t}]:[]});return{groups:Object.fromEntries(a.map(({entityType:e,groups:t})=>[e,t.map(({group:e})=>e)])),hints:s,metaEntries:new Map(a.flatMap(({entityType:e,groups:[t]})=>t?[[e,t.entryCtx]]:[]))}},k=e=>`${e}Meta`,W={sameForAllInstances:e=>`All ${e} instances have the same recipe groups and recipes.`,constantDuringSession:()=>"They do not change during the session."},L={sameForAllInstances:e=>`All ${e} instances have the same options.`,constantDuringSession:()=>"The options do not change during the session."},F=(e,t,n)=>e.map(e=>` ${t[e](n)}`).join(""),K=({section:e},{groups:t,hints:n},{entityType:i,purpose:s,recipeGroup:a})=>{let p=t.filter(({dryRuns:e})=>!e).map(({groupId:e})=>e);return 0===t.length?{}:{[e]:{type:new o(new r(new o(a))),description:`The recipe groups for ${s} this ${i}: ${t.map(({groupId:e})=>e).join(", ")}. A group is listed only while the configurator offers it on the entity.${p.length>0?` Recipes of these groups cannot be dry-run: ${p.join(", ")}.`:""}${F(n,W,i)}`}}},G=({entityType:e,childRecipes:t,replaceRecipes:n,optionsEdges:i},{recipeGroup:a,fieldOption:p})=>new s({name:k(e),fields:Object.assign(K(v,t,{entityType:e,purpose:"adding children to",recipeGroup:a}),K(O,n,{entityType:e,purpose:"replacing",recipeGroup:a}),...i.map(({options:{edgeName:t,field:n,validate:i,dryRuns:s},hints:a})=>({[t]:{type:new r(new o(p)),description:`The values "${n}" of this ${e} can take, as the configurator offers them in the current state of the entity. Null when the configurator does not offer a choice on this entity. ${i?`modify${e} rejects a "${n}" value that is not in the list.`:`modify${e} does not check "${n}" against the list.`}${s?"":" Its options cannot be dry-run."}${F(a,L,e)}`}})))}),V=e=>Object.entries(e).map(([e,t])=>`${e} (${t.map(({groupId:e})=>e).join(", ")})`),Y=(e,t)=>{let{type:n,enumValues:i,localized:r,description:o}=m(e,t);return{type:{kind:"value",type:n},localized:!0===r,description:o,enumValues:i}},x=(e,t,n,i,r)=>{let o=t.startsWith("$")?((e,t,n,i)=>{let r=((e,t,{expressions:n,entityTypes:i})=>{let r=i.find(t=>t===e);for(let i of void 0===r?[e]:n.entityExpressions.get(r)?.shapeGroups??[]){let e=[...n.expressions.get(i)?.values()??[]].find(e=>e.name===t);if(e?.declaredSchema)return{implementation:e.implementation,declaredSchema:e.declaredSchema}}})(e.name,t,n);if(!r)return void i.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t));let{implementation:o}=r;if("violations"===o.kind)return void i.error(f.ASSISTANT_UNSUPPORTED_EXPRESSION,y.ASSISTANT_UNSUPPORTED_EXPRESSION(e.name,t));if("relation"===o.kind){let[{target:e,cardinality:t}]=o.params;return{type:{kind:"edge",target:e,cardinality:t},localized:!1,description:void 0}}return Y(r.declaredSchema,n.resolveRef)})(e,t,i,r):((e,t,{resolveRef:n},i)=>{let r=Object.entries(e.shape.properties).find(([e])=>e===t)?.[1];return r?Y(r,n):void i.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t))})(e,t,i,r);if(!o)return;let s=n?.as??(t.startsWith("$")?`_${t.slice(1)}`:t);return b.has(s)?void r.error(f.ASSISTANT_RESERVED_FIELD_NAME,y.ASSISTANT_RESERVED_FIELD_NAME(e.name,t,s)):{name:s,source:t,type:o.type,localized:o.localized,description:$(n?.description??o.description,o.enumValues),describedByManifest:n?.description!==void 0,enumValues:o.enumValues,valueDescription:n?.description??o.description}},q=(e,t,n,i,r)=>{let o=new Map,s=new Set(n);for(let i of[...t.flat(),...n]){let t=o.get(i.name);t?t.source!==i.source?r.error(f.ASSISTANT_FIELD_NAME_CONFLICT,y.ASSISTANT_FIELD_NAME_CONFLICT(e,i.name,[t.source,i.source])):s.has(i)&&i.describedByManifest&&o.set(i.name,{...t,description:i.description,describedByManifest:!0,valueDescription:i.valueDescription}):o.set(i.name,i)}return[...o.values()].map(e=>{let t=e.enumValues&&i(e.source);return t?{...e,enumValues:t,description:$(e.valueDescription,t)}:e})},B=({target:e,cardinality:t},n)=>{let i=n(e);switch(t){case"1-1":return new o(i);case"0-1":return i;case"0-N":case"1-N":return new o(new r(new o(i)))}},z=(e,n,i)=>{let r={id:{type:new o(t),description:i?`Unique id of the entity, e.g. "${i}-1".`:void 0},type:{type:new o(p),description:i?`Entity type name, e.g. "${i}".`:void 0}};for(let t of e)r[t.name]={type:"edge"===t.type.kind?B(t.type,n):t.type.type,description:t.description};return r},H=e=>Object.fromEntries(e.map(({name:e,source:t,localized:n})=>[e,n?{source:t,localized:!0}:{source:t}]));export const createAssistantSchema=(u,{model:b,states:W,phxDefinitions:L,expressions:F,components:K},Y)=>{let B,Q,X,J=Y.errors.length,Z=Y.at("entities"),ee=S(b.commonTypes,L),et=b.rootEntityTypes[0]??b.entityTypes[0];for(let e of b.resolvedShapes.keys())R.has(e)&&Y.error(f.ASSISTANT_RESERVED_TYPE_NAME,y.ASSISTANT_RESERVED_TYPE_NAME(e,[...R]));let en=((e,t,n)=>{let i=new Map;for(let r of e){let e=[];for(let[i,o]of Object.entries(r.entries)){let s=x(r,i,o,t,n.at(r.name,i));s&&e.push(s)}i.set(r.name,e)}return i})(((e,t,n)=>{let i=[];for(let[n,r]of t.resolvedShapes){let t=e[n];t&&i.push({name:n,shape:r,entries:t})}let r=new Set(t.resolvedShapes.keys());for(let t of Object.keys(e))r.has(t)||n.at(t).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("entities",t));return i})(u.entities??{},b,Z),{resolveRef:ee,expressions:F,entityTypes:b.entityTypes},Z),ei=q(w,[],en.get(w)??[],()=>void 0,Y),er=new Map,eo=C(u.childRecipes??{},v,{model:b,components:K},Y.at(v.section)),es=C(u.replaceRecipes??{},O,{model:b,components:K},Y.at(O.section)),ea=eo.groups,ep=es.groups,ed=new Map,el=e=>{let[t,...n]=[...b.aliases].find(([t])=>t===e)?.[1]??[];return(t&&0===n.length?er.get(t):void 0)??ef.get(e)??eh},ec=e=>er.get(e)??el(e),eh=new i({name:w,description:"Every domain entity.",fields:()=>z(ei,ec,et)}),ef=new Map([[w,eh]]),ey=new Map([[w,ei]]);for(let e of b.aliases.keys()){if(e===w)continue;let t=q(e,[ei],en.get(e)??[],()=>void 0,Y);ey.set(e,t),ef.set(e,new i({name:e,interfaces:[eh],fields:()=>z(t,ec)}))}let eu={};for(let e of b.entityTypes){let t=[w,...[...b.aliases].filter(([t,n])=>t!==w&&n.includes(e)).map(([e])=>e)],n=[...b.resolvedShapes].find(([t])=>t===e)?.[1],i=q(e,t.map(e=>ey.get(e)??[]),en.get(e)??[],e=>{let t=Object.entries(n?.properties??{}).find(([t])=>t===e)?.[1];return t&&m(t,ee).enumValues},Y);eu[e]=H(i),er.set(e,new s({name:e,interfaces:t.flatMap(e=>ef.get(e)??[]),fields:()=>{let t=ed.get(e);return{...z(i,ec),...t?{meta:{type:new o(t),description:"What the configurator offers on this entity besides its fields."}}:{}}}}))}let eg=((e,t,n)=>{let i=new Set;for(let r of Object.keys(e)){let e=t.entityTypes.find(e=>e===r),o=e?[e]:[...t.aliases].find(([e])=>e===r)?.[1];o?o.forEach(e=>i.add(e)):n.at(r).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("deletable",r))}return t.entityTypes.filter(e=>i.has(e))})(u.deletable??{},b,Y.at("deletable")),em=((e,t,n)=>{let{model:i}=t,r=((e,t,n)=>{let i=new Map;for(let[r,o]of Object.entries(e)){let e=t.entityTypes.find(e=>e===r),s=e?[e]:[...t.aliases].find(([e])=>e===r)?.[1],a=[...t.resolvedShapes].find(([e])=>e===r)?.[1];if(!s||!a){n.at(r).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("writable",r));continue}for(let e of Object.keys(o)){let t=n.at(r,e);e.startsWith("$")||D.has(e)?t.error(f.ASSISTANT_NOT_WRITABLE,y.ASSISTANT_NOT_WRITABLE(r,e)):j(a.properties,e)?s.forEach(t=>{let n=i.get(t)??new Map;i.set(t,n.has(e)?n:n.set(e,r))}):t.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("writable",r,e))}}return i})(e,i,n);return i.entityTypes.flatMap(e=>{let o=[...i.resolvedShapes].find(([t])=>t===e)?.[1],s=[...r.get(e)??[]].flatMap(([i,r])=>{let s=o&&j(o.properties,i);return(s&&((e,{property:t,writableKey:n},i,{resolveRef:r,exposed:o,sources:s},a)=>{let p=Object.entries(j(s,e)??{}),c=o.get(e)?.find(({source:e})=>e===t)?.name??p.find(([,{source:e}])=>e===t)?.[0],h=void 0===c?p.find(([e])=>e===t)?.[1]:void 0;if(h)return void a.at(n,t).error(f.ASSISTANT_FIELD_NAME_CONFLICT,y.ASSISTANT_FIELD_NAME_CONFLICT(e,t,[h.source,t],`${n}.${t}`));let{type:u,enumValues:S,localized:w,description:T}=m(i,r),N=d(u),E=c??t,A=void 0===c?$(T,S):void 0;return w?{name:E,property:t,type:g,description:A?`${A} ${M}`:M}:{name:E,property:t,type:l(N)?N:g,description:A}})(e,{property:i,writableKey:r},s,t,n))??[]});return s.length>0?[{entityType:e,fields:s}]:[]})})(u.writable??{},{model:b,resolveRef:ee,exposed:en,sources:eu},Y.at("writable")),eS=((e,t,n,i)=>{let{model:r}=n,o=new Map;for(let[s,a]of Object.entries(e)){let e=r.entityTypes.find(e=>e===s),p=e?[e]:[...r.aliases].find(([e])=>e===s)?.[1]??[];for(let[e,r]of Object.entries(a)){let a=r?.options;if(!a)continue;let d=i.at(s,e,"options"),l=`${s}.${e}`;for(let i of p){let r=t.find(e=>e.entityType===i)?.fields.find(t=>t.property===e);if(!r)continue;let s=a.as??`${r.name}Options`,p=P(i,a.componentType,n),c=o.get(i)??[],h=c.find(e=>e.options.edgeName===s||e.options.field===r.name);if(p.includes(a.instanceName))if(s===v.section||s===O.section)d.error(f.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME,y.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME(l,s,r.name));else if(h)d.error(f.ASSISTANT_DUPLICATE_OPTIONS_EDGE,y.ASSISTANT_DUPLICATE_OPTIONS_EDGE(i,h.options.edgeName===s?{edgeName:s}:{field:r.name},[h.entry,l]));else{let e={field:r.name,edgeName:s,componentType:a.componentType,instanceName:a.instanceName,validate:a.validate??!0,dryRuns:a.allowDryRuns??!0};o.set(i,[...c,{options:e,hints:U(a.hints),entry:l,entryCtx:d}])}else d.error(f.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT,y.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT(l,a,i,p))}}}return o})(u.writable??{},em,{model:b,components:K},Y.at("writable"));var ew,eT,eN,eE=[eo.metaEntries,es.metaEntries,new Map([...eS].flatMap(([e,[t]])=>t?[[e,t.entryCtx]]:[]))];for(let e of b.entityTypes){let t=eE.flatMap(t=>t.get(e)??[])[0],n=k(e);t&&[...b.resolvedShapes.keys()].some(e=>e===n)&&t.error(f.ASSISTANT_META_TYPE_NAME_CONFLICT,y.ASSISTANT_META_TYPE_NAME_CONFLICT(e,n))}let eA=(ew=()=>el(ef.has(T)?T:w),eT=()=>el(w),B=new s({name:I,description:"One reason a change cannot be made right now.",fields:{type:{type:new o(p),description:'Kind of the problem, or "uncaught".'},entityId:{type:t,description:"The entity the problem is on, when it is on one."},message:{type:p,description:"The problem as the configurator words it for the user."}}}),new s({name:A,description:"What using a recipe or writing an option would do, tried out on the configuration the query reads. Nothing is changed.",fields:()=>({ok:{type:new o(e),description:"Whether the change would succeed on the configuration the query reads."},root:{type:ew(),description:"The root entity of the configuration as it would be after the change; null when ok is false. Everything selected under it reads that configuration."},changedEntities:{type:new o(new r(new o(eT()))),description:"Every entity the change would add or modify, read from that configuration; empty when ok is false. An entity whose id the configuration does not have yet would be added, and its id may differ in the real mutation. An entity that is written to is listed even when it gets the values it already has."},deletedEntityIds:{type:new o(new r(new o(t))),description:"The ids of the entities the change would remove; empty when ok is false."},errors:{type:new o(new r(new o(B))),description:"Why the change cannot be made; empty when ok is true."}})})),eI={recipeGroup:(eN=[...Object.keys(ea).length>0?[v.mutation]:[],...Object.keys(ep).length>0?[O.mutation]:[]],Q=eN.join(" or "),X=new s({name:E,description:"One recipe of a recipe group: something that can be added to the entity, or something the entity can be replaced with, depending on the edge the group is listed under.",fields:{key:{type:new o(p),description:`Identifies the recipe within its group; pass it to ${Q} as recipeKey. Keys can change with the configuration and with the language, so read them from the listing rather than remembering them.`},name:{type:new o(p),description:"Name shown to the user."},description:{type:p},imageUrl:{type:p,description:"Thumbnail shown to the user."},dryRun:{type:eA,description:"Tries the recipe out. Each selected dry-run costs a full recalculation, so select it only on the recipes you are deciding between. Null for a group whose recipes cannot be dry-run."}}}),new s({name:N,description:"A group of recipes of an entity, as the configurator offers them to the user.",fields:{groupId:{type:new o(p),description:`Identifies the group on its entity; pass it to ${Q} as recipeGroupId.`},name:{type:new o(p),description:"Name shown to the user."},description:{type:p},recipes:{type:new o(new r(new o(X)))}}})),fieldOption:new s({name:_,description:"One choice of a field, as the configurator offers it to the user.",fields:{value:{type:new o(g),description:"The value to write to the field."},name:{type:p,description:"Name shown to the user."},description:{type:p},imageUrl:{type:p,description:"Image shown to the user."},color:{type:p,description:'Color shown to the user, as "#rrggbb".'},dryRun:{type:eA,description:"Tries writing the value to the field. Each selected dry-run costs a full recalculation, so select it only on the options you are deciding between. Null for a field whose options cannot be dry-run."}}})};for(let e of b.entityTypes){let t=j(ea,e)??[],n=j(ep,e)??[],i=eS.get(e)??[];(t.length>0||n.length>0||i.length>0)&&ed.set(e,G({entityType:e,childRecipes:{groups:t,hints:eo.hints.get(e)??[]},replaceRecipes:{groups:n,hints:es.hints.get(e)??[]},optionsEdges:i},eI))}let e_=Object.fromEntries(b.entityTypes.flatMap(e=>{let t=eS.get(e);return t?[[e,t.map(({options:e})=>e)]]:[]}));if(Y.errors.length>J)return;let ev=((e,t)=>{let n;try{let t=e();if(n=h(t).map(e=>e.message),0===n.length)return c(t)}catch(e){n=[e instanceof Error?e.message:String(e)]}t.error(f.ASSISTANT_INVALID_SCHEMA,y.ASSISTANT_INVALID_SCHEMA(n))})(()=>{var e,i;let d;return new a({query:(e=el(ef.has(T)?T:w),i=el(w),d=(e=>{let t={};for(let[n,i,r]of[["navigationState","Active navigation state.",e.navigationStates],["viewState","Active view state.",e.viewStates],["toolState","Active tool state.",e.toolStates]])r.length>1&&(t[n]={type:new o(p),description:$(i,r)});if(0!==Object.keys(t).length)return new s({name:"Navigation",description:"The active UI states of the configurator.",fields:t})})(W),new s({name:"Query",fields:{root:{type:new o(e),description:"The root entity of the configuration."},entities:{type:new o(new r(i)),args:{ids:{type:new r(new o(t))}},description:`Every entity of the configuration, or, when ids are given, those entities in the same order with null for an unknown id. Ids have the form "<Type>-<number>"${et?`, e.g. "${et}-1"`:""}; any other id is an error.`},selectedEntity:{type:new o(i),description:"The selected entity, or the root entity when nothing is selected."},...d?{navigation:{type:new o(d)}}:{}}})),mutation:(({deletableTypes:e,writableTypes:i,childRecipes:a,replaceRecipes:d,objectTypes:l,anyDomainEntity:c})=>{let h,f;if(0!==e.length||0!==i.length||0!==Object.keys(a).length||0!==Object.keys(d).length)return new s({name:"Mutation",fields:Object.assign(0===e.length?{}:{deleteEntity:{type:new o(new r(new o(t))),args:{id:{type:new o(t)}},description:`Deletes the entity with the given id, together with the entities composed into it, and returns the ids of every entity the deletion removed, the given one first. Deletable entity types: ${e.join(", ")}. Nothing can be read from removed entities afterwards, so query what you need from them before deleting.`}},0===(h=V(a)).length?{}:{addChild:{type:new o(new r(new o(c))),args:{parentId:{type:new o(t)},recipeGroupId:{type:new o(p)},recipeKey:{type:new o(p)}},description:`Adds a child to the entity with the id parentId by one recipe of one of its recipe groups. Entity types with recipe groups: ${h.join("; ")}. Read the groupId and the recipe key from "meta { childRecipes }" of the parent. Returns every entity the change added, the recipe's own first and then whatever the configurator added in response, such as a part the new child needs; the list is empty when the configurator removed them again.`}},0===(f=V(d)).length?{}:{replaceEntity:{type:new o(new r(new o(c))),args:{entityId:{type:new o(t)},recipeGroupId:{type:new o(p)},recipeKey:{type:new o(p)}},description:`Replaces the entity with the id entityId by one recipe of one of its replace recipe groups. Entity types with replace recipe groups: ${f.join("; ")}. Read the groupId and the recipe key from "meta { replaceRecipes }" of the entity. The replacement is a new entity with a new id: the id passed in no longer exists afterwards, and the replacement has the field values of its recipe, not those of the entity it replaces. Returns every entity the change added, the replacement first and then whatever the configurator added in response, such as a part the replacement needs; the list is empty when the configurator removed them again.`}},...i.flatMap(e=>{let i=l.get(e.entityType);return i?[(({entityType:e,fields:i},r)=>{let s=Object.fromEntries(i.map(({name:e,type:t,description:n})=>[e,{type:t,description:n}]));return{[`modify${e}`]:{type:r,args:{id:{type:new o(t)},delta:{type:new o(new n({name:`${e}Delta`,fields:s}))}},description:`Changes writable fields of the one ${e} with the given id: ${i.map(({name:e})=>e).join(", ")}. The delta sets only the fields it names and needs at least one; values are in stored units, as the field descriptions say. Returns the entity as it is after the change, including what the configurator adjusted in response, or null when the change caused the entity to be removed.`}}})(e,i)]:[]}))})})({deletableTypes:eg,writableTypes:em,childRecipes:ea,replaceRecipes:ep,objectTypes:er,anyDomainEntity:el(w)}),types:[...ef.values(),...er.values()]})},Y);return void 0===ev?void 0:{sdl:ev,fields:eu,deletableTypes:eg,writableFields:Object.fromEntries(em.map(({entityType:e,fields:t})=>[e,Object.fromEntries(t.map(({name:e,property:t})=>[e,t]))])),childRecipes:ea,replaceRecipes:ep,fieldOptions:e_}};
1
+ import{GraphQLBoolean as e,GraphQLID as t,GraphQLInputObjectType as n,GraphQLInterfaceType as i,GraphQLList as r,GraphQLNonNull as o,GraphQLObjectType as s,GraphQLSchema as a,GraphQLString as p,getNullableType as l,isInputType as d,isNonNullType as c,printSchema as h,validateSchema as f}from"graphql";import{isArray as u}from"@salsita-ai/common/utils";import{DiagnosticCode as y,diagnosticMessages as m}from"../../../../errors/index.js";import{ASSISTANT_HINTS as g}from"../../../raw-spec/index.js";import{createSchemaRefResolver as S,isNullableSchema as T,phxDefinitionRefName as N}from"../../common/index.js";import{GraphQLJSON as w,assistantFieldType as A}from"./assistant-field-type.js";let E="AnyDomainEntity",I="RootEntity",_="RecipeGroup",O="Recipe",v="DryRun",b="DryRunError",$="FieldOption",R={section:"childRecipes",component:"childEntityRecipes",mutation:"addChild"},j={section:"replaceRecipes",component:"replaceEntityRecipes",mutation:"replaceEntity"},M=new Set(["id","type","meta"]),D=new Set(["Query","Mutation","Navigation",_,O,v,b,$,"JSON","String","Int","Float","Boolean","ID"]),C=(e,t)=>{if(!t||0===t.length)return e;let n=`One of: ${t.map(e=>`"${e}"`).join(", ")}.`;return e?/[.!?]$/.test(e)?`${e} ${n}`:`${e}. ${n}`:n},U=new Set(["id","type"]),P="The raw stored value: a string, a message descriptor or a multilingual object.",k=(e,t)=>Object.entries(e).find(([e])=>e===t)?.[1],L=(e,t,{model:n,components:i})=>{let r=new Set([e,...[...n.aliases].filter(([,t])=>t.includes(e)).map(([e])=>e)]);return i.filter(({componentName:e,typeOrAlias:n})=>e===t&&r.has(n)).map(({instanceName:e})=>String(e))},W=(...e)=>g.filter(t=>e.some(e=>e?.includes(t))),F=(e,t,n,i)=>{let{model:r}=n,o=new Map,s=new Map;for(let[a,{groups:p,hints:l}]of Object.entries(e)){let e=r.entityTypes.find(e=>e===a),d=e?[e]:[...r.aliases].find(([e])=>e===a)?.[1];if(!d){i.at(a).error(y.ASSISTANT_UNKNOWN_TYPE,m.ASSISTANT_UNKNOWN_TYPE(t.section,a));continue}for(let[e,r]of(d.forEach(e=>s.set(e,W(s.get(e),l))),Object.entries(p))){let s=i.at(a,"groups",e),p=`${a}.groups.${e}`,l={groupId:r?.as??e,instanceName:e,...r?.description===void 0?{}:{description:r.description},dryRuns:r?.allowDryRuns??!0};for(let i of d){let r=L(i,t.component,n),d=o.get(i)??[],c=d.find(e=>e.group.groupId===l.groupId);r.includes(e)?c?s.error(y.ASSISTANT_DUPLICATE_RECIPE_GROUP,m.ASSISTANT_DUPLICATE_RECIPE_GROUP(t,i,l.groupId,[c.entry,p])):o.set(i,[...d,{group:l,entry:p,entryCtx:s}]):s.error(y.ASSISTANT_UNKNOWN_RECIPE_GROUP,m.ASSISTANT_UNKNOWN_RECIPE_GROUP(t,a,e,i,r))}}}let a=r.entityTypes.flatMap(e=>{let t=o.get(e);return t?[{entityType:e,groups:t}]:[]});return{groups:Object.fromEntries(a.map(({entityType:e,groups:t})=>[e,t.map(({group:e})=>e)])),hints:s,metaEntries:new Map(a.flatMap(({entityType:e,groups:[t]})=>t?[[e,t.entryCtx]]:[]))}},K=e=>`${e}Meta`,G={sameForAllInstances:e=>`All ${e} instances have the same recipe groups and recipes.`,constantDuringSession:()=>"They do not change during the session."},Y={sameForAllInstances:e=>`All ${e} instances have the same options.`,constantDuringSession:()=>"The options do not change during the session."},V=(e,t,n)=>e.map(e=>` ${t[e](n)}`).join(""),x=({section:e},{groups:t,hints:n},{entityType:i,purpose:s,recipeGroup:a})=>{let p=t.filter(({dryRuns:e})=>!e).map(({groupId:e})=>e);return 0===t.length?{}:{[e]:{type:new o(new r(new o(a))),description:`The recipe groups for ${s} this ${i}: ${t.map(({groupId:e})=>e).join(", ")}. A group is listed only while the configurator offers it on the entity.${p.length>0?` Recipes of these groups cannot be dry-run: ${p.join(", ")}.`:""}${V(n,G,i)}`}}},q=({entityType:e,childRecipes:t,replaceRecipes:n,optionsEdges:i},{recipeGroup:a,fieldOption:p})=>new s({name:K(e),fields:Object.assign(x(R,t,{entityType:e,purpose:"adding children to",recipeGroup:a}),x(j,n,{entityType:e,purpose:"replacing",recipeGroup:a}),...i.map(({options:{edgeName:t,field:n,validate:i,dryRuns:s},hints:a})=>({[t]:{type:new r(new o(p)),description:`The values "${n}" of this ${e} can take, as the configurator offers them in the current state of the entity. Null when the configurator does not offer a choice on this entity. ${i?`modify${e} rejects a "${n}" value that is not in the list.`:`modify${e} does not check "${n}" against the list.`}${s?"":" Its options cannot be dry-run."}${V(a,Y,e)}`}})))}),B=e=>Object.entries(e).map(([e,t])=>`${e} (${t.map(({groupId:e})=>e).join(", ")})`),z=e=>`${e.charAt(0).toUpperCase()+e.slice(1)}Result`,H=e=>{let t=(({anyOf:e,oneOf:t})=>[...e??[],...t??[]].filter(e=>"null"!==e.type))(e);return e.$ref||1!==t.length?e:t[0]},Q=(e,t)=>{let{type:n,enumValues:i,localized:r,description:s}=A(e,t),a=l(n),p=r||!d(a)?w:a;return{type:c(n)?new o(p):p,description:r?`${C(s,i)??""} ${P}`.trim():C(s,i)}},X=(e,t)=>{let n=(e=>{let t=H(e),n=t?.type==="array"&&t.items&&!u(t.items)?H(t.items):void 0,i=n??t;if(i?.$ref!==void 0&&"$DomainEntity"===N(i.$ref))return{target:i.references??E,list:void 0!==n}})(e);if(n)return{kind:"edge",...n,nullable:T(e,t),description:e.description};let{type:i,enumValues:r,localized:s,description:a}=A(e,t);return s?{kind:"value",type:c(i)?new o(w):w,description:`${a??""} ${P}`.trim()}:{kind:"value",type:i,description:C(a,r)}},J=(e,t)=>{let{type:n,enumValues:i,localized:r,description:o}=A(e,t);return{type:{kind:"value",type:n},localized:!0===r,description:o,enumValues:i}},Z=(e,t,n,i,r)=>{let o=t.startsWith("$")?((e,t,n,i)=>{let r=((e,t,{expressions:n,entityTypes:i})=>{let r=i.find(t=>t===e);for(let i of void 0===r?[e]:n.entityExpressions.get(r)?.shapeGroups??[]){let e=[...n.expressions.get(i)?.values()??[]].find(e=>e.name===t);if(e?.declaredSchema)return{implementation:e.implementation,declaredSchema:e.declaredSchema}}})(e.name,t,n);if(!r)return void i.error(y.ASSISTANT_UNKNOWN_FIELD,m.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t));let{implementation:o}=r;if("violations"===o.kind)return void i.error(y.ASSISTANT_UNSUPPORTED_EXPRESSION,m.ASSISTANT_UNSUPPORTED_EXPRESSION(e.name,t));if("relation"===o.kind){let[{target:e,cardinality:t}]=o.params;return{type:{kind:"edge",target:e,cardinality:t},localized:!1,description:void 0}}return J(r.declaredSchema,n.resolveRef)})(e,t,i,r):((e,t,{resolveRef:n},i)=>{let r=Object.entries(e.shape.properties).find(([e])=>e===t)?.[1];return r?J(r,n):void i.error(y.ASSISTANT_UNKNOWN_FIELD,m.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t))})(e,t,i,r);if(!o)return;let s=n?.as??(t.startsWith("$")?`_${t.slice(1)}`:t);return M.has(s)?void r.error(y.ASSISTANT_RESERVED_FIELD_NAME,m.ASSISTANT_RESERVED_FIELD_NAME(e.name,t,s)):{name:s,source:t,type:o.type,localized:o.localized,description:C(n?.description??o.description,o.enumValues),describedByManifest:n?.description!==void 0,enumValues:o.enumValues,valueDescription:n?.description??o.description}},ee=(e,t,n,i,r)=>{let o=new Map,s=new Set(n);for(let i of[...t.flat(),...n]){let t=o.get(i.name);t?t.source!==i.source?r.error(y.ASSISTANT_FIELD_NAME_CONFLICT,m.ASSISTANT_FIELD_NAME_CONFLICT(e,i.name,[t.source,i.source])):s.has(i)&&i.describedByManifest&&o.set(i.name,{...t,description:i.description,describedByManifest:!0,valueDescription:i.valueDescription}):o.set(i.name,i)}return[...o.values()].map(e=>{let t=e.enumValues&&i(e.source);return t?{...e,enumValues:t,description:C(e.valueDescription,t)}:e})},et=({target:e,cardinality:t},n)=>{let i=n(e);switch(t){case"1-1":return new o(i);case"0-1":return i;case"0-N":case"1-N":return new o(new r(new o(i)))}},en=(e,n,i)=>{let r={id:{type:new o(t),description:i?`Unique id of the entity, e.g. "${i}-1".`:void 0},type:{type:new o(p),description:i?`Entity type name, e.g. "${i}".`:void 0}};for(let t of e)r[t.name]={type:"edge"===t.type.kind?et(t.type,n):t.type.type,description:t.description};return r},ei=e=>Object.fromEntries(e.map(({name:e,source:t,localized:n})=>[e,n?{source:t,localized:!0}:{source:t}]));export const createAssistantSchema=(c,{model:u,states:g,phxDefinitions:T,expressions:N,components:M,actions:G},Y)=>{let V,x,H,J=Y.errors.length,et=Y.at("entities"),er=S(u.commonTypes,T),eo=u.rootEntityTypes[0]??u.entityTypes[0];for(let e of u.resolvedShapes.keys())D.has(e)&&Y.error(y.ASSISTANT_RESERVED_TYPE_NAME,m.ASSISTANT_RESERVED_TYPE_NAME(e,[...D]));let es=((e,t,n)=>{let i=new Map;for(let r of e){let e=[];for(let[i,o]of Object.entries(r.entries)){let s=Z(r,i,o,t,n.at(r.name,i));s&&e.push(s)}i.set(r.name,e)}return i})(((e,t,n)=>{let i=[];for(let[n,r]of t.resolvedShapes){let t=e[n];t&&i.push({name:n,shape:r,entries:t})}let r=new Set(t.resolvedShapes.keys());for(let t of Object.keys(e))r.has(t)||n.at(t).error(y.ASSISTANT_UNKNOWN_TYPE,m.ASSISTANT_UNKNOWN_TYPE("entities",t));return i})(c.entities??{},u,et),{resolveRef:er,expressions:N,entityTypes:u.entityTypes},et),ea=ee(E,[],es.get(E)??[],()=>void 0,Y),ep=new Map,el=F(c.childRecipes??{},R,{model:u,components:M},Y.at(R.section)),ed=F(c.replaceRecipes??{},j,{model:u,components:M},Y.at(j.section)),ec=el.groups,eh=ed.groups,ef=new Map,eu=e=>{let[t,...n]=[...u.aliases].find(([t])=>t===e)?.[1]??[];return(t&&0===n.length?ep.get(t):void 0)??eg.get(e)??em},ey=e=>ep.get(e)??eu(e),em=new i({name:E,description:"Every domain entity.",fields:()=>en(ea,ey,eo)}),eg=new Map([[E,em]]),eS=new Map([[E,ea]]);for(let e of u.aliases.keys()){if(e===E)continue;let t=ee(e,[ea],es.get(e)??[],()=>void 0,Y);eS.set(e,t),eg.set(e,new i({name:e,interfaces:[em],fields:()=>en(t,ey)}))}let eT={};for(let e of u.entityTypes){let t=[E,...[...u.aliases].filter(([t,n])=>t!==E&&n.includes(e)).map(([e])=>e)],n=[...u.resolvedShapes].find(([t])=>t===e)?.[1],i=ee(e,t.map(e=>eS.get(e)??[]),es.get(e)??[],e=>{let t=Object.entries(n?.properties??{}).find(([t])=>t===e)?.[1];return t&&A(t,er).enumValues},Y);eT[e]=ei(i),ep.set(e,new s({name:e,interfaces:t.flatMap(e=>eg.get(e)??[]),fields:()=>{let t=ef.get(e);return{...en(i,ey),...t?{meta:{type:new o(t),description:"What the configurator offers on this entity besides its fields."}}:{}}}}))}let eN=((e,t,n)=>{let i=new Set;for(let r of Object.keys(e)){let e=t.entityTypes.find(e=>e===r),o=e?[e]:[...t.aliases].find(([e])=>e===r)?.[1];o?o.forEach(e=>i.add(e)):n.at(r).error(y.ASSISTANT_UNKNOWN_TYPE,m.ASSISTANT_UNKNOWN_TYPE("deletable",r))}return t.entityTypes.filter(e=>i.has(e))})(c.deletable??{},u,Y.at("deletable")),ew=((e,t,n)=>{let{model:i}=t,r=((e,t,n)=>{let i=new Map;for(let[r,o]of Object.entries(e)){let e=t.entityTypes.find(e=>e===r),s=e?[e]:[...t.aliases].find(([e])=>e===r)?.[1],a=[...t.resolvedShapes].find(([e])=>e===r)?.[1];if(!s||!a){n.at(r).error(y.ASSISTANT_UNKNOWN_TYPE,m.ASSISTANT_UNKNOWN_TYPE("writable",r));continue}for(let e of Object.keys(o)){let t=n.at(r,e);e.startsWith("$")||U.has(e)?t.error(y.ASSISTANT_NOT_WRITABLE,m.ASSISTANT_NOT_WRITABLE(r,e)):k(a.properties,e)?s.forEach(t=>{let n=i.get(t)??new Map;i.set(t,n.has(e)?n:n.set(e,r))}):t.error(y.ASSISTANT_UNKNOWN_FIELD,m.ASSISTANT_UNKNOWN_FIELD("writable",r,e))}}return i})(e,i,n);return i.entityTypes.flatMap(e=>{let o=[...i.resolvedShapes].find(([t])=>t===e)?.[1],s=[...r.get(e)??[]].flatMap(([i,r])=>{let s=o&&k(o.properties,i);return(s&&((e,{property:t,writableKey:n},i,{resolveRef:r,exposed:o,sources:s},a)=>{let p=Object.entries(k(s,e)??{}),c=o.get(e)?.find(({source:e})=>e===t)?.name??p.find(([,{source:e}])=>e===t)?.[0],h=void 0===c?p.find(([e])=>e===t)?.[1]:void 0;if(h)return void a.at(n,t).error(y.ASSISTANT_FIELD_NAME_CONFLICT,m.ASSISTANT_FIELD_NAME_CONFLICT(e,t,[h.source,t],`${n}.${t}`));let{type:f,enumValues:u,localized:g,description:S}=A(i,r),T=l(f),N=c??t,E=void 0===c?C(S,u):void 0;return g?{name:N,property:t,type:w,description:E?`${E} ${P}`:P}:{name:N,property:t,type:d(T)?T:w,description:E}})(e,{property:i,writableKey:r},s,t,n))??[]});return s.length>0?[{entityType:e,fields:s}]:[]})})(c.writable??{},{model:u,resolveRef:er,exposed:es,sources:eT},Y.at("writable")),eA=((e,t,n,i)=>{let{model:r}=n,o=new Map;for(let[s,a]of Object.entries(e)){let e=r.entityTypes.find(e=>e===s),p=e?[e]:[...r.aliases].find(([e])=>e===s)?.[1]??[];for(let[e,r]of Object.entries(a)){let a=r?.options;if(!a)continue;let l=i.at(s,e,"options"),d=`${s}.${e}`;for(let i of p){let r=t.find(e=>e.entityType===i)?.fields.find(t=>t.property===e);if(!r)continue;let s=a.as??`${r.name}Options`,p=L(i,a.componentType,n),c=o.get(i)??[],h=c.find(e=>e.options.edgeName===s||e.options.field===r.name);if(p.includes(a.instanceName))if(s===R.section||s===j.section)l.error(y.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME,m.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME(d,s,r.name));else if(h)l.error(y.ASSISTANT_DUPLICATE_OPTIONS_EDGE,m.ASSISTANT_DUPLICATE_OPTIONS_EDGE(i,h.options.edgeName===s?{edgeName:s}:{field:r.name},[h.entry,d]));else{let e={field:r.name,edgeName:s,componentType:a.componentType,instanceName:a.instanceName,validate:a.validate??!0,dryRuns:a.allowDryRuns??!0};o.set(i,[...c,{options:e,hints:W(a.hints),entry:d,entryCtx:l}])}else l.error(y.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT,m.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT(d,a,i,p))}}}return o})(c.writable??{},ew,{model:u,components:M},Y.at("writable"));var eE,eI,e_,eO=[el.metaEntries,ed.metaEntries,new Map([...eA].flatMap(([e,[t]])=>t?[[e,t.entryCtx]]:[]))];for(let e of u.entityTypes){let t=eO.flatMap(t=>t.get(e)??[])[0],n=K(e);t&&[...u.resolvedShapes.keys()].some(e=>e===n)&&t.error(y.ASSISTANT_META_TYPE_NAME_CONFLICT,m.ASSISTANT_META_TYPE_NAME_CONFLICT(e,n))}let ev=(eE=()=>eu(eg.has(I)?I:E),eI=()=>eu(E),V=new s({name:b,description:"One reason a change cannot be made right now.",fields:{type:{type:new o(p),description:'Kind of the problem, or "uncaught".'},entityId:{type:t,description:"The entity the problem is on, when it is on one."},message:{type:p,description:"The problem as the configurator words it for the user."}}}),new s({name:v,description:"What using a recipe or writing an option would do, tried out on the configuration the query reads. Nothing is changed.",fields:()=>({ok:{type:new o(e),description:"Whether the change would succeed on the configuration the query reads."},root:{type:eE(),description:"The root entity of the configuration as it would be after the change; null when ok is false. Everything selected under it reads that configuration."},changedEntities:{type:new o(new r(new o(eI()))),description:"Every entity the change would add or modify, read from that configuration; empty when ok is false. An entity whose id the configuration does not have yet would be added, and its id may differ in the real mutation. An entity that is written to is listed even when it gets the values it already has."},deletedEntityIds:{type:new o(new r(new o(t))),description:"The ids of the entities the change would remove; empty when ok is false."},errors:{type:new o(new r(new o(V))),description:"Why the change cannot be made; empty when ok is true."}})})),eb={recipeGroup:(e_=[...Object.keys(ec).length>0?[R.mutation]:[],...Object.keys(eh).length>0?[j.mutation]:[]],x=e_.join(" or "),H=new s({name:O,description:"One recipe of a recipe group: something that can be added to the entity, or something the entity can be replaced with, depending on the edge the group is listed under.",fields:{key:{type:new o(p),description:`Identifies the recipe within its group; pass it to ${x} as recipeKey. Keys can change with the configuration and with the language, so read them from the listing rather than remembering them.`},name:{type:new o(p),description:"Name shown to the user."},description:{type:p},imageUrl:{type:p,description:"Thumbnail shown to the user."},dryRun:{type:ev,description:"Tries the recipe out. Each selected dry-run costs a full recalculation, so select it only on the recipes you are deciding between. Null for a group whose recipes cannot be dry-run."}}}),new s({name:_,description:"A group of recipes of an entity, as the configurator offers them to the user.",fields:{groupId:{type:new o(p),description:`Identifies the group on its entity; pass it to ${x} as recipeGroupId.`},name:{type:new o(p),description:"Name shown to the user."},description:{type:p},recipes:{type:new o(new r(new o(H)))}}})),fieldOption:new s({name:$,description:"One choice of a field, as the configurator offers it to the user.",fields:{value:{type:new o(w),description:"The value to write to the field."},name:{type:p,description:"Name shown to the user."},description:{type:p},imageUrl:{type:p,description:"Image shown to the user."},color:{type:p,description:'Color shown to the user, as "#rrggbb".'},dryRun:{type:ev,description:"Tries writing the value to the field. Each selected dry-run costs a full recalculation, so select it only on the options you are deciding between. Null for a field whose options cannot be dry-run."}}})};for(let e of u.entityTypes){let t=k(ec,e)??[],n=k(eh,e)??[],i=eA.get(e)??[];(t.length>0||n.length>0||i.length>0)&&ef.set(e,q({entityType:e,childRecipes:{groups:t,hints:el.hints.get(e)??[]},replaceRecipes:{groups:n,hints:ed.hints.get(e)??[]},optionsEdges:i},eb))}let e$=Object.fromEntries(u.entityTypes.flatMap(e=>{let t=eA.get(e);return t?[[e,t.map(({options:e})=>e)]]:[]})),eR=((e,{actions:t,resolveRef:n,builtInMutations:i,typeNames:r},o)=>{let s=[],a=[...t.values()].map(e=>String(e.name));for(let[p,l]of Object.entries(e)){let e=o.at(p),d=[...t.values()].find(e=>e.name===p);if(!d){e.error(y.ASSISTANT_UNKNOWN_ACTION,m.ASSISTANT_UNKNOWN_ACTION(p,a));continue}let c=l?.as??p,h=s.find(e=>e.fieldName===c),f=z(c);if(i.has(c)||h){e.error(y.ASSISTANT_MUTATION_NAME_CONFLICT,m.ASSISTANT_MUTATION_NAME_CONFLICT(p,c,h?`"assistant.actions.${h.actionName}" already exposes`:"the built-in mutation of that name already takes"));continue}if(r.has(f)||s.some(e=>z(e.fieldName)===f)){e.error(y.ASSISTANT_ACTION_RESULT_TYPE_CONFLICT,m.ASSISTANT_ACTION_RESULT_TYPE_CONFLICT(p,c,f));continue}s.push({fieldName:c,actionName:p,description:l?.description??d.description,args:Object.fromEntries(Object.entries(d.params).map(([e,{schema:t}])=>[e,Q(t,n)])),result:Object.fromEntries(Object.entries(d.result).map(([e,t])=>[e,X(t,n)]))})}return s})(c.actions??{},{actions:G,resolveRef:er,builtInMutations:new Set(["deleteEntity",R.mutation,j.mutation,...ew.map(({entityType:e})=>`modify${e}`)]),typeNames:new Set([...D,...u.resolvedShapes.keys(),...ef.keys()])},Y.at("actions"));if(Y.errors.length>J)return;let ej=((e,t)=>{let n;try{let t=e();if(n=f(t).map(e=>e.message),0===n.length)return h(t)}catch(e){n=[e instanceof Error?e.message:String(e)]}t.error(y.ASSISTANT_INVALID_SCHEMA,m.ASSISTANT_INVALID_SCHEMA(n))})(()=>{var e,i;let l;return new a({query:(e=eu(eg.has(I)?I:E),i=eu(E),l=(e=>{let t={};for(let[n,i,r]of[["navigationState","Active navigation state.",e.navigationStates],["viewState","Active view state.",e.viewStates],["toolState","Active tool state.",e.toolStates]])r.length>1&&(t[n]={type:new o(p),description:C(i,r)});if(0!==Object.keys(t).length)return new s({name:"Navigation",description:"The active UI states of the configurator.",fields:t})})(g),new s({name:"Query",fields:{root:{type:new o(e),description:"The root entity of the configuration."},entities:{type:new o(new r(i)),args:{ids:{type:new r(new o(t))}},description:`Every entity of the configuration, or, when ids are given, those entities in the same order with null for an unknown id. Ids have the form "<Type>-<number>"${eo?`, e.g. "${eo}-1"`:""}; any other id is an error.`},selectedEntity:{type:new o(i),description:"The selected entity, or the root entity when nothing is selected."},...l?{navigation:{type:new o(l)}}:{}}})),mutation:(({deletableTypes:e,writableTypes:i,childRecipes:a,replaceRecipes:l,actionFields:d,objectTypes:c,anyDomainEntity:h,targetOutputType:f})=>{let u,y;if(0!==e.length||0!==i.length||0!==Object.keys(a).length||0!==Object.keys(l).length||0!==d.length)return new s({name:"Mutation",fields:Object.assign(0===e.length?{}:{deleteEntity:{type:new o(new r(new o(t))),args:{id:{type:new o(t)}},description:`Deletes the entity with the given id, together with the entities composed into it, and returns the ids of every entity the deletion removed, the given one first. Deletable entity types: ${e.join(", ")}. Nothing can be read from removed entities afterwards, so query what you need from them before deleting.`}},0===(u=B(a)).length?{}:{addChild:{type:new o(new r(new o(h))),args:{parentId:{type:new o(t)},recipeGroupId:{type:new o(p)},recipeKey:{type:new o(p)}},description:`Adds a child to the entity with the id parentId by one recipe of one of its recipe groups. Entity types with recipe groups: ${u.join("; ")}. Read the groupId and the recipe key from "meta { childRecipes }" of the parent. Returns every entity the change added, the recipe's own first and then whatever the configurator added in response, such as a part the new child needs; the list is empty when the configurator removed them again.`}},0===(y=B(l)).length?{}:{replaceEntity:{type:new o(new r(new o(h))),args:{entityId:{type:new o(t)},recipeGroupId:{type:new o(p)},recipeKey:{type:new o(p)}},description:`Replaces the entity with the id entityId by one recipe of one of its replace recipe groups. Entity types with replace recipe groups: ${y.join("; ")}. Read the groupId and the recipe key from "meta { replaceRecipes }" of the entity. The replacement is a new entity with a new id: the id passed in no longer exists afterwards, and the replacement has the field values of its recipe, not those of the entity it replaces. Returns every entity the change added, the replacement first and then whatever the configurator added in response, such as a part the replacement needs; the list is empty when the configurator removed them again.`}},...i.flatMap(e=>{let i=c.get(e.entityType);return i?[(({entityType:e,fields:i},r)=>{let s=Object.fromEntries(i.map(({name:e,type:t,description:n})=>[e,{type:t,description:n}]));return{[`modify${e}`]:{type:r,args:{id:{type:new o(t)},delta:{type:new o(new n({name:`${e}Delta`,fields:s}))}},description:`Changes writable fields of the one ${e} with the given id: ${i.map(({name:e})=>e).join(", ")}. The delta sets only the fields it names and needs at least one; values are in stored units, as the field descriptions say. Returns the entity as it is after the change, including what the configurator adjusted in response, or null when the change caused the entity to be removed.`}}})(e,i)]:[]}),Object.fromEntries(d.map(e=>[e.fieldName,{type:new o(new s({name:z(e.fieldName),description:`What ${e.fieldName} returns, read from the configuration after the change.`,fields:()=>Object.fromEntries(Object.entries(e.result).map(([e,t])=>[e,{type:"edge"===t.kind?(({target:e,list:t,nullable:n},i)=>{let s=t?new r(new o(i(e))):i(e);return n?s:new o(s)})(t,f):t.type,description:t.description}]))})),args:e.args,description:e.description}])))})})({deletableTypes:eN,writableTypes:ew,childRecipes:ec,replaceRecipes:eh,actionFields:eR,objectTypes:ep,anyDomainEntity:eu(E),targetOutputType:ey}),types:[...eg.values(),...ep.values()]})},Y);return void 0===ej?void 0:{sdl:ej,fields:eT,deletableTypes:eN,writableFields:Object.fromEntries(ew.map(({entityType:e,fields:t})=>[e,Object.fromEntries(t.map(({name:e,property:t})=>[e,t]))])),childRecipes:ec,replaceRecipes:eh,fieldOptions:e$,actions:Object.fromEntries(eR.map(({fieldName:e,actionName:t})=>[e,t]))}};
@@ -2,7 +2,7 @@ import { Branded } from '@salsita-ai/common/utils';
2
2
  import type { ParseContext } from '../../../../core/index.js';
3
3
  import type { MergedAssistant } from '../../../merge/index.js';
4
4
  import type { EntityTypeName } from '../../model/index.js';
5
- import { type AssistantFieldOptionsByType, type AssistantFieldSources, type AssistantRecipeGroups, type AssistantSchemaInput, type AssistantWritableFields } from './assistant-schema.js';
5
+ import { type AssistantActions, type AssistantFieldOptionsByType, type AssistantFieldSources, type AssistantRecipeGroups, type AssistantSchemaInput, type AssistantWritableFields } from './assistant-schema.js';
6
6
  /**
7
7
  * The experimental assistant manifest with its GraphQL SDL, prepared once at parse time so the
8
8
  * `.phoenix` codegen, the in-browser hot-reload runtime and deployment registration all carry the
@@ -10,8 +10,9 @@ import { type AssistantFieldOptionsByType, type AssistantFieldSources, type Assi
10
10
  * expressions the runtime resolvers read; `deletableTypes` lists the entity types `deleteEntity`
11
11
  * may delete; `writableFields` maps the delta fields of each `modify<Type>` mutation to the stored
12
12
  * properties they write; `childRecipes` and `replaceRecipes` list the recipe groups each entity type exposes; `fieldOptions` lists
13
- * the options edges of each entity type's writable fields. `null` when the application declares no
14
- * `assistant` section or it is invalid.
13
+ * the options edges of each entity type's writable fields; `actions` maps each custom `Mutation`
14
+ * field to the declared action it runs. `null` when the application declares no `assistant`
15
+ * section or it is invalid.
15
16
  */
16
17
  export type AssistantSpec = Branded<'AssistantSpec', {
17
18
  readonly sdl: string;
@@ -21,5 +22,6 @@ export type AssistantSpec = Branded<'AssistantSpec', {
21
22
  readonly childRecipes: AssistantRecipeGroups;
22
23
  readonly replaceRecipes: AssistantRecipeGroups;
23
24
  readonly fieldOptions: AssistantFieldOptionsByType;
25
+ readonly actions: AssistantActions;
24
26
  }> | null;
25
27
  export declare const AssistantSpec: (merged: MergedAssistant, input: AssistantSchemaInput, ctx: ParseContext) => AssistantSpec;
@@ -1,3 +1,4 @@
1
+ export * from './actions.js';
1
2
  export * from './app-metadata.js';
2
3
  export * from './assistant/index.js';
3
4
  export * from './application-version.js';
@@ -1 +1 @@
1
- export*from"./app-metadata.js";export*from"./assistant/index.js";export*from"./application-version.js";export*from"./bundle-size-budgets.js";export*from"./data-spec/index.js";export*from"./env.js";export*from"./infra.js";export*from"./state-value.js";export*from"./theme.js";export*from"./transformers.js";export*from"./ui.js";
1
+ export*from"./actions.js";export*from"./app-metadata.js";export*from"./assistant/index.js";export*from"./application-version.js";export*from"./bundle-size-budgets.js";export*from"./data-spec/index.js";export*from"./env.js";export*from"./infra.js";export*from"./state-value.js";export*from"./theme.js";export*from"./transformers.js";export*from"./ui.js";
@@ -1,5 +1,5 @@
1
1
  import type { $DomainEntity, DomainEntity } from '#package/domain';
2
- import type { AnimationSystem, CameraControlSystem, CameraSystem, CanvasSystem, DragAndDropSystem, ExportSystem, GraphQLSystem, ImageRenderingSystem, LayoutSystem, SketchingSystem } from './systems/index.js';
2
+ import type { AnimationSystem, AssistantSystem, CameraControlSystem, CameraSystem, CanvasSystem, DragAndDropSystem, ExportSystem, GraphQLSystem, ImageRenderingSystem, LayoutSystem, SketchingSystem } from './systems/index.js';
3
3
  /**
4
4
  * The configurator systems of one slot. Every system reaches the domain through runtime selectors,
5
5
  * so its own entity types are all it needs and the erased aliases are what the runtime hands around.
@@ -18,6 +18,7 @@ export interface ConfiguratorExtensionSystems<ENTITIES extends DomainEntity<stri
18
18
  readonly exportSystem: ExportSystem<ENTITIES, ALLOWED_ROOT_ENTITIES, $MAP, NAVIGATION_STATES, VIEW_STATES, TOOL_STATES, EXPORT_STATES>;
19
19
  readonly cameraSystem: CameraSystem<ENTITIES>;
20
20
  readonly graphQLSystem: GraphQLSystem;
21
+ readonly assistantSystem: AssistantSystem;
21
22
  }
22
23
  /** The erased shape the runtime slice constructs; consumers that know their entities narrow on read. */
23
24
  export type AnyConfiguratorExtensionSystems = ConfiguratorExtensionSystems<any, any, any, any, any, any, any>;
@@ -1 +1 @@
1
- let e=["canvasSystem","cameraControlSystem","animationSystem","dragAndDropSystem","imageRenderingSystem","layoutSystem","sketchingSystem","exportSystem","cameraSystem","graphQLSystem"];export const isConfiguratorExtensionSystems=t=>e.every(e=>e in t);
1
+ let e=["canvasSystem","cameraControlSystem","animationSystem","dragAndDropSystem","imageRenderingSystem","layoutSystem","sketchingSystem","exportSystem","cameraSystem","graphQLSystem","assistantSystem"];export const isConfiguratorExtensionSystems=t=>e.every(e=>e in t);
@@ -1,7 +1,7 @@
1
1
  import type { AccessInfoSelectors, DomainContextSelectors, DomainServicesSelectors, SpecSelectors } from '#package/domain';
2
2
  import type { CommonServicesSelectors } from '#package/react-sdk';
3
3
  import type { AnyConfiguratorExtensionSystems } from './configurator-extension-systems.js';
4
- import { AnimationSystem, type AnyCameraSystem, type AnyCanvasSystem, type AnyDragAndDropSystem, type AnyExportSystem, type AnyImageRenderingSystem, type AnyLayoutSystem, type AnySketchingSystem, CameraControlSystem, GraphQLSystem } from './systems/index.js';
4
+ import { AnimationSystem, type AnyCameraSystem, type AnyCanvasSystem, type AnyDragAndDropSystem, type AnyExportSystem, type AnyImageRenderingSystem, type AnyLayoutSystem, type AnySketchingSystem, AssistantSystem, CameraControlSystem, GraphQLSystem } from './systems/index.js';
5
5
  interface Context {
6
6
  readonly domainContextSelectors: DomainContextSelectors;
7
7
  readonly specSelectors: SpecSelectors;
@@ -31,6 +31,7 @@ export declare const createConfiguratorExtensionSelectors: (context: Context) =>
31
31
  getExportSystem: () => AnyExportSystem;
32
32
  getCameraSystem: () => AnyCameraSystem;
33
33
  getGraphQLSystem: () => GraphQLSystem;
34
+ getAssistantSystem: () => AssistantSystem;
34
35
  };
35
36
  export type ConfiguratorExtensionSelectors = ReturnType<typeof createConfiguratorExtensionSelectors>;
36
37
  export {};
@@ -1 +1 @@
1
- import{AnimationSystem as e,CameraControlSystem as t,CameraSystem as n,CanvasSystem as o,DragAndDropSystem as r,ExportSystem as g,GraphQLSystem as s,ImageRenderingSystem as i,LayoutSystem as a,SketchingSystem as m}from"./systems/index.js";export const createConfiguratorExtensionSelectors=S=>{let{domainContextSelectors:y,specSelectors:u,domainServicesSelectors:C,accessSelectors:w,commonServicesSelectors:c}=S,f={getConfigurationId:()=>w.getConfiguratorConfigurationId(),getAuthorizedClient:()=>c.getConfiguratorAuthorizedClient(),domainContextSelectors:y,domainServicesSelectors:C,specSelectors:u},d={getSystems:()=>k,getCanvasSystem:()=>x,getCameraControlSystem:()=>p,getAnimationSystem:()=>A,getDragAndDropSystem:()=>h,getImageRenderingSystem:()=>j,getLayoutSystem:()=>z,getSketchingSystem:()=>D,getExportSystem:()=>E,getCameraSystem:()=>L,getGraphQLSystem:()=>I},l={...f,configuratorExtensionSelectors:d},x=new o(f),p=new t({configuratorExtensionSelectors:d}),h=new r(l),A=new e(f),E=new g(l),I=new s(f),z=new a(f),D=new m(l),L=new n(l),j=new i(l),k={cameraControlSystem:p,layoutSystem:z,sketchingSystem:D,dragAndDropSystem:h,canvasSystem:x,cameraSystem:L,exportSystem:E,imageRenderingSystem:j,animationSystem:A,graphQLSystem:I};return d};
1
+ import{AnimationSystem as e,AssistantSystem as t,CameraControlSystem as n,CameraSystem as o,CanvasSystem as r,DragAndDropSystem as s,ExportSystem as g,GraphQLSystem as i,ImageRenderingSystem as a,LayoutSystem as m,SketchingSystem as S}from"./systems/index.js";export const createConfiguratorExtensionSelectors=y=>{let{domainContextSelectors:u,specSelectors:w,domainServicesSelectors:C,accessSelectors:c,commonServicesSelectors:f}=y,l={getConfigurationId:()=>c.getConfiguratorConfigurationId(),getAuthorizedClient:()=>f.getConfiguratorAuthorizedClient(),domainContextSelectors:u,domainServicesSelectors:C,specSelectors:w},d={getSystems:()=>G,getCanvasSystem:()=>p,getCameraControlSystem:()=>A,getAnimationSystem:()=>h,getDragAndDropSystem:()=>E,getImageRenderingSystem:()=>v,getLayoutSystem:()=>L,getSketchingSystem:()=>j,getExportSystem:()=>I,getCameraSystem:()=>k,getGraphQLSystem:()=>z,getAssistantSystem:()=>D},x={...l,configuratorExtensionSelectors:d},p=new r(l),A=new n({configuratorExtensionSelectors:d}),E=new s(x),h=new e(l),I=new g(x),z=new i(l),D=new t({configuratorExtensionSelectors:d,domainContextSelectors:u,specSelectors:w}),L=new m(l),j=new S(x),k=new o(x),v=new a(x),G={cameraControlSystem:A,layoutSystem:L,sketchingSystem:j,dragAndDropSystem:E,canvasSystem:p,cameraSystem:k,exportSystem:I,imageRenderingSystem:v,animationSystem:h,graphQLSystem:z,assistantSystem:D};return d};
@@ -0,0 +1,35 @@
1
+ import type { AnyClientTool } from '@tanstack/ai';
2
+ import type { DomainContextSelectors, InitializableSystem, SpecSelectors } from '#package/domain';
3
+ import type { ConfiguratorExtensionSelectors } from '../../selectors.js';
4
+ /** A tool of the assistant that the model calls and the browser runs, as the chat client accepts it. */
5
+ export type AssistantClientTool = AnyClientTool;
6
+ /**
7
+ * Constructor context of an `AssistantSystem`: whole selector objects, like its peers take them, so
8
+ * the tools reach the store, the session mode and the `GraphQLSystem` when they are called.
9
+ */
10
+ export interface AssistantSystemContext {
11
+ readonly configuratorExtensionSelectors: ConfiguratorExtensionSelectors;
12
+ readonly domainContextSelectors: DomainContextSelectors;
13
+ readonly specSelectors: SpecSelectors;
14
+ }
15
+ /**
16
+ * Owns the client tools of the conversational assistant: `getBrowserDetails`, `query` and `apply`.
17
+ * They are built once, over the runtime's selectors, and offered only by a configurator whose
18
+ * application spec has an `assistant` section, so a configurator without one has no tools to
19
+ * register with a chat.
20
+ */
21
+ export declare class AssistantSystem implements InitializableSystem {
22
+ private readonly _context;
23
+ private readonly _tools;
24
+ private _isInitialized;
25
+ constructor(_context: AssistantSystemContext);
26
+ initialize: () => void;
27
+ /**
28
+ * The tools to register with the chat: all of them when the application spec has an `assistant`
29
+ * section, none otherwise or before the first initialization. The section is read on every call
30
+ * and not in `initialize()`, because editor hot reload adds or removes it by reconciliation alone.
31
+ * Each answer is always the same array instance, so the getter is a valid snapshot for a hook
32
+ * subscribed to the runtime.
33
+ */
34
+ getTools: () => readonly AssistantClientTool[];
35
+ }
@@ -0,0 +1 @@
1
+ import{createBrowserDetailsClientTool as t}from"./browser-details.js";import{createApplyClientTool as e,createQueryClientTool as s}from"./graphql-tools.js";let i=[];export class AssistantSystem{_context;_tools;_isInitialized=!1;constructor(i){this._context=i;let{configuratorExtensionSelectors:o,domainContextSelectors:l}=i,r={getGraphQLSystem:()=>o.getGraphQLSystem(),getStoreSystem:()=>l.getStoreSystem(),getActiveMode:()=>l.getActiveMode()};this._tools=[t(),s(r),e(r)]}initialize=()=>{this._isInitialized=!0};getTools=()=>this._isInitialized&&this._context.specSelectors.getAssistant()?this._tools:i}
@@ -2,7 +2,7 @@
2
2
  * Browser implementation of the assistant's `getBrowserDetails` tool: draws the browser details onto
3
3
  * a canvas and returns the capture as a PNG image part, so the model reads them from an image.
4
4
  */
5
- export declare const browserDetailsClientTool: import("@tanstack/ai").ClientTool<{
5
+ export declare const createBrowserDetailsClientTool: () => import("@tanstack/ai").ClientTool<{
6
6
  type: string;
7
7
  properties: {};
8
8
  required: never[];
@@ -0,0 +1 @@
1
+ import{browserDetailsTool as e}from"@salsita-ai/contracts/assistant";let t=e=>{let t=[];for(let i=0;i<e.length;i+=64)t.push(e.slice(i,i+64));return t};export const createBrowserDetailsClientTool=()=>e.client(()=>{let e=(()=>{let e=[`User agent: ${navigator.userAgent}`,`Viewport: ${window.innerWidth} x ${window.innerHeight} px`,`Screen: ${window.screen.width} x ${window.screen.height} px`,`Device pixel ratio: ${window.devicePixelRatio}`,`Language: ${navigator.language}`,`Time zone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`].flatMap(t),i=document.createElement("canvas");i.width=720,i.height=48+26*e.length;let n=i.getContext("2d");if(!n)throw Error("The browser details capture failed because the canvas has no 2D context. Retry in another browser.");return n.fillStyle="#ffffff",n.fillRect(0,0,i.width,i.height),n.fillStyle="#111111",n.font="16px monospace",n.textBaseline="top",e.forEach((e,t)=>n.fillText(e,24,24+26*t)),i.toDataURL("image/png")})();return[{type:"image",source:{type:"data",value:e.slice(e.indexOf(",")+1),mimeType:"image/png"}}]});
@@ -1,14 +1,13 @@
1
1
  import type { DomainEntity, DomainMode, DomainState } from '#package/domain';
2
- import type { GraphQLSystem } from '../application-runtime/index.js';
2
+ import type { GraphQLSystem } from '../graphql-system/graphql-system.js';
3
3
  /**
4
- * What the assistant's client tools need from the running configurator. The chat hook passes it as
5
- * the client context of `useChat`, which captures it when a request starts: a tool call reads the
6
- * systems as they were when its reply began streaming. A runtime replaced in between (dev hot
7
- * reload) fails that call, which is accepted.
4
+ * What the assistant's client tools need from the running configurator, as accessors they call when
5
+ * the model calls them: a tool call always runs against the systems and the session mode current at
6
+ * that moment, never against ones captured when its reply began streaming.
8
7
  */
9
- export interface AssistantToolContext {
10
- readonly graphQLSystem: Pick<GraphQLSystem, 'prepare' | 'execute'>;
11
- readonly storeSystem: {
8
+ export interface AssistantToolDependencies {
9
+ readonly getGraphQLSystem: () => Pick<GraphQLSystem, 'prepare' | 'execute'>;
10
+ readonly getStoreSystem: () => {
12
11
  readonly isInitialized: boolean;
13
12
  readonly stateSlices: {
14
13
  readonly committed: {
@@ -25,7 +24,7 @@ export interface AssistantToolContext {
25
24
  * committed state and drops their emissions, so mutations in the list show a hypothetical state and
26
25
  * the configuration, the undo stack and the saved revision stay as they were.
27
26
  */
28
- export declare const queryClientTool: import("@tanstack/ai").ClientTool<{
27
+ export declare const createQueryClientTool: (dependencies: AssistantToolDependencies) => import("@tanstack/ai").ClientTool<{
29
28
  type: string;
30
29
  properties: {
31
30
  operations: {
@@ -53,7 +52,7 @@ export declare const queryClientTool: import("@tanstack/ai").ClientTool<{
53
52
  };
54
53
  };
55
54
  required: string[];
56
- }, undefined, "query", AssistantToolContext, false, undefined> & {
55
+ }, undefined, "query", unknown, false, undefined> & {
57
56
  inputSchema: {
58
57
  type: string;
59
58
  properties: {
@@ -90,10 +89,10 @@ export declare const queryClientTool: import("@tanstack/ai").ClientTool<{
90
89
  * Browser implementation of the assistant's `apply` tool: hands the operations to
91
90
  * `GraphQLSystem.execute`, which commits their changes as one undo step, and returns its result,
92
91
  * including why nothing was committed when a commit was held or lost to a conflict. Only an owner
93
- * session may change the configuration; the check lives here and not in the system, whose other
94
- * caller, the editor panel, has its own rules.
92
+ * session may change the configuration; the check lives here and not in the `GraphQLSystem`, whose
93
+ * other caller, the editor panel, has its own rules.
95
94
  */
96
- export declare const applyClientTool: import("@tanstack/ai").ClientTool<{
95
+ export declare const createApplyClientTool: (dependencies: AssistantToolDependencies) => import("@tanstack/ai").ClientTool<{
97
96
  type: string;
98
97
  properties: {
99
98
  operations: {
@@ -121,7 +120,7 @@ export declare const applyClientTool: import("@tanstack/ai").ClientTool<{
121
120
  };
122
121
  };
123
122
  required: string[];
124
- }, undefined, "apply", AssistantToolContext, false, undefined> & {
123
+ }, undefined, "apply", unknown, false, undefined> & {
125
124
  inputSchema: {
126
125
  type: string;
127
126
  properties: {
@@ -0,0 +1 @@
1
+ import{AssistantGraphQLToolInput as e,applyTool as t,queryTool as o}from"@salsita-ai/contracts/assistant";let a=e=>({results:[],committed:!1,message:e}),i=e=>JSON.parse(JSON.stringify(e)),s=t=>{let o=e.safeParse(t);if(!o.success){let e=o.error.issues.map(e=>`${e.path.join(".")}: ${e.message}`).join("; ");return{ok:!1,refusal:a(`Nothing was run, because the tool input is not a list of operations (${e}). Send { "operations": [{ "query": "<one GraphQL operation>" }] } with at least one item.`)}}return{ok:!0,operations:o.data.operations.map(({query:e,variables:t,operationName:o})=>({document:e,variables:t??void 0,operationName:o??void 0}))}};export const createQueryClientTool=e=>o.client(async t=>{let o=s(t);if(!o.ok)return o.refusal;let n=e.getStoreSystem();return n.isInitialized?i({results:(await e.getGraphQLSystem().prepare(n.stateSlices.committed.value.state,o.operations)).map(({result:e})=>e),committed:!1}):a("Nothing was run, because the configuration is not loaded yet, so there is no state to query. Call the tool again once the configurator has finished loading.")});export const createApplyClientTool=e=>t.client(async t=>{if("owner"!==e.getActiveMode())return a("Nothing was run, because changes cannot be applied in this session: the user may view this configuration but not change it. The query tool still works here, including mutations, to show what a change would do without keeping it.");let o=s(t);return o.ok?i(await e.getGraphQLSystem().execute(o.operations)):o.refusal});
@@ -1 +1 @@
1
- import{GraphQLError as e,buildSchema as t,defaultFieldResolver as i,getNamedType as o,graphql as a,validateSchema as n}from"graphql";import{assertExistence as r,createSelector as s,isMessageDescriptor as l,isMultilingualString as c}from"@salsita-ai/common/utils";import{DomainEntityIdSchema as h,findAssistantMutation as d}from"#package/domain";import{createEntityMeta as m}from"./entity-meta.js";let p={errors:[new e('No assistant manifest in the application spec. The GraphQL schema is generated from the "assistant" section. Add an "assistant" section to a spec file to expose a schema.')]},u={errors:[new e("The configuration is not loaded yet, so there is no state to query. Run the query again once the configurator has finished loading.")]},f=new RegExp(h.pattern),y=e=>"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"id"in e&&"string"==typeof e.id,g=(e,t)=>"object"==typeof e&&null!==e?Reflect.get(e,t):void 0,v=e=>e instanceof Error?e.message:String(e),S=e=>/[.!?]$/.test(e)?e:`${e}.`,_=e=>"object"==typeof e&&null!==e&&Object.getPrototypeOf(e)===Object.prototype,x=(e,t)=>{let i=_(e)?e._raw:void 0;if(y(i))return i;if(!Array.isArray(e)&&!_(e))return e;if(t.has(e))throw Error("The value contains itself. Return ids or copies of the values instead of objects that reference each other.");let o=new Set([...t,e]);return Array.isArray(e)?e.map(e=>x(e,o)):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,x(t,o)]))},w=(e,t)=>Array.isArray(e)?e.map(e=>w(e,t)):"string"==typeof e||l(e)||c(e)?t(e):e,$=t=>new e(`The GraphQL schema generated from the "assistant" manifest is invalid: ${S(t)} Regenerate the application so the schema is rebuilt from the current spec.`),E=e=>(e.errors?.length??0)>0,b=t=>({errors:[new e(`Not run: operation ${t+1} failed, so the operations after it were skipped and no change of the list takes effect. Fix the failing operation and send the whole list again.`)]});export class GraphQLSystem{_context;_selectSchema=s([s.leaf(e=>e)],e=>{try{let i=t(e),o=n(i);return o.length>0?$(o.map(e=>e.message).join(" ")):i}catch(e){return $(v(e))}});_selectFieldResolver=s([s.leaf(e=>e)],t=>(a,n,r,s)=>{if(s.parentType===s.schema.getQueryType())return i(a,n,r,s);if(s.parentType===s.schema.getMutationType())return this._resolveMutation(s.fieldName,String(s.path.key),n,r);if(!y(a))return i(a,n,r,s);if("meta"===s.fieldName){let e;return m({entity:a,state:("object"==typeof(e=g(a,"_state"))&&null!==e&&"entities"in e&&"rootEntityId"in e?e:void 0)??r.state},{manifest:r.manifest,recipes:this._recipeContext(),prepareStateEmission:(e,t,i)=>this._context.domainContextSelectors.getStoreSystem().prepareStateEmission(e,t,i),find$Entity:(e,t)=>this._find$Entity(e,t),validateEntity:e=>this._context.domainContextSelectors.getDomain().validateEntity(e)})}let{source:l,localized:c}=t[s.parentType.name]?.[s.fieldName]??{source:s.fieldName},h=((t,i)=>{try{return g(t,i)}catch(o){throw new e(`Expression "${i}" failed on ${y(t)?t.id:"an entity"}: ${S(v(o))} The expression threw while the query read it; fix the expression or the configuration state it reads.`,{originalError:o instanceof Error?o:void 0})}})(a,l);return c?w(h,this._context.domainServicesSelectors.getResolveLocalizable()):l.startsWith("$")&&"JSON"===o(s.returnType).name?((t,i,o)=>{try{return x(o,new Set)}catch(o){throw new e(`Expression "${i}" returned a value that is not plain serializable data on ${y(t)?t.id:"an entity"}: ${S(v(o))} A JSON field can only return data that serializes to JSON.`,{originalError:o instanceof Error?o:void 0})}})(a,l,h):h});constructor(e){this._context=e}_get$Entity=(e,t)=>this._context.domainContextSelectors.getDomain().get$Entity(e,t);_find$Entity=(e,t)=>this._context.domainContextSelectors.getDomain().getEntity(e,t)?this._get$Entity(e,t):null;_recipeContext=()=>({componentReader:this._context.domainContextSelectors.getComponentReader(),recipeCooker:this._context.domainContextSelectors.getRecipeCookerSystem(),resolveLocalizable:this._context.domainServicesSelectors.getResolveLocalizable()});_rootValue={root:(e,{state:t})=>this._get$Entity(t.rootEntityId,t),entities:({ids:t},{state:i})=>{if(null==t)return i.entities.map(e=>this._get$Entity(e.id,i));var o=i.rootEntityId;let a=t.filter(e=>!f.test(e));if(a.length>0)throw new e(`${a.map(e=>`"${e}"`).join(", ")} ${1===a.length?"is not an entity id":"are not entity ids"}. Entity ids have the form "<Type>-<number>", e.g. "${o}". Use ids as returned by the "id" field.`);return t.map(e=>f.test(e)?this._find$Entity(e,i):null)},selectedEntity:(e,{state:t})=>this._find$Entity(this._context.domainContextSelectors.getNavigationSystem().getActiveSelectionState(t),t),navigation:(e,{state:t})=>{let i=this._context.domainContextSelectors.getNavigationSystem();return{navigationState:i.getActiveNavigationState(t),viewState:i.getActiveViewState(t),toolState:i.getActiveToolState(t)}}};_resolveType=e=>y(e)?e.type:void 0;initialize=()=>{};_resolveMutation=(t,i,o,a)=>{if(void 0!==a.failedMutationField)throw new e(`Not run: the earlier field "${a.failedMutationField}" of this operation failed, so "${i}" was skipped and no change of the operation takes effect. Fix the failing field and send the operation again.`);try{return this._runMutation(t,o,a)}catch(e){throw a.failedMutationField=i,e}};_runMutation=(t,i,o)=>{let a=d(t,o.manifest);if(!a)throw new e(`The schema declares the mutation "${t}", but the configurator has no implementation for it. Regenerate the application so the schema matches the configurator.`);let n=o.state,r=a.implementation(i,n,{manifest:o.manifest,domain:this._context.domainContextSelectors.getDomain(),...this._recipeContext()});if(r.updates.length>0){let i=this._context.domainContextSelectors.getStoreSystem().prepareStateEmission(r.updates,n,"committed");if(!i.validity.valid)throw new e(`The changes of "${t}" were not applied, because the resulting configuration is invalid: ${(e=>{if("uncaught"===e.severity)return`validating it threw: ${S(v(e.error))}`;let t=[...new Set(e.entityViolations.filter(({violation:t})=>t.severity===e.severity).map(({entityId:e})=>e))];return`it has ${e.severity} violations on ${t.join(", ")}.`})(i.validity)} Change the request so the configuration stays valid.`);o.emissions.push(i),o.state=i.state}return r.readResult({previousState:n,state:o.state})};_setup=()=>{let t=this._context.specSelectors.getAssistant();if(!t)return{ready:!1,result:p};let i=this._selectSchema(t.sdl);return i instanceof e?{ready:!1,result:{errors:[i]}}:{ready:!0,assistant:t,schema:i,fieldResolver:this._selectFieldResolver(t.fields)}};prepare=async(e,t)=>{let i,o=this._setup();if(!o.ready)return t.map(()=>({result:o.result,emissions:[]}));let n={manifest:o.assistant,state:e,emissions:[],failedMutationField:void 0},r=[];for(let[e,s]of t.entries())if(void 0===i){let t=n.emissions.length;n.failedMutationField=void 0;let l=await a({schema:o.schema,source:s.document,rootValue:this._rootValue,contextValue:n,variableValues:s.variables,operationName:s.operationName,fieldResolver:o.fieldResolver,typeResolver:this._resolveType});r.push({result:l,emissions:n.emissions.slice(t)}),E(l)&&(i=e)}else r.push({result:b(i),emissions:[]});return r};_prepareAndCommit=async e=>{let t,i,o,a=this._context.domainContextSelectors.getStoreSystem(),n=await this.prepare(a.stateSlices.committed.value.state,e),s=n.map(({result:e})=>e),l=n.flatMap(e=>e.emissions);return s.some(E)||0===l.length?{results:s,outcome:"none"}:{results:s,outcome:a.commitPrepared((t=r(l[0]),i=r(l[l.length-1]),o=l.some(e=>void 0!==e.transformationLog),{kind:"committed",previousState:t.previousState,state:i.state,updates:l.flatMap(e=>e.updates),validity:i.validity,transformationLog:o?l.flatMap(e=>e.transformationLog??[]):void 0}))}};execute=async e=>{if(!this._context.domainContextSelectors.getStoreSystem().isInitialized)return{results:e.map(()=>u),committed:!1};let t=await this._prepareAndCommit(e),{results:i,outcome:o}="conflict"===t.outcome?await this._prepareAndCommit(e):t;return"committed"===o?{results:i,committed:!0}:"held"===o?{results:i,committed:!1,message:"The changes were not committed yet: the application held them, usually to ask the user for approval. They may still be applied once the user approves, and the next turn shows whether they were. Do not send the operations again."}:"conflict"===o?{results:i,committed:!1,message:"The changes were not committed, because the configuration changed while they were being applied. The results describe a state that was discarded. Query the current configuration and send the operations again if they still make sense."}:{results:i,committed:!1}}}
1
+ import{GraphQLError as e,buildSchema as t,defaultFieldResolver as i,getNamedType as o,graphql as a,validateSchema as n}from"graphql";import{assertExistence as r,createSelector as s,isMessageDescriptor as l,isMultilingualString as c}from"@salsita-ai/common/utils";import{DomainEntityIdSchema as h,findAssistantMutation as d}from"#package/domain";import{createEntityMeta as m}from"./entity-meta.js";let p={errors:[new e('No assistant manifest in the application spec. The GraphQL schema is generated from the "assistant" section. Add an "assistant" section to a spec file to expose a schema.')]},u={errors:[new e("The configuration is not loaded yet, so there is no state to query. Run the query again once the configurator has finished loading.")]},f=new RegExp(h.pattern),y=e=>"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"id"in e&&"string"==typeof e.id,g=(e,t)=>"object"==typeof e&&null!==e?Reflect.get(e,t):void 0,v=e=>e instanceof Error?e.message:String(e),S=e=>/[.!?]$/.test(e)?e:`${e}.`,_=e=>"object"==typeof e&&null!==e&&Object.getPrototypeOf(e)===Object.prototype,x=(e,t)=>{let i=_(e)?e._raw:void 0;if(y(i))return i;if(!Array.isArray(e)&&!_(e))return e;if(t.has(e))throw Error("The value contains itself. Return ids or copies of the values instead of objects that reference each other.");let o=new Set([...t,e]);return Array.isArray(e)?e.map(e=>x(e,o)):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,x(t,o)]))},w=(e,t)=>Array.isArray(e)?e.map(e=>w(e,t)):"string"==typeof e||l(e)||c(e)?t(e):e,$=t=>new e(`The GraphQL schema generated from the "assistant" manifest is invalid: ${S(t)} Regenerate the application so the schema is rebuilt from the current spec.`),E=e=>(e.errors?.length??0)>0,b=t=>({errors:[new e(`Not run: operation ${t+1} failed, so the operations after it were skipped and no change of the list takes effect. Fix the failing operation and send the whole list again.`)]});export class GraphQLSystem{_context;_selectSchema=s([s.leaf(e=>e)],e=>{try{let i=t(e),o=n(i);return o.length>0?$(o.map(e=>e.message).join(" ")):i}catch(e){return $(v(e))}});_selectFieldResolver=s([s.leaf(e=>e)],t=>(a,n,r,s)=>{if(s.parentType===s.schema.getQueryType())return i(a,n,r,s);if(s.parentType===s.schema.getMutationType())return this._resolveMutation(s.fieldName,String(s.path.key),n,r);if(!y(a))return i(a,n,r,s);if("meta"===s.fieldName){let e;return m({entity:a,state:("object"==typeof(e=g(a,"_state"))&&null!==e&&"entities"in e&&"rootEntityId"in e?e:void 0)??r.state},{manifest:r.manifest,recipes:this._recipeContext(),prepareStateEmission:(e,t,i)=>this._context.domainContextSelectors.getStoreSystem().prepareStateEmission(e,t,i),find$Entity:(e,t)=>this._find$Entity(e,t),validateEntity:e=>this._context.domainContextSelectors.getDomain().validateEntity(e)})}let{source:l,localized:c}=t[s.parentType.name]?.[s.fieldName]??{source:s.fieldName},h=((t,i)=>{try{return g(t,i)}catch(o){throw new e(`Expression "${i}" failed on ${y(t)?t.id:"an entity"}: ${S(v(o))} The expression threw while the query read it; fix the expression or the configuration state it reads.`,{originalError:o instanceof Error?o:void 0})}})(a,l);return c?w(h,this._context.domainServicesSelectors.getResolveLocalizable()):l.startsWith("$")&&"JSON"===o(s.returnType).name?((t,i,o)=>{try{return x(o,new Set)}catch(o){throw new e(`Expression "${i}" returned a value that is not plain serializable data on ${y(t)?t.id:"an entity"}: ${S(v(o))} A JSON field can only return data that serializes to JSON.`,{originalError:o instanceof Error?o:void 0})}})(a,l,h):h});constructor(e){this._context=e}_get$Entity=(e,t)=>this._context.domainContextSelectors.getDomain().get$Entity(e,t);_find$Entity=(e,t)=>this._context.domainContextSelectors.getDomain().getEntity(e,t)?this._get$Entity(e,t):null;_recipeContext=()=>({componentReader:this._context.domainContextSelectors.getComponentReader(),recipeCooker:this._context.domainContextSelectors.getRecipeCookerSystem(),resolveLocalizable:this._context.domainServicesSelectors.getResolveLocalizable()});_rootValue={root:(e,{state:t})=>this._get$Entity(t.rootEntityId,t),entities:({ids:t},{state:i})=>{if(null==t)return i.entities.map(e=>this._get$Entity(e.id,i));var o=i.rootEntityId;let a=t.filter(e=>!f.test(e));if(a.length>0)throw new e(`${a.map(e=>`"${e}"`).join(", ")} ${1===a.length?"is not an entity id":"are not entity ids"}. Entity ids have the form "<Type>-<number>", e.g. "${o}". Use ids as returned by the "id" field.`);return t.map(e=>f.test(e)?this._find$Entity(e,i):null)},selectedEntity:(e,{state:t})=>this._find$Entity(this._context.domainContextSelectors.getNavigationSystem().getActiveSelectionState(t),t),navigation:(e,{state:t})=>{let i=this._context.domainContextSelectors.getNavigationSystem();return{navigationState:i.getActiveNavigationState(t),viewState:i.getActiveViewState(t),toolState:i.getActiveToolState(t)}}};_resolveType=e=>y(e)?e.type:void 0;initialize=()=>{};_resolveMutation=(t,i,o,a)=>{if(void 0!==a.failedMutationField)throw new e(`Not run: the earlier field "${a.failedMutationField}" of this operation failed, so "${i}" was skipped and no change of the operation takes effect. Fix the failing field and send the operation again.`);try{return this._runMutation(t,o,a)}catch(e){throw a.failedMutationField=i,e}};_runMutation=(t,i,o)=>{let a=d(t,o.manifest);if(!a)throw new e(`The schema declares the mutation "${t}", but the configurator has no implementation for it. Regenerate the application so the schema matches the configurator.`);let n=o.state,r=a.implementation(i,n,{manifest:o.manifest,action:this._context.domainContextSelectors.getActionSystem().createContext(n),resolveLocalizable:this._context.domainServicesSelectors.getResolveLocalizable()});if(r.updates.length>0){let i=this._context.domainContextSelectors.getStoreSystem().prepareStateEmission(r.updates,n,"committed");if(!i.validity.valid)throw new e(`The changes of "${t}" were not applied, because the resulting configuration is invalid: ${(e=>{if("uncaught"===e.severity)return`validating it threw: ${S(v(e.error))}`;let t=[...new Set(e.entityViolations.filter(({violation:t})=>t.severity===e.severity).map(({entityId:e})=>e))];return`it has ${e.severity} violations on ${t.join(", ")}.`})(i.validity)} Change the request so the configuration stays valid.`);o.emissions.push(i),o.state=i.state}return r.readResult({previousState:n,state:o.state})};_setup=()=>{let t=this._context.specSelectors.getAssistant();if(!t)return{ready:!1,result:p};let i=this._selectSchema(t.sdl);return i instanceof e?{ready:!1,result:{errors:[i]}}:{ready:!0,assistant:t,schema:i,fieldResolver:this._selectFieldResolver(t.fields)}};prepare=async(e,t)=>{let i,o=this._setup();if(!o.ready)return t.map(()=>({result:o.result,emissions:[]}));let n={manifest:o.assistant,state:e,emissions:[],failedMutationField:void 0},r=[];for(let[e,s]of t.entries())if(void 0===i){let t=n.emissions.length;n.failedMutationField=void 0;let l=await a({schema:o.schema,source:s.document,rootValue:this._rootValue,contextValue:n,variableValues:s.variables,operationName:s.operationName,fieldResolver:o.fieldResolver,typeResolver:this._resolveType});r.push({result:l,emissions:n.emissions.slice(t)}),E(l)&&(i=e)}else r.push({result:b(i),emissions:[]});return r};_prepareAndCommit=async e=>{let t,i,o,a=this._context.domainContextSelectors.getStoreSystem(),n=await this.prepare(a.stateSlices.committed.value.state,e),s=n.map(({result:e})=>e),l=n.flatMap(e=>e.emissions);return s.some(E)||0===l.length?{results:s,outcome:"none"}:{results:s,outcome:a.commitPrepared((t=r(l[0]),i=r(l[l.length-1]),o=l.some(e=>void 0!==e.transformationLog),{kind:"committed",previousState:t.previousState,state:i.state,updates:l.flatMap(e=>e.updates),validity:i.validity,transformationLog:o?l.flatMap(e=>e.transformationLog??[]):void 0}))}};execute=async e=>{if(!this._context.domainContextSelectors.getStoreSystem().isInitialized)return{results:e.map(()=>u),committed:!1};let t=await this._prepareAndCommit(e),{results:i,outcome:o}="conflict"===t.outcome?await this._prepareAndCommit(e):t;return"committed"===o?{results:i,committed:!0}:"held"===o?{results:i,committed:!1,message:"The changes were not committed yet: the application held them, usually to ask the user for approval. They may still be applied once the user approves, and the next turn shows whether they were. Do not send the operations again."}:"conflict"===o?{results:i,committed:!1,message:"The changes were not committed, because the configuration changed while they were being applied. The results describe a state that was discarded. Query the current configuration and send the operations again if they still make sense."}:{results:i,committed:!1}}}
@@ -1,4 +1,5 @@
1
1
  export { AnimationSystem, type AnimationSystemContext } from './animation-system.js';
2
+ export { type AssistantClientTool, AssistantSystem, type AssistantSystemContext, } from './assistant-system/assistant-system.js';
2
3
  export { CameraControlSystem, CameraControlType } from './camera-control-system/camera-control-system.js';
3
4
  export { type AnyCameraSystem, CameraSystem, type CameraSystemContext } from './camera-control-system/camera-system.js';
4
5
  export { createCameraControls } from './camera-control-system/create-camera-controls.js';
@@ -1 +1 @@
1
- export{AnimationSystem}from"./animation-system.js";export{CameraControlSystem,CameraControlType}from"./camera-control-system/camera-control-system.js";export{CameraSystem}from"./camera-control-system/camera-system.js";export{createCameraControls}from"./camera-control-system/create-camera-controls.js";export{CanvasSystem}from"./canvas-system.js";export{DragAndDropSystem}from"./drag-and-drop-system/drag-and-drop-system.js";export{ExportSystem}from"./export-system/export-system.js";export{GraphQLSystem}from"./graphql-system/graphql-system.js";export{ImageRenderingSystem}from"./image-rendering-system/image-rendering-system.js";export{LayoutSystem}from"./layout-system/layout-system.js";export{toolbarHelpElementName}from"./layout-system/toolbar-help-element.js";export{SketchingSystem}from"./sketching-system/sketching-system.js";export{LineEndPointUpdateTag,LineLengthUpdateTag,LineLineConnectionUpdateTag,LineRectangleBottomLeftConnectionUpdateTag,LineRectangleBottomRightConnectionUpdateTag,LineRectangleTopLeftConnectionUpdateTag,LineRectangleTopRightConnectionUpdateTag,LineSketchingPointUpdateTag,LineStartPointUpdateTag,RectangleBottomLeftCornerUpdateTag,RectangleBottomRightCornerUpdateTag,RectangleDepthUpdateTag,RectangleSketchingPointUpdateTag,RectangleTopLeftCornerUpdateTag,RectangleTopRightCornerUpdateTag,RectangleWidthUpdateTag,SetInitialSketchingPointPositionTag,SketchingFixTransformationTag,isAnySketchingPointUpdate,isLineEndPointUpdate,isLineLengthUpdate,isLineLineConnectionUpdate,isLineRectangleBottomLeftConnectionUpdate,isLineRectangleBottomRightConnectionUpdate,isLineRectangleTopLeftConnectionUpdate,isLineRectangleTopRightConnectionUpdate,isLineSketchingPointUpdate,isLineStartPointUpdate,isRectangleBottomLeftCornerUpdate,isRectangleBottomRightCornerUpdate,isRectangleDepthUpdate,isRectangleSketchingPointUpdate,isRectangleTopLeftCornerUpdate,isRectangleTopRightCornerUpdate,isRectangleWidthUpdate,isSetInitialLinePositionUpdate,isSetInitialRectanglePositionUpdate,isSketchingFixTransformationUpdate}from"./sketching-system/sketching-updates.js";
1
+ export{AnimationSystem}from"./animation-system.js";export{AssistantSystem}from"./assistant-system/assistant-system.js";export{CameraControlSystem,CameraControlType}from"./camera-control-system/camera-control-system.js";export{CameraSystem}from"./camera-control-system/camera-system.js";export{createCameraControls}from"./camera-control-system/create-camera-controls.js";export{CanvasSystem}from"./canvas-system.js";export{DragAndDropSystem}from"./drag-and-drop-system/drag-and-drop-system.js";export{ExportSystem}from"./export-system/export-system.js";export{GraphQLSystem}from"./graphql-system/graphql-system.js";export{ImageRenderingSystem}from"./image-rendering-system/image-rendering-system.js";export{LayoutSystem}from"./layout-system/layout-system.js";export{toolbarHelpElementName}from"./layout-system/toolbar-help-element.js";export{SketchingSystem}from"./sketching-system/sketching-system.js";export{LineEndPointUpdateTag,LineLengthUpdateTag,LineLineConnectionUpdateTag,LineRectangleBottomLeftConnectionUpdateTag,LineRectangleBottomRightConnectionUpdateTag,LineRectangleTopLeftConnectionUpdateTag,LineRectangleTopRightConnectionUpdateTag,LineSketchingPointUpdateTag,LineStartPointUpdateTag,RectangleBottomLeftCornerUpdateTag,RectangleBottomRightCornerUpdateTag,RectangleDepthUpdateTag,RectangleSketchingPointUpdateTag,RectangleTopLeftCornerUpdateTag,RectangleTopRightCornerUpdateTag,RectangleWidthUpdateTag,SetInitialSketchingPointPositionTag,SketchingFixTransformationTag,isAnySketchingPointUpdate,isLineEndPointUpdate,isLineLengthUpdate,isLineLineConnectionUpdate,isLineRectangleBottomLeftConnectionUpdate,isLineRectangleBottomRightConnectionUpdate,isLineRectangleTopLeftConnectionUpdate,isLineRectangleTopRightConnectionUpdate,isLineSketchingPointUpdate,isLineStartPointUpdate,isRectangleBottomLeftCornerUpdate,isRectangleBottomRightCornerUpdate,isRectangleDepthUpdate,isRectangleSketchingPointUpdate,isRectangleTopLeftCornerUpdate,isRectangleTopRightCornerUpdate,isRectangleWidthUpdate,isSetInitialLinePositionUpdate,isSetInitialRectanglePositionUpdate,isSketchingFixTransformationUpdate}from"./sketching-system/sketching-updates.js";
@@ -1 +1 @@
1
- import{fetchServerSentEvents as t,useChat as e}from"@tanstack/ai-react";import{useCallback as a,useMemo as r}from"react";import{useAuthorizedClient as s,useConfigurationId as n,useDomain as o}from"#package/react-sdk";import{useConfigurator as i}from"../application-runtime/index.js";import{browserDetailsClientTool as c}from"./browser-details.js";import{applyClientTool as p,queryClientTool as l}from"./graphql-tools.js";let m=[c,l,p];export const useAssistantChat=()=>{let c=n(),p=s(),l=r(()=>p.getAssistantChatConnection(c),[p,c]),d=r(()=>{let e=async()=>({headers:await l.headers()}),a=t(l.url,e),r=t(`${l.url}/runs`,e);return{...a,joinRun:r.joinRun}},[l]),{graphQLSystem:u}=i(),{storeSystem:h,domainContextSelectors:f}=o(),{getActiveMode:w}=f,{messages:g,isLoading:j,error:y,sendMessage:C,stop:S,runId:$}=e({threadId:`assistant:${c}`,connection:d,persistence:!0,history:{pageSize:50},tools:m,context:r(()=>({graphQLSystem:u,storeSystem:h,getActiveMode:w}),[u,h,w])});return{messages:g,isLoading:j,error:y,send:a(async t=>{let e={sentAt:new Date().toISOString()};await C({content:t,metadata:e})},[C]),stop:a(async()=>{S(),null!=$&&await fetch(`${l.url}/runs/${encodeURIComponent($)}/cancel`,{method:"POST",headers:await l.headers()})},[l,$,S])}};
1
+ import{fetchServerSentEvents as t,useChat as e}from"@tanstack/ai-react";import{useCallback as a,useMemo as n}from"react";import{useApplicationRuntimeSelector as s,useAuthorizedClient as r,useConfigurationId as o}from"#package/react-sdk";import{useConfigurator as i}from"../application-runtime/index.js";export const useAssistantChat=()=>{let c=o(),p=r(),l=n(()=>p.getAssistantChatConnection(c),[p,c]),u=n(()=>{let e=async()=>({headers:await l.headers()}),a=t(l.url,e),n=t(`${l.url}/runs`,e);return{...a,joinRun:n.joinRun}},[l]),{assistantSystem:d}=i(),{messages:m,isLoading:h,error:f,sendMessage:g,stop:w,runId:y}=e({threadId:`assistant:${c}`,connection:u,persistence:!0,history:{pageSize:50},tools:s(d.getTools)});return{messages:m,isLoading:h,error:f,send:a(async t=>{let e={sentAt:new Date().toISOString()};await g({content:t,metadata:e})},[g]),stop:a(async()=>{w(),null!=y&&await fetch(`${l.url}/runs/${encodeURIComponent(y)}/cancel`,{method:"POST",headers:await l.headers()})},[l,y,w])}};
@@ -1,5 +1,5 @@
1
1
  {
2
- "generatedAt": "2026-10-08T11:31:27.903Z",
2
+ "generatedAt": "2026-10-09T07:13:29.578Z",
3
3
  "categories": [
4
4
  {
5
5
  "name": "Phoenix",
@@ -26,7 +26,7 @@
26
26
  },
27
27
  {
28
28
  "title": "Best Practices",
29
- "description": "1. **YAML is king** - 99% of configuration should be in spec/\\*.yaml files 2. **Custom code locations** (in order of preference): - `src/expressions/` - Computed/derived properties -...",
29
+ "description": "1. **YAML is king** - 99% of configuration should be in spec/\\*.yaml files 2. **Custom code locations** (in order of preference): - `src/expressions/` - Computed/derived properties - `src/actions/` -...",
30
30
  "path": "docs/phoenix/best-practices.mdx",
31
31
  "category": [
32
32
  "Phoenix",
@@ -2479,6 +2479,16 @@
2479
2479
  ],
2480
2480
  "source": "storybook-example"
2481
2481
  },
2482
+ {
2483
+ "title": "Domain Actions",
2484
+ "description": "A plate carries holes, and a hole can be nudged by an offset as long as it stays on the plate. The arrow buttons of a selected hole and the AI assistant both make this change, so the rule (\"stay on...",
2485
+ "path": "docs/other-features/domain-actions.mdx",
2486
+ "category": [
2487
+ "Other features",
2488
+ "Domain Actions"
2489
+ ],
2490
+ "source": "storybook-example"
2491
+ },
2482
2492
  {
2483
2493
  "title": "Not Found (404)",
2484
2494
  "description": "Error page that is displayed when the configuration is not accesible.",