@salsita-ai/sdk 0.50.0-develop.9cf426b400 → 0.50.0-develop.aabb56df09

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 (110) hide show
  1. package/dist/application-spec/generate-application/code/templates/skills/phoenix-feedback-skill.js +1 -1
  2. package/dist/application-spec/generate-application/code/templates/skills/phoenix-skill.js +1 -1
  3. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.js +1 -1
  4. package/dist/configurator/application-runtime/extensions/selectors.js +1 -1
  5. package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.d.ts +146 -13
  6. package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.js +1 -1
  7. package/dist/configurator/application-runtime/extensions/systems/assistant-system/change-recorder.d.ts +85 -0
  8. package/dist/configurator/application-runtime/extensions/systems/assistant-system/change-recorder.js +1 -0
  9. package/dist/configurator/application-runtime/extensions/systems/assistant-system/graphql-tools.d.ts +8 -3
  10. package/dist/configurator/application-runtime/extensions/systems/assistant-system/graphql-tools.js +1 -1
  11. package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.d.ts +4 -0
  12. package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.js +1 -1
  13. package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.d.ts +16 -1
  14. package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.js +1 -1
  15. package/dist/configurator/application-runtime/extensions/systems/graphql-system/side-effects.d.ts +9 -0
  16. package/dist/configurator/application-runtime/extensions/systems/graphql-system/side-effects.js +1 -0
  17. package/dist/configurator/application-runtime/extensions/systems/index.d.ts +1 -1
  18. package/dist/configurator/application-runtime/extensions/systems/layout-system/layout-system.d.ts +2 -0
  19. package/dist/configurator/application-runtime/extensions/systems/layout-system/layout-system.js +1 -1
  20. package/dist/configurator/common/frontend-analytics.d.ts +21 -21
  21. package/dist/configurator/index.d.ts +0 -1
  22. package/dist/configurator/index.js +1 -1
  23. package/dist/configurator/pages/LoadedConfiguratorDetailPage.js +1 -1
  24. package/dist/configurator/scene/scene-analytics/scene-analytics.d.ts +2 -2
  25. package/dist/configurator/ui/assistant/AssistantChips.d.ts +11 -0
  26. package/dist/configurator/ui/assistant/AssistantChips.js +1 -0
  27. package/dist/configurator/ui/assistant/AssistantComposer.d.ts +6 -0
  28. package/dist/configurator/ui/assistant/AssistantComposer.js +1 -0
  29. package/dist/configurator/ui/assistant/AssistantMarkdown.d.ts +7 -0
  30. package/dist/configurator/ui/assistant/AssistantMarkdown.js +1 -0
  31. package/dist/configurator/ui/assistant/AssistantPanel.d.ts +11 -0
  32. package/dist/configurator/ui/assistant/AssistantPanel.js +1 -0
  33. package/dist/configurator/ui/assistant/AssistantThread.d.ts +6 -0
  34. package/dist/configurator/ui/assistant/AssistantThread.js +1 -0
  35. package/dist/configurator/ui/assistant/assistant-failure.d.ts +18 -0
  36. package/dist/configurator/ui/assistant/assistant-failure.js +1 -0
  37. package/dist/configurator/ui/assistant/index.d.ts +2 -0
  38. package/dist/configurator/ui/assistant/index.js +1 -0
  39. package/dist/configurator/ui/assistant/streamed-markdown.d.ts +6 -0
  40. package/dist/configurator/ui/assistant/streamed-markdown.js +2 -0
  41. package/dist/configurator/ui/assistant/theme.d.ts +2 -0
  42. package/dist/configurator/ui/assistant/theme.js +1 -0
  43. package/dist/configurator/ui/assistant/thread-items.d.ts +37 -0
  44. package/dist/configurator/ui/assistant/thread-items.js +1 -0
  45. package/dist/configurator/ui/assistant/tool-chip.d.ts +37 -0
  46. package/dist/configurator/ui/assistant/tool-chip.js +1 -0
  47. package/dist/configurator/ui/assistant/use-follow-stream.d.ts +17 -0
  48. package/dist/configurator/ui/assistant/use-follow-stream.js +1 -0
  49. package/dist/configurator/ui/assistant/use-is-assistant-panel-open.d.ts +5 -0
  50. package/dist/configurator/ui/assistant/use-is-assistant-panel-open.js +1 -0
  51. package/dist/configurator/ui/configurator-layout/universal/DesktopLayout.js +5 -5
  52. package/dist/configurator/ui/configurator-layout/universal/MobileLayout.d.ts +2 -0
  53. package/dist/configurator/ui/configurator-layout/universal/MobileLayout.js +4 -4
  54. package/dist/configurator/ui/legacy/mobile-controls/MobileControls.d.ts +1 -1
  55. package/dist/configurator/ui/phoenix-layout-elements/AssistantToolbarButton.d.ts +10 -0
  56. package/dist/configurator/ui/phoenix-layout-elements/AssistantToolbarButton.js +1 -0
  57. package/dist/configurator/ui/phoenix-layout-elements/index.d.ts +1 -0
  58. package/dist/configurator/ui/phoenix-layout-elements/index.js +1 -1
  59. package/dist/docs/index.json +1 -1
  60. package/dist/docs/layouts/toolbar.mdx +6 -0
  61. package/dist/docs/other-features/side-effects.mdx +26 -0
  62. package/dist/docs/phoenix/phoenix-cli.mdx +1 -1
  63. package/dist/domain/components/updates.d.ts +16 -0
  64. package/dist/domain/domain-context/index.d.ts +1 -1
  65. package/dist/domain/domain-context/store-system/store-system.js +1 -1
  66. package/dist/domain/system-components/phoenix-layout-elements/assistant-toolbar-button.d.ts +44 -0
  67. package/dist/domain/system-components/phoenix-layout-elements/assistant-toolbar-button.js +1 -0
  68. package/dist/domain/system-components/phoenix-layout-elements/index.d.ts +1 -0
  69. package/dist/domain/system-components/phoenix-layout-elements/index.js +1 -1
  70. package/dist/domain/system-components/phoenix-layout-elements/phoenix-layout-element.d.ts +2 -1
  71. package/dist/domain/system-components/phoenix-layout-elements/phoenix-layout-element.js +1 -1
  72. package/dist/editor/graphql/GraphQLPanel.js +1 -1
  73. package/dist/i18n/locales/cs/messages.js +1 -1
  74. package/dist/i18n/locales/da/messages.js +1 -1
  75. package/dist/i18n/locales/de/messages.js +1 -1
  76. package/dist/i18n/locales/de-AT/messages.js +1 -1
  77. package/dist/i18n/locales/en/messages.js +1 -1
  78. package/dist/i18n/locales/en-AU/messages.js +1 -1
  79. package/dist/i18n/locales/en-GB/messages.js +1 -1
  80. package/dist/i18n/locales/es/messages.js +1 -1
  81. package/dist/i18n/locales/fr/messages.js +1 -1
  82. package/dist/i18n/locales/hu/messages.js +1 -1
  83. package/dist/i18n/locales/it/messages.js +1 -1
  84. package/dist/i18n/locales/nl/messages.js +1 -1
  85. package/dist/i18n/locales/pl/messages.js +1 -1
  86. package/dist/i18n/locales/pt/messages.js +1 -1
  87. package/dist/i18n/locales/ro/messages.js +1 -1
  88. package/dist/i18n/locales/sk/messages.js +1 -1
  89. package/dist/i18n/locales/tr/messages.js +1 -1
  90. package/dist/legacy/domain-spec/__generated/domain-schema.d.ts +6 -0
  91. package/dist/phoenix/application-spec/generate-assistant-prompt.d.ts +3 -2
  92. package/dist/phoenix/application-spec/generate-assistant-prompt.js +1 -1
  93. package/dist/phoenix/commands/deploy.js +2 -2
  94. package/dist/react-sdk/application-runtime/common-services/analytics/analytics-service.d.ts +2 -2
  95. package/dist/react-sdk/application-runtime/common-services/analytics/domain-controls-analytics.d.ts +21 -21
  96. package/dist/react-sdk/application-runtime/hooks/data/use-published-data.d.ts +1 -1
  97. package/dist/ui-sdk/common/use-viewport-size.d.ts +4 -1
  98. package/dist/ui-sdk/common/use-viewport-size.js +1 -1
  99. package/dist/ui-sdk/components/mobile-controls/index.d.ts +1 -1
  100. package/dist/ui-sdk/theme/types.d.ts +4 -0
  101. package/package.json +5 -8
  102. package/schema/domain-spec.json +24 -0
  103. package/dist/configurator/assistant/index.d.ts +0 -1
  104. package/dist/configurator/assistant/index.js +0 -1
  105. package/dist/configurator/assistant/use-assistant-chat.d.ts +0 -20
  106. package/dist/configurator/assistant/use-assistant-chat.js +0 -1
  107. package/dist/extras/assistant/AssistantChat.d.ts +0 -6
  108. package/dist/extras/assistant/AssistantChat.js +0 -1
  109. package/dist/extras/assistant/index.d.ts +0 -1
  110. package/dist/extras/assistant/index.js +0 -1
@@ -51,4 +51,4 @@ The message leaves this project and is read by the Phoenix team. Never include:
51
51
  - secrets and credentials: API tokens, keys, passwords or \`.env\` values, also when they appear inside an error or a log you quote. Replace each with \`<redacted>\`;
52
52
  - personal data, or data of the project's customers and end users, such as names, email addresses and orders, other than a contact the user asked you to add.
53
53
 
54
- Parts of this project may go into a message: file names and paths, snippets of its specs and code, and the user's own words. They are sent only as part of a draft the user saw and approved, which is why the draft you show is always the full text.`;export const generatePhoenixFeedbackSkill=()=>e({name:"phoenix-feedback",description:"Drafting feedback about the Phoenix SDK, CLI, documentation or Studio for the Phoenix team and sending it with the phoenix feedback command once the user approves the draft, covering when to raise it, the report template with the build and configurator links, the evaluation interview at the end of a run, how to send it and what must never be included. Use when the SDK or CLI misbehaves, a doc or skill misled you, a missing feature forced a workaround, the user asks to send feedback, or the user is done with the configurator and the run should be evaluated.",sections:[t,o,"## Report Template\nWrite a report as plain text with the labels below, in this order, so the Phoenix team reads every report the same way. Keep every label; write `none` or `not deployed yet` where you have nothing to put.\n```text\nBuild: <build id> <Studio build page link>\nConfigurator: <live configurator link>\n\nWhat I was doing:\n<the task and the step you were on>\n\nWhat happened and what I expected:\n<what you ran or called, the result you got, and the result you expected>\n\nExact error or agent output:\n<the error text or the output, copied unchanged>\n\nWorkaround:\n<what you did instead, or none>\n\nConversation log:\n<the conversation condensed to the turns that matter: what the user asked, what you tried, what failed>\n```\n- **Build** is the latest build of this project, the one whose sources show the problem. `pnpm phoenix deploy` prints its id as `Build <id> started` and its page as `Follow the build in Studio: <url>`. When that line is missing, compose the link as `https://<workspace>.<studio host>/builder/deployments/<build id>`: the workspace is the one named at `phoenix login`, and the host is `studio.eu.salsita.ai` for the `eu` region, `studio.salsita.ai` for `us` and `studio-staging.salsita.app` for staging. A Studio address passed to login with `--studioUrl` replaces the workspace and host. Never invent a build id: when the project was not deployed, write `not deployed yet`.\n- **Configurator** is the live address `pnpm phoenix deploy` prints once the build is live.\n- The team downloads the sources of the build from its Studio page, so do not paste whole files; quote only the lines that show the problem.\n- Quote errors and output exactly. A report that paraphrases an error cannot be searched for.\n- Condense the conversation log, do not dump it: keep the user's requests, your decisions and the failures, and leave out tool output that the other sections already carry.",n,"## How to Send It\nWrite a report or an evaluation to a text file and send the file, so the shell changes nothing in it:\n```bash\npnpm phoenix feedback --file <path> --type bug --agent '<your agent name>'\n```\nPut the file outside the project, in the system's temporary folder, and delete it after sending. A note of a line or two can go in as an argument instead:\n```bash\npnpm phoenix feedback '<message>' --type idea --agent '<your agent name>'\n```\n- Give either `--file` or the message argument, never both.\n- Put a message argument in single quotes, so the shell passes backticks, `$` and double quotes through unchanged. In bash or zsh, write a single quote inside the message as `'\\''`; in PowerShell, double it instead.\n- `--type` is `bug`, `idea` or `other` (default `other`). Use `idea` for a missing feature or an improvement, and `other` for an evaluation.\n- `--agent` names you, the coding agent, so the team can tell agent feedback from a person's.\n- `--contact '<email>'` only when the user wants a reply and gave you the contact to use.\n- The workspace, user, SDK version and the spec's `project` are attached automatically. `--projectSlug <slug>` names another project of the workspace.\n- A message holds at most 100,000 characters. Shorten the conversation log first when a report is longer.\n\nThe command needs `phoenix login`. If it answers that you are not signed in, tell the user once and continue; do not sign in yourself, because the sign-in is approved in a browser.\n\nAfter sending, confirm it to the user in one line.",a]});
54
+ Parts of this project may go into a message: file names and paths, snippets of its specs and code, and the user's own words. They are sent only as part of a draft the user saw and approved, which is why the draft you show is always the full text.`;export const generatePhoenixFeedbackSkill=()=>e({name:"phoenix-feedback",description:"Evaluating a finished run and drafting feedback about the Phoenix SDK, CLI, documentation or Studio for the Phoenix team, sent with the phoenix feedback command once the user approves the draft. Use right after phoenix deploy reports the configurator live or when the user says they are done, to offer the evaluation of the run, and when the SDK or CLI misbehaves, a doc or skill misled you, a missing feature forced a workaround or the user asks to send feedback.",sections:[t,o,"## Report Template\nWrite a report as plain text with the labels below, in this order, so the Phoenix team reads every report the same way. Keep every label; write `none` or `not deployed yet` where you have nothing to put.\n```text\nBuild: <build id> <Studio build page link>\nConfigurator: <live configurator link>\n\nWhat I was doing:\n<the task and the step you were on>\n\nWhat happened and what I expected:\n<what you ran or called, the result you got, and the result you expected>\n\nExact error or agent output:\n<the error text or the output, copied unchanged>\n\nWorkaround:\n<what you did instead, or none>\n\nConversation log:\n<the conversation condensed to the turns that matter: what the user asked, what you tried, what failed>\n```\n- **Build** is the latest build of this project, the one whose sources show the problem. `pnpm phoenix deploy` prints its id as `Build <id> started` and its page as `Follow the build in Studio: <url>`. When that line is missing, compose the link as `https://<workspace>.<studio host>/builder/deployments/<build id>`: the workspace is the one named at `phoenix login`, and the host is `studio.eu.salsita.ai` for the `eu` region, `studio.salsita.ai` for `us` and `studio-staging.salsita.app` for staging. A Studio address passed to login with `--studioUrl` replaces the workspace and host. Never invent a build id: when the project was not deployed, write `not deployed yet`.\n- **Configurator** is the live address `pnpm phoenix deploy` prints once the build is live.\n- The team downloads the sources of the build from its Studio page, so do not paste whole files; quote only the lines that show the problem.\n- Quote errors and output exactly. A report that paraphrases an error cannot be searched for.\n- Condense the conversation log, do not dump it: keep the user's requests, your decisions and the failures, and leave out tool output that the other sections already carry.",n,"## How to Send It\nWrite a report or an evaluation to a text file and send the file, so the shell changes nothing in it:\n```bash\npnpm phoenix feedback --file <path> --type bug --agent '<your agent name>'\n```\nPut the file outside the project, in the system's temporary folder, and delete it after sending. A note of a line or two can go in as an argument instead:\n```bash\npnpm phoenix feedback '<message>' --type idea --agent '<your agent name>'\n```\n- Give either `--file` or the message argument, never both.\n- Put a message argument in single quotes, so the shell passes backticks, `$` and double quotes through unchanged. In bash or zsh, write a single quote inside the message as `'\\''`; in PowerShell, double it instead.\n- `--type` is `bug`, `idea` or `other` (default `other`). Use `idea` for a missing feature or an improvement, and `other` for an evaluation.\n- `--agent` names you, the coding agent, so the team can tell agent feedback from a person's.\n- `--contact '<email>'` only when the user wants a reply and gave you the contact to use.\n- The workspace, user, SDK version and the spec's `project` are attached automatically. `--projectSlug <slug>` names another project of the workspace.\n- A message holds at most 100,000 characters. Shorten the conversation log first when a report is longer.\n\nThe command needs `phoenix login`. If it answers that you are not signed in, tell the user once and continue; do not sign in yourself, because the sign-in is approved in a browser.\n\nAfter sending, confirm it to the user in one line.",a]});
@@ -1 +1 @@
1
- import{renderAgentSkill as e}from"./agent-skill.js";import{sdkGuidanceSections as t}from"./sdk-content.js";export const followsCanaryBuilds=e=>!e.useWorkspace&&e.sdkVersion.includes("-develop.");export const generatePhoenixSkill=({checkLatestCanary:n})=>e({name:"phoenix",description:`Phoenix SDK project conventions, covering project structure, architecture principles, key patterns, file and export rules, webhook membership, versioning the domain model once it is deployed, showing the user the dev preview and the build of a deploy, and how to search the SDK documentation${n?", and the internal-beta check for the latest canary SDK build":""}. Use before writing or changing specs or source code in this Phoenix configurator project.`,sections:[...n?["## Stay on the Latest Canary\nDuring the internal beta this project uses the `canary` build of the SDK, which is published from every change to the platform. Once per conversation, before you change anything, compare the installed version with the newest canary:\n```bash\npnpm list @salsita-ai/sdk --depth 0\nnpm view @salsita-ai/sdk@canary version\n```\nWhen they differ, tell the user which version you are moving to, then update the project and regenerate its files:\n```bash\npnpm add @salsita-ai/sdk@canary\npnpm phoenix sync\n```\n`sync` rewrites the Phoenix skills, so read the ones you use again after it. When the user runs a globally installed `phoenix`, update that too with `npm install -g @salsita-ai/sdk@canary`. If the project no longer builds after the update, stop and tell the user; the `phoenix-feedback` skill covers reporting it."]:[],t.projectStructure,t.architecturePrinciples,t.keyPatterns,t.fileConventions,t.exportRules,t.webhookMembership,t.doNotEdit,t.modelVersioning,"## Show the Preview While You Work\nThe user should see the configurator change as you build it. Before your first change in a conversation, make sure `pnpm phoenix dev` is running (start it in the background when it is not) and open the address it prints as `Preview: <url>` (also written to `.phoenix/phoenix-dev.log`) in the user's browser: `open '<url>'` on macOS, `xdg-open '<url>'` on Linux, `Start-Process '<url>'` in PowerShell, `start \"\" \"<url>\"` in cmd. Keep the quotes, the shell would otherwise read a `?` in the address as a pattern. The log keeps the lines of earlier runs, so when you have just started dev, wait for the `Preview:` line written after your start and use the last one. Open it once; the preview reloads on every change, so tell the user to keep that tab open instead of opening it again.","## Show the Build After a Deploy\n`pnpm phoenix deploy` starts a build on the server and waits for it to go live. Right after `Build <id> started` it prints `Follow the build in Studio: <url>`. Run the deploy so that you can read its output while it runs, and open that link in the user's browser, quoted as above, as soon as it appears, so they can follow the build they just triggered. When the line is missing, the sign-in is older than the link: tell the user the build is listed under Deployments in Studio, and that `pnpm phoenix login <workspace>` brings the link back.","## Code Review\nUse the `phoenix-review` skill to review code changes before committing.",t.sdkDocumentation]});
1
+ import{renderAgentSkill as e}from"./agent-skill.js";import{sdkGuidanceSections as t}from"./sdk-content.js";export const followsCanaryBuilds=e=>!e.useWorkspace&&e.sdkVersion.includes("-develop.");export const generatePhoenixSkill=({checkLatestCanary:n})=>e({name:"phoenix",description:`Phoenix SDK project conventions, covering project structure, architecture principles, key patterns, file and export rules, webhook membership, versioning the domain model once it is deployed, showing the user the dev preview and the build of a deploy, the run evaluation that follows a live deploy, and how to search the SDK documentation${n?", and the internal-beta check for the latest canary SDK build":""}. Use before writing or changing specs or source code in this Phoenix configurator project.`,sections:[...n?["## Stay on the Latest Canary\nDuring the internal beta this project uses the `canary` build of the SDK, which is published from every change to the platform. Once per conversation, before you change anything, compare the installed version with the newest canary:\n```bash\npnpm list @salsita-ai/sdk --depth 0\nnpm view @salsita-ai/sdk@canary version\n```\nWhen they differ, tell the user which version you are moving to, then update the project and regenerate its files:\n```bash\npnpm add @salsita-ai/sdk@canary\npnpm phoenix sync\n```\n`sync` rewrites the Phoenix skills, so read the ones you use again after it. When the user runs a globally installed `phoenix`, update that too with `npm install -g @salsita-ai/sdk@canary`. If the project no longer builds after the update, stop and tell the user; the `phoenix-feedback` skill covers reporting it."]:[],t.projectStructure,t.architecturePrinciples,t.keyPatterns,t.fileConventions,t.exportRules,t.webhookMembership,t.doNotEdit,t.modelVersioning,"## Show the Preview While You Work\nThe user should see the configurator change as you build it. Before your first change in a conversation, make sure `pnpm phoenix dev` is running (start it in the background when it is not) and open the address it prints as `Preview: <url>` (also written to `.phoenix/phoenix-dev.log`) in the user's browser: `open '<url>'` on macOS, `xdg-open '<url>'` on Linux, `Start-Process '<url>'` in PowerShell, `start \"\" \"<url>\"` in cmd. Keep the quotes, the shell would otherwise read a `?` in the address as a pattern. The log keeps the lines of earlier runs, so when you have just started dev, wait for the `Preview:` line written after your start and use the last one. Open it once; the preview reloads on every change, so tell the user to keep that tab open instead of opening it again.",'## Show the Build After a Deploy\n`pnpm phoenix deploy` starts a build on the server and waits for it to go live. Right after `Build <id> started` it prints `Follow the build in Studio: <url>`. Run the deploy so that you can read its output while it runs, and open that link in the user\'s browser, quoted as above, as soon as it appears, so they can follow the build they just triggered. When the line is missing, the sign-in is older than the link: tell the user the build is listed under Deployments in Studio, and that `pnpm phoenix login <workspace>` brings the link back.\n\nWhen the deploy reports the configurator live, load the `phoenix-feedback` skill before you write your final message and follow its "Evaluate the Run" section, so the user is asked about the run while they are still there. It is asked once per conversation, and only once the user has nothing more to build.',"## Code Review\nUse the `phoenix-review` skill to review code changes before committing.",t.sdkDocumentation]});
@@ -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 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]))}};
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,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 w}from"../../common/index.js";import{GraphQLJSON as N,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: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(y.ASSISTANT_UNKNOWN_TYPE,m.ASSISTANT_UNKNOWN_TYPE(t.section,a));continue}for(let[e,r]of(l.forEach(e=>s.set(e,W(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=L(i,t.component,n),l=o.get(i)??[],c=l.find(e=>e.group.groupId===d.groupId);r.includes(e)?c?s.error(y.ASSISTANT_DUPLICATE_RECIPE_GROUP,m.ASSISTANT_DUPLICATE_RECIPE_GROUP(t,i,d.groupId,[c.entry,p])):o.set(i,[...l,{group:d,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=d(n),p=r||!l(a)?N: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"===w(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(N):N,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:w,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:w,entityTypes:u.entityTypes},et),ea=ee(E,[],es.get(E)??[],()=>void 0,Y),ep=new Map,ed=F(c.childRecipes??{},R,{model:u,components:M},Y.at(R.section)),el=F(c.replaceRecipes??{},j,{model:u,components:M},Y.at(j.section)),ec=ed.groups,eh=el.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 ew=((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")),eN=((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=d(f),w=c??t,E=void 0===c?C(S,u):void 0;return g?{name:w,property:t,type:N,description:E?`${E} ${P}`:P}:{name:w,property:t,type:l(T)?T:N,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 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=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)d.error(y.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME,m.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME(l,s,r.name));else if(h)d.error(y.ASSISTANT_DUPLICATE_OPTIONS_EDGE,m.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:W(a.hints),entry:l,entryCtx:d}])}else d.error(y.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT,m.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT(l,a,i,p))}}}return o})(c.writable??{},eN,{model:u,components:M},Y.at("writable"));var eE,eI,e_,eO=[ed.metaEntries,el.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."},sideEffects:{type:new o(new r(new o(p))),description:"What the configurator would do beyond the change itself, such as parts it would add or replace, in its own words; 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(N),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:ed.hints.get(e)??[]},replaceRecipes:{groups:n,hints:el.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,d]of Object.entries(e)){let e=o.at(p),l=[...t.values()].find(e=>e.name===p);if(!l){e.error(y.ASSISTANT_UNKNOWN_ACTION,m.ASSISTANT_UNKNOWN_ACTION(p,a));continue}let c=d?.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:d?.description??l.description,args:Object.fromEntries(Object.entries(l.params).map(([e,{schema:t}])=>[e,Q(t,n)])),result:Object.fromEntries(Object.entries(l.result).map(([e,t])=>[e,X(t,n)]))})}return s})(c.actions??{},{actions:G,resolveRef:er,builtInMutations:new Set(["deleteEntity",R.mutation,j.mutation,...eN.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 d;return new a({query:(e=eu(eg.has(I)?I:E),i=eu(E),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: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."},...d?{navigation:{type:new o(d)}}:{}}})),mutation:(({deletableTypes:e,writableTypes:i,childRecipes:a,replaceRecipes:d,actionFields:l,objectTypes:c,anyDomainEntity:h,targetOutputType:f})=>{let u,y;if(0!==e.length||0!==i.length||0!==Object.keys(a).length||0!==Object.keys(d).length||0!==l.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(d)).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(l.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:ew,writableTypes:eN,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:ew,writableFields:Object.fromEntries(eN.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]))}};
@@ -1 +1 @@
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};
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,d={getConfigurationId:()=>c.getConfiguratorConfigurationId(),getAuthorizedClient:()=>f.getConfiguratorAuthorizedClient(),domainContextSelectors:u,domainServicesSelectors:C,specSelectors:w},l={getSystems:()=>G,getCanvasSystem:()=>p,getCameraControlSystem:()=>A,getAnimationSystem:()=>E,getDragAndDropSystem:()=>h,getImageRenderingSystem:()=>v,getLayoutSystem:()=>L,getSketchingSystem:()=>j,getExportSystem:()=>I,getCameraSystem:()=>k,getGraphQLSystem:()=>z,getAssistantSystem:()=>D},x={...d,configuratorExtensionSelectors:l},p=new r(d),A=new n({configuratorExtensionSelectors:l}),h=new s(x),E=new e(d),I=new g(x),z=new i(d),D=new t(x),L=new m(d),j=new S(x),k=new o(x),v=new a(x),G={cameraControlSystem:A,layoutSystem:L,sketchingSystem:j,dragAndDropSystem:h,canvasSystem:p,cameraSystem:k,exportSystem:I,imageRenderingSystem:v,animationSystem:E,graphQLSystem:z,assistantSystem:D};return l};
@@ -1,35 +1,168 @@
1
1
  import type { AnyClientTool } from '@tanstack/ai';
2
- import type { DomainContextSelectors, InitializableSystem, SpecSelectors } from '#package/domain';
2
+ import { type UIMessage } from '@tanstack/ai-client';
3
+ import { type ObservableWithLastValue } from '@salsita-ai/common/utils';
4
+ import type { AuthorizedPhoenixApiClient } from '#package/client';
5
+ import type { DomainContextSelectors, DomainServicesSelectors, InitializableSystem, SpecSelectors } from '#package/domain';
3
6
  import type { ConfiguratorExtensionSelectors } from '../../selectors.js';
4
7
  /** A tool of the assistant that the model calls and the browser runs, as the chat client accepts it. */
5
8
  export type AssistantClientTool = AnyClientTool;
6
9
  /**
7
10
  * 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.
11
+ * the tools reach the store, the session mode and the `GraphQLSystem` when they are called, and the
12
+ * chat reaches the server of the current session when it sends a request.
9
13
  */
10
14
  export interface AssistantSystemContext {
11
15
  readonly configuratorExtensionSelectors: ConfiguratorExtensionSelectors;
12
16
  readonly domainContextSelectors: DomainContextSelectors;
17
+ readonly domainServicesSelectors: DomainServicesSelectors;
13
18
  readonly specSelectors: SpecSelectors;
19
+ readonly getConfigurationId: () => string;
20
+ readonly getAuthorizedClient: () => AuthorizedPhoenixApiClient<any, any, any>;
14
21
  }
15
22
  /**
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.
23
+ * The conversation with the assistant as the panel paints it. One value is published per change, so
24
+ * it changes with every chunk of a streaming reply.
25
+ */
26
+ export interface AssistantChatSnapshot {
27
+ /** The thread as painted: hydrated from the server, then streamed. */
28
+ readonly messages: ReadonlyArray<UIMessage>;
29
+ /** True while a round of a reply streams or its browser tools run; false in the pause before the next round. */
30
+ readonly isLoading: boolean;
31
+ readonly error: Error | undefined;
32
+ /**
33
+ * HTTP status of the latest request the server answered with a failure, for telling a refusal from
34
+ * a dropped connection when `error` is set. Nothing when the latest answered request succeeded or
35
+ * the server was never reached.
36
+ */
37
+ readonly failedStatus: number | undefined;
38
+ /** False when the server said this session may read the thread but not add to it. */
39
+ readonly isContinuable: boolean;
40
+ /** False until the first request of the chat, the thread read, was answered or failed. */
41
+ readonly isLoaded: boolean;
42
+ }
43
+ /**
44
+ * The built-in assistant panel as a layout and the toolbar button see it: whether it is open, and
45
+ * the few facts about it they render. It changes only when one of those does.
46
+ */
47
+ export interface AssistantPanelSnapshot {
48
+ readonly open: boolean;
49
+ /** True when a reply finished while the panel was closed and the panel was not opened since. */
50
+ readonly hasUnreadReply: boolean;
51
+ /** True while the message input has focus; a phone layout gives the panel the whole screen then. */
52
+ readonly isInputFocused: boolean;
53
+ }
54
+ /**
55
+ * Owns the conversational assistant of a configurator: its client tools (`getBrowserDetails`,
56
+ * `query` and `apply`), the chat with the server, the state of the built-in panel, and the record
57
+ * of what changed in the configuration since the agent last acted, which every user message carries.
58
+ *
59
+ * The server owns the thread, so the chat keeps nothing in browser storage: its client hydrates
60
+ * from the server and rejoins a reply that is still streaming.
61
+ *
62
+ * WORKAROUND: the runtime cannot tell a system that its configuration was left, and a system cannot
63
+ * observe the application spec. Until it can do both, the chat is started and ended from outside,
64
+ * through {@link AssistantSystem.activate}; see there for what that costs.
20
65
  */
21
66
  export declare class AssistantSystem implements InitializableSystem {
22
67
  private readonly _context;
23
68
  private readonly _tools;
24
- private _isInitialized;
69
+ private readonly _chat;
70
+ private readonly _panel;
71
+ /** Identity of the current `activate()` call; nothing while the chat is not active. */
72
+ private _activation;
73
+ /** The chat of the current activation; nothing while no chat is active. */
74
+ private _current;
75
+ /**
76
+ * Chats that have ended while their reply was still running and are finishing it in the
77
+ * background. Each leaves the set when its reply ends or when a new chat takes its thread over.
78
+ */
79
+ private readonly _finishing;
80
+ private readonly _recorder;
81
+ /** The recorder's subscription to the committed emissions of the store; made by the first `initialize()`. */
82
+ private _recording;
25
83
  constructor(_context: AssistantSystemContext);
84
+ /** The conversation. It never completes, and holds the empty chat whenever no chat is active. */
85
+ readonly chat$: ObservableWithLastValue<AssistantChatSnapshot>;
86
+ /** The state of the built-in panel. It never completes. */
87
+ readonly panel$: ObservableWithLastValue<AssistantPanelSnapshot>;
88
+ /**
89
+ * A new configuration load: the chat of the previous one is deactivated and both observables go
90
+ * back to their empty values. An activation that is still held outlives it and gets the chat of
91
+ * the new load, because the page that holds it can be mounted before this runs: a configuration
92
+ * that is entered again renders its page at once and initializes from an effect after the page's.
93
+ *
94
+ * Accepted cost: on such a re-entry the thread is read twice. The page's `activate()` has already
95
+ * created a client and started its read when this runs, and that client is replaced here, because
96
+ * the system cannot tell that it was created for the load that is only now being initialized.
97
+ *
98
+ * The change recorder starts over from the loaded state, so the first message after a load says
99
+ * that the changes are unavailable. The store is retained across loads and has already emitted the
100
+ * loaded state when this runs, so one subscription serves every load.
101
+ */
26
102
  initialize: () => void;
27
103
  /**
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.
104
+ * Starts the chat of the loaded configuration: creates the client, which reads the thread from the
105
+ * server and rejoins a reply that is still running. The returned function ends it.
106
+ *
107
+ * WORKAROUND, to be replaced once the runtime has teardown and spec observation for systems. Two
108
+ * things a system cannot learn by itself are decided by the caller, the loaded configurator page:
109
+ *
110
+ * - Whether the application spec has an `assistant` section, also after editor hot reload added or
111
+ * removed it. The page calls this only while the section is there; the system does not check.
112
+ * - That the user left the configuration. No `initialize()` follows a route change, so without the
113
+ * returned function the chat would go on working on a configuration nobody looks at.
114
+ *
115
+ * Ending the chat does not cut a running reply off: it finishes in the background, where every
116
+ * tool call it still makes is answered with a refusal that tells the model to stop, and it no
117
+ * longer reaches `chat$` or `panel$`. A tool call that is already running when the chat ends is
118
+ * not interrupted, so an `apply` that has started may still commit. The background reply keeps
119
+ * the configuration and the authorized client it started with.
120
+ *
121
+ * The background reply ends early when a new chat starts for the same configuration, which is
122
+ * what opening the configuration again does: see `_takeOverThread`.
123
+ */
124
+ activate: () => (() => void);
125
+ /**
126
+ * Sends a user message with the record of what changed in the configuration since the agent last
127
+ * acted, which the server puts in front of the message for the model. The record is taken only
128
+ * when there is a chat to send it on, because taking it moves its baseline.
129
+ */
130
+ send: (content: string) => Promise<void>;
131
+ /**
132
+ * Stops the reply on both sides. Closing the stream alone keeps the server run going, because a
133
+ * closed connection is also how a reload looks and a reload must be able to rejoin the run.
134
+ */
135
+ stop: () => Promise<void>;
136
+ /**
137
+ * Loads the thread from the server again, rejoining a reply that is still running there. It never
138
+ * sends a message again, because the server may already hold it; a message that did not reach the
139
+ * server is therefore gone from the thread and has to be written again.
140
+ */
141
+ reloadThread: () => void;
142
+ setOpen: (open: boolean) => void;
143
+ setInputFocused: (isInputFocused: boolean) => void;
144
+ private _committedState;
145
+ private _patchPanel;
146
+ /**
147
+ * Disconnects every chat that is still finishing a reply on the thread of the given configuration,
148
+ * so the chat that is about to start is the only one on it.
149
+ *
150
+ * Two clients on one thread would both follow the same server run: the new one rejoins it when it
151
+ * reads the thread. Both would then handle the run's next tool call, the old one with a refusal
152
+ * and the new one for real, and both would send the result back, of which the server accepts one.
153
+ * The model could be told that nothing was run about a change that was made.
154
+ *
155
+ * Stopping a client only closes its stream in the browser. Nothing is cancelled on the server, so
156
+ * the run goes on there and the new chat rejoins it. A chat that finishes a reply for another
157
+ * configuration is on another thread and is left alone.
158
+ */
159
+ private _takeOverThread;
160
+ private _startClient;
161
+ /**
162
+ * Lets go of the current chat and puts the empty chat in its place. The client itself is left as
163
+ * it is: whether it finishes its reply or is cut off is the caller's decision.
33
164
  */
34
- getTools: () => readonly AssistantClientTool[];
165
+ private _retireChat;
166
+ /** Ends the current chat without cutting its reply off. */
167
+ private _endChat;
35
168
  }
@@ -1 +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}
1
+ import{ChatClient as t,fetchServerSentEvents as e}from"@tanstack/ai-client";import{BehaviorSubject as i}from"rxjs";import{skip as s}from"rxjs/operators";import{isShallowEqual as a}from"@salsita-ai/common/utils";import{createBrowserDetailsClientTool as n}from"./browser-details.js";import{ChangeRecorder as r}from"./change-recorder.js";import{createApplyClientTool as o,createQueryClientTool as c}from"./graphql-tools.js";let l=Object.freeze({messages:Object.freeze([]),isLoading:!1,error:void 0,failedStatus:void 0,isContinuable:!0,isLoaded:!1}),h=Object.freeze({open:!1,hasUnreadReply:!1,isInputFocused:!1}),d=Object.freeze({}),u=Object.freeze({results:Object.freeze([]),committed:!1,sideEffects:Object.freeze([]),message:"Nothing was run, because the user closed the configurator while this reply was being written. Do not call any more tools in this reply and end it now. The tools work again as soon as the user writes the next message."}),_=t=>{if(t.getError())return!0;let e=t.getMessages().at(-1)?.parts.at(-1);return e?.type!=="tool-call"&&e?.type!=="tool-result"};export class AssistantSystem{_context;_tools;_chat=new i(l);_panel=new i(h);_activation=null;_current=null;_finishing=new Set;_recorder;_recording=null;constructor(t){this._context=t;let{configuratorExtensionSelectors:e,domainContextSelectors:i,domainServicesSelectors:s,specSelectors:a}=t;this._recorder=new r({maxEntities:30},{readers:{selectedEntityId:t=>i.getNavigationSystem().getActiveSelectionState(t),navigationState:t=>i.getNavigationSystem().getActiveNavigationState(t),viewState:t=>i.getNavigationSystem().getActiveViewState(t),toolState:t=>i.getNavigationSystem().getActiveToolState(t)},getExposedFields:()=>a.getAssistant()?.fields??d,resolveLocalizable:t=>s.getResolveLocalizable()(t)});let l={getGraphQLSystem:()=>e.getGraphQLSystem(),getStoreSystem:()=>i.getStoreSystem(),getActiveMode:()=>i.getActiveMode(),clearChanges:()=>this._recorder.clear(this._committedState())};this._tools=[n(),c(l),o(l)]}chat$=this._chat;panel$=this._panel;initialize=()=>{let{committed:t}=this._context.domainContextSelectors.getStoreSystem().stateSlices;this._recording??=t.pipe(s(1)).subscribe(this._recorder.record),this._recorder.reset(t.value.state),this._endChat(),this._patchPanel(h),this._activation&&this._startClient()};activate=()=>{this._endChat();let t={};return this._activation=t,this._startClient(),()=>{this._activation===t&&(this._activation=null,this._endChat())}};send=async t=>{let e=this._current;if(!e)return;let i={changes:this._recorder.take(this._committedState())};await e.client.sendMessage({content:t,metadata:i})};stop=async()=>{let t=this._current;if(!t)return;let e=t.client.getCurrentRunId();if(t.client.stop(),null!=e)try{let i=t.getConnection();await fetch(`${i.url}/runs/${encodeURIComponent(e)}/cancel`,{method:"POST",headers:await i.headers()})}catch(t){this._context.domainServicesSelectors.getLogger().warn("Could not cancel the assistant run on the server",{error:t})}};reloadThread=()=>{if(!this._activation)return;let t=this._retireChat();t?.client.stop(),t?.dispose(),this._recorder.reset(this._committedState()),this._startClient()};setOpen=t=>{this._patchPanel(t?{open:t,hasUnreadReply:!1}:{open:t,isInputFocused:!1})};setInputFocused=t=>{this._patchPanel({isInputFocused:t})};_committedState=()=>this._context.domainContextSelectors.getStoreSystem().stateSlices.committed.value.state;_patchPanel=t=>{let e={...this._panel.value,...t};a(e,this._panel.value)||this._panel.next(e)};_takeOverThread=t=>{for(let e of this._finishing)e.configurationId===t&&(e.client.stop(),e.dispose())};_startClient=()=>{let i={active:!0},s=this._context.getConfigurationId();this._takeOverThread(s);let n=this._context.getAuthorizedClient(),r=()=>n.getAssistantChatConnection(s),o=t=>{if(!i.active)return;let e={...this._chat.value,...t};a(e,this._chat.value)||this._chat.next(e)},c=async(t,e)=>{let i=await fetch(t,e).finally(()=>o({isLoaded:!0})),s=i.headers.get("x-assistant-thread-continuable");return o({failedStatus:i.ok?void 0:i.status,...null!=s&&{isContinuable:"false"!==s}}),i},l=async()=>({headers:await r().headers(),fetchClient:c}),h=e(()=>r().url,l),d=e(()=>`${r().url}/runs`,l),g=this._tools.map(t=>({...t,execute:(e,s)=>i.active?t.execute?.(e,s):u})),p=new t({threadId:`assistant:${s}`,connection:{...h,joinRun:d.joinRun},persistence:!0,history:{pageSize:50},tools:g,onMessagesChange:t=>o({messages:t}),onLoadingChange:t=>{let e=i.active&&this._chat.value.isLoading;o({isLoading:t}),!t&&_(p)&&(i.active?e&&!this._panel.value.open&&this._patchPanel({hasUnreadReply:!0}):v())},onErrorChange:t=>{i.active&&t!==this._chat.value.error&&(o({error:t}),t&&this._context.domainServicesSelectors.getLogger().error("The assistant request failed",{status:this._chat.value.failedStatus},t))}}),m=!1,v=()=>{m||(m=!0,this._finishing.delete(f),p.dispose())},f={client:p,configurationId:s,generation:i,getConnection:r,dispose:v};this._current=f,p.attach()};_retireChat=()=>{let t=this._current;return this._current=null,t&&(t.generation.active=!1),this._chat.value!==l&&this._chat.next(l),t};_endChat=()=>{let t=this._retireChat();if(t){if(!t.client.getIsLoading()&&_(t.client))return void t.dispose();this._finishing.add(t)}}}
@@ -0,0 +1,85 @@
1
+ import type { Localizable } from '@salsita-ai/common/utils';
2
+ import { type $DomainEntity, type AssistantManifest, type DomainEntity, type DomainState, type StateEmission } from '#package/domain';
3
+ type AnyDomainEntity = DomainEntity<string>;
4
+ type AnyDomainState = DomainState<AnyDomainEntity>;
5
+ type AnyStateEmission = StateEmission<AnyDomainEntity, Record<string, $DomainEntity<AnyDomainEntity>>>;
6
+ /**
7
+ * What the change record compares besides the entities: the values the `Query` root of the
8
+ * assistant's schema exposes as `selectedEntity` and `navigation`, read off a state.
9
+ */
10
+ export interface ChangeRecorderStateReaders {
11
+ readonly selectedEntityId: (state: AnyDomainState) => string | undefined;
12
+ readonly navigationState: (state: AnyDomainState) => string | undefined;
13
+ readonly viewState: (state: AnyDomainState) => string | undefined;
14
+ readonly toolState: (state: AnyDomainState) => string | undefined;
15
+ }
16
+ /** What a {@link ChangeRecorder} reads from the running configurator. */
17
+ export interface ChangeRecorderContext {
18
+ readonly readers: ChangeRecorderStateReaders;
19
+ /**
20
+ * The field table of the assistant manifest: per entity type of the schema, each exposed field
21
+ * name with the stored field or expression it reads. The record lists nothing the table does not
22
+ * hold, so the agent is shown only what it could also query. Read at every take, because editor
23
+ * hot reload replaces the manifest.
24
+ */
25
+ readonly getExposedFields: () => AssistantManifest['fields'];
26
+ readonly resolveLocalizable: (message: Localizable) => string;
27
+ }
28
+ export interface ChangeRecorderProps {
29
+ /** More differing entities than this are counted and not listed. */
30
+ readonly maxEntities: number;
31
+ }
32
+ /**
33
+ * Records what changed in the committed configuration since the assistant agent last acted, and
34
+ * prints it as the change record a user message carries to the agent.
35
+ *
36
+ * The record is a net diff: the committed state at the last take or clear is kept as the baseline
37
+ * and compared with the current one, so a value that was changed and changed back is not listed.
38
+ * Of the emissions in between, only the last update that touched each entity and each entity field
39
+ * is kept, to say why a line is there. Selection and navigation are read off the two states and
40
+ * never from their updates.
41
+ *
42
+ * Only what the assistant manifest exposes is listed: entities of the types its schema has, and of
43
+ * their stored fields the exposed ones, under their exposed names and localized like the schema
44
+ * returns them. A change of anything else is not in the record.
45
+ */
46
+ export declare class ChangeRecorder {
47
+ private readonly _props;
48
+ private readonly _context;
49
+ private _baseline;
50
+ /** True from a reset until the first take: what happened before the baseline is not known. */
51
+ private _isUnavailable;
52
+ private readonly _touches;
53
+ private _lastReset;
54
+ private _wasUndoneOrRedone;
55
+ constructor(_props: ChangeRecorderProps, _context: ChangeRecorderContext);
56
+ /** Starts over from this committed state; the next take reports `unavailable`. */
57
+ reset: (state: AnyDomainState) => void;
58
+ /** Records one committed emission: the last update that touched each entity and field, or the reset. */
59
+ record: (emission: AnyStateEmission) => void;
60
+ /** The change record since the last take or clear, as the prompt describes it; moves the baseline. */
61
+ take: (state: AnyDomainState) => string;
62
+ /** Forgets what was recorded and makes this committed state the baseline. */
63
+ clear: (state: AnyDomainState) => void;
64
+ private _touchesOf;
65
+ private _touchFields;
66
+ private _print;
67
+ private _diffStates;
68
+ /** Added and modified entities in the order of the current state, then the deleted ones in the order they had. */
69
+ private _diffEntities;
70
+ /**
71
+ * The lines of the exposed stored fields that differ, in manifest order. A field no update
72
+ * touched since its entity was created or replaced under an id that existed before is explained
73
+ * by that creation.
74
+ */
75
+ private _diffFields;
76
+ /** Why a line is in the record; a line no recorded update explains was left by a reset. */
77
+ private _comment;
78
+ /**
79
+ * What the agent is told about an update, else what the user was told, else the update tag. As
80
+ * for `sideEffects`, an `agentHint` replaces the `hint` whatever it holds: `null` or empty text
81
+ * hides the wording from the agent, not the change, so the tag stands in.
82
+ */
83
+ private _explain;
84
+ }
85
+ export {};
@@ -0,0 +1 @@
1
+ import{match as e}from"ts-pattern";import{isUndoRedoReset as t}from"#package/domain";import{localize as i}from"../graphql-system/graphql-system.js";let s=[["selected","selectedEntityId"],["navigationState","navigationState"],["viewState","viewState"],["toolState","toolState"]],n=e=>e.length>80?`${e.slice(0,80)}…`:e,a=e=>void 0===e||""===e?"none":e,r=e=>new Map(Object.entries(e)),l=["id","type"];export class ChangeRecorder{_props;_context;_baseline;_isUnavailable=!0;_touches=new Map;_lastReset;_wasUndoneOrRedone=!1;constructor(e,t){this._props=e,this._context=t}reset=e=>{this.clear(e),this._isUnavailable=!0};record=i=>{if("reset"===i.kind){this._touches.clear(),this._lastReset=t(i)?"undo/redo":"reset",this._wasUndoneOrRedone||="undo/redo"===this._lastReset;return}for(let t of i.updates)e(t).with({kind:"createDomainEntity"},e=>{this._touchesOf(e.entityId).created=e}).with({kind:"deleteEntity"},e=>{let t=this._touchesOf(e.entityId);t.fields.clear(),t.deleted=e}).with({kind:"modifyDomainEntity"},e=>{this._touchFields(e.entityId,Object.keys(e.stateDelta),e)}).with({kind:"replaceDomainEntity"},e=>{let{replacementEntity:t}=e;this._touchesOf(e.entityId).fields.clear(),this._touchesOf(e.entityId).deleted=e,this._touchesOf(t.id).created=e}).with({kind:"createEphemeralRecord"},{kind:"modifyEphemeralRecord"},{kind:"deleteEphemeralRecord"},()=>{}).exhaustive()};take=e=>{let t=this._print(e);return this.clear(e),this._isUnavailable=!1,t};clear=e=>{this._baseline=e,this._touches.clear(),this._lastReset=void 0,this._wasUndoneOrRedone=!1};_touchesOf=e=>{let t=this._touches.get(e);if(t)return t;let i={created:void 0,deleted:void 0,fields:new Map};return this._touches.set(e,i),i};_touchFields=(e,t,i)=>{let s=this._touchesOf(e);for(let e of t)s.fields.set(e,i)};_print=e=>{let t=this._baseline;if(this._isUnavailable||!t)return"[changes: unavailable]";let{lines:i,count:s}=this._diffEntities(t,e);if(s>this._props.maxEntities)return`[changes: too many (${s})]`;let n=[...this._diffStates(t,e),...i];return 0===n.length?"[changes: none]":["[changes]",...this._wasUndoneOrRedone?["reset: undo/redo"]:[],...n].join("\n")};_diffStates=(e,t)=>s.flatMap(([i,s])=>{let n=a(this._context.readers[s](e)),r=a(this._context.readers[s](t));return n===r?[]:[`${i}: ${n} -> ${r}`]});_diffEntities=(e,t)=>{let i=this._context.getExposedFields(),s=new Map(e.entities.map(e=>[e.id,e])),n=new Set(t.entities.map(e=>e.id)),a=t.entities.flatMap(e=>{let t=i[e.type],n=s.get(e.id);if(!t)return[];if(!n)return[[`A ${e.id}${this._comment(this._touches.get(e.id)?.created)}`]];let a=n===e?[]:this._diffFields(n,e,t);return a.length>0?[[`M ${e.id}`,...a]]:[]}),r=e.entities.filter(e=>i[e.type]&&!n.has(e.id)).map(e=>[`D ${e.id}${this._comment(this._touches.get(e.id)?.deleted)}`]);return{lines:[...a,...r].flat(),count:a.length+r.length}};_diffFields=(e,t,s)=>{let a=r(e),d=r(t),o=this._touches.get(t.id);return Object.entries(s).flatMap(([e,{source:t,localized:s}])=>{if(!(!t.startsWith("$")&&!l.includes(t)))return[];let r=e=>{let t;return void 0===(t=s?i(e,this._context.resolveLocalizable):e)?"undefined":JSON.stringify(t)},h=r(a.get(t)),c=r(d.get(t));return h===c?[]:[` ${e}: ${n(h)} -> ${n(c)}${this._comment(o?.fields.get(t)??o?.created)}`]})};_comment=e=>e?` # ${this._explain(e).replace(/\s*\n\s*/g," ")}`:this._lastReset?` # ${this._lastReset}`:"";_explain=({agentHint:e,hint:t,updateTag:i})=>void 0!==e?null===e||""===e?i:e:t?this._context.resolveLocalizable(t):i}
@@ -6,7 +6,7 @@ import type { GraphQLSystem } from '../graphql-system/graphql-system.js';
6
6
  * that moment, never against ones captured when its reply began streaming.
7
7
  */
8
8
  export interface AssistantToolDependencies {
9
- readonly getGraphQLSystem: () => Pick<GraphQLSystem, 'prepare' | 'execute'>;
9
+ readonly getGraphQLSystem: () => Pick<GraphQLSystem, 'prepare' | 'execute' | 'readSideEffects'>;
10
10
  readonly getStoreSystem: () => {
11
11
  readonly isInitialized: boolean;
12
12
  readonly stateSlices: {
@@ -18,11 +18,14 @@ export interface AssistantToolDependencies {
18
18
  };
19
19
  };
20
20
  readonly getActiveMode: () => DomainMode;
21
+ /** Forgets the changes recorded for the next change record, so it never lists what the agent itself changed. */
22
+ readonly clearChanges: () => void;
21
23
  }
22
24
  /**
23
25
  * Browser implementation of the assistant's `query` tool: prepares the operations from the
24
26
  * committed state and drops their emissions, so mutations in the list show a hypothetical state and
25
- * the configuration, the undo stack and the saved revision stay as they were.
27
+ * the configuration, the undo stack and the saved revision stay as they were. The side effects of
28
+ * the dropped emissions are still reported, as what the changes would do.
26
29
  */
27
30
  export declare const createQueryClientTool: (dependencies: AssistantToolDependencies) => import("@tanstack/ai").ClientTool<{
28
31
  type: string;
@@ -88,7 +91,9 @@ export declare const createQueryClientTool: (dependencies: AssistantToolDependen
88
91
  /**
89
92
  * Browser implementation of the assistant's `apply` tool: hands the operations to
90
93
  * `GraphQLSystem.execute`, which commits their changes as one undo step, and returns its result,
91
- * including why nothing was committed when a commit was held or lost to a conflict. Only an owner
94
+ * including why nothing was committed when a commit was held or lost to a conflict. A commit clears
95
+ * the recorded changes; a held one does not, so it shows in the next change record once the user
96
+ * approves it. Only an owner
92
97
  * session may change the configuration; the check lives here and not in the `GraphQLSystem`, whose
93
98
  * other caller, the editor panel, has its own rules.
94
99
  */
@@ -1 +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
+ import{AssistantGraphQLToolInput as e,applyTool as t,queryTool as o}from"@salsita-ai/contracts/assistant";let a=e=>({results:[],committed:!1,message:e,sideEffects:[]}),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();if(!n.isInitialized)return 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.");let r=e.getGraphQLSystem(),l=await r.prepare(n.stateSlices.committed.value.state,o.operations);return i({results:l.map(({result:e})=>e),committed:!1,sideEffects:r.readSideEffects(l)})});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);if(!o.ok)return o.refusal;let n=await e.getGraphQLSystem().execute(o.operations);return n.committed&&e.clearChanges(),i(n)});
@@ -47,12 +47,14 @@ export declare const createEntityMeta: (source: EntityMetaSource, context: Entit
47
47
  root: null;
48
48
  changedEntities: never[];
49
49
  deletedEntityIds: never[];
50
+ sideEffects: never[];
50
51
  errors: readonly DryRunError[];
51
52
  } | {
52
53
  ok: boolean;
53
54
  root: unknown;
54
55
  changedEntities: {}[];
55
56
  deletedEntityIds: DomainEntityId<string>[];
57
+ sideEffects: readonly string[];
56
58
  errors: never[];
57
59
  } | null;
58
60
  }[];
@@ -71,12 +73,14 @@ export declare const createEntityMeta: (source: EntityMetaSource, context: Entit
71
73
  root: null;
72
74
  changedEntities: never[];
73
75
  deletedEntityIds: never[];
76
+ sideEffects: never[];
74
77
  errors: readonly DryRunError[];
75
78
  } | {
76
79
  ok: boolean;
77
80
  root: unknown;
78
81
  changedEntities: {}[];
79
82
  deletedEntityIds: DomainEntityId<string>[];
83
+ sideEffects: readonly string[];
80
84
  errors: never[];
81
85
  } | null;
82
86
  }[];
@@ -1 +1 @@
1
- import{findAssistantFieldOptions as e,findAssistantRecipeGroups as t,modifyEntityUpdateTag as i,prepareAssistantRecipeUpdates as r,readAssistantFieldOptions as n,readAssistantRecipeGroup as s,systemUpdateFactory as a}from"#package/domain";let o=e=>({ok:!1,root:null,changedEntities:[],deletedEntityIds:[],errors:e}),d=(e,{state:t},{recipes:i,prepareStateEmission:r,find$Entity:n})=>{let{validity:s,state:a}=r(e,t,"committed");if(s.valid){let e=new Map(t.entities.map(e=>[e.id,e])),i=new Set(a.entities.map(e=>e.id));return{ok:!0,root:n(a.rootEntityId,a),changedEntities:a.entities.filter(t=>e.get(t.id)!==t).flatMap(e=>n(e.id,a)??[]),deletedEntityIds:t.entities.map(e=>e.id).filter(e=>!i.has(e)),errors:[]}}return o("uncaught"===s.severity?[{type:"uncaught",entityId:null,message:s.error.message}]:s.entityViolations.filter(({violation:e})=>e.severity===s.severity).map(({entityId:e,violation:t})=>({type:t.type,entityId:e,message:void 0===t.message?null:i.resolveLocalizable(t.message)})))};export const createEntityMeta=(l,c)=>{let p=e=>()=>t(c.manifest,e,l.entity.type).flatMap(t=>{let i=s(e,t,l.entity.id,l.state,c.recipes);return i?[((e,t,i)=>{let{group:n,label:s,description:a,recipes:l}=e,{resolveLocalizable:c}=i.recipes;return{groupId:n.groupId,name:void 0===s?n.instanceName:c(s),description:n.description??(void 0===a?null:c(a)),recipes:l.map(n=>((e,t,i,n)=>{let{key:s,item:a}=e,{resolveLocalizable:l}=n.recipes;return{key:s,name:l(a.title),description:void 0===a.description?null:l(a.description),imageUrl:void 0===a.thumbnailUrl?null:l(a.thumbnailUrl),dryRun:()=>t.group.dryRuns?((e,t,i,n)=>{let{updates:s,error:a}=((e,t,{entity:i,state:n},{recipes:s})=>{try{return{updates:r(e,t,i.id,n,s),error:void 0}}catch(e){if("child"===t.target.kind)throw e;return{updates:void 0,error:e instanceof Error?e.message:String(e)}}})(e,t,i,n);return void 0===s?o([{type:"uncaught",entityId:null,message:a}]):d(s,i,n)})(e,t,i,n):null}})(n,e,t,i))}})(i,l,c)]:[]});return{...Object.fromEntries(e(c.manifest,l.entity.type).map(e=>[e.edgeName,()=>n(e,l.entity.id,l.state,c.recipes)?.map(t=>({...t,dryRun:()=>e.dryRuns?(({field:e},{value:t},r,n)=>{let{entity:s}=r,l=Object.entries(Object.entries(n.manifest.writableFields??{}).find(([e])=>e===s.type)?.[1]??{}).find(([t])=>t===e)?.[1];if(void 0===l)throw Error(`The options of "${e}" on "${s.id}" cannot be dry-run: the schema lists them, but the configurator has no writable field "${e}" on ${s.type}. Regenerate the application so the schema matches the configurator.`);let c=r.state.entities.find(e=>e.id===s.id),p={[l]:t},u=c?n.validateEntity({...c,...p}):{success:!0};return u.success?d([a.DomainEntityModification({entityId:s.id,stateDelta:p,updateTag:i})],r,n):o([{type:"uncaught",entityId:s.id,message:`Writing ${JSON.stringify(t)} to "${e}" would make "${s.id}" an invalid ${s.type}: ${u.errors.join("; ")}.${e===l?"":` The message names the stored property: ${e} is stored as ${l}.`} The option comes from the configurator and cannot be corrected from here, so do not write it.`}])})(e,t,l,c):null}))??null])),childRecipes:p("child"),replaceRecipes:p("replace")}};
1
+ import{findAssistantFieldOptions as e,findAssistantRecipeGroups as t,modifyEntityUpdateTag as i,prepareAssistantRecipeUpdates as r,readAssistantFieldOptions as n,readAssistantRecipeGroup as s,systemUpdateFactory as a}from"#package/domain";import{readSideEffects as o}from"./side-effects.js";let d=e=>({ok:!1,root:null,changedEntities:[],deletedEntityIds:[],sideEffects:[],errors:e}),l=(e,{state:t},{recipes:i,prepareStateEmission:r,find$Entity:n})=>{let{validity:s,state:a,updates:l}=r(e,t,"committed");if(s.valid){let e=new Map(t.entities.map(e=>[e.id,e])),r=new Set(a.entities.map(e=>e.id));return{ok:!0,root:n(a.rootEntityId,a),changedEntities:a.entities.filter(t=>e.get(t.id)!==t).flatMap(e=>n(e.id,a)??[]),deletedEntityIds:t.entities.map(e=>e.id).filter(e=>!r.has(e)),sideEffects:o(l,i.resolveLocalizable),errors:[]}}return d("uncaught"===s.severity?[{type:"uncaught",entityId:null,message:s.error.message}]:s.entityViolations.filter(({violation:e})=>e.severity===s.severity).map(({entityId:e,violation:t})=>({type:t.type,entityId:e,message:void 0===t.message?null:i.resolveLocalizable(t.message)})))};export const createEntityMeta=(o,c)=>{let p=e=>()=>t(c.manifest,e,o.entity.type).flatMap(t=>{let i=s(e,t,o.entity.id,o.state,c.recipes);return i?[((e,t,i)=>{let{group:n,label:s,description:a,recipes:o}=e,{resolveLocalizable:c}=i.recipes;return{groupId:n.groupId,name:void 0===s?n.instanceName:c(s),description:n.description??(void 0===a?null:c(a)),recipes:o.map(n=>((e,t,i,n)=>{let{key:s,item:a}=e,{resolveLocalizable:o}=n.recipes;return{key:s,name:o(a.title),description:void 0===a.description?null:o(a.description),imageUrl:void 0===a.thumbnailUrl?null:o(a.thumbnailUrl),dryRun:()=>t.group.dryRuns?((e,t,i,n)=>{let{updates:s,error:a}=((e,t,{entity:i,state:n},{recipes:s})=>{try{return{updates:r(e,t,i.id,n,s),error:void 0}}catch(e){if("child"===t.target.kind)throw e;return{updates:void 0,error:e instanceof Error?e.message:String(e)}}})(e,t,i,n);return void 0===s?d([{type:"uncaught",entityId:null,message:a}]):l(s,i,n)})(e,t,i,n):null}})(n,e,t,i))}})(i,o,c)]:[]});return{...Object.fromEntries(e(c.manifest,o.entity.type).map(e=>[e.edgeName,()=>n(e,o.entity.id,o.state,c.recipes)?.map(t=>({...t,dryRun:()=>e.dryRuns?(({field:e},{value:t},r,n)=>{let{entity:s}=r,o=Object.entries(Object.entries(n.manifest.writableFields??{}).find(([e])=>e===s.type)?.[1]??{}).find(([t])=>t===e)?.[1];if(void 0===o)throw Error(`The options of "${e}" on "${s.id}" cannot be dry-run: the schema lists them, but the configurator has no writable field "${e}" on ${s.type}. Regenerate the application so the schema matches the configurator.`);let c=r.state.entities.find(e=>e.id===s.id),p={[o]:t},u=c?n.validateEntity({...c,...p}):{success:!0};return u.success?l([a.DomainEntityModification({entityId:s.id,stateDelta:p,updateTag:i})],r,n):d([{type:"uncaught",entityId:s.id,message:`Writing ${JSON.stringify(t)} to "${e}" would make "${s.id}" an invalid ${s.type}: ${u.errors.join("; ")}.${e===o?"":` The message names the stored property: ${e} is stored as ${o}.`} The option comes from the configurator and cannot be corrected from here, so do not write it.`}])})(e,t,o,c):null}))??null])),childRecipes:p("child"),replaceRecipes:p("replace")}};
@@ -1,4 +1,5 @@
1
1
  import { type ExecutionResult } from 'graphql';
2
+ import { type Localizable } from '@salsita-ai/common/utils';
2
3
  import { type $DomainEntity, type DomainContextSelectors, type DomainEntity, type DomainServicesSelectors, type DomainState, type SpecSelectors, type StateUpdateEmission } from '#package/domain';
3
4
  /** One single-operation GraphQL document with its own variables, as executed by {@link GraphQLSystem}. */
4
5
  export interface GraphQLOperation {
@@ -26,13 +27,22 @@ export interface PreparedOperation {
26
27
  /**
27
28
  * What {@link GraphQLSystem.execute} returns: the results of the operations as prepared from the
28
29
  * committed state, whether their changes were committed as one undo step, and, when the operations
29
- * succeeded but their changes were not committed, the reason addressed to the caller.
30
+ * succeeded but their changes were not committed, the reason addressed to the caller. `sideEffects`
31
+ * describes the prepared changes whether or not they were committed, so a caller can weigh a held
32
+ * commit before the user approves it.
30
33
  */
31
34
  export interface GraphQLExecution {
32
35
  readonly results: readonly ExecutionResult[];
33
36
  readonly committed: boolean;
34
37
  readonly message?: string;
38
+ /** What the configurator did, or would do, beyond what the operations asked for, in applied order. */
39
+ readonly sideEffects: readonly string[];
35
40
  }
41
+ /**
42
+ * Resolves a localizable value, or each item of a list of them, to a string in the current locale.
43
+ * `null` and values that are not localizable pass through, so the schema's nullability decides.
44
+ */
45
+ export declare const localize: (value: unknown, resolveLocalizable: (message: Localizable) => string) => unknown;
36
46
  /**
37
47
  * Executes GraphQL operations against the schema generated from the application spec `assistant`
38
48
  * manifest, resolving it against the committed domain state. Agent-independent: the assistant's
@@ -75,6 +85,11 @@ export declare class GraphQLSystem {
75
85
  * "not run" error instead.
76
86
  */
77
87
  prepare: (originalState: AnyDomainState, operations: readonly GraphQLOperation[]) => Promise<readonly PreparedOperation[]>;
88
+ /**
89
+ * The side effects of prepared operations: the hints of every update of their emissions, as the
90
+ * agent is told them, in applied order.
91
+ */
92
+ readSideEffects: (prepared: readonly PreparedOperation[]) => readonly string[];
78
93
  private readonly _prepareAndCommit;
79
94
  /**
80
95
  * Prepares the operations from the committed state and commits their changes as one emission,