@noodleseed/assistant 1.19.0 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ReactElement, RefAttributes } from 'react';
2
2
  import { a as AssistantThemeMode } from './appearance-Cc-eqSbp.cjs';
3
3
  import { AssistantAppearance, AssistantAppearanceWarning, NoodleAssistantElement } from './index.cjs';
4
- import { c as AssistantClient, d as AssistantViewAvailableDetail, A as AssistantPageContext, a as AssistantContext, e as AssistantModelContextUpdate, f as AssistantClientEvent, g as AssistantErrorDetail } from './client-BQ30Fq-c.cjs';
4
+ import { c as AssistantClient, d as AssistantViewAvailableDetail, A as AssistantPageContext, a as AssistantContext, e as AssistantModelContextUpdate, f as AssistantClientEvent, g as AssistantErrorDetail } from './client-BZ7xPwfW.cjs';
5
5
  import 'ai';
6
6
 
7
7
  interface NoodleAppViewProps {
@@ -37,6 +37,13 @@ interface NoodleAssistantProps<TPageContext extends AssistantPageContext = Assis
37
37
  readonly pageContext?: TPageContext;
38
38
  readonly modelContext?: AssistantModelContextUpdate;
39
39
  readonly onEvent?: (event: AssistantClientEvent) => void;
40
+ /**
41
+ * Fires at most once per component instance, when the element's shadow DOM is rendered and its
42
+ * imperative API (`sendMessage`, `confirmTool`, …) is callable — NOT when a session exists (listen
43
+ * for the `session_started` client event via `onEvent` for that). It fires whether the element
44
+ * upgraded before or after this component mounted, and the first callback identity wins: a later
45
+ * re-render with a different `onReady` is never invoked.
46
+ */
40
47
  readonly onReady?: () => void;
41
48
  readonly onError?: (error: AssistantErrorDetail) => void;
42
49
  readonly onAppearanceWarning?: (warning: AssistantAppearanceWarning) => void;
package/dist/react.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ReactElement, RefAttributes } from 'react';
2
2
  import { a as AssistantThemeMode } from './appearance-Cc-eqSbp.js';
3
3
  import { AssistantAppearance, AssistantAppearanceWarning, NoodleAssistantElement } from './index.js';
4
- import { c as AssistantClient, d as AssistantViewAvailableDetail, A as AssistantPageContext, a as AssistantContext, e as AssistantModelContextUpdate, f as AssistantClientEvent, g as AssistantErrorDetail } from './client-B6pnBmF8.js';
4
+ import { c as AssistantClient, d as AssistantViewAvailableDetail, A as AssistantPageContext, a as AssistantContext, e as AssistantModelContextUpdate, f as AssistantClientEvent, g as AssistantErrorDetail } from './client-BkJlpN5N.js';
5
5
  import 'ai';
6
6
 
7
7
  interface NoodleAppViewProps {
@@ -37,6 +37,13 @@ interface NoodleAssistantProps<TPageContext extends AssistantPageContext = Assis
37
37
  readonly pageContext?: TPageContext;
38
38
  readonly modelContext?: AssistantModelContextUpdate;
39
39
  readonly onEvent?: (event: AssistantClientEvent) => void;
40
+ /**
41
+ * Fires at most once per component instance, when the element's shadow DOM is rendered and its
42
+ * imperative API (`sendMessage`, `confirmTool`, …) is callable — NOT when a session exists (listen
43
+ * for the `session_started` client event via `onEvent` for that). It fires whether the element
44
+ * upgraded before or after this component mounted, and the first callback identity wins: a later
45
+ * re-render with a different `onReady` is never invoked.
46
+ */
40
47
  readonly onReady?: () => void;
41
48
  readonly onError?: (error: AssistantErrorDetail) => void;
42
49
  readonly onAppearanceWarning?: (warning: AssistantAppearanceWarning) => void;
package/dist/react.js CHANGED
@@ -3,8 +3,8 @@ import {
3
3
  registerNoodleAssistant,
4
4
  unmountAssistantApp,
5
5
  updateAssistantAppTheme
6
- } from "./chunk-RFETV5KQ.js";
7
- import "./chunk-S373FCAI.js";
6
+ } from "./chunk-LEKEIHJV.js";
7
+ import "./chunk-ZPZHPXIQ.js";
8
8
  import "./chunk-3YYTUJPJ.js";
9
9
  import "./chunk-5FUTL2UF.js";
10
10
 
