@webless/agent 0.2.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.
@@ -0,0 +1,932 @@
1
+ // src/react/components/AgentRail/AgentRail.tsx
2
+ import { useEffect, useRef as useRef2 } from "react";
3
+
4
+ // src/react/components/ToolTimeline/ToolTimeline.tsx
5
+ import { jsx, jsxs } from "react/jsx-runtime";
6
+ function SpinnerIcon() {
7
+ return /* @__PURE__ */ jsxs("svg", { className: "agent-status__spinner", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: [
8
+ /* @__PURE__ */ jsx("circle", { cx: "8", cy: "8", r: "6", stroke: "currentColor", strokeWidth: "1.5", strokeOpacity: "0.25" }),
9
+ /* @__PURE__ */ jsx("path", { d: "M14 8a6 6 0 0 0-6-6", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" })
10
+ ] });
11
+ }
12
+ function getCurrentStep(steps) {
13
+ const active = steps.find((step) => step.state === "active");
14
+ if (active) return active;
15
+ const error = steps.find((step) => step.state === "error");
16
+ if (error) return error;
17
+ const pending = steps.find((step) => step.state === "pending");
18
+ if (pending) return pending;
19
+ return steps.at(-1) ?? null;
20
+ }
21
+ function ToolTimeline({
22
+ steps,
23
+ streamingText,
24
+ showStreaming = false,
25
+ inline = false
26
+ }) {
27
+ if (steps.length === 0 && !(showStreaming && streamingText)) return null;
28
+ const currentStep = getCurrentStep(steps);
29
+ const showStatus = currentStep && currentStep.state !== "completed" && !(showStreaming && streamingText);
30
+ return /* @__PURE__ */ jsxs(
31
+ "div",
32
+ {
33
+ className: `tool-timeline${inline ? " tool-timeline--inline" : ""}`,
34
+ role: "status",
35
+ "aria-live": "polite",
36
+ "aria-label": "Agent progress",
37
+ children: [
38
+ showStatus ? /* @__PURE__ */ jsxs("div", { className: "agent-status", children: [
39
+ currentStep.state === "error" ? /* @__PURE__ */ jsx("span", { className: "agent-status__icon agent-status__icon--error", "aria-hidden": "true", children: "!" }) : /* @__PURE__ */ jsx("span", { className: "agent-status__icon", "aria-hidden": "true", children: /* @__PURE__ */ jsx(SpinnerIcon, {}) }),
40
+ /* @__PURE__ */ jsxs("div", { className: "agent-status__copy", children: [
41
+ /* @__PURE__ */ jsx("span", { className: "agent-status__label", children: currentStep.label }),
42
+ currentStep.detail ? /* @__PURE__ */ jsx("span", { className: "agent-status__detail", children: currentStep.detail }) : null
43
+ ] })
44
+ ] }, currentStep.id) : null,
45
+ showStreaming && streamingText ? /* @__PURE__ */ jsxs("p", { className: "tool-timeline__streaming-text", children: [
46
+ streamingText,
47
+ /* @__PURE__ */ jsx("span", { className: "tool-timeline__cursor", "aria-hidden": "true" })
48
+ ] }) : null
49
+ ]
50
+ }
51
+ );
52
+ }
53
+
54
+ // src/react/components/AgentActivityBubble/AgentActivityBubble.tsx
55
+ import { jsx as jsx2 } from "react/jsx-runtime";
56
+ function AgentActivityBubble({
57
+ steps,
58
+ streamingText,
59
+ showStreaming = false
60
+ }) {
61
+ return /* @__PURE__ */ jsx2("article", { className: "agent-activity-bubble", children: /* @__PURE__ */ jsx2("div", { className: "agent-activity-bubble__shell", children: /* @__PURE__ */ jsx2(
62
+ ToolTimeline,
63
+ {
64
+ steps,
65
+ streamingText,
66
+ showStreaming,
67
+ inline: true
68
+ }
69
+ ) }) });
70
+ }
71
+
72
+ // src/react/components/Composer/Composer.tsx
73
+ import { useRef, useState } from "react";
74
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
75
+ function SendIcon() {
76
+ return /* @__PURE__ */ jsx3("svg", { viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsx3("path", { d: "M8 12V4M8 4l-3 3M8 4l3 3", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }) });
77
+ }
78
+ function Composer({
79
+ disabled = false,
80
+ placeholder = "Ask anything\u2026",
81
+ variant = "default",
82
+ onSubmit
83
+ }) {
84
+ const [value, setValue] = useState("");
85
+ const inputRef = useRef(null);
86
+ function submitCurrent() {
87
+ const trimmed = value.trim();
88
+ if (!trimmed || disabled) return;
89
+ onSubmit?.(trimmed);
90
+ setValue("");
91
+ inputRef.current?.focus();
92
+ }
93
+ function handleSubmit(event) {
94
+ event.preventDefault();
95
+ submitCurrent();
96
+ }
97
+ function handleKeyDown(event) {
98
+ if (event.key === "Enter" && !event.shiftKey) {
99
+ event.preventDefault();
100
+ submitCurrent();
101
+ }
102
+ }
103
+ return /* @__PURE__ */ jsx3("form", { className: `composer${variant === "dock" ? " composer--dock" : ""}`, onSubmit: handleSubmit, children: /* @__PURE__ */ jsxs2("div", { className: "composer__field", children: [
104
+ /* @__PURE__ */ jsx3(
105
+ "textarea",
106
+ {
107
+ ref: inputRef,
108
+ className: "composer__input",
109
+ rows: 1,
110
+ value,
111
+ placeholder,
112
+ disabled,
113
+ "aria-label": "Message",
114
+ onChange: (event) => setValue(event.target.value),
115
+ onKeyDown: handleKeyDown
116
+ }
117
+ ),
118
+ /* @__PURE__ */ jsx3(
119
+ "button",
120
+ {
121
+ type: "submit",
122
+ className: "composer__send",
123
+ disabled: disabled || !value.trim(),
124
+ "aria-label": "Send message",
125
+ children: /* @__PURE__ */ jsx3(SendIcon, {})
126
+ }
127
+ )
128
+ ] }) });
129
+ }
130
+
131
+ // src/react/components/FollowUpChips/FollowUpChips.tsx
132
+ import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
133
+ function FollowUpChips({
134
+ suggestions,
135
+ disabled = false,
136
+ label = "Follow up",
137
+ variant = "default",
138
+ onSelect
139
+ }) {
140
+ if (suggestions.length === 0) return null;
141
+ if (variant === "dock") {
142
+ return /* @__PURE__ */ jsx4("div", { className: "followups followups--dock", children: /* @__PURE__ */ jsx4("div", { className: "followups__scroll", children: suggestions.map((suggestion) => /* @__PURE__ */ jsx4(
143
+ "button",
144
+ {
145
+ type: "button",
146
+ className: "followups__chip followups__chip--dock",
147
+ disabled,
148
+ onClick: () => onSelect?.(suggestion),
149
+ children: suggestion.label
150
+ },
151
+ suggestion.id
152
+ )) }) });
153
+ }
154
+ return /* @__PURE__ */ jsxs3("div", { className: "followups", children: [
155
+ /* @__PURE__ */ jsx4("span", { className: "followups__label", children: label }),
156
+ /* @__PURE__ */ jsx4("div", { className: "followups__list", children: suggestions.map((suggestion) => /* @__PURE__ */ jsx4(
157
+ "button",
158
+ {
159
+ type: "button",
160
+ className: "followups__chip",
161
+ disabled,
162
+ onClick: () => onSelect?.(suggestion),
163
+ children: suggestion.label
164
+ },
165
+ suggestion.id
166
+ )) })
167
+ ] });
168
+ }
169
+
170
+ // src/react/components/MessageBubble/MessageBubble.tsx
171
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
172
+ function MessageBubble({ message }) {
173
+ if (message.role === "visitor") {
174
+ return /* @__PURE__ */ jsx5("article", { className: "message-bubble message-bubble--visitor", children: /* @__PURE__ */ jsx5("p", { className: "message-bubble__text", children: message.text }) });
175
+ }
176
+ return /* @__PURE__ */ jsx5("article", { className: "message-bubble message-bubble--agent", children: /* @__PURE__ */ jsxs4("p", { className: "message-bubble__text", children: [
177
+ message.text,
178
+ message.streaming ? /* @__PURE__ */ jsx5("span", { className: "tool-timeline__cursor", "aria-hidden": "true" }) : null
179
+ ] }) });
180
+ }
181
+
182
+ // src/react/components/AgentRail/AgentRail.tsx
183
+ import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
184
+ function MinimizeIcon() {
185
+ return /* @__PURE__ */ jsx6("svg", { viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsx6("path", { d: "M3.5 8h9", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round" }) });
186
+ }
187
+ function ExpandIcon() {
188
+ return /* @__PURE__ */ jsx6("svg", { viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsx6(
189
+ "path",
190
+ {
191
+ d: "M6 3.5H3.5V6M10 3.5h2.5V6M10 12.5h2.5V10M6 12.5H3.5V10",
192
+ stroke: "currentColor",
193
+ strokeWidth: "1.5",
194
+ strokeLinecap: "round",
195
+ strokeLinejoin: "round"
196
+ }
197
+ ) });
198
+ }
199
+ function RestoreIcon() {
200
+ return /* @__PURE__ */ jsx6("svg", { viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsx6(
201
+ "path",
202
+ {
203
+ d: "M5.5 5.5H3.5V7.5M10.5 5.5h2V7.5M10.5 10.5h2V8.5M5.5 10.5H3.5V8.5",
204
+ stroke: "currentColor",
205
+ strokeWidth: "1.5",
206
+ strokeLinecap: "round",
207
+ strokeLinejoin: "round"
208
+ }
209
+ ) });
210
+ }
211
+ function AgentRail({
212
+ state,
213
+ theme,
214
+ brandLabel = "Webless Assist",
215
+ poweredByLabel = "Powered by Webless",
216
+ composerPlaceholder = "Ask anything\u2026",
217
+ mobileFullscreen = false,
218
+ expanded = false,
219
+ onCollapse,
220
+ onClose,
221
+ onExpandToggle,
222
+ onSubmit,
223
+ onFollowUpSelect
224
+ }) {
225
+ const transcriptRef = useRef2(null);
226
+ const railStyle = theme?.railMaxWidth ? { ["--rail-width"]: theme.railMaxWidth, ["--as-rail-max-width"]: theme.railMaxWidth } : void 0;
227
+ const isBusy = state.phase === "thinking" || state.phase === "running-tools" || state.phase === "streaming";
228
+ const showActivity = state.toolSteps.length > 0 && (state.phase === "thinking" || state.phase === "running-tools" || state.phase === "streaming");
229
+ const showStreamingInActivity = state.phase === "streaming" && Boolean(state.streamingText);
230
+ const hasVisitorMessages2 = state.messages.some((message) => message.role === "visitor");
231
+ const showIdleFollowUps = !hasVisitorMessages2 && state.followUps.length > 0;
232
+ const showCompleteFollowUps = state.phase === "complete" && state.followUps.length > 0 && hasVisitorMessages2;
233
+ const showDockFollowUps = expanded && (showIdleFollowUps || showCompleteFollowUps);
234
+ useEffect(() => {
235
+ const node = transcriptRef.current;
236
+ if (!node) return;
237
+ node.scrollTop = node.scrollHeight;
238
+ }, [state.messages, state.toolSteps, state.streamingText, state.followUps, state.journey]);
239
+ return /* @__PURE__ */ jsxs5(
240
+ "aside",
241
+ {
242
+ className: `agent-rail${mobileFullscreen ? " agent-rail--mobile-fullscreen" : ""}${expanded ? " agent-rail--expanded" : ""}`,
243
+ style: railStyle,
244
+ "aria-label": "Agent conversation",
245
+ children: [
246
+ /* @__PURE__ */ jsx6("header", { className: "agent-rail__header", children: /* @__PURE__ */ jsxs5("div", { className: "agent-rail__brand-row", children: [
247
+ onCollapse ? /* @__PURE__ */ jsx6(
248
+ "button",
249
+ {
250
+ type: "button",
251
+ className: "agent-rail__collapse",
252
+ "aria-label": "Collapse assist",
253
+ onClick: onCollapse,
254
+ children: /* @__PURE__ */ jsx6(MinimizeIcon, {})
255
+ }
256
+ ) : onClose ? /* @__PURE__ */ jsx6("button", { type: "button", className: "agent-rail__close", "aria-label": "Close agent", onClick: onClose, children: /* @__PURE__ */ jsx6(MinimizeIcon, {}) }) : /* @__PURE__ */ jsx6("span", { className: "agent-rail__brand-spacer", "aria-hidden": "true" }),
257
+ /* @__PURE__ */ jsx6("span", { className: "agent-rail__brand-label", children: brandLabel }),
258
+ onExpandToggle ? /* @__PURE__ */ jsx6(
259
+ "button",
260
+ {
261
+ type: "button",
262
+ className: "agent-rail__expand",
263
+ "aria-label": expanded ? "Restore assist panel" : "Expand assist panel",
264
+ onClick: onExpandToggle,
265
+ children: expanded ? /* @__PURE__ */ jsx6(RestoreIcon, {}) : /* @__PURE__ */ jsx6(ExpandIcon, {})
266
+ }
267
+ ) : /* @__PURE__ */ jsx6("span", { className: "agent-rail__brand-spacer", "aria-hidden": "true" })
268
+ ] }) }),
269
+ /* @__PURE__ */ jsxs5("div", { ref: transcriptRef, className: "agent-rail__transcript", children: [
270
+ state.messages.map((message) => /* @__PURE__ */ jsx6(MessageBubble, { message }, message.id)),
271
+ showActivity ? /* @__PURE__ */ jsx6(
272
+ AgentActivityBubble,
273
+ {
274
+ steps: state.toolSteps,
275
+ streamingText: state.streamingText,
276
+ showStreaming: showStreamingInActivity
277
+ }
278
+ ) : null,
279
+ !expanded && showIdleFollowUps ? /* @__PURE__ */ jsx6("div", { className: "agent-rail__followups-slot", children: /* @__PURE__ */ jsx6(
280
+ FollowUpChips,
281
+ {
282
+ suggestions: state.followUps,
283
+ disabled: isBusy,
284
+ label: "Try asking",
285
+ onSelect: (suggestion) => onFollowUpSelect?.(suggestion.label)
286
+ }
287
+ ) }) : null,
288
+ !expanded && showCompleteFollowUps ? /* @__PURE__ */ jsx6("div", { className: "agent-rail__followups-slot", children: /* @__PURE__ */ jsx6(
289
+ FollowUpChips,
290
+ {
291
+ suggestions: state.followUps,
292
+ disabled: isBusy,
293
+ onSelect: (suggestion) => onFollowUpSelect?.(suggestion.label)
294
+ }
295
+ ) }) : null,
296
+ state.error ? /* @__PURE__ */ jsx6("p", { role: "alert", style: { fontSize: 13, color: "var(--as-danger)", margin: 0 }, children: state.error }) : null
297
+ ] }),
298
+ expanded ? /* @__PURE__ */ jsxs5("div", { className: "agent-rail__dock-wrap", children: [
299
+ showDockFollowUps ? /* @__PURE__ */ jsx6("div", { className: "agent-rail__dock-followups", children: /* @__PURE__ */ jsx6(
300
+ FollowUpChips,
301
+ {
302
+ variant: "dock",
303
+ suggestions: state.followUps,
304
+ disabled: isBusy,
305
+ onSelect: (suggestion) => onFollowUpSelect?.(suggestion.label)
306
+ }
307
+ ) }) : null,
308
+ /* @__PURE__ */ jsx6("div", { className: "agent-rail__dock", children: /* @__PURE__ */ jsx6(
309
+ Composer,
310
+ {
311
+ variant: "dock",
312
+ disabled: isBusy,
313
+ placeholder: composerPlaceholder,
314
+ onSubmit
315
+ }
316
+ ) }),
317
+ /* @__PURE__ */ jsxs5("div", { className: "agent-rail__footer", children: [
318
+ /* @__PURE__ */ jsx6("p", { className: "agent-rail__footer-disclaimer", children: "AI can make mistakes. Check important info." }),
319
+ /* @__PURE__ */ jsx6("p", { className: "agent-rail__footer-note", children: poweredByLabel })
320
+ ] })
321
+ ] }) : /* @__PURE__ */ jsxs5("div", { className: "agent-rail__composer-wrap", children: [
322
+ /* @__PURE__ */ jsx6(
323
+ Composer,
324
+ {
325
+ disabled: isBusy,
326
+ placeholder: composerPlaceholder,
327
+ onSubmit
328
+ }
329
+ ),
330
+ /* @__PURE__ */ jsxs5("div", { className: "agent-rail__footer", children: [
331
+ /* @__PURE__ */ jsx6("p", { className: "agent-rail__footer-disclaimer", children: "AI can make mistakes. Check important info." }),
332
+ /* @__PURE__ */ jsx6("p", { className: "agent-rail__footer-note", children: poweredByLabel })
333
+ ] })
334
+ ] })
335
+ ]
336
+ }
337
+ );
338
+ }
339
+
340
+ // src/react/components/AssistEdgeTab/AssistEdgeTab.tsx
341
+ import { Fragment, jsx as jsx7, jsxs as jsxs6 } from "react/jsx-runtime";
342
+ function SparklesIcon() {
343
+ return /* @__PURE__ */ jsxs6("svg", { className: "assist-edge-tab__sparkles", viewBox: "0 0 18 16", fill: "none", "aria-hidden": "true", children: [
344
+ /* @__PURE__ */ jsx7("path", { d: "M8 1.2l.95 2.7 2.85.05-2.25 1.75.8 2.75L8 6.7 5.65 8.45l.8-2.75L4.2 3.95l2.85-.05L8 1.2z", fill: "currentColor" }),
345
+ /* @__PURE__ */ jsx7("path", { d: "M14.2 6.4l.55 1.55 1.65.03-1.3 1 .46 1.58-1.36-1-1.36 1 .46-1.58-1.3-1 1.65-.03.55-1.55z", fill: "currentColor" }),
346
+ /* @__PURE__ */ jsx7("path", { d: "M3.1 9.1l.4 1.15 1.22.02-.96.74.34 1.17-1-.74-1 .74.34-1.17-.96-.74 1.22-.02.4-1.15z", fill: "currentColor" })
347
+ ] });
348
+ }
349
+ function ChevronLeftIcon() {
350
+ return /* @__PURE__ */ jsx7("svg", { viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsx7("path", { d: "M10 4L6 8l4 4", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round" }) });
351
+ }
352
+ function ChevronDownIcon() {
353
+ return /* @__PURE__ */ jsx7("svg", { viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsx7("path", { d: "M4 6l4 4 4-4", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round" }) });
354
+ }
355
+ function DragDots() {
356
+ return /* @__PURE__ */ jsx7("span", { className: "assist-edge-tab__dots", "aria-hidden": "true", children: Array.from({ length: 12 }, (_, index) => /* @__PURE__ */ jsx7("i", {}, index)) });
357
+ }
358
+ var VARIANT_COPY = {
359
+ outline: { label: "Assist", aria: "Open Assist" },
360
+ ask: { label: "Ask anything", aria: "Ask anything" },
361
+ fill: { label: "Assist", aria: "Open Assist" }
362
+ };
363
+ function AssistEdgeTab({
364
+ variant,
365
+ side,
366
+ along,
367
+ inset,
368
+ visible,
369
+ onOpen
370
+ }) {
371
+ const copy = VARIANT_COPY[variant];
372
+ const style = {
373
+ "--tab-along": `${along}%`,
374
+ "--tab-inset": `${inset}px`
375
+ };
376
+ return /* @__PURE__ */ jsxs6(
377
+ "button",
378
+ {
379
+ type: "button",
380
+ className: `assist-edge-tab assist-edge-tab--${variant} assist-edge-tab--${side}${visible ? " is-visible" : ""}`,
381
+ style,
382
+ "aria-label": copy.aria,
383
+ "aria-hidden": !visible,
384
+ tabIndex: visible ? 0 : -1,
385
+ onClick: onOpen,
386
+ children: [
387
+ variant === "outline" ? /* @__PURE__ */ jsxs6(Fragment, { children: [
388
+ /* @__PURE__ */ jsx7(SparklesIcon, {}),
389
+ /* @__PURE__ */ jsx7("span", { className: "assist-edge-tab__label", children: copy.label }),
390
+ /* @__PURE__ */ jsx7(ChevronDownIcon, {})
391
+ ] }) : null,
392
+ variant === "ask" ? /* @__PURE__ */ jsxs6(Fragment, { children: [
393
+ /* @__PURE__ */ jsx7(ChevronLeftIcon, {}),
394
+ /* @__PURE__ */ jsx7("span", { className: "assist-edge-tab__label", children: copy.label }),
395
+ /* @__PURE__ */ jsx7(DragDots, {})
396
+ ] }) : null,
397
+ variant === "fill" ? /* @__PURE__ */ jsxs6(Fragment, { children: [
398
+ /* @__PURE__ */ jsx7(SparklesIcon, {}),
399
+ /* @__PURE__ */ jsx7("span", { className: "assist-edge-tab__label", children: copy.label }),
400
+ /* @__PURE__ */ jsx7(ChevronLeftIcon, {})
401
+ ] }) : null
402
+ ]
403
+ }
404
+ );
405
+ }
406
+
407
+ // src/react/hooks/useAgentChat.ts
408
+ import { useCallback, useEffect as useEffect2, useMemo, useRef as useRef3, useState as useState2 } from "react";
409
+
410
+ // src/runtime/client.ts
411
+ import {
412
+ Client,
413
+ ClientError
414
+ } from "eve/client";
415
+
416
+ // src/runtime/config.ts
417
+ var DEFAULT_RUNTIME_ORIGIN = "https://runtime.staging.webless.ai";
418
+ var trimTrailingSlash = (value) => value.replace(/\/+$/, "");
419
+ function buildEveHost(origin, indexId) {
420
+ const base = trimTrailingSlash(origin);
421
+ return `${base}?indexId=${encodeURIComponent(indexId.trim())}`;
422
+ }
423
+ function resolveAgentRuntimeConfig(input) {
424
+ const origin = trimTrailingSlash(input.runtimeOrigin?.trim() || DEFAULT_RUNTIME_ORIGIN);
425
+ const resolvedIndexId = input.indexId.trim();
426
+ return {
427
+ origin,
428
+ indexId: resolvedIndexId,
429
+ host: resolvedIndexId ? buildEveHost(origin, resolvedIndexId) : origin
430
+ };
431
+ }
432
+
433
+ // src/runtime/session-store.ts
434
+ var DEFAULT_STORAGE_KEY_PREFIX = "webless:agent";
435
+ function normalizeRuntimeOrigin(runtimeOrigin) {
436
+ const trimmed = runtimeOrigin?.trim();
437
+ if (!trimmed) return "_";
438
+ return trimmed.replace(/\/+$/, "");
439
+ }
440
+ function buildAgentStorageKeyPrefix(input) {
441
+ const customerId = input.customerId?.trim() || "_";
442
+ const indexId = input.indexId.trim();
443
+ if (!indexId) {
444
+ throw new Error("indexId is required to build agent storage keys.");
445
+ }
446
+ return `${DEFAULT_STORAGE_KEY_PREFIX}:${customerId}:${indexId}:${normalizeRuntimeOrigin(input.runtimeOrigin)}`;
447
+ }
448
+ function createSessionId() {
449
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
450
+ return crypto.randomUUID();
451
+ }
452
+ return `sess_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
453
+ }
454
+ function resolvePrefix(options) {
455
+ return options?.storageKeyPrefix?.trim() || DEFAULT_STORAGE_KEY_PREFIX;
456
+ }
457
+ function getOrCreateVisitorSessionId(options) {
458
+ const prefix = resolvePrefix(options);
459
+ const visitorKey = `${prefix}:visitorSessionId`;
460
+ if (typeof sessionStorage === "undefined") {
461
+ return createSessionId();
462
+ }
463
+ const existing = sessionStorage.getItem(visitorKey)?.trim();
464
+ if (existing) return existing;
465
+ const next = createSessionId();
466
+ sessionStorage.setItem(visitorKey, next);
467
+ return next;
468
+ }
469
+ function runtimeSessionIdKey(visitorSessionId, prefix) {
470
+ return `${prefix}:eve:${visitorSessionId}:sessionId`;
471
+ }
472
+ function runtimeStreamIndexKey(visitorSessionId, prefix) {
473
+ return `${prefix}:eve:${visitorSessionId}:streamIndex`;
474
+ }
475
+ function loadPersistedAgentSession(visitorSessionId, options) {
476
+ if (typeof sessionStorage === "undefined" || !visitorSessionId.trim()) return null;
477
+ const prefix = resolvePrefix(options);
478
+ const sessionId = sessionStorage.getItem(runtimeSessionIdKey(visitorSessionId, prefix))?.trim();
479
+ if (!sessionId) return null;
480
+ const rawIndex = sessionStorage.getItem(runtimeStreamIndexKey(visitorSessionId, prefix));
481
+ const streamIndex = rawIndex ? Number.parseInt(rawIndex, 10) : 0;
482
+ return {
483
+ sessionId,
484
+ streamIndex: Number.isFinite(streamIndex) && streamIndex >= 0 ? streamIndex : 0
485
+ };
486
+ }
487
+ function savePersistedAgentSession(visitorSessionId, sessionId, streamIndex, options) {
488
+ if (typeof sessionStorage === "undefined" || !visitorSessionId.trim() || !sessionId.trim()) {
489
+ return;
490
+ }
491
+ const prefix = resolvePrefix(options);
492
+ sessionStorage.setItem(runtimeSessionIdKey(visitorSessionId, prefix), sessionId);
493
+ sessionStorage.setItem(
494
+ runtimeStreamIndexKey(visitorSessionId, prefix),
495
+ String(Math.max(0, streamIndex))
496
+ );
497
+ }
498
+ function clearPersistedAgentSession(visitorSessionId, options) {
499
+ if (typeof sessionStorage === "undefined" || !visitorSessionId.trim()) return;
500
+ const prefix = resolvePrefix(options);
501
+ sessionStorage.removeItem(runtimeSessionIdKey(visitorSessionId, prefix));
502
+ sessionStorage.removeItem(runtimeStreamIndexKey(visitorSessionId, prefix));
503
+ }
504
+
505
+ // src/runtime/client.ts
506
+ function mapStepLabel(event) {
507
+ if (event.type !== "step.started") return null;
508
+ const stepIndex = event.data.stepIndex;
509
+ return {
510
+ label: "Model step running",
511
+ detail: typeof stepIndex === "number" ? `Step ${stepIndex + 1}` : void 0
512
+ };
513
+ }
514
+ var AgentSession = class {
515
+ constructor(indexId, runtimeOrigin, visitorSessionId, storeOptions) {
516
+ this.indexId = indexId;
517
+ this.runtimeOrigin = runtimeOrigin;
518
+ this.visitorSessionId = visitorSessionId;
519
+ this.storeOptions = storeOptions;
520
+ }
521
+ indexId;
522
+ runtimeOrigin;
523
+ visitorSessionId;
524
+ storeOptions;
525
+ client;
526
+ clientHost;
527
+ session;
528
+ activeResponse;
529
+ renderedPrefix = "";
530
+ getActiveSessionId() {
531
+ return this.session?.state.sessionId ?? loadPersistedAgentSession(this.visitorSessionId, this.storeOptions)?.sessionId;
532
+ }
533
+ reset() {
534
+ void this.activeResponse?.cancel().catch(() => {
535
+ });
536
+ this.activeResponse = void 0;
537
+ this.session = void 0;
538
+ this.renderedPrefix = "";
539
+ clearPersistedAgentSession(this.visitorSessionId, this.storeOptions);
540
+ }
541
+ persistSessionCursor(session) {
542
+ savePersistedAgentSession(
543
+ this.visitorSessionId,
544
+ session.state.sessionId,
545
+ session.state.streamIndex,
546
+ this.storeOptions
547
+ );
548
+ }
549
+ ensureClient() {
550
+ const config = resolveAgentRuntimeConfig({
551
+ indexId: this.indexId,
552
+ runtimeOrigin: this.runtimeOrigin
553
+ });
554
+ if (!config.indexId) {
555
+ throw new Error("indexId is required.");
556
+ }
557
+ if (this.client && this.clientHost === config.host) {
558
+ return this.client;
559
+ }
560
+ this.reset();
561
+ this.client = new Client({ host: config.host });
562
+ this.clientHost = config.host;
563
+ return this.client;
564
+ }
565
+ attachPersistedSession(client) {
566
+ const persisted = loadPersistedAgentSession(this.visitorSessionId, this.storeOptions);
567
+ if (!persisted?.sessionId) return void 0;
568
+ this.renderedPrefix = "";
569
+ return client.sessions.attach(persisted.sessionId, {
570
+ streamIndex: persisted.streamIndex
571
+ });
572
+ }
573
+ async sendTurn(message, signal, handlers) {
574
+ const client = this.ensureClient();
575
+ let response;
576
+ let session = this.session ?? this.attachPersistedSession(client);
577
+ if (session) {
578
+ this.session = session;
579
+ try {
580
+ response = await session.send(message, { signal });
581
+ } catch (error) {
582
+ if (error instanceof ClientError && error.status === 409 && error.code === "session_not_active") {
583
+ clearPersistedAgentSession(this.visitorSessionId, this.storeOptions);
584
+ this.session = void 0;
585
+ session = void 0;
586
+ } else {
587
+ throw error;
588
+ }
589
+ }
590
+ }
591
+ if (!response) {
592
+ const created = await client.sessions.create({ message, signal });
593
+ response = created.response;
594
+ session = created.session;
595
+ this.session = session;
596
+ this.renderedPrefix = "";
597
+ this.persistSessionCursor(session);
598
+ }
599
+ this.activeResponse = response;
600
+ let rendered = this.renderedPrefix;
601
+ try {
602
+ for await (const event of response) {
603
+ if (signal.aborted) break;
604
+ const step = mapStepLabel(event);
605
+ if (step) handlers.onStep?.(step.label, step.detail);
606
+ if (event.type === "message.appended") {
607
+ const { messageDelta, messageSoFar } = event.data;
608
+ let delta = messageDelta;
609
+ if (messageSoFar.startsWith(rendered)) {
610
+ delta = messageSoFar.slice(rendered.length);
611
+ rendered = messageSoFar;
612
+ } else if (messageDelta) {
613
+ rendered += messageDelta;
614
+ }
615
+ if (delta) handlers.onDelta(delta);
616
+ }
617
+ if (event.type === "message.completed") {
618
+ handlers.onComplete?.();
619
+ }
620
+ if (event.type === "session.failed") {
621
+ throw new Error(event.data.message || event.data.code);
622
+ }
623
+ }
624
+ } finally {
625
+ this.activeResponse = void 0;
626
+ this.renderedPrefix = rendered;
627
+ if (session) {
628
+ this.persistSessionCursor(session);
629
+ }
630
+ }
631
+ if (!rendered.trim() && !signal.aborted) {
632
+ throw new Error("Empty response from runtime");
633
+ }
634
+ if (signal.aborted) {
635
+ await response.cancel().catch(() => {
636
+ });
637
+ }
638
+ return rendered.trim();
639
+ }
640
+ cancelActive() {
641
+ this.activeResponse?.cancel().catch(() => {
642
+ });
643
+ }
644
+ };
645
+ function createAgentClient(options) {
646
+ const indexId = options.indexId.trim();
647
+ if (!indexId) {
648
+ throw new Error("indexId is required.");
649
+ }
650
+ const runtimeOrigin = options.runtimeOrigin?.trim() || resolveAgentRuntimeConfig({ indexId }).origin;
651
+ const storeOptions = {
652
+ storageKeyPrefix: options.storageKeyPrefix?.trim() || buildAgentStorageKeyPrefix({
653
+ customerId: options.customerId,
654
+ indexId,
655
+ runtimeOrigin
656
+ })
657
+ };
658
+ const visitorSessionId = options.visitorSessionId?.trim() || getOrCreateVisitorSessionId(storeOptions);
659
+ const session = new AgentSession(indexId, runtimeOrigin, visitorSessionId, storeOptions);
660
+ return {
661
+ indexId,
662
+ runtimeOrigin,
663
+ visitorSessionId,
664
+ sendTurn: (message, sendOptions) => session.sendTurn(
665
+ message,
666
+ sendOptions.signal ?? new AbortController().signal,
667
+ sendOptions.handlers
668
+ ),
669
+ reset: () => session.reset(),
670
+ cancelActive: () => session.cancelActive(),
671
+ getActiveSessionId: () => session.getActiveSessionId()
672
+ };
673
+ }
674
+
675
+ // src/runtime/errors.ts
676
+ import { ClientError as ClientError2 } from "eve/client";
677
+ function formatAgentError(error) {
678
+ if (error instanceof ClientError2) {
679
+ if (error.status === 401 && error.code === "index_required") {
680
+ return "Missing indexId \u2014 pass a published index id to createAgentClient().";
681
+ }
682
+ if (error.status === 403 && error.code === "agent_unavailable") {
683
+ return "Agent unavailable for this index (disabled or unpublished).";
684
+ }
685
+ if (error.status === 409 && error.code === "session_not_active") {
686
+ return "Session expired \u2014 send a new message to start again.";
687
+ }
688
+ return error.message || `Runtime error (${error.status})`;
689
+ }
690
+ if (error instanceof DOMException && error.name === "AbortError") {
691
+ return "";
692
+ }
693
+ if (error instanceof Error) return error.message;
694
+ return "Runtime request failed";
695
+ }
696
+
697
+ // src/react/hooks/useAgentChat.ts
698
+ var GREETING_MESSAGE = {
699
+ id: "greeting",
700
+ role: "agent",
701
+ text: "Hi! I'm connected to the Webless Agent Runtime. Ask anything about your published site index.",
702
+ createdAt: 0
703
+ };
704
+ var INITIAL_STATE = {
705
+ phase: "idle",
706
+ messages: [GREETING_MESSAGE],
707
+ toolSteps: [],
708
+ journey: null,
709
+ followUps: [],
710
+ streamingText: "",
711
+ error: null
712
+ };
713
+ var STATUS_SEQUENCE = [
714
+ { id: "s1", label: "Starting Eve session", ms: 400 },
715
+ { id: "s2", label: "Connecting to runtime", ms: 500 }
716
+ ];
717
+ var DEFAULT_FOLLOW_UPS = [
718
+ { id: "fu-1", label: "What can you help me with?" },
719
+ { id: "fu-2", label: "Summarize your capabilities" },
720
+ { id: "fu-3", label: "What should I ask next?" }
721
+ ];
722
+ function delay(ms, signal) {
723
+ return new Promise((resolve, reject) => {
724
+ const timer = window.setTimeout(resolve, ms);
725
+ signal.addEventListener(
726
+ "abort",
727
+ () => {
728
+ window.clearTimeout(timer);
729
+ reject(new DOMException("Aborted", "AbortError"));
730
+ },
731
+ { once: true }
732
+ );
733
+ });
734
+ }
735
+ async function runStatusSequence(signal, onStep) {
736
+ for (const item of STATUS_SEQUENCE) {
737
+ onStep({ id: item.id, label: item.label, detail: item.detail, state: "active" });
738
+ await delay(item.ms, signal);
739
+ }
740
+ }
741
+ function useAgentChat({
742
+ customerId,
743
+ indexId,
744
+ runtimeOrigin,
745
+ visitorSessionId,
746
+ storageKeyPrefix
747
+ }) {
748
+ const [state, setState] = useState2(INITIAL_STATE);
749
+ const runRef = useRef3(null);
750
+ const resolvedStorageKeyPrefix = useMemo(
751
+ () => storageKeyPrefix?.trim() || buildAgentStorageKeyPrefix({ customerId, indexId, runtimeOrigin }),
752
+ [customerId, indexId, runtimeOrigin, storageKeyPrefix]
753
+ );
754
+ const visitorId = useMemo(
755
+ () => visitorSessionId?.trim() || getOrCreateVisitorSessionId({ storageKeyPrefix: resolvedStorageKeyPrefix }),
756
+ [resolvedStorageKeyPrefix, visitorSessionId]
757
+ );
758
+ const clientRef = useRef3(
759
+ createAgentClient({
760
+ customerId,
761
+ indexId,
762
+ runtimeOrigin,
763
+ visitorSessionId: visitorId,
764
+ storageKeyPrefix: resolvedStorageKeyPrefix
765
+ })
766
+ );
767
+ const identityRef = useRef3(null);
768
+ const identityKey = `${customerId ?? ""}|${indexId}|${runtimeOrigin ?? ""}|${resolvedStorageKeyPrefix}|${visitorId}`;
769
+ useEffect2(() => {
770
+ if (identityRef.current === null) {
771
+ identityRef.current = identityKey;
772
+ return;
773
+ }
774
+ if (identityRef.current === identityKey) {
775
+ return;
776
+ }
777
+ identityRef.current = identityKey;
778
+ runRef.current?.abort();
779
+ runRef.current = null;
780
+ clientRef.current.reset();
781
+ clientRef.current = createAgentClient({
782
+ customerId,
783
+ indexId,
784
+ runtimeOrigin,
785
+ visitorSessionId: visitorId,
786
+ storageKeyPrefix: resolvedStorageKeyPrefix
787
+ });
788
+ setState(INITIAL_STATE);
789
+ }, [customerId, identityKey, indexId, runtimeOrigin, resolvedStorageKeyPrefix, visitorId]);
790
+ const reset = useCallback(() => {
791
+ runRef.current?.abort();
792
+ runRef.current = null;
793
+ clientRef.current.reset();
794
+ setState(INITIAL_STATE);
795
+ }, []);
796
+ const submit = useCallback(
797
+ async (visitorText) => {
798
+ runRef.current?.abort();
799
+ clientRef.current.cancelActive();
800
+ const controller = new AbortController();
801
+ runRef.current = controller;
802
+ const { signal } = controller;
803
+ const isActiveRun = () => runRef.current === controller && !signal.aborted;
804
+ const visitorMessage = {
805
+ id: `visitor-${Date.now()}`,
806
+ role: "visitor",
807
+ text: visitorText,
808
+ createdAt: Date.now()
809
+ };
810
+ setState((prev) => ({
811
+ ...prev,
812
+ phase: "thinking",
813
+ messages: [...prev.messages, visitorMessage],
814
+ toolSteps: [{ id: "s1", label: "Starting Eve session", state: "active" }],
815
+ journey: null,
816
+ followUps: [],
817
+ streamingText: "",
818
+ error: null
819
+ }));
820
+ try {
821
+ let streamStarted = false;
822
+ const planningPromise = runStatusSequence(signal, (step) => {
823
+ if (streamStarted || !isActiveRun()) return;
824
+ setState((prev) => ({ ...prev, phase: "running-tools", toolSteps: [step] }));
825
+ });
826
+ let streamed = "";
827
+ const finalText = await clientRef.current.sendTurn(visitorText, {
828
+ signal,
829
+ handlers: {
830
+ onStep: (label, detail) => {
831
+ if (streamStarted || !isActiveRun()) return;
832
+ setState((prev) => ({
833
+ ...prev,
834
+ phase: "running-tools",
835
+ toolSteps: [{ id: `step-${label}`, label, detail, state: "active" }]
836
+ }));
837
+ },
838
+ onDelta: (delta) => {
839
+ if (!isActiveRun()) return;
840
+ void planningPromise.catch(() => {
841
+ });
842
+ if (!streamStarted) {
843
+ streamStarted = true;
844
+ setState((prev) => ({
845
+ ...prev,
846
+ phase: "streaming",
847
+ toolSteps: [],
848
+ streamingText: ""
849
+ }));
850
+ }
851
+ streamed += delta;
852
+ setState((prev) => ({ ...prev, phase: "streaming", streamingText: streamed }));
853
+ },
854
+ onComplete: () => {
855
+ if (!isActiveRun()) return;
856
+ streamStarted = true;
857
+ }
858
+ }
859
+ });
860
+ await planningPromise.catch(() => {
861
+ });
862
+ if (!isActiveRun()) return;
863
+ const agentMessage = {
864
+ id: `agent-${Date.now()}`,
865
+ role: "agent",
866
+ text: finalText,
867
+ createdAt: Date.now()
868
+ };
869
+ setState((prev) => ({
870
+ ...prev,
871
+ phase: "complete",
872
+ messages: [...prev.messages, agentMessage],
873
+ toolSteps: [],
874
+ streamingText: "",
875
+ followUps: DEFAULT_FOLLOW_UPS,
876
+ journey: null
877
+ }));
878
+ } catch (error) {
879
+ if (error instanceof DOMException && error.name === "AbortError") return;
880
+ if (!isActiveRun()) return;
881
+ const message = formatAgentError(error);
882
+ if (!message) return;
883
+ setState((prev) => ({
884
+ ...prev,
885
+ phase: "complete",
886
+ toolSteps: [],
887
+ streamingText: "",
888
+ error: message
889
+ }));
890
+ }
891
+ },
892
+ [customerId, indexId, runtimeOrigin, resolvedStorageKeyPrefix, visitorId]
893
+ );
894
+ useEffect2(() => {
895
+ return () => {
896
+ runRef.current?.abort();
897
+ clientRef.current.cancelActive();
898
+ };
899
+ }, []);
900
+ return {
901
+ state,
902
+ reset,
903
+ submit,
904
+ visitorSessionId: visitorId,
905
+ sessionId: clientRef.current.getActiveSessionId()
906
+ };
907
+ }
908
+ function hasVisitorMessages(messages) {
909
+ return messages.some((message) => message.role === "visitor");
910
+ }
911
+ function createIdleSuggestions() {
912
+ return [
913
+ { id: "idle-1", label: "Hello \u2014 what can you do?" },
914
+ { id: "idle-2", label: "Help me evaluate this product" },
915
+ { id: "idle-3", label: "What should I ask you?" }
916
+ ];
917
+ }
918
+ function isAgentBusy(phase) {
919
+ return phase === "thinking" || phase === "running-tools" || phase === "streaming";
920
+ }
921
+
922
+ export {
923
+ AgentRail,
924
+ AssistEdgeTab,
925
+ DEFAULT_RUNTIME_ORIGIN,
926
+ resolveAgentRuntimeConfig,
927
+ useAgentChat,
928
+ hasVisitorMessages,
929
+ createIdleSuggestions,
930
+ isAgentBusy
931
+ };
932
+ //# sourceMappingURL=chunk-WLQDMWO6.js.map