@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.
Files changed (51) hide show
  1. package/README.md +6 -1
  2. package/dist/core/antigravity/tool-presentation.d.ts +13 -0
  3. package/dist/core/antigravity/tool-presentation.js +20 -0
  4. package/dist/core/assistant-client/ag-ui-transport.js +13 -1
  5. package/dist/core/events.d.ts +5 -1
  6. package/dist/core/tool-events.d.ts +18 -8
  7. package/dist/core/tool-events.js +72 -16
  8. package/dist/core/tool-presentation.d.ts +14 -0
  9. package/dist/core/tool-presentation.js +8 -0
  10. package/dist/core/user-text-redaction.d.ts +2 -1
  11. package/dist/core/user-text-redaction.js +10 -3
  12. package/dist/embed-widget/browser/frontend-session-bridge.d.ts +99 -0
  13. package/dist/embed-widget/browser/frontend-session-bridge.js +384 -0
  14. package/dist/embed-widget/browser/session-store.d.ts +3 -9
  15. package/dist/embed-widget/browser/session-store.js +6 -38
  16. package/dist/embed-widget/react/embed.d.ts +3 -10
  17. package/dist/embed-widget/react/embed.js +8 -52
  18. package/dist/embed-widget/vanilla/index.d.ts +0 -5
  19. package/dist/embed-widget/vanilla/index.js +4 -14
  20. package/dist/embed-widget/vanilla/state.d.ts +3 -11
  21. package/dist/embed-widget/vanilla/state.js +6 -37
  22. package/dist/embed-widget/vanilla/style.css +1 -1
  23. package/dist/react/agent-bridge/frontend-session-bridge.d.ts +2 -56
  24. package/dist/react/agent-bridge/frontend-session-bridge.js +2 -248
  25. package/dist/react/components/Icon.d.ts +1 -1
  26. package/dist/react/components/Icon.js +1 -0
  27. package/dist/react/components/Markdown.d.ts +1 -0
  28. package/dist/react/components/Markdown.js +1 -1
  29. package/dist/react/components/MessageList.d.ts +1 -1
  30. package/dist/react/components/MessageRow.d.ts +3 -0
  31. package/dist/react/components/MessageRow.js +10 -8
  32. package/dist/react/components/ToolCard.d.ts +3 -1
  33. package/dist/react/components/ToolCard.js +77 -58
  34. package/dist/react/components/ToolCard.rules.d.ts +20 -0
  35. package/dist/react/components/ToolCard.rules.js +92 -0
  36. package/dist/react/features/chat-pane/components/AgentRuntimePicker.js +18 -6
  37. package/dist/react/features/chat-pane/components/ChatPane.js +3 -3
  38. package/dist/react/features/chat-pane/hooks/useChatPane.hooks.d.ts +3 -1
  39. package/dist/react/features/chat-pane/hooks/useChatPane.hooks.js +9 -3
  40. package/dist/react/features/chat-pane/styles.d.ts +1 -1
  41. package/dist/react/features/chat-pane/styles.js +76 -9
  42. package/dist/react/features/chat-pane/types.d.ts +3 -0
  43. package/dist/react/hooks/useUserTextGuard.d.ts +1 -0
  44. package/dist/react/hooks/useUserTextGuard.js +3 -1
  45. package/dist/react/tool-call-display.d.ts +11 -0
  46. package/dist/react/tool-call-display.js +59 -2
  47. package/package.json +91 -86
  48. package/dist/core/browser/page-actions.d.ts +0 -121
  49. package/dist/core/browser/page-actions.js +0 -115
  50. package/dist/embed-widget/browser/page-actions.d.ts +0 -2
  51. package/dist/embed-widget/browser/page-actions.js +0 -3
@@ -1,7 +1,6 @@
1
1
  const ARIA_LABEL = 'aria-label';
2
2
  import { CHAT_BUBBLE_STYLE } from '../../contracts/chat-bubble-style.js';
3
3
  import { createVanillaChatController } from './state.js';
4
- import { isQueuedPageAction } from '../../core/browser/page-actions.js';
5
4
  export { createVanillaChatController } from './state.js';
