@jini-ai/chat 0.6.15 → 0.6.16
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 +6 -1
- package/dist/core/antigravity/tool-presentation.d.ts +13 -0
- package/dist/core/antigravity/tool-presentation.js +20 -0
- package/dist/core/assistant-client/ag-ui-transport.js +13 -1
- package/dist/core/events.d.ts +5 -1
- package/dist/core/tool-events.d.ts +18 -8
- package/dist/core/tool-events.js +72 -16
- package/dist/core/tool-presentation.d.ts +14 -0
- package/dist/core/tool-presentation.js +8 -0
- package/dist/core/user-text-redaction.d.ts +2 -1
- package/dist/core/user-text-redaction.js +10 -3
- package/dist/embed-widget/browser/frontend-session-bridge.d.ts +99 -0
- package/dist/embed-widget/browser/frontend-session-bridge.js +384 -0
- package/dist/embed-widget/browser/session-store.d.ts +3 -9
- package/dist/embed-widget/browser/session-store.js +6 -38
- package/dist/embed-widget/react/embed.d.ts +3 -10
- package/dist/embed-widget/react/embed.js +8 -52
- package/dist/embed-widget/vanilla/index.d.ts +0 -5
- package/dist/embed-widget/vanilla/index.js +4 -14
- package/dist/embed-widget/vanilla/state.d.ts +3 -11
- package/dist/embed-widget/vanilla/state.js +6 -37
- package/dist/embed-widget/vanilla/style.css +1 -1
- package/dist/react/agent-bridge/frontend-session-bridge.d.ts +2 -56
- package/dist/react/agent-bridge/frontend-session-bridge.js +2 -248
- package/dist/react/components/Icon.d.ts +1 -1
- package/dist/react/components/Icon.js +1 -0
- package/dist/react/components/Markdown.d.ts +1 -0
- package/dist/react/components/Markdown.js +1 -1
- package/dist/react/components/MessageList.d.ts +1 -1
- package/dist/react/components/MessageRow.d.ts +3 -0
- package/dist/react/components/MessageRow.js +10 -8
- package/dist/react/components/ToolCard.d.ts +3 -1
- package/dist/react/components/ToolCard.js +77 -58
- package/dist/react/components/ToolCard.rules.d.ts +20 -0
- package/dist/react/components/ToolCard.rules.js +92 -0
- package/dist/react/features/chat-pane/components/AgentRuntimePicker.js +18 -6
- package/dist/react/features/chat-pane/components/ChatPane.js +3 -3
- package/dist/react/features/chat-pane/hooks/useChatPane.hooks.d.ts +3 -1
- package/dist/react/features/chat-pane/hooks/useChatPane.hooks.js +9 -3
- package/dist/react/features/chat-pane/styles.d.ts +1 -1
- package/dist/react/features/chat-pane/styles.js +76 -9
- package/dist/react/features/chat-pane/types.d.ts +3 -0
- package/dist/react/hooks/useUserTextGuard.d.ts +1 -0
- package/dist/react/hooks/useUserTextGuard.js +3 -1
- package/dist/react/tool-call-display.d.ts +11 -0
- package/dist/react/tool-call-display.js +59 -2
- package/package.json +91 -86
- package/dist/core/browser/page-actions.d.ts +0 -121
- package/dist/core/browser/page-actions.js +0 -115
- package/dist/embed-widget/browser/page-actions.d.ts +0 -2
- package/dist/embed-widget/browser/page-actions.js +0 -3
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
import { decodeSseFrames } from '@jini-ai/core/primitives';
|
|
2
|
+
/**
|
|
3
|
+
* @module agent-bridge/frontend-session-bridge
|
|
4
|
+
*
|
|
5
|
+
* The browser half of agent-driven frontend control: one SSE connection to the daemon, and the
|
|
6
|
+
* routing that turns each relayed invocation into a call on something in this page.
|
|
7
|
+
*
|
|
8
|
+
* Everything on the server side already existed — `FrontendSessionRegistry` addresses a run to a
|
|
9
|
+
* surface, the frontend-session routes carry invocations out and answers back, and
|
|
10
|
+
* `createFrontendControl` assembles them. `ChatPaneAgentBridgeAccess` declared the contract this
|
|
11
|
+
* satisfies and had **zero implementations**, which is why an agent could reach a tool and the
|
|
12
|
+
* tool could reach nothing.
|
|
13
|
+
*
|
|
14
|
+
* Design notes worth knowing before changing this:
|
|
15
|
+
*
|
|
16
|
+
* - **The connection is owned here, not by `subscribe`.** `ChatPaneAgentBridgeAccess.subscribe` is
|
|
17
|
+
* called by the chat pane's own effect, so tying the stream's lifetime to it would mean page
|
|
18
|
+
* control dies when the pane unmounts — and the page is drivable whether or not a chat pane
|
|
19
|
+
* exists. `subscribe` registers a listener; `close()` tears the connection down.
|
|
20
|
+
* - **Capabilities are claimed from what is actually wired.** The claim sent at connect time is
|
|
21
|
+
* derived from the presence of a `pageDriver` and the keys of `executors`, never from a static
|
|
22
|
+
* list. A surface that claims what it cannot serve turns a fast, named refusal into a timeout.
|
|
23
|
+
* - **An executed invocation is never executed twice.** If the stream drops between the daemon
|
|
24
|
+
* delivering an invocation and this page POSTing the answer, the daemon correctly fails that
|
|
25
|
+
* call — but the click already happened. Without the `executed` set below, the retry clicks
|
|
26
|
+
* again. Buttons are not idempotent.
|
|
27
|
+
* - **The bind token never leaves this module except to the host.** It arrives on the `attached`
|
|
28
|
+
* event and must ride to run-start; it deliberately does not appear in any URL (see
|
|
29
|
+
* `@jini-ai/daemon`'s `FrontendSessionHandle`).
|
|
30
|
+
* - **Read the bind token at send time, not once.** `EventSource` reconnects on its own — after a
|
|
31
|
+
* daemon restart, a sleeping laptop, or an ordinary network blip — and each reattach mints a new
|
|
32
|
+
* session and a new token. A host that captured `ready`'s token keeps sending a dead one, every
|
|
33
|
+
* later run fails to bind, and the only trace is a daemon-side log line: the agent is simply told
|
|
34
|
+
* "no frontend is bound to this run". `ready` therefore answers "has it attached at least once";
|
|
35
|
+
* {@link FrontendSessionBridge.bindToken} answers "what is valid now", and only the latter
|
|
36
|
+
* belongs in a run request.
|
|
37
|
+
*/
|
|
38
|
+
import { CHAT_CAPABILITIES } from '../../core/index.js';
|
|
39
|
+
import { PAGE_CAPABILITIES, executePageCapability } from '@jini-ai/agentic';
|
|
40
|
+
/** How many settled invocation ids to remember for replay suppression. */
|
|
41
|
+
const EXECUTED_MEMORY = 256;
|
|
42
|
+
/** Ids this surface can actually serve, given what the host wired up. */
|
|
43
|
+
function claimedCapabilities(options) {
|
|
44
|
+
if (options.capabilityIds)
|
|
45
|
+
return [...options.capabilityIds];
|
|
46
|
+
const claims = CHAT_CAPABILITIES.map((capability) => capability.id);
|
|
47
|
+
if (options.pageDriver !== undefined) {
|
|
48
|
+
claims.push(...PAGE_CAPABILITIES.map((capability) => capability.id));
|
|
49
|
+
}
|
|
50
|
+
// Dialog-support handshake only; page.approval is not an executable tool id.
|
|
51
|
+
if (options.pageApproval)
|
|
52
|
+
claims.push('page.approval');
|
|
53
|
+
claims.push(...Object.keys(options.executors ?? {}));
|
|
54
|
+
return claims;
|
|
55
|
+
}
|
|
56
|
+
function errorMessage(error) {
|
|
57
|
+
return error instanceof Error ? error.message : String(error);
|
|
58
|
+
}
|
|
59
|
+
/** Parses a frame's data into an object, or says why it is not one. */
|
|
60
|
+
function parseFrameObject(data) {
|
|
61
|
+
let parsed;
|
|
62
|
+
try {
|
|
63
|
+
parsed = JSON.parse(data);
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
return { error };
|
|
67
|
+
}
|
|
68
|
+
// `JSON.parse` succeeds on any valid JSON value, not just objects — a bare `null`, number,
|
|
69
|
+
// string or boolean parses cleanly and would throw *outside* this try/catch on the very next
|
|
70
|
+
// `frame['type']` read (`null` is the one of those that actually throws; the others just read
|
|
71
|
+
// back `undefined` harmlessly). Guarding here routes every one of those through the same
|
|
72
|
+
// `onError` path as an unparseable frame, rather than only some of them crashing the listener.
|
|
73
|
+
if (parsed === null || typeof parsed !== 'object') {
|
|
74
|
+
return { error: new Error(`malformed frame: expected a JSON object, got ${JSON.stringify(parsed)}`) };
|
|
75
|
+
}
|
|
76
|
+
return { frame: parsed };
|
|
77
|
+
}
|
|
78
|
+
/** Reads an `invocation` frame into the pane's action shape, refusing one with no usable id. */
|
|
79
|
+
function readInvocation(frame) {
|
|
80
|
+
const rawInvocationId = frame['invocationId'];
|
|
81
|
+
if (typeof rawInvocationId !== 'string' || rawInvocationId.length === 0) {
|
|
82
|
+
return { kind: 'malformed', error: new Error('invocation frame missing invocationId') };
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
kind: 'invocation',
|
|
86
|
+
action: {
|
|
87
|
+
invocationId: rawInvocationId,
|
|
88
|
+
capabilityId: String(frame['capabilityId']),
|
|
89
|
+
input: (frame['input'] ?? {}),
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/** Classifies one frame's raw data; the listener only applies the result. */
|
|
94
|
+
function readFrame(data) {
|
|
95
|
+
const parsed = parseFrameObject(data);
|
|
96
|
+
if ('error' in parsed)
|
|
97
|
+
return { kind: 'malformed', error: parsed.error };
|
|
98
|
+
const { frame } = parsed;
|
|
99
|
+
switch (frame['type']) {
|
|
100
|
+
case 'cancelled':
|
|
101
|
+
return { kind: 'cancelled', invocationId: String(frame['invocationId']) };
|
|
102
|
+
case 'attached':
|
|
103
|
+
return { kind: 'attached', sessionId: String(frame['sessionId']), bindToken: String(frame['bindToken']) };
|
|
104
|
+
case 'error':
|
|
105
|
+
return { kind: 'refused', message: String(frame['message']) };
|
|
106
|
+
case 'invocation':
|
|
107
|
+
return readInvocation(frame);
|
|
108
|
+
default:
|
|
109
|
+
// Unknown frame types are ignored rather than treated as errors, so the daemon's event
|
|
110
|
+
// vocabulary can grow without every deployed surface needing to ship first.
|
|
111
|
+
return { kind: 'ignored' };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Opens the surface's connection and starts routing invocations.
|
|
116
|
+
*
|
|
117
|
+
* @param options - What this page can serve and where the daemon is.
|
|
118
|
+
* @returns The pane's bridge, the attach result, and a teardown.
|
|
119
|
+
*/
|
|
120
|
+
export function createFrontendSessionBridge({ baseUrl: base, openStream, request, fetch, endpointPrefix = '/api/frontend-sessions', headers }, options = {}) {
|
|
121
|
+
const capabilities = claimedCapabilities(options);
|
|
122
|
+
// The only caller (`respond`) never passes its own signal, so the deadline is the whole signal.
|
|
123
|
+
const send = request ?? (({ url, init, timeoutMs }) => (fetch ?? globalThis.fetch)(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }));
|
|
124
|
+
let sessionId;
|
|
125
|
+
/** Replaced on every reattach; a promise resolved once could never carry this. */
|
|
126
|
+
let currentBindToken;
|
|
127
|
+
// Definite assignment rather than no-op placeholders: a Promise executor runs synchronously, so
|
|
128
|
+
// both are set before this line finishes, and placeholders would only add two functions that
|
|
129
|
+
// can never be called.
|
|
130
|
+
let resolveReady;
|
|
131
|
+
let rejectReady;
|
|
132
|
+
const ready = new Promise((resolve, reject) => {
|
|
133
|
+
resolveReady = resolve;
|
|
134
|
+
rejectReady = reject;
|
|
135
|
+
});
|
|
136
|
+
/** Chat-pane listeners. The pane registers exactly one; a second host could register another. */
|
|
137
|
+
const chatListeners = new Set();
|
|
138
|
+
/** Invocation ids already run here, so a stream reconnect cannot double-click a button. */
|
|
139
|
+
const executed = new Set();
|
|
140
|
+
const pending = new Map();
|
|
141
|
+
// A page driver owns one live screen. Serialize its observations, effect and acknowledgement;
|
|
142
|
+
// otherwise a second invocation could overwrite the first one's host-bound navigation plan.
|
|
143
|
+
let pageQueue = Promise.resolve();
|
|
144
|
+
const abortPending = () => {
|
|
145
|
+
for (const controller of pending.values()) {
|
|
146
|
+
controller.abort();
|
|
147
|
+
}
|
|
148
|
+
pending.clear();
|
|
149
|
+
};
|
|
150
|
+
const query = capabilities.map((id) => `capability=${encodeURIComponent(id)}`).join('&');
|
|
151
|
+
const source = openStream({ url: `${base}${endpointPrefix}/stream?${query}`, ...(headers ? { headers: headers() } : {}) });
|
|
152
|
+
async function respond(invocationId, body) {
|
|
153
|
+
if (sessionId === undefined)
|
|
154
|
+
throw new Error('the surface is not attached yet');
|
|
155
|
+
const wire = boundedFrontendResponse({ invocationId, body, maxBytes: options.maxResponseBytes });
|
|
156
|
+
const response = await send({
|
|
157
|
+
url: `${base}${endpointPrefix}/${encodeURIComponent(sessionId)}/responses`,
|
|
158
|
+
init: { method: 'POST', headers: { 'content-type': 'application/json', ...headers?.(), ...(headers ? { 'x-frontend-bind-token': currentBindToken ?? '' } : {}) }, body: wire.payload },
|
|
159
|
+
timeoutMs: 15_000,
|
|
160
|
+
});
|
|
161
|
+
await assertFrontendResponse({ response, invocationId, body, scoped: Boolean(headers), refused: wire.refused });
|
|
162
|
+
}
|
|
163
|
+
const respondSuccess = (invocationId, output) => respond(invocationId, { ok: true, output });
|
|
164
|
+
const respondError = (invocationId, message) => respond(invocationId, { ok: false, message });
|
|
165
|
+
/** Freeze once, ask on the app's existing human-only channel, then use the same page executor.
|
|
166
|
+
* The server pauses its execution deadline only after acknowledging the bounded human wait. */
|
|
167
|
+
async function servePage(action, signal) {
|
|
168
|
+
const input = options.preparePageInput ? options.preparePageInput({ action }) : structuredClone(action.input);
|
|
169
|
+
const args = { capabilityId: action.capabilityId, input };
|
|
170
|
+
if (options.pageApproval && !options.pageApproval.isDirect(args)) {
|
|
171
|
+
await respond(action.invocationId, { phase: 'approval-pending' });
|
|
172
|
+
const answer = await options.pageApproval.request({ ...args, input: structuredClone(input), signal });
|
|
173
|
+
// Report the decision before effects, including decline/expiry; the server audits it.
|
|
174
|
+
await respond(action.invocationId, { phase: 'execution-started', decision: answer.confirmed ? 'approved' : answer.reason });
|
|
175
|
+
if (!answer.confirmed)
|
|
176
|
+
return { executed: false, reason: answer.reason };
|
|
177
|
+
}
|
|
178
|
+
if (signal.aborted)
|
|
179
|
+
return { executed: false, reason: 'abandoned' };
|
|
180
|
+
return executePageCapability({ driver: options.pageDriver, ...args }, { signal });
|
|
181
|
+
}
|
|
182
|
+
/** Runs one non-chat invocation here and answers it. Chat ones go to the pane instead. */
|
|
183
|
+
async function serveLocally(action, controller) {
|
|
184
|
+
let output;
|
|
185
|
+
try {
|
|
186
|
+
controller.signal.throwIfAborted();
|
|
187
|
+
if (options.pageDriver !== undefined && action.capabilityId.startsWith('page.')) {
|
|
188
|
+
output = await servePage(action, controller.signal);
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
const entry = Object.entries(options.executors ?? {})
|
|
192
|
+
.find(([prefix]) => action.capabilityId.startsWith(prefix));
|
|
193
|
+
if (entry === undefined)
|
|
194
|
+
throw new Error(`nothing on this page serves "${action.capabilityId}"`);
|
|
195
|
+
output = await entry[1](action.capabilityId, action.input);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
pending.delete(action.invocationId);
|
|
200
|
+
await respondError(action.invocationId, errorMessage(error)).catch(options.onError ?? (() => undefined));
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
await acknowledge({ action, output, signal: controller.signal });
|
|
204
|
+
pending.delete(action.invocationId);
|
|
205
|
+
}
|
|
206
|
+
async function acknowledge({ action, output, signal }) {
|
|
207
|
+
try {
|
|
208
|
+
signal.throwIfAborted();
|
|
209
|
+
const projected = await options.onBeforeResponse?.({ action, output });
|
|
210
|
+
const acceptedOutput = projected ?? output;
|
|
211
|
+
await respondSuccess(action.invocationId, acceptedOutput);
|
|
212
|
+
signal.throwIfAborted();
|
|
213
|
+
await options.onAfterResponse?.({ action, output: acceptedOutput });
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
options.onError?.(error);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
function remember(invocationId) {
|
|
220
|
+
executed.add(invocationId);
|
|
221
|
+
if (executed.size > EXECUTED_MEMORY) {
|
|
222
|
+
const oldest = executed.values().next().value;
|
|
223
|
+
if (oldest !== undefined)
|
|
224
|
+
executed.delete(oldest);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/** Runs one well-formed invocation: replay check, announcement, then pane or local serving. */
|
|
228
|
+
function handleInvocation(action) {
|
|
229
|
+
// A redelivery after a dropped answer must not re-run the side effect.
|
|
230
|
+
if (executed.has(action.invocationId)) {
|
|
231
|
+
void respondError(action.invocationId, 'already executed on this surface').catch(() => undefined);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (options.capabilityIds && !options.capabilityIds.includes(action.capabilityId)) {
|
|
235
|
+
void respondError(action.invocationId, 'Capability unavailable').catch(() => undefined);
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
remember(action.invocationId);
|
|
239
|
+
options.onInvocation?.(action);
|
|
240
|
+
if (action.capabilityId.startsWith('chat.')) {
|
|
241
|
+
for (const listener of chatListeners)
|
|
242
|
+
listener(action);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
const controller = new AbortController();
|
|
246
|
+
pending.set(action.invocationId, controller);
|
|
247
|
+
if (action.capabilityId.startsWith('page.')) {
|
|
248
|
+
pageQueue = pageQueue.then(() => serveLocally(action, controller)).catch(error => options.onError?.(error));
|
|
249
|
+
}
|
|
250
|
+
else
|
|
251
|
+
void serveLocally(action, controller);
|
|
252
|
+
}
|
|
253
|
+
source.addEventListener('message', (event) => {
|
|
254
|
+
const frame = readFrame(event.data);
|
|
255
|
+
switch (frame.kind) {
|
|
256
|
+
case 'cancelled':
|
|
257
|
+
pending.get(frame.invocationId)?.abort();
|
|
258
|
+
return;
|
|
259
|
+
case 'attached':
|
|
260
|
+
abortPending();
|
|
261
|
+
sessionId = frame.sessionId;
|
|
262
|
+
currentBindToken = frame.bindToken;
|
|
263
|
+
// A no-op after the first attach — which is exactly why `currentBindToken` exists.
|
|
264
|
+
resolveReady({ sessionId, bindToken: currentBindToken });
|
|
265
|
+
return;
|
|
266
|
+
case 'refused':
|
|
267
|
+
rejectReady(new Error(frame.message));
|
|
268
|
+
return;
|
|
269
|
+
case 'malformed':
|
|
270
|
+
options.onError?.(frame.error);
|
|
271
|
+
return;
|
|
272
|
+
case 'invocation':
|
|
273
|
+
handleInvocation(frame.action);
|
|
274
|
+
return;
|
|
275
|
+
case 'ignored':
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
source.addEventListener('error', (event) => {
|
|
280
|
+
abortPending();
|
|
281
|
+
// The daemon deletes a session's bind token the instant that connection drops, so by the time
|
|
282
|
+
// this fires the token in hand is already gone from the registry. Holding it until the next
|
|
283
|
+
// `attached` frame leaves a window where `bindToken()` hands back something dead, and a run
|
|
284
|
+
// started in that window fails to bind — reported to the agent only as "no frontend is bound
|
|
285
|
+
// to this run", with the real reason (a reconnect it never saw) nowhere in view.
|
|
286
|
+
// Reporting no token is the honest answer for a surface that is, right now, not attached.
|
|
287
|
+
currentBindToken = undefined;
|
|
288
|
+
sessionId = undefined;
|
|
289
|
+
options.onError?.(event);
|
|
290
|
+
});
|
|
291
|
+
const bridgeAccess = {
|
|
292
|
+
subscribe(onAction) {
|
|
293
|
+
chatListeners.add(onAction);
|
|
294
|
+
// Removes this listener only. The connection outlives any one pane — see the module doc.
|
|
295
|
+
return () => chatListeners.delete(onAction);
|
|
296
|
+
},
|
|
297
|
+
respondSuccess,
|
|
298
|
+
respondError,
|
|
299
|
+
};
|
|
300
|
+
return {
|
|
301
|
+
bridgeAccess,
|
|
302
|
+
ready,
|
|
303
|
+
bindToken: () => currentBindToken,
|
|
304
|
+
close() {
|
|
305
|
+
abortPending();
|
|
306
|
+
source.close();
|
|
307
|
+
chatListeners.clear();
|
|
308
|
+
// A closed bridge serves nothing, so binding a run to it would strand that run rather than
|
|
309
|
+
// fail it — this is what stops a torn-down surface (a StrictMode remount, a route change)
|
|
310
|
+
// from handing its dead token to the next run.
|
|
311
|
+
currentBindToken = undefined;
|
|
312
|
+
sessionId = undefined;
|
|
313
|
+
},
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
/** Authenticated streaming replacement for EventSource when credentials belong in headers.
|
|
317
|
+
* Uses the shared SSE decoder; reconnect creates a new attachment and clears the old token.
|
|
318
|
+
* O(stream bytes), bounded frame buffer; close aborts fetch/readers and the reconnect timer. */
|
|
319
|
+
export function openFetchFrontendStream({ url, headers }, { fetch: send = globalThis.fetch, reconnectMs = 1000 } = {}) {
|
|
320
|
+
const events = new EventTarget();
|
|
321
|
+
const abort = new AbortController();
|
|
322
|
+
let retry;
|
|
323
|
+
let delay = reconnectMs;
|
|
324
|
+
async function connect() {
|
|
325
|
+
let retryable = true;
|
|
326
|
+
try {
|
|
327
|
+
const response = await send(url, { credentials: 'same-origin', mode: 'same-origin', redirect: 'error', headers: headers(), signal: abort.signal });
|
|
328
|
+
retryable = ![401, 403, 404, 429].includes(response.status);
|
|
329
|
+
if (!response.ok || !response.body)
|
|
330
|
+
throw new Error('Frontend stream unavailable');
|
|
331
|
+
for await (const frame of decodeSseFrames({ source: streamChunks(response.body) }, { maxBufferChars: 128_000 })) {
|
|
332
|
+
delay = reconnectMs; // A delivered event proves the connection recovered.
|
|
333
|
+
if (!abort.signal.aborted)
|
|
334
|
+
events.dispatchEvent(new MessageEvent('message', { data: frame.data }));
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
catch { /* The stream error has one value-free notification below. */ }
|
|
338
|
+
if (abort.signal.aborted)
|
|
339
|
+
return;
|
|
340
|
+
events.dispatchEvent(new Event('error'));
|
|
341
|
+
if (retryable) {
|
|
342
|
+
retry = setTimeout(() => { void connect(); }, delay);
|
|
343
|
+
delay = Math.min(delay * 2, 30_000);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
void connect();
|
|
347
|
+
return { addEventListener: events.addEventListener.bind(events),
|
|
348
|
+
close() { abort.abort(); clearTimeout(retry); } };
|
|
349
|
+
}
|
|
350
|
+
async function* streamChunks(body) {
|
|
351
|
+
const reader = body.getReader();
|
|
352
|
+
try {
|
|
353
|
+
for (;;) {
|
|
354
|
+
const next = await reader.read();
|
|
355
|
+
if (next.done) {
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
yield next.value;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
finally {
|
|
362
|
+
await reader.cancel().catch(() => undefined);
|
|
363
|
+
reader.releaseLock();
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
/** Transport bounds differ from executor output truncation: keep the envelope valid JSON. */
|
|
367
|
+
function boundedFrontendResponse({ invocationId, body, maxBytes }) {
|
|
368
|
+
const payload = JSON.stringify({ invocationId, ...body });
|
|
369
|
+
if (maxBytes === undefined || new TextEncoder().encode(payload).length <= maxBytes)
|
|
370
|
+
return { payload, refused: false };
|
|
371
|
+
return { payload: JSON.stringify({ invocationId, ok: false, message: 'Frontend result too large; narrow the query.' }), refused: true };
|
|
372
|
+
}
|
|
373
|
+
async function assertFrontendResponse({ response, invocationId, body, scoped, refused }) {
|
|
374
|
+
if (!response.ok)
|
|
375
|
+
throw new Error(`answering "${invocationId}" failed: ${response.status}`);
|
|
376
|
+
if (refused)
|
|
377
|
+
throw new Error('Frontend result too large; narrow the query.');
|
|
378
|
+
if ('phase' in body || scoped) {
|
|
379
|
+
const result = await response.json();
|
|
380
|
+
if (!result.settled)
|
|
381
|
+
throw new Error('Page invocation expired or was cancelled; no action was taken');
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
//# sourceMappingURL=frontend-session-bridge.js.map
|
|
@@ -15,15 +15,10 @@ export interface BrowserSessionStore {
|
|
|
15
15
|
state: PersistedEmbedState;
|
|
16
16
|
}): void;
|
|
17
17
|
clear(args: Record<string, never>): void;
|
|
18
|
-
enqueue(args: {
|
|
19
|
-
action: unknown;
|
|
20
|
-
}): void;
|
|
21
|
-
drain(args: Record<string, never>): unknown | null;
|
|
22
18
|
}
|
|
23
19
|
export interface BrowserSessionStoreArgs {
|
|
24
20
|
readonly storage: SessionStoragePort;
|
|
25
21
|
readonly transcriptKey: string;
|
|
26
|
-
readonly actionKey: string;
|
|
27
22
|
readonly maxMessages: number;
|
|
28
23
|
readonly maxBytes: number;
|
|
29
24
|
readonly validateMessage: (args: {
|
|
@@ -31,14 +26,13 @@ export interface BrowserSessionStoreArgs {
|
|
|
31
26
|
}) => boolean;
|
|
32
27
|
}
|
|
33
28
|
/**
|
|
34
|
-
* Creates bounded, fail-soft transcript storage
|
|
35
|
-
* Corrupt transcripts are cleared as a whole.
|
|
36
|
-
* and a failed delete prevents delivery. Serialization/storage failures never escape.
|
|
29
|
+
* Creates bounded, fail-soft transcript storage.
|
|
30
|
+
* Corrupt transcripts are cleared as a whole. Serialization/storage failures never escape.
|
|
37
31
|
* Reject oversized stored envelopes before parsing, validate the whole message batch, then trim
|
|
38
32
|
* oldest messages first. Circular serialization is fail-soft. Keys, limits, validator and Storage
|
|
39
33
|
* are injected so separate controllers never accidentally share a product-selected namespace.
|
|
40
34
|
* @complexity Load O(bytes + messages); save O(messages * serialized bytes) in the
|
|
41
|
-
* worst trimming case
|
|
35
|
+
* worst trimming case. State is instance-local.
|
|
42
36
|
*/
|
|
43
37
|
export declare function createBrowserSessionStore(args: BrowserSessionStoreArgs): BrowserSessionStore;
|
|
44
38
|
//# sourceMappingURL=session-store.d.ts.map
|
|
@@ -1,17 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Creates bounded, fail-soft transcript storage
|
|
3
|
-
* Corrupt transcripts are cleared as a whole.
|
|
4
|
-
* and a failed delete prevents delivery. Serialization/storage failures never escape.
|
|
2
|
+
* Creates bounded, fail-soft transcript storage.
|
|
3
|
+
* Corrupt transcripts are cleared as a whole. Serialization/storage failures never escape.
|
|
5
4
|
* Reject oversized stored envelopes before parsing, validate the whole message batch, then trim
|
|
6
5
|
* oldest messages first. Circular serialization is fail-soft. Keys, limits, validator and Storage
|
|
7
6
|
* are injected so separate controllers never accidentally share a product-selected namespace.
|
|
8
7
|
* @complexity Load O(bytes + messages); save O(messages * serialized bytes) in the
|
|
9
|
-
* worst trimming case
|
|
8
|
+
* worst trimming case. State is instance-local.
|
|
10
9
|
*/
|
|
11
10
|
export function createBrowserSessionStore(args) {
|
|
12
|
-
const { storage, transcriptKey,
|
|
13
|
-
if (!transcriptKey
|
|
14
|
-
throw new Error('Transcript
|
|
11
|
+
const { storage, transcriptKey, maxMessages, maxBytes, validateMessage } = args;
|
|
12
|
+
if (!transcriptKey) {
|
|
13
|
+
throw new Error('Transcript key must be nonempty');
|
|
15
14
|
}
|
|
16
15
|
if (!Number.isSafeInteger(maxMessages) || maxMessages < 0)
|
|
17
16
|
throw new Error('Invalid message limit');
|
|
@@ -57,37 +56,6 @@ export function createBrowserSessionStore(args) {
|
|
|
57
56
|
catch { /* The live conversation continues even when serialization or storage fails. */ }
|
|
58
57
|
},
|
|
59
58
|
clear,
|
|
60
|
-
enqueue({ action }) {
|
|
61
|
-
try {
|
|
62
|
-
const serialized = JSON.stringify(action);
|
|
63
|
-
if (serialized !== undefined)
|
|
64
|
-
storage.setItem(actionKey, serialized);
|
|
65
|
-
}
|
|
66
|
-
catch { /* The live page continues without a queued action. */ }
|
|
67
|
-
},
|
|
68
|
-
drain(_args) {
|
|
69
|
-
let raw;
|
|
70
|
-
try {
|
|
71
|
-
raw = storage.getItem(actionKey);
|
|
72
|
-
}
|
|
73
|
-
catch {
|
|
74
|
-
return null;
|
|
75
|
-
}
|
|
76
|
-
if (raw === null)
|
|
77
|
-
return null;
|
|
78
|
-
try {
|
|
79
|
-
storage.removeItem(actionKey);
|
|
80
|
-
}
|
|
81
|
-
catch {
|
|
82
|
-
return null;
|
|
83
|
-
}
|
|
84
|
-
try {
|
|
85
|
-
return JSON.parse(raw);
|
|
86
|
-
}
|
|
87
|
-
catch {
|
|
88
|
-
return null;
|
|
89
|
-
}
|
|
90
|
-
},
|
|
91
59
|
};
|
|
92
60
|
}
|
|
93
61
|
const utf8Bytes = (value) => new TextEncoder().encode(value).length;
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import type { ChatTransport } from '../../core/transport.js';
|
|
2
2
|
import type { ChatPaneAgent } from '../../react/chat-pane.js';
|
|
3
3
|
import type { BrowserSessionStore } from '../browser/session-store.js';
|
|
4
|
-
import type { PageActionPort } from '../../core/browser/page-actions.js';
|
|
5
4
|
export { useEmbedChatDialog } from './dialog.hooks.js';
|
|
6
5
|
import type { EmbedHeaderCopy, EscapeKeyPort } from './header.js';
|
|
7
6
|
export { EmbedChatHeader } from './header.js';
|
|
@@ -10,18 +9,12 @@ export interface EmbedChatCopy extends EmbedHeaderCopy {
|
|
|
10
9
|
readonly title: string;
|
|
11
10
|
readonly fabLabel: string;
|
|
12
11
|
readonly placeholder: string;
|
|
13
|
-
readonly proposalLabel: (args: {
|
|
14
|
-
title: string;
|
|
15
|
-
}) => string;
|
|
16
|
-
readonly proposalGo: string;
|
|
17
12
|
}
|
|
18
13
|
export interface EmbedChatWidgetArgs {
|
|
19
14
|
readonly agent: ChatPaneAgent;
|
|
20
15
|
readonly copy: EmbedChatCopy;
|
|
21
16
|
readonly transport: ChatTransport;
|
|
22
17
|
readonly session: BrowserSessionStore;
|
|
23
|
-
readonly pageActions: PageActionPort;
|
|
24
|
-
readonly directiveEventName: string;
|
|
25
18
|
readonly keyboard: EscapeKeyPort;
|
|
26
19
|
/** Schedules after host layout; returns cancellation. No browser global is captured. */
|
|
27
20
|
readonly scheduleFrame: (args: {
|
|
@@ -29,10 +22,10 @@ export interface EmbedChatWidgetArgs {
|
|
|
29
22
|
}) => () => void;
|
|
30
23
|
}
|
|
31
24
|
/**
|
|
32
|
-
* Wires the existing pane/fab to per-instance transcript and
|
|
25
|
+
* Wires the existing pane/fab to per-instance transcript and transport ports.
|
|
33
26
|
* Keep effect ports stable for the lifetime of a mounted widget; remount for a new
|
|
34
|
-
* session/agent.
|
|
35
|
-
*
|
|
27
|
+
* session/agent. Page control lives on the shared frontend bridge, so transcript rehydration
|
|
28
|
+
* cannot replay effects. Reset remounts the pane after confirmation.
|
|
36
29
|
* @complexity O(messages + latest reply events) per transcript update; O(message IDs) retained.
|
|
37
30
|
*/
|
|
38
31
|
export declare function EmbedChatWidget(args: EmbedChatWidgetArgs): import("react").JSX.Element;
|
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
import { useCallback, useEffect,
|
|
2
|
+
import { useCallback, useEffect, useState } from 'react';
|
|
3
3
|
import { createRoot } from 'react-dom/client';
|
|
4
|
-
import { isTerminalRunStatus } from '../../core/messages.js';
|
|
5
4
|
import { ChatPane } from '../../react/chat-pane.js';
|
|
6
5
|
import { ChatFab } from '../../react/components/ChatFab.js';
|
|
7
6
|
import { JiniChatProvider } from '../../react/components/JiniChatProvider.js';
|
|
8
|
-
import { extractPageActions, splitPageActions, isQueuedPageAction } from '../../core/browser/page-actions.js';
|
|
9
7
|
import { EmbedChatHeader } from './header.js';
|
|
10
8
|
import { useEmbedChatSurface } from './dialog.hooks.js';
|
|
11
9
|
export { useEmbedChatDialog } from './dialog.hooks.js';
|
|
@@ -14,71 +12,29 @@ const shellStyles = `
|
|
|
14
12
|
.jini-chat-embed__panel { position:fixed; right:var(--jini-embed-right,24px); bottom:var(--jini-embed-bottom,88px); width:min(var(--jini-embed-width,440px),calc(100vw - 32px)); height:min(var(--jini-embed-height,620px),calc(100dvh - 120px)); z-index:var(--jini-embed-z-index,1000); display:flex; flex-direction:column; }
|
|
15
13
|
.jini-chat-embed__panel[hidden] { display:none; }
|
|
16
14
|
.jini-chat-embed__panel > .jini-chat-pane { flex:1; min-height:0; }
|
|
17
|
-
.jini-chat-embed__reset-confirm
|
|
18
|
-
.jini-chat-embed__proposal { padding:12px; background:var(--jini-embed-proposal-background,Canvas); color:var(--jini-embed-proposal-color,CanvasText); }
|
|
15
|
+
.jini-chat-embed__reset-confirm { display:flex; align-items:center; gap:8px; }
|
|
19
16
|
`;
|
|
20
17
|
/**
|
|
21
|
-
* Wires the existing pane/fab to per-instance transcript and
|
|
18
|
+
* Wires the existing pane/fab to per-instance transcript and transport ports.
|
|
22
19
|
* Keep effect ports stable for the lifetime of a mounted widget; remount for a new
|
|
23
|
-
* session/agent.
|
|
24
|
-
*
|
|
20
|
+
* session/agent. Page control lives on the shared frontend bridge, so transcript rehydration
|
|
21
|
+
* cannot replay effects. Reset remounts the pane after confirmation.
|
|
25
22
|
* @complexity O(messages + latest reply events) per transcript update; O(message IDs) retained.
|
|
26
23
|
*/
|
|
27
24
|
export function EmbedChatWidget(args) {
|
|
28
|
-
const { agent, copy, transport, session,
|
|
25
|
+
const { agent, copy, transport, session, keyboard } = args;
|
|
29
26
|
const [initial] = useState(() => session.load({}));
|
|
30
27
|
const [paneKey, setPaneKey] = useState(0);
|
|
31
28
|
const { open, toggle, panelRef, launcherRef, panelId } = useEmbedChatSurface({ initialOpen: initial.open }, { resetKey: paneKey });
|
|
32
29
|
const [messages, setMessages] = useState(initial.messages);
|
|
33
|
-
const [pending, setPending] = useState(null);
|
|
34
|
-
const processed = useRef(new Set(initial.messages.map(message => message.id)));
|
|
35
30
|
useEffect(() => { session.save({ state: { open, messages } }); }, [session, open, messages]);
|
|
36
|
-
useEffect(() => {
|
|
37
|
-
const queued = { value: session.drain({}) };
|
|
38
|
-
if (!isQueuedPageAction(queued) || queued.value.type === 'navigate')
|
|
39
|
-
return undefined;
|
|
40
|
-
const action = queued.value;
|
|
41
|
-
return scheduleFrame({ callback: () => { pageActions.execute({ action }); } });
|
|
42
|
-
}, [session, pageActions, scheduleFrame]);
|
|
43
|
-
useEffect(() => () => pageActions.clearHighlight({}), [pageActions]);
|
|
44
31
|
const reset = useCallback(() => {
|
|
45
32
|
session.clear({});
|
|
46
33
|
setMessages([]);
|
|
47
34
|
setPaneKey(key => key + 1);
|
|
48
|
-
setPending(null);
|
|
49
|
-
processed.current.clear();
|
|
50
35
|
}, [session]);
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
return;
|
|
54
|
-
if (proposal.bundled && pageActions.allows({ action: proposal.bundled }))
|
|
55
|
-
session.enqueue({ action: proposal.bundled });
|
|
56
|
-
// Both writes must finish before the host navigation can tear down this page.
|
|
57
|
-
session.save({ state: { open, messages: transcript } });
|
|
58
|
-
pageActions.navigate({ action: proposal.navigate });
|
|
59
|
-
}, [session, pageActions, open]);
|
|
60
|
-
const onMessagesChange = useCallback((next) => {
|
|
61
|
-
setMessages(next);
|
|
62
|
-
const latest = next.at(-1);
|
|
63
|
-
if (!latest || latest.role !== 'assistant' || !isTerminalRunStatus({ status: latest.runStatus }) || processed.current.has(latest.id))
|
|
64
|
-
return;
|
|
65
|
-
processed.current.add(latest.id);
|
|
66
|
-
setPending(null);
|
|
67
|
-
const actions = extractPageActions({ events: latest.events, directiveEventName })
|
|
68
|
-
.filter(action => pageActions.allows({ action }));
|
|
69
|
-
const { navigate, other } = splitPageActions({ actions });
|
|
70
|
-
if (!navigate) {
|
|
71
|
-
if (other)
|
|
72
|
-
pageActions.execute({ action: other });
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
const proposal = { navigate, bundled: other };
|
|
76
|
-
if (navigate.auto)
|
|
77
|
-
go(proposal, next);
|
|
78
|
-
else
|
|
79
|
-
setPending(proposal);
|
|
80
|
-
}, [directiveEventName, pageActions, go]);
|
|
81
|
-
return _jsxs("div", { className: "jini-chat-embed", children: [_jsx("style", { children: shellStyles }), _jsx("div", { ref: launcherRef, tabIndex: -1, children: _jsx(ChatFab, { open: open, onToggle: toggle, "aria-label": copy.fabLabel, label: copy.fabLabel, "aria-controls": panelId, "aria-haspopup": "dialog" }) }), _jsx(JiniChatProvider, { transport: transport, children: _jsxs("div", { id: panelId, className: "jini-chat-embed__panel", hidden: !open, ref: panelRef, role: "dialog", "aria-modal": "true", "aria-label": copy.title, children: [_jsx(ChatPane, { transport: transport, agents: [agent], initialSelection: { agentId: agent.id }, initialMessages: messages, title: copy.title, placeholder: copy.placeholder, variant: "embed", header: _jsx(EmbedChatHeader, { title: copy.title, hasMessages: messages.length > 0, onReset: reset, copy: copy, keyboard: keyboard }), onMessagesChange: onMessagesChange }, paneKey), pending ? _jsxs("div", { className: "jini-chat-embed__proposal", children: [_jsx("span", { children: copy.proposalLabel({ title: pending.navigate.target.title }) }), _jsx("button", { type: "button", onClick: () => { setPending(null); go(pending, messages); }, children: copy.proposalGo })] }) : null] }) })] });
|
|
36
|
+
const onMessagesChange = useCallback((next) => { setMessages(next); }, []);
|
|
37
|
+
return _jsxs("div", { className: "jini-chat-embed", children: [_jsx("style", { children: shellStyles }), _jsx("div", { ref: launcherRef, tabIndex: -1, children: _jsx(ChatFab, { open: open, onToggle: toggle, "aria-label": copy.fabLabel, label: copy.fabLabel, "aria-controls": panelId, "aria-haspopup": "dialog" }) }), _jsx(JiniChatProvider, { transport: transport, children: _jsx("div", { id: panelId, className: "jini-chat-embed__panel", hidden: !open, ref: panelRef, role: "dialog", "aria-modal": "true", "aria-label": copy.title, children: _jsx(ChatPane, { transport: transport, agents: [agent], initialSelection: { agentId: agent.id }, initialMessages: messages, title: copy.title, placeholder: copy.placeholder, variant: "embed", header: _jsx(EmbedChatHeader, { title: copy.title, hasMessages: messages.length > 0, onReset: reset, copy: copy, keyboard: keyboard }), onMessagesChange: onMessagesChange }, paneKey) }) })] });
|
|
82
38
|
}
|
|
83
39
|
/** Mounts into a host-provided node and returns lifecycle cleanup. O(1) plus React rendering. */
|
|
84
40
|
export function mountEmbedChat({ element, widget }) {
|
|
@@ -13,10 +13,6 @@ export interface VanillaChatCopy {
|
|
|
13
13
|
readonly confirm: string;
|
|
14
14
|
readonly confirmDraft?: string;
|
|
15
15
|
readonly keep: string;
|
|
16
|
-
readonly proposalGo: string;
|
|
17
|
-
readonly proposalLabel: (args: {
|
|
18
|
-
title: string;
|
|
19
|
-
}) => string;
|
|
20
16
|
readonly thinking: string;
|
|
21
17
|
readonly greeting?: string;
|
|
22
18
|
readonly suggestionsLabel?: string;
|
|
@@ -53,7 +49,6 @@ export declare function mountVanillaChat(args: MountVanillaChatArgs, options?: {
|
|
|
53
49
|
send({ text }: {
|
|
54
50
|
text: string;
|
|
55
51
|
}, _opts?: {}): Promise<boolean>;
|
|
56
|
-
acceptProposal(_input?: Record<string, never>, _opts?: {}): void;
|
|
57
52
|
cancel(_input?: Record<string, never>, _opts?: {}): void;
|
|
58
53
|
reset(_input?: Record<string, never>, _opts?: {}): void;
|
|
59
54
|
dispose(_input?: Record<string, never>, _opts?: {}): void;
|