@proteos/component-sdk 0.88.0 → 0.89.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@proteos/component-sdk",
3
- "version": "0.88.0",
3
+ "version": "0.89.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Typed runtime hooks for authoring Proteos custom components — the SDK you import inside a component bundle.",
6
6
  "repository": {
@@ -42,7 +42,7 @@
42
42
  "src"
43
43
  ],
44
44
  "dependencies": {
45
- "@proteos/sdk": "^0.88.0"
45
+ "@proteos/sdk": "^0.89.0"
46
46
  },
47
47
  "peerDependencies": {
48
48
  "@tanstack/react-query": ">=5.0.0",
@@ -60,8 +60,8 @@
60
60
  "tsup": "^8.3.0",
61
61
  "typescript": "^6.0.3",
62
62
  "vitest": "^3.2.4",
63
- "@proteos/biome-config": "0.0.0",
64
- "@proteos/tsconfig": "0.0.0"
63
+ "@proteos/tsconfig": "0.0.0",
64
+ "@proteos/biome-config": "0.0.0"
65
65
  },
66
66
  "scripts": {
67
67
  "build": "tsup",
@@ -1,9 +1,10 @@
1
- import { renderHook } from '@testing-library/react'
1
+ import { act, renderHook } from '@testing-library/react'
2
2
  import type { ReactNode } from 'react'
3
3
  import { afterEach, describe, expect, it, vi } from 'vitest'
4
4
 
5
5
  import { RuntimeProvider, type RuntimeValue } from './context'
6
6
  import {
7
+ useAgentTools,
7
8
  useAgentWindow,
8
9
  useApiBaseUrl,
9
10
  useComponentModal,
@@ -354,6 +355,110 @@ describe('runtime hooks', () => {
354
355
  )
355
356
  })
356
357
 
358
+ it('useAgentTools posts its tools and state, answers calls with the latest handler, and withdraws on unmount', async () => {
359
+ const post = vi.spyOn(window.parent, 'postMessage').mockImplementation(() => {})
360
+ const posted = () =>
361
+ post.mock.calls.map(([payload]) => payload as Record<string, unknown> & { type: string })
362
+ const host = (data: unknown) =>
363
+ act(async () => {
364
+ window.dispatchEvent(new MessageEvent('message', { data }))
365
+ // Let the handler's promise settle and its reply post.
366
+ await new Promise((resolve) => setTimeout(resolve, 0))
367
+ })
368
+ const { rerender, unmount } = renderHook(
369
+ ({ drafts }: { drafts: number }) =>
370
+ useAgentTools({
371
+ label: 'Cluster canvas',
372
+ state: { drafts },
373
+ tools: [
374
+ {
375
+ name: 'preview_clusters',
376
+ description: 'Draft clusters',
377
+ inputSchema: { type: 'object' },
378
+ run: (input: { count: number }) => ({ drafted: input.count, drafts }),
379
+ },
380
+ {
381
+ name: 'confirm_drafts',
382
+ description: 'Confirm',
383
+ run: () => {
384
+ throw new Error('Nothing to confirm')
385
+ },
386
+ },
387
+ ],
388
+ }),
389
+ { wrapper: wrapper(makeValue()), initialProps: { drafts: 0 } },
390
+ )
391
+ expect(posted()).toEqual([
392
+ {
393
+ source: MESSAGE_SOURCE,
394
+ type: 'AGENT_TOOLS',
395
+ label: 'Cluster canvas',
396
+ state: { drafts: 0 },
397
+ tools: [
398
+ {
399
+ name: 'preview_clusters',
400
+ description: 'Draft clusters',
401
+ inputSchema: { type: 'object' },
402
+ },
403
+ { name: 'confirm_drafts', description: 'Confirm' },
404
+ ],
405
+ },
406
+ ])
407
+ // A re-render with the same state posts nothing; a state change re-posts.
408
+ rerender({ drafts: 0 })
409
+ expect(posted()).toHaveLength(1)
410
+ rerender({ drafts: 2 })
411
+ expect(posted()).toHaveLength(2)
412
+ expect(posted()[1]).toMatchObject({ type: 'AGENT_TOOLS', state: { drafts: 2 } })
413
+
414
+ await host({
415
+ source: MESSAGE_SOURCE,
416
+ type: 'AGENT_TOOL_CALL',
417
+ requestId: 'r1',
418
+ tool: 'preview_clusters',
419
+ input: { count: 3 },
420
+ })
421
+ await host({
422
+ source: MESSAGE_SOURCE,
423
+ type: 'AGENT_TOOL_CALL',
424
+ requestId: 'r2',
425
+ tool: 'confirm_drafts',
426
+ input: {},
427
+ })
428
+ await host({
429
+ source: MESSAGE_SOURCE,
430
+ type: 'AGENT_TOOL_CALL',
431
+ requestId: 'r3',
432
+ tool: 'nope',
433
+ input: {},
434
+ })
435
+ const results = posted().filter((payload) => payload.type === 'AGENT_TOOL_RESULT')
436
+ expect(results).toEqual([
437
+ // The handler of the latest render: it sees drafts = 2.
438
+ {
439
+ source: MESSAGE_SOURCE,
440
+ type: 'AGENT_TOOL_RESULT',
441
+ requestId: 'r1',
442
+ output: { drafted: 3, drafts: 2 },
443
+ },
444
+ {
445
+ source: MESSAGE_SOURCE,
446
+ type: 'AGENT_TOOL_RESULT',
447
+ requestId: 'r2',
448
+ error: 'Nothing to confirm',
449
+ },
450
+ {
451
+ source: MESSAGE_SOURCE,
452
+ type: 'AGENT_TOOL_RESULT',
453
+ requestId: 'r3',
454
+ error: 'This component has no tool nope',
455
+ },
456
+ ])
457
+
458
+ unmount()
459
+ expect(posted().at(-1)).toEqual({ source: MESSAGE_SOURCE, type: 'AGENT_TOOLS', tools: [] })
460
+ })
461
+
357
462
  it('throws a clear error when used outside the runtime', () => {
358
463
  // Silence the expected React error-boundary console noise.
359
464
  vi.spyOn(console, 'error').mockImplementation(() => {})
package/src/hooks.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { PageAction } from '@proteos/sdk'
2
- import { useCallback, useContext, useEffect, useMemo, useState } from 'react'
2
+ import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
3
3
 
4
4
  import {
5
5
  type AgentWindowController,
@@ -12,12 +12,17 @@ import {
12
12
  RuntimeContext,
13
13
  type RuntimeContextValue,
14
14
  } from './context'
15
- import type {
16
- KnowledgeEditorModalResult,
17
- PageActionContext,
18
- PageActionOutcome,
19
- PageContext,
20
- RecordDraftReviewOutcome,
15
+ import {
16
+ type AgentToolResultMessage,
17
+ type AgentToolsMessage,
18
+ type Envelope,
19
+ isHostMessage,
20
+ type KnowledgeEditorModalResult,
21
+ MESSAGE_SOURCE,
22
+ type PageActionContext,
23
+ type PageActionOutcome,
24
+ type PageContext,
25
+ type RecordDraftReviewOutcome,
21
26
  } from './protocol'
22
27
 
23
28
  /**
@@ -378,3 +383,118 @@ export function useFillViewportHeight(options: FillViewportOptions = {}): number
378
383
 
379
384
  return height
380
385
  }
386
+
387
+ /** A tool a component offers the workspace agent. */
388
+ export interface AgentTool<Input = unknown> {
389
+ /** Unique within the component, snake_case, e.g. `preview_clusters`. */
390
+ name: string
391
+ /** What the tool does and when to use it — the agent reads only this. */
392
+ description: string
393
+ /** JSON Schema of the input object. */
394
+ inputSchema?: Record<string, unknown>
395
+ /** Changes nothing (reads what the component shows). */
396
+ readOnly?: boolean
397
+ /** Runs when the agent calls the tool. The returned value (JSON-like) is
398
+ * the tool's result; a thrown error is reported to the agent. */
399
+ run: (input: Input) => unknown
400
+ }
401
+
402
+ export interface UseAgentToolsOptions {
403
+ /** How the agent sees this component in describe_tab. */
404
+ label?: string
405
+ /** A compact, JSON-like snapshot of what the component shows — what the
406
+ * agent reads in describe_tab. Re-posted whenever it changes. */
407
+ state?: unknown
408
+ // biome-ignore lint/suspicious/noExplicitAny: each tool types its own input
409
+ tools: AgentTool<any>[]
410
+ }
411
+
412
+ /**
413
+ * Offer tools and a state snapshot to the workspace agent. On a page open in
414
+ * the Ava workspace, the agent finds this component in `describe_tab` (its
415
+ * tools, their input schemas and `state`) and calls a tool with
416
+ * `component_call {target, tool, input}`. Elsewhere it is a no-op: the host
417
+ * ignores the registration.
418
+ *
419
+ * Call it once per component. Handlers may close over render values; the
420
+ * latest ones run. Agent tools only change what the component shows: write
421
+ * through the platform (actions, records) so the server stays the source of
422
+ * truth, and the turn-end refresh brings the component up to date.
423
+ *
424
+ * ```tsx
425
+ * useAgentTools({
426
+ * label: 'Cluster canvas',
427
+ * state: { clusters, drafts },
428
+ * tools: [{ name: 'preview_clusters', description: '…', inputSchema, run: (input) => preview(input) }],
429
+ * })
430
+ * ```
431
+ */
432
+ export function useAgentTools(options: UseAgentToolsOptions): void {
433
+ const latest = useRef(options)
434
+ latest.current = options
435
+
436
+ // What rides the wire: posted whenever it changes, withdrawn on unmount.
437
+ const wire = JSON.stringify({
438
+ label: options.label,
439
+ state: options.state,
440
+ tools: options.tools.map(({ name, description, inputSchema, readOnly }) => ({
441
+ name,
442
+ description,
443
+ ...(inputSchema ? { inputSchema } : {}),
444
+ ...(readOnly ? { readOnly: true } : {}),
445
+ })),
446
+ })
447
+ useEffect(() => {
448
+ const { label, state, tools } = JSON.parse(wire) as Omit<AgentToolsMessage, 'type'>
449
+ const envelope: Envelope<AgentToolsMessage> = {
450
+ source: MESSAGE_SOURCE,
451
+ type: 'AGENT_TOOLS',
452
+ tools,
453
+ ...(label !== undefined ? { label } : {}),
454
+ ...(state !== undefined ? { state } : {}),
455
+ }
456
+ window.parent?.postMessage(envelope, '*')
457
+ }, [wire])
458
+ useEffect(
459
+ () => () => {
460
+ const envelope: Envelope<AgentToolsMessage> = {
461
+ source: MESSAGE_SOURCE,
462
+ type: 'AGENT_TOOLS',
463
+ tools: [],
464
+ }
465
+ window.parent?.postMessage(envelope, '*')
466
+ },
467
+ [],
468
+ )
469
+
470
+ useEffect(() => {
471
+ function onMessage(event: MessageEvent) {
472
+ const data: unknown = event.data
473
+ if (!isHostMessage(data) || data.type !== 'AGENT_TOOL_CALL') return
474
+ const { requestId, tool, input } = data
475
+ const reply = (result: { output?: unknown; error?: string }) => {
476
+ const envelope: Envelope<AgentToolResultMessage> = {
477
+ source: MESSAGE_SOURCE,
478
+ type: 'AGENT_TOOL_RESULT',
479
+ requestId,
480
+ ...result,
481
+ }
482
+ window.parent?.postMessage(envelope, '*')
483
+ }
484
+ const definition = latest.current.tools.find((it) => it.name === tool)
485
+ if (!definition) {
486
+ reply({ error: `This component has no tool ${tool}` })
487
+ return
488
+ }
489
+ Promise.resolve()
490
+ .then(() => definition.run(input))
491
+ .then(
492
+ (output) => reply(output === undefined ? {} : { output }),
493
+ (error: unknown) =>
494
+ reply({ error: error instanceof Error ? error.message : String(error) }),
495
+ )
496
+ }
497
+ window.addEventListener('message', onMessage)
498
+ return () => window.removeEventListener('message', onMessage)
499
+ }, [])
500
+ }
package/src/index.ts CHANGED
@@ -19,8 +19,15 @@ export type {
19
19
  RuntimeValue,
20
20
  } from './context'
21
21
  export { RuntimeProvider } from './context'
22
- export type { FillViewportOptions, HostLocation, ModalHost } from './hooks'
22
+ export type {
23
+ AgentTool,
24
+ FillViewportOptions,
25
+ HostLocation,
26
+ ModalHost,
27
+ UseAgentToolsOptions,
28
+ } from './hooks'
23
29
  export {
30
+ useAgentTools,
24
31
  useAgentWindow,
25
32
  useApiBaseUrl,
26
33
  useAuthToken,
@@ -41,6 +48,10 @@ export {
41
48
  } from './hooks'
42
49
  export {
43
50
  type AgentTabsAvailabilityMessage,
51
+ type AgentToolCallMessage,
52
+ type AgentToolResultMessage,
53
+ type AgentToolSpec,
54
+ type AgentToolsMessage,
44
55
  type AgentWindowTab,
45
56
  type AuthRefreshMessage,
46
57
  type CloseAgentWindowMessage,
package/src/protocol.ts CHANGED
@@ -240,8 +240,19 @@ export interface KnowledgeEditorClosedMessage {
240
240
  result?: KnowledgeEditorModalResult
241
241
  }
242
242
 
243
+ /** The agent calls one of the tools this frame registered with
244
+ * AGENT_TOOLS. The runtime answers AGENT_TOOL_RESULT with the same
245
+ * `requestId`. */
246
+ export interface AgentToolCallMessage {
247
+ type: 'AGENT_TOOL_CALL'
248
+ requestId: string
249
+ tool: string
250
+ input: unknown
251
+ }
252
+
243
253
  export type HostMessage =
244
254
  | InitMessage
255
+ | AgentToolCallMessage
245
256
  | AgentTabsAvailabilityMessage
246
257
  | AuthRefreshMessage
247
258
  | DataInvalidateMessage
@@ -505,6 +516,37 @@ export interface RunPageActionMessage {
505
516
  context?: PageActionContext
506
517
  }
507
518
 
519
+ /** A tool a component offers the workspace agent, as it rides the wire. */
520
+ export interface AgentToolSpec {
521
+ /** Unique within the component, snake_case, e.g. `preview_clusters`. */
522
+ name: string
523
+ /** What the tool does and when to use it — the agent reads only this. */
524
+ description: string
525
+ /** JSON Schema of the input object. */
526
+ inputSchema?: Record<string, unknown>
527
+ /** Changes nothing (reads what the component shows). */
528
+ readOnly?: boolean
529
+ }
530
+
531
+ /** The tools and state this frame offers the workspace agent — a full
532
+ * replacement of what it posted before. An empty `tools` withdraws the
533
+ * frame. `state` is the snapshot the agent reads in describe_tab; plain,
534
+ * JSON-like data only. Ignored by hosts without an agent workspace. */
535
+ export interface AgentToolsMessage {
536
+ type: 'AGENT_TOOLS'
537
+ tools: AgentToolSpec[]
538
+ label?: string
539
+ state?: unknown
540
+ }
541
+
542
+ /** The answer to AGENT_TOOL_CALL: the handler's output, or its error. */
543
+ export interface AgentToolResultMessage {
544
+ type: 'AGENT_TOOL_RESULT'
545
+ requestId: string
546
+ output?: unknown
547
+ error?: string
548
+ }
549
+
508
550
  export interface ErrorMessage {
509
551
  type: 'ERROR'
510
552
  message: string
@@ -527,6 +569,8 @@ export type RuntimeMessage =
527
569
  | CloseAgentWindowMessage
528
570
  | RecordWrittenMessage
529
571
  | RunPageActionMessage
572
+ | AgentToolsMessage
573
+ | AgentToolResultMessage
530
574
  | ErrorMessage
531
575
 
532
576
  // Wire envelope: the message plus the source discriminator.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/protocol.ts"],"names":[],"mappings":";AAYO,IAAM,cAAA,GAAiB;AAuBvB,IAAM,yBAAA,GAA4B;AAmflC,SAAS,cAAc,IAAA,EAA8C;AAC1E,EAAA,OACE,OAAO,IAAA,KAAS,QAAA,IAChB,IAAA,KAAS,IAAA,IACR,KAA8B,MAAA,KAAW,cAAA,IAC1C,OAAQ,IAAA,CAA4B,IAAA,KAAS,QAAA;AAEjD;AAEO,SAAS,iBAAiB,IAAA,EAAiD;AAChF,EAAA,OACE,OAAO,IAAA,KAAS,QAAA,IAChB,IAAA,KAAS,IAAA,IACR,KAA8B,MAAA,KAAW,cAAA,IAC1C,OAAQ,IAAA,CAA4B,IAAA,KAAS,QAAA;AAEjD","file":"chunk-A4D64VS2.js","sourcesContent":["// postMessage protocol between the host page and the component-runtime iframe.\n// This is the single source of truth for the wire contract: the host renderer\n// (clients/web .../component-frame.tsx), the runtime shell\n// (clients/web/component-runtime/shell.tsx), and the author-facing hooks\n// (this package's RuntimeProvider / useNavigate) all import these same types so\n// every end stays in lockstep.\n//\n// Every message carries `source: MESSAGE_SOURCE` so we can ignore the unrelated\n// postMessage traffic that shares the window (OIDC silent-renew, Vite HMR, …).\n\nimport type { PageAction } from '@proteos/sdk'\n\nexport const MESSAGE_SOURCE = 'proteos-component-runtime' as const\n\n/**\n * z-index the component iframe is promoted to while one of its own overlays\n * (modal, popover, menu, select, tooltip) is open. The iframe goes\n * `position: fixed; inset: 0` at this z so the overlay — which portals to the\n * IFRAME's body and would otherwise clip at the frame's box — can paint over\n * the rest of the page.\n *\n * Host z ladder this slots into:\n * 50 @proteos/ui Modal / Tooltip / ImageLightbox (default tier)\n * 1000+ full-page panel stack (scrim 1000, panels 1001+n)\n * 1090 peek scrim 1100 peek panel, ask-proteos window\n * 1150 ← THIS\n * 1200 menu popover, command palette, action dialog, component modal\n * 1300 select popover\n *\n * Above the peek/full-page surfaces a component can live on, below the global\n * host chrome. Note the cap: inside a peek (a `fixed` + z-index ancestor) the\n * promoted iframe paints within that 1100 stacking context — it covers the\n * peek's own content and everything under it, but host chrome at 1200+ still\n * wins. That is the intended layering, not a bug.\n */\nexport const COMPONENT_OVERLAY_Z_INDEX = 1150\n\n/** Viewport-relative box of the iframe's in-flow placeholder, in CSS px. */\nexport interface OverlayRect {\n top: number\n left: number\n width: number\n height: number\n}\n\n/** What the viewer is doing with the record on the host page.\n *\n * - `view` — a read-only record page, or a page without a record\n * (platform, kiosk, public, previews).\n * - `create` — the form for a record that is not saved yet (`record` holds\n * the seed values only, no `id`).\n * - `edit` — the form over an existing record (`record` is the SAVED row;\n * in-flight edits are not reflected).\n *\n * Inside an action's / workflow's invoke dialog (a trigger page) `mode` is\n * `create` while the person fills the params and `view` once the run is on\n * its way; `phase` says where the run is.\n *\n * A snapshot like `record`: the host remounts the frame when the page\n * switches between view and edit, so a new INIT carries the new mode. Also\n * the Liquid scope key `mode` when props are resolved. */\nexport type PageMode = 'view' | 'create' | 'edit'\n\n/** Where an invocation is in the invoke dialog's lifecycle — set only on a\n * trigger page (the dialog of an action / workflow); absent everywhere else.\n *\n * - `input` — the form over the params (`record` = the seeded params).\n * - `running` — the run is in flight (`record` = the submitted params;\n * `params.execution` for a workflow).\n * - `result` — the run ended (`record` = the params plus the action's\n * returns; `params.result` / `params.execution`).\n *\n * Also the Liquid scope key `phase`. */\nexport type TriggerPhase = 'input' | 'running' | 'result'\n\nexport interface PageContext {\n record?: Record<string, unknown>\n entity?: { slug: string; [key: string]: unknown }\n params?: Record<string, unknown>\n mode: PageMode\n phase?: TriggerPhase\n /** The signed-in viewer (absent on public pages and offline previews). The\n * host resolves `{{ current_user.* }}` and the bare `current_user` prop\n * sentinel against it before posting props. */\n current_user?: { id: string; email: string; given_name: string; family_name: string }\n [key: string]: unknown\n}\n\n// ── Host → runtime ──────────────────────────────────────────────────────────\n\nexport interface InitMessage {\n type: 'INIT'\n /** Raw bearer token (the OIDC `id_token`). The runtime's ProteosClient\n * prepends `Bearer ` when building the Authorization header, so the host\n * sends the token verbatim — NOT a full `Bearer …` header value.\n * Empty string in public mode (`isPublic: true`). */\n authToken: string\n /** API origin the bundle endpoint + SDK calls resolve against. */\n apiBaseUrl: string\n /** Content hash (hex SHA-256) of the component's deployed bundle, from the\n * component's `bundle_checksum`. The runtime appends it as `?v=` to the\n * bundle request so the server can mark the response immutable — the\n * browser then serves every later mount from its cache without a round\n * trip. Absent when the host does not know it yet (metadata still\n * loading, or a row deployed before checksum stamping); the bundle then\n * revalidates as before. */\n bundleVersion?: string\n /** Key under which the runtime shares its query cache with sibling and\n * successor frames of the same component through the host (same\n * origin): the host warms a new frame from the last state a frame with\n * this key left behind. Covers the slug AND the resolved props, so two\n * placements configured differently never share. Absent on hosts that\n * do not keep a store (previews, public pages). */\n cacheKey?: string\n /** Resolved props for the component (Liquid templating happens host-side). */\n props: Record<string, unknown>\n pageCtx: PageContext\n /** PUBLIC mode: the component renders on an unauthenticated public page.\n * The shell fetches the bundle from the public endpoint (no bearer) and\n * injects a restricted sdk — only `functions.actions.invokePublic` reaches\n * the platform. Requires `orgId`. */\n isPublic?: boolean\n /** Org id for public mode — public endpoints carry the org in the path\n * because there is no token to scope from. */\n orgId?: string\n /** Set when this frame is the CONTENT of a host component modal (opened by\n * another component via OPEN_MODAL). The component reads it through\n * `useModalHost()` and closes with a result by posting MODAL_RESULT with\n * this id. Absent on ordinary page-hosted frames. */\n modalRequestId?: string\n /** Whether OPEN_AGENT_WINDOW with a `tab` opens it here (a host with an\n * agent and a workspace beside it). AGENT_TABS_AVAILABILITY updates it. */\n canOpenAgentTabs?: boolean\n}\n\n/** The host can now (or no longer) open OPEN_AGENT_WINDOW's `tab` — e.g. its\n * agents finished loading after INIT. */\nexport interface AgentTabsAvailabilityMessage {\n type: 'AGENT_TABS_AVAILABILITY'\n canOpenAgentTabs: boolean\n}\n\nexport interface AuthRefreshMessage {\n type: 'AUTH_REFRESH'\n token: string\n}\n\nexport interface DataInvalidateMessage {\n type: 'DATA_INVALIDATE'\n queryKey?: unknown[]\n}\n\n/** Where the iframe's in-flow box sits in the host viewport. Sent while the\n * frame is promoted (OVERLAY_STATE open) so the runtime can keep its content\n * parked at the original rect while the iframe itself covers the viewport —\n * and re-sent when the host window resizes under an open overlay. */\nexport interface OverlayRectMessage {\n type: 'OVERLAY_RECT'\n rect: OverlayRect\n}\n\n/** Resolution of an OPEN_MODAL request: the host modal closed. `result` is the\n * value the modal's component passed to MODAL_RESULT, and is absent when the\n * modal was dismissed (backdrop / Esc / ×). */\nexport interface ModalClosedMessage {\n type: 'MODAL_CLOSED'\n requestId: string\n result?: unknown\n}\n\n/** How a RUN_PAGE_ACTION ended, by what the button did:\n *\n * - `done` — the run went through: an action's `returns` (null when it\n * returned none), a workflow's accepted `executionId`, the\n * record an intent created / updated.\n * - `failed` — the invocation failed and the person closed the error.\n * - `cancelled` — the person stepped out before anything ran or saved.\n * - `handed_over` — an `agent` / `link` button: the chat or the tab is open;\n * what happens there is not reported back.\n * - `unavailable` — nothing was opened: `invalid` (the action does not parse),\n * `hidden` (its `visible_when` does not match, an intent\n * has no record to act on, a link no address to open),\n * `busy` (another page action is still open), `unsupported`\n * (a public page, a host without page actions — a preview —\n * or an agent button where there is no agent window). */\nexport type PageActionOutcome =\n | { status: 'done'; kind: 'action'; returns: Record<string, unknown> | null }\n | { status: 'done'; kind: 'workflow'; executionId: string }\n | {\n status: 'done'\n kind: 'intent'\n mode: 'create' | 'update'\n entitySlug: string\n recordId: string\n title: string\n }\n | { status: 'failed'; error: { code: string; message: string } }\n | { status: 'cancelled' }\n | { status: 'handed_over'; kind: 'agent' | 'link' }\n | { status: 'unavailable'; reason: 'invalid' | 'hidden' | 'busy' | 'unsupported' }\n\n/** Resolution of a RUN_PAGE_ACTION request, once the run's flow is over. */\nexport interface PageActionSettledMessage {\n type: 'PAGE_ACTION_SETTLED'\n requestId: string\n outcome: PageActionOutcome\n}\n\n/** How a host record-draft review ended: the draft's terminal status. */\nexport type RecordDraftReviewOutcome = 'approved' | 'approved_with_changes' | 'rejected'\n\n/** Resolution of an OPEN_RECORD_DRAFT_REVIEW request: the review closed.\n * `outcome` is absent when it closed undecided — the draft stays proposed —\n * or when the host could not open it (a public page, a preview, a review\n * from this frame already open). */\nexport interface RecordDraftReviewClosedMessage {\n type: 'RECORD_DRAFT_REVIEW_CLOSED'\n requestId: string\n outcome?: RecordDraftReviewOutcome\n}\n\n/** What a host knowledge-editor modal reports once it closes, when it saved\n * (or created) the node at least once. */\nexport interface KnowledgeEditorModalResult {\n /** The node edited — or created, see `created`. */\n nodeId: string\n /** Its title as last saved. */\n title: string\n /** True when the modal created the node (no `nodeId` was passed). */\n created: boolean\n}\n\n/** Resolution of an OPEN_KNOWLEDGE_EDITOR request: the modal closed. `result`\n * is absent when nothing was saved — dismissed (an unsaved draft stays on\n * the device), or the host could not open it (a public page, a preview, a\n * modal from this frame already open). */\nexport interface KnowledgeEditorClosedMessage {\n type: 'KNOWLEDGE_EDITOR_CLOSED'\n requestId: string\n result?: KnowledgeEditorModalResult\n}\n\nexport type HostMessage =\n | InitMessage\n | AgentTabsAvailabilityMessage\n | AuthRefreshMessage\n | DataInvalidateMessage\n | OverlayRectMessage\n | ModalClosedMessage\n | PageActionSettledMessage\n | RecordDraftReviewClosedMessage\n | KnowledgeEditorClosedMessage\n\n// ── Runtime → host ──────────────────────────────────────────────────────────\n\nexport interface ReadyMessage {\n type: 'READY'\n}\n\nexport interface ResizeMessage {\n type: 'RESIZE'\n height: number\n}\n\nexport interface NavigateMessage {\n type: 'NAVIGATE'\n to: string\n}\n\n/** Open an in-app path in a peek (slide-over) panel instead of full-page\n * navigation. Same `/…` in-app path grammar as NAVIGATE; the host decides\n * what can peek (today: platform pages) and falls back to NAVIGATE otherwise. */\nexport interface OpenPeekMessage {\n type: 'OPEN_PEEK'\n to: string\n}\n\n/** Ask the host to open a prepared call: the host shows the conversation brief's\n * preview (its softphone owns the dial) and lets the user place the call.\n * Ignored on public pages and on hosts without a softphone. */\nexport interface OpenCallMessage {\n type: 'OPEN_CALL'\n /** The conversation brief to preview and dial from. */\n conversationBriefId: string\n}\n\n/** Ask the host to open its review of a record draft (a proposed record\n * write): the current values next to the proposed ones, editable for one\n * record, a table for several. The host answers RECORD_DRAFT_REVIEW_CLOSED\n * with the same `requestId` once the review closes. Approving writes the\n * records server-side as the viewer; the host then sends DATA_INVALIDATE.\n *\n * One review per frame at a time; ignored (answered without an outcome) on\n * public pages and by hosts without one. */\nexport interface OpenRecordDraftReviewMessage {\n type: 'OPEN_RECORD_DRAFT_REVIEW'\n /** Correlates the eventual RECORD_DRAFT_REVIEW_CLOSED. Generated by the runtime. */\n requestId: string\n /** The record draft to review. */\n recordDraftId: string\n}\n\n/** Fields for a knowledge node the editor modal creates on its first save. */\nexport interface KnowledgeEditorCreateDefaults {\n /** Prefills the title field. */\n title?: string\n summary?: string\n /** File the node into a space. Omitted: unassigned. */\n space_slug?: string\n status?: 'draft' | 'published'\n label_ids?: string[]\n}\n\n/** Ask the host to open its knowledge editor — the app's own `KnowledgeEditor`\n * in a dialog — on one knowledge node, or on a new one. Read mode with an\n * outline, Edit for the tools, local drafts, and a save that refuses to\n * overwrite a node changed meanwhile. The host answers\n * KNOWLEDGE_EDITOR_CLOSED with the same `requestId`.\n *\n * One per frame at a time; ignored (answered without a result) on public\n * pages and by hosts without one. */\nexport interface OpenKnowledgeEditorMessage {\n type: 'OPEN_KNOWLEDGE_EDITOR'\n /** Correlates the eventual KNOWLEDGE_EDITOR_CLOSED. Generated by the runtime. */\n requestId: string\n /** The node to open. Omit to create one on the first save. */\n nodeId?: string\n /** Dialog heading. Defaults to the node's title (or \"New note\"). */\n title?: string\n /** Where an unsaved draft of a NEW node is kept, so it survives a reload —\n * a key stable for what the node is for, e.g. `note:deal:<record id>`. */\n draftKey?: string\n /** Used when creating (no `nodeId`). */\n createDefaults?: KnowledgeEditorCreateDefaults\n /** Open straight into edit mode. Default: read for an existing node. */\n mode?: 'read' | 'edit'\n}\n\n/** The runtime has (or no longer has) an overlay open and needs the host to\n * promote (or restore) the iframe. See {@link COMPONENT_OVERLAY_Z_INDEX}.\n *\n * Same-origin today, so the runtime applies the promotion styles to its own\n * `window.frameElement` synchronously (pre-paint, no flicker) and this message\n * is the host's cue to MIRROR that state into React — gate RESIZE, hold the\n * placeholder height, start posting OVERLAY_RECT. When components move to a\n * dedicated origin the runtime can no longer touch the frame and this message\n * becomes the actuation instead; the runtime hides its overlay until the\n * answering OVERLAY_RECT arrives. */\nexport interface OverlayStateMessage {\n type: 'OVERLAY_STATE'\n open: boolean\n}\n\n/** Width of a host component modal's panel: `sm` 384px, `md` 512px, `lg` 672px,\n * `xl` 896px. Below 640px the modal is a full-screen sheet whatever the\n * width. */\nexport type ModalWidth = 'sm' | 'md' | 'lg' | 'xl'\n\n/** Ask the host to open ANOTHER component in a central modal, above everything\n * this frame could reach on its own. The host answers with MODAL_CLOSED\n * carrying the same `requestId`.\n *\n * One modal per opener at a time: while a request from this frame is still\n * open, the host answers any further OPEN_MODAL from it as dismissed (a\n * double click must not stack two dialogs). The modal's own component may\n * open another — that request comes from a different frame. */\nexport interface OpenModalMessage {\n type: 'OPEN_MODAL'\n /** Correlates the eventual MODAL_CLOSED. Generated by the opener. */\n requestId: string\n /** Slug of the component to mount inside the modal. */\n componentSlug: string\n /** Props for that component. The host renders Liquid in every string value\n * against the OPENER's page scope (`record`, `entity`, `params`,\n * `current_user`) before handing them over — exactly as it does for a\n * page-placed component. So `{{ … }}` / `{% … %}` in a value is evaluated,\n * not passed through. */\n props?: Record<string, unknown>\n /** Optional modal heading. */\n title?: string\n /** Panel width. Defaults to `lg`. */\n width?: ModalWidth\n /** Height of the component's frame, in px. Set: the frame is that tall from\n * the first paint (capped at the viewport), scrolls its own content, and\n * sits edge to edge in the panel — the component owns its padding. Unset:\n * the frame grows with its content inside the host's padded body. */\n height?: number\n}\n\n/** Escape was pressed with focus inside the iframe, and nothing in the runtime\n * consumed it.\n *\n * Keyboard events don't cross the iframe boundary, and react-aria binds its\n * Escape handling to the overlay element in its own React tree — so a\n * host-rendered dialog CANNOT see Escape once the user has clicked into a\n * component. The runtime forwards it so the host can dismiss on the user's\n * behalf. Not sent while the runtime has its own overlay open: that overlay\n * owns Escape. */\nexport interface EscapePressedMessage {\n type: 'ESCAPE_PRESSED'\n}\n\n/** Posted by the component INSIDE a host modal to close it with a value. The\n * `requestId` is the one INIT carried as `modalRequestId`. */\nexport interface ModalResultMessage {\n type: 'MODAL_RESULT'\n requestId: string\n result?: unknown\n}\n\n/** A stored draft the host opens as a workspace tab beside the assistant. */\nexport type AgentWindowTab =\n | { kind: 'message-draft'; messageId: string }\n | { kind: 'record-draft'; recordDraftId: string }\n\n/** Ask the host to open its agent session window (the floating assistant).\n *\n * - `tab` set (\"Edit with Ava\"): the host opens that draft as a workspace\n * tab, full-screen, beside a fresh session with the org's primary agent,\n * and closes the component modal this frame sits in so the window is not\n * hidden behind it. The other fields are ignored then; a host that cannot\n * show the workspace (a phone) does nothing.\n * - `sessionId` set: the window resumes THAT session (its agent is read from\n * the session). A `prompt` is sent into it.\n * - no `sessionId`: a fresh session with `agentKey` (or the agent currently\n * selected in the window); a `prompt` is sent as its first message. With\n * neither field the window just opens as it is.\n *\n * Ignored on public pages (there is no signed-in user to run an agent as). */\nexport interface OpenAgentWindowMessage {\n type: 'OPEN_AGENT_WINDOW'\n sessionId?: string\n agentKey?: string\n prompt?: string\n /** Model-only context sent with `prompt`; never rendered. */\n context?: string\n tab?: AgentWindowTab\n}\n\n/** Ask the host to minimize its agent session window. The active session and\n * its stream stay alive — reopening resumes it. */\nexport interface CloseAgentWindowMessage {\n type: 'CLOSE_AGENT_WINDOW'\n}\n\n/** A record write the component made through its sdk (`data.records.*`)\n * succeeded. Posted by the runtime shell — not by component code — so the\n * host can refresh what it shows of that entity and, when the component\n * sits in a surface that reports edits (the Ava workspace), tell the agent.\n * `patch` is what was submitted, `record` what the server returned. */\nexport interface RecordWrittenMessage {\n type: 'RECORD_WRITTEN'\n entitySlug: string\n operation: 'create' | 'update' | 'delete' | 'batch_upsert'\n recordId?: string\n patch?: Record<string, unknown>\n record?: Record<string, unknown>\n /** Rows in a batch upsert. */\n count?: number\n}\n\n/** A record a page action acts on, as the component names it. */\nexport interface PageActionRecord {\n entitySlug: string\n recordId: string\n /** Shown when the person picks among several records for an intent. */\n title?: string\n /** The entity's display name, shown beside `title` in that pick. */\n entityName?: string\n}\n\n/** What the component knows that the button needs — layered over what the\n * host already knows about the page. */\nexport interface PageActionContext {\n /** Merged over the page scope (`record`, `entity`, `params`, `mode`,\n * `current_user`) the action's Liquid templates render against — `params`\n * / `inputs` prefill, `prompt`, `context`, `entity`, `record`, `url`.\n * Shallow: a key given here replaces the page's. `current_user` is always\n * the host's. */\n scope?: Record<string, unknown>\n /** The records the button acts on. Default: the page record (none on a page\n * without one).\n *\n * - `action` with entity scope — the one record it is invoked on.\n * - `action` with entity_batch scope — every record, in ONE invocation.\n * - `intent` `update_record` without a `record` — the records of the\n * intent's entity it may update: one is updated, several are offered\n * to pick from. */\n records?: PageActionRecord[]\n}\n\n/** Ask the host to run a page action — the same button a page or list toolbar\n * carries, defined inline by the component. The host dispatches it exactly\n * as a toolbar press (invoke dialog, record proposal review, agent window,\n * new tab) and answers PAGE_ACTION_SETTLED with the same `requestId` once\n * the flow is over.\n *\n * One page action at a time: while one is open (from any component) the\n * host answers further requests `unavailable: busy`. */\nexport interface RunPageActionMessage {\n type: 'RUN_PAGE_ACTION'\n /** Correlates the eventual PAGE_ACTION_SETTLED. Generated by the runtime. */\n requestId: string\n action: PageAction\n context?: PageActionContext\n}\n\nexport interface ErrorMessage {\n type: 'ERROR'\n message: string\n stack?: string\n}\n\nexport type RuntimeMessage =\n | ReadyMessage\n | ResizeMessage\n | NavigateMessage\n | OpenPeekMessage\n | OpenCallMessage\n | OpenRecordDraftReviewMessage\n | OpenKnowledgeEditorMessage\n | OverlayStateMessage\n | OpenModalMessage\n | ModalResultMessage\n | EscapePressedMessage\n | OpenAgentWindowMessage\n | CloseAgentWindowMessage\n | RecordWrittenMessage\n | RunPageActionMessage\n | ErrorMessage\n\n// Wire envelope: the message plus the source discriminator.\nexport type Envelope<T> = T & { source: typeof MESSAGE_SOURCE }\n\nexport function isHostMessage(data: unknown): data is Envelope<HostMessage> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { source?: unknown }).source === MESSAGE_SOURCE &&\n typeof (data as { type?: unknown }).type === 'string'\n )\n}\n\nexport function isRuntimeMessage(data: unknown): data is Envelope<RuntimeMessage> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { source?: unknown }).source === MESSAGE_SOURCE &&\n typeof (data as { type?: unknown }).type === 'string'\n )\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/protocol.ts"],"names":[],"mappings":";;;AAYO,IAAM,cAAA,GAAiB;AAuBvB,IAAM,yBAAA,GAA4B;AAmflC,SAAS,cAAc,IAAA,EAA8C;AAC1E,EAAA,OACE,OAAO,IAAA,KAAS,QAAA,IAChB,IAAA,KAAS,IAAA,IACR,KAA8B,MAAA,KAAW,cAAA,IAC1C,OAAQ,IAAA,CAA4B,IAAA,KAAS,QAAA;AAEjD;AAEO,SAAS,iBAAiB,IAAA,EAAiD;AAChF,EAAA,OACE,OAAO,IAAA,KAAS,QAAA,IAChB,IAAA,KAAS,IAAA,IACR,KAA8B,MAAA,KAAW,cAAA,IAC1C,OAAQ,IAAA,CAA4B,IAAA,KAAS,QAAA;AAEjD","file":"chunk-YW4W3PQV.cjs","sourcesContent":["// postMessage protocol between the host page and the component-runtime iframe.\n// This is the single source of truth for the wire contract: the host renderer\n// (clients/web .../component-frame.tsx), the runtime shell\n// (clients/web/component-runtime/shell.tsx), and the author-facing hooks\n// (this package's RuntimeProvider / useNavigate) all import these same types so\n// every end stays in lockstep.\n//\n// Every message carries `source: MESSAGE_SOURCE` so we can ignore the unrelated\n// postMessage traffic that shares the window (OIDC silent-renew, Vite HMR, …).\n\nimport type { PageAction } from '@proteos/sdk'\n\nexport const MESSAGE_SOURCE = 'proteos-component-runtime' as const\n\n/**\n * z-index the component iframe is promoted to while one of its own overlays\n * (modal, popover, menu, select, tooltip) is open. The iframe goes\n * `position: fixed; inset: 0` at this z so the overlay — which portals to the\n * IFRAME's body and would otherwise clip at the frame's box — can paint over\n * the rest of the page.\n *\n * Host z ladder this slots into:\n * 50 @proteos/ui Modal / Tooltip / ImageLightbox (default tier)\n * 1000+ full-page panel stack (scrim 1000, panels 1001+n)\n * 1090 peek scrim 1100 peek panel, ask-proteos window\n * 1150 ← THIS\n * 1200 menu popover, command palette, action dialog, component modal\n * 1300 select popover\n *\n * Above the peek/full-page surfaces a component can live on, below the global\n * host chrome. Note the cap: inside a peek (a `fixed` + z-index ancestor) the\n * promoted iframe paints within that 1100 stacking context — it covers the\n * peek's own content and everything under it, but host chrome at 1200+ still\n * wins. That is the intended layering, not a bug.\n */\nexport const COMPONENT_OVERLAY_Z_INDEX = 1150\n\n/** Viewport-relative box of the iframe's in-flow placeholder, in CSS px. */\nexport interface OverlayRect {\n top: number\n left: number\n width: number\n height: number\n}\n\n/** What the viewer is doing with the record on the host page.\n *\n * - `view` — a read-only record page, or a page without a record\n * (platform, kiosk, public, previews).\n * - `create` — the form for a record that is not saved yet (`record` holds\n * the seed values only, no `id`).\n * - `edit` — the form over an existing record (`record` is the SAVED row;\n * in-flight edits are not reflected).\n *\n * Inside an action's / workflow's invoke dialog (a trigger page) `mode` is\n * `create` while the person fills the params and `view` once the run is on\n * its way; `phase` says where the run is.\n *\n * A snapshot like `record`: the host remounts the frame when the page\n * switches between view and edit, so a new INIT carries the new mode. Also\n * the Liquid scope key `mode` when props are resolved. */\nexport type PageMode = 'view' | 'create' | 'edit'\n\n/** Where an invocation is in the invoke dialog's lifecycle — set only on a\n * trigger page (the dialog of an action / workflow); absent everywhere else.\n *\n * - `input` — the form over the params (`record` = the seeded params).\n * - `running` — the run is in flight (`record` = the submitted params;\n * `params.execution` for a workflow).\n * - `result` — the run ended (`record` = the params plus the action's\n * returns; `params.result` / `params.execution`).\n *\n * Also the Liquid scope key `phase`. */\nexport type TriggerPhase = 'input' | 'running' | 'result'\n\nexport interface PageContext {\n record?: Record<string, unknown>\n entity?: { slug: string; [key: string]: unknown }\n params?: Record<string, unknown>\n mode: PageMode\n phase?: TriggerPhase\n /** The signed-in viewer (absent on public pages and offline previews). The\n * host resolves `{{ current_user.* }}` and the bare `current_user` prop\n * sentinel against it before posting props. */\n current_user?: { id: string; email: string; given_name: string; family_name: string }\n [key: string]: unknown\n}\n\n// ── Host → runtime ──────────────────────────────────────────────────────────\n\nexport interface InitMessage {\n type: 'INIT'\n /** Raw bearer token (the OIDC `id_token`). The runtime's ProteosClient\n * prepends `Bearer ` when building the Authorization header, so the host\n * sends the token verbatim — NOT a full `Bearer …` header value.\n * Empty string in public mode (`isPublic: true`). */\n authToken: string\n /** API origin the bundle endpoint + SDK calls resolve against. */\n apiBaseUrl: string\n /** Content hash (hex SHA-256) of the component's deployed bundle, from the\n * component's `bundle_checksum`. The runtime appends it as `?v=` to the\n * bundle request so the server can mark the response immutable — the\n * browser then serves every later mount from its cache without a round\n * trip. Absent when the host does not know it yet (metadata still\n * loading, or a row deployed before checksum stamping); the bundle then\n * revalidates as before. */\n bundleVersion?: string\n /** Key under which the runtime shares its query cache with sibling and\n * successor frames of the same component through the host (same\n * origin): the host warms a new frame from the last state a frame with\n * this key left behind. Covers the slug AND the resolved props, so two\n * placements configured differently never share. Absent on hosts that\n * do not keep a store (previews, public pages). */\n cacheKey?: string\n /** Resolved props for the component (Liquid templating happens host-side). */\n props: Record<string, unknown>\n pageCtx: PageContext\n /** PUBLIC mode: the component renders on an unauthenticated public page.\n * The shell fetches the bundle from the public endpoint (no bearer) and\n * injects a restricted sdk — only `functions.actions.invokePublic` reaches\n * the platform. Requires `orgId`. */\n isPublic?: boolean\n /** Org id for public mode — public endpoints carry the org in the path\n * because there is no token to scope from. */\n orgId?: string\n /** Set when this frame is the CONTENT of a host component modal (opened by\n * another component via OPEN_MODAL). The component reads it through\n * `useModalHost()` and closes with a result by posting MODAL_RESULT with\n * this id. Absent on ordinary page-hosted frames. */\n modalRequestId?: string\n /** Whether OPEN_AGENT_WINDOW with a `tab` opens it here (a host with an\n * agent and a workspace beside it). AGENT_TABS_AVAILABILITY updates it. */\n canOpenAgentTabs?: boolean\n}\n\n/** The host can now (or no longer) open OPEN_AGENT_WINDOW's `tab` — e.g. its\n * agents finished loading after INIT. */\nexport interface AgentTabsAvailabilityMessage {\n type: 'AGENT_TABS_AVAILABILITY'\n canOpenAgentTabs: boolean\n}\n\nexport interface AuthRefreshMessage {\n type: 'AUTH_REFRESH'\n token: string\n}\n\nexport interface DataInvalidateMessage {\n type: 'DATA_INVALIDATE'\n queryKey?: unknown[]\n}\n\n/** Where the iframe's in-flow box sits in the host viewport. Sent while the\n * frame is promoted (OVERLAY_STATE open) so the runtime can keep its content\n * parked at the original rect while the iframe itself covers the viewport —\n * and re-sent when the host window resizes under an open overlay. */\nexport interface OverlayRectMessage {\n type: 'OVERLAY_RECT'\n rect: OverlayRect\n}\n\n/** Resolution of an OPEN_MODAL request: the host modal closed. `result` is the\n * value the modal's component passed to MODAL_RESULT, and is absent when the\n * modal was dismissed (backdrop / Esc / ×). */\nexport interface ModalClosedMessage {\n type: 'MODAL_CLOSED'\n requestId: string\n result?: unknown\n}\n\n/** How a RUN_PAGE_ACTION ended, by what the button did:\n *\n * - `done` — the run went through: an action's `returns` (null when it\n * returned none), a workflow's accepted `executionId`, the\n * record an intent created / updated.\n * - `failed` — the invocation failed and the person closed the error.\n * - `cancelled` — the person stepped out before anything ran or saved.\n * - `handed_over` — an `agent` / `link` button: the chat or the tab is open;\n * what happens there is not reported back.\n * - `unavailable` — nothing was opened: `invalid` (the action does not parse),\n * `hidden` (its `visible_when` does not match, an intent\n * has no record to act on, a link no address to open),\n * `busy` (another page action is still open), `unsupported`\n * (a public page, a host without page actions — a preview —\n * or an agent button where there is no agent window). */\nexport type PageActionOutcome =\n | { status: 'done'; kind: 'action'; returns: Record<string, unknown> | null }\n | { status: 'done'; kind: 'workflow'; executionId: string }\n | {\n status: 'done'\n kind: 'intent'\n mode: 'create' | 'update'\n entitySlug: string\n recordId: string\n title: string\n }\n | { status: 'failed'; error: { code: string; message: string } }\n | { status: 'cancelled' }\n | { status: 'handed_over'; kind: 'agent' | 'link' }\n | { status: 'unavailable'; reason: 'invalid' | 'hidden' | 'busy' | 'unsupported' }\n\n/** Resolution of a RUN_PAGE_ACTION request, once the run's flow is over. */\nexport interface PageActionSettledMessage {\n type: 'PAGE_ACTION_SETTLED'\n requestId: string\n outcome: PageActionOutcome\n}\n\n/** How a host record-draft review ended: the draft's terminal status. */\nexport type RecordDraftReviewOutcome = 'approved' | 'approved_with_changes' | 'rejected'\n\n/** Resolution of an OPEN_RECORD_DRAFT_REVIEW request: the review closed.\n * `outcome` is absent when it closed undecided — the draft stays proposed —\n * or when the host could not open it (a public page, a preview, a review\n * from this frame already open). */\nexport interface RecordDraftReviewClosedMessage {\n type: 'RECORD_DRAFT_REVIEW_CLOSED'\n requestId: string\n outcome?: RecordDraftReviewOutcome\n}\n\n/** What a host knowledge-editor modal reports once it closes, when it saved\n * (or created) the node at least once. */\nexport interface KnowledgeEditorModalResult {\n /** The node edited — or created, see `created`. */\n nodeId: string\n /** Its title as last saved. */\n title: string\n /** True when the modal created the node (no `nodeId` was passed). */\n created: boolean\n}\n\n/** Resolution of an OPEN_KNOWLEDGE_EDITOR request: the modal closed. `result`\n * is absent when nothing was saved — dismissed (an unsaved draft stays on\n * the device), or the host could not open it (a public page, a preview, a\n * modal from this frame already open). */\nexport interface KnowledgeEditorClosedMessage {\n type: 'KNOWLEDGE_EDITOR_CLOSED'\n requestId: string\n result?: KnowledgeEditorModalResult\n}\n\nexport type HostMessage =\n | InitMessage\n | AgentTabsAvailabilityMessage\n | AuthRefreshMessage\n | DataInvalidateMessage\n | OverlayRectMessage\n | ModalClosedMessage\n | PageActionSettledMessage\n | RecordDraftReviewClosedMessage\n | KnowledgeEditorClosedMessage\n\n// ── Runtime → host ──────────────────────────────────────────────────────────\n\nexport interface ReadyMessage {\n type: 'READY'\n}\n\nexport interface ResizeMessage {\n type: 'RESIZE'\n height: number\n}\n\nexport interface NavigateMessage {\n type: 'NAVIGATE'\n to: string\n}\n\n/** Open an in-app path in a peek (slide-over) panel instead of full-page\n * navigation. Same `/…` in-app path grammar as NAVIGATE; the host decides\n * what can peek (today: platform pages) and falls back to NAVIGATE otherwise. */\nexport interface OpenPeekMessage {\n type: 'OPEN_PEEK'\n to: string\n}\n\n/** Ask the host to open a prepared call: the host shows the conversation brief's\n * preview (its softphone owns the dial) and lets the user place the call.\n * Ignored on public pages and on hosts without a softphone. */\nexport interface OpenCallMessage {\n type: 'OPEN_CALL'\n /** The conversation brief to preview and dial from. */\n conversationBriefId: string\n}\n\n/** Ask the host to open its review of a record draft (a proposed record\n * write): the current values next to the proposed ones, editable for one\n * record, a table for several. The host answers RECORD_DRAFT_REVIEW_CLOSED\n * with the same `requestId` once the review closes. Approving writes the\n * records server-side as the viewer; the host then sends DATA_INVALIDATE.\n *\n * One review per frame at a time; ignored (answered without an outcome) on\n * public pages and by hosts without one. */\nexport interface OpenRecordDraftReviewMessage {\n type: 'OPEN_RECORD_DRAFT_REVIEW'\n /** Correlates the eventual RECORD_DRAFT_REVIEW_CLOSED. Generated by the runtime. */\n requestId: string\n /** The record draft to review. */\n recordDraftId: string\n}\n\n/** Fields for a knowledge node the editor modal creates on its first save. */\nexport interface KnowledgeEditorCreateDefaults {\n /** Prefills the title field. */\n title?: string\n summary?: string\n /** File the node into a space. Omitted: unassigned. */\n space_slug?: string\n status?: 'draft' | 'published'\n label_ids?: string[]\n}\n\n/** Ask the host to open its knowledge editor — the app's own `KnowledgeEditor`\n * in a dialog — on one knowledge node, or on a new one. Read mode with an\n * outline, Edit for the tools, local drafts, and a save that refuses to\n * overwrite a node changed meanwhile. The host answers\n * KNOWLEDGE_EDITOR_CLOSED with the same `requestId`.\n *\n * One per frame at a time; ignored (answered without a result) on public\n * pages and by hosts without one. */\nexport interface OpenKnowledgeEditorMessage {\n type: 'OPEN_KNOWLEDGE_EDITOR'\n /** Correlates the eventual KNOWLEDGE_EDITOR_CLOSED. Generated by the runtime. */\n requestId: string\n /** The node to open. Omit to create one on the first save. */\n nodeId?: string\n /** Dialog heading. Defaults to the node's title (or \"New note\"). */\n title?: string\n /** Where an unsaved draft of a NEW node is kept, so it survives a reload —\n * a key stable for what the node is for, e.g. `note:deal:<record id>`. */\n draftKey?: string\n /** Used when creating (no `nodeId`). */\n createDefaults?: KnowledgeEditorCreateDefaults\n /** Open straight into edit mode. Default: read for an existing node. */\n mode?: 'read' | 'edit'\n}\n\n/** The runtime has (or no longer has) an overlay open and needs the host to\n * promote (or restore) the iframe. See {@link COMPONENT_OVERLAY_Z_INDEX}.\n *\n * Same-origin today, so the runtime applies the promotion styles to its own\n * `window.frameElement` synchronously (pre-paint, no flicker) and this message\n * is the host's cue to MIRROR that state into React — gate RESIZE, hold the\n * placeholder height, start posting OVERLAY_RECT. When components move to a\n * dedicated origin the runtime can no longer touch the frame and this message\n * becomes the actuation instead; the runtime hides its overlay until the\n * answering OVERLAY_RECT arrives. */\nexport interface OverlayStateMessage {\n type: 'OVERLAY_STATE'\n open: boolean\n}\n\n/** Width of a host component modal's panel: `sm` 384px, `md` 512px, `lg` 672px,\n * `xl` 896px. Below 640px the modal is a full-screen sheet whatever the\n * width. */\nexport type ModalWidth = 'sm' | 'md' | 'lg' | 'xl'\n\n/** Ask the host to open ANOTHER component in a central modal, above everything\n * this frame could reach on its own. The host answers with MODAL_CLOSED\n * carrying the same `requestId`.\n *\n * One modal per opener at a time: while a request from this frame is still\n * open, the host answers any further OPEN_MODAL from it as dismissed (a\n * double click must not stack two dialogs). The modal's own component may\n * open another — that request comes from a different frame. */\nexport interface OpenModalMessage {\n type: 'OPEN_MODAL'\n /** Correlates the eventual MODAL_CLOSED. Generated by the opener. */\n requestId: string\n /** Slug of the component to mount inside the modal. */\n componentSlug: string\n /** Props for that component. The host renders Liquid in every string value\n * against the OPENER's page scope (`record`, `entity`, `params`,\n * `current_user`) before handing them over — exactly as it does for a\n * page-placed component. So `{{ … }}` / `{% … %}` in a value is evaluated,\n * not passed through. */\n props?: Record<string, unknown>\n /** Optional modal heading. */\n title?: string\n /** Panel width. Defaults to `lg`. */\n width?: ModalWidth\n /** Height of the component's frame, in px. Set: the frame is that tall from\n * the first paint (capped at the viewport), scrolls its own content, and\n * sits edge to edge in the panel — the component owns its padding. Unset:\n * the frame grows with its content inside the host's padded body. */\n height?: number\n}\n\n/** Escape was pressed with focus inside the iframe, and nothing in the runtime\n * consumed it.\n *\n * Keyboard events don't cross the iframe boundary, and react-aria binds its\n * Escape handling to the overlay element in its own React tree — so a\n * host-rendered dialog CANNOT see Escape once the user has clicked into a\n * component. The runtime forwards it so the host can dismiss on the user's\n * behalf. Not sent while the runtime has its own overlay open: that overlay\n * owns Escape. */\nexport interface EscapePressedMessage {\n type: 'ESCAPE_PRESSED'\n}\n\n/** Posted by the component INSIDE a host modal to close it with a value. The\n * `requestId` is the one INIT carried as `modalRequestId`. */\nexport interface ModalResultMessage {\n type: 'MODAL_RESULT'\n requestId: string\n result?: unknown\n}\n\n/** A stored draft the host opens as a workspace tab beside the assistant. */\nexport type AgentWindowTab =\n | { kind: 'message-draft'; messageId: string }\n | { kind: 'record-draft'; recordDraftId: string }\n\n/** Ask the host to open its agent session window (the floating assistant).\n *\n * - `tab` set (\"Edit with Ava\"): the host opens that draft as a workspace\n * tab, full-screen, beside a fresh session with the org's primary agent,\n * and closes the component modal this frame sits in so the window is not\n * hidden behind it. The other fields are ignored then; a host that cannot\n * show the workspace (a phone) does nothing.\n * - `sessionId` set: the window resumes THAT session (its agent is read from\n * the session). A `prompt` is sent into it.\n * - no `sessionId`: a fresh session with `agentKey` (or the agent currently\n * selected in the window); a `prompt` is sent as its first message. With\n * neither field the window just opens as it is.\n *\n * Ignored on public pages (there is no signed-in user to run an agent as). */\nexport interface OpenAgentWindowMessage {\n type: 'OPEN_AGENT_WINDOW'\n sessionId?: string\n agentKey?: string\n prompt?: string\n /** Model-only context sent with `prompt`; never rendered. */\n context?: string\n tab?: AgentWindowTab\n}\n\n/** Ask the host to minimize its agent session window. The active session and\n * its stream stay alive — reopening resumes it. */\nexport interface CloseAgentWindowMessage {\n type: 'CLOSE_AGENT_WINDOW'\n}\n\n/** A record write the component made through its sdk (`data.records.*`)\n * succeeded. Posted by the runtime shell — not by component code — so the\n * host can refresh what it shows of that entity and, when the component\n * sits in a surface that reports edits (the Ava workspace), tell the agent.\n * `patch` is what was submitted, `record` what the server returned. */\nexport interface RecordWrittenMessage {\n type: 'RECORD_WRITTEN'\n entitySlug: string\n operation: 'create' | 'update' | 'delete' | 'batch_upsert'\n recordId?: string\n patch?: Record<string, unknown>\n record?: Record<string, unknown>\n /** Rows in a batch upsert. */\n count?: number\n}\n\n/** A record a page action acts on, as the component names it. */\nexport interface PageActionRecord {\n entitySlug: string\n recordId: string\n /** Shown when the person picks among several records for an intent. */\n title?: string\n /** The entity's display name, shown beside `title` in that pick. */\n entityName?: string\n}\n\n/** What the component knows that the button needs — layered over what the\n * host already knows about the page. */\nexport interface PageActionContext {\n /** Merged over the page scope (`record`, `entity`, `params`, `mode`,\n * `current_user`) the action's Liquid templates render against — `params`\n * / `inputs` prefill, `prompt`, `context`, `entity`, `record`, `url`.\n * Shallow: a key given here replaces the page's. `current_user` is always\n * the host's. */\n scope?: Record<string, unknown>\n /** The records the button acts on. Default: the page record (none on a page\n * without one).\n *\n * - `action` with entity scope — the one record it is invoked on.\n * - `action` with entity_batch scope — every record, in ONE invocation.\n * - `intent` `update_record` without a `record` — the records of the\n * intent's entity it may update: one is updated, several are offered\n * to pick from. */\n records?: PageActionRecord[]\n}\n\n/** Ask the host to run a page action — the same button a page or list toolbar\n * carries, defined inline by the component. The host dispatches it exactly\n * as a toolbar press (invoke dialog, record proposal review, agent window,\n * new tab) and answers PAGE_ACTION_SETTLED with the same `requestId` once\n * the flow is over.\n *\n * One page action at a time: while one is open (from any component) the\n * host answers further requests `unavailable: busy`. */\nexport interface RunPageActionMessage {\n type: 'RUN_PAGE_ACTION'\n /** Correlates the eventual PAGE_ACTION_SETTLED. Generated by the runtime. */\n requestId: string\n action: PageAction\n context?: PageActionContext\n}\n\nexport interface ErrorMessage {\n type: 'ERROR'\n message: string\n stack?: string\n}\n\nexport type RuntimeMessage =\n | ReadyMessage\n | ResizeMessage\n | NavigateMessage\n | OpenPeekMessage\n | OpenCallMessage\n | OpenRecordDraftReviewMessage\n | OpenKnowledgeEditorMessage\n | OverlayStateMessage\n | OpenModalMessage\n | ModalResultMessage\n | EscapePressedMessage\n | OpenAgentWindowMessage\n | CloseAgentWindowMessage\n | RecordWrittenMessage\n | RunPageActionMessage\n | ErrorMessage\n\n// Wire envelope: the message plus the source discriminator.\nexport type Envelope<T> = T & { source: typeof MESSAGE_SOURCE }\n\nexport function isHostMessage(data: unknown): data is Envelope<HostMessage> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { source?: unknown }).source === MESSAGE_SOURCE &&\n typeof (data as { type?: unknown }).type === 'string'\n )\n}\n\nexport function isRuntimeMessage(data: unknown): data is Envelope<RuntimeMessage> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { source?: unknown }).source === MESSAGE_SOURCE &&\n typeof (data as { type?: unknown }).type === 'string'\n )\n}\n"]}