@noodleseed/assistant 1.2.0 → 1.3.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/README.md +136 -20
- package/dist/{appearance-KDbtkt2G.d.cts → appearance-BLO7kFYB.d.cts} +39 -0
- package/dist/{appearance-KDbtkt2G.d.ts → appearance-BLO7kFYB.d.ts} +39 -0
- package/dist/{chunk-WUDHE5BD.js → chunk-N6TFOYOX.js} +7 -1
- package/dist/chunk-N6TFOYOX.js.map +1 -0
- package/dist/chunk-QMDSNLTA.js +4459 -0
- package/dist/chunk-QMDSNLTA.js.map +1 -0
- package/dist/{client-DkAfqcSb.d.ts → client-Bm990MFE.d.cts} +2 -1
- package/dist/{client-CwvdK4O6.d.cts → client-Dd7_LZLY.d.ts} +2 -1
- package/dist/client.cjs +6 -0
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +2 -2
- package/dist/client.d.ts +2 -2
- package/dist/client.js +1 -1
- package/dist/index.cjs +3686 -334
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/react.cjs +3693 -335
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +2 -2
- package/dist/react.d.ts +2 -2
- package/dist/react.js +11 -5
- package/dist/react.js.map +1 -1
- package/dist/server.d.cts +1 -1
- package/dist/server.d.ts +1 -1
- package/package.json +5 -1
- package/dist/chunk-J2YDKISA.js +0 -1113
- package/dist/chunk-J2YDKISA.js.map +0 -1
- package/dist/chunk-WUDHE5BD.js.map +0 -1
package/README.md
CHANGED
|
@@ -15,10 +15,10 @@ assistant session.
|
|
|
15
15
|
|
|
16
16
|
The model configuration and SaaS integration credentials have different owners:
|
|
17
17
|
|
|
18
|
-
| Owner
|
|
19
|
-
|
|
|
20
|
-
| Noodle deployment | `ASSISTANT_MODEL_BASE_URL`, `ASSISTANT_MODEL`, `ASSISTANT_MODEL_API_KEY`
|
|
21
|
-
| Customer backend
|
|
18
|
+
| Owner | Configuration | Destination |
|
|
19
|
+
| ----------------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------------- |
|
|
20
|
+
| Noodle deployment | `ASSISTANT_MODEL_BASE_URL`, `ASSISTANT_MODEL`, `ASSISTANT_MODEL_API_KEY` | Managed with `noodle variables set` / `noodle secrets set` |
|
|
21
|
+
| Customer backend | `NOODLE_SERVICE_URL`, `NOODLE_ASSISTANT_CLIENT_ID`, `NOODLE_ASSISTANT_CLIENT_SECRET` | Backend environment or secret manager only |
|
|
22
22
|
|
|
23
23
|
`allowedOrigins` accepts exact origins. Production origins must be HTTPS; plain HTTP is accepted only for
|
|
24
24
|
loopback development origins such as `http://localhost:3000`. Local MCP authoring remains available without
|
|
@@ -41,6 +41,109 @@ example:
|
|
|
41
41
|
npm install @noodleseed/assistant
|
|
42
42
|
```
|
|
43
43
|
|
|
44
|
+
### Author `server.ts`
|
|
45
|
+
|
|
46
|
+
Put customer identity and colors in the server's top-level `branding` option. Put only assistant-specific
|
|
47
|
+
structure and treatment in `embeddedAssistant({ presentation })`:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import {
|
|
51
|
+
embeddedAssistant,
|
|
52
|
+
openAICompatible,
|
|
53
|
+
secret,
|
|
54
|
+
server,
|
|
55
|
+
tool,
|
|
56
|
+
variable,
|
|
57
|
+
z,
|
|
58
|
+
} from "@noodleseed/one";
|
|
59
|
+
|
|
60
|
+
export default server(
|
|
61
|
+
"acme_support",
|
|
62
|
+
{
|
|
63
|
+
title: "Acme Support",
|
|
64
|
+
version: "1.0.0",
|
|
65
|
+
branding: {
|
|
66
|
+
name: "Acme Assistant",
|
|
67
|
+
accent: "#5B4CF0",
|
|
68
|
+
surface: "#FFFFFF",
|
|
69
|
+
surfaceDark: "#15131A",
|
|
70
|
+
mark: { uri: "https://assets.acme.example/mark.svg", alt: "Acme" },
|
|
71
|
+
colorScheme: "auto",
|
|
72
|
+
},
|
|
73
|
+
assistant: embeddedAssistant({
|
|
74
|
+
model: openAICompatible({
|
|
75
|
+
baseUrl: variable("ASSISTANT_MODEL_BASE_URL"),
|
|
76
|
+
model: variable("ASSISTANT_MODEL"),
|
|
77
|
+
apiKey: secret("ASSISTANT_MODEL_API_KEY"),
|
|
78
|
+
}),
|
|
79
|
+
allowedOrigins: ["http://localhost:3000", "https://app.acme.example"],
|
|
80
|
+
layout: {
|
|
81
|
+
mode: "floating",
|
|
82
|
+
position: "bottom-right",
|
|
83
|
+
panelWidth: 520,
|
|
84
|
+
panelMinHeight: 540,
|
|
85
|
+
panelMaxHeight: 740,
|
|
86
|
+
edgeOffset: 24,
|
|
87
|
+
},
|
|
88
|
+
behavior: { showTimestamps: true },
|
|
89
|
+
labels: {
|
|
90
|
+
welcomeHeading: "How can Acme help?",
|
|
91
|
+
welcomeMessage: "Fast answers from the tools your team already uses.",
|
|
92
|
+
composerPlaceholder: "Message Acme Support…",
|
|
93
|
+
sessionReady: "Acme support is online",
|
|
94
|
+
},
|
|
95
|
+
presentation: {
|
|
96
|
+
panel: {
|
|
97
|
+
surface: "solid",
|
|
98
|
+
elevation: "dramatic",
|
|
99
|
+
border: "strong",
|
|
100
|
+
radius: 20,
|
|
101
|
+
},
|
|
102
|
+
launcher: {
|
|
103
|
+
icon: "chat",
|
|
104
|
+
size: "lg",
|
|
105
|
+
status: "session",
|
|
106
|
+
effect: "pulse",
|
|
107
|
+
},
|
|
108
|
+
header: {
|
|
109
|
+
mark: "status",
|
|
110
|
+
badge: { text: "Support online", tone: "success", indicator: true },
|
|
111
|
+
},
|
|
112
|
+
composer: {
|
|
113
|
+
leadingIcon: "brand-mark",
|
|
114
|
+
sendIcon: "paper-plane",
|
|
115
|
+
shape: "rounded",
|
|
116
|
+
},
|
|
117
|
+
messages: { userStyle: "accent", assistantStyle: "bubble" },
|
|
118
|
+
},
|
|
119
|
+
}),
|
|
120
|
+
},
|
|
121
|
+
[
|
|
122
|
+
tool("status", {
|
|
123
|
+
description: "Read the support service status.",
|
|
124
|
+
input: z.object({}),
|
|
125
|
+
output: z.object({ status: z.string() }),
|
|
126
|
+
fulfil: () => ({ status: "operational" }),
|
|
127
|
+
}),
|
|
128
|
+
],
|
|
129
|
+
);
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`presentation` is a closed set of semantic primitives for the panel, launcher, header, composer, and
|
|
133
|
+
messages. The Atlas-style product treatment above is the maximum supported customization level: it can
|
|
134
|
+
change geometry, status decoration, controls, and message treatment without replacing the assistant's
|
|
135
|
+
structure. It has no raw HTML, CSS, inline SVG, class-name, or callback field;
|
|
136
|
+
markup-looking text stays text. `presentation.panel.radius` is a bounded panel-specific geometry override,
|
|
137
|
+
not a second color or identity source. An HTTPS or packaged SVG referenced by `branding.logo`, `branding.mark`, or
|
|
138
|
+
`branding.avatar` is a bounded asset, not inline renderer markup.
|
|
139
|
+
|
|
140
|
+
If `presentation` is omitted, the complete Halo baseline remains: glass panel, soft elevation, subtle
|
|
141
|
+
border/motion, medium brand-mark launcher without status or effect, undecorated header, pill composer with
|
|
142
|
+
no leading icon and an arrow-up send icon, and bubble user/plain assistant messages at comfortable width.
|
|
143
|
+
Partial objects merge with those defaults.
|
|
144
|
+
|
|
145
|
+
### Configure and deploy
|
|
146
|
+
|
|
44
147
|
Configure the model through Noodle managed config, validate, and deploy the assistant-enabled server before
|
|
45
148
|
creating the embed client:
|
|
46
149
|
|
|
@@ -63,7 +166,7 @@ Move those values to the customer backend's secret manager without printing or c
|
|
|
63
166
|
route can exchange the current signed-in user like this:
|
|
64
167
|
|
|
65
168
|
```ts
|
|
66
|
-
import { createAssistantSession } from
|
|
169
|
+
import { createAssistantSession } from "@noodleseed/assistant/server";
|
|
67
170
|
|
|
68
171
|
export async function POST(request: Request) {
|
|
69
172
|
const user = await requireCurrentUser(request);
|
|
@@ -84,17 +187,20 @@ export async function POST(request: Request) {
|
|
|
84
187
|
Then add the framework-neutral element:
|
|
85
188
|
|
|
86
189
|
```ts
|
|
87
|
-
import
|
|
190
|
+
import "@noodleseed/assistant";
|
|
88
191
|
```
|
|
89
192
|
|
|
90
193
|
```html
|
|
91
|
-
<noodle-assistant
|
|
194
|
+
<noodle-assistant
|
|
195
|
+
session-endpoint="/api/assistant/session"
|
|
196
|
+
theme="auto"
|
|
197
|
+
></noodle-assistant>
|
|
92
198
|
```
|
|
93
199
|
|
|
94
200
|
Or use React:
|
|
95
201
|
|
|
96
202
|
```tsx
|
|
97
|
-
import { NoodleAssistant } from
|
|
203
|
+
import { NoodleAssistant } from "@noodleseed/assistant/react";
|
|
98
204
|
|
|
99
205
|
<NoodleAssistant sessionEndpoint="/api/assistant/session" theme="auto" />;
|
|
100
206
|
```
|
|
@@ -103,10 +209,10 @@ For a customer-owned renderer, subscribe to the same turn and interaction stream
|
|
|
103
209
|
custom element or touching browser storage:
|
|
104
210
|
|
|
105
211
|
```ts
|
|
106
|
-
import { createAssistantClient } from
|
|
212
|
+
import { createAssistantClient } from "@noodleseed/assistant/client";
|
|
107
213
|
|
|
108
214
|
const assistant = createAssistantClient({
|
|
109
|
-
sessionEndpoint:
|
|
215
|
+
sessionEndpoint: "/api/assistant/session",
|
|
110
216
|
clientContext: () => ({
|
|
111
217
|
locale: navigator.language,
|
|
112
218
|
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
@@ -114,18 +220,18 @@ const assistant = createAssistantClient({
|
|
|
114
220
|
});
|
|
115
221
|
|
|
116
222
|
assistant.updateModelContext({
|
|
117
|
-
content: [{ type:
|
|
118
|
-
structuredContent: { widget: { name:
|
|
223
|
+
content: [{ type: "text", text: "The time-off form is mounted." }],
|
|
224
|
+
structuredContent: { widget: { name: "time-off", lifecycle: "mounted" } },
|
|
119
225
|
});
|
|
120
226
|
|
|
121
227
|
const unsubscribe = assistant.subscribe((event) => {
|
|
122
228
|
renderAssistantEvent(event);
|
|
123
|
-
if (event.event ===
|
|
229
|
+
if (event.event === "view_available") {
|
|
124
230
|
renderRegisteredView(event.data.resourceUri, event.data.result);
|
|
125
231
|
}
|
|
126
232
|
});
|
|
127
|
-
await assistant.sendMessage(
|
|
128
|
-
await assistant.respond(
|
|
233
|
+
await assistant.sendMessage("Book next Thursday and Friday off");
|
|
234
|
+
await assistant.respond("interaction_123", { action: "accept" });
|
|
129
235
|
// Resolve one interaction once; alternatives are { action: 'decline' } or { action: 'cancel' }.
|
|
130
236
|
|
|
131
237
|
unsubscribe();
|
|
@@ -173,7 +279,7 @@ fetch the `ui://` URI or inject its resource HTML into your page. The standard e
|
|
|
173
279
|
but forwards the same detail as a DOM event:
|
|
174
280
|
|
|
175
281
|
```ts
|
|
176
|
-
element.addEventListener(
|
|
282
|
+
element.addEventListener("assistant-view-available", (event) => {
|
|
177
283
|
renderRegisteredView(event.detail.resourceUri, event.detail.result);
|
|
178
284
|
});
|
|
179
285
|
```
|
|
@@ -186,15 +292,18 @@ replay across sessions. React applications may observe recovery and structured f
|
|
|
186
292
|
<NoodleAssistant
|
|
187
293
|
sessionEndpoint="/api/assistant/session"
|
|
188
294
|
onSessionExpired={() => reportAssistantRecovery()}
|
|
189
|
-
onError={({ code, status, retryable }) =>
|
|
190
|
-
|
|
295
|
+
onError={({ code, status, retryable }) =>
|
|
296
|
+
reportAssistantError({ code, status, retryable })
|
|
297
|
+
}
|
|
298
|
+
/>
|
|
191
299
|
```
|
|
192
300
|
|
|
193
301
|
`createAssistantSession` returns the opaque token, expiry, resolved non-secret configuration, and explicit
|
|
194
302
|
turn/interaction endpoint URLs. Forward that response unchanged to the component or headless client.
|
|
195
303
|
|
|
196
|
-
The MCP server's top-level `branding` block
|
|
197
|
-
assistant. Set semantic CSS variables only for application-level integration
|
|
304
|
+
The MCP server's top-level `branding` block is the sole deployment source for identity and colors shared by
|
|
305
|
+
widgets and the assistant. Set public semantic CSS variables only for application-level integration
|
|
306
|
+
overrides:
|
|
198
307
|
|
|
199
308
|
```css
|
|
200
309
|
noodle-assistant {
|
|
@@ -204,6 +313,13 @@ noodle-assistant {
|
|
|
204
313
|
}
|
|
205
314
|
```
|
|
206
315
|
|
|
316
|
+
For each matching region or token, precedence is host-provided slot content or a public CSS custom property,
|
|
317
|
+
then compiled server `presentation`/`branding`, then Halo defaults. The public slots are `launcher-icon`,
|
|
318
|
+
`header-leading`, `header-actions`, `empty-state`, `composer-leading`, `composer-trailing`, and
|
|
319
|
+
`conversation-footer`; slotted host DOM replaces the renderer fallback for that region. Slots are a trusted
|
|
320
|
+
embedding-page integration API, not a way to put HTML or callbacks in deployment configuration. Internal
|
|
321
|
+
shadow-DOM selectors and classes are not public API.
|
|
322
|
+
|
|
207
323
|
Server branding controls customer name, themed logo/mark/avatar assets, semantic light/dark colors, density,
|
|
208
324
|
radius, typography, and automatic theme. `embeddedAssistant(...)` controls floating/inline/drawer layout,
|
|
209
325
|
position and dimensions, mobile and launcher/header/avatar/timestamp behavior, visible labels, suggested
|
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
type AssistantThemeMode = 'auto' | 'light' | 'dark';
|
|
2
2
|
type AssistantLayoutMode = 'floating' | 'inline' | 'drawer';
|
|
3
3
|
type AssistantPosition = 'bottom-left' | 'bottom-right';
|
|
4
|
+
type AssistantPresentationTone = 'neutral' | 'success' | 'warning' | 'danger';
|
|
5
|
+
interface AssistantPresentationConfiguration {
|
|
6
|
+
readonly panel?: {
|
|
7
|
+
readonly surface?: 'solid' | 'glass';
|
|
8
|
+
readonly elevation?: 'soft' | 'dramatic';
|
|
9
|
+
readonly border?: 'subtle' | 'strong';
|
|
10
|
+
readonly radius?: number;
|
|
11
|
+
};
|
|
12
|
+
readonly launcher?: {
|
|
13
|
+
readonly icon?: 'brand-mark' | 'chat' | 'none';
|
|
14
|
+
readonly size?: 'md' | 'lg';
|
|
15
|
+
readonly status?: 'none' | 'session';
|
|
16
|
+
readonly effect?: 'none' | 'pulse';
|
|
17
|
+
};
|
|
18
|
+
readonly header?: {
|
|
19
|
+
readonly mark?: 'none' | 'brand-mark' | 'status';
|
|
20
|
+
readonly badge?: {
|
|
21
|
+
readonly text: string;
|
|
22
|
+
readonly tone?: AssistantPresentationTone;
|
|
23
|
+
readonly indicator?: boolean;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
readonly composer?: {
|
|
27
|
+
readonly leadingIcon?: 'none' | 'brand-mark';
|
|
28
|
+
readonly sendIcon?: 'arrow-up' | 'paper-plane';
|
|
29
|
+
readonly shape?: 'rounded' | 'pill';
|
|
30
|
+
};
|
|
31
|
+
readonly messages?: {
|
|
32
|
+
readonly userStyle?: 'bubble' | 'accent';
|
|
33
|
+
readonly assistantStyle?: 'plain' | 'bubble';
|
|
34
|
+
};
|
|
35
|
+
}
|
|
4
36
|
interface AssistantConfiguration {
|
|
5
37
|
readonly branding?: {
|
|
6
38
|
readonly name?: string;
|
|
@@ -50,6 +82,7 @@ interface AssistantUiConfiguration {
|
|
|
50
82
|
readonly panelWidth?: number;
|
|
51
83
|
readonly panelMinHeight?: number;
|
|
52
84
|
readonly panelMaxHeight?: number;
|
|
85
|
+
readonly edgeOffset?: number;
|
|
53
86
|
readonly zIndex?: number;
|
|
54
87
|
readonly density?: 'compact' | 'comfortable';
|
|
55
88
|
readonly mobileFullscreen?: boolean;
|
|
@@ -64,6 +97,7 @@ interface AssistantUiConfiguration {
|
|
|
64
97
|
readonly showTimestamps?: boolean;
|
|
65
98
|
};
|
|
66
99
|
readonly labels?: Partial<AssistantLabels>;
|
|
100
|
+
readonly presentation?: AssistantPresentationConfiguration;
|
|
67
101
|
readonly suggestedPrompts?: readonly string[];
|
|
68
102
|
readonly privacyUrl?: string;
|
|
69
103
|
readonly termsUrl?: string;
|
|
@@ -74,6 +108,7 @@ interface AssistantLabels {
|
|
|
74
108
|
readonly welcomeHeading: string;
|
|
75
109
|
readonly welcomeMessage: string;
|
|
76
110
|
readonly composerPlaceholder: string;
|
|
111
|
+
readonly thinking: string;
|
|
77
112
|
readonly send: string;
|
|
78
113
|
readonly stop: string;
|
|
79
114
|
readonly close: string;
|
|
@@ -83,6 +118,10 @@ interface AssistantLabels {
|
|
|
83
118
|
readonly retry: string;
|
|
84
119
|
readonly unavailable: string;
|
|
85
120
|
readonly sessionExpired: string;
|
|
121
|
+
readonly sessionIdle: string;
|
|
122
|
+
readonly sessionLoading: string;
|
|
123
|
+
readonly sessionReady: string;
|
|
124
|
+
readonly sessionError: string;
|
|
86
125
|
}
|
|
87
126
|
|
|
88
127
|
export type { AssistantThemeMode as A, AssistantConfiguration as a };
|
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
type AssistantThemeMode = 'auto' | 'light' | 'dark';
|
|
2
2
|
type AssistantLayoutMode = 'floating' | 'inline' | 'drawer';
|
|
3
3
|
type AssistantPosition = 'bottom-left' | 'bottom-right';
|
|
4
|
+
type AssistantPresentationTone = 'neutral' | 'success' | 'warning' | 'danger';
|
|
5
|
+
interface AssistantPresentationConfiguration {
|
|
6
|
+
readonly panel?: {
|
|
7
|
+
readonly surface?: 'solid' | 'glass';
|
|
8
|
+
readonly elevation?: 'soft' | 'dramatic';
|
|
9
|
+
readonly border?: 'subtle' | 'strong';
|
|
10
|
+
readonly radius?: number;
|
|
11
|
+
};
|
|
12
|
+
readonly launcher?: {
|
|
13
|
+
readonly icon?: 'brand-mark' | 'chat' | 'none';
|
|
14
|
+
readonly size?: 'md' | 'lg';
|
|
15
|
+
readonly status?: 'none' | 'session';
|
|
16
|
+
readonly effect?: 'none' | 'pulse';
|
|
17
|
+
};
|
|
18
|
+
readonly header?: {
|
|
19
|
+
readonly mark?: 'none' | 'brand-mark' | 'status';
|
|
20
|
+
readonly badge?: {
|
|
21
|
+
readonly text: string;
|
|
22
|
+
readonly tone?: AssistantPresentationTone;
|
|
23
|
+
readonly indicator?: boolean;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
readonly composer?: {
|
|
27
|
+
readonly leadingIcon?: 'none' | 'brand-mark';
|
|
28
|
+
readonly sendIcon?: 'arrow-up' | 'paper-plane';
|
|
29
|
+
readonly shape?: 'rounded' | 'pill';
|
|
30
|
+
};
|
|
31
|
+
readonly messages?: {
|
|
32
|
+
readonly userStyle?: 'bubble' | 'accent';
|
|
33
|
+
readonly assistantStyle?: 'plain' | 'bubble';
|
|
34
|
+
};
|
|
35
|
+
}
|
|
4
36
|
interface AssistantConfiguration {
|
|
5
37
|
readonly branding?: {
|
|
6
38
|
readonly name?: string;
|
|
@@ -50,6 +82,7 @@ interface AssistantUiConfiguration {
|
|
|
50
82
|
readonly panelWidth?: number;
|
|
51
83
|
readonly panelMinHeight?: number;
|
|
52
84
|
readonly panelMaxHeight?: number;
|
|
85
|
+
readonly edgeOffset?: number;
|
|
53
86
|
readonly zIndex?: number;
|
|
54
87
|
readonly density?: 'compact' | 'comfortable';
|
|
55
88
|
readonly mobileFullscreen?: boolean;
|
|
@@ -64,6 +97,7 @@ interface AssistantUiConfiguration {
|
|
|
64
97
|
readonly showTimestamps?: boolean;
|
|
65
98
|
};
|
|
66
99
|
readonly labels?: Partial<AssistantLabels>;
|
|
100
|
+
readonly presentation?: AssistantPresentationConfiguration;
|
|
67
101
|
readonly suggestedPrompts?: readonly string[];
|
|
68
102
|
readonly privacyUrl?: string;
|
|
69
103
|
readonly termsUrl?: string;
|
|
@@ -74,6 +108,7 @@ interface AssistantLabels {
|
|
|
74
108
|
readonly welcomeHeading: string;
|
|
75
109
|
readonly welcomeMessage: string;
|
|
76
110
|
readonly composerPlaceholder: string;
|
|
111
|
+
readonly thinking: string;
|
|
77
112
|
readonly send: string;
|
|
78
113
|
readonly stop: string;
|
|
79
114
|
readonly close: string;
|
|
@@ -83,6 +118,10 @@ interface AssistantLabels {
|
|
|
83
118
|
readonly retry: string;
|
|
84
119
|
readonly unavailable: string;
|
|
85
120
|
readonly sessionExpired: string;
|
|
121
|
+
readonly sessionIdle: string;
|
|
122
|
+
readonly sessionLoading: string;
|
|
123
|
+
readonly sessionReady: string;
|
|
124
|
+
readonly sessionError: string;
|
|
86
125
|
}
|
|
87
126
|
|
|
88
127
|
export type { AssistantThemeMode as A, AssistantConfiguration as a };
|
|
@@ -338,6 +338,12 @@ var DefaultAssistantClient = class {
|
|
|
338
338
|
this.#listeners.add(listener);
|
|
339
339
|
return () => this.#listeners.delete(listener);
|
|
340
340
|
}
|
|
341
|
+
async connect() {
|
|
342
|
+
if (this.#session) return;
|
|
343
|
+
await this.#singleFlight(async (signal) => {
|
|
344
|
+
if (!this.#session) await this.#createSession(signal);
|
|
345
|
+
});
|
|
346
|
+
}
|
|
341
347
|
async sendMessage(text) {
|
|
342
348
|
const message = text.trim();
|
|
343
349
|
if (!message) return;
|
|
@@ -633,4 +639,4 @@ export {
|
|
|
633
639
|
AssistantClientError,
|
|
634
640
|
createAssistantClient
|
|
635
641
|
};
|
|
636
|
-
//# sourceMappingURL=chunk-
|
|
642
|
+
//# sourceMappingURL=chunk-N6TFOYOX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/events.ts","../src/model-context.ts","../src/transport.ts","../src/client.ts"],"sourcesContent":["import type { AssistantConfiguration } from './appearance.js';\nimport type { AssistantJsonValue, AssistantModelContextUpdate } from './model-context.js';\nimport type { AssistantEvent } from './transport.js';\n\ninterface NamedEvent<Name extends string, Data> {\n readonly event: Name;\n readonly data: Data;\n}\n\ninterface TurnDetail {\n readonly turnId?: string;\n}\n\nexport interface AssistantContentDetail extends TurnDetail {\n readonly delta: string;\n}\n\nexport interface AssistantToolProposedDetail extends TurnDetail {\n readonly id: string;\n readonly tool: string;\n readonly arguments?: AssistantJsonValue;\n readonly expiresAt?: string;\n /** Optional only for compatibility with assistant services published before named-event pinning. */\n readonly requiresConfirmation?: true;\n}\n\nexport interface AssistantInputRequestedDetail extends TurnDetail {\n readonly id: string;\n readonly message: string;\n readonly requestedSchema: Readonly<Record<string, unknown>>;\n readonly expiresAt: string;\n}\n\nexport interface AssistantInteractionResolvedDetail extends TurnDetail {\n readonly id: string;\n /** Optional only for compatibility with the original accept-only confirmation endpoint. */\n readonly action?: 'accept' | 'decline' | 'cancel';\n}\n\nexport interface AssistantToolCompletedDetail extends TurnDetail {\n readonly id: string;\n readonly tool: string;\n readonly result: AssistantJsonValue;\n readonly replayed?: true;\n}\n\nexport interface AssistantViewAvailableDetail extends TurnDetail {\n /** Model tool-call id for an immediate result, or interaction id for a confirmed result. */\n readonly id: string;\n readonly tool: string;\n readonly resourceUri: string;\n readonly title?: string;\n /** Bounded, schema-redacted public tool output; widget-only metadata is never included. */\n readonly result: AssistantJsonValue;\n readonly replayed?: true;\n}\n\nexport interface AssistantErrorEventDetail extends TurnDetail {\n readonly code: string;\n readonly status?: number;\n readonly retryable?: boolean;\n}\n\nexport type AssistantContentEvent = NamedEvent<'content', AssistantContentDetail>;\nexport type AssistantToolProposedEvent = NamedEvent<'tool_proposed', AssistantToolProposedDetail>;\nexport type AssistantInputRequestedEvent = NamedEvent<\n 'input_requested',\n AssistantInputRequestedDetail\n>;\nexport type AssistantInteractionResolvedEvent = NamedEvent<\n 'interaction_resolved',\n AssistantInteractionResolvedDetail\n>;\nexport type AssistantToolCompletedEvent = NamedEvent<\n 'tool_completed',\n AssistantToolCompletedDetail\n>;\nexport type AssistantViewAvailableEvent = NamedEvent<\n 'view_available',\n AssistantViewAvailableDetail\n>;\nexport type AssistantErrorEvent = NamedEvent<'error', AssistantErrorEventDetail>;\nexport type AssistantDoneEvent = NamedEvent<'done', TurnDetail>;\n\ninterface AssistantLegacyInteractionProposedDetail {\n readonly id: string;\n readonly tool?: string;\n readonly title?: string;\n readonly arguments?: AssistantJsonValue;\n}\n\ntype AssistantContextValue = string | number | boolean | null;\n\nexport type AssistantClientLifecycleEvent =\n | NamedEvent<\n 'session_started',\n { readonly expiresAt: string; readonly configuration?: AssistantConfiguration }\n >\n | NamedEvent<'session_expired', Readonly<Record<string, never>>>\n | NamedEvent<'session_reset', Readonly<Record<string, never>>>\n | NamedEvent<\n 'context_changed',\n { readonly context: Readonly<Record<string, AssistantContextValue>> }\n >\n | NamedEvent<'model_context_changed', { readonly modelContext: AssistantModelContextUpdate }>\n | NamedEvent<'message_started', { readonly message: string }>\n | NamedEvent<'message_completed', Readonly<Record<string, never>>>\n | NamedEvent<\n 'interaction_started',\n { readonly id: string; readonly action: 'accept' | 'decline' | 'cancel' }\n >\n | NamedEvent<\n 'interaction_completed',\n { readonly id: string; readonly action: 'accept' | 'decline' | 'cancel' }\n >;\n\nexport interface AssistantUnrecognizedEvent {\n readonly event: 'unrecognized';\n readonly data: {\n readonly name: string;\n readonly payload: Readonly<Record<string, unknown>>;\n };\n}\n\n/** Closed event union for the DOM-free client; unknown future SSE names remain observable safely. */\nexport type AssistantClientEvent =\n | AssistantContentEvent\n | AssistantToolProposedEvent\n | AssistantInputRequestedEvent\n | AssistantInteractionResolvedEvent\n | AssistantToolCompletedEvent\n | AssistantViewAvailableEvent\n | AssistantErrorEvent\n | AssistantDoneEvent\n | NamedEvent<'interaction_proposed', AssistantLegacyInteractionProposedDetail>\n | AssistantClientLifecycleEvent\n | AssistantUnrecognizedEvent;\n\n/** Normalize and minimally validate generic transport frames before asserting public event types. */\nexport function toAssistantClientEvent(event: AssistantEvent): AssistantClientEvent {\n const value = event.data;\n switch (event.event) {\n case 'content':\n if (typeof value.delta === 'string' && hasOptionalTurnId(value)) {\n return event as unknown as AssistantContentEvent;\n }\n break;\n case 'tool_proposed':\n if (\n hasString(value, 'id') &&\n hasString(value, 'tool') &&\n hasOptionalJson(value.arguments) &&\n hasOptionalString(value.expiresAt) &&\n (value.requiresConfirmation === undefined || value.requiresConfirmation === true) &&\n hasOptionalTurnId(value)\n ) {\n return event as unknown as AssistantToolProposedEvent;\n }\n break;\n case 'input_requested':\n if (\n hasString(value, 'id') &&\n hasString(value, 'message') &&\n isRecord(value.requestedSchema) &&\n hasString(value, 'expiresAt') &&\n hasOptionalTurnId(value)\n ) {\n return event as unknown as AssistantInputRequestedEvent;\n }\n break;\n case 'interaction_resolved':\n if (\n hasString(value, 'id') &&\n (value.action === undefined || isInteractionAction(value.action)) &&\n hasOptionalTurnId(value)\n ) {\n return event as unknown as AssistantInteractionResolvedEvent;\n }\n break;\n case 'tool_completed':\n if (\n hasString(value, 'id') &&\n hasString(value, 'tool') &&\n isJsonValue(value.result, 0) &&\n (value.replayed === undefined || value.replayed === true) &&\n hasOptionalTurnId(value)\n ) {\n return event as unknown as AssistantToolCompletedEvent;\n }\n break;\n case 'view_available':\n if (isViewAvailableDetail(value)) return event as unknown as AssistantViewAvailableEvent;\n break;\n case 'error':\n if (\n hasString(value, 'code') &&\n (value.status === undefined || typeof value.status === 'number') &&\n (value.retryable === undefined || typeof value.retryable === 'boolean') &&\n hasOptionalTurnId(value)\n ) {\n return event as unknown as AssistantErrorEvent;\n }\n break;\n case 'done':\n if (hasOptionalTurnId(value)) return event as AssistantDoneEvent;\n break;\n case 'interaction_proposed':\n if (\n hasString(value, 'id') &&\n (hasString(value, 'tool') || hasString(value, 'title')) &&\n hasOptionalJson(value.arguments)\n ) {\n return event as unknown as NamedEvent<\n 'interaction_proposed',\n AssistantLegacyInteractionProposedDetail\n >;\n }\n break;\n }\n return { event: 'unrecognized', data: { name: event.event, payload: value } };\n}\n\nfunction isViewAvailableDetail(value: Readonly<Record<string, unknown>>): boolean {\n return (\n hasString(value, 'id') &&\n hasString(value, 'tool') &&\n typeof value.resourceUri === 'string' &&\n value.resourceUri.startsWith('ui://') &&\n hasOptionalString(value.title) &&\n (value.replayed === undefined || value.replayed === true) &&\n isJsonValue(value.result, 0) &&\n hasOptionalTurnId(value)\n );\n}\n\nfunction hasOptionalTurnId(value: Readonly<Record<string, unknown>>): boolean {\n return hasOptionalString(value.turnId);\n}\n\nfunction hasString(value: Readonly<Record<string, unknown>>, key: string): boolean {\n const entry = value[key];\n return typeof entry === 'string' && entry.length > 0;\n}\n\nfunction hasOptionalString(value: unknown): value is string | undefined {\n return value === undefined || typeof value === 'string';\n}\n\nfunction hasOptionalJson(value: unknown): boolean {\n return value === undefined || isJsonValue(value, 0);\n}\n\nfunction isInteractionAction(value: unknown): value is 'accept' | 'decline' | 'cancel' {\n return value === 'accept' || value === 'decline' || value === 'cancel';\n}\n\nfunction isJsonValue(value: unknown, depth: number): value is AssistantJsonValue {\n if (depth > 16) return false;\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;\n if (typeof value === 'number') return Number.isFinite(value);\n if (Array.isArray(value)) {\n return value.length <= 256 && value.every((entry) => isJsonValue(entry, depth + 1));\n }\n if (!isRecord(value)) return false;\n const entries = Object.entries(value);\n return entries.length <= 256 && entries.every(([, entry]) => isJsonValue(entry, depth + 1));\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","export type AssistantJsonValue =\n | string\n | number\n | boolean\n | null\n | readonly AssistantJsonValue[]\n | { readonly [key: string]: AssistantJsonValue };\n\n/** MCP-Apps-shaped summary deliberately selected by the renderer for the next assistant turn. */\nexport interface AssistantModelContextUpdate {\n readonly content?: readonly { readonly type: 'text'; readonly text: string }[];\n readonly structuredContent?: Readonly<Record<string, AssistantJsonValue>>;\n}\n\nconst MAX_BYTES = 16 * 1024;\nconst MAX_DEPTH = 8;\nconst MAX_ENTRIES = 128;\nconst SENSITIVE_KEY = /(?:secret|token|api[-_]?key|password|credential|authorization|cookie)/i;\nconst CREDENTIAL_SHAPED_TEXT =\n /(?:-----BEGIN [A-Z ]*PRIVATE KEY-----|\\bsk-[A-Za-z0-9_-]{20,}\\b|\\b(?:bearer|basic)\\s+[A-Za-z0-9._~+/=-]{20,}\\b|\\b[A-Za-z0-9_-]{16,}\\.[A-Za-z0-9_-]{16,}\\.[A-Za-z0-9_-]{16,}\\b)/i;\n\n/** Validate and detach renderer-owned mutable data before retaining it in the client. */\nexport function copyAssistantModelContext(\n update: AssistantModelContextUpdate,\n): AssistantModelContextUpdate {\n const copied = copyJsonValue(update, '$', 0, new Set<object>());\n assertModelContextShape(copied);\n const encoded = JSON.stringify(copied);\n if (new TextEncoder().encode(encoded).byteLength > MAX_BYTES) {\n throw new Error('Model context must not exceed 16 KiB');\n }\n return copied;\n}\n\nfunction assertModelContextShape(value: unknown): asserts value is AssistantModelContextUpdate {\n if (!isPlainRecord(value)) throw new Error('Model context must be a JSON object');\n for (const key of Object.keys(value)) {\n if (key !== 'content' && key !== 'structuredContent') {\n throw new Error(`Model context contains unknown field ${key}`);\n }\n }\n if (value.content !== undefined) {\n if (!Array.isArray(value.content)) throw new Error('Model context content must be an array');\n for (const part of value.content) {\n if (\n !isPlainRecord(part) ||\n Object.keys(part).some((key) => key !== 'type' && key !== 'text') ||\n part.type !== 'text' ||\n typeof part.text !== 'string'\n ) {\n throw new Error('Model context content supports text parts only');\n }\n }\n }\n if (value.structuredContent !== undefined && !isPlainRecord(value.structuredContent)) {\n throw new Error('Model context structuredContent must be an object');\n }\n}\n\nfunction copyJsonValue(\n value: unknown,\n path: string,\n depth: number,\n ancestors: Set<object>,\n): AssistantJsonValue {\n if (depth > MAX_DEPTH) throw new Error(`Model context exceeds maximum depth at ${path}`);\n if (typeof value === 'string') {\n if (CREDENTIAL_SHAPED_TEXT.test(value)) {\n throw new Error(`Model context contains credential-shaped text at ${path}`);\n }\n return value;\n }\n if (\n value === null ||\n typeof value === 'boolean' ||\n (typeof value === 'number' && Number.isFinite(value))\n ) {\n return value;\n }\n if (typeof value !== 'object') throw new Error(`Model context contains non-JSON data at ${path}`);\n if (hasToJsonProperty(value)) {\n throw new Error(`Model context must not define or inherit toJSON at ${path}`);\n }\n const prototype = Object.getPrototypeOf(value);\n if (Array.isArray(value)) {\n if (prototype !== Array.prototype) {\n throw new Error(`Model context contains a non-JSON object at ${path}`);\n }\n } else if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`Model context contains a non-JSON object at ${path}`);\n }\n if (ancestors.has(value)) throw new Error(`Model context contains a cycle at ${path}`);\n\n if (Array.isArray(value)) {\n if (value.length > MAX_ENTRIES) {\n throw new Error(`Model context has more than 128 entries at ${path}`);\n }\n const copy: AssistantJsonValue[] = [];\n ancestors.add(value);\n for (let index = 0; index < value.length; index += 1) {\n const entry = Object.hasOwn(value, index) ? value[index] : null;\n copy.push(copyJsonValue(entry, `${path}.${index}`, depth + 1, ancestors));\n }\n ancestors.delete(value);\n return copy;\n }\n\n const entries = Object.entries(value);\n if (entries.length > MAX_ENTRIES) {\n throw new Error(`Model context has more than 128 entries at ${path}`);\n }\n const copy: Record<string, AssistantJsonValue> = Object.create(null);\n ancestors.add(value);\n for (const [key, entry] of entries) {\n if (SENSITIVE_KEY.test(key)) {\n throw new Error(`Model context contains sensitive key ${path}.${key}`);\n }\n copy[key] = copyJsonValue(entry, `${path}.${key}`, depth + 1, ancestors);\n }\n ancestors.delete(value);\n return copy;\n}\n\nfunction isPlainRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction hasToJsonProperty(value: object): boolean {\n let current: object | null = value;\n const visited = new Set<object>();\n while (current !== null && !visited.has(current)) {\n visited.add(current);\n if (Object.getOwnPropertyDescriptor(current, 'toJSON') !== undefined) return true;\n current = Object.getPrototypeOf(current);\n }\n return false;\n}\n","export interface AssistantEvent {\n readonly event: string;\n readonly data: Readonly<Record<string, unknown>>;\n}\n\nexport interface AssistantErrorDetail {\n readonly code: string;\n readonly status?: number;\n readonly retryable: boolean;\n}\n\n/** A 2xx response that is not one complete, well-formed assistant event stream. */\nexport class AssistantTransportError extends Error {\n readonly code = 'invalid_response' as const;\n\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'AssistantTransportError';\n }\n}\n\n/**\n * Consume JSON-bearing server-sent events without buffering the whole assistant turn.\n *\n * `done` is the stream commit marker. It is delivered only after EOF proves that it was the one terminal\n * event, so truncated, duplicate-terminal, and post-terminal responses can never resolve a client turn.\n */\nexport async function consumeAssistantEvents(\n response: Response,\n onEvent: (event: AssistantEvent) => void,\n): Promise<void> {\n const stream = new AssistantEventStream(onEvent);\n if (!response.body) {\n let text: string;\n try {\n text = await response.text();\n } catch (error) {\n if (isAbortError(error)) throw error;\n throw invalidStream('assistant event stream could not be read', error);\n }\n stream.push(text);\n stream.finish(response.headers.get('content-type') ?? '');\n return;\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8', { fatal: true });\n while (true) {\n let result: ReadableStreamReadResult<Uint8Array>;\n try {\n result = await reader.read();\n } catch (error) {\n if (isAbortError(error)) throw error;\n throw invalidStream('assistant event stream ended unexpectedly', error);\n }\n\n let chunk: string;\n try {\n chunk = decoder.decode(result.value, { stream: !result.done });\n } catch (error) {\n throw invalidStream('assistant event stream contained invalid UTF-8', error);\n }\n stream.push(chunk);\n if (result.done) break;\n }\n stream.finish(response.headers.get('content-type') ?? '');\n}\n\nclass AssistantEventStream {\n readonly #onEvent: (event: AssistantEvent) => void;\n #pending = '';\n #terminal: AssistantEvent | undefined;\n\n constructor(onEvent: (event: AssistantEvent) => void) {\n this.#onEvent = onEvent;\n }\n\n push(chunk: string): void {\n this.#pending += chunk;\n const protectedCarriageReturn = this.#pending.endsWith('\\r');\n const normalizable = protectedCarriageReturn ? this.#pending.slice(0, -1) : this.#pending;\n const frames = normalizeLineEndings(normalizable).split('\\n\\n');\n this.#pending = `${frames.pop() ?? ''}${protectedCarriageReturn ? '\\r' : ''}`;\n for (const frame of frames) this.#acceptFrame(frame);\n }\n\n finish(contentType: string): void {\n if (this.#pending.trim().length > 0) {\n throw invalidStream('assistant event stream ended with an unterminated frame');\n }\n if (!this.#terminal) {\n throw invalidStream(\n `assistant response did not contain a terminal done event (content-type: ${contentType || 'unknown'})`,\n );\n }\n this.#onEvent(this.#terminal);\n }\n\n #acceptFrame(frame: string): void {\n const event = parseFrame(frame);\n if (!event) return;\n if (this.#terminal) {\n throw invalidStream('assistant event stream contained an event after done');\n }\n if (event.event === 'done') {\n this.#terminal = event;\n return;\n }\n this.#onEvent(event);\n }\n}\n\nfunction parseFrame(frame: string): AssistantEvent | undefined {\n let event: string | undefined;\n const data: string[] = [];\n let hasFields = false;\n for (const line of frame.split('\\n')) {\n if (!line || line.startsWith(':')) continue;\n hasFields = true;\n const separator = line.indexOf(':');\n const field = separator < 0 ? line : line.slice(0, separator);\n const value = separator < 0 ? '' : line.slice(separator + 1).replace(/^ /, '');\n if (field === 'event') event = value;\n if (field === 'data') data.push(value);\n }\n if (!hasFields) return undefined;\n if (!event || data.length === 0) {\n throw invalidStream('assistant event stream contained a malformed frame');\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(data.join('\\n'));\n } catch (error) {\n throw invalidStream('assistant event stream contained malformed JSON', error);\n }\n if (event === 'done' && !isValidDonePayload(parsed)) {\n throw invalidStream('assistant event stream contained an invalid done event');\n }\n return { event, data: isRecord(parsed) ? parsed : { value: parsed } };\n}\n\nfunction normalizeLineEndings(input: string): string {\n return input.replaceAll('\\r\\n', '\\n').replaceAll('\\r', '\\n');\n}\n\nfunction isValidDonePayload(value: unknown): value is Readonly<Record<string, unknown>> {\n return (\n isRecord(value) &&\n (value.turnId === undefined || (typeof value.turnId === 'string' && value.turnId.length > 0))\n );\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction invalidStream(message: string, cause?: unknown): AssistantTransportError {\n return new AssistantTransportError(message, cause === undefined ? undefined : { cause });\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMException && error.name === 'AbortError';\n}\n","import type { AssistantConfiguration } from './appearance.js';\nimport { type AssistantClientEvent, toAssistantClientEvent } from './events.js';\nimport {\n type AssistantJsonValue,\n type AssistantModelContextUpdate,\n copyAssistantModelContext,\n} from './model-context.js';\nimport {\n type AssistantErrorDetail,\n AssistantTransportError,\n consumeAssistantEvents,\n} from './transport.js';\n\nexport type AssistantContextValue = string | number | boolean | null;\nexport type AssistantContext = Readonly<Record<string, AssistantContextValue>>;\n\nexport interface AssistantClientContext {\n readonly locale?: string;\n readonly timeZone?: string;\n}\n\nexport type { AssistantJsonValue, AssistantModelContextUpdate } from './model-context.js';\n\nexport type AssistantInteractionResponse =\n | { readonly action: 'accept'; readonly content?: AssistantJsonValue }\n | { readonly action: 'decline' | 'cancel' };\n\nexport interface AssistantSessionResponse {\n readonly token: string;\n readonly expiresAt: string;\n readonly endpoints: {\n readonly turns: string;\n readonly toolConfirmations: string;\n readonly interactions?: string;\n };\n readonly configuration?: AssistantConfiguration;\n}\n\nexport type {\n AssistantClientEvent,\n AssistantClientLifecycleEvent,\n AssistantContentDetail,\n AssistantContentEvent,\n AssistantDoneEvent,\n AssistantErrorEvent,\n AssistantErrorEventDetail,\n AssistantInputRequestedDetail,\n AssistantInputRequestedEvent,\n AssistantInteractionResolvedDetail,\n AssistantInteractionResolvedEvent,\n AssistantToolCompletedDetail,\n AssistantToolCompletedEvent,\n AssistantToolProposedDetail,\n AssistantToolProposedEvent,\n AssistantUnrecognizedEvent,\n AssistantViewAvailableDetail,\n AssistantViewAvailableEvent,\n} from './events.js';\n\nexport interface CreateAssistantClientOptions {\n readonly sessionEndpoint: string;\n readonly fetch?: typeof fetch;\n /** Untrusted page context sent only when exchanging a session. */\n readonly context?: AssistantContext;\n /** Untrusted presentation hints evaluated for every turn request. */\n readonly clientContext?: AssistantClientContext | (() => AssistantClientContext | undefined);\n /** Latest renderer-selected summary included as untrusted data on every message turn. */\n readonly modelContext?: AssistantModelContextUpdate;\n}\n\nexport interface AssistantClient {\n subscribe(listener: (event: AssistantClientEvent) => void): () => void;\n connect(): Promise<void>;\n sendMessage(message: string): Promise<void>;\n respond(id: string, response: AssistantInteractionResponse): Promise<void>;\n updateContext(context: AssistantContext): void;\n updateModelContext(update: AssistantModelContextUpdate): void;\n resetSession(): void;\n abort(): void;\n}\n\nexport class AssistantClientError extends Error {\n readonly detail: AssistantErrorDetail;\n\n constructor(detail: AssistantErrorDetail, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'AssistantClientError';\n this.detail = detail;\n }\n}\n\nclass DefaultAssistantClient implements AssistantClient {\n readonly #sessionEndpoint: string;\n readonly #fetch: typeof fetch;\n readonly #listeners = new Set<(event: AssistantClientEvent) => void>();\n readonly #clientContext:\n | AssistantClientContext\n | (() => AssistantClientContext | undefined)\n | undefined;\n #session: AssistantSessionResponse | undefined;\n #context: AssistantContext | undefined;\n #modelContext: AssistantModelContextUpdate | undefined;\n #active: AbortController | undefined;\n\n constructor(options: CreateAssistantClientOptions) {\n if (!options.sessionEndpoint) throw new Error('sessionEndpoint is required');\n this.#sessionEndpoint = options.sessionEndpoint;\n // Some browsers require `window.fetch` to be invoked with its global receiver. Keep the default\n // behind a closure instead of storing the unbound host method; injected test/server fetches remain exact.\n this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));\n this.#context = options.context ? { ...options.context } : undefined;\n this.#modelContext = options.modelContext\n ? copyAssistantModelContext(options.modelContext)\n : undefined;\n this.#clientContext = options.clientContext;\n }\n\n subscribe(listener: (event: AssistantClientEvent) => void): () => void {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n\n async connect(): Promise<void> {\n if (this.#session) return;\n await this.#singleFlight(async (signal) => {\n if (!this.#session) await this.#createSession(signal);\n });\n }\n\n async sendMessage(text: string): Promise<void> {\n const message = text.trim();\n if (!message) return;\n await this.#singleFlight(async (signal) => {\n await this.#sendTurn(message, true, signal, this.#modelContext);\n });\n }\n\n async respond(id: string, resolution: AssistantInteractionResponse): Promise<void> {\n if (!id) {\n throw clientError('invalid_request', 'interaction id is required', false);\n }\n await this.#singleFlight(async (signal) => {\n const session = this.#session;\n if (!session) {\n throw clientError('confirmation_expired', 'assistant session is not active', false);\n }\n const modernEndpoint = session.endpoints.interactions;\n if (!modernEndpoint && resolution.action !== 'accept') {\n throw clientError(\n 'unsupported_service',\n 'the assistant service does not support declining or cancelling interactions',\n false,\n );\n }\n const endpoint = modernEndpoint ?? session.endpoints.toolConfirmations;\n const body = modernEndpoint\n ? {\n id,\n action: resolution.action,\n ...(resolution.action === 'accept' && resolution.content !== undefined\n ? { content: resolution.content }\n : {}),\n }\n : { id };\n this.#emit({ event: 'interaction_started', data: { id, action: resolution.action } });\n const response = await this.#request(\n endpoint,\n {\n method: 'POST',\n headers: authorizedHeaders(session.token, 'text/event-stream'),\n body: JSON.stringify(body),\n signal,\n },\n 'confirmation_failed',\n );\n if (response.status === 401) {\n this.#session = undefined;\n this.#emit({ event: 'session_expired', data: {} });\n }\n if (!response.ok) {\n const serverCode = await readStableErrorCode(response);\n const expired = response.status === 401 || response.status === 409;\n throw clientError(\n serverCode ?? (expired ? 'confirmation_expired' : 'confirmation_failed'),\n `Assistant interaction failed (${response.status})`,\n false,\n response.status,\n );\n }\n await this.#consume(response);\n this.#emit({ event: 'interaction_completed', data: { id, action: resolution.action } });\n });\n }\n\n updateContext(context: AssistantContext): void {\n this.#context = { ...context };\n this.#emit({ event: 'context_changed', data: { context: this.#context } });\n }\n\n updateModelContext(update: AssistantModelContextUpdate): void {\n this.#modelContext = copyAssistantModelContext(update);\n this.#emit({ event: 'model_context_changed', data: { modelContext: this.#modelContext } });\n }\n\n resetSession(): void {\n this.#session = undefined;\n this.#emit({ event: 'session_reset', data: {} });\n }\n\n abort(): void {\n this.#active?.abort();\n }\n\n async #sendTurn(\n message: string,\n mayRetry: boolean,\n signal: AbortSignal,\n modelContext: AssistantModelContextUpdate | undefined,\n ): Promise<void> {\n const session = this.#session ?? (await this.#createSession(signal));\n if (mayRetry) this.#emit({ event: 'message_started', data: { message } });\n const clientContext = this.#resolveClientContext();\n const response = await this.#request(\n session.endpoints.turns,\n {\n method: 'POST',\n headers: authorizedHeaders(session.token, 'text/event-stream'),\n body: JSON.stringify({\n message,\n ...(clientContext ? { clientContext } : {}),\n ...(modelContext ? { modelContext } : {}),\n }),\n signal,\n },\n 'turn_failed',\n );\n if (response.status === 401 && mayRetry) {\n this.#session = undefined;\n this.#emit({ event: 'session_expired', data: {} });\n await this.#sendTurn(message, false, signal, modelContext);\n return;\n }\n if (!response.ok) {\n throw clientError(\n 'turn_failed',\n `Assistant turn failed (${response.status})`,\n false,\n response.status,\n );\n }\n await this.#consume(response);\n this.#emit({ event: 'message_completed', data: {} });\n }\n\n #resolveClientContext(): AssistantClientContext | undefined {\n let value: AssistantClientContext | undefined;\n try {\n value =\n typeof this.#clientContext === 'function' ? this.#clientContext() : this.#clientContext;\n } catch (error) {\n throw clientError(\n 'turn_failed',\n 'Assistant client context provider failed',\n false,\n undefined,\n {\n cause: error,\n },\n );\n }\n if (!value) return undefined;\n const context = {\n ...(typeof value.locale === 'string' && value.locale ? { locale: value.locale } : {}),\n ...(typeof value.timeZone === 'string' && value.timeZone ? { timeZone: value.timeZone } : {}),\n };\n return Object.keys(context).length > 0 ? context : undefined;\n }\n\n async #createSession(signal: AbortSignal): Promise<AssistantSessionResponse> {\n const response = await this.#request(\n this.#sessionEndpoint,\n {\n method: 'POST',\n headers: { Accept: 'application/json', 'Content-Type': 'application/json' },\n body: JSON.stringify(this.#context ? { context: this.#context } : {}),\n credentials: 'same-origin',\n signal,\n },\n 'session_failed',\n );\n if (!response.ok) {\n throw clientError(\n 'session_failed',\n `Assistant session failed (${response.status})`,\n true,\n response.status,\n );\n }\n let value: unknown;\n try {\n value = await response.json();\n } catch (error) {\n throw clientError(\n 'session_failed',\n 'Assistant session returned invalid JSON',\n true,\n undefined,\n {\n cause: error,\n },\n );\n }\n const session = parseSession(value);\n this.#session = session;\n this.#emit({\n event: 'session_started',\n data: {\n expiresAt: session.expiresAt,\n ...(session.configuration ? { configuration: session.configuration } : {}),\n },\n });\n return session;\n }\n\n async #consume(response: Response): Promise<void> {\n let streamError: AssistantErrorDetail | undefined;\n try {\n await consumeAssistantEvents(response, (event) => {\n const clientEvent = toAssistantClientEvent(event);\n this.#emit(clientEvent);\n if (clientEvent.event !== 'error' || typeof clientEvent.data.code !== 'string') return;\n streamError = {\n code: clientEvent.data.code,\n ...(typeof clientEvent.data.status === 'number'\n ? { status: clientEvent.data.status }\n : {}),\n retryable: clientEvent.data.retryable === true,\n };\n });\n } catch (error) {\n if (error instanceof AssistantTransportError) {\n throw clientError(error.code, error.message, false, undefined, { cause: error });\n }\n throw error;\n }\n if (streamError) {\n throw clientError(\n streamError.code,\n `Assistant stream failed (${streamError.code})`,\n streamError.retryable,\n streamError.status,\n );\n }\n }\n\n async #request(input: string, init: RequestInit, failureCode: string): Promise<Response> {\n try {\n return await this.#fetch(input, init);\n } catch (error) {\n if (init.signal?.aborted) throw error;\n throw clientError(failureCode, 'Assistant request failed', true, undefined, { cause: error });\n }\n }\n\n async #singleFlight(operation: (signal: AbortSignal) => Promise<void>): Promise<void> {\n if (this.#active) {\n throw clientError('request_in_progress', 'an assistant request is already in progress', true);\n }\n const controller = new AbortController();\n this.#active = controller;\n try {\n await operation(controller.signal);\n } catch (error) {\n if (controller.signal.aborted) {\n throw clientError('request_aborted', 'assistant request was aborted', true, undefined, {\n cause: error,\n });\n }\n throw error;\n } finally {\n this.#active = undefined;\n }\n }\n\n #emit(event: AssistantClientEvent): void {\n for (const listener of this.#listeners) {\n try {\n listener(event);\n } catch {\n // Renderers are independent observers; one subscriber cannot change a completed request.\n }\n }\n }\n}\n\nexport function createAssistantClient(options: CreateAssistantClientOptions): AssistantClient {\n return new DefaultAssistantClient(options);\n}\n\nfunction authorizedHeaders(token: string, accept: string): Readonly<Record<string, string>> {\n return {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n Accept: accept,\n };\n}\n\nfunction parseSession(value: unknown): AssistantSessionResponse {\n if (!isRecord(value) || !isRecord(value.endpoints)) {\n throw clientError('session_failed', 'Assistant session response is invalid', true);\n }\n const interactions = value.endpoints.interactions;\n if (\n typeof value.token !== 'string' ||\n typeof value.expiresAt !== 'string' ||\n typeof value.endpoints.turns !== 'string' ||\n typeof value.endpoints.toolConfirmations !== 'string' ||\n (interactions !== undefined && typeof interactions !== 'string')\n ) {\n throw clientError('session_failed', 'Assistant session response is invalid', true);\n }\n return {\n token: value.token,\n expiresAt: value.expiresAt,\n endpoints: {\n turns: value.endpoints.turns,\n toolConfirmations: value.endpoints.toolConfirmations,\n ...(typeof interactions === 'string' ? { interactions } : {}),\n },\n ...(isRecord(value.configuration)\n ? { configuration: value.configuration as AssistantConfiguration }\n : {}),\n };\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nasync function readStableErrorCode(response: Response): Promise<string | undefined> {\n let value: unknown;\n try {\n value = await response.json();\n } catch {\n return undefined;\n }\n if (!isRecord(value) || typeof value.code !== 'string') return undefined;\n return /^[A-Za-z0-9_.-]{1,64}$/.test(value.code) ? value.code : undefined;\n}\n\nfunction clientError(\n code: string,\n message: string,\n retryable: boolean,\n status?: number,\n options?: ErrorOptions,\n): AssistantClientError {\n return new AssistantClientError(\n { code, ...(status === undefined ? {} : { status }), retryable },\n message,\n options,\n );\n}\n"],"mappings":";AA2IO,SAAS,uBAAuB,OAA6C;AAClF,QAAM,QAAQ,MAAM;AACpB,UAAQ,MAAM,OAAO;AAAA,IACnB,KAAK;AACH,UAAI,OAAO,MAAM,UAAU,YAAY,kBAAkB,KAAK,GAAG;AAC/D,eAAO;AAAA,MACT;AACA;AAAA,IACF,KAAK;AACH,UACE,UAAU,OAAO,IAAI,KACrB,UAAU,OAAO,MAAM,KACvB,gBAAgB,MAAM,SAAS,KAC/B,kBAAkB,MAAM,SAAS,MAChC,MAAM,yBAAyB,UAAa,MAAM,yBAAyB,SAC5E,kBAAkB,KAAK,GACvB;AACA,eAAO;AAAA,MACT;AACA;AAAA,IACF,KAAK;AACH,UACE,UAAU,OAAO,IAAI,KACrB,UAAU,OAAO,SAAS,KAC1B,SAAS,MAAM,eAAe,KAC9B,UAAU,OAAO,WAAW,KAC5B,kBAAkB,KAAK,GACvB;AACA,eAAO;AAAA,MACT;AACA;AAAA,IACF,KAAK;AACH,UACE,UAAU,OAAO,IAAI,MACpB,MAAM,WAAW,UAAa,oBAAoB,MAAM,MAAM,MAC/D,k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