@salsita-ai/sdk 0.50.0-develop.b5dfdd9774 → 0.50.0-develop.b65a5a9c66
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/admin/common/admin-interface.d.ts +11 -1
- package/dist/admin/common/admin-interface.js +1 -1
- package/dist/admin/ui/layout/UserProfile.d.ts +1 -1
- package/dist/admin/ui/layout/UserProfile.js +1 -1
- package/dist/admin/ui/maintenance/ImportPresets.js +1 -1
- package/dist/application/mount-application.js +1 -1
- package/dist/application/mount-configurator.js +1 -1
- package/dist/application/studio-embedding.d.ts +6 -0
- package/dist/application/studio-embedding.js +1 -0
- package/dist/application-spec/core/enhanced-json-schema.d.ts +5 -6
- package/dist/application-spec/core/enhanced-json-schema.js +1 -1
- package/dist/application-spec/core/markers/index.d.ts +1 -0
- package/dist/application-spec/core/markers/index.js +1 -1
- package/dist/application-spec/core/markers/set-in-studio-marker.d.ts +15 -0
- package/dist/application-spec/core/markers/set-in-studio-marker.js +1 -0
- package/dist/application-spec/errors/diagnostic-codes.d.ts +14 -0
- package/dist/application-spec/errors/diagnostic-codes.js +1 -1
- package/dist/application-spec/errors/diagnostic-messages.d.ts +14 -0
- package/dist/application-spec/errors/diagnostic-messages.js +1 -1
- package/dist/application-spec/generate-application/code/domain-runtime-files.d.ts +3 -3
- package/dist/application-spec/generate-application/code/domain-runtime-files.js +1 -1
- package/dist/application-spec/generate-application/code/standalone-app-files.d.ts +0 -12
- package/dist/application-spec/generate-application/code/standalone-app-files.js +1 -1
- package/dist/application-spec/generate-application/code/templates/admin-config.d.ts +5 -1
- package/dist/application-spec/generate-application/code/templates/admin-config.js +4 -4
- package/dist/application-spec/generate-application/code/templates/configurator-config.js +6 -6
- package/dist/application-spec/generate-application/code/templates/domain-spec/generate-phx-globals.d.ts +1 -1
- package/dist/application-spec/generate-application/code/templates/domain-spec/generate-phx-globals.js +19 -0
- package/dist/application-spec/generate-application/code/templates/domain-spec.js +12 -12
- package/dist/application-spec/generate-application/code/templates/global-definition/generate-phx-types.js +12 -12
- package/dist/application-spec/generate-application/code/templates/globals.js +21 -12
- package/dist/application-spec/generate-application/code/templates/sign-in-page-options.d.ts +5 -0
- package/dist/application-spec/generate-application/code/templates/sign-in-page-options.js +1 -0
- package/dist/application-spec/generate-application/code/templates/skills/core/cli.js +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/features/custom-layout/custom-layout.js +2 -2
- package/dist/application-spec/generate-application/code/templates/skills/features/custom-layout/sign-in.d.ts +3 -0
- package/dist/application-spec/generate-application/code/templates/skills/features/custom-layout/sign-in.js +19 -0
- package/dist/application-spec/generate-application/code/templates/skills/features/webhooks/authentication.d.ts +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/features/webhooks/authentication.js +32 -26
- package/dist/application-spec/generate-application/code/templates/skills/features/webhooks/entry-and-environment.js +1 -3
- package/dist/application-spec/generate-application/code/templates/skills/features/webhooks/publishing.js +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/features/webhooks/session-fields.d.ts +3 -0
- package/dist/application-spec/generate-application/code/templates/skills/features/webhooks/session-fields.js +1 -0
- package/dist/application-spec/generate-application/code/templates/skills/features/webhooks/webhooks.js +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/guide.d.ts +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/sdk-subpath-imports.js +1 -1
- package/dist/application-spec/generate-application/code/templates/webhook-builders.js +3 -2
- package/dist/application-spec/generate-application/code/templates/webhook-index.d.ts +1 -2
- package/dist/application-spec/generate-application/code/templates/webhook-index.js +3 -7
- package/dist/application-spec/generate-application/code/webhook-safe-files.d.ts +3 -1
- package/dist/application-spec/generate-application/code/webhook-safe-files.js +1 -1
- package/dist/application-spec/parse-application-files/access/access-handler-kinds.d.ts +18 -0
- package/dist/application-spec/parse-application-files/access/access-handler-kinds.js +1 -0
- package/dist/application-spec/parse-application-files/access/analyzed-file.d.ts +7 -0
- package/dist/application-spec/parse-application-files/access/analyzed-file.js +1 -0
- package/dist/application-spec/parse-application-files/access/check-access-handler-files.d.ts +20 -0
- package/dist/application-spec/parse-application-files/access/check-access-handler-files.js +1 -0
- package/dist/application-spec/parse-application-files/access/check-auth-hook-files.d.ts +17 -0
- package/dist/application-spec/parse-application-files/access/check-auth-hook-files.js +1 -0
- package/dist/application-spec/parse-application-files/access/index.d.ts +5 -0
- package/dist/application-spec/parse-application-files/access/index.js +1 -0
- package/dist/application-spec/parse-application-files/access/sign-in-control.d.ts +7 -0
- package/dist/application-spec/parse-application-files/access/sign-in-control.js +1 -0
- package/dist/application-spec/parse-application-files/categorize/categorize-files.d.ts +2 -1
- package/dist/application-spec/parse-application-files/categorize/categorize-files.js +1 -1
- package/dist/application-spec/parse-application-files/categorize/module-analysis.d.ts +30 -4
- package/dist/application-spec/parse-application-files/categorize/module-analysis.js +1 -1
- package/dist/application-spec/parse-application-files/categorize/webhook-safety.js +1 -1
- package/dist/application-spec/parse-application-files/merge/merged-app-metadata.d.ts +14 -1
- package/dist/application-spec/parse-application-files/merge/merged-app-metadata.js +1 -1
- package/dist/application-spec/parse-application-files/merge/merged-spec.d.ts +7 -1
- package/dist/application-spec/parse-application-files/merge/merged-spec.js +1 -1
- package/dist/application-spec/parse-application-files/parse-application-files.js +1 -1
- package/dist/application-spec/parse-application-files/parse-common-admin-spec.js +1 -1
- package/dist/application-spec/parse-application-files/raw-spec/raw-spec-file.d.ts +6 -0
- package/dist/application-spec/parse-application-files/raw-spec/raw-spec-file.js +1 -1
- package/dist/application-spec/parse-application-files/spec/application/configurator-spec/configurator-spec.d.ts +6 -0
- package/dist/application-spec/parse-application-files/spec/application/configurator-spec/configurator-spec.js +1 -1
- package/dist/application-spec/parse-application-files/spec/model/index.d.ts +2 -1
- package/dist/application-spec/parse-application-files/spec/model/index.js +1 -1
- package/dist/application-spec/parse-application-files/spec/model/session-data-schema.d.ts +5 -2
- package/dist/application-spec/parse-application-files/spec/model/session-data-schema.js +1 -1
- package/dist/application-spec/parse-application-files/spec/model/session-fields/index.d.ts +1 -0
- package/dist/application-spec/parse-application-files/spec/model/session-fields/index.js +1 -0
- package/dist/application-spec/parse-application-files/spec/model/session-fields/session-fields.d.ts +15 -0
- package/dist/application-spec/parse-application-files/spec/model/session-fields/session-fields.js +1 -0
- package/dist/application-spec/parse-application-files/spec/sections/app-metadata.js +1 -1
- package/dist/client/authenticated-client.d.ts +5 -1
- package/dist/client/authenticated-client.js +1 -1
- package/dist/client/authorized-client.d.ts +3 -1
- package/dist/client/authorized-client.js +1 -1
- package/dist/client/base-client.d.ts +15 -1
- package/dist/client/base-client.js +1 -1
- package/dist/client/contract.d.ts +25 -0
- package/dist/client/contract.js +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.js +1 -1
- package/dist/client/phoenix-api.d.ts +941 -8
- package/dist/client/unauthenticated-client.d.ts +1 -0
- package/dist/client/unauthenticated-client.js +1 -1
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.d.ts +9 -3
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.js +1 -1
- package/dist/configurator/common/configurator-interface.d.ts +11 -1
- package/dist/configurator/common/configurator-interface.js +1 -1
- package/dist/docs/index.json +1 -1
- package/dist/docs/phoenix/admin.mdx +5 -40
- package/dist/docs/phoenix/clerk-sign-in.mdx +9 -5
- package/dist/docs/phoenix/data-sources.mdx +25 -29
- package/dist/docs/phoenix/deployments.mdx +3 -3
- package/dist/docs/phoenix/finalization.mdx +0 -1
- package/dist/docs/phoenix/integration/authentication-external.mdx +5 -5
- package/dist/docs/phoenix/integration/authentication-internal.mdx +1 -1
- package/dist/docs/phoenix/integration/finalization-internal.mdx +1 -4
- package/dist/docs/phoenix/integration/integration-modes-internal.mdx +9 -0
- package/dist/docs/phoenix/phoenix-cli.mdx +4 -4
- package/dist/docs/phoenix/project-structure.mdx +13 -8
- package/dist/docs/phoenix/publishing.mdx +21 -28
- package/dist/docs/phoenix/sdk-builder-workflow.mdx +2 -2
- package/dist/docs/phoenix/sessions-and-access.mdx +169 -163
- package/dist/docs/phoenix/webhook-membership.mdx +3 -0
- package/dist/docs/phoenix/webhooks.mdx +90 -113
- package/dist/domain/application/access/access-handlers.d.ts +19 -0
- package/dist/domain/application/access/access-handlers.js +1 -0
- package/dist/domain/application/access/anonymous-handler.d.ts +16 -0
- package/dist/domain/application/access/anonymous-handler.js +1 -0
- package/dist/domain/application/access/chunk-scopes-handler.d.ts +27 -0
- package/dist/domain/application/access/chunk-scopes-handler.js +1 -0
- package/dist/domain/application/access/code-handler.d.ts +16 -0
- package/dist/domain/application/access/code-handler.js +1 -0
- package/dist/domain/application/access/index.d.ts +7 -0
- package/dist/domain/application/access/index.js +1 -0
- package/dist/domain/application/access/refresh-handler.d.ts +16 -0
- package/dist/domain/application/access/refresh-handler.js +1 -0
- package/dist/domain/application/access/signed-in-handler.d.ts +44 -0
- package/dist/domain/application/access/signed-in-handler.js +1 -0
- package/dist/domain/application/access/visitor-handler.d.ts +23 -0
- package/dist/domain/application/access/visitor-handler.js +1 -0
- package/dist/domain/application/application-config.d.ts +29 -0
- package/dist/domain/application/configurator-builder.d.ts +2 -0
- package/dist/domain/application/configurator-builder.js +1 -1
- package/dist/domain/application/index.d.ts +2 -1
- package/dist/domain/application/index.js +1 -1
- package/dist/domain/application/standard-properties.d.ts +1 -1
- package/dist/domain/application/standard-properties.js +1 -1
- package/dist/domain/core/domain-factory.d.ts +6 -0
- package/dist/domain/core/domain-factory.js +1 -1
- package/dist/domain/core/fit-session-data.d.ts +16 -0
- package/dist/domain/core/fit-session-data.js +1 -0
- package/dist/domain/domain-runtime/domain-context/actions.d.ts +4 -0
- package/dist/domain/domain-runtime/domain-context/actions.js +1 -1
- package/dist/domain/domain-runtime/domain-context/domain-context.d.ts +8 -0
- package/dist/domain/domain-runtime/domain-context/domain-context.js +1 -1
- package/dist/domain/domain-runtime/domain-context/selectors.d.ts +1 -0
- package/dist/domain/domain-runtime/domain-context/selectors.js +1 -1
- package/dist/domain/domain-runtime/domain-context/types.d.ts +8 -4
- package/dist/domain/domain-runtime/domain-runtime.d.ts +8 -0
- package/dist/domain/mocks/create-mock-domain-runtime.d.ts +4 -0
- package/dist/domain/spec/sections/app-metadata.d.ts +10 -0
- package/dist/editor/domain-editors/use-implementation-files.js +1 -1
- package/dist/extras/clerk/index.d.ts +6 -0
- package/dist/extras/cognito/AccountAvatar.d.ts +7 -0
- package/dist/extras/cognito/AccountAvatar.js +1 -0
- package/dist/extras/cognito/AccountControl.d.ts +13 -0
- package/dist/extras/cognito/AccountControl.js +1 -0
- package/dist/extras/cognito/AdminSignInPage.d.ts +26 -0
- package/dist/extras/cognito/AdminSignInPage.js +1 -0
- package/dist/extras/cognito/CognitoSignInPage.d.ts +8 -2
- package/dist/extras/cognito/CognitoSignInPage.js +1 -1
- package/dist/extras/cognito/ConfiguratorSignInPage.d.ts +19 -0
- package/dist/extras/cognito/ConfiguratorSignInPage.js +1 -0
- package/dist/extras/cognito/SignInFailurePage.d.ts +11 -0
- package/dist/extras/cognito/SignInFailurePage.js +1 -0
- package/dist/extras/cognito/SignInGateLayout.d.ts +25 -0
- package/dist/extras/cognito/SignInGateLayout.js +1 -0
- package/dist/extras/cognito/SignInNotice.d.ts +8 -0
- package/dist/extras/cognito/SignInNotice.js +1 -0
- package/dist/extras/cognito/index.d.ts +4 -0
- package/dist/extras/cognito/index.js +1 -1
- 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.d.ts +10 -3
- package/dist/phoenix/application-spec/resolve-deployment-data.js +2 -2
- package/dist/phoenix/commands/deps/deps.js +2 -2
- package/dist/phoenix/commands/prepare-deployment-command.js +2 -2
- package/dist/phoenix/commands/prepare-local-environment-command.js +1 -1
- package/dist/phoenix/services/prepare-development-environment.js +2 -2
- package/dist/phoenix/services/variant-file-session.js +1 -1
- package/dist/react-sdk/application-runtime/common-services/selectors.js +1 -1
- package/dist/react-sdk/application-runtime/domain-application-context/configuration-persist-system.d.ts +6 -0
- package/dist/react-sdk/application-runtime/domain-application-context/configuration-persist-system.js +1 -1
- package/dist/react-sdk/application-runtime/host-properties/selectors.d.ts +2 -2
- package/dist/react-sdk/application-runtime/integration/integration-mode.d.ts +30 -0
- package/dist/react-sdk/application-runtime/integration/integration-mode.js +1 -1
- package/dist/react-sdk/application-runtime/runtime/create-application-runtime.d.ts +20 -6
- package/dist/react-sdk/application-runtime/session/actions.d.ts +2 -1
- package/dist/react-sdk/application-runtime/session/actions.js +1 -1
- package/dist/react-sdk/application-runtime/session/initialize.js +1 -1
- package/dist/react-sdk/application-runtime/session/selectors.d.ts +2 -0
- package/dist/react-sdk/application-runtime/session/selectors.js +1 -1
- package/dist/react-sdk/application-runtime/session/session-service.d.ts +34 -1
- package/dist/react-sdk/application-runtime/session/session-service.js +1 -1
- package/dist/react-sdk/application-runtime/session/session-token.d.ts +8 -0
- package/dist/react-sdk/application-runtime/session/session-token.js +1 -1
- package/dist/react-sdk/application-runtime/session/types.d.ts +6 -1
- package/dist/react-sdk/domain-context/common-hooks/use-domain-context.d.ts +1 -0
- package/dist/react-sdk/preset-selection/PresetSelectionProvider.js +1 -1
- package/dist/react-sdk/session/AccessDeniedAdminPage.d.ts +13 -0
- package/dist/react-sdk/session/AccessDeniedAdminPage.js +1 -0
- package/dist/react-sdk/session/AccessDeniedPage.d.ts +20 -0
- package/dist/react-sdk/session/AccessDeniedPage.js +1 -0
- package/dist/react-sdk/session/SessionServiceProvider.js +1 -1
- package/dist/react-sdk/session/index.d.ts +3 -0
- package/dist/react-sdk/session/index.js +1 -1
- package/dist/react-sdk/session/sign-in-address.d.ts +13 -0
- package/dist/react-sdk/session/sign-in-address.js +1 -0
- package/dist/react-sdk/session/studio-frame.d.ts +7 -0
- package/dist/react-sdk/session/studio-frame.js +1 -0
- package/dist/react-sdk/session/use-sign-in.d.ts +50 -0
- package/dist/react-sdk/session/use-sign-in.js +1 -0
- package/dist/webhook/builders/auth-handler-builder.d.ts +21 -1
- package/dist/webhook/builders/auth-handler-builder.js +1 -1
- package/dist/webhook/builders/common.d.ts +9 -0
- package/dist/webhook/builders/webhook-builder.d.ts +13 -0
- package/dist/webhook/builders/webhook-builder.js +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
import{match as t}from"ts-pattern";import{InfoError as
|
|
1
|
+
import{P as e,match as t}from"ts-pattern";import{InfoError as s}from"@salsita-ai/common/utils";import{CONFIGURATOR_UNAVAILABLE_HEADER as r}from"@salsita-ai/contracts/api";import{createApiBaseClient as i}from"./base-client.js";import{ConfiguratorUnavailableError as o,InvalidDeploymentError as a,SignInRefusedError as n,SignInUnavailableError as l}from"./contract.js";import{checkApiVersion as p}from"./version.js";let d=e=>"string"==typeof e?e:null,c=(i,p,c)=>"true"===p.headers.get(r)?new o:t(i).with({statusCode:400,invalidDeployment:!0},()=>new a).with({statusCode:403,code:e.union("not-invited","access-refused")},({code:e,email:t,name:s})=>new n(e,d(t),d(s))).with({statusCode:503,code:"sign-in-unavailable"},({message:e})=>new l(`Server responded 503: ${d(e)??"Service unavailable"}`)).with({statusCode:403},()=>new s(`${c} API request failed: ${JSON.stringify(i)}`)).otherwise(()=>Error(`${c} API request failed: ${JSON.stringify(i)}`));export class UnauthenticatedClient{_baseUrl;_logger;_client;constructor(e,t){this._baseUrl=e,this._logger=t,this._client=i(this._baseUrl)}authenticateDeployment=async e=>{let t=await this._client.GET("/deployments/{deploymentId}/token",{params:{path:{deploymentId:e}}});if(p(t,this._logger),t.error)throw c(t.error,t.response,"authenticateDeployment");return t.data.bearerToken};authenticateSession=async(e,t,s,r)=>{let i=await this._client.POST("/deployments/{deploymentId}/session",{params:{path:{deploymentId:e}},body:{code:t,refreshToken:s,browserUserId:r}});if(p(i,this._logger),i.error)throw c(i.error,i.response,"authenticateSession");return i.data};signOutSession=async(e,t)=>{let s=await this._client.POST("/deployments/{deploymentId}/auth/sign-out",{params:{path:{deploymentId:e}},body:{refreshToken:t},keepalive:!0});if(s.error)throw c(s.error,s.response,"signOutSession")}}
|
|
@@ -252,6 +252,8 @@ export declare class AssistantSystem implements InitializableSystem {
|
|
|
252
252
|
private readonly _toolDependencies;
|
|
253
253
|
/** Aborting it unregisters the WebMCP tools of the current load; nothing while none are registered. */
|
|
254
254
|
private _webMcpRegistration;
|
|
255
|
+
/** The session manifest the WebMCP tools were last settled for, registered or not. */
|
|
256
|
+
private _webMcpManifest;
|
|
255
257
|
constructor(_context: AssistantSystemContext);
|
|
256
258
|
/** The conversation. It never completes, and holds the empty chat whenever no chat is active. */
|
|
257
259
|
readonly chat$: ObservableWithLastValue<AssistantChatSnapshot>;
|
|
@@ -628,12 +630,16 @@ export declare class AssistantSystem implements InitializableSystem {
|
|
|
628
630
|
* locked against a running panel reply either; the conflict retry of `GraphQLSystem.execute` is
|
|
629
631
|
* all that orders the two.
|
|
630
632
|
*
|
|
631
|
-
*
|
|
632
|
-
*
|
|
633
|
-
* WebMCP off
|
|
633
|
+
* The tools are settled again when the session's manifest changes while the configuration is open:
|
|
634
|
+
* a session refreshed in place, with a new role or new session data, can narrow or widen it, or turn
|
|
635
|
+
* WebMCP off. The change is noticed at the store reset that such a refresh makes; see
|
|
636
|
+
* `_refreshWebMcp`. An editor hot reload that changes the `assistant` section is picked up the same
|
|
637
|
+
* way when it resets the store, and otherwise takes effect at the next load.
|
|
634
638
|
*/
|
|
635
639
|
private _registerWebMcp;
|
|
636
640
|
private _unregisterWebMcp;
|
|
641
|
+
/** Registers the WebMCP tools again when the session's manifest is no longer the one they were settled for. */
|
|
642
|
+
private _refreshWebMcp;
|
|
637
643
|
private _startClient;
|
|
638
644
|
/**
|
|
639
645
|
* Lets go of the current chat and puts the empty chat in its place. The client itself is left as
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ChatClient as e,fetchServerSentEvents as t}from"@tanstack/ai-client";import{BehaviorSubject as a,firstValueFrom as i,race as s,timer as n}from"rxjs";import{filter as r,skip as o}from"rxjs/operators";import{match as l}from"ts-pattern";import{isShallowEqual as h}from"@salsita-ai/common/utils";import{ASSISTANT_TRANSCRIPT_EVENT as c,AssistantTranscriptEvent as u,assistantImageReference as d}from"@salsita-ai/contracts/assistant";import{AssistantRequestError as _}from"#package/client";import{applicationConfigComponent as g}from"#package/domain";import{generateShareLink as p}from"#package/react-sdk";import{AssistantSpeechPlayer as m}from"./assistant-speech-player.js";import{ChangeRecorder as v}from"./change-recorder.js";import{ComposerAttachments as f}from"./composer-attachments.js";import{createApplyClientTool as y,createQueryClientTool as S,runApplyTool as w,runQueryTool as x,toToolResult as b}from"./graphql-tools.js";import{rasterizeImage as C}from"./rasterize-image.js";import{isSpeakableReply as A}from"./speakable-reply.js";import{registerWebMcpTools as I,runShareLinkTool as T}from"./webmcp/index.js";let M=Object.freeze({messages:Object.freeze([]),isLoading:!1,error:void 0,failedStatus:void 0,retryAfterSeconds:void 0,runFailed:void 0,isContinuable:!0,isLocked:!1,isNetworkLocked:!1,isLoaded:!1,isVoiceEnabled:!1,isResuming:!1,earlierThreads:Object.freeze([]),earlierThreadId:null,isLoadingEarlierThread:!1,hasOlderMessages:!1,isLoadingOlderMessages:!1}),O=Object.freeze({top:0,right:0,bottom:0,left:0}),R=Object.freeze({kind:"transition"}),k=Object.freeze({open:!1,hasUnreadReply:!1,isInputFocused:!1}),L=Object.freeze({}),E=b({results:[],committed:!1,sideEffects:[],warnings:[],screenshots:new Map,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."}),$=e=>{if(e.getError())return!0;let t=e.getMessages().at(-1)?.parts.at(-1);return t?.type!=="tool-call"&&t?.type!=="tool-result"},U=async e=>{try{let t=await e.clone().json(),a=t?.page;return a?.truncated===!0&&"string"==typeof a.cursor&&""!==a.cursor}catch{return!1}},F=e=>{let t=e.map(e=>e.role).lastIndexOf("user");return e.slice(t+1).every(e=>0===e.parts.length)?t:-1},j=async e=>{let t=new Uint8Array(await e.arrayBuffer()),a="";for(let e=0;e<t.length;e+=32768)a+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(a)};export class AssistantSystem{_context;_tools;_chat=new a(M);_panel=new a(k);_annotationOverlay=new a(null);_imageView=new a(null);_composerAttachments=new f;_releaseInert=null;_annotationRun=null;_activation=null;_current=null;_finishing=new Set;_resuming=null;_refused=null;_firstAttempt=null;_chain={};_recorder;_recording=null;_applyToolCallIds=new WeakMap;_undoTipToolCallId=new a(void 0);_screenshotUrls=new Map;_player=new m({createAudio:()=>this._context.createAudio(),logError:(e,t)=>this._context.domainServicesSelectors.getLogger().error(e,{},t)});_voiceReplyChat=null;_toolDependencies;_webMcpRegistration=null;constructor(e){this._context=e;let{configuratorExtensionSelectors:t,domainContextSelectors:a,domainServicesSelectors:i,getAssistantSetup:s}=e,n=(e,t)=>e?.find(e=>e.state===t)?.name??t;this._recorder=new v({maxEntities:30},{readers:{selectedEntityId:e=>a.getNavigationSystem().getActiveSelectionState(e),navigationState:e=>n(s().manifest?.navigation?.navigationStates,a.getNavigationSystem().getActiveNavigationState(e)),viewState:e=>n(s().manifest?.navigation?.viewStates,a.getNavigationSystem().getActiveViewState(e)),toolState:e=>n(s().manifest?.navigation?.toolStates,a.getNavigationSystem().getActiveToolState(e))},getExposedFields:()=>s().manifest?.fields??L,resolveLocalizable:e=>i.getResolveLocalizable()(e)}),this._toolDependencies={getGraphQLSystem:()=>t.getGraphQLSystem(),getStoreSystem:()=>a.getStoreSystem(),getActiveMode:()=>a.getActiveMode(),getIsViewMode:()=>a.getIsViewMode(),getApplicationConfig:()=>a.getComponentReader().readFirstRootComponent({componentTypes:[g]},this._committedState())?.state,generateShareLink:({shareStrategy:e,...t})=>p({configurationId:this._context.getConfigurationId(),shareStrategy:e,save:()=>this._context.domainApplicationContextSelectors.getConfigurationPersistSystem().save(),apiClient:this._context.getAuthorizedClient()},t)};let r=(e,t)=>{void 0!==t&&void 0!==e.preparedState&&(this._applyToolCallIds.set(e.preparedState,t),this._refreshUndoTip()),e.committed&&this._recorder.clear(this._committedState())};this._tools=[S(this._toolDependencies),y(this._toolDependencies,r)],a.getUndoSystem().tip$.subscribe(this._refreshUndoTip)}chat$=this._chat;panel$=this._panel;annotationOverlay$=this._annotationOverlay;imageView$=this._imageView;composerAttachments$=this._composerAttachments.attachments$;hasFreeAttachmentSlot$=this._composerAttachments.hasFreeSlot$;undoTipToolCallId$=this._undoTipToolCallId;playback$=this._player.playback$;muted$=this._player.muted$;getSessionManifest=()=>this._context.getAssistantSetup().manifest;initialize=()=>{let{committed:e}=this._context.domainContextSelectors.getStoreSystem().stateSlices;this._recording??=e.pipe(o(1)).subscribe(this._recorder.record),this._recorder.reset(e.value.state),this._endChat(),this._patchPanel(k),this._releaseScreenshotUrls(),this._player.reset(),this._closeAnnotationOverlay(),this.closeImageView(),this.clearAttachments(),this._activation&&(this._startClient(),this._registerWebMcp())};activate=()=>{this._endChat();let e={};return this._activation=e,this._startClient(),this._registerWebMcp(),()=>{this._activation===e&&(this._activation=null,this._endChat(),this._player.stop(),this._unregisterWebMcp())}};send=async(e,t=[],{onSent:a,onUnsent:i,audio:s}={})=>{if(!this._chat.value.isContinuable&&!await this.resume())return;let n=this._current;if(!n)return;let r={changes:this._recorder.take(this._committedState()),locale:this._context.domainServicesSelectors.getI18n().locale},o=()=>this._recorder.reset(this._committedState()),l=t.map(({blob:e})=>e),h=s?{type:"audio",source:{type:"data",value:await j(s),mimeType:s.type}}:null,c=!1,u=(i,s)=>{c||(c=!0,a?.());let n=t.flatMap((e,t)=>{let a=s[t];return"image"===e.type||void 0===a?[]:[{imageId:a,pins:e.pins,source:e.source}]});return this._voiceReplyChat=h?i:null,this._sendOn(i,this._messageContent(h?"":e,s,h),0===n.length?r:{...r,annotations:n})},d=e=>{if(!h||!e.generation.active||e.client.getIsLoading())return;let t=e.client.getMessages(),{error:a,failedStatus:s}=this._chat.value,n=F(t);if(a&&void 0!==s&&-1!==n){e.client.setMessagesManually(t.slice(0,n)),o(),422!==s&&i?.();return}t.some(e=>"user"===e.role&&e.parts.some(e=>"audio"===e.type))&&this.reloadThread()};this._firstAttempt=n;try{let e=0===l.length?[]:await this._uploadImages(n,l);if(null===e||!n.generation.active)return void o();if("refused"!==e){await u(n,e);let t=this._findRefusedMessageIndex(n);if(-1===t)return void d(n);this._refused={chat:n,index:t}}}finally{this._firstAttempt===n&&(this._firstAttempt=null)}if(!await this.resume()){c||o(),this._current&&d(this._current);return}let _=this._current,g=_?await this._uploadSuccessorImages(_,l):null;if(!_||null===g||"refused"===g||!_.generation.active){_&&"refused"===g&&this._reportUploadFailure(_,this._chat.value.error),c&&i?.(),o();return}await u(_,g),d(_)};annotate=async e=>null!==this._annotationOverlay.value?null:l(e).with({type:"attachment"},e=>this._annotateAttachment(e)).with({type:"view"},()=>this._annotateIntoSlot("view",e=>this._annotateView(e))).with({type:"image"},e=>this._annotateIntoSlot("image",t=>this._annotateImage(t,e))).exhaustive();_annotateIntoSlot=async(e,t)=>{let a,i=this._composerAttachments.reserveSlot();if(!i)return null;try{a=await this._runAnnotation(t)}finally{i()}return a&&this._composerAttachments.attach({type:"annotation",blob:a.blob,pins:a.pins,source:e})};viewAnnotation=e=>{if(null!==this._annotationOverlay.value)return;let t={kind:"viewer",annotation:e,close:()=>{this._annotationOverlay.value===t&&this._setAnnotationOverlay(null)}};this._setAnnotationOverlay(t)};viewImage=e=>{this._imageView.next(e)};closeImageView=()=>{null!==this._imageView.value&&this._imageView.next(null)};attach=e=>this._composerAttachments.attach({type:"image",blob:e});reserveAttachmentSlot=()=>this._composerAttachments.reserveSlot();restoreAttachments=e=>this._composerAttachments.restore(e);removeAttachment=e=>this._composerAttachments.remove(e);clearAttachments=()=>this._composerAttachments.clear();resume=async()=>{let e=this._current;if(!e)return!1;if(this._chat.value.isContinuable)return!0;if(this._resuming)return this._resuming;let t=this._compact(e).finally(()=>{this._resuming===t&&(this._resuming=null)});return this._resuming=t,t};loadScreenshotUrl=e=>{let t=this._screenshotUrls.get(e);if(t)return t;let a=this._current;if(!a)return Promise.reject(Error(`The screenshot ${e} cannot be read, because the assistant chat is not active. Open the assistant panel of the configuration first.`));let i=this._screenshotUrls,s=a.authorizedClient.getAssistantImage(a.configurationId,e).then(e=>URL.createObjectURL(e));return i.set(e,s),s.catch(()=>{i.get(e)===s&&i.delete(e)}),s};playReply=e=>{let t=this._current;t&&this._player.toggle({messageId:e,loadSpeech:()=>this._loadSpeech(t,e),isAutoplay:!1})};stopPlayback=()=>{this._player.stop()};setMuted=e=>{this._player.setMuted(e)};unlockPlayback=()=>{this._player.unlock()};loadEarlierThread=async()=>{let e=this._current,{earlierThreadId:t,isLoadingEarlierThread:a,hasOlderMessages:i}=this._chat.value;if(!e||null===t||a||i)return;let s=this._chain;this._chat.next({...this._chat.value,isLoadingEarlierThread:!0});try{let a=await e.authorizedClient.getAssistantEarlierThread(e.configurationId,t);if(this._chain!==s||this._chat.value.earlierThreadId!==t)return;let[i,...n]=this._chat.value.earlierThreads,r={threadId:t,messages:a.messages};this._chat.next({...this._chat.value,earlierThreads:i?.threadId===t?[r,...n]:[r,...this._chat.value.earlierThreads],earlierThreadId:a.previousThreadId})}catch(e){this._context.domainServicesSelectors.getLogger().warn("Could not load the earlier assistant conversation",{error:e})}finally{this._chain===s&&this._chat.next({...this._chat.value,isLoadingEarlierThread:!1})}};loadOlderMessages=async()=>{let e=this._current,{hasOlderMessages:t,isLoadingOlderMessages:a}=this._chat.value;if(e&&t&&!a){this._chat.next({...this._chat.value,isLoadingOlderMessages:!0});try{await e.client.loadOlderMessages()}catch(e){this._context.domainServicesSelectors.getLogger().warn("Could not load older assistant messages",{error:e})}finally{e===this._current&&this._chat.next({...this._chat.value,hasOlderMessages:e.client.getHasOlderMessages(),isLoadingOlderMessages:!1})}}};stop=async()=>{let e=this._current;if(!e)return;let t=e.client.getCurrentRunId();if(this._voiceReplyChat===e&&(this._voiceReplyChat=null),e.client.stop(),null!=t)try{let a=e.getConnection();await fetch(`${a.url}/runs/${encodeURIComponent(t)}/cancel`,{method:"POST",headers:await a.headers()})}catch(e){this._context.domainServicesSelectors.getLogger().warn("Could not cancel the assistant run on the server",{error:e})}};reloadThread=()=>{this._restartChat({regenerate:!1})};regenerate=()=>{this._restartChat({regenerate:!0})};_restartChat=({regenerate:e})=>{if(!this._activation)return;let t=this._retireChat();t?.client.stop(),t?.dispose(),this._recorder.reset(this._committedState()),this._startClient({regenerate:e})};undoToolCalls=e=>{let t=this._context.domainContextSelectors.getUndoSystem(),a=()=>{let t=this._findTipToolCallId();return void 0!==t&&e.has(t)};for(;a();)t.undo()};setOpen=e=>{this._patchPanel(e?{open:e,hasUnreadReply:!1}:{open:e,isInputFocused:!1})};setInputFocused=e=>{this._patchPanel({isInputFocused:e})};_setAnnotationOverlay=e=>{null!==e&&null===this._releaseInert&&(this._releaseInert=this._context.configuratorExtensionSelectors.getLayoutSystem().makeInert()),this._annotationOverlay.next(e),null===e&&(this._releaseInert?.(),this._releaseInert=null)};_annotateView=async e=>{let{getCameraControlSystem:t,getCanvasSystem:a}=this._context.configuratorExtensionSelectors,o=t(),l=a().r3fHandle$.value?.get().frameloop==="demand",h=()=>this._annotationRun===e;if(this._setAnnotationOverlay(R),await i(s(o.transitionState$.pipe(r(e=>"still"===e||"sleep"===e&&!l)),n(2e3))),!h())return this._setAnnotationOverlay(null),null;let c=()=>i(o.cameraOffsetSettled$.pipe(r(Boolean))),u=null;try{o.setCameraOffsetOverride(O),await c();let e=await this._context.configuratorExtensionSelectors.getImageRenderingSystem().captureView();h()&&(u=await this._edit(e))}catch(e){this._logAnnotationFailure("The configurator view could not be frozen for an annotation",e)}this._setAnnotationOverlay(R);try{o.setCameraOffsetOverride(null),await c()}finally{o.setCameraOffsetOverride(null),this._setAnnotationOverlay(null)}return u};_runAnnotation=async e=>{let t={},a=null;this._annotationRun=t;try{a=await e(t)}finally{this._annotationRun!==t?a=null:this._annotationRun=null}return a};_annotateAttachment=async({attachmentId:e,background:t})=>{let a=this._composerAttachments.attachments$.value.find(({id:t})=>t===e);if(!a||"annotation"===a.type)return null;let i=await this._runAnnotation(e=>this._annotateImage(e,{type:"image",image:a.blob,background:t}));return i&&this._composerAttachments.replace(e,{type:"annotation",blob:i.blob,pins:i.pins,source:"image"})};_annotationArea=()=>{let e=this._context.configuratorExtensionSelectors.getCanvasSystem().r3fHandle$.value?.get().gl.domElement,t=globalThis.devicePixelRatio||1;return e&&e.width>0&&e.height>0?{width:e.width,height:e.height}:{width:Math.max(1,Math.round(globalThis.innerWidth*t)),height:Math.max(1,Math.round(globalThis.innerHeight*t))}};_annotateImage=async(e,{image:t,background:a})=>{this._setAnnotationOverlay(R);try{let i=await C(t,a,this._annotationArea());return this._annotationRun===e?await this._edit(i):null}catch(e){return this._logAnnotationFailure("The image could not be drawn for an annotation",e),null}finally{this._setAnnotationOverlay(null)}};_edit=e=>{let{getCanvasSystem:t,getExportSystem:a}=this._context.configuratorExtensionSelectors,i=t().r3fHandle$.value,s=i?a().pauseFrameloop(i):()=>{};return new Promise(t=>{this._setAnnotationOverlay({kind:"editor",view:e,finish:t})}).finally(s)};_logAnnotationFailure=(e,t)=>{let a=t instanceof Error?t:Error(String(t));this._context.domainServicesSelectors.getLogger().error(e,{},a)};_closeAnnotationOverlay=()=>{let e=this._annotationOverlay.value;this._annotationRun=null,e?.kind==="editor"&&e.finish(null),e?.kind==="viewer"&&e.close()};_findRefusedMessageIndex=e=>{let{failedStatus:t,isContinuable:a}=this._chat.value;return this._firstAttempt===e&&e.generation.active&&409===t&&!a?F(e.client.getMessages()):-1};_messageContent=(e,t,a)=>0!==t.length||a?[...e?[{type:"text",content:e}]:[],...a?[a]:[],...t.map(e=>({type:"image",source:{type:"url",value:d(e)}}))]:e;_uploadImages=async(e,t)=>{if(0===t.length)return[];e.generation.active&&this._chat.next({...this._chat.value,error:void 0,failedStatus:void 0,runFailed:void 0});try{return(await Promise.all(t.map(t=>e.authorizedClient.uploadAssistantImage(e.configurationId,t)))).map(({imageId:e})=>e)}catch(a){let t=a instanceof Error?a:Error(String(a));if(t instanceof _&&t.threadNotContinuable)return e.generation.active&&this._chat.next({...this._chat.value,isContinuable:!1,error:t,failedStatus:t.status,runFailed:void 0}),"refused";return this._reportUploadFailure(e,t),null}};_uploadSuccessorImages=async(e,t)=>{if(0===t.length)return[];this._chat.next({...this._chat.value,isResuming:!0});try{return await this._uploadImages(e,t)}finally{e.generation.active&&this._chat.next({...this._chat.value,isResuming:!1})}};_reportUploadFailure=(e,t)=>{e.generation.active&&this._chat.next({...this._chat.value,error:t,failedStatus:t instanceof _?t.status:void 0,runFailed:void 0}),this._context.domainServicesSelectors.getLogger().error("The images of the assistant message could not be uploaded",{},t)};_sendOn=async(e,t,a)=>{let{client:i}=e;i.getIsLoading()||null===i.getResumeState()||i.stop();try{await i.sendMessage({content:t,metadata:a})}catch(a){let t=a instanceof Error?a:Error(String(a));e.generation.active&&this._chat.next({...this._chat.value,error:t,runFailed:void 0}),this._context.domainServicesSelectors.getLogger().error("The assistant message could not be sent",{},t)}};_compact=async e=>{this._chat.next({...this._chat.value,isResuming:!0,error:void 0,failedStatus:void 0,runFailed:void 0});try{let{previousThreadId:t}=await e.authorizedClient.compactAssistantThread(e.configurationId);if(!e.generation.active)return!1;let{messages:a,earlierThreads:i,earlierThreadId:s,isLoadingEarlierThread:n}=this._chat.value,r=this._refused?.chat===e?a.slice(0,this._refused.index):a,o=e.client.getHasOlderMessages()?t:s;return e.generation.active=!1,this._current=null,e.client.stop(),e.dispose(),this._chat.next({...M,earlierThreads:[...i,{threadId:t,messages:r}],earlierThreadId:o,isLoadingEarlierThread:n}),this._startClient(),!0}catch(a){let t=a instanceof Error?a:Error(String(a));if(t instanceof _&&409===t.status)return e.generation.active&&this.reloadThread(),!1;return e.generation.active&&this._chat.next({...this._chat.value,isResuming:!1,error:t,failedStatus:t instanceof _?t.status:void 0,runFailed:void 0,...t instanceof _&&t.locked&&{isLocked:!0,isNetworkLocked:t.networkLocked}}),this._context.domainServicesSelectors.getLogger().error("The assistant thread could not be resumed",{},t),!1}};_findTipToolCallId=()=>{let e=this._context.domainContextSelectors.getUndoSystem(),t=e.tip$.value?.committedState;return void 0!==t&&e.canUndo()?this._applyToolCallIds.get(t):void 0};_refreshUndoTip=()=>{let e=this._findTipToolCallId();e!==this._undoTipToolCallId.value&&this._undoTipToolCallId.next(e)};_loadSpeech=(e,t)=>e.authorizedClient.getAssistantReplySpeech(e.configurationId,t);_readVoiceReply=e=>{if(this._player.muted$.value||!this._chat.value.isVoiceEnabled)return;let t=e.client.getMessages(),a=t.map(e=>e.role).lastIndexOf("user")+1,i=t.slice(a).reverse().find(e=>e.parts.some(e=>"text"===e.type&&""!==e.content.trim()));i&&A(i)&&this._player.play({messageId:i.id,loadSpeech:()=>this._loadSpeech(e,i.id),isAutoplay:!0})};_committedState=()=>this._context.domainContextSelectors.getStoreSystem().stateSlices.committed.value.state;_patchPanel=e=>{let t={...this._panel.value,...e};h(t,this._panel.value)||this._panel.next(t)};_takeOverThread=e=>{for(let t of this._finishing)t.configurationId===e&&(t.client.stop(),t.dispose())};_registerWebMcp=()=>{this._unregisterWebMcp();let e=this._context.getWebMcpHost(),t=this._context.getConfigurationId(),{modelContext:a}=e,{manifest:i}=this._context.getAssistantSetup();if(!a||!i||!1===i.webmcp)return void e.settleLoad({configurationId:t,tools:!1});let s=new AbortController;this._webMcpRegistration=s,I({modelContext:a,manifest:i,run:{query:e=>x(this._toolDependencies,e,{screenshots:"inline",surface:"webmcp"}),apply:e=>w(this._toolDependencies,e,{screenshots:"inline",surface:"webmcp"}),share:e=>T(this._toolDependencies,e)},signal:s.signal}).then(()=>{this._webMcpRegistration===s&&e.settleLoad({configurationId:t,tools:!0})},a=>{this._webMcpRegistration===s&&(this._unregisterWebMcp(),e.settleLoad({configurationId:t,tools:!1})),this._context.domainServicesSelectors.getLogger().warn("The WebMCP tools could not be registered",{},a instanceof Error?a:void 0)})};_unregisterWebMcp=()=>{this._webMcpRegistration?.abort(),this._webMcpRegistration=null};_startClient=({regenerate:a=!1}={})=>{let i={active:!0},s=a,n=this._context.getConfigurationId();this._takeOverThread(n);let r=this._context.getAuthorizedClient(),o=()=>{if(i.active){let{manifest:e,error:t}=this._context.getAssistantSetup();if(t)throw t;if(!e)throw Error("The assistant is disabled for this session.")}return r.getAssistantChatConnection(n)},l=e=>{if(!i.active)return;let t={...this._chat.value,...e};h(t,this._chat.value)||this._chat.next(t)},d=async(e,t)=>{let a,i=await fetch(e,t).finally(()=>l({isLoaded:!0})),s=i.headers.get("x-assistant-thread-continuable"),n=i.headers.get("x-assistant-locked"),r="true"===n||"network"===n,o=null!=s&&i.ok,h=o&&0===this._chat.value.earlierThreads.length,c=h?i.headers.get("x-assistant-previous-thread"):null,u=i.headers.get("x-assistant-run-failed");return l({failedStatus:i.ok?void 0:i.status,retryAfterSeconds:i.ok?void 0:null!==(a=i.headers.get("retry-after"))&&/^\d+$/.test(a.trim())?Number(a):void 0,...o?{runFailed:"busy"===u?"busy":"true"===u?"other":void 0}:t?.method==="POST"&&{runFailed:void 0},...null!=s&&{isContinuable:"false"!==s},...(o||r)&&{isLocked:r,isNetworkLocked:"network"===n},...o&&{isVoiceEnabled:"true"===i.headers.get("x-assistant-voice")},...h&&{earlierThreadId:c,...null!==c&&{hasOlderMessages:await U(i)}}}),i},_=async()=>({headers:await o().headers(),fetchClient:d}),g=t(()=>o().url,_),p=t(()=>`${o().url}/runs`,_),m=this._tools.map(e=>({...e,execute:(t,a)=>{if(!i.active)return E;let{manifest:s,error:n}=this._context.getAssistantSetup();return n||!s?{error:n?.message??"The assistant is disabled for this session."}:e.execute?.(t,a)}})),v=new e({threadId:`assistant:${n}`,connection:{...g,joinRun:p.joinRun},persistence:!0,history:{pageSize:50},tools:m,onMessagesChange:e=>{l({messages:e,hasOlderMessages:v.getHasOlderMessages()}),s&&e.length>0&&(s=!1,queueMicrotask(()=>{i.active&&void 0!==this._chat.value.runFailed&&!v.getIsLoading()&&v.reload()}))},onLoadingChange:e=>{let t=i.active&&this._chat.value.isLoading;if(l({isLoading:e}),!e&&$(v)){if(!i.active)return void y();t&&!this._panel.value.open&&this._patchPanel({hasUnreadReply:!0}),this._voiceReplyChat===S&&(this._voiceReplyChat=null,v.getError()||this._readVoiceReply(S))}},onCustomEvent:(e,t)=>{let a=e===c?u.safeParse(t):null;if(!a?.success)return;let{messageId:i,transcript:s}=a.data;v.setMessagesManually(v.getMessages().map(e=>e.id===i?{...e,parts:e.parts.flatMap(e=>"audio"===e.type?[{type:"text",content:s}]:[e]),metadata:{...e.metadata,spoken:!0}}:e))},onErrorChange:e=>{i.active&&e!==this._chat.value.error&&(!e||-1===this._findRefusedMessageIndex(S))&&(l({error:e,...e&&{runFailed:(e=>{let t=e?.code;if("string"==typeof t)return"provider_busy"===t?"busy":"other"})(e)}}),e&&this._context.domainServicesSelectors.getLogger().error("The assistant request failed",{status:this._chat.value.failedStatus},e))}}),f=!1,y=()=>{f||(f=!0,this._finishing.delete(S),v.dispose())},S={client:v,configurationId:n,generation:i,authorizedClient:r,getConnection:o,dispose:y};this._current=S,v.attach()};_retireChat=()=>{let e=this._current;return this._current=null,e&&(e.generation.active=!1),this._chain={},this._resuming=null,this._refused=null,this._voiceReplyChat=null,this._chat.value!==M&&this._chat.next(M),e};_releaseScreenshotUrls=()=>{for(let e of this._screenshotUrls.values())e.then(URL.revokeObjectURL,()=>void 0);this._screenshotUrls=new Map};_endChat=()=>{let e=this._retireChat();if(e){if(!e.client.getIsLoading()&&$(e.client))return void e.dispose();this._finishing.add(e)}}}
|
|
1
|
+
import{ChatClient as e,fetchServerSentEvents as t}from"@tanstack/ai-client";import{BehaviorSubject as i,firstValueFrom as a,race as s,timer as n}from"rxjs";import{filter as r,skip as o}from"rxjs/operators";import{match as l}from"ts-pattern";import{isShallowEqual as h}from"@salsita-ai/common/utils";import{ASSISTANT_TRANSCRIPT_EVENT as c,AssistantTranscriptEvent as u,assistantImageReference as d}from"@salsita-ai/contracts/assistant";import{AssistantRequestError as _}from"#package/client";import{applicationConfigComponent as g}from"#package/domain";import{generateShareLink as p}from"#package/react-sdk";import{AssistantSpeechPlayer as m}from"./assistant-speech-player.js";import{ChangeRecorder as f}from"./change-recorder.js";import{ComposerAttachments as v}from"./composer-attachments.js";import{createApplyClientTool as y,createQueryClientTool as S,runApplyTool as w,runQueryTool as x,toToolResult as b}from"./graphql-tools.js";import{rasterizeImage as C}from"./rasterize-image.js";import{isSpeakableReply as A}from"./speakable-reply.js";import{registerWebMcpTools as I,runShareLinkTool as M}from"./webmcp/index.js";let T=Object.freeze({messages:Object.freeze([]),isLoading:!1,error:void 0,failedStatus:void 0,retryAfterSeconds:void 0,runFailed:void 0,isContinuable:!0,isLocked:!1,isNetworkLocked:!1,isLoaded:!1,isVoiceEnabled:!1,isResuming:!1,earlierThreads:Object.freeze([]),earlierThreadId:null,isLoadingEarlierThread:!1,hasOlderMessages:!1,isLoadingOlderMessages:!1}),O=Object.freeze({top:0,right:0,bottom:0,left:0}),R=Object.freeze({kind:"transition"}),k=Object.freeze({open:!1,hasUnreadReply:!1,isInputFocused:!1}),L=Object.freeze({}),E=b({results:[],committed:!1,sideEffects:[],warnings:[],screenshots:new Map,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."}),$=e=>{if(e.getError())return!0;let t=e.getMessages().at(-1)?.parts.at(-1);return t?.type!=="tool-call"&&t?.type!=="tool-result"},U=async e=>{try{let t=await e.clone().json(),i=t?.page;return i?.truncated===!0&&"string"==typeof i.cursor&&""!==i.cursor}catch{return!1}},F=e=>{let t=e.map(e=>e.role).lastIndexOf("user");return e.slice(t+1).every(e=>0===e.parts.length)?t:-1},j=async e=>{let t=new Uint8Array(await e.arrayBuffer()),i="";for(let e=0;e<t.length;e+=32768)i+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(i)};export class AssistantSystem{_context;_tools;_chat=new i(T);_panel=new i(k);_annotationOverlay=new i(null);_imageView=new i(null);_composerAttachments=new v;_releaseInert=null;_annotationRun=null;_activation=null;_current=null;_finishing=new Set;_resuming=null;_refused=null;_firstAttempt=null;_chain={};_recorder;_recording=null;_applyToolCallIds=new WeakMap;_undoTipToolCallId=new i(void 0);_screenshotUrls=new Map;_player=new m({createAudio:()=>this._context.createAudio(),logError:(e,t)=>this._context.domainServicesSelectors.getLogger().error(e,{},t)});_voiceReplyChat=null;_toolDependencies;_webMcpRegistration=null;_webMcpManifest=null;constructor(e){this._context=e;let{configuratorExtensionSelectors:t,domainContextSelectors:i,domainServicesSelectors:a,getAssistantSetup:s}=e,n=(e,t)=>e?.find(e=>e.state===t)?.name??t;this._recorder=new f({maxEntities:30},{readers:{selectedEntityId:e=>i.getNavigationSystem().getActiveSelectionState(e),navigationState:e=>n(s().manifest?.navigation?.navigationStates,i.getNavigationSystem().getActiveNavigationState(e)),viewState:e=>n(s().manifest?.navigation?.viewStates,i.getNavigationSystem().getActiveViewState(e)),toolState:e=>n(s().manifest?.navigation?.toolStates,i.getNavigationSystem().getActiveToolState(e))},getExposedFields:()=>s().manifest?.fields??L,resolveLocalizable:e=>a.getResolveLocalizable()(e)}),this._toolDependencies={getGraphQLSystem:()=>t.getGraphQLSystem(),getStoreSystem:()=>i.getStoreSystem(),getActiveMode:()=>i.getActiveMode(),getIsViewMode:()=>i.getIsViewMode(),getApplicationConfig:()=>i.getComponentReader().readFirstRootComponent({componentTypes:[g]},this._committedState())?.state,generateShareLink:({shareStrategy:e,...t})=>p({configurationId:this._context.getConfigurationId(),shareStrategy:e,save:()=>this._context.domainApplicationContextSelectors.getConfigurationPersistSystem().save(),apiClient:this._context.getAuthorizedClient()},t)};let r=(e,t)=>{void 0!==t&&void 0!==e.preparedState&&(this._applyToolCallIds.set(e.preparedState,t),this._refreshUndoTip()),e.committed&&this._recorder.clear(this._committedState())};this._tools=[S(this._toolDependencies),y(this._toolDependencies,r)],i.getUndoSystem().tip$.subscribe(this._refreshUndoTip)}chat$=this._chat;panel$=this._panel;annotationOverlay$=this._annotationOverlay;imageView$=this._imageView;composerAttachments$=this._composerAttachments.attachments$;hasFreeAttachmentSlot$=this._composerAttachments.hasFreeSlot$;undoTipToolCallId$=this._undoTipToolCallId;playback$=this._player.playback$;muted$=this._player.muted$;getSessionManifest=()=>this._context.getAssistantSetup().manifest;initialize=()=>{let{committed:e}=this._context.domainContextSelectors.getStoreSystem().stateSlices;this._recording??=e.pipe(o(1)).subscribe(e=>{this._recorder.record(e),"reset"===e.kind&&this._refreshWebMcp()}),this._recorder.reset(e.value.state),this._endChat(),this._patchPanel(k),this._releaseScreenshotUrls(),this._player.reset(),this._closeAnnotationOverlay(),this.closeImageView(),this.clearAttachments(),this._activation&&(this._startClient(),this._registerWebMcp())};activate=()=>{this._endChat();let e={};return this._activation=e,this._startClient(),this._registerWebMcp(),()=>{this._activation===e&&(this._activation=null,this._endChat(),this._player.stop(),this._unregisterWebMcp())}};send=async(e,t=[],{onSent:i,onUnsent:a,audio:s}={})=>{if(!this._chat.value.isContinuable&&!await this.resume())return;let n=this._current;if(!n)return;let r={changes:this._recorder.take(this._committedState()),locale:this._context.domainServicesSelectors.getI18n().locale},o=()=>this._recorder.reset(this._committedState()),l=t.map(({blob:e})=>e),h=s?{type:"audio",source:{type:"data",value:await j(s),mimeType:s.type}}:null,c=!1,u=(a,s)=>{c||(c=!0,i?.());let n=t.flatMap((e,t)=>{let i=s[t];return"image"===e.type||void 0===i?[]:[{imageId:i,pins:e.pins,source:e.source}]});return this._voiceReplyChat=h?a:null,this._sendOn(a,this._messageContent(h?"":e,s,h),0===n.length?r:{...r,annotations:n})},d=e=>{if(!h||!e.generation.active||e.client.getIsLoading())return;let t=e.client.getMessages(),{error:i,failedStatus:s}=this._chat.value,n=F(t);if(i&&void 0!==s&&-1!==n){e.client.setMessagesManually(t.slice(0,n)),o(),422!==s&&a?.();return}t.some(e=>"user"===e.role&&e.parts.some(e=>"audio"===e.type))&&this.reloadThread()};this._firstAttempt=n;try{let e=0===l.length?[]:await this._uploadImages(n,l);if(null===e||!n.generation.active)return void o();if("refused"!==e){await u(n,e);let t=this._findRefusedMessageIndex(n);if(-1===t)return void d(n);this._refused={chat:n,index:t}}}finally{this._firstAttempt===n&&(this._firstAttempt=null)}if(!await this.resume()){c||o(),this._current&&d(this._current);return}let _=this._current,g=_?await this._uploadSuccessorImages(_,l):null;if(!_||null===g||"refused"===g||!_.generation.active){_&&"refused"===g&&this._reportUploadFailure(_,this._chat.value.error),c&&a?.(),o();return}await u(_,g),d(_)};annotate=async e=>null!==this._annotationOverlay.value?null:l(e).with({type:"attachment"},e=>this._annotateAttachment(e)).with({type:"view"},()=>this._annotateIntoSlot("view",e=>this._annotateView(e))).with({type:"image"},e=>this._annotateIntoSlot("image",t=>this._annotateImage(t,e))).exhaustive();_annotateIntoSlot=async(e,t)=>{let i,a=this._composerAttachments.reserveSlot();if(!a)return null;try{i=await this._runAnnotation(t)}finally{a()}return i&&this._composerAttachments.attach({type:"annotation",blob:i.blob,pins:i.pins,source:e})};viewAnnotation=e=>{if(null!==this._annotationOverlay.value)return;let t={kind:"viewer",annotation:e,close:()=>{this._annotationOverlay.value===t&&this._setAnnotationOverlay(null)}};this._setAnnotationOverlay(t)};viewImage=e=>{this._imageView.next(e)};closeImageView=()=>{null!==this._imageView.value&&this._imageView.next(null)};attach=e=>this._composerAttachments.attach({type:"image",blob:e});reserveAttachmentSlot=()=>this._composerAttachments.reserveSlot();restoreAttachments=e=>this._composerAttachments.restore(e);removeAttachment=e=>this._composerAttachments.remove(e);clearAttachments=()=>this._composerAttachments.clear();resume=async()=>{let e=this._current;if(!e)return!1;if(this._chat.value.isContinuable)return!0;if(this._resuming)return this._resuming;let t=this._compact(e).finally(()=>{this._resuming===t&&(this._resuming=null)});return this._resuming=t,t};loadScreenshotUrl=e=>{let t=this._screenshotUrls.get(e);if(t)return t;let i=this._current;if(!i)return Promise.reject(Error(`The screenshot ${e} cannot be read, because the assistant chat is not active. Open the assistant panel of the configuration first.`));let a=this._screenshotUrls,s=i.authorizedClient.getAssistantImage(i.configurationId,e).then(e=>URL.createObjectURL(e));return a.set(e,s),s.catch(()=>{a.get(e)===s&&a.delete(e)}),s};playReply=e=>{let t=this._current;t&&this._player.toggle({messageId:e,loadSpeech:()=>this._loadSpeech(t,e),isAutoplay:!1})};stopPlayback=()=>{this._player.stop()};setMuted=e=>{this._player.setMuted(e)};unlockPlayback=()=>{this._player.unlock()};loadEarlierThread=async()=>{let e=this._current,{earlierThreadId:t,isLoadingEarlierThread:i,hasOlderMessages:a}=this._chat.value;if(!e||null===t||i||a)return;let s=this._chain;this._chat.next({...this._chat.value,isLoadingEarlierThread:!0});try{let i=await e.authorizedClient.getAssistantEarlierThread(e.configurationId,t);if(this._chain!==s||this._chat.value.earlierThreadId!==t)return;let[a,...n]=this._chat.value.earlierThreads,r={threadId:t,messages:i.messages};this._chat.next({...this._chat.value,earlierThreads:a?.threadId===t?[r,...n]:[r,...this._chat.value.earlierThreads],earlierThreadId:i.previousThreadId})}catch(e){this._context.domainServicesSelectors.getLogger().warn("Could not load the earlier assistant conversation",{error:e})}finally{this._chain===s&&this._chat.next({...this._chat.value,isLoadingEarlierThread:!1})}};loadOlderMessages=async()=>{let e=this._current,{hasOlderMessages:t,isLoadingOlderMessages:i}=this._chat.value;if(e&&t&&!i){this._chat.next({...this._chat.value,isLoadingOlderMessages:!0});try{await e.client.loadOlderMessages()}catch(e){this._context.domainServicesSelectors.getLogger().warn("Could not load older assistant messages",{error:e})}finally{e===this._current&&this._chat.next({...this._chat.value,hasOlderMessages:e.client.getHasOlderMessages(),isLoadingOlderMessages:!1})}}};stop=async()=>{let e=this._current;if(!e)return;let t=e.client.getCurrentRunId();if(this._voiceReplyChat===e&&(this._voiceReplyChat=null),e.client.stop(),null!=t)try{let i=e.getConnection();await fetch(`${i.url}/runs/${encodeURIComponent(t)}/cancel`,{method:"POST",headers:await i.headers()})}catch(e){this._context.domainServicesSelectors.getLogger().warn("Could not cancel the assistant run on the server",{error:e})}};reloadThread=()=>{this._restartChat({regenerate:!1})};regenerate=()=>{this._restartChat({regenerate:!0})};_restartChat=({regenerate:e})=>{if(!this._activation)return;let t=this._retireChat();t?.client.stop(),t?.dispose(),this._recorder.reset(this._committedState()),this._startClient({regenerate:e})};undoToolCalls=e=>{let t=this._context.domainContextSelectors.getUndoSystem(),i=()=>{let t=this._findTipToolCallId();return void 0!==t&&e.has(t)};for(;i();)t.undo()};setOpen=e=>{this._patchPanel(e?{open:e,hasUnreadReply:!1}:{open:e,isInputFocused:!1})};setInputFocused=e=>{this._patchPanel({isInputFocused:e})};_setAnnotationOverlay=e=>{null!==e&&null===this._releaseInert&&(this._releaseInert=this._context.configuratorExtensionSelectors.getLayoutSystem().makeInert()),this._annotationOverlay.next(e),null===e&&(this._releaseInert?.(),this._releaseInert=null)};_annotateView=async e=>{let{getCameraControlSystem:t,getCanvasSystem:i}=this._context.configuratorExtensionSelectors,o=t(),l=i().r3fHandle$.value?.get().frameloop==="demand",h=()=>this._annotationRun===e;if(this._setAnnotationOverlay(R),await a(s(o.transitionState$.pipe(r(e=>"still"===e||"sleep"===e&&!l)),n(2e3))),!h())return this._setAnnotationOverlay(null),null;let c=()=>a(o.cameraOffsetSettled$.pipe(r(Boolean))),u=null;try{o.setCameraOffsetOverride(O),await c();let e=await this._context.configuratorExtensionSelectors.getImageRenderingSystem().captureView();h()&&(u=await this._edit(e))}catch(e){this._logAnnotationFailure("The configurator view could not be frozen for an annotation",e)}this._setAnnotationOverlay(R);try{o.setCameraOffsetOverride(null),await c()}finally{o.setCameraOffsetOverride(null),this._setAnnotationOverlay(null)}return u};_runAnnotation=async e=>{let t={},i=null;this._annotationRun=t;try{i=await e(t)}finally{this._annotationRun!==t?i=null:this._annotationRun=null}return i};_annotateAttachment=async({attachmentId:e,background:t})=>{let i=this._composerAttachments.attachments$.value.find(({id:t})=>t===e);if(!i||"annotation"===i.type)return null;let a=await this._runAnnotation(e=>this._annotateImage(e,{type:"image",image:i.blob,background:t}));return a&&this._composerAttachments.replace(e,{type:"annotation",blob:a.blob,pins:a.pins,source:"image"})};_annotationArea=()=>{let e=this._context.configuratorExtensionSelectors.getCanvasSystem().r3fHandle$.value?.get().gl.domElement,t=globalThis.devicePixelRatio||1;return e&&e.width>0&&e.height>0?{width:e.width,height:e.height}:{width:Math.max(1,Math.round(globalThis.innerWidth*t)),height:Math.max(1,Math.round(globalThis.innerHeight*t))}};_annotateImage=async(e,{image:t,background:i})=>{this._setAnnotationOverlay(R);try{let a=await C(t,i,this._annotationArea());return this._annotationRun===e?await this._edit(a):null}catch(e){return this._logAnnotationFailure("The image could not be drawn for an annotation",e),null}finally{this._setAnnotationOverlay(null)}};_edit=e=>{let{getCanvasSystem:t,getExportSystem:i}=this._context.configuratorExtensionSelectors,a=t().r3fHandle$.value,s=a?i().pauseFrameloop(a):()=>{};return new Promise(t=>{this._setAnnotationOverlay({kind:"editor",view:e,finish:t})}).finally(s)};_logAnnotationFailure=(e,t)=>{let i=t instanceof Error?t:Error(String(t));this._context.domainServicesSelectors.getLogger().error(e,{},i)};_closeAnnotationOverlay=()=>{let e=this._annotationOverlay.value;this._annotationRun=null,e?.kind==="editor"&&e.finish(null),e?.kind==="viewer"&&e.close()};_findRefusedMessageIndex=e=>{let{failedStatus:t,isContinuable:i}=this._chat.value;return this._firstAttempt===e&&e.generation.active&&409===t&&!i?F(e.client.getMessages()):-1};_messageContent=(e,t,i)=>0!==t.length||i?[...e?[{type:"text",content:e}]:[],...i?[i]:[],...t.map(e=>({type:"image",source:{type:"url",value:d(e)}}))]:e;_uploadImages=async(e,t)=>{if(0===t.length)return[];e.generation.active&&this._chat.next({...this._chat.value,error:void 0,failedStatus:void 0,runFailed:void 0});try{return(await Promise.all(t.map(t=>e.authorizedClient.uploadAssistantImage(e.configurationId,t)))).map(({imageId:e})=>e)}catch(i){let t=i instanceof Error?i:Error(String(i));if(t instanceof _&&t.threadNotContinuable)return e.generation.active&&this._chat.next({...this._chat.value,isContinuable:!1,error:t,failedStatus:t.status,runFailed:void 0}),"refused";return this._reportUploadFailure(e,t),null}};_uploadSuccessorImages=async(e,t)=>{if(0===t.length)return[];this._chat.next({...this._chat.value,isResuming:!0});try{return await this._uploadImages(e,t)}finally{e.generation.active&&this._chat.next({...this._chat.value,isResuming:!1})}};_reportUploadFailure=(e,t)=>{e.generation.active&&this._chat.next({...this._chat.value,error:t,failedStatus:t instanceof _?t.status:void 0,runFailed:void 0}),this._context.domainServicesSelectors.getLogger().error("The images of the assistant message could not be uploaded",{},t)};_sendOn=async(e,t,i)=>{let{client:a}=e;a.getIsLoading()||null===a.getResumeState()||a.stop();try{await a.sendMessage({content:t,metadata:i})}catch(i){let t=i instanceof Error?i:Error(String(i));e.generation.active&&this._chat.next({...this._chat.value,error:t,runFailed:void 0}),this._context.domainServicesSelectors.getLogger().error("The assistant message could not be sent",{},t)}};_compact=async e=>{this._chat.next({...this._chat.value,isResuming:!0,error:void 0,failedStatus:void 0,runFailed:void 0});try{let{previousThreadId:t}=await e.authorizedClient.compactAssistantThread(e.configurationId);if(!e.generation.active)return!1;let{messages:i,earlierThreads:a,earlierThreadId:s,isLoadingEarlierThread:n}=this._chat.value,r=this._refused?.chat===e?i.slice(0,this._refused.index):i,o=e.client.getHasOlderMessages()?t:s;return e.generation.active=!1,this._current=null,e.client.stop(),e.dispose(),this._chat.next({...T,earlierThreads:[...a,{threadId:t,messages:r}],earlierThreadId:o,isLoadingEarlierThread:n}),this._startClient(),!0}catch(i){let t=i instanceof Error?i:Error(String(i));if(t instanceof _&&409===t.status)return e.generation.active&&this.reloadThread(),!1;return e.generation.active&&this._chat.next({...this._chat.value,isResuming:!1,error:t,failedStatus:t instanceof _?t.status:void 0,runFailed:void 0,...t instanceof _&&t.locked&&{isLocked:!0,isNetworkLocked:t.networkLocked}}),this._context.domainServicesSelectors.getLogger().error("The assistant thread could not be resumed",{},t),!1}};_findTipToolCallId=()=>{let e=this._context.domainContextSelectors.getUndoSystem(),t=e.tip$.value?.committedState;return void 0!==t&&e.canUndo()?this._applyToolCallIds.get(t):void 0};_refreshUndoTip=()=>{let e=this._findTipToolCallId();e!==this._undoTipToolCallId.value&&this._undoTipToolCallId.next(e)};_loadSpeech=(e,t)=>e.authorizedClient.getAssistantReplySpeech(e.configurationId,t);_readVoiceReply=e=>{if(this._player.muted$.value||!this._chat.value.isVoiceEnabled)return;let t=e.client.getMessages(),i=t.map(e=>e.role).lastIndexOf("user")+1,a=t.slice(i).reverse().find(e=>e.parts.some(e=>"text"===e.type&&""!==e.content.trim()));a&&A(a)&&this._player.play({messageId:a.id,loadSpeech:()=>this._loadSpeech(e,a.id),isAutoplay:!0})};_committedState=()=>this._context.domainContextSelectors.getStoreSystem().stateSlices.committed.value.state;_patchPanel=e=>{let t={...this._panel.value,...e};h(t,this._panel.value)||this._panel.next(t)};_takeOverThread=e=>{for(let t of this._finishing)t.configurationId===e&&(t.client.stop(),t.dispose())};_registerWebMcp=()=>{this._unregisterWebMcp();let e=this._context.getWebMcpHost(),t=this._context.getConfigurationId(),{modelContext:i}=e,{manifest:a}=this._context.getAssistantSetup();if(this._webMcpManifest=a,!i||!a||!1===a.webmcp)return void e.settleLoad({configurationId:t,tools:!1});let s=new AbortController;this._webMcpRegistration=s,I({modelContext:i,manifest:a,run:{query:e=>x(this._toolDependencies,e,{screenshots:"inline",surface:"webmcp"}),apply:e=>w(this._toolDependencies,e,{screenshots:"inline",surface:"webmcp"}),share:e=>M(this._toolDependencies,e)},signal:s.signal}).then(()=>{this._webMcpRegistration===s&&e.settleLoad({configurationId:t,tools:!0})},i=>{this._webMcpRegistration===s&&(this._unregisterWebMcp(),e.settleLoad({configurationId:t,tools:!1})),this._context.domainServicesSelectors.getLogger().warn("The WebMCP tools could not be registered",{},i instanceof Error?i:void 0)})};_unregisterWebMcp=()=>{this._webMcpRegistration?.abort(),this._webMcpRegistration=null};_refreshWebMcp=()=>{this._activation&&this._context.domainContextSelectors.getIsInitialized()&&this._context.getAssistantSetup().manifest!==this._webMcpManifest&&this._registerWebMcp()};_startClient=({regenerate:i=!1}={})=>{let a={active:!0},s=i,n=this._context.getConfigurationId();this._takeOverThread(n);let r=this._context.getAuthorizedClient(),o=()=>{if(a.active){let{manifest:e,error:t}=this._context.getAssistantSetup();if(t)throw t;if(!e)throw Error("The assistant is disabled for this session.")}return r.getAssistantChatConnection(n)},l=e=>{if(!a.active)return;let t={...this._chat.value,...e};h(t,this._chat.value)||this._chat.next(t)},d=async(e,t)=>{let i,a=await fetch(e,t).finally(()=>l({isLoaded:!0})),s=a.headers.get("x-assistant-thread-continuable"),n=a.headers.get("x-assistant-locked"),r="true"===n||"network"===n,o=null!=s&&a.ok,h=o&&0===this._chat.value.earlierThreads.length,c=h?a.headers.get("x-assistant-previous-thread"):null,u=a.headers.get("x-assistant-run-failed");return l({failedStatus:a.ok?void 0:a.status,retryAfterSeconds:a.ok?void 0:null!==(i=a.headers.get("retry-after"))&&/^\d+$/.test(i.trim())?Number(i):void 0,...o?{runFailed:"busy"===u?"busy":"true"===u?"other":void 0}:t?.method==="POST"&&{runFailed:void 0},...null!=s&&{isContinuable:"false"!==s},...(o||r)&&{isLocked:r,isNetworkLocked:"network"===n},...o&&{isVoiceEnabled:"true"===a.headers.get("x-assistant-voice")},...h&&{earlierThreadId:c,...null!==c&&{hasOlderMessages:await U(a)}}}),a},_=async()=>({headers:await o().headers(),fetchClient:d}),g=t(()=>o().url,_),p=t(()=>`${o().url}/runs`,_),m=this._tools.map(e=>({...e,execute:(t,i)=>{if(!a.active)return E;let{manifest:s,error:n}=this._context.getAssistantSetup();return n||!s?{error:n?.message??"The assistant is disabled for this session."}:e.execute?.(t,i)}})),f=new e({threadId:`assistant:${n}`,connection:{...g,joinRun:p.joinRun},persistence:!0,history:{pageSize:50},tools:m,onMessagesChange:e=>{l({messages:e,hasOlderMessages:f.getHasOlderMessages()}),s&&e.length>0&&(s=!1,queueMicrotask(()=>{a.active&&void 0!==this._chat.value.runFailed&&!f.getIsLoading()&&f.reload()}))},onLoadingChange:e=>{let t=a.active&&this._chat.value.isLoading;if(l({isLoading:e}),!e&&$(f)){if(!a.active)return void y();t&&!this._panel.value.open&&this._patchPanel({hasUnreadReply:!0}),this._voiceReplyChat===S&&(this._voiceReplyChat=null,f.getError()||this._readVoiceReply(S))}},onCustomEvent:(e,t)=>{let i=e===c?u.safeParse(t):null;if(!i?.success)return;let{messageId:a,transcript:s}=i.data;f.setMessagesManually(f.getMessages().map(e=>e.id===a?{...e,parts:e.parts.flatMap(e=>"audio"===e.type?[{type:"text",content:s}]:[e]),metadata:{...e.metadata,spoken:!0}}:e))},onErrorChange:e=>{a.active&&e!==this._chat.value.error&&(!e||-1===this._findRefusedMessageIndex(S))&&(l({error:e,...e&&{runFailed:(e=>{let t=e?.code;if("string"==typeof t)return"provider_busy"===t?"busy":"other"})(e)}}),e&&this._context.domainServicesSelectors.getLogger().error("The assistant request failed",{status:this._chat.value.failedStatus},e))}}),v=!1,y=()=>{v||(v=!0,this._finishing.delete(S),f.dispose())},S={client:f,configurationId:n,generation:a,authorizedClient:r,getConnection:o,dispose:y};this._current=S,f.attach()};_retireChat=()=>{let e=this._current;return this._current=null,e&&(e.generation.active=!1),this._chain={},this._resuming=null,this._refused=null,this._voiceReplyChat=null,this._chat.value!==T&&this._chat.next(T),e};_releaseScreenshotUrls=()=>{for(let e of this._screenshotUrls.values())e.then(URL.revokeObjectURL,()=>void 0);this._screenshotUrls=new Map};_endChat=()=>{let e=this._retireChat();if(e){if(!e.client.getIsLoading()&&$(e.client))return void e.dispose();this._finishing.add(e)}}}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type $DomainEntity, type ActionTypes, type ConfiguratorBuilder, type CreateCustomPhoenixEntityElement, type CreateCustomPhoenixLayoutElement, type CreateGetThemeHandler, type CreateGetWebComponentOptionsHandler, type CreatePhoenixHandler, type DomainEntity, type IsCreateRecipeUpdate, type IsReplaceRecipeUpdate, type TransformerBuilder, type TransformerFactory, type UpdateFactory, getIdSequence } from '#package/domain';
|
|
2
|
-
import { type CreateAddEntityFab, type CreateAppLoader, type CreateCollectFrontendDataHandler, type CreateConfigurationNotFoundPage, type CreateConfiguratorErrorPage, type CreateDeleteEntityFab, type CreateFilterPublishedChunksHandler, type CreateNavigationHotspot, type CreateNotAuthenticatedPage, type CreateOnApplicationStartProvider, type CreateOnBackendDataReadyProvider, type CreateOnConfiguratorReadyProvider, type CreateOnFrontendDataReadyProvider, type CreateOnGoToIndexHandler, type CreateOnPresetLoadedHandler, type CreateOnPublishedDataReadyProvider, type CreateOnRoutingReadyProvider, type CreateOnSessionReadyProvider, type CreatePresetUi, type CreateSelectionHotspot, type CreateToolMenuFab, type IsAngleDimensionUpdate, type IsAttributeSelectionUpdate, type IsAttributeSwitchUpdate, type IsDeleteEntityUpdate, type IsDistanceDimensionUpdate, type IsGenericDimensionUpdate, type IsSwatchSelectionUpdate, type IsTextValueUpdate, type UseAccessService, type UseActiveNavigationState, type UseActiveToolState, type UseActiveViewState, type UseActiveViewports, type UseAnalyticsService, type UseAngleDimension, type UseAttributeSelection, type UseAttributeSwitch, type UseAuthenticatedClient, type UseAuthorizedClient, type UseBackendData, type UseChildEntitySelection, type UseComponent, type UseComponents, type UseComposition, type UseConfigurationId, type UseConfigurationSaveState, type UseConfiguratorMessages, type UseConfiguratorRouting, type UseControlViolations, type UseCookRecipes, type UseCookReplaceRecipes, type UseCookedRecipes, type UseCookedReplaceRecipes, type UseCreateAuthorizedClient, type UseDeleteEntity, type UseDeletedEntity, type UseDeselect, type UseDistanceDimension, type UseDistanceDimensionSelection, type UseDomainApplicationContext, type UseDomainApplicationProps, type UseDomainContext, type UseDomainEntityState, type UseEntityPrice, type UseEntitySelector, type UseFinalizeAction, type UseFinalizeActions, type UseFinalizeViolations, type UseFirstComponent, type UseFirstRootComponent, type UseFrontendData, type UseGenericDimension, type UseGroupedRecipeOptions, type UseHoveredDomainEntityId, type UseHoveredEntity, type UseHoveredEntityId, type UseIntegrationService, type UseIntegrationState, type UseIsFullscreenActive, type UseLoadedData, type UseLoadingState, type UseLocaleSwitch, type UseMapViolationHints, type UseNavigate, type UsePopNavigate, type UsePresetEmbeddedState, type UsePresetSelection, type UsePublishedData, type UsePushNavigate, type UseRecipeEmbeddedState, type UseReplaceEntityRecipeOptions, type UseRootComponents, type UseRootEntityId, type UseRootEntityPrice, type UseRootEntitySelector, type UseRootEntityState, type UseSelectEntity, type UseSelectParent, type UseSelectedDomainEntityId, type UseSelectedEntity, type UseSelectedEntityId, type UseSession, type UseSessionRole, type UseSessionService, type UseSetFullscreen, type UseSetViewState, type UseShareLinks, type UseSlice, type UseState, type UseStateValidity, type UseStepNavigation, type UseSwatchSelection, type UseSynchronizedSelector, type UseSynchronizedSelector$, type UseTabNavigation, type UseTextValue, type UseUndoRedo, type UseUpdateControl, type UseUpdatedControl, useActiveViewChildState, useGenerateShareLink, useLoadingStateValue, useLocalizable, useResolveLocalizable } from '#package/react-sdk';
|
|
2
|
+
import { type CreateAccessDeniedPage, type CreateAddEntityFab, type CreateAppLoader, type CreateCollectFrontendDataHandler, type CreateConfigurationNotFoundPage, type CreateConfiguratorErrorPage, type CreateDeleteEntityFab, type CreateFilterPublishedChunksHandler, type CreateNavigationHotspot, type CreateNotAuthenticatedPage, type CreateOnApplicationStartProvider, type CreateOnBackendDataReadyProvider, type CreateOnConfiguratorReadyProvider, type CreateOnFrontendDataReadyProvider, type CreateOnGoToIndexHandler, type CreateOnPresetLoadedHandler, type CreateOnPublishedDataReadyProvider, type CreateOnRoutingReadyProvider, type CreateOnSessionReadyProvider, type CreatePresetUi, type CreateSelectionHotspot, type CreateToolMenuFab, type IsAngleDimensionUpdate, type IsAttributeSelectionUpdate, type IsAttributeSwitchUpdate, type IsDeleteEntityUpdate, type IsDistanceDimensionUpdate, type IsGenericDimensionUpdate, type IsSwatchSelectionUpdate, type IsTextValueUpdate, type UseAccessService, type UseActiveNavigationState, type UseActiveToolState, type UseActiveViewState, type UseActiveViewports, type UseAnalyticsService, type UseAngleDimension, type UseAttributeSelection, type UseAttributeSwitch, type UseAuthenticatedClient, type UseAuthorizedClient, type UseBackendData, type UseChildEntitySelection, type UseComponent, type UseComponents, type UseComposition, type UseConfigurationId, type UseConfigurationSaveState, type UseConfiguratorMessages, type UseConfiguratorRouting, type UseControlViolations, type UseCookRecipes, type UseCookReplaceRecipes, type UseCookedRecipes, type UseCookedReplaceRecipes, type UseCreateAuthorizedClient, type UseDeleteEntity, type UseDeletedEntity, type UseDeselect, type UseDistanceDimension, type UseDistanceDimensionSelection, type UseDomainApplicationContext, type UseDomainApplicationProps, type UseDomainContext, type UseDomainEntityState, type UseEntityPrice, type UseEntitySelector, type UseFinalizeAction, type UseFinalizeActions, type UseFinalizeViolations, type UseFirstComponent, type UseFirstRootComponent, type UseFrontendData, type UseGenericDimension, type UseGroupedRecipeOptions, type UseHoveredDomainEntityId, type UseHoveredEntity, type UseHoveredEntityId, type UseIntegrationService, type UseIntegrationState, type UseIsFullscreenActive, type UseLoadedData, type UseLoadingState, type UseLocaleSwitch, type UseMapViolationHints, type UseNavigate, type UsePopNavigate, type UsePresetEmbeddedState, type UsePresetSelection, type UsePublishedData, type UsePushNavigate, type UseRecipeEmbeddedState, type UseReplaceEntityRecipeOptions, type UseRootComponents, type UseRootEntityId, type UseRootEntityPrice, type UseRootEntitySelector, type UseRootEntityState, type UseSelectEntity, type UseSelectParent, type UseSelectedDomainEntityId, type UseSelectedEntity, type UseSelectedEntityId, type UseSession, type UseSessionRole, type UseSessionService, type UseSetFullscreen, type UseSetViewState, type UseShareLinks, type UseSignIn, type UseSlice, type UseState, type UseStateValidity, type UseStepNavigation, type UseSwatchSelection, type UseSynchronizedSelector, type UseSynchronizedSelector$, type UseTabNavigation, type UseTextValue, type UseUndoRedo, type UseUpdateControl, type UseUpdatedControl, useActiveViewChildState, useGenerateShareLink, useLoadingStateValue, useLocalizable, useResolveLocalizable } from '#package/react-sdk';
|
|
3
3
|
import { type CreatePhoenixIconSet } from '#package/ui-sdk';
|
|
4
4
|
import { type UseConfiguratorExtensions, createActionFactory } from '../application-runtime/index.js';
|
|
5
5
|
import { usePreview, usePropertyPageStack, usePropertyPageState } from '../configurator-context/index.js';
|
|
@@ -181,6 +181,11 @@ export interface ConfiguratorInterface<ENTITIES extends DomainEntity<string>, AL
|
|
|
181
181
|
* Creates a custom page shown when session authentication fails.
|
|
182
182
|
*/
|
|
183
183
|
createNotAuthenticatedPage: CreateNotAuthenticatedPage;
|
|
184
|
+
/**
|
|
185
|
+
* Creates the page shown when a Studio-account sign-in is refused: the account is not invited, or the project's
|
|
186
|
+
* signed-in handler refused it. Replaces the built-in access-denied page of the Studio-account sign-in page.
|
|
187
|
+
*/
|
|
188
|
+
createAccessDeniedPage: CreateAccessDeniedPage;
|
|
184
189
|
/**
|
|
185
190
|
* Creates the page shown when a configuration cannot be loaded or opened, replacing the built-in
|
|
186
191
|
* `ConfigurationNotFoundPage`.
|
|
@@ -261,6 +266,11 @@ export interface ConfiguratorInterface<ENTITIES extends DomainEntity<string>, AL
|
|
|
261
266
|
* Internal hook to access the session service in the initialization code.
|
|
262
267
|
*/
|
|
263
268
|
useSessionService: UseSessionService;
|
|
269
|
+
/**
|
|
270
|
+
* The Studio-account sign-in: its state (signing in, refused, failed), the person signed in, and `signIn` and
|
|
271
|
+
* `signOut`, for a project's own sign-in page or account control.
|
|
272
|
+
*/
|
|
273
|
+
useSignIn: UseSignIn;
|
|
264
274
|
/**
|
|
265
275
|
* Domain context with all typesd domain systems
|
|
266
276
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createCustomPhoenixEntityElement as e,createCustomPhoenixLayoutElement as t,createGetThemeHandler as o,createGetWebComponentOptionsHandler as r,createPhoenixHandler as i,createTransformer as n,createTransformerBuilder as s,createUpdateFactory as m,getIdSequence as a,isCreateEntityUpdate as p,isReplaceEntityUpdate as d}from"#package/domain";import{
|
|
1
|
+
import{createCustomPhoenixEntityElement as e,createCustomPhoenixLayoutElement as t,createGetThemeHandler as o,createGetWebComponentOptionsHandler as r,createPhoenixHandler as i,createTransformer as n,createTransformerBuilder as s,createUpdateFactory as m,getIdSequence as a,isCreateEntityUpdate as p,isReplaceEntityUpdate as d}from"#package/domain";import{createAccessDeniedPage as c,createAddEntityFab as u,createAppLoader as f,createCollectFrontendDataHandler as l,createConfigurationNotFoundPage as g,createConfiguratorErrorPage as j,createDeleteEntityFab as x,createFilterPublishedChunksHandler as k,createNavigationHotspot as y,createNotAuthenticatedPage as A,createOnApplicationStartProvider as I,createOnBackendDataReadyProvider as C,createOnConfiguratorReadyProvider as S,createOnFrontendDataReadyProvider as w,createOnGoToIndexHandler as E,createOnPresetLoadedHandler as b,createOnPublishedDataReadyProvider as q,createOnRoutingReadyProvider as B,createOnSessionReadyProvider as P,createPresetUi as R,createSelectionHotspot as U,createToolMenuFab as h,isAngleDimensionUpdate as v,isAttributeSelectionUpdate as z,isAttributeSwitchUpdate as D,isDeleteEntityUpdate as F,isDistanceDimensionUpdate as G,isGenericDimensionUpdate as H,isSwatchSelectionUpdate as J,isTextValueUpdate as K,useAccessService as L,useActiveNavigationState as M,useActiveToolState as N,useActiveViewChildState as O,useActiveViewState as Q,useActiveViewports as T,useAnalyticsService as V,useAngleDimension as W,useAttributeSelection as X,useAttributeSwitch as Y,useAuthenticatedClient as Z,useAuthorizedClient as $,useBackendData as _,useChildEntitySelection as ee,useCommittedSlice as et,useCommittedState as eo,useComponent as er,useComponents as ei,useComposition as en,useConfigurationId as es,useConfigurationSaveState as em,useConfiguratorMessages as ea,useConfiguratorRouting as ep,useControlViolations as ed,useCookRecipes as ec,useCookReplaceRecipes as eu,useCookedRecipes as ef,useCookedReplaceRecipes as el,useCreateAuthorizedClient as eg,useDeleteEntity as ej,useDeletedEntity as ex,useDeselect as ek,useDistanceDimension as ey,useDistanceDimensionSelection as eA,useDomain as eI,useDomainApplication as eC,useDomainApplicationProps as eS,useDomainEntityRenderedState as ew,useDomainEntityState as eE,useEntityPrice as eb,useEntitySelector as eq,useFinalizeAction as eB,useFinalizeActions as eP,useFinalizeViolations as eR,useFirstComponent as eU,useFirstRenderedComponent as eh,useFirstRootComponent as ev,useFirstRootRenderedComponent as ez,useFrontendData as eD,useGenerateShareLink as eF,useGenericDimension as eG,useGroupedRecipeOptions as eH,useHoveredDomainEntityId as eJ,useHoveredEntity as eK,useHoveredEntityId as eL,useIntegrationService as eM,useIntegrationState as eN,useIsFullscreenActive as eO,useLoadedData as eQ,useLoadingState as eT,useLoadingStateValue as eV,useLocaleSwitch as eW,useLocalizable as eX,useMapViolationHints as eY,useNavigate as eZ,usePopNavigate as e$,usePresetEmbeddedState as e_,usePresetSelection as e0,usePublishedData as e1,usePushNavigate as e2,useRecipeEmbeddedState as e3,useRenderedComponent as e4,useRenderedComponents as e5,useRenderedEntitySelector as e6,useRenderedRootEntitySelector as e7,useRenderedSelector as e8,useRenderedSelector$ as e9,useRenderedSlice as te,useRenderedState as tt,useReplaceEntityRecipeOptions as to,useResolveLocalizable as tr,useRootComponents as ti,useRootEntityId as tn,useRootEntityPrice as ts,useRootEntityRenderedId as tm,useRootEntityRenderedState as ta,useRootEntitySelector as tp,useRootEntityState as td,useRootRenderedComponents as tc,useSelectEntity as tu,useSelectParent as tf,useSelectedDomainEntityId as tl,useSelectedEntity as tg,useSelectedEntityId as tj,useSession as tx,useSessionRole as tk,useSessionService as ty,useSetFullscreen as tA,useSetViewState as tI,useShareLinks as tC,useSignIn as tS,useStateValidity as tw,useStepNavigation as tE,useStoreSelector as tb,useStoreSelector$ as tq,useSwatchSelection as tB,useTabNavigation as tP,useTextValue as tR,useUndoRedo as tU,useUpdateControl as th,useUpdatedControl as tv}from"#package/react-sdk";import{createPhoenixIconSet as tz}from"#package/ui-sdk";import{createActionFactory as tD,useConfigurator as tF}from"../application-runtime/index.js";import{usePreview as tG,usePropertyPageStack as tH,usePropertyPageState as tJ}from"../configurator-context/index.js";import{useCloseAction as tK}from"../integration/index.js";import{createGetTextureProcessingMapHandler as tL}from"../scene/index.js";import{useUpdateEntityObjectSelection as tM}from"../scene/scene-entity/drag-and-drop/use-updated-selection.js";import{useAssistantPanel as tN,useMeasurements as tO,useToolbarActions as tQ}from"../toolbar-actions/index.js";import{LayoutSlots as tT,createCanvasLoader as tV,createLayoutAdminUi as tW,createLayoutCustomOwnerUi as tX,createLayoutCustomReadUi as tY,createLayoutDialog as tZ,createLayoutFooter as t$,createLayoutToolbarDesktop as t_,createLayoutToolbarDesktopFullScreen as t0,createLayoutToolbarReadDesktop as t1,createLayoutToolbarReadDesktopFullScreen as t2,createLayoutUserUi as t3,createToolbarHelp as t4,useAssistantComposer as t5,useAssistantThread as t6,useSceneSafeArea as t7}from"../ui/index.js";import{createPresetDeviceNotSupported as t8,createPresetPageAction as t9}from"../ui/preset-layout/PresetUi.js";import{useResetCamera as oe}from"./use-reset-camera.js";export const createConfiguratorInterface=ot=>({updates:m(),getIdSequence:a,createGetWebComponentOptionsHandler:r,createGetThemeHandler:o,createPhoenixHandler:i,createCustomPhoenixEntityElement:e,createCustomPhoenixLayoutElement:t,createPhoenixIconSet:tz,createGetTextureProcessingMapHandler:tL,createCollectFrontendDataHandler:l,createFilterPublishedChunksHandler:k,createOnGoToIndexHandler:E,createOnApplicationStartProvider:I,createOnSessionReadyProvider:P,createOnPublishedDataReadyProvider:q,createOnFrontendDataReadyProvider:w,createOnBackendDataReadyProvider:C,createOnRoutingReadyProvider:B,createOnConfiguratorReadyProvider:S,createOnPresetLoadedHandler:b,createPresetUi:R,createPresetPageAction:t9,createPresetDeviceNotSupported:t8,createLayoutFooter:t$,createAppLoader:f,createCanvasLoader:tV,createLayoutDialog:tZ,createLayoutToolbarDesktop:t_,createLayoutToolbarDesktopFullScreen:t0,createLayoutToolbarReadDesktop:t1,createLayoutToolbarReadDesktopFullScreen:t2,createLayoutCustomOwnerUi:tX,createLayoutCustomReadUi:tY,createLayoutAdminUi:tW,createLayoutUserUi:t3,createToolbarHelp:t4,createNotAuthenticatedPage:A,createAccessDeniedPage:c,createConfigurationNotFoundPage:g,createConfiguratorErrorPage:j,createAddEntityFab:u,createDeleteEntityFab:x,createSelectionHotspot:U,createNavigationHotspot:y,createToolMenuFab:h,createTransformer:n,transformerBuilder:s(),useAnalytics:V,useAuthenticatedClient:Z,useAuthorizedClient:$,useCreateAuthorizedClient:eg,useAccessService:L,useConfigurationId:es,useSession:tx,useSessionRole:tk,useSessionService:ty,useSignIn:tS,useDomain:eI,useDomainApplication:eC,useConfigurator:tF,implementActions:tD(),useConfiguratorRouting:ep,usePresetSelection:e0,usePublishedData:e1,useFrontendData:eD,useBackendData:_,useDomainApplicationProps:eS,useLoadedData:eQ,useIntegrationService:eM,useIntegrationState:eN,usePresetEmbeddedState:e_,useRecipeEmbeddedState:e3,useCommittedSlice:et,useRenderedSlice:te,useCommittedState:eo,useRenderedState:tt,useStoreSelector:tb,useRenderedSelector:e8,useStoreSelector$:tq,useRenderedSelector$:e9,useEntitySelector:eq,useRenderedEntitySelector:e6,useRootEntitySelector:tp,useRenderedRootEntitySelector:e7,useStateValidity:tw,useMapViolationHints:eY,useNavigate:eZ,usePopNavigate:e$,usePushNavigate:e2,useControlViolations:ed,useFinalizeViolations:eR,useConfiguratorMessages:ea,useConfigurationSaveState:em,useFinalizeAction:eB,useFinalizeActions:eP,useComponent:er,useRenderedComponent:e4,useComponents:ei,useRenderedComponents:e5,useFirstComponent:eU,useFirstRenderedComponent:eh,useRootComponents:ti,useRootRenderedComponents:tc,useFirstRootComponent:ev,useFirstRootRenderedComponent:ez,useEntityState:eE,useEntityRenderedState:ew,useRootEntityState:td,useRootEntityRenderedState:ta,useRootEntityId:tn,useRootEntityRenderedId:tm,useEntityPrice:eb,useRootEntityPrice:ts,useSelectedEntity:tg,useSelectedEntityId:tj,useSelectedDomainEntityId:tl,useSelectEntity:tu,useDeselect:ek,useSelectParent:tf,useHoveredEntity:eK,useHoveredEntityId:eL,useHoveredDomainEntityId:eJ,useActiveNavigationState:M,useActiveViewState:Q,useActiveViewChildState:O,useSetViewState:tI,useActiveToolState:N,useIsFullscreenActive:eO,useSetFullscreen:tA,useResetCamera:oe,useUndoRedo:tU,useTabNavigation:tP,useStepNavigation:tE,useSceneSafeArea:t7,useActiveViewports:T,usePreview:tG,useCloseAction:tK,useIsCloningAllowed:tT.useIsCloningAllowed,useResolveLocalizable:tr,useLocalizable:eX,useToolbarActions:tQ,useMeasurements:tO,useLocaleSwitch:eW,useShareLinks:tC,useAssistantPanel:tN,useAssistantThread:t6,useAssistantComposer:t5,useComposition:en,useUpdateControl:th,useUpdatedControl:tv,useCookRecipes:ec,useCookedRecipes:ef,useCookReplaceRecipes:eu,useCookedReplaceRecipes:el,useDeleteEntity:ej,useDeletedEntity:ex,useSwatchSelection:tB,useTextValue:tR,useAttributeSelection:X,useAttributeSwitch:Y,useDistanceDimension:ey,useDistanceDimensionSelection:eA,useGenericDimension:eG,useAngleDimension:W,useChildEntitySelection:ee,useGroupedRecipeOptions:eH,useReplaceEntityRecipeOptions:to,useUpdateEntityObjectSelection:tM,useGenerateShareLink:eF,useLoadingState:eT,useLoadingStateValue:eV,usePropertyPageStack:tH,usePropertyPageState:tJ,isCreateEntityUpdate:p,isReplaceEntityUpdate:d,isDeleteEntityUpdate:F,isAngleDimensionUpdate:v,isDistanceDimensionUpdate:G,isGenericDimensionUpdate:H,isAttributeSelectionUpdate:z,isAttributeSwitchUpdate:D,isTextValueUpdate:K,isSwatchSelectionUpdate:J});
|
package/dist/docs/index.json
CHANGED
|
@@ -107,47 +107,16 @@ Setting up admin functionality requires configuring authentication, domain model
|
|
|
107
107
|
|
|
108
108
|
### Authentication Setup
|
|
109
109
|
|
|
110
|
-
Admin requires authentication that can assign admin roles to users.
|
|
111
|
-
|
|
112
|
-
See [Clerk Sign-In](?path=/docs/phoenix-clerk-sign-in--docs) for the inline Admin fallback page, generated publishable key, method configuration, and account-switching behavior.
|
|
113
|
-
|
|
114
|
-
**Enable Auth Hook**: In phx-cli projects, authentication is configured in `spec/application.yaml`:
|
|
110
|
+
Admin requires authentication that can assign admin roles to users. The access mode in `spec/application.yaml` sets it up, and the project writes no auth code:
|
|
115
111
|
|
|
116
112
|
```yaml
|
|
117
113
|
# spec/application.yaml
|
|
118
|
-
|
|
119
|
-
useClerk: true
|
|
120
|
-
```
|
|
121
|
-
|
|
122
|
-
phx-cli generates the frontend and webhook configuration in `.phoenix/` from your spec files, so the project writes no configuration file for it.
|
|
123
|
-
|
|
124
|
-
**Webhook Auth Handler**: Create an auth handler for Clerk integration:
|
|
125
|
-
|
|
126
|
-
```typescript
|
|
127
|
-
// src/webhooks/handlers/auth-handler.ts
|
|
128
|
-
export const authHandler = phx.webhooks.authHandlerBuilder
|
|
129
|
-
.withClerkSessionHandler() // Handles inline Clerk session exchange
|
|
130
|
-
.withClerkCodeHandler() // Handles Clerk OAuth integration
|
|
131
|
-
.withClerkRefreshHandler() // Handles Clerk token refresh
|
|
132
|
-
.withAnonymousHandler(async () => {
|
|
133
|
-
// Handle anonymous access (typically not allowed for admin)
|
|
134
|
-
return {
|
|
135
|
-
success: false,
|
|
136
|
-
}
|
|
137
|
-
})
|
|
138
|
-
.build()
|
|
114
|
+
access: public # The default; invited and public-with-sign-in work the same for the admin
|
|
139
115
|
```
|
|
140
116
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
Register the auth handler in the webhook entry, the default export of `src/webhooks/index.ts`:
|
|
117
|
+
In `public`, `invited` and `public-with-sign-in` the admin signs in with a Studio account, and the person's Admin or Superadmin grant in the project opens it (see [Studio-account sign-in](?path=/docs/phoenix-webhooks--docs#studio-account-sign-in)). With `access: legacy-clerk` the built-in Clerk handlers sign the admin in instead, with credentials from the workspace's Clerk settings in Studio; see [Clerk Sign-In](?path=/docs/phoenix-clerk-sign-in--docs) for the inline Admin fallback page, generated publishable key, method configuration, and account-switching behavior. With `access: custom` the project's own code handler grants the admin role (see [Webhooks - Auth Hook](?path=/docs/phoenix-webhooks--docs#auth-hook)).
|
|
144
118
|
|
|
145
|
-
|
|
146
|
-
// src/webhooks/index.ts
|
|
147
|
-
import { authHandler } from './handlers/auth-handler.js'
|
|
148
|
-
|
|
149
|
-
export default phx.webhooks.webhookBuilder.withAuthHook(authHandler).build()
|
|
150
|
-
```
|
|
119
|
+
phx-cli generates the frontend and webhook configuration in `.phoenix/` from your spec files, so the project writes no configuration file for it.
|
|
151
120
|
|
|
152
121
|
Admin publishing needs no builder: the SDK adds the Admin finalization to the webhook itself (see [Webhook Integration](#webhook-integration)).
|
|
153
122
|
|
|
@@ -365,13 +334,9 @@ Admin finalization needs nothing in your webhook entry: the SDK builds it and ad
|
|
|
365
334
|
|
|
366
335
|
```typescript
|
|
367
336
|
// src/webhooks/index.ts
|
|
368
|
-
import { authHandler } from './handlers/auth-handler.js'
|
|
369
337
|
import { configuratorFinalizeHandler } from './handlers/configurator-finalize-handler.js'
|
|
370
338
|
|
|
371
|
-
export default phx.webhooks.webhookBuilder
|
|
372
|
-
.withAuthHook(authHandler)
|
|
373
|
-
.withConfiguratorFinalize(configuratorFinalizeHandler)
|
|
374
|
-
.build()
|
|
339
|
+
export default phx.webhooks.webhookBuilder.withConfiguratorFinalize(configuratorFinalizeHandler).build()
|
|
375
340
|
```
|
|
376
341
|
|
|
377
342
|
You customize publishing only with handlers default-exported from files in `src/handlers/`, which join the webhook automatically: `phx.domain.admin.createMapPublishedRevisionDataHandler` or `phx.domain.admin.createMapPublishedChunkedDataHandler` for the published data, and `phx.domain.admin.createDataRowValidatorHandler` and `phx.domain.admin.createSheetValidatorHandler` for validating manual and connected data.
|
|
@@ -1,26 +1,30 @@
|
|
|
1
1
|
# Clerk Sign-In
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> **Legacy.** Clerk sign-in is the `legacy-clerk` access mode, for workspaces Salsita set up with Clerk. A workspace with Studio accounts signs people in with `invited` or `public-with-sign-in` (see [Webhooks — Studio-account sign-in](?path=/docs/phoenix-webhooks--docs#studio-account-sign-in)).
|
|
4
|
+
|
|
5
|
+
Phoenix projects that use Clerk can replace the redirect-only OAuth entry point with an inline sign-in page for the Configurator, Admin, or both. The integration is opt-in through `@salsita-ai/sdk/extras/clerk`; projects in another access mode than `legacy-clerk` do not install or bundle Clerk React.
|
|
4
6
|
|
|
5
7
|
The page supports email and password (including password reset), Google OAuth, and discoverable passkeys. Methods render in the order supplied. After Clerk authenticates the browser, Phoenix exchanges the short-lived Clerk session token for the normal one-time authorization code and session without reloading the application. The existing server OAuth redirect remains the fallback if the in-place exchange cannot complete.
|
|
6
8
|
|
|
7
9
|
## Enable Clerk
|
|
8
10
|
|
|
9
|
-
Set
|
|
11
|
+
Set the Legacy Clerk access mode in the application spec:
|
|
10
12
|
|
|
11
13
|
```yaml
|
|
12
14
|
# spec/application.yaml
|
|
13
|
-
|
|
14
|
-
useClerk: true
|
|
15
|
+
access: legacy-clerk
|
|
15
16
|
```
|
|
16
17
|
|
|
17
18
|
`@clerk/clerk-react` then becomes a dependency the project declares: run `phoenix deps` through your package manager (for example `pnpm phoenix deps`) and install to add it, because `phoenix sync`, `dev` and `build` stop while it is missing. `phoenix sync` generates typed Clerk environment readers. In a project on the legacy pipeline (see [Current and legacy project tooling](?path=/docs/phoenix-phoenix-cli--docs#current-and-legacy-project-tooling)), `phoenix sync` adds the dependency itself. `phoenix deployment:prepare-local` writes the deployment's public `CLERK_PUBLISHABLE_KEY` to `.env.generated`; application source should read it from `phx.frontendEnv`, not hardcode a key.
|
|
18
19
|
|
|
19
20
|
## Configure the auth webhook
|
|
20
21
|
|
|
21
|
-
|
|
22
|
+
With `access: legacy-clerk` the webhook's auth hook already has the Clerk session, code and refresh handlers and lets visitors in, with or without `src/webhooks/index.ts`, so there is nothing to write.
|
|
23
|
+
|
|
24
|
+
A project that must refuse visitors, or add its own handlers beside Clerk, still assembles the hook with the deprecated builder, for which parsing reports `AUTH_HOOK_DEPRECATED`:
|
|
22
25
|
|
|
23
26
|
```typescript
|
|
27
|
+
// src/webhooks/index.ts
|
|
24
28
|
const authHandler = phx.webhooks.authHandlerBuilder
|
|
25
29
|
.withClerkSessionHandler()
|
|
26
30
|
.withClerkCodeHandler()
|
|
@@ -19,7 +19,7 @@ This approach also enables seamless integration with third-party systems. For ex
|
|
|
19
19
|
|
|
20
20
|
## Session Data
|
|
21
21
|
|
|
22
|
-
Session data contains user-specific information that persists during the user's session but doesn't affect the final configuration. Session data is populated
|
|
22
|
+
Session data contains user-specific information that persists during the user's session but doesn't affect the final configuration. Session data is populated by the auth hook during the authentication process and is part of the signed session token, making it secure and trustworthy.
|
|
23
23
|
|
|
24
24
|
Session data is commonly used to store user contextual information like user roles, tags, and user-level access tokens to third-party services. Since it's signed by the backend, expressions can trust this data for authorization and personalization decisions.
|
|
25
25
|
|
|
@@ -38,36 +38,34 @@ sessionData:
|
|
|
38
38
|
|
|
39
39
|
Session data properties must be optional because admin and preset sessions can carry an empty custom payload. Authentication handlers can still populate the declared fields for user sessions; expressions should handle their absence when they also run in admin or preset contexts.
|
|
40
40
|
|
|
41
|
-
**
|
|
41
|
+
**Code Handler Example**, for a project with `access: custom` (in the Studio-account modes the identity fields come from the Studio account, and a [visitor handler](?path=/docs/phoenix-webhooks--docs#auth-hook) adds data for visitors):
|
|
42
42
|
|
|
43
43
|
```typescript
|
|
44
|
-
// src/
|
|
45
|
-
export
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
})
|
|
51
|
-
|
|
52
|
-
if (!response.ok) {
|
|
53
|
-
logger.warn(`The user API refused the access token with status ${response.status}.`)
|
|
54
|
-
|
|
55
|
-
return { success: false }
|
|
56
|
-
}
|
|
44
|
+
// src/handlers/code.ts
|
|
45
|
+
export default phx.access.createCodeHandler(async ({ accessToken }) => {
|
|
46
|
+
// USER_API_URL is declared under `env.webhook` in a spec file
|
|
47
|
+
const response = await fetch(`${phx.webhooksEnv.USER_API_URL}/me`, {
|
|
48
|
+
headers: { authorization: `Bearer ${accessToken}` },
|
|
49
|
+
})
|
|
57
50
|
|
|
58
|
-
|
|
51
|
+
if (!response.ok) {
|
|
52
|
+
console.warn(`The user API refused the access token with status ${response.status}.`)
|
|
59
53
|
|
|
60
|
-
return {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
54
|
+
return { success: false }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const userInfo: { readonly id: string; readonly role: 'user' | 'admin' } = await response.json()
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
success: true,
|
|
61
|
+
data: {
|
|
62
|
+
accessToken,
|
|
63
|
+
userRole: userInfo.role,
|
|
64
|
+
},
|
|
65
|
+
role: userInfo.role,
|
|
66
|
+
userId: userInfo.id,
|
|
67
|
+
}
|
|
68
|
+
})
|
|
71
69
|
```
|
|
72
70
|
|
|
73
71
|
**Usage in Expressions**:
|
|
@@ -514,12 +512,10 @@ export const backendDataHandler: FetchBackendData = async ({ frontendData }, { l
|
|
|
514
512
|
|
|
515
513
|
```typescript
|
|
516
514
|
// src/webhooks/index.ts
|
|
517
|
-
import { authHandler } from './handlers/auth-handler.js'
|
|
518
515
|
import { backendDataHandler } from './handlers/backend-data-handler.js'
|
|
519
516
|
import { configuratorFinalizeHandler } from './handlers/configurator-finalize-handler.js'
|
|
520
517
|
|
|
521
518
|
export default phx.webhooks.webhookBuilder
|
|
522
|
-
.withAuthHook(authHandler)
|
|
523
519
|
.withFetchBackendData(backendDataHandler)
|
|
524
520
|
.withConfiguratorFinalize(configuratorFinalizeHandler)
|
|
525
521
|
.build()
|
|
@@ -20,7 +20,7 @@ A **Customer** represents an organization or business entity using Phoenix Platf
|
|
|
20
20
|
|
|
21
21
|
- Unique customer ID and name
|
|
22
22
|
- Customer slug that becomes their subdomain (e.g., `customer.studio.salsita.ai`)
|
|
23
|
-
- Authentication settings
|
|
23
|
+
- Authentication settings: Studio accounts, or the legacy Clerk integration for workspaces Salsita set up with Clerk
|
|
24
24
|
- OAuth provider configurations for external integrations
|
|
25
25
|
|
|
26
26
|
Customers serve as the top-tier security boundary. All data, configurations, and deployments are isolated at the customer boundary, ensuring complete data separation between different organizations.
|
|
@@ -60,6 +60,7 @@ interface Deployment {
|
|
|
60
60
|
isActive: boolean
|
|
61
61
|
allowedOrigins: AllowedOrigin[]
|
|
62
62
|
useAuthHook: boolean
|
|
63
|
+
accessMode: AccessMode | null // null for a deployment registered by an SDK older than `access`
|
|
63
64
|
webhooks: Webhook[]
|
|
64
65
|
privateS3Bucket: PrivateS3Bucket
|
|
65
66
|
privateDeploymentResourcesPath: PrivateDeploymentResourcesPath
|
|
@@ -219,8 +220,7 @@ Define your deployment settings in the spec file:
|
|
|
219
220
|
# spec/application.yaml
|
|
220
221
|
application:
|
|
221
222
|
name: my-configurator
|
|
222
|
-
|
|
223
|
-
useAuthHook: true
|
|
223
|
+
access: custom
|
|
224
224
|
finalize:
|
|
225
225
|
collectData: false
|
|
226
226
|
acl:
|
|
@@ -206,7 +206,6 @@ When chunked publishing is configured, both the finalize and `fetchBackendData`
|
|
|
206
206
|
|
|
207
207
|
```typescript
|
|
208
208
|
export default phx.webhooks.webhookBuilder
|
|
209
|
-
.withAuthHook(authHandler)
|
|
210
209
|
.withConfiguratorFinalize(configuratorFinalizeHandler)
|
|
211
210
|
.withFetchBackendData(backendDataHandler)
|
|
212
211
|
.build()
|
|
@@ -15,12 +15,12 @@ When the configurator is integrated into a third-party system (`handoff` or `hea
|
|
|
15
15
|
|
|
16
16
|
## Prerequisites
|
|
17
17
|
|
|
18
|
-
The
|
|
18
|
+
The project uses `access: custom`. You need two values:
|
|
19
19
|
|
|
20
|
-
| Value | Description
|
|
21
|
-
| ----------- |
|
|
22
|
-
| `clientId` |
|
|
23
|
-
| `serverUrl` | Base URL of the configurator server
|
|
20
|
+
| Value | Description |
|
|
21
|
+
| ----------- | --------------------------------------------------------------------------------------------------------------------- |
|
|
22
|
+
| `clientId` | The configurator environment's id: `ENVIRONMENT_ID`, which the configurator reads as `phx.frontendEnv.ENVIRONMENT_ID` |
|
|
23
|
+
| `serverUrl` | Base URL of the configurator server, the configurator's `SERVER_URL` |
|
|
24
24
|
|
|
25
25
|
## Token Exchange
|
|
26
26
|
|
|
@@ -15,7 +15,7 @@ See also: [Authentication (External)](?path=/docs/phoenix-integration-authentica
|
|
|
15
15
|
|
|
16
16
|
## Auth Webhook
|
|
17
17
|
|
|
18
|
-
The
|
|
18
|
+
The project needs `access: custom` in `spec/application.yaml`, or `access: legacy-clerk` when it also signs people in with Clerk; the Studio-account modes (`public`, `invited`, `public-with-sign-in`) refuse a project's own sign-in. The example below lives in `src/webhooks/auth.ts` and is wired up in `src/webhooks/index.ts`, built with the deprecated `phx.webhooks.authHandlerBuilder` (parsing reports `AUTH_HOOK_DEPRECATED`). In `custom` the same handlers can instead be default exports of `phx.access.createCodeHandler`, `createRefreshHandler` and `createAnonymousHandler` in `src/handlers/`, without the second `ctx` argument (see [Webhooks - Auth Hook](?path=/docs/phoenix-webhooks--docs#auth-hook)). It has up to three handlers:
|
|
19
19
|
|
|
20
20
|
- **Code handler** — validates the partner's token and creates a session
|
|
21
21
|
- **Refresh handler** — re-validates and extends an expiring session
|
|
@@ -231,8 +231,5 @@ The callback handler receives the resolved resource links and replay data. To au
|
|
|
231
231
|
Register the finalize handler in the webhooks entry point:
|
|
232
232
|
|
|
233
233
|
```ts
|
|
234
|
-
export default phx.webhooks.webhookBuilder
|
|
235
|
-
.withAuthHook(authHandler)
|
|
236
|
-
.withConfiguratorFinalize(configuratorFinalizeHandler)
|
|
237
|
-
.build()
|
|
234
|
+
export default phx.webhooks.webhookBuilder.withConfiguratorFinalize(configuratorFinalizeHandler).build()
|
|
238
235
|
```
|
|
@@ -60,6 +60,15 @@ Maximum host control. The configurator is embedded as a web component, but the h
|
|
|
60
60
|
|
|
61
61
|
Despite the name, the configurator still renders its full UI — "headless" refers to the host providing the brain (routing, auth, lifecycle decisions), not the absence of a visual interface.
|
|
62
62
|
|
|
63
|
+
### embedded
|
|
64
|
+
|
|
65
|
+
Builder Studio's own mode, never set by a project: Studio opens a hosted configurator or admin panel in a frame on the page's own address, with `?code=…&embedded=studio`, and a framed page with that parameter starts in this mode by itself. A page that sets its own `integration-mode` keeps it.
|
|
66
|
+
|
|
67
|
+
- Consumes the one-use `code` from the URL, which signs the frame in as the Studio account
|
|
68
|
+
- Stores auth tokens in sessionStorage, so the sign-in ends with the tab
|
|
69
|
+
- Hides the configurator's own sign-in elements and never redirects to sign in; Studio's bar shows the account
|
|
70
|
+
- Tells Studio its state (`ready`, `denied`, `failed`) by `postMessage`, only to the Studio origin the server names in `GET /auth/config`
|
|
71
|
+
|
|
63
72
|
## Which Mode Do I Pick?
|
|
64
73
|
|
|
65
74
|
Start at the top, stop at the first match:
|