6
5
  function svgIcon({ document, path }) {
7
6
  const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
@@ -75,9 +74,11 @@ export function mountVanillaChat(args, options = {}) {
75
74
  announcements.setAttribute('aria-atomic', 'false');
76
75
  const error = node('div', 'jini-chat-vanilla__error');
77
76
  error.setAttribute('role', 'alert');
78
- const proposal = node('div', 'jini-chat-vanilla__proposal');
77
+ const proposal = node('div', 'jini-chat-vanilla__tool-confirmation');
78
+ proposal.hidden = true;
79
+ proposal.setAttribute('data-agent-private', '');
79
80
  const proposalText = node('span', '');
80
- const go = button(copy.proposalGo);
81
+ const go = button('Allow');
81
82
  proposal.append(proposalText, go);
82
83
  const form = node('form', 'jini-chat-vanilla__composer');
83
84
  const input = node('textarea', 'jini-chat-vanilla__input');
@@ -122,8 +123,6 @@ export function mountVanillaChat(args, options = {}) {
122
123
  send.disabled = state.busy || !input.value.trim();
123
124
  input.disabled = state.busy;
124
125
  stop.hidden = !state.busy;
125
- proposal.hidden = state.proposal === null;
126
- proposalText.textContent = state.proposal ? copy.proposalLabel({ title: state.proposal.navigate.target.title }) : '';
127
126
  };
128
127
  const createRow = ({ message }) => {
129
128
  const row = { element: node('div', `jini-chat-vanilla__message jini-chat-vanilla__message--${message.role}`), content: '\0' };
@@ -256,7 +255,6 @@ export function mountVanillaChat(args, options = {}) {
256
255
  const dismissConfirmation = () => { confirmation.hidden = true; reset.focus(); };
257
256
  listen(keep, 'click', dismissConfirmation);
258
257
  listen(confirm, 'click', () => { confirmation.hidden = true; input.value = ''; controller.reset({}); input.focus(); });
259
- listen(go, 'click', () => controller.acceptProposal({}));
260
258
  listen(stop, 'click', () => controller.cancel({}));
261
259
  listen(form, 'submit', event => {
262
260
  event.preventDefault();
@@ -311,12 +309,6 @@ export function mountVanillaChat(args, options = {}) {
311
309
  controller.setOpen({ open: true });
312
310
  focusEntry({ busy: controller.getState({}).busy });
313
311
  });
314
- const queued = { value: args.session.drain({}) };
315
- let cancelFrame = () => { };
316
- if (isQueuedPageAction(queued) && queued.value.type !== 'navigate') {
317
- const action = queued.value;
318
- cancelFrame = args.scheduleFrame({ callback: () => { args.pageActions.execute({ action }); } });
319
- }
320
312
  controller.setOpen({ open: options.initialOpen ?? controller.getState({}).open });
321
313
  initialized = true;
322
314
  element.dataset.chatMounted = 'true';
@@ -325,11 +317,9 @@ export function mountVanillaChat(args, options = {}) {
325
317
  controller,
326
318
  unmount(_input = {}, _opts = {}) {
327
319
  listeners.forEach(dispose => dispose());
328
- cancelFrame();
329
320
  cancelRenderFrame();
330
321
  delete element.dataset.chatMounted;
331
322
  controller.dispose({});
332
- args.pageActions.clearHighlight({});
333
323
  shell.remove();
334
324
  },
335
325
  };
@@ -1,22 +1,15 @@
1
1
  import type { ChatMessage } from '../../core/messages.js';
2
2
  import type { ChatTransport } from '../../core/transport.js';
3
3
  import type { BrowserSessionStore } from '../browser/session-store.js';
4
- import type { PageActionPort, NavigateAction, NonNavigateAction } from '../../core/browser/page-actions.js';
5
4
  export interface VanillaChatState {
6
5
  readonly open: boolean;
7
6
  readonly messages: ChatMessage[];
8
7
  readonly busy: boolean;
9
8
  readonly error: string | null;
10
- readonly proposal: {
11
- navigate: NavigateAction;
12
- bundled: NonNavigateAction | null;
13
- } | null;
14
9
  }
15
10
  export interface VanillaChatControllerArgs {
16
11
  readonly transport: ChatTransport;
17
12
  readonly session: BrowserSessionStore;
18
- readonly pageActions: PageActionPort;
19
- readonly directiveEventName: string;
20
13
  readonly agentId: string;
21
14
  readonly ids: (args: Record<string, never>) => string;
22
15
  readonly createAbortController: (args: Record<string, never>) => AbortController;
@@ -25,9 +18,9 @@ export interface VanillaChatControllerArgs {
25
18
  }) => void;
26
19
  }
27
20
  /**
28
- * Framework-free visitor state over the existing transport/session/page-action owners.
29
- * Restored messages never replay directives. Only a successful live settlement can act;
30
- * persistence and queued effects finish synchronously before navigation tears down the page.
21
+ * Framework-free visitor state over the existing transport/session owners.
22
+ * Restored messages never replay effects; page control belongs to the shared frontend bridge.
23
+ * Terminal navigation flushes the transport snapshot before the host tears down the page.
31
24
  * Reset invalidates callbacks before aborting, preventing late chunks from reviving a thread.
32
25
  * @complexity O(retained transcript + reply events + reply characters) per update; storage writes
33
26
  * occur only on settle/open/reset/navigation, never per streamed chunk. Session bounds persisted bytes.
@@ -40,7 +33,6 @@ export declare function createVanillaChatController(args: VanillaChatControllerA
40
33
  send({ text }: {
41
34
  text: string;
42
35
  }, _opts?: {}): Promise<boolean>;
43
- acceptProposal(_input?: Record<string, never>, _opts?: {}): void;
44
36
  cancel(_input?: Record<string, never>, _opts?: {}): void;
45
37
  reset(_input?: Record<string, never>, _opts?: {}): void;
46
38
  dispose(_input?: Record<string, never>, _opts?: {}): void;
@@ -1,16 +1,15 @@
1
1
  import { assistantContentFromEvents } from '../../core/assistant-content.js';
2
- import { extractPageActions, splitPageActions } from '../../core/browser/page-actions.js';
3
2
  /**
4
- * Framework-free visitor state over the existing transport/session/page-action owners.
5
- * Restored messages never replay directives. Only a successful live settlement can act;
6
- * persistence and queued effects finish synchronously before navigation tears down the page.
3
+ * Framework-free visitor state over the existing transport/session owners.
4
+ * Restored messages never replay effects; page control belongs to the shared frontend bridge.
5
+ * Terminal navigation flushes the transport snapshot before the host tears down the page.
7
6
  * Reset invalidates callbacks before aborting, preventing late chunks from reviving a thread.
8
7
  * @complexity O(retained transcript + reply events + reply characters) per update; storage writes
9
8
  * occur only on settle/open/reset/navigation, never per streamed chunk. Session bounds persisted bytes.
10
9
  */
11
10
  export function createVanillaChatController(args, _options = {}) {
12
11
  const initial = args.session.load({});
13
- let state = { ...initial, busy: false, error: null, proposal: null };
12
+ let state = { ...initial, busy: false, error: null };
14
13
  let generation = 0;
15
14
  let active = null;
16
15
  const publish = ({ persist = true } = {}) => {
@@ -18,32 +17,6 @@ export function createVanillaChatController(args, _options = {}) {
18
17
  args.session.save({ state: { open: state.open, messages: state.messages } });
19
18
  args.onChange({ state });
20
19
  };
21
- const go = (proposal) => {
22
- if (!args.pageActions.allows({ action: proposal.navigate }))
23
- return;
24
- if (proposal.bundled && args.pageActions.allows({ action: proposal.bundled }))
25
- args.session.enqueue({ action: proposal.bundled });
26
- state = { ...state, proposal: null };
27
- publish();
28
- args.pageActions.navigate({ action: proposal.navigate });
29
- };
30
- const settleActions = (events) => {
31
- const actions = extractPageActions({ events, directiveEventName: args.directiveEventName })
32
- .filter(action => args.pageActions.allows({ action }));
33
- const { navigate, other } = splitPageActions({ actions });
34
- if (!navigate) {
35
- if (other)
36
- args.pageActions.execute({ action: other });
37
- return;
38
- }
39
- const proposal = { navigate, bundled: other };
40
- if (navigate.auto)
41
- go(proposal);
42
- else {
43
- state = { ...state, proposal };
44
- publish();
45
- }
46
- };
47
20
  return {
48
21
  getState(_input = {}, _opts = {}) { return state; },
49
22
  setOpen({ open }, _opts = {}) { state = { ...state, open }; publish(); },
@@ -57,7 +30,7 @@ export function createVanillaChatController(args, _options = {}) {
57
30
  active = abort;
58
31
  const history = [...state.messages, { id: args.ids({}), role: 'user', content }];
59
32
  const reply = { id: args.ids({}), role: 'assistant', content: '', events: [], runStatus: 'running' };
60
- state = { ...state, messages: [...history, reply], busy: true, error: null, proposal: null };
33
+ state = { ...state, messages: [...history, reply], busy: true, error: null };
61
34
  publish({ persist: false });
62
35
  let events = [];
63
36
  let failed = false;
@@ -84,8 +57,6 @@ export function createVanillaChatController(args, _options = {}) {
84
57
  const completedStatus = abort.signal.aborted ? 'canceled' : 'succeeded';
85
58
  updateReply({ ...reply, content: assistantContentFromEvents({ events }), events: [...events],
86
59
  runStatus: failed ? 'failed' : completedStatus }, { persist: true });
87
- if (!failed && !abort.signal.aborted)
88
- settleActions(events);
89
60
  };
90
61
  try {
91
62
  await args.transport.startRun({ history, agentId: args.agentId, assistantMessageId: reply.id, signal: abort.signal }, {
@@ -105,15 +76,13 @@ export function createVanillaChatController(args, _options = {}) {
105
76
  }
106
77
  return true;
107
78
  },
108
- acceptProposal(_input = {}, _opts = {}) { if (state.proposal)
109
- go(state.proposal); },
110
79
  cancel(_input = {}, _opts = {}) { active?.abort(); },
111
80
  reset(_input = {}, _opts = {}) {
112
81
  generation += 1;
113
82
  active?.abort();
114
83
  active = null;
115
84
  args.session.clear({});
116
- state = { open: state.open, messages: [], busy: false, error: null, proposal: null };
85
+ state = { open: state.open, messages: [], busy: false, error: null };
117
86
  publish();
118
87
  },
119
88
  dispose(_input = {}, _opts = {}) { generation += 1; active?.abort(); active = null; },
@@ -10,7 +10,7 @@
10
10
  .jini-chat-vanilla :focus-visible{outline:3px solid var(--jini-chat-accent,#2563eb);outline-offset:3px}
11
11
  .jini-chat-vanilla{font:14px/1.5 var(--font-body,system-ui,sans-serif);color:var(--jini-chat-text,var(--color-text,CanvasText))}
12
12
  .jini-chat-vanilla__panel{position:fixed;right:var(--jini-embed-right,24px);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;background:var(--jini-chat-background,var(--color-background,Canvas));border:1px solid var(--jini-chat-border,#767676);border-radius:16px;box-shadow:0 12px 48px #0003;overflow:hidden}
13
- .jini-chat-vanilla__header,.jini-chat-vanilla__composer,.jini-chat-vanilla__confirmation,.jini-chat-vanilla__proposal{display:flex;align-items:center;gap:8px;padding:12px;border-bottom:1px solid var(--jini-chat-border,#767676)}
13
+ .jini-chat-vanilla__header,.jini-chat-vanilla__composer,.jini-chat-vanilla__confirmation,.jini-chat-vanilla__tool-confirmation{display:flex;align-items:center;gap:8px;padding:12px;border-bottom:1px solid var(--jini-chat-border,#767676)}
14
14
  .jini-chat-vanilla__title{flex:1}
15
15
  .jini-chat-vanilla__button{font:inherit;color:inherit;background:transparent;border:1px solid var(--jini-chat-border,#767676);border-radius:8px;padding:6px 10px;cursor:pointer}
16
16
  .jini-chat-vanilla__button:disabled{opacity:.5;cursor:default}
@@ -1,57 +1,3 @@
1
- import { type PageDriver } from '@jini-ai/agentic';
2
- import type { ChatPaneAgentBridgeAccess, ChatPaneAgentToolAction } from '../features/chat-pane/types.js';
3
- export interface FrontendSessionBridgeOptions {
4
- /** Supplying one claims the six `page.*` verbs. Omit for a chat-only surface. */
5
- readonly pageDriver?: PageDriver;
6
- /**
7
- * Product capabilities, keyed by id prefix (`'cms.'`). Each claims every capability under it.
8
- * This is how a consumer exposes verbs the engine has never heard of.
9
- */
10
- readonly executors?: Readonly<Record<string, (capabilityId: string, input: Record<string, unknown>) => Promise<unknown>>>;
11
- /** Called for every invocation before it runs — the hook a product uses to show an activity trail. */
12
- readonly onInvocation?: (action: ChatPaneAgentToolAction) => void;
13
- /** Reported for failures that are nobody's tool call: stream errors, malformed frames. */
14
- readonly onError?: (error: unknown) => void;
15
- }
16
- /** The host supplies its origin and stream transport; native fetch defaults may be overridden. */
17
- export interface FrontendSessionBridgeArgs {
18
- /** Pass an empty string for the same-origin proxy used by a browser host. */
19
- readonly baseUrl: string;
20
- readonly openStream: (args: {
21
- url: string;
22
- }) => EventSource;
23
- readonly fetch?: typeof globalThis.fetch;
24
- readonly request?: (args: {
25
- url: string;
26
- init: RequestInit;
27
- timeoutMs: number;
28
- }) => Promise<Response>;
29
- }
30
- export interface FrontendSessionBridge {
31
- /** Hand this to `ChatPane`'s `agentControl.bridgeAccess`. */
32
- readonly bridgeAccess: ChatPaneAgentBridgeAccess;
33
- /**
34
- * Resolves the *first* time the daemon attaches this surface — an "is it live yet" signal.
35
- *
36
- * Its `bindToken` is only correct until the next reconnect, so do not stash it. Call
37
- * {@link FrontendSessionBridge.bindToken} when building a run request instead.
38
- */
39
- readonly ready: Promise<{
40
- sessionId: string;
41
- bindToken: string;
42
- }>;
43
- /**
44
- * The token for the attachment that is live *now*, or `undefined` before the first attach and
45
- * after {@link FrontendSessionBridge.close}. Read it at run-start; see the module doc.
46
- */
47
- bindToken(): string | undefined;
48
- close(): void;
49
- }
50
- /**
51
- * Opens the surface's connection and starts routing invocations.
52
- *
53
- * @param options - What this page can serve and where the daemon is.
54
- * @returns The pane's bridge, the attach result, and a teardown.
55
- */
56
- export declare function createFrontendSessionBridge({ baseUrl: base, openStream, request, fetch }: FrontendSessionBridgeArgs, options?: FrontendSessionBridgeOptions): FrontendSessionBridge;
1
+ /** Compatibility entry; the framework-free browser bridge owns the lifecycle. */
2
+ export * from '../../embed-widget/browser/frontend-session-bridge.js';
57
3
  //# sourceMappingURL=frontend-session-bridge.d.ts.map
@@ -1,249 +1,3 @@
1
- /**
2
- * @module agent-bridge/frontend-session-bridge
3
- *
4
- * The browser half of agent-driven frontend control: one SSE connection to the daemon, and the
5
- * routing that turns each relayed invocation into a call on something in this page.
6
- *
7
- * Everything on the server side already existed — `FrontendSessionRegistry` addresses a run to a
8
- * surface, the frontend-session routes carry invocations out and answers back, and
9
- * `createFrontendControl` assembles them. `ChatPaneAgentBridgeAccess` declared the contract this
10
- * satisfies and had **zero implementations**, which is why an agent could reach a tool and the
11
- * tool could reach nothing.
12
- *
13
- * Design notes worth knowing before changing this:
14
- *
15
- * - **The connection is owned here, not by `subscribe`.** `ChatPaneAgentBridgeAccess.subscribe` is
16
- * called by the chat pane's own effect, so tying the stream's lifetime to it would mean page
17
- * control dies when the pane unmounts — and the page is drivable whether or not a chat pane
18
- * exists. `subscribe` registers a listener; `close()` tears the connection down.
19
- * - **Capabilities are claimed from what is actually wired.** The claim sent at connect time is
20
- * derived from the presence of a `pageDriver` and the keys of `executors`, never from a static
21
- * list. A surface that claims what it cannot serve turns a fast, named refusal into a timeout.
22
- * - **An executed invocation is never executed twice.** If the stream drops between the daemon
23
- * delivering an invocation and this page POSTing the answer, the daemon correctly fails that
24
- * call — but the click already happened. Without the `executed` set below, the retry clicks
25
- * again. Buttons are not idempotent.
26
- * - **The bind token never leaves this module except to the host.** It arrives on the `attached`
27
- * event and must ride to run-start; it deliberately does not appear in any URL (see
28
- * `@jini-ai/daemon`'s `FrontendSessionHandle`).
29
- * - **Read the bind token at send time, not once.** `EventSource` reconnects on its own — after a
30
- * daemon restart, a sleeping laptop, or an ordinary network blip — and each reattach mints a new
31
- * session and a new token. A host that captured `ready`'s token keeps sending a dead one, every
32
- * later run fails to bind, and the only trace is a daemon-side log line: the agent is simply told
33
- * "no frontend is bound to this run". `ready` therefore answers "has it attached at least once";
34
- * {@link FrontendSessionBridge.bindToken} answers "what is valid now", and only the latter
35
- * belongs in a run request.
36
- */
37
- import { CHAT_CAPABILITIES } from '../../core/index.js';
38
- import { PAGE_CAPABILITIES, executePageCapability } from '@jini-ai/agentic';
39
- /** How many settled invocation ids to remember for replay suppression. */
40
- const EXECUTED_MEMORY = 256;
41
- /** Ids this surface can actually serve, given what the host wired up. */
42
- function claimedCapabilities(options) {
43
- const claims = CHAT_CAPABILITIES.map((capability) => capability.id);
44
- if (options.pageDriver !== undefined) {
45
- claims.push(...PAGE_CAPABILITIES.map((capability) => capability.id));
46
- }
47
- claims.push(...Object.keys(options.executors ?? {}));
48
- return claims;
49
- }
50
- function errorMessage(error) {
51
- return error instanceof Error ? error.message : String(error);
52
- }
53
- /** Parses a frame's data into an object, or says why it is not one. */
54
- function parseFrameObject(data) {
55
- let parsed;
56
- try {
57
- parsed = JSON.parse(data);
58
- }
59
- catch (error) {
60
- return { error };
61
- }
62
- // `JSON.parse` succeeds on any valid JSON value, not just objects — a bare `null`, number,
63
- // string or boolean parses cleanly and would throw *outside* this try/catch on the very next
64
- // `frame['type']` read (`null` is the one of those that actually throws; the others just read
65
- // back `undefined` harmlessly). Guarding here routes every one of those through the same
66
- // `onError` path as an unparseable frame, rather than only some of them crashing the listener.
67
- if (parsed === null || typeof parsed !== 'object') {
68
- return { error: new Error(`malformed frame: expected a JSON object, got ${JSON.stringify(parsed)}`) };
69
- }
70
- return { frame: parsed };
71
- }
72
- /** Reads an `invocation` frame into the pane's action shape, refusing one with no usable id. */
73
- function readInvocation(frame) {
74
- const rawInvocationId = frame['invocationId'];
75
- if (typeof rawInvocationId !== 'string' || rawInvocationId.length === 0) {
76
- return { kind: 'malformed', error: new Error('invocation frame missing invocationId') };
77
- }
78
- return {
79
- kind: 'invocation',
80
- action: {
81
- invocationId: rawInvocationId,
82
- capabilityId: String(frame['capabilityId']),
83
- input: (frame['input'] ?? {}),
84
- },
85
- };
86
- }
87
- /** Classifies one frame's raw data; the listener only applies the result. */
88
- function readFrame(data) {
89
- const parsed = parseFrameObject(data);
90
- if ('error' in parsed)
91
- return { kind: 'malformed', error: parsed.error };
92
- const { frame } = parsed;
93
- switch (frame['type']) {
94
- case 'attached':
95
- return { kind: 'attached', sessionId: String(frame['sessionId']), bindToken: String(frame['bindToken']) };
96
- case 'error':
97
- return { kind: 'refused', message: String(frame['message']) };
98
- case 'invocation':
99
- return readInvocation(frame);
100
- default:
101
- // Unknown frame types are ignored rather than treated as errors, so the daemon's event
102
- // vocabulary can grow without every deployed surface needing to ship first.
103
- return { kind: 'ignored' };
104
- }
105
- }
106
- /**
107
- * Opens the surface's connection and starts routing invocations.
108
- *
109
- * @param options - What this page can serve and where the daemon is.
110
- * @returns The pane's bridge, the attach result, and a teardown.
111
- */
112
- export function createFrontendSessionBridge({ baseUrl: base, openStream, request, fetch }, options = {}) {
113
- const capabilities = claimedCapabilities(options);
114
- // The only caller (`respond`) never passes its own signal, so the deadline is the whole signal.
115
- const send = request ?? (({ url, init, timeoutMs }) => (fetch ?? globalThis.fetch)(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }));
116
- let sessionId;
117
- /** Replaced on every reattach; a promise resolved once could never carry this. */
118
- let currentBindToken;
119
- // Definite assignment rather than no-op placeholders: a Promise executor runs synchronously, so
120
- // both are set before this line finishes, and placeholders would only add two functions that
121
- // can never be called.
122
- let resolveReady;
123
- let rejectReady;
124
- const ready = new Promise((resolve, reject) => {
125
- resolveReady = resolve;
126
- rejectReady = reject;
127
- });
128
- /** Chat-pane listeners. The pane registers exactly one; a second host could register another. */
129
- const chatListeners = new Set();
130
- /** Invocation ids already run here, so a stream reconnect cannot double-click a button. */
131
- const executed = new Set();
132
- const query = capabilities.map((id) => `capability=${encodeURIComponent(id)}`).join('&');
133
- const source = openStream({ url: `${base}/api/frontend-sessions/stream?${query}` });
134
- async function respond(invocationId, body) {
135
- if (sessionId === undefined)
136
- throw new Error('the surface is not attached yet');
137
- const response = await send({
138
- url: `${base}/api/frontend-sessions/${encodeURIComponent(sessionId)}/responses`,
139
- init: { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ invocationId, ...body }) },
140
- timeoutMs: 15_000,
141
- });
142
- if (!response.ok)
143
- throw new Error(`answering "${invocationId}" failed: ${response.status}`);
144
- }
145
- const respondSuccess = (invocationId, output) => respond(invocationId, { ok: true, output });
146
- const respondError = (invocationId, message) => respond(invocationId, { ok: false, message });
147
- /** Runs one non-chat invocation here and answers it. Chat ones go to the pane instead. */
148
- async function serveLocally(action) {
149
- let output;
150
- try {
151
- if (options.pageDriver !== undefined && action.capabilityId.startsWith('page.')) {
152
- output = await executePageCapability({ driver: options.pageDriver, capabilityId: action.capabilityId, input: action.input });
153
- }
154
- else {
155
- const entry = Object.entries(options.executors ?? {})
156
- .find(([prefix]) => action.capabilityId.startsWith(prefix));
157
- if (entry === undefined)
158
- throw new Error(`nothing on this page serves "${action.capabilityId}"`);
159
- output = await entry[1](action.capabilityId, action.input);
160
- }
161
- }
162
- catch (error) {
163
- await respondError(action.invocationId, errorMessage(error)).catch(options.onError ?? (() => undefined));
164
- return;
165
- }
166
- await respondSuccess(action.invocationId, output).catch(options.onError ?? (() => undefined));
167
- }
168
- function remember(invocationId) {
169
- executed.add(invocationId);
170
- if (executed.size > EXECUTED_MEMORY) {
171
- const oldest = executed.values().next().value;
172
- if (oldest !== undefined)
173
- executed.delete(oldest);
174
- }
175
- }
176
- /** Runs one well-formed invocation: replay check, announcement, then pane or local serving. */
177
- function handleInvocation(action) {
178
- // A redelivery after a dropped answer must not re-run the side effect.
179
- if (executed.has(action.invocationId)) {
180
- void respondError(action.invocationId, 'already executed on this surface').catch(() => undefined);
181
- return;
182
- }
183
- remember(action.invocationId);
184
- options.onInvocation?.(action);
185
- if (action.capabilityId.startsWith('chat.')) {
186
- for (const listener of chatListeners)
187
- listener(action);
188
- return;
189
- }
190
- void serveLocally(action);
191
- }
192
- source.addEventListener('message', (event) => {
193
- const frame = readFrame(event.data);
194
- switch (frame.kind) {
195
- case 'attached':
196
- sessionId = frame.sessionId;
197
- currentBindToken = frame.bindToken;
198
- // A no-op after the first attach — which is exactly why `currentBindToken` exists.
199
- resolveReady({ sessionId, bindToken: currentBindToken });
200
- return;
201
- case 'refused':
202
- rejectReady(new Error(frame.message));
203
- return;
204
- case 'malformed':
205
- options.onError?.(frame.error);
206
- return;
207
- case 'invocation':
208
- handleInvocation(frame.action);
209
- return;
210
- case 'ignored':
211
- return;
212
- }
213
- });
214
- source.addEventListener('error', (event) => {
215
- // The daemon deletes a session's bind token the instant that connection drops, so by the time
216
- // this fires the token in hand is already gone from the registry. Holding it until the next
217
- // `attached` frame leaves a window where `bindToken()` hands back something dead, and a run
218
- // started in that window fails to bind — reported to the agent only as "no frontend is bound
219
- // to this run", with the real reason (a reconnect it never saw) nowhere in view.
220
- // Reporting no token is the honest answer for a surface that is, right now, not attached.
221
- currentBindToken = undefined;
222
- sessionId = undefined;
223
- options.onError?.(event);
224
- });
225
- const bridgeAccess = {
226
- subscribe(onAction) {
227
- chatListeners.add(onAction);
228
- // Removes this listener only. The connection outlives any one pane — see the module doc.
229
- return () => chatListeners.delete(onAction);
230
- },
231
- respondSuccess,
232
- respondError,
233
- };
234
- return {
235
- bridgeAccess,
236
- ready,
237
- bindToken: () => currentBindToken,
238
- close() {
239
- source.close();
240
- chatListeners.clear();
241
- // A closed bridge serves nothing, so binding a run to it would strand that run rather than
242
- // fail it — this is what stops a torn-down surface (a StrictMode remount, a route change)
243
- // from handing its dead token to the next run.
244
- currentBindToken = undefined;
245
- sessionId = undefined;
246
- },
247
- };
248
- }
1
+ /** Compatibility entry; the framework-free browser bridge owns the lifecycle. */
2
+ export * from '../../embed-widget/browser/frontend-session-bridge.js';
249
3
  //# sourceMappingURL=frontend-session-bridge.js.map
@@ -7,7 +7,7 @@
7
7
  * AgentIcon and WorkingDirPicker.
8
8
  */
9
9
  import type { SVGProps } from 'react';
10
- export type IconName = 'spinner' | 'check' | 'close' | 'chevron-down' | 'chevron-left' | 'chevron-right' | 'attach' | 'file' | 'image' | 'x' | 'comment' | 'search' | 'plus' | 'pencil' | 'copy';
10
+ export type IconName = 'spinner' | 'check' | 'close' | 'chevron-down' | 'chevron-left' | 'chevron-right' | 'attach' | 'file' | 'image' | 'x' | 'comment' | 'search' | 'plus' | 'pencil' | 'copy' | 'retry';
11
11
  interface IconProps extends Omit<SVGProps<SVGSVGElement>, 'name'> {
12
12
  name: IconName;
13
13
  size?: number | string;
@@ -6,6 +6,7 @@ const ICON_GLYPHS = {
6
6
  check: _jsx("path", { d: "M20 6 9 17l-5-5" }),
7
7
  close: CROSS,
8
8
  x: CROSS,
9
+ retry: _jsxs(_Fragment, { children: [_jsx("path", { d: "M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" }), _jsx("path", { d: "M3 3v5h5" })] }),
9
10
  'chevron-down': _jsx("path", { d: "m6 9 6 6 6-6" }),
10
11
  /** Conversation-switcher trigger — a speech bubble reads as "chat history" without a label. */
11
12
  comment: (_jsx("path", { d: "M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" })),
@@ -2,4 +2,5 @@ export interface MarkdownProps {
2
2
  children: string;
3
3
  }
4
4
  export declare function Markdown({ children }: MarkdownProps): import("react").JSX.Element;
5
+ export declare const SAFE_LINK_HREF: RegExp;
5
6
  //# sourceMappingURL=Markdown.d.ts.map
@@ -415,7 +415,7 @@ const MD_LINK_PARTS = /^\[([^\]\n]+)\]\((.+)\)$/u;
415
415
  const INLINE_RE = new RegExp(String.raw `(\x60[^\x60]+\x60)|(${MD_LINK})|(\*\*[^*]+\*\*)|(\*[^*]+\*|${UNDERSCORE_EM})|(https?:\/\/[^\s)]+)`, 'gu');
416
416
  // Only these targets become anchors; anything else (`javascript:`, `data:`, protocol-relative
417
417
  // `//host`) stays literal text, since the text is untrusted model output.
418
- const SAFE_LINK_HREF = /^(?:https?:\/\/|mailto:|\/(?!\/)|#)/iu;
418
+ export const SAFE_LINK_HREF = /^(?:https?:\/\/|mailto:|\/(?!\/)|#)/iu;
419
419
  // Every link opens in a new tab — an in-app path too, so following one never navigates the tab the
420
420
  // chat lives in (owner 2026-10-08). Only a `#` same-document anchor stays in place. ChatPane's
421
421
  // click guard (`useChatPaneNewTabLinks`) covers links this renderer does not draw.
@@ -6,7 +6,7 @@ interface PendingPrompt {
6
6
  attachments?: ChatAttachment[];
7
7
  onCancel: () => void;
8
8
  }
9
- export interface MessageListProps extends Pick<MessageRowProps, 'projectFileNames' | 'onRequestOpenFile' | 'renderAttachment' | 'showUsageTotal' | 'showUsageLine' | 'toolCallDisplay' | 'showThinking'> {
9
+ export interface MessageListProps extends Pick<MessageRowProps, 'projectFileNames' | 'onRequestOpenFile' | 'renderAttachment' | 'showUsageTotal' | 'showUsageLine' | 'toolCallDisplay' | 'showThinking' | 'sendingLabel'> {
10
10
  messages: ChatMessage[];
11
11
  isStreaming?: boolean;
12
12
  /** Mirrors `useConversation().scrollIntent` — when `true`, this component scrolls to the bottom on mount/update. */
@@ -73,6 +73,9 @@ export interface MessageRowProps {
73
73
  runStreaming?: boolean;
74
74
  /** Whether the server has yet to accept this reply's run (its user turn is still pending). */
75
75
  runSending?: boolean;
76
+ /** Host-localized text shown verbatim only while this run is active and sending.
77
+ * Omit to use the translated `Sending…` label. */
78
+ sendingLabel?: string;
76
79
  runSucceeded?: boolean;
77
80
  /** Whether this message's question-form (if any) is still the active/answerable one. */
78
81
  questionFormInteractive?: boolean;