@@ -79,6 +79,7 @@ var NoodleAssistantWithRef = forwardRef(
79
79
  const ready = () => {
80
80
  if (readyNotified.current) return;
81
81
  readyNotified.current = true;
82
+ console.debug("[noodle-assistant] ready");
82
83
  props.onReady?.();
83
84
  };
84
85
  const error = (event) => props.onError?.(event.detail);
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/react.ts","../src/react-app-view.ts"],"sourcesContent":["import {\n createElement,\n forwardRef,\n type ReactElement,\n type RefAttributes,\n useEffect,\n useImperativeHandle,\n useRef,\n} from 'react';\nimport type { AssistantThemeMode } from './appearance.js';\nimport type { AssistantAppearance, AssistantAppearanceWarning } from './host-appearance.js';\n\nexport type { AssistantAppearance, AssistantAppearanceWarning } from './host-appearance.js';\n\nimport type {\n AssistantClientEvent,\n AssistantContext,\n AssistantModelContextUpdate,\n AssistantPageContext,\n} from './client.js';\nimport { type NoodleAssistantElement, registerNoodleAssistant } from './element.js';\nimport type { AssistantErrorDetail } from './transport.js';\n\nexport { NoodleAppView, type NoodleAppViewProps } from './react-app-view.js';\n\nexport interface NoodleAssistantProps<\n TPageContext extends AssistantPageContext = AssistantContext,\n> {\n /** In-app mount: the customer backend route that exchanges an embed secret for a session. */\n readonly sessionEndpoint?: string;\n /** Public mount: the non-secret embed id `noodle deploy` printed. Exclusive with `sessionEndpoint`. */\n readonly embedId?: string;\n /** Only for a dev or self-hosted service; a published page needs no origin. */\n readonly serviceUrl?: string;\n readonly theme?: AssistantThemeMode;\n readonly appearance?: AssistantAppearance;\n readonly open?: boolean;\n readonly className?: string;\n readonly context?: AssistantContext;\n readonly pageContext?: TPageContext;\n readonly modelContext?: AssistantModelContextUpdate;\n readonly onEvent?: (event: AssistantClientEvent) => void;\n readonly onReady?: () => void;\n readonly onError?: (error: AssistantErrorDetail) => void;\n readonly onAppearanceWarning?: (warning: AssistantAppearanceWarning) => void;\n readonly onSessionExpired?: () => void;\n}\n\nconst NoodleAssistantWithRef = forwardRef<NoodleAssistantElement, NoodleAssistantProps>(\n function NoodleAssistant(props, forwardedRef): ReactElement {\n const ref = useRef<NoodleAssistantElement>(null);\n const readyNotified = useRef(false);\n useImperativeHandle(forwardedRef, () => ref.current as NoodleAssistantElement, []);\n useEffect(() => {\n const element = ref.current;\n if (!element) return;\n const ready = () => {\n if (readyNotified.current) return;\n readyNotified.current = true;\n props.onReady?.();\n };\n const error = (event: Event) =>\n props.onError?.((event as CustomEvent<AssistantErrorDetail>).detail);\n const expired = () => props.onSessionExpired?.();\n const assistantEvent = (event: Event) =>\n props.onEvent?.((event as CustomEvent<AssistantClientEvent>).detail);\n const appearanceWarning = (event: Event) =>\n props.onAppearanceWarning?.((event as CustomEvent<AssistantAppearanceWarning>).detail);\n element.addEventListener('assistant-ready', ready);\n element.addEventListener('assistant-error', error);\n element.addEventListener('assistant-session-expired', expired);\n element.addEventListener('assistant-event', assistantEvent);\n element.addEventListener('assistant-appearance-warning', appearanceWarning);\n registerNoodleAssistant();\n element.sessionEndpoint = props.sessionEndpoint ?? '';\n element.embedId = props.embedId ?? '';\n element.serviceUrl = props.serviceUrl ?? '';\n element.appearance = props.appearance;\n element.toggleAttribute('open', props.open === true);\n if (props.context) element.updateContext(props.context);\n if (props.pageContext) element.updatePageContext(props.pageContext);\n if (props.modelContext) element.updateModelContext(props.modelContext);\n // The canonical entry may have registered and upgraded the element before this effect ran.\n // Readiness is sticky once the shadow root exists, so late React listeners still fire once.\n if (element.shadowRoot) ready();\n return () => {\n element.removeEventListener('assistant-ready', ready);\n element.removeEventListener('assistant-error', error);\n element.removeEventListener('assistant-session-expired', expired);\n element.removeEventListener('assistant-event', assistantEvent);\n element.removeEventListener('assistant-appearance-warning', appearanceWarning);\n };\n }, [\n props.context,\n props.appearance,\n props.modelContext,\n props.onError,\n props.onAppearanceWarning,\n props.onEvent,\n props.onReady,\n props.onSessionExpired,\n props.open,\n props.pageContext,\n props.sessionEndpoint,\n props.embedId,\n props.serviceUrl,\n ]);\n return createElement('noodle-assistant', {\n ref,\n class: props.className,\n ...(props.sessionEndpoint ? { 'session-endpoint': props.sessionEndpoint } : {}),\n ...(props.embedId ? { 'embed-id': props.embedId } : {}),\n ...(props.serviceUrl ? { 'service-url': props.serviceUrl } : {}),\n ...(props.theme ? { theme: props.theme } : {}),\n });\n },\n);\n\nexport const NoodleAssistant = NoodleAssistantWithRef as <\n TPageContext extends AssistantPageContext = AssistantContext,\n>(\n props: NoodleAssistantProps<TPageContext> & RefAttributes<NoodleAssistantElement>,\n) => ReactElement;\n","import { createElement, type ReactElement, useEffect, useRef } from 'react';\nimport { mountAssistantApp, unmountAssistantApp, updateAssistantAppTheme } from './app-host.js';\nimport type { AssistantClient, AssistantViewAvailableDetail } from './client.js';\n\nexport interface NoodleAppViewProps {\n readonly client: AssistantClient;\n readonly view: AssistantViewAvailableDetail;\n readonly theme?: 'light' | 'dark';\n readonly className?: string;\n readonly onError?: (failure: {\n readonly code: 'view_render_timeout';\n readonly retryable: false;\n }) => void;\n}\n\n/**\n * Securely hosts one service-resolved MCP App inside a customer-owned React renderer.\n *\n * The bridge lifetime follows semantic view identity, so ordinary parent rerenders cannot reset an\n * in-progress App interaction.\n */\nexport function NoodleAppView({\n client,\n view,\n theme = 'light',\n className,\n onError,\n}: NoodleAppViewProps): ReactElement {\n const container = useRef<HTMLDivElement>(null);\n const mounted = useRef<HTMLElement>(null);\n const current = useRef({ view, theme, onError });\n const viewId = view.id;\n const resourceUri = view.resourceUri;\n\n useEffect(() => {\n current.current = { view, theme, onError };\n });\n\n useEffect(() => {\n const host = container.current;\n if (!host) return;\n const initialView = { ...current.current.view, id: viewId, resourceUri };\n const sandboxUrl = client.appSandboxUrl?.();\n const card = mountAssistantApp(\n initialView,\n {\n client,\n sendMessage: (message) => client.sendMessage(message),\n updateModelContext: (update) => client.updateModelContext(update),\n theme: current.current.theme,\n },\n {\n ...(sandboxUrl ? { sandboxUrl } : {}),\n getDetail: () => current.current.view,\n onRenderFailure: (failure) => current.current.onError?.(failure),\n },\n );\n if (!card) return;\n mounted.current = card;\n host.replaceChildren(card);\n return () => {\n if (mounted.current === card) mounted.current = null;\n void unmountAssistantApp(card);\n };\n }, [client, resourceUri, viewId]);\n\n useEffect(() => {\n if (mounted.current) updateAssistantAppTheme(mounted.current, theme);\n }, [the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Aa,SAAQ,kBAAkB,MAAM,WAAW;AAClE,UAAI,MAAM,aAAc,SAAQ,mBAAmB,MAAM,YAAY;AAGrE,UAAI,QAAQ,WAAY,OAAM;AAC9B,aAAO,MAAM;AACX,gBAAQ,oBAAoB,mBAAmB,KAAK;AACpD,gBAAQ,oBAAoB,mBAAmB,KAAK;AACpD,gBAAQ,oBAAoB,6BAA6B,OAAO;AAChE,gBAAQ,oBAAoB,mBAAmB,cAAc;AAC7D,gBAAQ,oBAAoB,gCAAgC,iBAAiB;AAAA,MAC/E;AAAA,IACF,GAAG;AAAA,MACD,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,IACR,CAAC;AACD,WAAOC,eAAc,oBAAoB;AAAA,MACvC;AAAA,MACA,OAAO,MAAM;AAAA,MACb,GAAI,MAAM,kBAAkB,EAAE,oBAAoB,MAAM,gBAAgB,IAAI,CAAC;AAAA,MAC7E,GAAI,MAAM,UAAU,EAAE,YAAY,MAAM,QAAQ,IAAI,CAAC;AAAA,MACrD,GAAI,MAAM,aAAa,EAAE,eAAe,MAAM,WAAW,IAAI,CAAC;AAAA,MAC9D,GAAI,MAAM,QAAQ,EAAE,OAAO,MAAM,MAAM,IAAI,CAAC;AAAA,IAC9C,CAAC;AAAA,EACH;AACF;AAEO,IAAMC,mBAAkB;","names":["createElement","useEffect","useRef","useRef","useEffect","createElement","NoodleAssistant"]}
1
+ {"version":3,"sources":["../src/react.ts","../src/react-app-view.ts"],"sourcesContent":["import {\n createElement,\n forwardRef,\n type ReactElement,\n type RefAttributes,\n useEffect,\n useImperativeHandle,\n useRef,\n} from 'react';\nimport type { AssistantThemeMode } from './appearance.js';\nimport type { AssistantAppearance, AssistantAppearanceWarning } from './host-appearance.js';\n\nexport type { AssistantAppearance, AssistantAppearanceWarning } from './host-appearance.js';\n\nimport type {\n AssistantClientEvent,\n AssistantContext,\n AssistantModelContextUpdate,\n AssistantPageContext,\n} from './client.js';\nimport { type NoodleAssistantElement, registerNoodleAssistant } from './element.js';\nimport type { AssistantErrorDetail } from './transport.js';\n\nexport { NoodleAppView, type NoodleAppViewProps } from './react-app-view.js';\n\nexport interface NoodleAssistantProps<\n TPageContext extends AssistantPageContext = AssistantContext,\n> {\n /** In-app mount: the customer backend route that exchanges an embed secret for a session. */\n readonly sessionEndpoint?: string;\n /** Public mount: the non-secret embed id `noodle deploy` printed. Exclusive with `sessionEndpoint`. */\n readonly embedId?: string;\n /** Only for a dev or self-hosted service; a published page needs no origin. */\n readonly serviceUrl?: string;\n readonly theme?: AssistantThemeMode;\n readonly appearance?: AssistantAppearance;\n readonly open?: boolean;\n readonly className?: string;\n readonly context?: AssistantContext;\n readonly pageContext?: TPageContext;\n readonly modelContext?: AssistantModelContextUpdate;\n readonly onEvent?: (event: AssistantClientEvent) => void;\n /**\n * Fires at most once per component instance, when the element's shadow DOM is rendered and its\n * imperative API (`sendMessage`, `confirmTool`, …) is callable — NOT when a session exists (listen\n * for the `session_started` client event via `onEvent` for that). It fires whether the element\n * upgraded before or after this component mounted, and the first callback identity wins: a later\n * re-render with a different `onReady` is never invoked.\n */\n readonly onReady?: () => void;\n readonly onError?: (error: AssistantErrorDetail) => void;\n readonly onAppearanceWarning?: (warning: AssistantAppearanceWarning) => void;\n readonly onSessionExpired?: () => void;\n}\n\nconst NoodleAssistantWithRef = forwardRef<NoodleAssistantElement, NoodleAssistantProps>(\n function NoodleAssistant(props, forwardedRef): ReactElement {\n const ref = useRef<NoodleAssistantElement>(null);\n const readyNotified = useRef(false);\n useImperativeHandle(forwardedRef, () => ref.current as NoodleAssistantElement, []);\n useEffect(() => {\n const element = ref.current;\n if (!element) return;\n const ready = () => {\n if (readyNotified.current) return;\n readyNotified.current = true;\n // The one observable breadcrumb for the readiness path: integrators could previously\n // neither convict nor exonerate this callback for a field failure.\n console.debug('[noodle-assistant] ready');\n props.onReady?.();\n };\n const error = (event: Event) =>\n props.onError?.((event as CustomEvent<AssistantErrorDetail>).detail);\n const expired = () => props.onSessionExpired?.();\n const assistantEvent = (event: Event) =>\n props.onEvent?.((event as CustomEvent<AssistantClientEvent>).detail);\n const appearanceWarning = (event: Event) =>\n props.onAppearanceWarning?.((event as CustomEvent<AssistantAppearanceWarning>).detail);\n element.addEventListener('assistant-ready', ready);\n element.addEventListener('assistant-error', error);\n element.addEventListener('assistant-session-expired', expired);\n element.addEventListener('assistant-event', assistantEvent);\n element.addEventListener('assistant-appearance-warning', appearanceWarning);\n registerNoodleAssistant();\n element.sessionEndpoint = props.sessionEndpoint ?? '';\n element.embedId = props.embedId ?? '';\n element.serviceUrl = props.serviceUrl ?? '';\n element.appearance = props.appearance;\n element.toggleAttribute('open', props.open === true);\n if (props.context) element.updateContext(props.context);\n if (props.pageContext) element.updatePageContext(props.pageContext);\n if (props.modelContext) element.updateModelContext(props.modelContext);\n // The canonical entry may have registered and upgraded the element before this effect ran.\n // Readiness is sticky once the shadow root exists, so late React listeners still fire once.\n if (element.shadowRoot) ready();\n return () => {\n element.removeEventListener('assistant-ready', ready);\n element.removeEventListener('assistant-error', error);\n element.removeEventListener('assistant-session-expired', expired);\n element.removeEventListener('assistant-event', assistantEvent);\n element.removeEventListener('assistant-appearance-warning', appearanceWarning);\n };\n }, [\n props.context,\n props.appearance,\n props.modelContext,\n props.onError,\n props.onAppearanceWarning,\n props.onEvent,\n props.onReady,\n props.onSessionExpired,\n props.open,\n props.pageContext,\n props.sessionEndpoint,\n props.embedId,\n props.serviceUrl,\n ]);\n return createElement('noodle-assistant', {\n ref,\n class: props.className,\n ...(props.sessionEndpoint ? { 'session-endpoint': props.sessionEndpoint } : {}),\n ...(props.embedId ? { 'embed-id': props.embedId } : {}),\n ...(props.serviceUrl ? { 'service-url': props.serviceUrl } : {}),\n ...(props.theme ? { theme: props.theme } : {}),\n });\n },\n);\n\nexport const NoodleAssistant = NoodleAssistantWithRef as <\n TPageContext extends AssistantPageContext = AssistantContext,\n>(\n props: NoodleAssistantProps<TPageContext> & RefAttributes<NoodleAssistantElement>,\n) => ReactElement;\n","import { createElement, type ReactElement, useEffect, useRef } from 'react';\nimport { mountAssistantApp, unmountAssistantApp, updateAssistantAppTheme } from './app-host.js';\nimport type { AssistantClient, AssistantViewAvailableDetail } from './client.js';\n\nexport interface NoodleAppViewProps {\n readonly client: AssistantClient;\n readonly view: AssistantViewAvailableDetail;\n readonly theme?: 'light' | 'dark';\n readonly className?: string;\n readonly onError?: (failure: {\n readonly code: 'view_render_timeout';\n readonly retryable: false;\n }) => void;\n}\n\n/**\n * Securely hosts one service-resolved MCP App inside a customer-owned React renderer.\n *\n * The bridge lifetime follows semantic view identity, so ordinary parent rerenders cannot reset an\n * in-progress App interaction.\n */\nexport function NoodleAppView({\n client,\n view,\n theme = 'light',\n className,\n onError,\n}: NoodleAppViewProps): ReactElement {\n const container = useRef<HTMLDivElement>(null);\n const mounted = useRef<HTMLElement>(null);\n const current = useRef({ view, theme, onError });\n const viewId = view.id;\n const resourceUri = view.resourceUri;\n\n useEffect(() => {\n current.current = { view, theme, onError };\n });\n\n useEffect(() => {\n const host = container.current;\n if (!host) return;\n const initialView = { ...current.current.view, id: viewId, resourceUri };\n const sandboxUrl = client.appSandboxUrl?.();\n const card = mountAssistantApp(\n initialView,\n {\n client,\n sendMessage: (message) => client.sendMessage(message),\n updateModelContext: (update) => client.updateModelContext(update),\n theme: current.current.theme,\n },\n {\n ...(sandboxUrl ? { sandboxUrl } : {}),\n getDetail: () => current.current.view,\n onRenderFailure: (failure) => current.current.onError?.(failure),\n },\n );\n if (!card) return;\n mounted.current = card;\n host.replaceChildren(card);\n return () => {\n if (mounted.current === card) mounted.current = null;\n void unmountAssistantApp(card);\n };\n }, [client, resourceUri, viewId]);\n\n useEffect(() => {\n if (mounted.current) updateAssistantAppT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QAAS,SAAQ,cAAc,MAAM,OAAO;AACtD,UAAI,MAAM,YAAa,SAAQ,kBAAkB,MAAM,WAAW;AAClE,UAAI,MAAM,aAAc,SAAQ,mBAAmB,MAAM,YAAY;AAGrE,UAAI,QAAQ,WAAY,OAAM;AAC9B,aAAO,MAAM;AACX,gBAAQ,oBAAoB,mBAAmB,KAAK;AACpD,gBAAQ,oBAAoB,mBAAmB,KAAK;AACpD,gBAAQ,oBAAoB,6BAA6B,OAAO;AAChE,gBAAQ,oBAAoB,mBAAmB,cAAc;AAC7D,gBAAQ,oBAAoB,gCAAgC,iBAAiB;AAAA,MAC/E;AAAA,IACF,GAAG;AAAA,MACD,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,IACR,CAAC;AACD,WAAOC,eAAc,oBAAoB;AAAA,MACvC;AAAA,MACA,OAAO,MAAM;AAAA,MACb,GAAI,MAAM,kBAAkB,EAAE,oBAAoB,MAAM,gBAAgB,IAAI,CAAC;AAAA,MAC7E,GAAI,MAAM,UAAU,EAAE,YAAY,MAAM,QAAQ,IAAI,CAAC;AAAA,MACrD,GAAI,MAAM,aAAa,EAAE,eAAe,MAAM,WAAW,IAAI,CAAC;AAAA,MAC9D,GAAI,MAAM,QAAQ,EAAE,OAAO,MAAM,MAAM,IAAI,CAAC;AAAA,IAC9C,CAAC;AAAA,EACH;AACF;AAEO,IAAMC,mBAAkB;","names":["createElement","useEffect","useRef","useRef","useEffect","createElement","NoodleAssistant"]}
package/dist/server.cjs CHANGED
@@ -20,10 +20,53 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/server.ts
21
21
  var server_exports = {};
22
22
  __export(server_exports, {
23
+ ASSISTANT_ELEVATION_REFUSAL_CODES: () => ASSISTANT_ELEVATION_REFUSAL_CODES,
24
+ AssistantSessionExchangeError: () => AssistantSessionExchangeError,
23
25
  createAssistantSession: () => createAssistantSession
24
26
  });
25
27
  module.exports = __toCommonJS(server_exports);
28
+ var ASSISTANT_ELEVATION_REFUSAL_CODES = [
29
+ "elevation_ticket_invalid",
30
+ "elevation_ticket_expired",
31
+ "elevation_tenant_mismatch",
32
+ "elevation_session_unavailable",
33
+ "elevation_already_signed_in"
34
+ ];
35
+ var AssistantSessionExchangeError = class extends Error {
36
+ detail;
37
+ constructor(detail, message) {
38
+ super(message);
39
+ this.name = "AssistantSessionExchangeError";
40
+ this.detail = detail;
41
+ }
42
+ /**
43
+ * The narrowed sign-in refusal, when this failure is one. `elevation_ticket_expired` means the
44
+ * visitor took too long — re-prompt; `elevation_tenant_mismatch` means a client reached for a
45
+ * conversation it does not own — alert someone, never retry.
46
+ */
47
+ get elevationRefusal() {
48
+ const code = this.detail.serviceCode;
49
+ return code !== void 0 && ASSISTANT_ELEVATION_REFUSAL_CODES.includes(code) ? code : void 0;
50
+ }
51
+ };
52
+ async function exchangeError(response) {
53
+ const body = await response.json().catch(() => void 0);
54
+ const serviceCode = typeof body?.code === "string" ? body.code : void 0;
55
+ return new AssistantSessionExchangeError(
56
+ {
57
+ code: "session_exchange_failed",
58
+ status: response.status,
59
+ // `elevation_unavailable` is a 503 an operator has to fix; retrying cannot help.
60
+ retryable: response.status >= 500 && serviceCode !== "elevation_unavailable",
61
+ ...serviceCode === void 0 ? {} : { serviceCode }
62
+ },
63
+ `Assistant session exchange failed (${response.status})`
64
+ );
65
+ }
26
66
  async function createAssistantSession(input, dependencies = {}) {
67
+ if (input.signInTicket !== void 0 && input.context !== void 0) {
68
+ throw new Error("context does not apply when spending a sign-in ticket");
69
+ }
27
70
  const request = dependencies.fetch ?? fetch;
28
71
  const serviceUrl = input.serviceUrl.replace(/\/$/, "");
29
72
  const credentials = Buffer.from(`${input.clientId}:${input.clientSecret}`, "utf8").toString(
@@ -39,17 +82,21 @@ async function createAssistantSession(input, dependencies = {}) {
39
82
  body: JSON.stringify({
40
83
  origin: input.origin,
41
84
  user: input.user,
85
+ ...input.signInTicket === void 0 ? {} : { signInTicket: input.signInTicket },
86
+ ...input.signInTicket !== void 0 && input.resume !== void 0 ? { resume: input.resume } : {},
42
87
  ...input.claims ? { claims: input.claims } : {},
43
88
  ...input.context ? { context: input.context } : {},
44
89
  ...input.preferences ? { preferences: input.preferences } : {},
45
90
  ...input.routing ? { routing: input.routing } : {}
46
91
  })
47
92
  });
48
- if (!response.ok) throw new Error(`Assistant session exchange failed (${response.status})`);
93
+ if (!response.ok) throw await exchangeError(response);
49
94
  return await response.json();
50
95
  }
51
96
  // Annotate the CommonJS export names for ESM import in node:
52
97
  0 && (module.exports = {
98
+ ASSISTANT_ELEVATION_REFUSAL_CODES,
99
+ AssistantSessionExchangeError,
53
100
  createAssistantSession
54
101
  });
55
102
  //# sourceMappingURL=server.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts"],"sourcesContent":["import type { AssistantConfiguration } from './appearance.js';\n\nexport interface CreateAssistantSessionInput {\n readonly serviceUrl: string;\n readonly clientId: string;\n readonly clientSecret: string;\n /** Browser origin to bind into the short-lived assistant session. */\n readonly origin: string;\n readonly user: {\n readonly id: string;\n readonly email?: string;\n readonly name?: string;\n readonly tenant?: string;\n readonly roles?: readonly string[];\n readonly scopes?: readonly string[];\n };\n readonly context?: Readonly<Record<string, string | number | boolean | null>>;\n /** Backend-verified user preferences; these outrank untrusted browser presentation hints. */\n readonly preferences?: {\n readonly locale?: string;\n readonly timeZone?: string;\n };\n /** Backend-verified connector routes keyed by authored `customerEndpoint` name. */\n readonly routing?: {\n readonly endpoints: Readonly<Record<string, string>>;\n };\n /**\n * Verified session claims from your authenticated backend. Only claims the server declares in\n * `embeddedAssistant({ sessionClaims })` reach tools (`\\${user.claims.<key>}`) and, when marked\n * `exposeToModel`, the assistant's identity context. Flat scalars only.\n */\n readonly claims?: Readonly<Record<string, string | number | boolean | null>>;\n}\n\nexport interface AssistantSession {\n readonly token: string;\n readonly expiresAt: string;\n readonly endpoints: {\n readonly turns: string;\n readonly toolConfirmations: string;\n readonly interactions?: string;\n readonly apps?: string;\n /** Additive hosted sandbox document for widget frames; absent on older services. */\n readonly sandbox?: string;\n };\n readonly configuration?: AssistantConfiguration;\n}\n\nexport async function createAssistantSession(\n input: CreateAssistantSessionInput,\n dependencies: { readonly fetch?: typeof fetch } = {},\n): Promise<AssistantSession> {\n const request = dependencies.fetch ?? fetch;\n const serviceUrl = input.serviceUrl.replace(/\\/$/, '');\n const credentials = Buffer.from(`${input.clientId}:${input.clientSecret}`, 'utf8').toString(\n 'base64',\n );\n const response = await request(`${serviceUrl}/v1/assistant/sessions`, {\n method: 'POST',\n headers: {\n Authorization: `Basic ${credentials}`,\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n origin: input.origin,\n user: input.user,\n ...(input.claims ? { claims: input.claims } : {}),\n ...(input.context ? { context: input.context } : {}),\n ...(input.preferences ? { preferences: input.preferences } : {}),\n ...(input.routing ? { routing: input.routing } : {}),\n }),\n });\n if (!response.ok) throw new Error(`Assistant session exchange failed (${response.status})`);\n return (await response.json()) as AssistantSession;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgDA,eAAsB,uBACpB,OACA,eAAkD,CAAC,GACxB;AAC3B,QAAM,UAAU,aAAa,SAAS;AACtC,QAAM,aAAa,MAAM,WAAW,QAAQ,OAAO,EAAE;AACrD,QAAM,cAAc,OAAO,KAAK,GAAG,MAAM,QAAQ,IAAI,MAAM,YAAY,IAAI,MAAM,EAAE;AAAA,IACjF;AAAA,EACF;AACA,QAAM,WAAW,MAAM,QAAQ,GAAG,UAAU,0BAA0B;AAAA,IACpE,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,eAAe,SAAS,WAAW;AAAA,MACnC,QAAQ;AAAA,MACR,gBAAgB;AAAA,IAClB;AAAA,IACA,MAAM,KAAK,UAAU;AAAA,MACnB,QAAQ,MAAM;AAAA,MACd,MAAM,MAAM;AAAA,MACZ,GAAI,MAAM,SAAS,EAAE,QAAQ,MAAM,OAAO,IAAI,CAAC;AAAA,MAC/C,GAAI,MAAM,UAAU,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,MAClD,GAAI,MAAM,cAAc,EAAE,aAAa,MAAM,YAAY,IAAI,CAAC;AAAA,MAC9D,GAAI,MAAM,UAAU,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,IACpD,CAAC;AAAA,EACH,CAAC;AACD,MAAI,CAAC,SAAS,GAAI,OAAM,IAAI,MAAM,sCAAsC,SAAS,MAAM,GAAG;AAC1F,SAAQ,MAAM,SAAS,KAAK;AAC9B;","names":[]}
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["import type { AssistantConfiguration } from './appearance.js';\n\ninterface AssistantSessionExchangeBase {\n readonly serviceUrl: string;\n readonly clientId: string;\n readonly clientSecret: string;\n /** Browser origin to bind into the short-lived assistant session. */\n readonly origin: string;\n /** The signed-in person your backend vouches for — on both arms: an elevation IS this vouching. */\n readonly user: {\n readonly id: string;\n readonly email?: string;\n readonly name?: string;\n readonly tenant?: string;\n readonly roles?: readonly string[];\n readonly scopes?: readonly string[];\n };\n /** Backend-verified user preferences; these outrank untrusted browser presentation hints. */\n readonly preferences?: {\n readonly locale?: string;\n readonly timeZone?: string;\n };\n /**\n * Verified session claims from your authenticated backend. Only claims the server declares in\n * `embeddedAssistant({ sessionClaims })` reach tools (`\\${user.claims.<key>}`) and, when marked\n * `exposeToModel`, the assistant's identity context. Flat scalars only.\n */\n readonly claims?: Readonly<Record<string, string | number | boolean | null>>;\n}\n\n/**\n * Fresh mint XOR mid-conversation sign-in, exclusive rather than merged for the same reason the\n * client's `sessionEndpoint`/`embedId` pair is: the two are different operations, and the wrong\n * combination should fail to typecheck instead of silently picking a meaning.\n *\n * `context` applies only when a session is being created; an elevation keeps the existing\n * conversation, so it is excluded rather than silently ignored. `routing` is allowed on both arms —\n * elevation is the first authenticated moment, so it is the only chance a routed connector's\n * session ever gets its backend-verified customer routes.\n */\nexport type CreateAssistantSessionInput =\n | (AssistantSessionExchangeBase & {\n readonly signInTicket?: undefined;\n readonly context?: Readonly<Record<string, string | number | boolean | null>>;\n /** Backend-verified connector routes keyed by authored `customerEndpoint` name. */\n readonly routing?: {\n readonly endpoints: Readonly<Record<string, string>>;\n };\n /** Resume applies only when spending a sign-in ticket; a fresh mint has nothing pending. */\n readonly resume?: undefined;\n })\n | (AssistantSessionExchangeBase & {\n /**\n * Single-use sign-in ticket from the widget's `assistant-sign-in-requested` event\n * (ADR 0201, 5.6b). Spending it binds this signed-in user to the visitor's existing\n * anonymous conversation instead of minting a new one. Unrelated to the server-held\n * interaction continuation, which never reaches browser code.\n */\n readonly signInTicket: string;\n readonly context?: undefined;\n /** Backend-verified connector routes keyed by authored `customerEndpoint` name. */\n readonly routing?: {\n readonly endpoints: Readonly<Record<string, string>>;\n };\n /**\n * Whether the service resumes the intercepted tool call as the elevated session's first\n * turn (issue #1177). ON by default — omit it and the visitor's pending question answers\n * itself after sign-in; pass `false` if your application provides its own affordance.\n */\n readonly resume?: boolean;\n });\n\nexport interface AssistantSession {\n readonly token: string;\n readonly expiresAt: string;\n readonly endpoints: {\n readonly turns: string;\n readonly toolConfirmations: string;\n readonly interactions?: string;\n readonly apps?: string;\n /** Additive hosted sandbox document for widget frames; absent on older services. */\n readonly sandbox?: string;\n };\n /**\n * Present only on an elevation that armed the one-shot resume of the intercepted tool. Forward\n * the response body unchanged and the widget answers with one automatic turn.\n */\n readonly resume?: { readonly tool: string };\n readonly configuration?: AssistantConfiguration;\n}\n\n/** The service's refusal codes for a sign-in ticket the exchange would not honour. */\nexport const ASSISTANT_ELEVATION_REFUSAL_CODES = [\n 'elevation_ticket_invalid',\n 'elevation_ticket_expired',\n 'elevation_tenant_mismatch',\n 'elevation_session_unavailable',\n 'elevation_already_signed_in',\n] as const;\nexport type AssistantElevationRefusalCode = (typeof ASSISTANT_ELEVATION_REFUSAL_CODES)[number];\n\n/**\n * Structurally mirrors the browser client's `AssistantErrorDetail` (declared locally: the backend\n * entry must not pull the browser transport module into its graph). `code` is a closed union owned\n * by this package; `serviceCode` passes the service's machine code through additively.\n */\nexport interface AssistantSessionExchangeErrorDetail {\n readonly code: 'session_exchange_failed';\n readonly status: number;\n /** 5xx infrastructure failures may be retried; a refused exchange must not be — tickets are single-use. */\n readonly retryable: boolean;\n /** The service's machine code when the body carried one, e.g. `elevation_ticket_expired`. */\n readonly serviceCode?: string;\n}\n\nexport class AssistantSessionExchangeError extends Error {\n readonly detail: AssistantSessionExchangeErrorDetail;\n\n constructor(detail: AssistantSessionExchangeErrorDetail, message: string) {\n super(message);\n this.name = 'AssistantSessionExchangeError';\n this.detail = detail;\n }\n\n /**\n * The narrowed sign-in refusal, when this failure is one. `elevation_ticket_expired` means the\n * visitor took too long — re-prompt; `elevation_tenant_mismatch` means a client reached for a\n * conversation it does not own — alert someone, never retry.\n */\n get elevationRefusal(): AssistantElevationRefusalCode | undefined {\n const code = this.detail.serviceCode;\n return code !== undefined &&\n (ASSISTANT_ELEVATION_REFUSAL_CODES as readonly string[]).includes(code)\n ? (code as AssistantElevationRefusalCode)\n : undefined;\n }\n}\n\n/** Never throws while reading the body — a proxy can answer with HTML instead of JSON. */\nasync function exchangeError(response: Response): Promise<AssistantSessionExchangeError> {\n const body = (await response.json().catch(() => undefined)) as\n | { readonly error?: unknown; readonly code?: unknown }\n | undefined;\n const serviceCode = typeof body?.code === 'string' ? body.code : undefined;\n return new AssistantSessionExchangeError(\n {\n code: 'session_exchange_failed',\n status: response.status,\n // `elevation_unavailable` is a 503 an operator has to fix; retrying cannot help.\n retryable: response.status >= 500 && serviceCode !== 'elevation_unavailable',\n ...(serviceCode === undefined ? {} : { serviceCode }),\n },\n `Assistant session exchange failed (${response.status})`,\n );\n}\n\nexport async function createAssistantSession(\n input: CreateAssistantSessionInput,\n dependencies: { readonly fetch?: typeof fetch } = {},\n): Promise<AssistantSession> {\n if (input.signInTicket !== undefined && (input as { context?: unknown }).context !== undefined) {\n // Mirrors resolveSessionSource: silently dropping what the service ignores would pick a\n // meaning the developer did not intend.\n throw new Error('context does not apply when spending a sign-in ticket');\n }\n const request = dependencies.fetch ?? fetch;\n const serviceUrl = input.serviceUrl.replace(/\\/$/, '');\n const credentials = Buffer.from(`${input.clientId}:${input.clientSecret}`, 'utf8').toString(\n 'base64',\n );\n const response = await request(`${serviceUrl}/v1/assistant/sessions`, {\n method: 'POST',\n headers: {\n Authorization: `Basic ${credentials}`,\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n origin: input.origin,\n user: input.user,\n ...(input.signInTicket === undefined ? {} : { signInTicket: input.signInTicket }),\n ...(input.signInTicket !== undefined && input.resume !== undefined\n ? { resume: input.resume }\n : {}),\n ...(input.claims ? { claims: input.claims } : {}),\n ...(input.context ? { context: input.context } : {}),\n ...(input.preferences ? { preferences: input.preferences } : {}),\n ...(input.routing ? { routing: input.routing } : {}),\n }),\n });\n // A fresh mint answers 201, an elevation 200; both are the same wire shape (ADR 0151).\n if (!response.ok) throw await exchangeError(response);\n return (await response.json()) as AssistantSession;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4FO,IAAM,oCAAoC;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAiBO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EAC9C;AAAA,EAET,YAAY,QAA6C,SAAiB;AACxE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,mBAA8D;AAChE,UAAM,OAAO,KAAK,OAAO;AACzB,W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,OAAO,IAAI,CAAC;AAAA,MAC/C,GAAI,MAAM,UAAU,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,MAClD,GAAI,MAAM,cAAc,EAAE,aAAa,MAAM,YAAY,IAAI,CAAC;AAAA,MAC9D,GAAI,MAAM,UAAU,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,IACpD,CAAC;AAAA,EACH,CAAC;AAED,MAAI,CAAC,SAAS,GAAI,OAAM,MAAM,cAAc,QAAQ;AACpD,SAAQ,MAAM,SAAS,KAAK;AAC9B;","names":[]}
package/dist/server.d.cts CHANGED
@@ -1,11 +1,12 @@
1
1
  import { A as AssistantConfiguration } from './appearance-Cc-eqSbp.cjs';
2
2
 
3
- interface CreateAssistantSessionInput {
3
+ interface AssistantSessionExchangeBase {
4
4
  readonly serviceUrl: string;
5
5
  readonly clientId: string;
6
6
  readonly clientSecret: string;
7
7
  /** Browser origin to bind into the short-lived assistant session. */
8
8
  readonly origin: string;
9
+ /** The signed-in person your backend vouches for — on both arms: an elevation IS this vouching. */
9
10
  readonly user: {
10
11
  readonly id: string;
11
12
  readonly email?: string;
@@ -14,16 +15,11 @@ interface CreateAssistantSessionInput {
14
15
  readonly roles?: readonly string[];
15
16
  readonly scopes?: readonly string[];
16
17
  };
17
- readonly context?: Readonly<Record<string, string | number | boolean | null>>;
18
18
  /** Backend-verified user preferences; these outrank untrusted browser presentation hints. */
19
19
  readonly preferences?: {
20
20
  readonly locale?: string;
21
21
  readonly timeZone?: string;
22
22
  };
23
- /** Backend-verified connector routes keyed by authored `customerEndpoint` name. */
24
- readonly routing?: {
25
- readonly endpoints: Readonly<Record<string, string>>;
26
- };
27
23
  /**
28
24
  * Verified session claims from your authenticated backend. Only claims the server declares in
29
25
  * `embeddedAssistant({ sessionClaims })` reach tools (`\${user.claims.<key>}`) and, when marked
@@ -31,6 +27,45 @@ interface CreateAssistantSessionInput {
31
27
  */
32
28
  readonly claims?: Readonly<Record<string, string | number | boolean | null>>;
33
29
  }
30
+ /**
31
+ * Fresh mint XOR mid-conversation sign-in, exclusive rather than merged for the same reason the
32
+ * client's `sessionEndpoint`/`embedId` pair is: the two are different operations, and the wrong
33
+ * combination should fail to typecheck instead of silently picking a meaning.
34
+ *
35
+ * `context` applies only when a session is being created; an elevation keeps the existing
36
+ * conversation, so it is excluded rather than silently ignored. `routing` is allowed on both arms —
37
+ * elevation is the first authenticated moment, so it is the only chance a routed connector's
38
+ * session ever gets its backend-verified customer routes.
39
+ */
40
+ type CreateAssistantSessionInput = (AssistantSessionExchangeBase & {
41
+ readonly signInTicket?: undefined;
42
+ readonly context?: Readonly<Record<string, string | number | boolean | null>>;
43
+ /** Backend-verified connector routes keyed by authored `customerEndpoint` name. */
44
+ readonly routing?: {
45
+ readonly endpoints: Readonly<Record<string, string>>;
46
+ };
47
+ /** Resume applies only when spending a sign-in ticket; a fresh mint has nothing pending. */
48
+ readonly resume?: undefined;
49
+ }) | (AssistantSessionExchangeBase & {
50
+ /**
51
+ * Single-use sign-in ticket from the widget's `assistant-sign-in-requested` event
52
+ * (ADR 0201, 5.6b). Spending it binds this signed-in user to the visitor's existing
53
+ * anonymous conversation instead of minting a new one. Unrelated to the server-held
54
+ * interaction continuation, which never reaches browser code.
55
+ */
56
+ readonly signInTicket: string;
57
+ readonly context?: undefined;
58
+ /** Backend-verified connector routes keyed by authored `customerEndpoint` name. */
59
+ readonly routing?: {
60
+ readonly endpoints: Readonly<Record<string, string>>;
61
+ };
62
+ /**
63
+ * Whether the service resumes the intercepted tool call as the elevated session's first
64
+ * turn (issue #1177). ON by default — omit it and the visitor's pending question answers
65
+ * itself after sign-in; pass `false` if your application provides its own affordance.
66
+ */
67
+ readonly resume?: boolean;
68
+ });
34
69
  interface AssistantSession {
35
70
  readonly token: string;
36
71
  readonly expiresAt: string;
@@ -42,10 +77,43 @@ interface AssistantSession {
42
77
  /** Additive hosted sandbox document for widget frames; absent on older services. */
43
78
  readonly sandbox?: string;
44
79
  };
80
+ /**
81
+ * Present only on an elevation that armed the one-shot resume of the intercepted tool. Forward
82
+ * the response body unchanged and the widget answers with one automatic turn.
83
+ */
84
+ readonly resume?: {
85
+ readonly tool: string;
86
+ };
45
87
  readonly configuration?: AssistantConfiguration;
46
88
  }
89
+ /** The service's refusal codes for a sign-in ticket the exchange would not honour. */
90
+ declare const ASSISTANT_ELEVATION_REFUSAL_CODES: readonly ["elevation_ticket_invalid", "elevation_ticket_expired", "elevation_tenant_mismatch", "elevation_session_unavailable", "elevation_already_signed_in"];
91
+ type AssistantElevationRefusalCode = (typeof ASSISTANT_ELEVATION_REFUSAL_CODES)[number];
92
+ /**
93
+ * Structurally mirrors the browser client's `AssistantErrorDetail` (declared locally: the backend
94
+ * entry must not pull the browser transport module into its graph). `code` is a closed union owned
95
+ * by this package; `serviceCode` passes the service's machine code through additively.
96
+ */
97
+ interface AssistantSessionExchangeErrorDetail {
98
+ readonly code: 'session_exchange_failed';
99
+ readonly status: number;
100
+ /** 5xx infrastructure failures may be retried; a refused exchange must not be — tickets are single-use. */
101
+ readonly retryable: boolean;
102
+ /** The service's machine code when the body carried one, e.g. `elevation_ticket_expired`. */
103
+ readonly serviceCode?: string;
104
+ }
105
+ declare class AssistantSessionExchangeError extends Error {
106
+ readonly detail: AssistantSessionExchangeErrorDetail;
107
+ constructor(detail: AssistantSessionExchangeErrorDetail, message: string);
108
+ /**
109
+ * The narrowed sign-in refusal, when this failure is one. `elevation_ticket_expired` means the
110
+ * visitor took too long — re-prompt; `elevation_tenant_mismatch` means a client reached for a
111
+ * conversation it does not own — alert someone, never retry.
112
+ */
113
+ get elevationRefusal(): AssistantElevationRefusalCode | undefined;
114
+ }
47
115
  declare function createAssistantSession(input: CreateAssistantSessionInput, dependencies?: {
48
116
  readonly fetch?: typeof fetch;
49
117
  }): Promise<AssistantSession>;
50
118
 
51
- export { type AssistantSession, type CreateAssistantSessionInput, createAssistantSession };
119
+ export { ASSISTANT_ELEVATION_REFUSAL_CODES, type AssistantElevationRefusalCode, type AssistantSession, AssistantSessionExchangeError, type AssistantSessionExchangeErrorDetail, type CreateAssistantSessionInput, createAssistantSession };
package/dist/server.d.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  import { A as AssistantConfiguration } from './appearance-Cc-eqSbp.js';
2
2
 
3
- interface CreateAssistantSessionInput {
3
+ interface AssistantSessionExchangeBase {
4
4
  readonly serviceUrl: string;
5
5
  readonly clientId: string;
6
6
  readonly clientSecret: string;
7
7
  /** Browser origin to bind into the short-lived assistant session. */
8
8
  readonly origin: string;
9
+ /** The signed-in person your backend vouches for — on both arms: an elevation IS this vouching. */
9
10
  readonly user: {
10
11
  readonly id: string;
11
12
  readonly email?: string;
@@ -14,16 +15,11 @@ interface CreateAssistantSessionInput {
14
15
  readonly roles?: readonly string[];
15
16
  readonly scopes?: readonly string[];
16
17
  };
17
- readonly context?: Readonly<Record<string, string | number | boolean | null>>;
18
18
  /** Backend-verified user preferences; these outrank untrusted browser presentation hints. */
19
19
  readonly preferences?: {
20
20
  readonly locale?: string;
21
21
  readonly timeZone?: string;
22
22
  };
23
- /** Backend-verified connector routes keyed by authored `customerEndpoint` name. */
24
- readonly routing?: {
25
- readonly endpoints: Readonly<Record<string, string>>;
26
- };
27
23
  /**
28
24
  * Verified session claims from your authenticated backend. Only claims the server declares in
29
25
  * `embeddedAssistant({ sessionClaims })` reach tools (`\${user.claims.<key>}`) and, when marked
@@ -31,6 +27,45 @@ interface CreateAssistantSessionInput {
31
27
  */
32
28
  readonly claims?: Readonly<Record<string, string | number | boolean | null>>;
33
29
  }
30
+ /**
31
+ * Fresh mint XOR mid-conversation sign-in, exclusive rather than merged for the same reason the
32
+ * client's `sessionEndpoint`/`embedId` pair is: the two are different operations, and the wrong
33
+ * combination should fail to typecheck instead of silently picking a meaning.
34
+ *
35
+ * `context` applies only when a session is being created; an elevation keeps the existing
36
+ * conversation, so it is excluded rather than silently ignored. `routing` is allowed on both arms —
37
+ * elevation is the first authenticated moment, so it is the only chance a routed connector's
38
+ * session ever gets its backend-verified customer routes.
39
+ */
40
+ type CreateAssistantSessionInput = (AssistantSessionExchangeBase & {
41
+ readonly signInTicket?: undefined;
42
+ readonly context?: Readonly<Record<string, string | number | boolean | null>>;
43
+ /** Backend-verified connector routes keyed by authored `customerEndpoint` name. */
44
+ readonly routing?: {
45
+ readonly endpoints: Readonly<Record<string, string>>;
46
+ };
47
+ /** Resume applies only when spending a sign-in ticket; a fresh mint has nothing pending. */
48
+ readonly resume?: undefined;
49
+ }) | (AssistantSessionExchangeBase & {
50
+ /**
51
+ * Single-use sign-in ticket from the widget's `assistant-sign-in-requested` event
52
+ * (ADR 0201, 5.6b). Spending it binds this signed-in user to the visitor's existing
53
+ * anonymous conversation instead of minting a new one. Unrelated to the server-held
54
+ * interaction continuation, which never reaches browser code.
55
+ */
56
+ readonly signInTicket: string;
57
+ readonly context?: undefined;
58
+ /** Backend-verified connector routes keyed by authored `customerEndpoint` name. */
59
+ readonly routing?: {
60
+ readonly endpoints: Readonly<Record<string, string>>;
61
+ };
62
+ /**
63
+ * Whether the service resumes the intercepted tool call as the elevated session's first
64
+ * turn (issue #1177). ON by default — omit it and the visitor's pending question answers
65
+ * itself after sign-in; pass `false` if your application provides its own affordance.
66
+ */
67
+ readonly resume?: boolean;
68
+ });
34
69
  interface AssistantSession {
35
70
  readonly token: string;
36
71
  readonly expiresAt: string;
@@ -42,10 +77,43 @@ interface AssistantSession {
42
77
  /** Additive hosted sandbox document for widget frames; absent on older services. */
43
78
  readonly sandbox?: string;
44
79
  };
80
+ /**
81
+ * Present only on an elevation that armed the one-shot resume of the intercepted tool. Forward
82
+ * the response body unchanged and the widget answers with one automatic turn.
83
+ */
84
+ readonly resume?: {
85
+ readonly tool: string;
86
+ };
45
87
  readonly configuration?: AssistantConfiguration;
46
88
  }
89
+ /** The service's refusal codes for a sign-in ticket the exchange would not honour. */
90
+ declare const ASSISTANT_ELEVATION_REFUSAL_CODES: readonly ["elevation_ticket_invalid", "elevation_ticket_expired", "elevation_tenant_mismatch", "elevation_session_unavailable", "elevation_already_signed_in"];
91
+ type AssistantElevationRefusalCode = (typeof ASSISTANT_ELEVATION_REFUSAL_CODES)[number];
92
+ /**
93
+ * Structurally mirrors the browser client's `AssistantErrorDetail` (declared locally: the backend
94
+ * entry must not pull the browser transport module into its graph). `code` is a closed union owned
95
+ * by this package; `serviceCode` passes the service's machine code through additively.
96
+ */
97
+ interface AssistantSessionExchangeErrorDetail {
98
+ readonly code: 'session_exchange_failed';
99
+ readonly status: number;
100
+ /** 5xx infrastructure failures may be retried; a refused exchange must not be — tickets are single-use. */
101
+ readonly retryable: boolean;
102
+ /** The service's machine code when the body carried one, e.g. `elevation_ticket_expired`. */
103
+ readonly serviceCode?: string;
104
+ }
105
+ declare class AssistantSessionExchangeError extends Error {
106
+ readonly detail: AssistantSessionExchangeErrorDetail;
107
+ constructor(detail: AssistantSessionExchangeErrorDetail, message: string);
108
+ /**
109
+ * The narrowed sign-in refusal, when this failure is one. `elevation_ticket_expired` means the
110
+ * visitor took too long — re-prompt; `elevation_tenant_mismatch` means a client reached for a
111
+ * conversation it does not own — alert someone, never retry.
112
+ */
113
+ get elevationRefusal(): AssistantElevationRefusalCode | undefined;
114
+ }
47
115
  declare function createAssistantSession(input: CreateAssistantSessionInput, dependencies?: {
48
116
  readonly fetch?: typeof fetch;
49
117
  }): Promise<AssistantSession>;
50
118
 
51
- export { type AssistantSession, type CreateAssistantSessionInput, createAssistantSession };
119
+ export { ASSISTANT_ELEVATION_REFUSAL_CODES, type AssistantElevationRefusalCode, type AssistantSession, AssistantSessionExchangeError, type AssistantSessionExchangeErrorDetail, type CreateAssistantSessionInput, createAssistantSession };
package/dist/server.js CHANGED
@@ -1,7 +1,48 @@
1
1
  import "./chunk-5FUTL2UF.js";
2
2
 
3
3
  // src/server.ts
4
+ var ASSISTANT_ELEVATION_REFUSAL_CODES = [
5
+ "elevation_ticket_invalid",
6
+ "elevation_ticket_expired",
7
+ "elevation_tenant_mismatch",
8
+ "elevation_session_unavailable",
9
+ "elevation_already_signed_in"
10
+ ];
11
+ var AssistantSessionExchangeError = class extends Error {
12
+ detail;
13
+ constructor(detail, message) {
14
+ super(message);
15
+ this.name = "AssistantSessionExchangeError";
16
+ this.detail = detail;
17
+ }
18
+ /**
19
+ * The narrowed sign-in refusal, when this failure is one. `elevation_ticket_expired` means the
20
+ * visitor took too long — re-prompt; `elevation_tenant_mismatch` means a client reached for a
21
+ * conversation it does not own — alert someone, never retry.
22
+ */
23
+ get elevationRefusal() {
24
+ const code = this.detail.serviceCode;
25
+ return code !== void 0 && ASSISTANT_ELEVATION_REFUSAL_CODES.includes(code) ? code : void 0;
26
+ }
27
+ };
28
+ async function exchangeError(response) {
29
+ const body = await response.json().catch(() => void 0);
30
+ const serviceCode = typeof body?.code === "string" ? body.code : void 0;
31
+ return new AssistantSessionExchangeError(
32
+ {
33
+ code: "session_exchange_failed",
34
+ status: response.status,
35
+ // `elevation_unavailable` is a 503 an operator has to fix; retrying cannot help.
36
+ retryable: response.status >= 500 && serviceCode !== "elevation_unavailable",
37
+ ...serviceCode === void 0 ? {} : { serviceCode }
38
+ },
39
+ `Assistant session exchange failed (${response.status})`
40
+ );
41
+ }
4
42
  async function createAssistantSession(input, dependencies = {}) {
43
+ if (input.signInTicket !== void 0 && input.context !== void 0) {
44
+ throw new Error("context does not apply when spending a sign-in ticket");
45
+ }
5
46
  const request = dependencies.fetch ?? fetch;
6
47
  const serviceUrl = input.serviceUrl.replace(/\/$/, "");
7
48
  const credentials = Buffer.from(`${input.clientId}:${input.clientSecret}`, "utf8").toString(
@@ -17,16 +58,20 @@ async function createAssistantSession(input, dependencies = {}) {
17
58
  body: JSON.stringify({
18
59
  origin: input.origin,
19
60
  user: input.user,
61
+ ...input.signInTicket === void 0 ? {} : { signInTicket: input.signInTicket },
62
+ ...input.signInTicket !== void 0 && input.resume !== void 0 ? { resume: input.resume } : {},
20
63
  ...input.claims ? { claims: input.claims } : {},
21
64
  ...input.context ? { context: input.context } : {},
22
65
  ...input.preferences ? { preferences: input.preferences } : {},
23
66
  ...input.routing ? { routing: input.routing } : {}
24
67
  })
25
68
  });
26
- if (!response.ok) throw new Error(`Assistant session exchange failed (${response.status})`);
69
+ if (!response.ok) throw await exchangeError(response);
27
70
  return await response.json();
28
71
  }
29
72
  export {
73
+ ASSISTANT_ELEVATION_REFUSAL_CODES,
74
+ AssistantSessionExchangeError,
30
75
  createAssistantSession
31
76
  };
32
77
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts"],"sourcesContent":["import type { AssistantConfiguration } from './appearance.js';\n\nexport interface CreateAssistantSessionInput {\n readonly serviceUrl: string;\n readonly clientId: string;\n readonly clientSecret: string;\n /** Browser origin to bind into the short-lived assistant session. */\n readonly origin: string;\n readonly user: {\n readonly id: string;\n readonly email?: string;\n readonly name?: string;\n readonly tenant?: string;\n readonly roles?: readonly string[];\n readonly scopes?: readonly string[];\n };\n readonly context?: Readonly<Record<string, string | number | boolean | null>>;\n /** Backend-verified user preferences; these outrank untrusted browser presentation hints. */\n readonly preferences?: {\n readonly locale?: string;\n readonly timeZone?: string;\n };\n /** Backend-verified connector routes keyed by authored `customerEndpoint` name. */\n readonly routing?: {\n readonly endpoints: Readonly<Record<string, string>>;\n };\n /**\n * Verified session claims from your authenticated backend. Only claims the server declares in\n * `embeddedAssistant({ sessionClaims })` reach tools (`\\${user.claims.<key>}`) and, when marked\n * `exposeToModel`, the assistant's identity context. Flat scalars only.\n */\n readonly claims?: Readonly<Record<string, string | number | boolean | null>>;\n}\n\nexport interface AssistantSession {\n readonly token: string;\n readonly expiresAt: string;\n readonly endpoints: {\n readonly turns: string;\n readonly toolConfirmations: string;\n readonly interactions?: string;\n readonly apps?: string;\n /** Additive hosted sandbox document for widget frames; absent on older services. */\n readonly sandbox?: string;\n };\n readonly configuration?: AssistantConfiguration;\n}\n\nexport async function createAssistantSession(\n input: CreateAssistantSessionInput,\n dependencies: { readonly fetch?: typeof fetch } = {},\n): Promise<AssistantSession> {\n const request = dependencies.fetch ?? fetch;\n const serviceUrl = input.serviceUrl.replace(/\\/$/, '');\n const credentials = Buffer.from(`${input.clientId}:${input.clientSecret}`, 'utf8').toString(\n 'base64',\n );\n const response = await request(`${serviceUrl}/v1/assistant/sessions`, {\n method: 'POST',\n headers: {\n Authorization: `Basic ${credentials}`,\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n origin: input.origin,\n user: input.user,\n ...(input.claims ? { claims: input.claims } : {}),\n ...(input.context ? { context: input.context } : {}),\n ...(input.preferences ? { preferences: input.preferences } : {}),\n ...(input.routing ? { routing: input.routing } : {}),\n }),\n });\n if (!response.ok) throw new Error(`Assistant session exchange failed (${response.status})`);\n return (await response.json()) as AssistantSession;\n}\n"],"mappings":";;;AAgDA,eAAsB,uBACpB,OACA,eAAkD,CAAC,GACxB;AAC3B,QAAM,UAAU,aAAa,SAAS;AACtC,QAAM,aAAa,MAAM,WAAW,QAAQ,OAAO,EAAE;AACrD,QAAM,cAAc,OAAO,KAAK,GAAG,MAAM,QAAQ,IAAI,MAAM,YAAY,IAAI,MAAM,EAAE;AAAA,IACjF;AAAA,EACF;AACA,QAAM,WAAW,MAAM,QAAQ,GAAG,UAAU,0BAA0B;AAAA,IACpE,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,eAAe,SAAS,WAAW;AAAA,MACnC,QAAQ;AAAA,MACR,gBAAgB;AAAA,IAClB;AAAA,IACA,MAAM,KAAK,UAAU;AAAA,MACnB,QAAQ,MAAM;AAAA,MACd,MAAM,MAAM;AAAA,MACZ,GAAI,MAAM,SAAS,EAAE,QAAQ,MAAM,OAAO,IAAI,CAAC;AAAA,MAC/C,GAAI,MAAM,UAAU,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,MAClD,GAAI,MAAM,cAAc,EAAE,aAAa,MAAM,YAAY,IAAI,CAAC;AAAA,MAC9D,GAAI,MAAM,UAAU,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,IACpD,CAAC;AAAA,EACH,CAAC;AACD,MAAI,CAAC,SAAS,GAAI,OAAM,IAAI,MAAM,sCAAsC,SAAS,MAAM,GAAG;AAC1F,SAAQ,MAAM,SAAS,KAAK;AAC9B;","names":[]}
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["import type { AssistantConfiguration } from './appearance.js';\n\ninterface AssistantSessionExchangeBase {\n readonly serviceUrl: string;\n readonly clientId: string;\n readonly clientSecret: string;\n /** Browser origin to bind into the short-lived assistant session. */\n readonly origin: string;\n /** The signed-in person your backend vouches for — on both arms: an elevation IS this vouching. */\n readonly user: {\n readonly id: string;\n readonly email?: string;\n readonly name?: string;\n readonly tenant?: string;\n readonly roles?: readonly string[];\n readonly scopes?: readonly string[];\n };\n /** Backend-verified user preferences; these outrank untrusted browser presentation hints. */\n readonly preferences?: {\n readonly locale?: string;\n readonly timeZone?: string;\n };\n /**\n * Verified session claims from your authenticated backend. Only claims the server declares in\n * `embeddedAssistant({ sessionClaims })` reach tools (`\\${user.claims.<key>}`) and, when marked\n * `exposeToModel`, the assistant's identity context. Flat scalars only.\n */\n readonly claims?: Readonly<Record<string, string | number | boolean | null>>;\n}\n\n/**\n * Fresh mint XOR mid-conversation sign-in, exclusive rather than merged for the same reason the\n * client's `sessionEndpoint`/`embedId` pair is: the two are different operations, and the wrong\n * combination should fail to typecheck instead of silently picking a meaning.\n *\n * `context` applies only when a session is being created; an elevation keeps the existing\n * conversation, so it is excluded rather than silently ignored. `routing` is allowed on both arms —\n * elevation is the first authenticated moment, so it is the only chance a routed connector's\n * session ever gets its backend-verified customer routes.\n */\nexport type CreateAssistantSessionInput =\n | (AssistantSessionExchangeBase & {\n readonly signInTicket?: undefined;\n readonly context?: Readonly<Record<string, string | number | boolean | null>>;\n /** Backend-verified connector routes keyed by authored `customerEndpoint` name. */\n readonly routing?: {\n readonly endpoints: Readonly<Record<string, string>>;\n };\n /** Resume applies only when spending a sign-in ticket; a fresh mint has nothing pending. */\n readonly resume?: undefined;\n })\n | (AssistantSessionExchangeBase & {\n /**\n * Single-use sign-in ticket from the widget's `assistant-sign-in-requested` event\n * (ADR 0201, 5.6b). Spending it binds this signed-in user to the visitor's existing\n * anonymous conversation instead of minting a new one. Unrelated to the server-held\n * interaction continuation, which never reaches browser code.\n */\n readonly signInTicket: string;\n readonly context?: undefined;\n /** Backend-verified connector routes keyed by authored `customerEndpoint` name. */\n readonly routing?: {\n readonly endpoints: Readonly<Record<string, string>>;\n };\n /**\n * Whether the service resumes the intercepted tool call as the elevated session's first\n * turn (issue #1177). ON by default — omit it and the visitor's pending question answers\n * itself after sign-in; pass `false` if your application provides its own affordance.\n */\n readonly resume?: boolean;\n });\n\nexport interface AssistantSession {\n readonly token: string;\n readonly expiresAt: string;\n readonly endpoints: {\n readonly turns: string;\n readonly toolConfirmations: string;\n readonly interactions?: string;\n readonly apps?: string;\n /** Additive hosted sandbox document for widget frames; absent on older services. */\n readonly sandbox?: string;\n };\n /**\n * Present only on an elevation that armed the one-shot resume of the intercepted tool. Forward\n * the response body unchanged and the widget answers with one automatic turn.\n */\n readonly resume?: { readonly tool: string };\n readonly configuration?: AssistantConfiguration;\n}\n\n/** The service's refusal codes for a sign-in ticket the exchange would not honour. */\nexport const ASSISTANT_ELEVATION_REFUSAL_CODES = [\n 'elevation_ticket_invalid',\n 'elevation_ticket_expired',\n 'elevation_tenant_mismatch',\n 'elevation_session_unavailable',\n 'elevation_already_signed_in',\n] as const;\nexport type AssistantElevationRefusalCode = (typeof ASSISTANT_ELEVATION_REFUSAL_CODES)[number];\n\n/**\n * Structurally mirrors the browser client's `AssistantErrorDetail` (declared locally: the backend\n * entry must not pull the browser transport module into its graph). `code` is a closed union owned\n * by this package; `serviceCode` passes the service's machine code through additively.\n */\nexport interface AssistantSessionExchangeErrorDetail {\n readonly code: 'session_exchange_failed';\n readonly status: number;\n /** 5xx infrastructure failures may be retried; a refused exchange must not be — tickets are single-use. */\n readonly retryable: boolean;\n /** The service's machine code when the body carried one, e.g. `elevation_ticket_expired`. */\n readonly serviceCode?: string;\n}\n\nexport class AssistantSessionExchangeError extends Error {\n readonly detail: AssistantSessionExchangeErrorDetail;\n\n constructor(detail: AssistantSessionExchangeErrorDetail, message: string) {\n super(message);\n this.name = 'AssistantSessionExchangeError';\n this.detail = detail;\n }\n\n /**\n * The narrowed sign-in refusal, when this failure is one. `elevation_ticket_expired` means the\n * visitor took too long — re-prompt; `elevation_tenant_mismatch` means a client reached for a\n * conversation it does not own — alert someone, never retry.\n */\n get elevationRefusal(): AssistantElevationRefusalCode | undefined {\n const code = this.detail.serviceCode;\n return code !== undefined &&\n (ASSISTANT_ELEVATION_REFUSAL_CODES as readonly string[]).includes(code)\n ? (code as AssistantElevationRefusalCode)\n : undefined;\n }\n}\n\n/** Never throws while reading the body — a proxy can answer with HTML instead of JSON. */\nasync function exchangeError(response: Response): Promise<AssistantSessionExchangeError> {\n const body = (await response.json().catch(() => undefined)) as\n | { readonly error?: unknown; readonly code?: unknown }\n | undefined;\n const serviceCode = typeof body?.code === 'string' ? body.code : undefined;\n return new AssistantSessionExchangeError(\n {\n code: 'session_exchange_failed',\n status: response.status,\n // `elevation_unavailable` is a 503 an operator has to fix; retrying cannot help.\n retryable: response.status >= 500 && serviceCode !== 'elevation_unavailable',\n ...(serviceCode === undefined ? {} : { serviceCode }),\n },\n `Assistant session exchange failed (${response.status})`,\n );\n}\n\nexport async function createAssistantSession(\n input: CreateAssistantSessionInput,\n dependencies: { readonly fetch?: typeof fetch } = {},\n): Promise<AssistantSession> {\n if (input.signInTicket !== undefined && (input as { context?: unknown }).context !== undefined) {\n // Mirrors resolveSessionSource: silently dropping what the service ignores would pick a\n // meaning the developer did not intend.\n throw new Error('context does not apply when spending a sign-in ticket');\n }\n const request = dependencies.fetch ?? fetch;\n const serviceUrl = input.serviceUrl.replace(/\\/$/, '');\n const credentials = Buffer.from(`${input.clientId}:${input.clientSecret}`, 'utf8').toString(\n 'base64',\n );\n const response = await request(`${serviceUrl}/v1/assistant/sessions`, {\n method: 'POST',\n headers: {\n Authorization: `Basic ${credentials}`,\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n origin: input.origin,\n user: input.user,\n ...(input.signInTicket === undefined ? {} : { signInTicket: input.signInTicket }),\n ...(input.signInTicket !== undefined && input.resume !== undefined\n ? { resume: input.resume }\n : {}),\n ...(input.claims ? { claims: input.claims } : {}),\n ...(input.context ? { context: input.context } : {}),\n ...(input.preferences ? { preferences: input.preferences } : {}),\n ...(input.routing ? { routing: input.routing } : {}),\n }),\n });\n // A fresh mint answers 201, an elevation 200; both are the same wire shape (ADR 0151).\n if (!response.ok) throw await exchangeError(response);\n return (await response.json()) as AssistantSession;\n}\n"],"mappings":";;;AA4FO,IAAM,oCAAoC;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAiBO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EAC9C;AAAA,EAET,YAAY,QAA6C,SAAiB;AACxE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,mBAA8D;AAChE,UAAM,OAAO,KAAK,OAAO;AACzB,WAAO,SAAS,UACb,kCAAwD,SAAS,IAAI,IACnE,OACD;AAAA,EACN;AACF;AAGA,eAAe,cAAc,UAA4D;AACvF,QAAM,OAAQ,MAAM,SAAS,KAAK,EAAE,MAAM,MAAM,MAAS;AAGzD,QAAM,cAAc,OAAO,MAAM,SAAS,WAAW,KAAK,OAAO;AACjE,SAAO,IAAI;AAAA,IACT;AAAA,MACE,MAAM;AAAA,MACN,QAAQ,SAAS;AAAA;AAAA,MAEjB,WAAW,SAAS,UAAU,OAAO,gBAAgB;AAAA,MACrD,GAAI,gBAAgB,SAAY,CAAC,IAAI,EAAE,YAAY;AAAA,IACrD;AAAA,IACA,sCAAsC,SAAS,MAAM;AAAA,EACvD;AACF;A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+ "version": "1.21.0",
4
4
  "description": "Embed the Noodle Seed customer-branded assistant in your web app with a Web Component, managed or custom React UI, DOM-free client, and backend session helper. Authoring and deploying the server is @noodleseed/one.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {