@salsita-ai/sdk 0.50.0-develop.db8514eccf → 0.50.0-develop.dbf0122072
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.
- package/dist/{phoenix/application-spec → application-spec/assistant}/generate-assistant-prompt.d.ts +2 -2
- package/dist/{phoenix/application-spec → application-spec/assistant}/generate-assistant-prompt.js +1 -1
- package/dist/application-spec/assistant/index.d.ts +1 -0
- package/dist/application-spec/assistant/index.js +1 -0
- package/dist/application-spec/generate-application/code/templates/domain-spec/generate-assistant.d.ts +2 -2
- package/dist/application-spec/generate-application/code/templates/domain-spec/generate-assistant.js +1 -1
- package/dist/application-spec/generate-application/code/templates/domain-spec.js +4 -4
- package/dist/application-spec/generate-application/runtime/sections/assistant-runtime.d.ts +4 -3
- package/dist/application-spec/generate-application/runtime/sections/assistant-runtime.js +1 -1
- package/dist/application-spec/index.d.ts +1 -0
- package/dist/application-spec/index.js +1 -1
- package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-field-type.d.ts +3 -8
- package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-field-type.js +1 -1
- package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.d.ts +9 -43
- package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.js +1 -1
- package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-server-settings.d.ts +1 -1
- package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant.d.ts +5 -21
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.d.ts +15 -3
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.js +1 -1
- package/dist/configurator/ui/assistant/AssistantChips.js +1 -1
- package/dist/configurator/ui/assistant/tool-chip.d.ts +8 -1
- package/dist/configurator/ui/assistant/tool-chip.js +1 -1
- package/dist/docs/index.json +1 -1
- package/dist/domain/application/application-config.d.ts +2 -62
- package/dist/domain/application/assistant/assistant-manifest.d.ts +61 -0
- package/dist/domain/application/assistant/assistant-manifest.js +1 -0
- package/dist/domain/application/assistant/assistant-resolved-manifest.d.ts +95 -0
- package/dist/domain/application/assistant/assistant-resolved-manifest.js +1 -0
- package/dist/domain/application/assistant/assistant-value-type.d.ts +9 -0
- package/dist/domain/application/assistant/assistant-value-type.js +1 -0
- package/dist/domain/application/assistant/build-assistant-manifest.d.ts +4 -0
- package/dist/domain/application/assistant/build-assistant-manifest.js +1 -0
- package/dist/domain/application/assistant/index.d.ts +3 -0
- package/dist/domain/application/assistant/index.js +1 -0
- package/dist/domain/application/assistant-field-options.d.ts +1 -1
- package/dist/domain/application/assistant-mutations.d.ts +1 -1
- package/dist/domain/application/assistant-recipe-groups.d.ts +1 -1
- package/dist/domain/application/configurator-builder.d.ts +4 -3
- package/dist/domain/application/index.d.ts +2 -1
- package/dist/domain/application/index.js +1 -1
- package/dist/domain/domain-runtime/domain-runtime.d.ts +4 -4
- package/dist/domain/domain-runtime/spec/selectors.d.ts +2 -2
- package/dist/domain/domain-runtime/spec/selectors.js +1 -1
- package/dist/domain/domain-runtime/spec/types.d.ts +3 -3
- package/dist/domain/mocks/create-mock-domain-runtime.d.ts +2 -2
- package/dist/i18n/locales/cs/messages.js +1 -1
- package/dist/i18n/locales/da/messages.js +1 -1
- package/dist/i18n/locales/de/messages.js +1 -1
- package/dist/i18n/locales/de-AT/messages.js +1 -1
- package/dist/i18n/locales/en/messages.js +1 -1
- package/dist/i18n/locales/en-AU/messages.js +1 -1
- package/dist/i18n/locales/en-GB/messages.js +1 -1
- package/dist/i18n/locales/es/messages.js +1 -1
- package/dist/i18n/locales/fr/messages.js +1 -1
- package/dist/i18n/locales/hu/messages.js +1 -1
- package/dist/i18n/locales/it/messages.js +1 -1
- package/dist/i18n/locales/nl/messages.js +1 -1
- package/dist/i18n/locales/pl/messages.js +1 -1
- package/dist/i18n/locales/pt/messages.js +1 -1
- package/dist/i18n/locales/ro/messages.js +1 -1
- package/dist/i18n/locales/sk/messages.js +1 -1
- package/dist/i18n/locales/tr/messages.js +1 -1
- package/dist/phoenix/application-spec/resolve-deployment-data.js +2 -2
- package/dist/phoenix/services/variant-file-session.js +1 -1
- package/dist/react-sdk/application-runtime/hooks/use-spec.d.ts +1 -1
- package/dist/react-sdk/application-runtime/runtime/create-application-runtime.d.ts +4 -4
- package/package.json +3 -3
package/dist/{phoenix/application-spec → application-spec/assistant}/generate-assistant-prompt.d.ts
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { AssistantManifest } from '#package/domain';
|
|
2
2
|
/**
|
|
3
3
|
* The part of the assistant's system prompt that explains how to read the generated GraphQL schema.
|
|
4
4
|
* It is generated here, by the SDK that also runs in the browser, and stored with the deployment,
|
|
@@ -10,4 +10,4 @@ import type { AssistantSpec } from '#package/application-spec';
|
|
|
10
10
|
* `query` and `apply` tools, which every run registers whatever the schema holds, and the change
|
|
11
11
|
* record the `AssistantSystem` attaches to every user message.
|
|
12
12
|
*/
|
|
13
|
-
export declare const generateAssistantPrompt: (assistant:
|
|
13
|
+
export declare const generateAssistantPrompt: (assistant: AssistantManifest) => string;
|
package/dist/{phoenix/application-spec → application-spec/assistant}/generate-assistant-prompt.js
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
let e=["How to read the GraphQL schema of this configurator:","- A configuration is a set of entities. `root` is the root entity, `entities` lists every entity or the ones with the given ids, and `selectedEntity` is the entity the user has selected, or the root entity when nothing is selected.","- Every entity has an `id` of the form `<Type>-<number>`, for example `Table-1`, and a `type` with its entity type name. Ids are assigned by the configurator: read them from the configuration and never make one up.","- A field whose name starts with `_` is computed by the configurator from other values. It can be read like any other field and never written.","- Numbers are in the units the configuration stores them in. A field description names the unit when the product defines one.",'- A text field that only takes fixed values lists them in its description as "One of: ...". Use exactly those values.',"- A field typed as another entity type or as a list of one is a relation: select fields on it to read the related entities.","- Field and type descriptions come from the team that built the configurator and say what a value means for the product."],t=["How changes work:","- Every field of the `Mutation` type is one change. Its description says what it changes and what it returns.","- The configurator checks the whole configuration after each change. A change that would leave it invalid fails with an error that names the entities at fault, and it is not applied. Later changes of the same request are then not run.","- The configurator may adjust other values in response to a change, so read what a mutation returns instead of assuming the values you sent."],a=["How to add entities:","- Entities are added from recipes, the same ones the configurator offers the user. An entity type that can take children has a `meta` field; `meta { childRecipes }` lists its recipe groups and their recipes.","- List the recipes of the group first, pick one by its `key`, then call `addChild` with the id of the parent, the `groupId` and the `key`. Keys change with the configuration and the language, so never reuse one from memory.","- `dryRun` on a recipe shows what adding it would do without adding it: whether it is `ok`, the `changedEntities` it would add or modify, the `deletedEntityIds` it would remove, the `sideEffects` the configurator says it would have, and the `errors` when it cannot be added. An entity whose id the configuration does not have yet is new. It is costly, so select it only on the recipes you are deciding between.","- Put each `addChild` in its own operation. The recipes of a group and what they add depend on the configuration before them, so after adding something, list the group again before adding from it once more."],n=["How to replace entities:","- An entity is replaced from recipes, the same ones the configurator offers the user. An entity type that can be replaced has a `meta` field; `meta { replaceRecipes }` lists its replace recipe groups and what the entity can be replaced with.","- List the recipes of the group first, pick one by its `key`, then call `replaceEntity` with the id of the entity, the `groupId` and the `key`. `dryRun` on a replace recipe shows what replacing would do without doing it: the replacement and everything else that changes are under `changedEntities`, and the replaced entity is among the `deletedEntityIds`.","- The replacement is a new entity with a new id, and its field values come from the recipe, so they can differ from those of the entity it replaces. Read the ids and values `replaceEntity` returns, and never use the old id again.","- Put each `replaceEntity` in its own operation. The recipes of a group and what they do depend on the configuration before them, so after replacing something, list the group of the replacement again before replacing once more."],o=["How to find the values a field can take:","- Some fields store a key whose choices the configurator holds elsewhere. Such a field has an edge under `meta` named after it: `meta { <field>Options }` lists its choices, each with the `value` to write and the `name` the user sees.","- Read the choices before you write such a field or name a choice to the user, and write the `value`, not the `name`. A value outside the list is rejected unless the edge description says the field is not checked.","- `dryRun` on an option shows what writing its value would do without writing it: whether it is `ok`, the `changedEntities` it would add or modify, the `deletedEntityIds` it would remove, the `sideEffects` the configurator says it would have, and the `errors` when the value cannot be written. It is costly, so select it only on the options you are deciding between. It is null when the edge description says the options cannot be dry-run.","- The choices can depend on the entity and on its current state. Read them again after a change, unless the edge description says they are the same for all instances or do not change."],i=["How the custom changes of this configurator work:","- Besides the generic changes, the `Mutation` type has fields the team built for this product. Each runs one domain operation the configurator itself uses, so prefer it over composing the same change from generic mutations. Its description says what it does and what its arguments mean.","- Its arguments are checked against what the operation declares; an argument that does not fit, or a change the product does not allow, fails the field with a message that says what to send instead.","- It returns an object whose fields the description names; a field typed as an entity reads that entity after the change."],s=["How to use the `query` and `apply` tools:","- Both take `operations`, a list of GraphQL documents that run in order. Each document holds exactly one operation. To do several things, send several items in one call instead of several calls.","- Write values into the document as literals. Use `variables` only for a value that cannot be written as a literal.","- Select only the fields you need: results are returned whole.","- The result has one GraphQL result per operation, in the order sent. When an operation fails, its `errors` say why and the operations after it are not run.","- `query` reads the configuration the user has open and never changes it. Call it before you say anything about the configuration."],h=["- This configurator exposes no changes, so there is nothing for `apply` to run. Say so when the user asks you to change the configuration."],r=['- Mutations inside `query` answer "what if" questions. Each operation sees the changes of the ones before it, so a mutation followed by a query shows the configuration as it would be. Nothing is kept and the user sees no change.',"- `apply` makes the changes the user asked for. It is all or nothing: when any operation fails, nothing is changed; when all succeed, the user gets them as one undo step.","- `committed` in the result says whether the changes were kept. When it is false although no operation failed, `message` says why: the changes may be waiting for the approval of the user, the user may have changed the configuration meanwhile, or this session may not change the configuration at all. Without a `message`, the operations changed nothing. Never tell the user a change was made unless `committed` is true.","- `sideEffects` in the result lists what the configurator did beyond what the operations asked for, such as parts it added or replaced to keep the configuration valid, in its own words. Tell the user about them when the changes were kept. When they were not, or in `query`, it lists what the mutations that succeeded would do. `dryRun` has the same list for a single recipe or option."],d=["How to read the change record:","- Every user message starts with a change record of the configuration since your previous action. It is the complete list of the entities that were added or deleted, of the stored fields of this schema that changed, and of the selection and navigation changes, so update your picture from it and do not query those again when it does not mention them.","- Fields whose name starts with `_` are computed and are never listed. Read them again when the record lists a change they may depend on.","- `[changes: none]`: nothing changed. Do not query again what you already know.","- `[changes]` is followed by one line per change. `selected`, `navigationState`, `viewState` and `toolState` lines show `<old> -> <new>` of what `selectedEntity` and `navigation` return, with `none` for an empty value. `A <id>` is an added entity and `D <id>` a deleted one. `M <id>` is a modified entity, followed by one `<field>: <old> -> <new>` line per changed field, under the name the field has in this schema. A `reset: undo/redo` line says the user undid or redid changes.","- The `#` comment at the end of a line names the control, the transformer or the explanation of the last change to that line.","- `[changes: unavailable]`: the page was loaded since your previous action, so earlier values may be stale. `[changes: too many (n)]`: n entities changed and are not listed. In both cases query what you need."],c=["- Changes you applied are not in the record, except those that were waiting for the approval of the user: they appear in it once approved."];export const generateAssistantPrompt=l=>{let u=/^type Mutation\b/m.test(l.sdl);return[e,...u?[t]:[],.../^\s+addChild\(/m.test(l.sdl)?[a]:[],.../^\s+replaceEntity\(/m.test(l.sdl)?[n]:[],.../^type FieldOption\b/m.test(l.sdl)?[o]:[],...Object.keys(l.actions).length>0?[i]:[],[...s,...u?r:h],[...d,...u?c:[]]].map(e=>e.join("\n")).join("\n\n")};
|
|
1
|
+
let e=["How to read the GraphQL schema of this configurator:","- A configuration is a set of entities. `root` is the root entity, `entities` lists every entity or the ones with the given ids, and `selectedEntity` is the entity the user has selected, or the root entity when nothing is selected.","- Every entity has an `id` of the form `<Type>-<number>`, for example `Table-1`, and a `type` with its entity type name. Ids are assigned by the configurator: read them from the configuration and never make one up.","- A field whose name starts with `_` is computed by the configurator from other values. It can be read like any other field and never written.","- Numbers are in the units the configuration stores them in. A field description names the unit when the product defines one.",'- A text field that only takes fixed values lists them in its description as "One of: ...". Use exactly those values.',"- A field typed as another entity type or as a list of one is a relation: select fields on it to read the related entities.","- Field and type descriptions come from the team that built the configurator and say what a value means for the product."],t=["How changes work:","- Every field of the `Mutation` type is one change. Its description says what it changes and what it returns.","- The configurator checks the whole configuration after each change. A change that would leave it invalid fails with an error that names the entities at fault, and it is not applied. Later changes of the same request are then not run.","- The configurator may adjust other values in response to a change, so read what a mutation returns instead of assuming the values you sent."],a=["How to add entities:","- Entities are added from recipes, the same ones the configurator offers the user. An entity type that can take children has a `meta` field; `meta { childRecipes }` lists its recipe groups and their recipes.","- List the recipes of the group first, pick one by its `key`, then call `addChild` with the id of the parent, the `groupId` and the `key`. Keys change with the configuration and the language, so never reuse one from memory.","- `dryRun` on a recipe shows what adding it would do without adding it: whether it is `ok`, the `changedEntities` it would add or modify, the `deletedEntityIds` it would remove, the `sideEffects` the configurator says it would have, and the `errors` when it cannot be added. An entity whose id the configuration does not have yet is new. It is costly, so select it only on the recipes you are deciding between.","- Put each `addChild` in its own operation. The recipes of a group and what they add depend on the configuration before them, so after adding something, list the group again before adding from it once more."],n=["How to replace entities:","- An entity is replaced from recipes, the same ones the configurator offers the user. An entity type that can be replaced has a `meta` field; `meta { replaceRecipes }` lists its replace recipe groups and what the entity can be replaced with.","- List the recipes of the group first, pick one by its `key`, then call `replaceEntity` with the id of the entity, the `groupId` and the `key`. `dryRun` on a replace recipe shows what replacing would do without doing it: the replacement and everything else that changes are under `changedEntities`, and the replaced entity is among the `deletedEntityIds`.","- The replacement is a new entity with a new id, and its field values come from the recipe, so they can differ from those of the entity it replaces. Read the ids and values `replaceEntity` returns, and never use the old id again.","- Put each `replaceEntity` in its own operation. The recipes of a group and what they do depend on the configuration before them, so after replacing something, list the group of the replacement again before replacing once more."],o=["How to find the values a field can take:","- Some fields store a key whose choices the configurator holds elsewhere. Such a field has an edge under `meta` named after it: `meta { <field>Options }` lists its choices, each with the `value` to write and the `name` the user sees.","- Read the choices before you write such a field or name a choice to the user, and write the `value`, not the `name`. A value outside the list is rejected unless the edge description says the field is not checked.","- `dryRun` on an option shows what writing its value would do without writing it: whether it is `ok`, the `changedEntities` it would add or modify, the `deletedEntityIds` it would remove, the `sideEffects` the configurator says it would have, and the `errors` when the value cannot be written. It is costly, so select it only on the options you are deciding between. It is null when the edge description says the options cannot be dry-run.","- The choices can depend on the entity and on its current state. Read them again after a change, unless the edge description says they are the same for all instances or do not change."],i=["How the custom changes of this configurator work:","- Besides the generic changes, the `Mutation` type has fields the team built for this product. Each runs one domain operation the configurator itself uses, so prefer it over composing the same change from generic mutations. Its description says what it does and what its arguments mean.","- Its arguments are checked against what the operation declares; an argument that does not fit, or a change the product does not allow, fails the field with a message that says what to send instead.","- It returns an object whose fields the description names; a field typed as an entity reads that entity after the change."],s=["How to use the `query` and `apply` tools:","- Both take `operations`, a list of GraphQL documents that run in order. Each document holds exactly one operation. To do several things, send several items in one call instead of several calls.","- Write values into the document as literals. Use `variables` only for a value that cannot be written as a literal.","- Select only the fields you need: results are returned whole.","- The result has one GraphQL result per operation, in the order sent. When an operation fails, its `errors` say why and the operations after it are not run.","- `query` reads the configuration the user has open and never changes it. Call it before you say anything about the configuration."],h=["- This configurator exposes no changes, so there is nothing for `apply` to run. Say so when the user asks you to change the configuration."],r=['- Mutations inside `query` answer "what if" questions. Each operation sees the changes of the ones before it, so a mutation followed by a query shows the configuration as it would be. Nothing is kept and the user sees no change.',"- `apply` makes the changes the user asked for. It is all or nothing: when any operation fails, nothing is changed; when all succeed, the user gets them as one undo step.","- `committed` in the result says whether the changes were kept. When it is false although no operation failed, `message` says why: the changes may be waiting for the approval of the user, the user may have changed the configuration meanwhile, or this session may not change the configuration at all. Without a `message`, the operations changed nothing. Never tell the user a change was made unless `committed` is true.","- `sideEffects` in the result lists what the configurator did beyond what the operations asked for, such as parts it added or replaced to keep the configuration valid, in its own words. Tell the user about them when the changes were kept. When they were not, or in `query`, it lists what the mutations that succeeded would do. `dryRun` has the same list for a single recipe or option."],d=["How to read the change record:","- Every user message starts with a change record of the configuration since your previous action. It is the complete list of the entities that were added or deleted, of the stored fields of this schema that changed, and of the selection and navigation changes, so update your picture from it and do not query those again when it does not mention them.","- Fields whose name starts with `_` are computed and are never listed. Read them again when the record lists a change they may depend on.","- `[changes: none]`: nothing changed. Do not query again what you already know.","- `[changes]` is followed by one line per change. `selected`, `navigationState`, `viewState` and `toolState` lines show `<old> -> <new>` of what `selectedEntity` and `navigation` return, with `none` for an empty value. `A <id>` is an added entity and `D <id>` a deleted one. `M <id>` is a modified entity, followed by one `<field>: <old> -> <new>` line per changed field, under the name the field has in this schema. A `reset: undo/redo` line says the user undid or redid changes.","- The `#` comment at the end of a line names the control, the transformer or the explanation of the last change to that line.","- `[changes: unavailable]`: the page was loaded since your previous action, so earlier values may be stale. `[changes: too many (n)]`: n entities changed and are not listed. In both cases query what you need."],c=["- Changes you applied are not in the record, except those that were waiting for the approval of the user: they appear in it once approved."];export const generateAssistantPrompt=l=>{let u=/^type Mutation\b/m.test(l.sdl);return[e,...u?[t]:[],.../^\s+addChild\(/m.test(l.sdl)?[a]:[],.../^\s+replaceEntity\(/m.test(l.sdl)?[n]:[],.../^type FieldOption\b/m.test(l.sdl)?[o]:[],...Object.keys(l.actions??{}).length>0?[i]:[],[...s,...u?r:h],[...d,...u?c:[]]].map(e=>e.join("\n")).join("\n\n")};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { generateAssistantPrompt } from './generate-assistant-prompt.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{generateAssistantPrompt}from"./generate-assistant-prompt.js";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { AssistantSpec } from '../../../../parse-application-files/index.js';
|
|
2
2
|
/**
|
|
3
|
-
* Emits the `$assistant` constant handed to `baseConfiguratorBuilder.withAssistant()`: the
|
|
4
|
-
*
|
|
3
|
+
* Emits the `$assistant` constant handed to `baseConfiguratorBuilder.withAssistant()`: the resolved
|
|
4
|
+
* JSON manifest, or `null` when the spec declares no `assistant` section.
|
|
5
5
|
*/
|
|
6
6
|
export declare const generateAssistantBlock: (assistant: AssistantSpec) => string;
|
package/dist/application-spec/generate-application/code/templates/domain-spec/generate-assistant.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const generateAssistantBlock=s=>`const $assistant:
|
|
1
|
+
export const generateAssistantBlock=s=>`const $assistant: AssistantResolvedManifest | null = ${JSON.stringify(s?.resolved??null,null,2)}`;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{CodeImports as e,autoHeader as a,skipApplicationTypeImports as i}from"../common/index.js";import{generateApplicationMetadataBlock as o,generateAssistantBlock as n,generateBaseConfiguratorBuilder as t,generateChunksSpec as s,generateDataSchemaConstants as r,generateDataSpec as p,generateDomainBlock as m,generateLocaleCodegen as d,generatePhxGlobalsBlock as c,generateResourcesCodegen as l,generateStateConstants as u}from"./domain-spec/index.js";let x="@salsita-ai/sdk/domain",g="@salsita-ai/sdk/i18n";export const globalDomainSpecPhxBinding={generateBindingBlock:c,generateStateConstants:u,registerApplicationTypeImports:i};export const generateApplicationSpecDomainSpecFile=(i,c=globalDomainSpecPhxBinding)=>{let u=new e,{registerApplicationTypeImports:f}=c,E=m({domainSpec:i.configurator,invariants:i.configurator.invariants,actions:i.configurator.actions,typePrefix:"",versionNsPrefix:"ModelV",isAdmin:!1,modelVersionsExportName:"modelVersions",relationExpressionsExportName:"relationExpressions",componentOpticsExportName:"componentOptics",valueExpressionsExportName:"valueExpressions",createRecipeExportName:"createRecipe",imports:u,registerApplicationTypeImports:f}),S=m({domainSpec:i.admin,invariants:i.admin.invariants,actions:void 0,typePrefix:"Admin",versionNsPrefix:"AdminV",isAdmin:!0,modelVersionsExportName:"adminModelVersions",relationExpressionsExportName:"adminRelationExpressions",componentOpticsExportName:"adminComponentOptics",valueExpressionsExportName:"adminValueExpressions",createRecipeExportName:"createAdminRecipe",imports:u,registerApplicationTypeImports:f}),{hasResources:$}=l(i);u.addImport(x,"ConfiguratorBuilder"),u.addImport(x,"EnumReflection"),u.addTypeImport(x,"
|
|
1
|
+
import{CodeImports as e,autoHeader as a,skipApplicationTypeImports as i}from"../common/index.js";import{generateApplicationMetadataBlock as o,generateAssistantBlock as n,generateBaseConfiguratorBuilder as t,generateChunksSpec as s,generateDataSchemaConstants as r,generateDataSpec as p,generateDomainBlock as m,generateLocaleCodegen as d,generatePhxGlobalsBlock as c,generateResourcesCodegen as l,generateStateConstants as u}from"./domain-spec/index.js";let x="@salsita-ai/sdk/domain",g="@salsita-ai/sdk/i18n";export const globalDomainSpecPhxBinding={generateBindingBlock:c,generateStateConstants:u,registerApplicationTypeImports:i};export const generateApplicationSpecDomainSpecFile=(i,c=globalDomainSpecPhxBinding)=>{let u=new e,{registerApplicationTypeImports:f}=c,E=m({domainSpec:i.configurator,invariants:i.configurator.invariants,actions:i.configurator.actions,typePrefix:"",versionNsPrefix:"ModelV",isAdmin:!1,modelVersionsExportName:"modelVersions",relationExpressionsExportName:"relationExpressions",componentOpticsExportName:"componentOptics",valueExpressionsExportName:"valueExpressions",createRecipeExportName:"createRecipe",imports:u,registerApplicationTypeImports:f}),S=m({domainSpec:i.admin,invariants:i.admin.invariants,actions:void 0,typePrefix:"Admin",versionNsPrefix:"AdminV",isAdmin:!0,modelVersionsExportName:"adminModelVersions",relationExpressionsExportName:"adminRelationExpressions",componentOpticsExportName:"adminComponentOptics",valueExpressionsExportName:"adminValueExpressions",createRecipeExportName:"createAdminRecipe",imports:u,registerApplicationTypeImports:f}),{hasResources:$}=l(i);u.addImport(x,"ConfiguratorBuilder"),u.addImport(x,"EnumReflection"),u.addTypeImport(x,"AssistantResolvedManifest"),u.addTypeImport(x,"ChunksSpec"),u.addTypeImport(x,"DataSpec"),u.addTypeImport(x,"EnumLike"),$&&u.addImport(x,"ResourceBuilder"),u.addImport(g,"mergeCatalogs"),u.addImport(g,"sdkCatalog"),u.addImport("@lingui/core","setupI18n");let v=r(i.configurator.dataSchemas,u,f),k=c.generateStateConstants({configuratorStates:i.configurator.states,adminStates:i.admin.states},u,f),I=o(i),{importBlock:N,catalogBlock:h,createI18nExport:A}=d(i.configurator.ui.availableLocales),{preBlock:B,builderBlock:C}=t(i,u,f),R=c.generateBindingBlock();return`${a("domain-spec.ts","Domain builders, model schemas, component optics and expression definitions derived from the spec.")}
|
|
2
2
|
${u.toString()}${N}
|
|
3
3
|
|
|
4
4
|
// ---- Data schemas ----
|
|
5
5
|
|
|
6
|
-
${
|
|
6
|
+
${v}
|
|
7
7
|
|
|
8
8
|
// ---- Admin domain ----
|
|
9
9
|
|
|
@@ -25,7 +25,7 @@ ${I}
|
|
|
25
25
|
|
|
26
26
|
// ---- State enums ----
|
|
27
27
|
|
|
28
|
-
${
|
|
28
|
+
${k}
|
|
29
29
|
|
|
30
30
|
const $dataSpec: DataSpec = ${p(i.dataSpec.entries)}
|
|
31
31
|
|
|
@@ -35,4 +35,4 @@ ${n(i.configurator.assistant)}
|
|
|
35
35
|
${B}
|
|
36
36
|
${C}
|
|
37
37
|
|
|
38
|
-
${
|
|
38
|
+
${R}`};
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { Branded } from '@salsita-ai/common/utils';
|
|
2
|
+
import type { AssistantResolvedManifest } from '#package/domain';
|
|
2
3
|
import type { RuntimeReferenceStore } from '../../../caching/index.js';
|
|
3
|
-
import type { ApplicationSpec
|
|
4
|
-
/**
|
|
4
|
+
import type { ApplicationSpec } from '../../../parse-application-files/index.js';
|
|
5
|
+
/** Resolved assistant manifest with change tracking, carried to the runtime spec on hot reload. */
|
|
5
6
|
export type AssistantRuntime = Branded<'AssistantRuntime', {
|
|
6
|
-
readonly assistant:
|
|
7
|
+
readonly assistant: AssistantResolvedManifest | null;
|
|
7
8
|
readonly changed: boolean;
|
|
8
9
|
}>;
|
|
9
10
|
export declare const AssistantRuntime: (spec: ApplicationSpec, referenceStore: RuntimeReferenceStore) => AssistantRuntime;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import s from"lodash-es/isEqual.js";import{Branded as t}from"@salsita-ai/common/utils";export const AssistantRuntime=(a,i)=>{let
|
|
1
|
+
import s from"lodash-es/isEqual.js";import{Branded as t}from"@salsita-ai/common/utils";export const AssistantRuntime=(a,i)=>{let e=i.createBuilder("assistant",{build:s=>s,getKey:()=>"assistant",compare:(t,a)=>s(t,a)}).build({assistant:a.configurator.assistant?.resolved??null});return t({assistant:e.output.assistant,changed:e.changed})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./core/index.js";export*from"./caching/index.js";export*from"./errors/index.js";export*from"./generate-application/index.js";export*from"./parse-application-files/index.js";export*from"./webhook-boundary.js";
|
|
1
|
+
export*from"./core/index.js";export*from"./caching/index.js";export*from"./errors/index.js";export*from"./generate-application/index.js";export*from"./parse-application-files/index.js";export*from"./webhook-boundary.js";export*from"./assistant/index.js";
|
|
@@ -1,18 +1,13 @@
|
|
|
1
|
-
import
|
|
1
|
+
import type { AssistantValueType } from '#package/domain';
|
|
2
2
|
import { type EnhancedJsonSchemaType } from '../../../../core/index.js';
|
|
3
3
|
import { type SchemaRefResolver } from '../../common/index.js';
|
|
4
|
-
/**
|
|
5
|
-
* Opaque scalar for values the assistant schema does not type: objects, custom TypeScript types and
|
|
6
|
-
* loose unions. A value is plain serializable data and passes through unchanged.
|
|
7
|
-
*/
|
|
8
|
-
export declare const GraphQLJSON: GraphQLScalarType<unknown, unknown>;
|
|
9
4
|
/**
|
|
10
5
|
* The GraphQL type of one whitelisted stored field or declared expression. `enumValues` lists the
|
|
11
6
|
* allowed values of a string enum, which the schema exposes as `String` and names in the field
|
|
12
7
|
* description.
|
|
13
8
|
*/
|
|
14
9
|
export interface AssistantFieldType {
|
|
15
|
-
readonly type:
|
|
10
|
+
readonly type: AssistantValueType;
|
|
16
11
|
readonly enumValues?: readonly string[];
|
|
17
12
|
/**
|
|
18
13
|
* The schema's own description, or without one that of the common type it references, directly or
|
|
@@ -30,4 +25,4 @@ export interface AssistantFieldType {
|
|
|
30
25
|
* `String` with their values, primitives → scalars, arrays of mappable items → lists, and everything
|
|
31
26
|
* else → `JSON`. Every type, `JSON` included, is non-null unless the schema admits `null`.
|
|
32
27
|
*/
|
|
33
|
-
export declare const
|
|
28
|
+
export declare const resolveAssistantFieldType: (schema: EnhancedJsonSchemaType, resolveRef: SchemaRefResolver) => AssistantFieldType;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isArray as e}from"@salsita-ai/common/utils";import{extractPhxDefName as n}from"../../../../core/index.js";import{commonTypeRefName as t,isNullableSchema as l,phxDefinitionRefName as r}from"../../common/index.js";let i={number:{kind:"scalar",name:"Float",nonNull:!1},integer:{kind:"scalar",name:"Int",nonNull:!1},string:{kind:"scalar",name:"String",nonNull:!1},boolean:{kind:"scalar",name:"Boolean",nonNull:!1}},a={kind:"scalar",name:"String",nonNull:!1},o={kind:"scalar",name:"ID",nonNull:!1},u=new Set(["Localizable","EnhancedLocalizable","MessageDescriptor","EnhancedMessageDescriptor","MultilingualString"]),s={type:{kind:"scalar",name:"JSON",nonNull:!1}},d=({anyOf:e,oneOf:n})=>[...e??[],...n??[]].filter(e=>"null"!==e.type),f=e=>"scalar"===e.kind?"JSON"===e.name:f(e.item),p=(l,y,c)=>{let v;if(void 0!==(v=void 0===l.$ref?void 0:r(l.$ref))&&u.has(v))return{type:a,localized:!0};if(l.tsType)return s;if(l.$ref){var g=l.$ref;if("DomainEntityId"===n(g))return{type:o};let e=t(g),r=void 0===e||c.has(e)?void 0:y(g);return void 0!==e&&r?p(r,y,new Set([...c,e])):s}if(l.anyOf||l.oneOf)return((e,n,t)=>{let l=d(e).map(e=>p(e,n,t)),[r]=l;if(1===l.length&&r)return r;let i=l.flatMap(({type:e,enumValues:n})=>e===a&&n?[n]:[]);if(l.length<2||i.length!==l.length||e.anyOf&&e.oneOf)return s;let o=i.flatMap(e=>[...new Set(e)]);return{type:a,enumValues:e.oneOf?o.filter(e=>o.indexOf(e)===o.lastIndexOf(e)):[...new Set(o)]}})(l,y,c);if(l.enum){let e;return(e=l.enum.filter(e=>null!==e)).every(e=>"string"==typeof e)?{type:a,enumValues:e}:s}if(e(l.type)){let e=l.type.filter(e=>"null"!==e),[n]=e;return 1===e.length&&n?p({...l,type:n},y,c):s}if("array"===l.type){var S=l.items;if(!S||e(S))return s;let n=m(S,y,c);return f(n.type)?s:{type:{kind:"list",item:n.type,nonNull:!1},enumValues:n.enumValues,localized:n.localized}}let h="string"==typeof l.type?i[l.type]:void 0;return h?{type:h}:s},m=(e,n,t)=>{let r=p(e,n,t);return{...r,type:{...r.type,nonNull:!l(e,n)}}},y=e=>{let n=d(e);return e.$ref??(1===n.length?n[0]?.$ref:void 0)},c=(e,n,l)=>{let r=t(e),i=void 0===r||l.has(r)?void 0:n(e);if(void 0===r||!i)return;let a=y(i);return void 0===i.description&&a?c(a,n,new Set([...l,r])):i.description};export const resolveAssistantFieldType=(e,n)=>{let t=y(e),l=void 0===e.description&&t?c(t,n,new Set):e.description;return{...m(e,n,new Set),...void 0===l?{}:{description:l}}};
|
package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { type AssistantFieldSource, type AssistantManifest, type AssistantRecipeGroup, type AssistantResolvedManifest, type AssistantStates } from '#package/domain';
|
|
2
2
|
import type { ParseContext, PhoenixDefinitions } from '../../../../core/index.js';
|
|
3
3
|
import { type RawAssistant } from '../../../raw-spec/index.js';
|
|
4
4
|
import type { Components } from '../../components/index.js';
|
|
5
5
|
import type { Expressions } from '../../expressions/index.js';
|
|
6
|
-
import type {
|
|
6
|
+
import type { ModelVersion } from '../../model/index.js';
|
|
7
7
|
import type { Actions } from '../actions.js';
|
|
8
8
|
/**
|
|
9
9
|
* The field sources of every entity object type: GraphQL object type name → GraphQL field name →
|
|
@@ -11,28 +11,11 @@ import type { Actions } from '../actions.js';
|
|
|
11
11
|
* a concrete type; `id` and `type` are implicit and never listed.
|
|
12
12
|
*/
|
|
13
13
|
export type AssistantFieldSources = Readonly<Record<string, Readonly<Record<string, AssistantFieldSource>>>>;
|
|
14
|
-
/**
|
|
15
|
-
* The stored property each delta field of a `modify<Type>` mutation writes: entity type → delta
|
|
16
|
-
* field name → shape property. Only entity types with at least one writable field appear, aliases
|
|
17
|
-
* expanded to their members.
|
|
18
|
-
*/
|
|
19
|
-
export type AssistantWritableFields = Readonly<Record<string, Readonly<Record<string, string>>>>;
|
|
20
14
|
/**
|
|
21
15
|
* The recipe groups of one kind per entity type, in manifest
|
|
22
16
|
* order. Only entity types with at least one group appear, aliases expanded to their members.
|
|
23
17
|
*/
|
|
24
18
|
export type AssistantRecipeGroups = Readonly<Record<string, readonly AssistantRecipeGroup[]>>;
|
|
25
|
-
/**
|
|
26
|
-
* The options edges `meta` exposes per entity type, which are also the choices `modify<Type>` checks
|
|
27
|
-
* a written value against, in manifest order. Only entity types with at least one edge appear,
|
|
28
|
-
* aliases expanded to their members.
|
|
29
|
-
*/
|
|
30
|
-
export type AssistantFieldOptionsByType = Readonly<Record<string, readonly AssistantFieldOptions[]>>;
|
|
31
|
-
/**
|
|
32
|
-
* The custom mutations the manifest exposes: `Mutation` field name → the declared action it runs,
|
|
33
|
-
* in manifest order. Empty when the manifest exposes no action.
|
|
34
|
-
*/
|
|
35
|
-
export type AssistantActions = Readonly<Record<string, string>>;
|
|
36
19
|
/**
|
|
37
20
|
* The printed assistant GraphQL schema, the field sources its runtime resolvers read through, the
|
|
38
21
|
* entity types `deleteEntity` may delete, the fields the `modify<Type>` mutations may write, the
|
|
@@ -40,16 +23,9 @@ export type AssistantActions = Readonly<Record<string, string>>;
|
|
|
40
23
|
* of writable fields, aliases expanded, and the actions the custom mutations run,
|
|
41
24
|
* so the runtime checks the same sets the schema describes.
|
|
42
25
|
*/
|
|
43
|
-
export
|
|
44
|
-
readonly
|
|
45
|
-
|
|
46
|
-
readonly deletableTypes: readonly EntityTypeName[];
|
|
47
|
-
readonly writableFields: AssistantWritableFields;
|
|
48
|
-
readonly childRecipes: AssistantRecipeGroups;
|
|
49
|
-
readonly replaceRecipes: AssistantRecipeGroups;
|
|
50
|
-
readonly fieldOptions: AssistantFieldOptionsByType;
|
|
51
|
-
readonly actions: AssistantActions;
|
|
52
|
-
}
|
|
26
|
+
export type AssistantSchema = Required<AssistantManifest> & {
|
|
27
|
+
readonly resolved: AssistantResolvedManifest;
|
|
28
|
+
};
|
|
53
29
|
/** What the assistant schema is built from, besides the manifest. */
|
|
54
30
|
export interface AssistantSchemaInput {
|
|
55
31
|
readonly model: ModelVersion;
|
|
@@ -63,17 +39,7 @@ export interface AssistantSchemaInput {
|
|
|
63
39
|
/** The declared actions, which `actions` manifest entries expose as custom mutations. */
|
|
64
40
|
readonly actions: Actions;
|
|
65
41
|
}
|
|
66
|
-
/**
|
|
67
|
-
export
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
readonly toolStates: readonly string[];
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Builds the assistant GraphQL schema from the manifest whitelist, the latest model and the
|
|
74
|
-
* configurator states: aliases become interfaces implementing `AnyDomainEntity`, entity types become
|
|
75
|
-
* object types implementing every alias that contains them, and `Query` exposes the root, entities,
|
|
76
|
-
* selection and navigation entry points. Returns `undefined` after reporting diagnostics when the
|
|
77
|
-
* manifest does not fit the model or the generated schema is not valid GraphQL.
|
|
78
|
-
*/
|
|
79
|
-
export declare const createAssistantSchema: (manifest: RawAssistant, { model, states, phxDefinitions, expressions, components, actions }: AssistantSchemaInput, ctx: ParseContext) => AssistantSchema | undefined;
|
|
42
|
+
/** Resolves the whitelist against parse-time models, keeping only JSON data needed to build its schema. */
|
|
43
|
+
export declare const resolveAssistantManifest: (manifest: RawAssistant, { model, states, phxDefinitions, expressions, components, actions }: AssistantSchemaInput, ctx: ParseContext) => AssistantResolvedManifest | undefined;
|
|
44
|
+
/** Builds at parse time as well, translating GraphQL construction failures into the existing diagnostic. */
|
|
45
|
+
export declare const createAssistantSchema: (manifest: RawAssistant, input: AssistantSchemaInput, ctx: ParseContext) => AssistantSchema | undefined;
|
package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{GraphQLBoolean as e,GraphQLID as t,GraphQLInputObjectType as n,GraphQLInterfaceType as i,GraphQLList as r,GraphQLNonNull as o,GraphQLObjectType as s,GraphQLSchema as a,GraphQLString as p,getNullableType as d,isInputType as l,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
|
+
import{isArray as e}from"@salsita-ai/common/utils";import{buildAssistantManifest as t}from"#package/domain";import{DiagnosticCode as r,diagnosticMessages as i}from"../../../../errors/index.js";import{ASSISTANT_HINTS as n}from"../../../raw-spec/index.js";import{createSchemaRefResolver as s,isNullableSchema as o,phxDefinitionRefName as a}from"../../common/index.js";import{resolveAssistantFieldType as l}from"./assistant-field-type.js";let p="AnyDomainEntity",S={section:"childRecipes",component:"childEntityRecipes",mutation:"addChild"},N={section:"replaceRecipes",component:"replaceEntityRecipes",mutation:"replaceEntity"},T=new Set(["id","type","meta"]),d=new Set(["Query","Mutation","Navigation","RecipeGroup","Recipe","DryRun","DryRunError","FieldOption","JSON","String","Int","Float","Boolean","ID"]),c=(e,t)=>{if(!t||0===t.length)return e;let r=`One of: ${t.map(e=>`"${e}"`).join(", ")}.`;return e?/[.!?]$/.test(e)?`${e} ${r}`:`${e}. ${r}`:r},f=new Set(["id","type"]),m="The raw stored value: a string, a message descriptor or a multilingual object.",A=(e,t)=>Object.entries(e).find(([e])=>e===t)?.[1],u=(e,t,{model:r,components:i})=>{let n=new Set([e,...[...r.aliases].filter(([,t])=>t.includes(e)).map(([e])=>e)]);return i.filter(({componentName:e,typeOrAlias:r})=>e===t&&n.has(r)).map(({instanceName:e})=>String(e))},_=(...e)=>n.filter(t=>e.some(e=>e?.includes(t))),E=(e,t,n,s)=>{let{model:o}=n,a=new Map,l=new Map;for(let[p,{groups:S,hints:N}]of Object.entries(e)){let e=o.entityTypes.find(e=>e===p),T=e?[e]:[...o.aliases].find(([e])=>e===p)?.[1];if(!T){s.at(p).error(r.ASSISTANT_UNKNOWN_TYPE,i.ASSISTANT_UNKNOWN_TYPE(t.section,p));continue}for(let[e,o]of(T.forEach(e=>l.set(e,_(l.get(e),N))),Object.entries(S))){let l=s.at(p,"groups",e),S=`${p}.groups.${e}`,N={groupId:o?.as??e,instanceName:e,...o?.description===void 0?{}:{description:o.description},dryRuns:o?.allowDryRuns??!0};for(let s of T){let o=u(s,t.component,n),T=a.get(s)??[],d=T.find(e=>e.group.groupId===N.groupId);o.includes(e)?d?l.error(r.ASSISTANT_DUPLICATE_RECIPE_GROUP,i.ASSISTANT_DUPLICATE_RECIPE_GROUP(t,s,N.groupId,[d.entry,S])):a.set(s,[...T,{group:N,entry:S,entryCtx:l}]):l.error(r.ASSISTANT_UNKNOWN_RECIPE_GROUP,i.ASSISTANT_UNKNOWN_RECIPE_GROUP(t,p,e,s,o))}}}let p=o.entityTypes.flatMap(e=>{let t=a.get(e);return t?[{entityType:e,groups:t}]:[]});return{groups:Object.fromEntries(p.map(({entityType:e,groups:t})=>[e,t.map(({group:e})=>e)])),hints:l,metaEntries:new Map(p.flatMap(({entityType:e,groups:[t]})=>t?[[e,t.entryCtx]]:[]))}},I=e=>`${e}Meta`,O=e=>`${e.charAt(0).toUpperCase()+e.slice(1)}Result`,y=e=>{let t=(({anyOf:e,oneOf:t})=>[...e??[],...t??[]].filter(e=>"null"!==e.type))(e);return e.$ref||1!==t.length?e:t[0]},h=(e,t)=>{let{type:r,enumValues:i,localized:n,description:s}=l(e,t),o={...r,nonNull:!1},a=n?`${c(s,i)??""} ${m}`.trim():c(s,i);return{type:{...n?{kind:"scalar",name:"JSON",nonNull:!1}:o,nonNull:r.nonNull},...void 0===a?{}:{description:a}}},g=(t,r)=>{let i=(t=>{let r=y(t),i=r?.type==="array"&&r.items&&!e(r.items)?y(r.items):void 0,n=i??r;if(n?.$ref!==void 0&&"$DomainEntity"===a(n.$ref))return{target:n.references??p,list:void 0!==i}})(t);if(i)return{kind:"edge",...i,nullable:o(t,r),...void 0===t.description?{}:{description:t.description}};let{type:n,enumValues:s,localized:S,description:N}=l(t,r),T=c(N,s);return S?{kind:"value",type:{kind:"scalar",name:"JSON",nonNull:n.nonNull},description:`${N??""} ${m}`.trim()}:{kind:"value",type:n,...void 0===T?{}:{description:T}}},v=(e,t)=>{let{type:r,enumValues:i,localized:n,description:s}=l(e,t);return{type:{kind:"value",type:r},localized:!0===n,description:s,enumValues:i}},R=(e,t,n,s,o)=>{let a=t.startsWith("$")?((e,t,n,s)=>{let o=((e,t,{expressions:r,entityTypes:i})=>{let n=i.find(t=>t===e);for(let i of void 0===n?[e]:r.entityExpressions.get(n)?.shapeGroups??[]){let e=[...r.expressions.get(i)?.values()??[]].find(e=>e.name===t);if(e?.declaredSchema)return{implementation:e.implementation,declaredSchema:e.declaredSchema}}})(e.name,t,n);if(!o)return void s.error(r.ASSISTANT_UNKNOWN_FIELD,i.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t));let{implementation:a}=o;if("violations"===a.kind)return void s.error(r.ASSISTANT_UNSUPPORTED_EXPRESSION,i.ASSISTANT_UNSUPPORTED_EXPRESSION(e.name,t));if("relation"===a.kind){let[{target:e,cardinality:t}]=a.params;return{type:{kind:"edge",target:e,cardinality:t},localized:!1,description:void 0}}return v(o.declaredSchema,n.resolveRef)})(e,t,s,o):((e,t,{resolveRef:n},s)=>{let o=Object.entries(e.shape.properties).find(([e])=>e===t)?.[1];return o?v(o,n):void s.error(r.ASSISTANT_UNKNOWN_FIELD,i.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t))})(e,t,s,o);if(!a)return;let l=n?.as??(t.startsWith("$")?`_${t.slice(1)}`:t);return T.has(l)?void o.error(r.ASSISTANT_RESERVED_FIELD_NAME,i.ASSISTANT_RESERVED_FIELD_NAME(e.name,t,l)):{name:l,source:t,type:a.type,localized:a.localized,description:c(n?.description??a.description,a.enumValues),describedByManifest:n?.description!==void 0,enumValues:a.enumValues,valueDescription:n?.description??a.description}},M=(e,t,n,s,o)=>{let a=new Map,l=new Set(n);for(let s of[...t.flat(),...n]){let t=a.get(s.name);t?t.source!==s.source?o.error(r.ASSISTANT_FIELD_NAME_CONFLICT,i.ASSISTANT_FIELD_NAME_CONFLICT(e,s.name,[t.source,s.source])):l.has(s)&&s.describedByManifest&&a.set(s.name,{...t,description:s.description,describedByManifest:!0,valueDescription:s.valueDescription}):a.set(s.name,s)}return[...a.values()].map(e=>{let t=e.enumValues&&s(e.source);return t?{...e,enumValues:t,description:c(e.valueDescription,t)}:e})};export const resolveAssistantManifest=(e,{model:t,states:n,phxDefinitions:o,expressions:a,components:T,actions:y},v)=>{let b=v.errors.length,D=v.at("entities"),C=s(t.commonTypes,o);for(let e of t.resolvedShapes.keys())d.has(e)&&v.error(r.ASSISTANT_RESERVED_TYPE_NAME,i.ASSISTANT_RESERVED_TYPE_NAME(e,[...d]));let P=((e,t,r)=>{let i=new Map;for(let n of e){let e=[];for(let[i,s]of Object.entries(n.entries)){let o=R(n,i,s,t,r.at(n.name,i));o&&e.push(o)}i.set(n.name,e)}return i})(((e,t,n)=>{let s=[];for(let[r,i]of t.resolvedShapes){let t=e[r];t&&s.push({name:r,shape:i,entries:t})}let o=new Set(t.resolvedShapes.keys());for(let t of Object.keys(e))o.has(t)||n.at(t).error(r.ASSISTANT_UNKNOWN_TYPE,i.ASSISTANT_UNKNOWN_TYPE("entities",t));return s})(e.entities??{},t,D),{resolveRef:C,expressions:a,entityTypes:t.entityTypes},D),U=M(p,[],P.get(p)??[],()=>void 0,v),j=new Map([[p,U]]);for(let e of t.aliases.keys())e!==p&&j.set(e,M(e,[U],P.get(e)??[],()=>void 0,v));for(let e of t.entityTypes){let r=[p,...[...t.aliases].filter(([t,r])=>t!==p&&r.includes(e)).map(([e])=>e)],i=[...t.resolvedShapes].find(([t])=>t===e)?.[1];j.set(e,M(e,r.map(e=>j.get(e)??[]),P.get(e)??[],e=>{let t=Object.entries(i?.properties??{}).find(([t])=>t===e)?.[1];return t&&l(t,C).enumValues},v))}let L=Object.fromEntries(t.entityTypes.map(e=>[e,Object.fromEntries((j.get(e)??[]).map(({name:e,source:t,localized:r})=>[e,r?{source:t,localized:!0}:{source:t}]))])),$=E(e.childRecipes??{},S,{model:t,components:T},v.at("childRecipes")),w=E(e.replaceRecipes??{},N,{model:t,components:T},v.at("replaceRecipes")),W=((e,t,n)=>{let s=new Set;for(let o of Object.keys(e)){let e=t.entityTypes.find(e=>e===o),a=e?[e]:[...t.aliases].find(([e])=>e===o)?.[1];a?a.forEach(e=>s.add(e)):n.at(o).error(r.ASSISTANT_UNKNOWN_TYPE,i.ASSISTANT_UNKNOWN_TYPE("deletable",o))}return t.entityTypes.filter(e=>s.has(e))})(e.deletable??{},t,v.at("deletable")),F=((e,t,n)=>{let{model:s}=t,o=((e,t,n)=>{let s=new Map;for(let[o,a]of Object.entries(e)){let e=t.entityTypes.find(e=>e===o),l=e?[e]:[...t.aliases].find(([e])=>e===o)?.[1],p=[...t.resolvedShapes].find(([e])=>e===o)?.[1];if(!l||!p){n.at(o).error(r.ASSISTANT_UNKNOWN_TYPE,i.ASSISTANT_UNKNOWN_TYPE("writable",o));continue}for(let e of Object.keys(a)){let t=n.at(o,e);e.startsWith("$")||f.has(e)?t.error(r.ASSISTANT_NOT_WRITABLE,i.ASSISTANT_NOT_WRITABLE(o,e)):A(p.properties,e)?l.forEach(t=>{let r=s.get(t)??new Map;s.set(t,r.has(e)?r:r.set(e,o))}):t.error(r.ASSISTANT_UNKNOWN_FIELD,i.ASSISTANT_UNKNOWN_FIELD("writable",o,e))}}return s})(e,s,n);return s.entityTypes.flatMap(e=>{let a=[...s.resolvedShapes].find(([t])=>t===e)?.[1],p=[...o.get(e)??[]].flatMap(([s,o])=>{let p=a&&A(a.properties,s);return(p&&((e,{property:t,writableKey:n},s,{resolveRef:o,exposed:a,sources:p},S)=>{let N=Object.entries(A(p,e)??{}),T=a.get(e)?.find(({source:e})=>e===t)?.name??N.find(([,{source:e}])=>e===t)?.[0],d=void 0===T?N.find(([e])=>e===t)?.[1]:void 0;if(d)return void S.at(n,t).error(r.ASSISTANT_FIELD_NAME_CONFLICT,i.ASSISTANT_FIELD_NAME_CONFLICT(e,t,[d.source,t],`${n}.${t}`));let{type:f,enumValues:u,localized:_,description:E}=l(s,o),I={...f,nonNull:!1},O=T??t,y=void 0===T?c(E,u):void 0;return _?{name:O,property:t,type:{kind:"scalar",name:"JSON",nonNull:!1},description:y?`${y} ${m}`:m}:{name:O,property:t,type:I,...void 0===y?{}:{description:y}}})(e,{property:s,writableKey:o},p,t,n))??[]});return p.length>0?[{entityType:e,fields:p}]:[]})})(e.writable??{},{model:t,resolveRef:C,exposed:P,sources:L},v.at("writable")),k=((e,t,n,s)=>{let{model:o}=n,a=new Map;for(let[l,p]of Object.entries(e)){let e=o.entityTypes.find(e=>e===l),T=e?[e]:[...o.aliases].find(([e])=>e===l)?.[1]??[];for(let[e,o]of Object.entries(p)){let p=o?.options;if(!p)continue;let d=s.at(l,e,"options"),c=`${l}.${e}`;for(let s of T){let o=t.find(e=>e.entityType===s)?.fields.find(t=>t.property===e);if(!o)continue;let l=p.as??`${o.name}Options`,T=u(s,p.componentType,n),f=a.get(s)??[],m=f.find(e=>e.options.edgeName===l||e.options.field===o.name);if(T.includes(p.instanceName))if(l===S.section||l===N.section)d.error(r.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME,i.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME(c,l,o.name));else if(m)d.error(r.ASSISTANT_DUPLICATE_OPTIONS_EDGE,i.ASSISTANT_DUPLICATE_OPTIONS_EDGE(s,m.options.edgeName===l?{edgeName:l}:{field:o.name},[m.entry,c]));else{let e={field:o.name,edgeName:l,componentType:p.componentType,instanceName:p.instanceName,validate:p.validate??!0,dryRuns:p.allowDryRuns??!0};a.set(s,[...f,{options:e,hints:_(p.hints),entry:c,entryCtx:d}])}else d.error(r.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT,i.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT(c,p,s,T))}}}return a})(e.writable??{},F,{model:t,components:T},v.at("writable"));var K=[$.metaEntries,w.metaEntries,new Map([...k].flatMap(([e,[t]])=>t?[[e,t.entryCtx]]:[]))];for(let e of t.entityTypes){let n=K.flatMap(t=>t.get(e)??[])[0],s=I(e);n&&[...t.resolvedShapes.keys()].some(e=>e===s)&&n.error(r.ASSISTANT_META_TYPE_NAME_CONFLICT,i.ASSISTANT_META_TYPE_NAME_CONFLICT(e,s))}let Y=t.entityTypes.filter(e=>($.groups[e]?.length??0)>0||(w.groups[e]?.length??0)>0||(k.get(e)?.length??0)>0).map(I),V=((e,{actions:t,resolveRef:n,builtInMutations:s,typeNames:o},a)=>{let l=[],p=[...t.values()].map(e=>String(e.name));for(let[S,N]of Object.entries(e)){let e=a.at(S),T=[...t.values()].find(e=>e.name===S);if(!T){e.error(r.ASSISTANT_UNKNOWN_ACTION,i.ASSISTANT_UNKNOWN_ACTION(S,p));continue}let d=N?.as??S,c=l.find(e=>e.fieldName===d),f=O(d);if(s.has(d)||c){e.error(r.ASSISTANT_MUTATION_NAME_CONFLICT,i.ASSISTANT_MUTATION_NAME_CONFLICT(S,d,c?`"assistant.actions.${c.actionName}" already exposes`:"the built-in mutation of that name already takes"));continue}if(o.has(f)||l.some(e=>O(e.fieldName)===f)){e.error(r.ASSISTANT_ACTION_RESULT_TYPE_CONFLICT,i.ASSISTANT_ACTION_RESULT_TYPE_CONFLICT(S,d,f));continue}let m=N?.description??T.description;l.push({fieldName:d,actionName:S,...void 0===m?{}:{description:m},args:Object.fromEntries(Object.entries(T.params).map(([e,{schema:t}])=>[e,h(t,n)])),result:Object.fromEntries(Object.entries(T.result).map(([e,t])=>[e,g(t,n)]))})}return l})(e.actions??{},{actions:y,resolveRef:C,builtInMutations:new Set(["deleteEntity",S.mutation,N.mutation,...F.map(({entityType:e})=>`modify${e}`)]),typeNames:new Set([...d,...t.resolvedShapes.keys(),...Y])},v.at("actions"));if(!(v.errors.length>b))return{entityTypes:t.entityTypes,aliases:Object.fromEntries(t.aliases),exampleType:t.rootEntityTypes[0]??t.entityTypes[0],states:{navigationStates:n.navigationStates,viewStates:n.viewStates,toolStates:n.toolStates},deletableTypes:W,writableTypes:F,actionFields:V,childRecipes:Object.fromEntries(Object.entries($.groups).map(([e,t])=>[e,{groups:t,hints:$.hints.get(e)??[]}])),replaceRecipes:Object.fromEntries(Object.entries(w.groups).map(([e,t])=>[e,{groups:t,hints:w.hints.get(e)??[]}])),optionsEdges:Object.fromEntries([...k].map(([e,t])=>[e,t.map(({options:e,hints:t})=>({options:e,hints:t}))])),fields:Object.fromEntries([...j].map(([e,t])=>[e,t.map(e=>({name:e.name,source:e.source,localized:e.localized,type:e.type,...void 0===e.description?{}:{description:e.description}}))]))}};export const createAssistantSchema=(e,n,s)=>{let o=resolveAssistantManifest(e,n,s);if(o)try{return{...t(o),resolved:o}}catch(e){s.error(r.ASSISTANT_INVALID_SCHEMA,i.ASSISTANT_INVALID_SCHEMA([e instanceof Error?e.message:String(e)]));return}};
|
|
@@ -4,7 +4,7 @@ import type { MergedAssistant } from '../../../merge/index.js';
|
|
|
4
4
|
/**
|
|
5
5
|
* The part of the assistant manifest only the server reads: the integrator's instructions for the
|
|
6
6
|
* assistant and the AI settings it runs with. It is kept beside `AssistantSpec`, never inside it,
|
|
7
|
-
* because
|
|
7
|
+
* because its resolved manifest is serialized into the application bundle and into hot reload, and these
|
|
8
8
|
* must not reach the browser of a customer. Deployment registration uploads them. `null` when the
|
|
9
9
|
* application declares no `assistant` section.
|
|
10
10
|
*/
|
package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant.d.ts
CHANGED
|
@@ -1,27 +1,11 @@
|
|
|
1
1
|
import { Branded } from '@salsita-ai/common/utils';
|
|
2
2
|
import type { ParseContext } from '../../../../core/index.js';
|
|
3
3
|
import type { MergedAssistant } from '../../../merge/index.js';
|
|
4
|
-
import type
|
|
5
|
-
import { type AssistantActions, type AssistantFieldOptionsByType, type AssistantFieldSources, type AssistantRecipeGroups, type AssistantSchemaInput, type AssistantWritableFields } from './assistant-schema.js';
|
|
4
|
+
import { type AssistantSchema, type AssistantSchemaInput } from './assistant-schema.js';
|
|
6
5
|
/**
|
|
7
|
-
* The
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* expressions the runtime resolvers read; `deletableTypes` lists the entity types `deleteEntity`
|
|
11
|
-
* may delete; `writableFields` maps the delta fields of each `modify<Type>` mutation to the stored
|
|
12
|
-
* properties they write; `childRecipes` and `replaceRecipes` list the recipe groups each entity type exposes; `fieldOptions` lists
|
|
13
|
-
* the options edges of each entity type's writable fields; `actions` maps each custom `Mutation`
|
|
14
|
-
* field to the declared action it runs. `null` when the application declares no `assistant`
|
|
15
|
-
* section or it is invalid.
|
|
6
|
+
* The validated built assistant schema and its JSON-only resolved input. Parsing constructs the
|
|
7
|
+
* schema to retain diagnostics; code generation and hot reload carry `resolved`, while deployment
|
|
8
|
+
* registration consumes the built SDL and resolver metadata. Null without a valid assistant section.
|
|
16
9
|
*/
|
|
17
|
-
export type AssistantSpec = Branded<'AssistantSpec',
|
|
18
|
-
readonly sdl: string;
|
|
19
|
-
readonly fields: AssistantFieldSources;
|
|
20
|
-
readonly deletableTypes: readonly EntityTypeName[];
|
|
21
|
-
readonly writableFields: AssistantWritableFields;
|
|
22
|
-
readonly childRecipes: AssistantRecipeGroups;
|
|
23
|
-
readonly replaceRecipes: AssistantRecipeGroups;
|
|
24
|
-
readonly fieldOptions: AssistantFieldOptionsByType;
|
|
25
|
-
readonly actions: AssistantActions;
|
|
26
|
-
}> | null;
|
|
10
|
+
export type AssistantSpec = Branded<'AssistantSpec', AssistantSchema> | null;
|
|
27
11
|
export declare const AssistantSpec: (merged: MergedAssistant, input: AssistantSchemaInput, ctx: ParseContext) => AssistantSpec;
|
|
@@ -126,6 +126,13 @@ export declare class AssistantSystem implements InitializableSystem {
|
|
|
126
126
|
* Sends a user message with the record of what changed in the configuration since the agent last
|
|
127
127
|
* acted, which the server puts in front of the message for the model. The record is taken only
|
|
128
128
|
* when there is a chat to send it on, because taking it moves its baseline.
|
|
129
|
+
*
|
|
130
|
+
* A thread can end in a tool call that nothing will answer: its reply parked while no page was
|
|
131
|
+
* open, or the page that ran the tool was left before the result was sent. The client refuses to
|
|
132
|
+
* send while it waits on such a call, so the wait is given up first, and the server records for
|
|
133
|
+
* the model that the call got no result.
|
|
134
|
+
*
|
|
135
|
+
* It never rejects: a message the client could not send is reported as the error of the chat.
|
|
129
136
|
*/
|
|
130
137
|
send: (content: string) => Promise<void>;
|
|
131
138
|
/**
|
|
@@ -152,9 +159,14 @@ export declare class AssistantSystem implements InitializableSystem {
|
|
|
152
159
|
* and the new one for real, and both would send the result back, of which the server accepts one.
|
|
153
160
|
* The model could be told that nothing was run about a change that was made.
|
|
154
161
|
*
|
|
155
|
-
* Stopping a client
|
|
156
|
-
*
|
|
157
|
-
*
|
|
162
|
+
* Stopping a client closes its stream in the browser and cancels nothing on the server: a run that
|
|
163
|
+
* is still producing goes on there and the new chat rejoins it. The stopped client also drops the
|
|
164
|
+
* result of a tool call that is still running in it, and any continuation it has not sent yet. Such
|
|
165
|
+
* a call still finishes, so an `apply` may commit, but the server never gets its result: the run is
|
|
166
|
+
* parked on the call with nothing running for the new chat to rejoin, and the thread waits on it
|
|
167
|
+
* until the user's next message gives the wait up; see `send`.
|
|
168
|
+
*
|
|
169
|
+
* A chat that finishes a reply for another configuration is on another thread and is left alone.
|
|
158
170
|
*/
|
|
159
171
|
private _takeOverThread;
|
|
160
172
|
private _startClient;
|
|
@@ -1 +1 @@
|
|
|
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
|
|
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 r}from"./browser-details.js";import{ChangeRecorder as n}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({}),g=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."}),u=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 n({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=[r(),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{client:i}=e;i.getIsLoading()||null===i.getResumeState()||i.stop();let s={changes:this._recorder.take(this._committedState())};try{await i.sendMessage({content:t,metadata:s})}catch(i){let t=i instanceof Error?i:Error(String(i));e.generation.active&&this._chat.next({...this._chat.value,error:t}),this._context.domainServicesSelectors.getLogger().error("The assistant message could not be sent",{},t)}};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 r=this._context.getAuthorizedClient(),n=()=>r.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 n().headers(),fetchClient:c}),h=e(()=>n().url,l),d=e(()=>`${n().url}/runs`,l),_=this._tools.map(t=>({...t,execute:(e,s)=>i.active?t.execute?.(e,s):g})),m=new t({threadId:`assistant:${s}`,connection:{...h,joinRun:d.joinRun},persistence:!0,history:{pageSize:50},tools:_,onMessagesChange:t=>o({messages:t}),onLoadingChange:t=>{let e=i.active&&this._chat.value.isLoading;o({isLoading:t}),!t&&u(m)&&(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))}}),p=!1,v=()=>{p||(p=!0,this._finishing.delete(S),m.dispose())},S={client:m,configurationId:s,generation:i,getConnection:n,dispose:v};this._current=S,m.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()&&u(t.client))return void t.dispose();this._finishing.add(t)}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as t,jsxs as e}from"react/jsx-runtime";import{Tooltip as a,styled as i}from"@mui/material";import{memo as
|
|
1
|
+
import{jsx as t,jsxs as e}from"react/jsx-runtime";import{Tooltip as a,styled as i}from"@mui/material";import{memo as s,useCallback as o}from"react";import{match as n}from"ts-pattern";import{useLocalizable as r}from"#package/react-sdk";import{PhxIcon as l}from"#package/ui-sdk";import{AssistantPanelName as d}from"./theme.js";let m={id:"sdk.assistant.tool.updateDesign.label",message:"Update design"},c={id:"sdk.assistant.tool.readDesign.label",message:"Read design"},p={id:"sdk.assistant.tool.mistake.hint",message:"The assistant made a mistake."},h={id:"sdk.assistant.tool.cancelled.hint",message:"Stopped before it finished."},g={id:"sdk.assistant.tool.noResult.hint",message:"The result of this step was lost. It may or may not have been done."},f={id:"sdk.assistant.tool.toolBudget.hint",message:"Not done: the assistant reached its limit of steps for one message."},u=i("div",{name:d,slot:"chips"})(({theme:{palette:t,spacing:e,typography:a}})=>({...a.caption,alignItems:"start",color:t.text.secondary,display:"grid",gap:e(.75),gridTemplateColumns:"min-content minmax(0, 1fr)"})),k=i("span",{name:d,slot:"activity"})(({theme:{typography:t}})=>({blockSize:`calc(${t.caption.lineHeight} * 1em)`,display:"grid",placeItems:"center"})),x=i(l,{name:d,slot:"activityIcon"})({fontSize:14,'[data-chips="active"] &':{animation:"phx-assistant-turn 2.4s linear infinite","@media (prefers-reduced-motion: reduce)":{animation:"none"}},"@keyframes phx-assistant-turn":{to:{rotate:"360deg"}}}),w=i("span",{name:d,slot:"chip"})(({theme:{palette:t,spacing:e}})=>({cursor:"default",display:"inline-block",whiteSpace:"nowrap","&:not(:last-child)::after":{color:t.text.secondary,content:'"\xb7"',display:"inline-block",marginInline:e(.75),textDecoration:"none"},'&[data-chip="failed"]':{color:t.error.main},'&[data-chip="flawed"]':{textDecoration:"line-through",textDecorationColor:t.error.main}})),y=s(({tool:e})=>{let{chip:i,input:s,result:l}=e,d=r(m),u=r(c),k=r(p),x=r(h),y=r(g),b=r(f),v=n(i.label).with({kind:"text"},({text:t})=>t).with({kind:"updateDesign"},()=>d).with({kind:"readDesign"},()=>u).exhaustive(),C=o(()=>{console.info(`Assistant tool call "${v}"`,{input:s,result:l})},[s,v,l]);return t(a,{title:n(i).with({errorCode:"cancelled"},()=>x).with({errorCode:"no_result"},()=>y).with({errorCode:"tool_budget"},()=>b).with({state:"failed"},{state:"flawed"},()=>k).otherwise(()=>""),placement:"top-start",children:t(w,{onClick:C,"data-chip":i.state,children:v})})});export const AssistantToolChips=s(({tools:a,isActive:i})=>e(u,{"data-chips":i?"active":"done","aria-busy":i,children:[t(k,{children:t(x,{name:"Gear"})}),t("div",{children:a.map(e=>t(y,{tool:e},e.id))})]}));
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type AssistantToolErrorCode } from '@salsita-ai/contracts/assistant';
|
|
1
2
|
/**
|
|
2
3
|
* How a tool call of the assistant looks in the thread: still running, finished, a change that was
|
|
3
4
|
* not kept (`failed`), or a read that answered with errors (`flawed`), which matters less because
|
|
@@ -16,6 +17,11 @@ export type AssistantToolChipLabel = {
|
|
|
16
17
|
export interface AssistantToolChip {
|
|
17
18
|
readonly label: AssistantToolChipLabel;
|
|
18
19
|
readonly state: AssistantToolChipState;
|
|
20
|
+
/**
|
|
21
|
+
* Why the server recorded an error in place of the call's result, when it said so with a code this
|
|
22
|
+
* panel knows. Nothing for a call that went wrong for any other reason.
|
|
23
|
+
*/
|
|
24
|
+
readonly errorCode: AssistantToolErrorCode | undefined;
|
|
19
25
|
}
|
|
20
26
|
/** A tool call of a message as the chip reads it. */
|
|
21
27
|
export interface AssistantToolCall {
|
|
@@ -32,6 +38,7 @@ export interface AssistantToolCall {
|
|
|
32
38
|
/**
|
|
33
39
|
* Describes one tool call for its chip: the label in the order operation names, fixed text for the
|
|
34
40
|
* `apply` and `query` tools, tool name; and whether the call runs, finished, or went wrong. Why it
|
|
35
|
-
* went wrong is
|
|
41
|
+
* went wrong is part of it only as the code of an error the server recorded: the text of a tool
|
|
42
|
+
* result is worded for the model, not for the user.
|
|
36
43
|
*/
|
|
37
44
|
export declare const describeToolCall: (call: AssistantToolCall) => AssistantToolChip;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Kind as e,parse as t}from"graphql";import{z as n}from"zod";import{
|
|
1
|
+
import{Kind as e,parse as t}from"graphql";import{z as n}from"zod";import{ASSISTANT_TOOL_ERROR_CODES as r,AssistantToolError as a,applyTool as i,queryTool as o}from"@salsita-ai/contracts/assistant";let l=n.object({operations:n.array(n.object({query:n.string(),operationName:n.string().nullish()}))}),s=n.object({results:n.array(n.object({errors:n.array(n.unknown()).optional()})),committed:n.boolean()});export const describeToolCall=n=>{let d=(({name:n,input:r})=>{let a,s=(a=l.safeParse(r)).success?a.data.operations.flatMap(({query:n,operationName:r})=>r??(n=>{try{let r=t(n).definitions.find(t=>t.kind===e.OPERATION_DEFINITION);return r?.kind===e.OPERATION_DEFINITION?r.name?.value:void 0}catch{return}})(n)??[]):[];return s.length>0?{kind:"text",text:s.join(", ")}:n===i.name?{kind:"updateDesign"}:n===o.name?{kind:"readDesign"}:{kind:"text",text:n}})(n);if(null==n.result&&null==n.error)return{label:d,state:n.isReplyRunning?"running":"done",errorCode:void 0};let u=(e=>{let t=a.safeParse(e);if(t.success)return r.find(e=>e===t.data.code)})(n.result);return{label:d,state:(({name:e,result:t,error:n},r)=>{if(null!=n||null!=r)return e===o.name?"flawed":"failed";if(e!==i.name&&e!==o.name)return"done";let a=s.safeParse(t);if(!a.success)return e===o.name?"flawed":"failed";let{results:l,committed:d}=a.data;return e===i.name?d?"done":"failed":l.some(({errors:e})=>(e?.length??0)>0)||0===l.length?"flawed":"done"})(n,u),errorCode:u}};
|
package/dist/docs/index.json
CHANGED