@aceshooting/lyra-ui 30.2.0 → 30.4.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/CHANGELOG.md +87 -0
- package/dist/ai/adapters/a2ui.d.ts +10 -4
- package/dist/ai/adapters/a2ui.js +1 -1
- package/dist/ai/adapters/ag-ui.d.ts +17 -4
- package/dist/ai/adapters/ag-ui.js +1 -1
- package/dist/ai/adapters/ai-sdk.js +1 -1
- package/dist/ai/runtime.js +1 -1
- package/dist/components/agent-tools/mcp-app/mcp-app-protocol.d.ts +15 -0
- package/dist/components/agent-tools/mcp-app/mcp-app-protocol.js +36 -0
- package/dist/components/agent-tools/mcp-app/mcp-app.class.d.ts +31 -4
- package/dist/components/agent-tools/mcp-app/mcp-app.class.js +4 -4
- package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +2 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/message-actions/message-actions.class.d.ts +3 -3
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +13 -4
- package/dist/components/conversation/message-parts/message-parts.class.js +12 -10
- package/dist/components/conversation/message-parts/message-parts.d.ts +1 -1
- package/dist/components/conversation/message-parts/message-parts.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.d.ts +1 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail.class.d.ts +1 -1
- package/dist/components/layout/app-rail/app-rail.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.d.ts +4 -1
- package/dist/components/layout/multi-split/multi-split.class.js +6 -3
- package/dist/components/layout/multi-split/multi-split.styles.js +1 -1
- package/dist/components/layout/navigation-menu/navigation-menu.class.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +3 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.d.ts +6 -4
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
- package/dist/components/layout/scroller/scroller.class.d.ts +1 -1
- package/dist/components/layout/scroller/scroller.class.js +1 -1
- package/dist/components/layout/split-panel/split-panel.class.d.ts +1 -1
- package/dist/components/layout/split-panel/split-panel.class.js +1 -1
- package/dist/components/layout/stepper/stepper.class.d.ts +1 -1
- package/dist/components/layout/stepper/stepper.class.js +1 -1
- package/dist/components/layout/widget/widget.class.d.ts +1 -1
- package/dist/components/layout/widget/widget.class.js +1 -1
- package/dist/components/media/file-input/file-input.styles.js +1 -1
- package/dist/components/media/map/map-control-chrome.js +1 -0
- package/dist/components/media/map/map-control-options.d.ts +6 -2
- package/dist/components/media/map/map-control-options.js +1 -1
- package/dist/components/media/map/map-controls-lifecycle.js +1 -1
- package/dist/components/media/map/map-controls-readiness.js +1 -0
- package/dist/components/media/map/map.class.d.ts +39 -2
- package/dist/components/media/map/map.class.js +13 -7
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/overlays/dialog/dialog.class.d.ts +2 -2
- package/dist/components/overlays/dialog/dialog.class.js +1 -1
- package/dist/components/utility/copy-button/copy-button.class.d.ts +13 -15
- package/dist/components/utility/copy-button/copy-button.class.js +3 -3
- package/dist/components/utility/copy-button/copy-button.styles.js +1 -1
- package/dist/components/utility/tour/tour.class.d.ts +2 -2
- package/dist/components/utility/tour/tour.class.js +1 -1
- package/dist/events.d.ts +10 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/modal-host.styles.js +1 -0
- package/dist/internal/modal-surface-controller.js +1 -1
- package/dist/internal/overlay-stack.d.ts +1 -1
- package/dist/internal/overlay-stack.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/internal/style-property-lease.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/llms/components/lr-app-rail.md +4 -0
- package/llms/components/lr-badge.md +3 -0
- package/llms/components/lr-copy-button.md +15 -7
- package/llms/components/lr-file-input.md +5 -0
- package/llms/components/lr-map.md +80 -8
- package/llms/components/lr-mcp-app.md +94 -4
- package/llms/components/lr-message-parts.md +18 -0
- package/llms/components/lr-multi-split.md +4 -0
- package/llms/components/lr-page.md +5 -1
- package/llms/components/lr-responsive-panel.md +5 -1
- package/llms/components/lr-select.md +3 -2
- package/llms/components/lr-token-input.md +4 -3
- package/llms/components/lr-tooltip.md +4 -4
- package/llms/peers.md +1 -1
- package/llms/shared/ai-and-peers.md +88 -3
- package/llms/shared/events-and-types.md +25 -1
- package/llms/shared/localization-and-rtl.md +29 -0
- package/llms/shared/styles-and-tokens.md +75 -14
- package/llms/shared.md +217 -18
- package/locales.json +1 -1
- package/package.json +8 -4
- package/registrations.json +1 -1
- package/skills/compose-lyra-interfaces/SKILL.md +5 -3
- package/skills/compose-lyra-interfaces/references/composition-patterns.md +8 -1
- package/skills/lyra-ui/SKILL.md +17 -8
- package/skills/lyra-ui/lyra-gen.md +95 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,92 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 30.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- fea5203: Add the shared optional size ladder to copy buttons. Keep viewport modals above ancestor stacking contexts and preserve their visual order across reconnects. Avoid redundant layout measurements and stale navigation-menu resize callbacks, and correct tooltip, sizing, and theme-contrast documentation.
|
|
8
|
+
|
|
9
|
+
Shared modal ordering and exit handling, allocation-preserving drawers, and copy-button sizing add runtime code; their required guides and generated editor data increase archive sizes. Only exceeded bundle and archive ceilings advance to the next 64-byte boundary after composition review; passing limits, measurement inputs and the UI download cap remain unchanged.
|
|
10
|
+
|
|
11
|
+
Make panorama pause-ownership qualification handle native callback delivery before the queued pause event, with deterministic coverage of both event orders.
|
|
12
|
+
|
|
13
|
+
Two compatible seven-sample Chromium quick comparisons against 30.3.0, run in opposite orders, retained 21 and 12 timing threshold exceedances. The second pair measured 10,000-row assignment median total time at 27.2 to 40.0 ms and chart-assignment p95 at 110.5 to 178.5 ms. All semantic checks and recorded work counts matched. Causes remain unresolved; neither pair is a performance pass. These advisory findings remain separate from passing preliminary hosted A/B qualification.
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- @aceshooting/lyra-translations@30.4.0
|
|
18
|
+
|
|
19
|
+
## 30.3.0
|
|
20
|
+
|
|
21
|
+
### Minor Changes
|
|
22
|
+
|
|
23
|
+
- 0d840bd: Add explicit widget registry and binding-state passthrough to message parts, preserve widget
|
|
24
|
+
identity during sibling text updates, and load non-text part renderers on demand. Correct the
|
|
25
|
+
structural A2UI-like helper's binding-state result and extend AG-UI reasoning/activity/custom
|
|
26
|
+
mapping with host-controlled custom-event destinations.
|
|
27
|
+
|
|
28
|
+
Add an opt-in official MCP Apps host transport with negotiated capabilities, bounded requests,
|
|
29
|
+
resource policy, cancellation and teardown alongside the existing default bridge. Incremental
|
|
30
|
+
text-delta accounting preserves untouched payload identities and handles UTF-8 surrogate joins
|
|
31
|
+
without repeatedly scanning retained message data. Support and qualification boundaries are
|
|
32
|
+
documented with the corresponding APIs.
|
|
33
|
+
|
|
34
|
+
The seven-sample quick Chromium comparison with 30.2.0 recorded eight advisory timing regressions
|
|
35
|
+
across table assignment, chart assignment and combobox metadata. Table update median increased
|
|
36
|
+
from 5.9 to 7.4 ms, while total median decreased from 28.1 to 27.7 ms; total p95 increased from
|
|
37
|
+
28.5 to 41.4 ms. The affected module closures and theme bytes are unchanged, and functional
|
|
38
|
+
assertions and bounded-work counts pass. Phase redistribution and isolated slow samples contribute
|
|
39
|
+
to these observations; their cause remains unresolved, so no runtime speedup is claimed.
|
|
40
|
+
- c3b40ec: Expose map control container, corner, native icon and attribution-link parts, geolocation state
|
|
41
|
+
parts and expanded-attribution styling hooks. Add `--lr-map-scale-bar-display` to hide the scale
|
|
42
|
+
ruler independently of its distance text. Control option objects now accept finite `order`
|
|
43
|
+
values to keep visual and keyboard order aligned while retaining existing controls.
|
|
44
|
+
Use theme-aware SVG control icons while preserving native compass rotation, and give attribution
|
|
45
|
+
links a 24px minimum target size.
|
|
46
|
+
|
|
47
|
+
Add `whenControlsReady()` for installed native controls and synchronized chrome, and expose
|
|
48
|
+
initialization skeleton, label and control-corner parts so deferred maps can share control styling.
|
|
49
|
+
Independent top and bottom rows and expanded-attribution container tokens support responsive layouts.
|
|
50
|
+
|
|
51
|
+
The map layout/readiness helpers, icons and public references increase the media bundle to
|
|
52
|
+
350,928 gzip bytes and the UI archive to 21,969,742 unpacked bytes. Advance only exceeded media,
|
|
53
|
+
UI and editor byte ceilings to the next 64-byte boundary; retain all passing limits and file ceilings.
|
|
54
|
+
|
|
55
|
+
The tiled map scale DOM ceiling increases from 15 to 17 for the two fixed control-row wrappers;
|
|
56
|
+
all data-dependent scale ceilings remain unchanged. The tile test verifies both rows are reused
|
|
57
|
+
across camera moves and overlay updates.
|
|
58
|
+
|
|
59
|
+
### Patch Changes
|
|
60
|
+
|
|
61
|
+
- 0d840bd: Preserve keyboard scroll intent through native smooth scrolling so Home, PageUp and upward arrow
|
|
62
|
+
navigation can release chat following. Clear obsolete intent after settlement, cancellation,
|
|
63
|
+
focus changes and explicit scroll commands, including virtual conversations. Prevented keys and
|
|
64
|
+
editing controls retain their native behavior.
|
|
65
|
+
- 0d840bd: Keep file-input labels, selected files and feedback inside intrinsically sized grid rows. Definite-height drop targets allocate the remaining space to the picker after the rest of the field content.
|
|
66
|
+
- 0d840bd: Add measured Gen bundle and archive limits for parser, runtime, chat, generated views and chat
|
|
67
|
+
composition. JavaScript permits 2% headroom, CSS 4%, and assets none; external optional peers
|
|
68
|
+
remain listed separately. Archive increases use the next 64-byte boundary.
|
|
69
|
+
|
|
70
|
+
Widgets, MCP Apps, chat scroll intent, public type exports, documentation and seven Gen messages
|
|
71
|
+
across all 70 locale catalogs increase UI, editor and translation bytes. Raise only exceeded
|
|
72
|
+
ceilings; retain passing limits, the download ceiling, historical reduction rule and file inventories.
|
|
73
|
+
|
|
74
|
+
Navigation and server/client examples, catalog and adapter guides, CLI presets and the candidate
|
|
75
|
+
adapter correction increase Gen to 140 public files. Set its archive byte ceilings to the next
|
|
76
|
+
64-byte boundary. Interactive select validation adds 57 gzip bytes over its reviewed measurement; advance
|
|
77
|
+
only its exceeded direct-entry ceiling to the next 64-byte boundary.
|
|
78
|
+
|
|
79
|
+
Reviewed 2026-10-26: Gen measures 206,707 packed / 770,450 unpacked bytes across 140 files.
|
|
80
|
+
Set its ceilings to 206,720 / 770,496 bytes. The latest growth is the SDK 7 integration guide
|
|
81
|
+
and initial release notes; runtime entries, file count and other passing limits stay unchanged.
|
|
82
|
+
- 0d840bd: Include generated-view status and action messages in every conversation locale catalog, retain
|
|
83
|
+
per-instance overrides, and update loaded MCP app locale and direction context without replacing
|
|
84
|
+
its frame. Locale changes during official app initialization are retained until the app is ready.
|
|
85
|
+
- 3d5644c: Expose a required select's invalid state after native form submission or `reportValidity()`,
|
|
86
|
+
including its accessible state and error styling. Silent validity checks keep pristine controls
|
|
87
|
+
unchanged, and resetting the form restores that state.
|
|
88
|
+
- @aceshooting/lyra-translations@30.3.0
|
|
89
|
+
|
|
3
90
|
## 30.2.0
|
|
4
91
|
|
|
5
92
|
### Minor Changes
|
|
@@ -1,6 +1,12 @@
|
|
|
1
|
-
import type{LyraWidgetDocument}from'../../components/conversation/widget-renderer/resolve.js';import{type ProviderSnapshotLimits}from'../snapshot.js';export interface A2UiLikeAction{id:string;payload?:unknown;}export interface A2UiLikeComponent{id:string;type:string;props?:Record<string,unknown>;text?:string;children?:string[];action?:A2UiLikeAction;}export interface A2UiLikeSurface{surfaceId?:string;rootId:string;components:A2UiLikeComponent[];data?:unknown;}
|
|
1
|
+
import type{LyraWidgetDocument}from'../../components/conversation/widget-renderer/resolve.js';import{type ProviderSnapshotLimits}from'../snapshot.js';export interface A2UiLikeAction{id:string;payload?:unknown;}export interface A2UiLikeComponent{id:string;type:string;props?:Record<string,unknown>;text?:string;children?:string[];action?:A2UiLikeAction;}export interface A2UiLikeSurface{surfaceId?:string;rootId:string;components:A2UiLikeComponent[];data?:unknown;}
|
|
2
|
+
/** A widget-compatible helper result. Assign `bindingState` separately to the renderer.*/
|
|
3
|
+
export interface A2UiAdapterResult extends LyraWidgetDocument{readonly bindingState?:unknown;
|
|
4
|
+
/** Compatibility alias for the helper's original state field; renderers do not read it.*/
|
|
5
|
+
readonly state?:unknown;}export type A2UiTypeMap=Readonly<Record<string,string>>;export interface A2UiAdapterLimits extends ProviderSnapshotLimits{maxComponents:number;maxDepth:number;maxOutputNodes:number;maxChildrenPerComponent:number;}export declare const DEFAULT_A2UI_ADAPTER_LIMITS:Readonly<A2UiAdapterLimits>;
|
|
2
6
|
/**
|
|
3
|
-
* Maps a
|
|
4
|
-
* document.
|
|
7
|
+
* Maps a limited A2UI-like structural component graph into Lyra's versioned, allowlisted widget
|
|
8
|
+
* document. This helper does not process native A2UI protocol messages or surface lifecycles.
|
|
9
|
+
* Assign the returned `bindingState` to the renderer's separate controlled-state property.
|
|
10
|
+
* Input, child-cardinality, traversal, and output budgets fail closed as `null`.
|
|
5
11
|
*/
|
|
6
|
-
export declare function adaptA2UiSurface(surface:unknown,typeMap:unknown,limits?:Partial<A2UiAdapterLimits>):
|
|
12
|
+
export declare function adaptA2UiSurface(surface:unknown,typeMap:unknown,limits?:Partial<A2UiAdapterLimits>):A2UiAdapterResult|null;
|
package/dist/ai/adapters/a2ui.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{positiveInteger}from"../../internal/numbers.js";import{createProviderSnapshotBudget,resolveProviderSnapshotLimits,snapshotProviderValue}from"../snapshot.js";const DEFAULT_A2UI_ADAPTER_LIMITS=Object.freeze({...resolveProviderSnapshotLimits({maxDepth:40,maxNodes:1e5,maxBytes:8388608}),maxComponents:5e3,maxDepth:32,maxOutputNodes:5e3,maxChildrenPerComponent:1e3});function resolveLimits(limits){const snapshot=resolveProviderSnapshotLimits({maxDepth:limits.maxDepth??DEFAULT_A2UI_ADAPTER_LIMITS.maxDepth,maxNodes:limits.maxNodes??DEFAULT_A2UI_ADAPTER_LIMITS.maxNodes,maxBytes:limits.maxBytes??DEFAULT_A2UI_ADAPTER_LIMITS.maxBytes,maxStringCharacters:limits.maxStringCharacters??DEFAULT_A2UI_ADAPTER_LIMITS.maxStringCharacters});return Object.freeze({...snapshot,maxComponents:positiveInteger(limits.maxComponents,DEFAULT_A2UI_ADAPTER_LIMITS.maxComponents),maxDepth:positiveInteger(limits.maxDepth,DEFAULT_A2UI_ADAPTER_LIMITS.maxDepth),maxOutputNodes:positiveInteger(limits.maxOutputNodes,DEFAULT_A2UI_ADAPTER_LIMITS.maxOutputNodes),maxChildrenPerComponent:positiveInteger(limits.maxChildrenPerComponent,DEFAULT_A2UI_ADAPTER_LIMITS.maxChildrenPerComponent)})}function record(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function componentRecord(value,limits){const component=record(value);if(!component||typeof component.id!="string"||typeof component.type!="string"||component.props!==void 0&&!record(component.props)||component.text!==void 0&&typeof component.text!="string"||component.children!==void 0&&(!Array.isArray(component.children)||component.children.length>limits.maxChildrenPerComponent||!component.children.every(child=>typeof child=="string")))return null;if(component.action!==void 0){const action=record(component.action);if(!action||typeof action.id!="string")return null}return component}function adaptA2UiSurface(surface,typeMap,limits={}){const resolved=resolveLimits(limits),budget=createProviderSnapshotBudget(resolved),ownedSurface=snapshotProviderValue(surface,budget);if(!ownedSurface.ok)return null;const source=record(ownedSurface.value);if(!source||typeof source.rootId!="string"||!Array.isArray(source.components)||source.components.length>resolved.maxComponents)return null;const ownedTypeMap=snapshotProviderValue(typeMap,budget),mappedTypes=ownedTypeMap.ok?record(ownedTypeMap.value):null;if(!mappedTypes||!Object.values(mappedTypes).every(value=>typeof value=="string"))return null;const byId=new Map;for(const value of source.components){const component=componentRecord(value,resolved);if(!component||byId.has(component.id))return null;byId.set(component.id,component)}let remainingOutputNodes=resolved.maxOutputNodes,outputLimitExceeded=!1;const reserveOutputNode=()=>remainingOutputNodes<=0?(outputLimitExceeded=!0,!1):(remainingOutputNodes-=1,!0),visit=(id,depth,ancestors)=>{if(depth>resolved.maxDepth||ancestors.has(id)||outputLimitExceeded)return null;const component=byId.get(id);if(!component)return null;const mappedType=mappedTypes[component.type];if(typeof mappedType!="string"||!mappedType||!reserveOutputNode())return null;const nextAncestors=new Set(ancestors);nextAncestors.add(id);const children=[];for(const childId of component.children??[]){if(outputLimitExceeded)break;const child=visit(childId,depth+1,nextAncestors);child&&children.push(child)}if(component.text){if(!reserveOutputNode())return null;children.unshift({type:"text",props:{value:component.text}})}return{id:component.id,type:mappedType,...component.props?{props:component.props}:{},...children.length?{children}:{},...component.action?{actionId:component.action.id,...Object.hasOwn(component.action,"payload")?{payload:component.action.payload}:{}}:{}}},root=visit(source.rootId,0,new Set);return!root||outputLimitExceeded?null:{version:"2",root,...Object.hasOwn(source,"data")?{state:source.data}:{}}}export{DEFAULT_A2UI_ADAPTER_LIMITS,adaptA2UiSurface};
|
|
1
|
+
import{positiveInteger}from"../../internal/numbers.js";import{createProviderSnapshotBudget,resolveProviderSnapshotLimits,snapshotProviderValue}from"../snapshot.js";const DEFAULT_A2UI_ADAPTER_LIMITS=Object.freeze({...resolveProviderSnapshotLimits({maxDepth:40,maxNodes:1e5,maxBytes:8388608}),maxComponents:5e3,maxDepth:32,maxOutputNodes:5e3,maxChildrenPerComponent:1e3});function resolveLimits(limits){const snapshot=resolveProviderSnapshotLimits({maxDepth:limits.maxDepth??DEFAULT_A2UI_ADAPTER_LIMITS.maxDepth,maxNodes:limits.maxNodes??DEFAULT_A2UI_ADAPTER_LIMITS.maxNodes,maxBytes:limits.maxBytes??DEFAULT_A2UI_ADAPTER_LIMITS.maxBytes,maxStringCharacters:limits.maxStringCharacters??DEFAULT_A2UI_ADAPTER_LIMITS.maxStringCharacters});return Object.freeze({...snapshot,maxComponents:positiveInteger(limits.maxComponents,DEFAULT_A2UI_ADAPTER_LIMITS.maxComponents),maxDepth:positiveInteger(limits.maxDepth,DEFAULT_A2UI_ADAPTER_LIMITS.maxDepth),maxOutputNodes:positiveInteger(limits.maxOutputNodes,DEFAULT_A2UI_ADAPTER_LIMITS.maxOutputNodes),maxChildrenPerComponent:positiveInteger(limits.maxChildrenPerComponent,DEFAULT_A2UI_ADAPTER_LIMITS.maxChildrenPerComponent)})}function record(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function componentRecord(value,limits){const component=record(value);if(!component||typeof component.id!="string"||typeof component.type!="string"||component.props!==void 0&&!record(component.props)||component.text!==void 0&&typeof component.text!="string"||component.children!==void 0&&(!Array.isArray(component.children)||component.children.length>limits.maxChildrenPerComponent||!component.children.every(child=>typeof child=="string")))return null;if(component.action!==void 0){const action=record(component.action);if(!action||typeof action.id!="string")return null}return component}function adaptA2UiSurface(surface,typeMap,limits={}){const resolved=resolveLimits(limits),budget=createProviderSnapshotBudget(resolved),ownedSurface=snapshotProviderValue(surface,budget);if(!ownedSurface.ok)return null;const source=record(ownedSurface.value);if(!source||typeof source.rootId!="string"||!Array.isArray(source.components)||source.components.length>resolved.maxComponents)return null;const ownedTypeMap=snapshotProviderValue(typeMap,budget),mappedTypes=ownedTypeMap.ok?record(ownedTypeMap.value):null;if(!mappedTypes||!Object.values(mappedTypes).every(value=>typeof value=="string"))return null;const byId=new Map;for(const value of source.components){const component=componentRecord(value,resolved);if(!component||byId.has(component.id))return null;byId.set(component.id,component)}let remainingOutputNodes=resolved.maxOutputNodes,outputLimitExceeded=!1;const reserveOutputNode=()=>remainingOutputNodes<=0?(outputLimitExceeded=!0,!1):(remainingOutputNodes-=1,!0),visit=(id,depth,ancestors)=>{if(depth>resolved.maxDepth||ancestors.has(id)||outputLimitExceeded)return null;const component=byId.get(id);if(!component)return null;const mappedType=mappedTypes[component.type];if(typeof mappedType!="string"||!mappedType||!reserveOutputNode())return null;const nextAncestors=new Set(ancestors);nextAncestors.add(id);const children=[];for(const childId of component.children??[]){if(outputLimitExceeded)break;const child=visit(childId,depth+1,nextAncestors);child&&children.push(child)}if(component.text){if(!reserveOutputNode())return null;children.unshift({type:"text",props:{value:component.text}})}return{id:component.id,type:mappedType,...component.props?{props:component.props}:{},...children.length?{children}:{},...component.action?{actionId:component.action.id,...Object.hasOwn(component.action,"payload")?{payload:component.action.payload}:{}}:{}}},root=visit(source.rootId,0,new Set);return!root||outputLimitExceeded?null:{version:"2",root,...Object.hasOwn(source,"data")?{bindingState:source.data,state:source.data}:{}}}export{DEFAULT_A2UI_ADAPTER_LIMITS,adaptA2UiSurface};
|
|
@@ -1,5 +1,18 @@
|
|
|
1
|
-
import{type AgentStreamEvent}from'../runtime.js';import{type ProviderSnapshotLimits}from'../snapshot.js';export interface AgUiLikeEvent{type:string;eventId?:string;runId?:string;messageId?:string;role?:string;delta?:unknown;toolCallId?:string;toolCallName?:string;result?:unknown;message?:string;code?:string;snapshot?:unknown;messages?:unknown[];
|
|
2
|
-
/**
|
|
3
|
-
export
|
|
1
|
+
import{type AgentStreamEvent}from'../runtime.js';import{type ProviderSnapshotLimits}from'../snapshot.js';export interface AgUiLikeEvent{type:string;eventId?:string;runId?:string;messageId?:string;role?:string;delta?:unknown;toolCallId?:string;toolCallName?:string;result?:unknown;message?:string;code?:string;snapshot?:unknown;messages?:unknown[];name?:string;value?:unknown;activityType?:string;content?:unknown;replace?:boolean;patch?:unknown[];}
|
|
2
|
+
/** Application-defined data carried by an AG-UI CUSTOM event.*/
|
|
3
|
+
export interface AgUiCustomEvent{name:string;value:unknown;}
|
|
4
|
+
/** Host-owned identities for a custom data part; repeated targets replace that part.*/
|
|
5
|
+
export interface AgUiCustomEventTarget{messageId:string;partId:string;}export interface AgUiAdapterOptions{
|
|
6
|
+
/** Opts a custom event into named data rendering. Omitted or null ignores the event.*/
|
|
7
|
+
customEventTarget?:(event:AgUiCustomEvent)=>AgUiCustomEventTarget|null;}export interface AgUiAdapterLimits extends ProviderSnapshotLimits{maxBufferedTools:number;
|
|
8
|
+
/** Maximum retained message identities, including activity patch baselines.*/
|
|
9
|
+
maxBufferedMessages:number;maxToolArgumentBytes:number;maxTextDeltaCharacters:number;}export declare const DEFAULT_AG_UI_ADAPTER_LIMITS:Readonly<AgUiAdapterLimits>;
|
|
10
|
+
/**
|
|
11
|
+
* Stateful, bounded mapper from AG-UI records to provider-neutral stream events.
|
|
12
|
+
* Visible reasoning uses reasoning parts; activity and opted-in custom events use named data parts.
|
|
13
|
+
* Compact chunks require upstream expansion. Phase, encrypted, raw, step, subagent, deprecated
|
|
14
|
+
* thinking and unknown events are ignored; custom events require explicit host routing.
|
|
15
|
+
*/
|
|
16
|
+
export declare class AgUiStreamAdapter{private readonly tools;private readonly messages;private readonly activities;private activityBytes;private readonly limits;private readonly customEventTarget;private generation;private sequence;constructor(limits?:Partial<AgUiAdapterLimits>,options?:AgUiAdapterOptions);get bufferedToolCount():number;
|
|
4
17
|
/** Clears buffers and returns the matching reducer reset boundary.*/
|
|
5
|
-
reset():AgentStreamEvent;private emit;private failure;private toolInvocation;push(event:unknown):AgentStreamEvent[];}
|
|
18
|
+
reset():AgentStreamEvent;private clearBuffers;private claimMessage;private activity;private emit;private failure;private toolInvocation;push(event:unknown):AgentStreamEvent[];}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseJsonPatch}from"../runtime.js";import{positiveInteger}from"../../internal/numbers.js";import{createProviderSnapshotBudget,resolveProviderSnapshotLimits,snapshotProviderValue}from"../snapshot.js";const DEFAULT_AG_UI_ADAPTER_LIMITS=Object.freeze({...resolveProviderSnapshotLimits(),maxBufferedTools:256,maxToolArgumentBytes:262144,maxTextDeltaCharacters:32768}),encoder=new TextEncoder;function resolveLimits(limits){return Object.freeze({...resolveProviderSnapshotLimits(limits),maxBufferedTools:positiveInteger(limits.maxBufferedTools,DEFAULT_AG_UI_ADAPTER_LIMITS.maxBufferedTools),maxToolArgumentBytes:positiveInteger(limits.maxToolArgumentBytes,DEFAULT_AG_UI_ADAPTER_LIMITS.maxToolArgumentBytes),maxTextDeltaCharacters:positiveInteger(limits.maxTextDeltaCharacters,DEFAULT_AG_UI_ADAPTER_LIMITS.maxTextDeltaCharacters)})}function record(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function safeType(value){if(record(value))try{const descriptor=Object.getOwnPropertyDescriptor(value,"type");return descriptor&&"value"in descriptor&&typeof descriptor.value=="string"?descriptor.value:void 0}catch{return}}function role(value){return value==="user"||value==="system"?value:"assistant"}function objectArgs(text,limits){try{const parsed=JSON.parse(text),owned=snapshotProviderValue(parsed,createProviderSnapshotBudget(limits));return owned.ok?record(owned.value):null}catch{return null}}function snapshotMessage(value,index){const source=record(value);if(!source)return null;const id=typeof source.id=="string"?source.id:`snapshot-${index}`,content=typeof source.content=="string"?source.content:"";return{id,role:role(source.role),status:"sent",parts:content?[{id:`${id}:text`,type:"text",text:content,state:"complete"}]:[]}}class AgUiStreamAdapter{constructor(limits={}){this.tools=new Map,this.generation=0,this.sequence=0,this.limits=resolveLimits(limits)}get bufferedToolCount(){return this.tools.size}reset(){return this.tools.clear(),this.generation+=1,this.sequence=0,this.emit({type:"reset"})}emit(event,eventId,suffix){this.sequence+=1;const correlatedId=eventId&&suffix?`${eventId}:${suffix}`:eventId;return{...event,generation:this.generation,sequence:this.sequence,...correlatedId?{eventId:correlatedId}:{}}}failure(message,code){return[this.emit({type:"error",message,code})]}toolInvocation(toolCallId,status){const buffer=this.tools.get(toolCallId)??{name:"tool",argsText:"",argsBytes:0,args:{}};return{id:toolCallId,name:buffer.name,args:buffer.args,status}}push(event){const eventType=safeType(event);if(!eventType)return[];const owned=snapshotProviderValue(event,createProviderSnapshotBudget(this.limits));if(!owned.ok)return this.failure(owned.failure==="limit"?"Provider event exceeds the configured adapter limit.":"Provider event is not serializable data.",owned.failure==="limit"?"stream_limit_exceeded":"invalid_provider_event");const source=record(owned.value);if(!source||source.type!==eventType)return[];const eventId=typeof source.eventId=="string"?source.eventId:void 0;switch(eventType){case"RUN_STARTED":return typeof source.runId!="string"||!source.runId?[]:(this.tools.clear(),this.generation+=1,this.sequence=0,[this.emit({type:"run-start",runId:source.runId},eventId)]);case"RUN_FINISHED":{if(source.runId!==void 0&&typeof source.runId!="string")return[];const output=this.emit({type:"run-status",...source.runId?{runId:source.runId}:{},status:{kind:"done"}},eventId);return this.tools.clear(),[output]}case"RUN_ERROR":{if(source.message!==void 0&&typeof source.message!="string")return[];if(source.code!==void 0&&typeof source.code!="string")return[];if(source.runId!==void 0&&typeof source.runId!="string")return[];const message=source.message??"Agent run failed",code=source.code,output=[this.emit({type:"error",message,...code?{code}:{}},eventId,"error"),this.emit({type:"run-status",...source.runId?{runId:source.runId}:{},status:{kind:"error",message}},eventId,"status")];return this.tools.clear(),output}case"TEXT_MESSAGE_START":return typeof source.messageId=="string"?[this.emit({type:"message-start",message:{id:source.messageId,role:role(source.role),status:"streaming",parts:[]}},eventId)]:[];case"TEXT_MESSAGE_CONTENT":return typeof source.messageId!="string"||typeof source.delta!="string"?[]:source.delta.length>this.limits.maxTextDeltaCharacters?this.failure("Text delta exceeds the configured adapter limit.","stream_limit_exceeded"):[this.emit({type:"message-part-delta",messageId:source.messageId,role:role(source.role),partId:`${source.messageId}:text`,partType:"text",delta:source.delta},eventId)];case"TEXT_MESSAGE_END":return typeof source.messageId=="string"?[this.emit({type:"message-complete",messageId:source.messageId},eventId)]:[];case"TOOL_CALL_START":return typeof source.toolCallId!="string"?[]:!this.tools.has(source.toolCallId)&&this.tools.size>=this.limits.maxBufferedTools?this.failure("Buffered tool count exceeds the configured adapter limit.","stream_limit_exceeded"):source.toolCallName!==void 0&&typeof source.toolCallName!="string"?[]:(this.tools.set(source.toolCallId,{name:source.toolCallName??"tool",argsText:"",argsBytes:0,args:{}}),[this.emit({type:"tool-upsert",invocation:this.toolInvocation(source.toolCallId,"running")},eventId)]);case"TOOL_CALL_ARGS":{if(typeof source.toolCallId!="string"||typeof source.delta!="string")return[];let buffer=this.tools.get(source.toolCallId);if(!buffer){if(this.tools.size>=this.limits.maxBufferedTools)return this.failure("Buffered tool count exceeds the configured adapter limit.","stream_limit_exceeded");buffer={name:"tool",argsText:"",argsBytes:0,args:{}}}const deltaBytes=encoder.encode(source.delta).byteLength;return deltaBytes>this.limits.maxToolArgumentBytes-buffer.argsBytes?(this.tools.delete(source.toolCallId),this.failure("Tool arguments exceed the configured adapter limit.","stream_limit_exceeded")):(buffer.argsText+=source.delta,buffer.argsBytes+=deltaBytes,buffer.args=objectArgs(buffer.argsText,this.limits)??buffer.args,this.tools.set(source.toolCallId,buffer),[this.emit({type:"tool-upsert",invocation:this.toolInvocation(source.toolCallId,"running")},eventId)])}case"TOOL_CALL_END":{if(typeof source.toolCallId!="string")return[];const invocation=this.toolInvocation(source.toolCallId,"running"),buffer=this.tools.get(source.toolCallId);return buffer&&(buffer.argsText="",buffer.argsBytes=0),[this.emit({type:"tool-upsert",invocation},eventId)]}case"TOOL_CALL_RESULT":{if(typeof source.toolCallId!="string")return[];const invocation={...this.toolInvocation(source.toolCallId,"success"),...Object.hasOwn(source,"result")?{result:source.result}:{}};return this.tools.delete(source.toolCallId),[this.emit({type:"tool-upsert",invocation},eventId)]}case"STATE_SNAPSHOT":return Object.hasOwn(source,"snapshot")?[this.emit({type:"state-snapshot",snapshot:source.snapshot},eventId)]:[];case"STATE_DELTA":{const patch=parseJsonPatch(source.delta);return patch?[this.emit({type:"state-delta",patch},eventId)]:[]}case"MESSAGES_SNAPSHOT":return source.messages!==void 0&&!Array.isArray(source.messages)?[]:[this.emit({type:"messages-snapshot",messages:(source.messages??[]).map(snapshotMessage).filter(message=>message!==null)},eventId)];default:return[]}}}export{AgUiStreamAdapter,DEFAULT_AG_UI_ADAPTER_LIMITS};
|
|
1
|
+
import{applySharedStatePatch,parseJsonPatch}from"../runtime.js";import{positiveInteger}from"../../internal/numbers.js";import{createProviderSnapshotBudget,resolveProviderSnapshotLimits,snapshotProviderValue}from"../snapshot.js";const DEFAULT_AG_UI_ADAPTER_LIMITS=Object.freeze({...resolveProviderSnapshotLimits(),maxBufferedTools:256,maxBufferedMessages:512,maxToolArgumentBytes:262144,maxTextDeltaCharacters:32768}),encoder=new TextEncoder;function resolveLimits(limits){return Object.freeze({...resolveProviderSnapshotLimits(limits),maxBufferedTools:positiveInteger(limits.maxBufferedTools,DEFAULT_AG_UI_ADAPTER_LIMITS.maxBufferedTools),maxBufferedMessages:positiveInteger(limits.maxBufferedMessages,DEFAULT_AG_UI_ADAPTER_LIMITS.maxBufferedMessages),maxToolArgumentBytes:positiveInteger(limits.maxToolArgumentBytes,DEFAULT_AG_UI_ADAPTER_LIMITS.maxToolArgumentBytes),maxTextDeltaCharacters:positiveInteger(limits.maxTextDeltaCharacters,DEFAULT_AG_UI_ADAPTER_LIMITS.maxTextDeltaCharacters)})}function record(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function safeType(value){if(record(value))try{const descriptor=Object.getOwnPropertyDescriptor(value,"type");return descriptor&&"value"in descriptor&&typeof descriptor.value=="string"?descriptor.value:void 0}catch{return}}function role(value){return value==="user"||value==="system"?value:"assistant"}function objectArgs(text,limits){try{const parsed=JSON.parse(text),owned=snapshotProviderValue(parsed,createProviderSnapshotBudget(limits));return owned.ok?record(owned.value):null}catch{return null}}function snapshotMessage(value,index){const source=record(value);if(!source)return null;const id=typeof source.id=="string"?source.id:`snapshot-${index}`,content=typeof source.content=="string"?source.content:"";if(source.role==="activity")return typeof source.activityType!="string"||!source.activityType||!record(source.content)?null:{id,role:"assistant",status:"sent",parts:[{id:`${id}:activity`,type:"data",name:source.activityType,data:source.content,state:"complete"}]};const partType=source.role==="reasoning"?"reasoning":"text";return{id,role:role(source.role),status:"sent",parts:content?[{id:`${id}:${partType}`,type:partType,text:content,state:"complete"}]:[]}}class AgUiStreamAdapter{constructor(limits={},options={}){this.tools=new Map,this.messages=new Map,this.activities=new Map,this.activityBytes=0,this.generation=0,this.sequence=0,this.limits=resolveLimits(limits),this.customEventTarget=options.customEventTarget}get bufferedToolCount(){return this.tools.size}reset(){return this.clearBuffers(),this.generation+=1,this.sequence=0,this.emit({type:"reset"})}clearBuffers(){this.tools.clear(),this.messages.clear(),this.activities.clear(),this.activityBytes=0}claimMessage(messageId,kind){const previous=this.messages.get(messageId);return previous&&kind==="custom"?null:previous==="custom"&&kind!=="activity"?(this.messages.set(messageId,kind),null):previous&&previous!==kind?[]:!previous&&this.messages.size>=this.limits.maxBufferedMessages?this.failure("Buffered message count exceeds the configured adapter limit.","stream_limit_exceeded"):(this.messages.set(messageId,kind),null)}activity(messageId,activityType,content,eventId){const snapshot=snapshotProviderValue(content,createProviderSnapshotBudget(this.limits));if(!snapshot.ok)return this.failure("Activity content exceeds the configured adapter limit.","stream_limit_exceeded");const data=record(snapshot.value);if(!data)return[];const previous=this.activities.get(messageId),bytes=this.activityBytes-(previous?.bytes??0)+snapshot.bytes;if(bytes>this.limits.maxBytes)return this.failure("Buffered activity content exceeds the configured adapter limit.","stream_limit_exceeded");const rejected=this.claimMessage(messageId,"activity");return rejected||(this.activities.set(messageId,{activityType,content:data,bytes:snapshot.bytes}),this.activityBytes=bytes,[this.emit({type:"message-part-upsert",messageId,role:"assistant",part:{id:`${messageId}:activity`,type:"data",name:activityType,data:content,state:"complete"}},eventId)])}emit(event,eventId,suffix){this.sequence+=1;const correlatedId=eventId&&suffix?`${eventId}:${suffix}`:eventId;return{...event,generation:this.generation,sequence:this.sequence,...correlatedId?{eventId:correlatedId}:{}}}failure(message,code){return[this.emit({type:"error",message,code})]}toolInvocation(toolCallId,status){const buffer=this.tools.get(toolCallId)??{name:"tool",argsText:"",argsBytes:0,args:{}};return{id:toolCallId,name:buffer.name,args:buffer.args,status}}push(event){const eventType=safeType(event);if(!eventType)return[];const owned=snapshotProviderValue(event,createProviderSnapshotBudget(this.limits));if(!owned.ok)return this.failure(owned.failure==="limit"?"Provider event exceeds the configured adapter limit.":"Provider event is not serializable data.",owned.failure==="limit"?"stream_limit_exceeded":"invalid_provider_event");const source=record(owned.value);if(!source||source.type!==eventType)return[];const eventId=typeof source.eventId=="string"?source.eventId:void 0;switch(eventType){case"RUN_STARTED":return typeof source.runId!="string"||!source.runId?[]:(this.clearBuffers(),this.generation+=1,this.sequence=0,[this.emit({type:"run-start",runId:source.runId},eventId)]);case"RUN_FINISHED":{if(source.runId!==void 0&&typeof source.runId!="string")return[];const output=this.emit({type:"run-status",...source.runId?{runId:source.runId}:{},status:{kind:"done"}},eventId);return this.clearBuffers(),[output]}case"RUN_ERROR":{if(source.message!==void 0&&typeof source.message!="string")return[];if(source.code!==void 0&&typeof source.code!="string")return[];if(source.runId!==void 0&&typeof source.runId!="string")return[];const message=source.message??"Agent run failed",code=source.code,output=[this.emit({type:"error",message,...code?{code}:{}},eventId,"error"),this.emit({type:"run-status",...source.runId?{runId:source.runId}:{},status:{kind:"error",message}},eventId,"status")];return this.clearBuffers(),output}case"TEXT_MESSAGE_START":case"REASONING_MESSAGE_START":{if(typeof source.messageId!="string"||!source.messageId)return[];const reasoning=eventType==="REASONING_MESSAGE_START",rejected=this.claimMessage(source.messageId,reasoning?"reasoning":"text");return rejected||[this.emit({type:"message-start",message:{id:source.messageId,role:reasoning?"assistant":role(source.role),status:"streaming",parts:[]}},eventId)]}case"TEXT_MESSAGE_CONTENT":case"REASONING_MESSAGE_CONTENT":{if(typeof source.messageId!="string"||!source.messageId||typeof source.delta!="string")return[];if(source.delta.length>this.limits.maxTextDeltaCharacters)return this.failure("Text delta exceeds the configured adapter limit.","stream_limit_exceeded");const partType=eventType==="REASONING_MESSAGE_CONTENT"?"reasoning":"text",rejected=this.claimMessage(source.messageId,partType);return rejected||[this.emit({type:"message-part-delta",messageId:source.messageId,role:partType==="reasoning"?"assistant":role(source.role),partId:`${source.messageId}:${partType}`,partType,delta:source.delta},eventId)]}case"TEXT_MESSAGE_END":case"REASONING_MESSAGE_END":return typeof source.messageId!="string"||!source.messageId?[]:this.claimMessage(source.messageId,eventType==="REASONING_MESSAGE_END"?"reasoning":"text")??[this.emit({type:"message-complete",messageId:source.messageId},eventId)];case"TOOL_CALL_START":return typeof source.toolCallId!="string"?[]:!this.tools.has(source.toolCallId)&&this.tools.size>=this.limits.maxBufferedTools?this.failure("Buffered tool count exceeds the configured adapter limit.","stream_limit_exceeded"):source.toolCallName!==void 0&&typeof source.toolCallName!="string"?[]:(this.tools.set(source.toolCallId,{name:source.toolCallName??"tool",argsText:"",argsBytes:0,args:{}}),[this.emit({type:"tool-upsert",invocation:this.toolInvocation(source.toolCallId,"running")},eventId)]);case"TOOL_CALL_ARGS":{if(typeof source.toolCallId!="string"||typeof source.delta!="string")return[];let buffer=this.tools.get(source.toolCallId);if(!buffer){if(this.tools.size>=this.limits.maxBufferedTools)return this.failure("Buffered tool count exceeds the configured adapter limit.","stream_limit_exceeded");buffer={name:"tool",argsText:"",argsBytes:0,args:{}}}const deltaBytes=encoder.encode(source.delta).byteLength;return deltaBytes>this.limits.maxToolArgumentBytes-buffer.argsBytes?(this.tools.delete(source.toolCallId),this.failure("Tool arguments exceed the configured adapter limit.","stream_limit_exceeded")):(buffer.argsText+=source.delta,buffer.argsBytes+=deltaBytes,buffer.args=objectArgs(buffer.argsText,this.limits)??buffer.args,this.tools.set(source.toolCallId,buffer),[this.emit({type:"tool-upsert",invocation:this.toolInvocation(source.toolCallId,"running")},eventId)])}case"TOOL_CALL_END":{if(typeof source.toolCallId!="string")return[];const invocation=this.toolInvocation(source.toolCallId,"running"),buffer=this.tools.get(source.toolCallId);return buffer&&(buffer.argsText="",buffer.argsBytes=0),[this.emit({type:"tool-upsert",invocation},eventId)]}case"TOOL_CALL_RESULT":{if(typeof source.toolCallId!="string")return[];const invocation={...this.toolInvocation(source.toolCallId,"success"),...Object.hasOwn(source,"result")?{result:source.result}:{}};return this.tools.delete(source.toolCallId),[this.emit({type:"tool-upsert",invocation},eventId)]}case"STATE_SNAPSHOT":return Object.hasOwn(source,"snapshot")?[this.emit({type:"state-snapshot",snapshot:source.snapshot},eventId)]:[];case"STATE_DELTA":{const patch=parseJsonPatch(source.delta);return patch?[this.emit({type:"state-delta",patch},eventId)]:[]}case"ACTIVITY_SNAPSHOT":return typeof source.messageId!="string"||!source.messageId||typeof source.activityType!="string"||!source.activityType||!record(source.content)||source.replace!==void 0&&typeof source.replace!="boolean"?[]:source.replace===!1&&this.messages.has(source.messageId)?[]:this.activity(source.messageId,source.activityType,source.content,eventId);case"ACTIVITY_DELTA":{if(typeof source.messageId!="string"||typeof source.activityType!="string")return[];const previous=this.activities.get(source.messageId);if(!previous||previous.activityType!==source.activityType)return[];const patch=parseJsonPatch(source.patch);return patch?this.activity(source.messageId,source.activityType,applySharedStatePatch(previous.content,patch),eventId):[]}case"CUSTOM":{if(!this.customEventTarget||typeof source.name!="string"||!source.name||!Object.hasOwn(source,"value"))return[];let target;try{target=this.customEventTarget({name:source.name,value:source.value})}catch{return this.failure("Custom event routing failed.","invalid_provider_event")}if(target===null)return[];const ownedTarget=snapshotProviderValue(target,createProviderSnapshotBudget(this.limits)),destination=ownedTarget.ok?record(ownedTarget.value):null;if(!destination||typeof destination.messageId!="string"||!destination.messageId||typeof destination.partId!="string"||!destination.partId)return[];const value=snapshotProviderValue(source.value,createProviderSnapshotBudget(this.limits));if(!value.ok)return this.failure("Custom event payload is invalid or exceeds the configured adapter limit.",value.failure==="limit"?"stream_limit_exceeded":"invalid_provider_event");const rejected=this.claimMessage(destination.messageId,"custom");return rejected||[this.emit({type:"message-part-upsert",messageId:destination.messageId,role:"assistant",part:{id:destination.partId,type:"data",name:source.name,data:value.value,state:"complete"}},eventId)]}case"MESSAGES_SNAPSHOT":{if(source.messages!==void 0&&!Array.isArray(source.messages))return[];const messages=(source.messages??[]).map(snapshotMessage).filter(message=>message!==null);if(messages.length>this.limits.maxBufferedMessages)return this.failure("Buffered message count exceeds the configured adapter limit.","stream_limit_exceeded");const activities=new Map,kinds=new Map;let bytes=0;for(const message of messages){const part=message.parts?.[0];if(kinds.set(message.id,part?.type==="data"?"activity":part?.type==="reasoning"?"reasoning":"text"),part?.type!=="data"||!part.name)continue;const ownedContent=snapshotProviderValue(part.data,createProviderSnapshotBudget(this.limits));if(!ownedContent.ok||bytes+ownedContent.bytes>this.limits.maxBytes)return this.failure("Buffered activity content exceeds the configured adapter limit.","stream_limit_exceeded");activities.set(message.id,{activityType:part.name,content:ownedContent.value,bytes:ownedContent.bytes}),bytes+=ownedContent.bytes}this.messages.clear(),this.activities.clear();for(const[id,kind]of kinds)this.messages.set(id,kind);for(const[id,activity]of activities)this.activities.set(id,activity);return this.activityBytes=bytes,[this.emit({type:"messages-snapshot",messages},eventId)]}default:return[]}}}export{AgUiStreamAdapter,DEFAULT_AG_UI_ADAPTER_LIMITS};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{positiveInteger}from"../../internal/numbers.js";import{createProviderSnapshotBudget,resolveProviderSnapshotLimits,snapshotProviderValue}from"../snapshot.js";const DEFAULT_AI_SDK_ADAPTER_LIMITS=Object.freeze({...resolveProviderSnapshotLimits(),maxParts:512}),MESSAGE_ROLES=new Set(["user","assistant","system"]);function resolveLimits(limits){const snapshot=resolveProviderSnapshotLimits(limits);return Object.freeze({...snapshot,maxParts:positiveInteger(limits.maxParts,DEFAULT_AI_SDK_ADAPTER_LIMITS.maxParts)})}function record(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function stringValue(value){return typeof value=="string"?value:void 0}function partState(value){return value==="done"||value==="output-available"||value==="output-error"||value==="output-denied"?"complete":"streaming"}function toolStatus(value,approval){return value==="output-error"?"error":value==="output-available"?"success":value==="approval-requested"?"pending":value==="output-denied"||value==="approval-responded"&&record(approval)?.approved===!1?"denied":"running"}function toolParts(part,index,messageId){const type=stringValue(part.type)??"",name=type==="dynamic-tool"?stringValue(part.toolName)??"tool":type.startsWith("tool-")?type.slice(5):"";if(!name)return[];const invocationId=stringValue(part.toolCallId)??`${messageId}:tool:${index}`,status=toolStatus(part.state,part.approval),input=record(part.input)??{},error=stringValue(part.errorText),call={id:`${invocationId}:call`,type:"tool-call",state:partState(part.state),invocation:{id:invocationId,name,args:input,status,...error?{error}:{}}},hasOutput=Object.hasOwn(part,"output");if(!hasOutput&&!error)return[call];const result=error?{id:`${invocationId}:result`,type:"tool-result",state:"complete",invocationId,name,error,...hasOutput?{result:part.output}:{}}:{id:`${invocationId}:result`,type:"tool-result",state:"complete",invocationId,name,result:part.output};return[call,result]}function adaptPart(value,index,messageId){const part=record(value);if(!part)return[];const type=stringValue(part.type);if(!type)return[];const id=stringValue(part.id)??`${messageId}:part:${index}`;if(type==="text"&&typeof part.text=="string"){const text={id,type:"text",text:part.text,state:partState(part.state)};return part.state==="output-error"?[text,{id:`${id}:error`,type:"error",message:stringValue(part.errorText)??"",code:"provider_part_error"}]:[text]}if(type==="reasoning"&&typeof part.text=="string"){const reasoning={id,type:"reasoning",text:part.text,state:partState(part.state)};return part.state==="output-error"?[reasoning,{id:`${id}:error`,type:"error",message:stringValue(part.errorText)??"",code:"provider_part_error"}]:[reasoning]}if(type==="dynamic-tool"||type.startsWith("tool-"))return toolParts(part,index,messageId);if(type==="source-url"||type==="source-document"){const sourceId=stringValue(part.sourceId)??stringValue(part.id)??id,label=stringValue(part.title)??stringValue(part.filename)??stringValue(part.url)??sourceId;return[{id,type:"citation",state:"complete",citation:{id,sourceId,label,metadata:{...part}}}]}if(type==="file"){const name=stringValue(part.filename)??stringValue(part.name)??id;return[{id,type:"attachment",state:partState(part.state),document:{id,name,...typeof part.mediaType=="string"?{mimeType:part.mediaType}:{},...typeof part.url=="string"?{uri:part.url}:{}}}]}return type.startsWith("data-")&&Object.hasOwn(part,"data")?[{id,type:"data",state:
|
|
1
|
+
import{positiveInteger}from"../../internal/numbers.js";import{createProviderSnapshotBudget,resolveProviderSnapshotLimits,snapshotProviderValue}from"../snapshot.js";const DEFAULT_AI_SDK_ADAPTER_LIMITS=Object.freeze({...resolveProviderSnapshotLimits(),maxParts:512}),MESSAGE_ROLES=new Set(["user","assistant","system"]),OPTIONAL_MESSAGE_FIELDS=new Set(["metadata"]),OPTIONAL_PART_FIELDS=new Set(["id","state","providerMetadata","filename","title","input","output","rawInput","errorText","providerExecuted","preliminary","toolMetadata","callProviderMetadata","resultProviderMetadata","approval"]),TOOL_INPUT_STATES=new Set(["input-streaming","input-available","approval-requested","approval-responded","output-available","output-error","output-denied"]);function resolveLimits(limits){const snapshot=resolveProviderSnapshotLimits(limits);return Object.freeze({...snapshot,maxParts:positiveInteger(limits.maxParts,DEFAULT_AI_SDK_ADAPTER_LIMITS.maxParts)})}function record(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function optionalFields(value,fields,budget){if(!record(value))return value;const keys=Reflect.ownKeys(value);if(keys.length>budget.remaining)throw new Error("SDK snapshot normalization exceeds the node limit.");budget.remaining-=keys.length;const output=Object.create(Object.getPrototypeOf(value));for(const key of keys){const descriptor=Object.getOwnPropertyDescriptor(value,key);descriptor&&(typeof key=="string"&&fields.has(key)&&"value"in descriptor&&descriptor.value===void 0||Object.defineProperty(output,key,descriptor))}return output}function normalizeSnapshot(value,limits){try{const budget={remaining:limits.maxNodes},message=record(optionalFields(value,OPTIONAL_MESSAGE_FIELDS,budget));if(!message)return value;const descriptor=Object.getOwnPropertyDescriptor(message,"parts");if(!descriptor||!("value"in descriptor)||!Array.isArray(descriptor.value))return message;const parts=descriptor.value;if(parts.length>limits.maxParts)return value;const keys=Reflect.ownKeys(parts);if(keys.length>budget.remaining)return null;budget.remaining-=keys.length;const output=new Array(parts.length);for(const key of keys){if(key==="length")continue;const part=Object.getOwnPropertyDescriptor(parts,key);part&&Object.defineProperty(output,key,"value"in part?{...part,value:optionalFields(part.value,OPTIONAL_PART_FIELDS,budget)}:part)}const normalized=Object.create(Object.getPrototypeOf(message));for(const key of Reflect.ownKeys(message)){const property=Object.getOwnPropertyDescriptor(message,key);property&&Object.defineProperty(normalized,key,key==="parts"?{...property,value:output}:property)}return normalized}catch{return null}}function stringValue(value){return typeof value=="string"?value:void 0}function partState(value){return value==="done"||value==="output-available"||value==="output-error"||value==="output-denied"?"complete":"streaming"}function toolStatus(value,approval){return value==="output-error"?"error":value==="output-available"?"success":value==="approval-requested"?"pending":value==="output-denied"||value==="approval-responded"&&record(approval)?.approved===!1?"denied":"running"}function toolParts(part,index,messageId){const type=stringValue(part.type)??"",name=type==="dynamic-tool"?stringValue(part.toolName)??"tool":type.startsWith("tool-")?type.slice(5):"";if(!name)return[];const invocationId=stringValue(part.toolCallId)??`${messageId}:tool:${index}`,status=toolStatus(part.state,part.approval),input=record(part.input)??{},error=stringValue(part.errorText),call={id:`${invocationId}:call`,type:"tool-call",state:partState(part.state),...typeof part.state=="string"&&TOOL_INPUT_STATES.has(part.state)?{metadata:{aiSdkInputState:part.state}}:{},invocation:{id:invocationId,name,args:input,status,...error?{error}:{}}},hasOutput=Object.hasOwn(part,"output");if(!hasOutput&&!error)return[call];const result=error?{id:`${invocationId}:result`,type:"tool-result",state:"complete",invocationId,name,error,...hasOutput?{result:part.output}:{}}:{id:`${invocationId}:result`,type:"tool-result",state:"complete",invocationId,name,result:part.output};return[call,result]}function adaptPart(value,index,messageId){const part=record(value);if(!part)return[];const type=stringValue(part.type);if(!type)return[];const id=stringValue(part.id)??`${messageId}:part:${index}`;if(type==="text"&&typeof part.text=="string"){const text={id,type:"text",text:part.text,state:partState(part.state)};return part.state==="output-error"?[text,{id:`${id}:error`,type:"error",message:stringValue(part.errorText)??"",code:"provider_part_error"}]:[text]}if(type==="reasoning"&&typeof part.text=="string"){const reasoning={id,type:"reasoning",text:part.text,state:partState(part.state)};return part.state==="output-error"?[reasoning,{id:`${id}:error`,type:"error",message:stringValue(part.errorText)??"",code:"provider_part_error"}]:[reasoning]}if(type==="dynamic-tool"||type.startsWith("tool-"))return toolParts(part,index,messageId);if(type==="source-url"||type==="source-document"){const sourceId=stringValue(part.sourceId)??stringValue(part.id)??id,label=stringValue(part.title)??stringValue(part.filename)??stringValue(part.url)??sourceId;return[{id,type:"citation",state:"complete",citation:{id,sourceId,label,metadata:{...part}}}]}if(type==="file"){const name=stringValue(part.filename)??stringValue(part.name)??id;return[{id,type:"attachment",state:partState(part.state),document:{id,name,...typeof part.mediaType=="string"?{mimeType:part.mediaType}:{},...typeof part.url=="string"?{uri:part.url}:{}}}]}return type.startsWith("data-")&&Object.hasOwn(part,"data")?[{id,type:"data",state:"complete",name:type.slice(5),data:part.data}]:[]}function adaptAiSdkMessage(message,limits={}){const resolved=resolveLimits(limits),owned=snapshotProviderValue(normalizeSnapshot(message,resolved),createProviderSnapshotBudget(resolved));if(!owned.ok)return null;const source=record(owned.value);if(!source||typeof source.id!="string"||typeof source.role!="string")return null;const parts=source.parts;if(parts!==void 0&&(!Array.isArray(parts)||parts.length>resolved.maxParts)||source.metadata!==void 0&&!record(source.metadata))return null;const role=MESSAGE_ROLES.has(source.role)?source.role:"assistant";return{id:source.id,role,status:"sent",parts:(parts??[]).flatMap((part,index)=>adaptPart(part,index,source.id)),...source.metadata?{metadata:source.metadata}:{}}}export{DEFAULT_AI_SDK_ADAPTER_LIMITS,adaptAiSdkMessage};
|
package/dist/ai/runtime.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{positiveInteger}from"../internal/numbers.js";import{createProviderSnapshotBudget,snapshotProviderValue}from"./snapshot.js";const DEFAULT_AGENT_STREAM_LIMITS=Object.freeze({maxMessages:512,maxPartsPerMessage:512,maxTools:256,maxDeltaCharacters:32768,maxTextCharactersPerPart:262144,maxIdentifierCharacters:1024,maxStatusMessageCharacters:8192,maxPatchOperations:256,maxSnapshotDepth:32,maxSnapshotNodes:1e4,maxSnapshotBytes:1048576,maxRetainedBytes:8388608}),usageByState=new WeakMap,FORBIDDEN_PATH_SEGMENTS=new Set(["__proto__","prototype","constructor"]),ARRAY_INDEX=/^(0|[1-9][0-9]*)$/,MESSAGE_ROLES=new Set(["user","assistant","system"]),MESSAGE_STATUSES=new Set(["sending","sent","failed","streaming"]),PART_STATES=new Set(["streaming","complete","interrupted"]),TOOL_STATUSES=new Set(["pending","running","success","error","denied","incomplete"]);function resolveLimits(limits){const resolved=Object.fromEntries(Object.entries(DEFAULT_AGENT_STREAM_LIMITS).map(([key,fallback])=>[key,positiveInteger(limits[key],fallback)]));return resolved.maxSnapshotBytes>resolved.maxRetainedBytes&&(resolved.maxSnapshotBytes=resolved.maxRetainedBytes),Object.freeze(resolved)}function emptyUsage(){return{messages:new Map,tools:new Map,sharedStateBytes:0,totalBytes:0}}function copyUsage(usage){return{messages:new Map(usage.messages),tools:new Map(usage.tools),sharedStateBytes:usage.sharedStateBytes,totalBytes:usage.totalBytes}}function createAgentStreamState(limits={}){const state={generation:0,cursor:0,limits:resolveLimits(limits),status:{kind:"idle"},messages:[],tools:[],sharedState:null};return usageByState.set(state,emptyUsage()),state}function snapshotLimits(limits,maxBytes=limits.maxSnapshotBytes){return{maxDepth:limits.maxSnapshotDepth,maxNodes:limits.maxSnapshotNodes,maxBytes,maxStringCharacters:Math.max(limits.maxTextCharactersPerPart,limits.maxStatusMessageCharacters)}}function ownValue(value,limits){const result=snapshotProviderValue(value,createProviderSnapshotBudget(snapshotLimits(limits)));return result.ok?{value:result.value,bytes:result.bytes}:null}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function validIdentifier(value,limits){return typeof value=="string"&&value.length>0&&value.length<=limits.maxIdentifierCharacters}function validOptionalString(value,maximum){return value===void 0||typeof value=="string"&&value.length<=maximum}function validStatus(value,limits){return!isRecord(value)||!validIdentifier(value.kind,limits)?!1:validOptionalString(value.message,limits.maxStatusMessageCharacters)}function validDocument(value,limits){return!isRecord(value)||!validIdentifier(value.id,limits)||typeof value.name!="string"?!1:["mimeType","uri","version"].every(key=>validOptionalString(value[key],limits.maxSnapshotBytes))}const MAX_TOOL_REDACTION_PATHS=100,MAX_TOOL_REDACTION_PATH_CHARACTERS=4096;function validOptionalFiniteNumber(value){return value===void 0||typeof value=="number"&&Number.isFinite(value)}function validOptionalRedactionPaths(value){return value===void 0?!0:Array.isArray(value)&&value.length<=MAX_TOOL_REDACTION_PATHS&&value.every(path=>typeof path=="string"&&path.length<=MAX_TOOL_REDACTION_PATH_CHARACTERS)}function validTool(value,limits){return isRecord(value)?validIdentifier(value.id,limits)&&validIdentifier(value.name,limits)&&validOptionalString(value.displayName,limits.maxIdentifierCharacters)&&isRecord(value.args)&&TOOL_STATUSES.has(String(value.status))&&validOptionalString(value.error,limits.maxStatusMessageCharacters)&&validOptionalFiniteNumber(value.startedAt)&&validOptionalFiniteNumber(value.endedAt)&&validOptionalRedactionPaths(value.redactedFields):!1}function validInterruption(value,limits){return isRecord(value)&&typeof value.resumable=="boolean"&&validOptionalString(value.reason,limits.maxStatusMessageCharacters)}function validPart(value,limits){if(!isRecord(value)||!validIdentifier(value.id,limits)||typeof value.type!="string"||value.state!==void 0&&!PART_STATES.has(String(value.state))||value.interruption!==void 0&&!validInterruption(value.interruption,limits)||value.metadata!==void 0&&!isRecord(value.metadata))return!1;switch(value.type){case"text":case"reasoning":return typeof value.text=="string"&&value.text.length<=limits.maxTextCharactersPerPart;case"tool-call":return validTool(value.invocation,limits);case"tool-result":{if(!validIdentifier(value.invocationId,limits)||!validOptionalString(value.name,limits.maxIdentifierCharacters))return!1;const hasResult=Object.hasOwn(value,"result");return Object.hasOwn(value,"error")?typeof value.error=="string"&&value.error.length<=limits.maxStatusMessageCharacters:hasResult}case"citation":return isRecord(value.citation)&&validIdentifier(value.citation.id,limits);case"attachment":return validDocument(value.document,limits);case"data":{const hasData=Object.hasOwn(value,"data"),hasWidget=Object.hasOwn(value,"widget");return hasData!==hasWidget&&validOptionalString(value.name,limits.maxIdentifierCharacters)}case"audio":return["src","transcript","mimeType"].every(key=>validOptionalString(value[key],limits.maxSnapshotBytes));case"error":return typeof value.message=="string"&&value.message.length<=limits.maxStatusMessageCharacters&&validOptionalString(value.code,limits.maxIdentifierCharacters)&&(value.retryable===void 0||typeof value.retryable=="boolean");default:return!1}}function ownedPart(value,limits){const owned=ownValue(value,limits);return owned&&validPart(owned.value,limits)?owned:null}function validMessage(value,limits){return!(!isRecord(value)||!validIdentifier(value.id,limits)||!MESSAGE_ROLES.has(value.role)||value.status!==void 0&&!MESSAGE_STATUSES.has(String(value.status))||value.timestamp!==void 0&&typeof value.timestamp!="string"||!validOptionalString(value.text,limits.maxTextCharactersPerPart)||value.metadata!==void 0&&!isRecord(value.metadata)||value.attachments!==void 0&&(!Array.isArray(value.attachments)||!value.attachments.every(item=>validDocument(item,limits)))||value.parts!==void 0&&(!Array.isArray(value.parts)||value.parts.length>limits.maxPartsPerMessage||!value.parts.every(part=>validPart(part,limits))))}function ownedMessage(value,limits){const owned=ownValue(value,limits);return owned&&validMessage(owned.value,limits)?owned:null}function ownedTool(value,limits){const owned=ownValue(value,limits);return owned&&validTool(owned.value,limits)?owned:null}function usageFor(state){const cached=usageByState.get(state);if(cached)return cached;const usage=emptyUsage();for(const message of state.messages){const bytes=ownValue(message,state.limits)?.bytes??state.limits.maxRetainedBytes;usage.messages.set(message.id,bytes),usage.totalBytes+=bytes}for(const tool of state.tools){const bytes=ownValue(tool,state.limits)?.bytes??state.limits.maxRetainedBytes;usage.tools.set(tool.id,bytes),usage.totalBytes+=bytes}const shared=ownValue(state.sharedState,state.limits);return usage.sharedStateBytes=shared?.bytes??state.limits.maxRetainedBytes,usage.totalBytes+=usage.sharedStateBytes,usageByState.set(state,usage),usage}function replaceUsageEntry(usage,collection,id,bytes){const map=usage[collection];usage.totalBytes-=map.get(id)??0,map.set(id,bytes),usage.totalBytes+=bytes}function commit(state,next,usage,cursor){if(usage.totalBytes>state.limits.maxRetainedBytes)return failEvent(state,cursor,"Retained stream state exceeds the configured limit.","stream_limit_exceeded");const committed={...next,generation:cursor.generation,cursor:cursor.sequence};return usageByState.set(committed,usage),committed}function failEvent(state,cursor,message,code){const failed={...state,...cursor?{generation:cursor.generation,cursor:cursor.sequence}:{},status:{kind:"error",message},error:{message,code}};return usageByState.set(failed,usageFor(state)),failed}function pointerSegments(path){if(path==="")return[];if(!path.startsWith("/"))return null;const rawSegments=path.slice(1).split("/");if(rawSegments.some(segment=>/~(?:[^01]|$)/.test(segment)))return null;const segments=rawSegments.map(segment=>segment.replace(/~1/g,"/").replace(/~0/g,"~"));return segments.some(segment=>FORBIDDEN_PATH_SEGMENTS.has(segment))?null:segments}function validPatchKeys(record,operation){const expected=operation==="remove"?["op","path"]:["op","path","value"],keys=Object.keys(record).sort();return keys.length===expected.length&&keys.every((key,index)=>key===expected.sort()[index])}function parseJsonPatch(value,limits={}){const resolved=resolveLimits(limits),owned=ownValue(value,resolved);if(!owned||!Array.isArray(owned.value)||owned.value.length>resolved.maxPatchOperations)return null;const operations=[];for(const candidate of owned.value){if(!isRecord(candidate))return null;const operation=candidate.op,path=candidate.path;if(operation!=="add"&&operation!=="replace"&&operation!=="remove"||typeof path!="string"||pointerSegments(path)===null||!validPatchKeys(candidate,operation))return null;operations.push(operation==="remove"?{op:operation,path}:{op:operation,path,value:candidate.value})}return operations}function arrayIndex(segment){if(!ARRAY_INDEX.test(segment))return null;const index=Number(segment);return Number.isSafeInteger(index)?index:null}function applyPatchOperation(root,operation){const segments=pointerSegments(operation.path);if(!segments)return root;if(!segments.length)return operation.op==="remove"?null:operation.value;let parent=root;for(const segment of segments.slice(0,-1))if(Array.isArray(parent)){const index=arrayIndex(segment);if(index===null||index>=parent.length)return root;parent=parent[index]}else if(isRecord(parent)){if(!Object.hasOwn(parent,segment))return root;parent=parent[segment]}else return root;const key=segments.at(-1);if(key===void 0)return root;if(Array.isArray(parent)){if(key==="-")return operation.op==="add"&&parent.push(operation.value),root;const index=arrayIndex(key);return index===null||(operation.op==="add"?index<=parent.length&&parent.splice(index,0,operation.value):operation.op==="remove"?index<parent.length&&parent.splice(index,1):index<parent.length&&(parent[index]=operation.value)),root}return isRecord(parent)&&(operation.op==="add"?parent[key]=operation.value:operation.op==="remove"?Object.hasOwn(parent,key)&&delete parent[key]:Object.hasOwn(parent,key)&&(parent[key]=operation.value)),root}function applySharedStatePatch(value,patch){const limits=DEFAULT_AGENT_STREAM_LIMITS,root=ownValue(value,limits),operations=parseJsonPatch(patch,limits);if(!root)return null;if(!operations)return root.value;let next=root.value;for(const operation of operations)next=applyPatchOperation(next,operation);return next}function baseCursor(event){const generation=event.generation,sequence=event.sequence;return typeof generation=="number"&&Number.isSafeInteger(generation)&&generation>=0&&typeof sequence=="number"&&Number.isSafeInteger(sequence)&&sequence>0?{generation,sequence}:null}function shouldIgnore(state,type,cursor){return type==="run-start"?cursor.generation<=state.generation:type==="reset"?cursor.generation<state.generation||cursor.generation===state.generation&&cursor.sequence<=state.cursor:cursor.generation!==state.generation||cursor.sequence<=state.cursor}function reduceAgentStream(state,event){const eventSnapshot=snapshotProviderValue(event,createProviderSnapshotBudget(snapshotLimits(state.limits)));if(!eventSnapshot.ok)return eventSnapshot.failure==="limit"?failEvent(state,void 0,"Stream event exceeds the configured limit.","stream_limit_exceeded"):failEvent(state,void 0,"Stream event is not valid serializable data.","invalid_stream_event");const source=eventSnapshot.value;if(!isRecord(source))return failEvent(state,void 0,"Stream event is not a record.","invalid_stream_event");const cursor=baseCursor(source);if(!cursor||typeof source.type!="string")return failEvent(state,void 0,"Stream event generation, sequence, or type is invalid.","invalid_stream_event");if(shouldIgnore(state,source.type,cursor))return state;const usage=copyUsage(usageFor(state));switch(source.type){case"reset":{const reset=createAgentStreamState(state.limits);return commit(state,reset,emptyUsage(),cursor)}case"run-start":{if(!validIdentifier(source.runId,state.limits))return failEvent(state,cursor,"Run start has an invalid run id.","invalid_stream_event");const started=createAgentStreamState(state.limits);return started.runId=source.runId,started.status={kind:"running"},commit(state,started,emptyUsage(),cursor)}case"stream-interrupt":case"stream-resume":{if(source.runId!==state.runId||!state.runId)return state;const interrupting=source.type==="stream-interrupt";if(interrupting&&!validInterruption(source.interruption,state.limits))return failEvent(state,cursor,"Stream interruption has an invalid shape.","invalid_stream_event");if(!interrupting&&state.interruption?.resumable!==!0)return state;const interruption=interrupting?source.interruption:void 0,messages=[];for(const current of state.messages){const parts=current.parts?.map(part=>{if(interrupting)return part.state==="streaming"?{...part,state:"interrupted",interruption}:part;if(part.state!=="interrupted"||part.interruption?.resumable!==!0)return part;const{interruption:_interruption,...resumed}=part;return{...resumed,state:"streaming"}}),message=ownedMessage({...current,...parts?{parts}:{}},state.limits);if(!message)return failEvent(state,cursor,"Interrupted message exceeds the configured limit.","stream_limit_exceeded");messages.push(message.value),replaceUsageEntry(usage,"messages",message.value.id,message.bytes)}return commit(state,{...state,messages,interruption},usage,cursor)}case"run-status":{if(!validStatus(source.status,state.limits)||source.runId!==void 0&&!validIdentifier(source.runId,state.limits))return failEvent(state,cursor,"Run status has an invalid shape.","invalid_stream_event");const status=source.status,error=status.kind==="error"?{message:status.message??state.error?.message??"Agent run failed",...state.error?.code&&(!status.message||status.message===state.error.message)?{code:state.error.code}:{}}:void 0;return commit(state,{...state,runId:source.runId??state.runId,status,error},usage,cursor)}case"messages-snapshot":{if(!Array.isArray(source.messages)||source.messages.length>state.limits.maxMessages)return failEvent(state,cursor,"Message snapshot exceeds the configured limit.","stream_limit_exceeded");const messages=[],messageBytes=new Map;let total=usage.totalBytes-[...usage.messages.values()].reduce((sum,bytes)=>sum+bytes,0);for(const candidate of source.messages){const message=ownedMessage(candidate,state.limits);if(!message||messageBytes.has(message.value.id))return failEvent(state,cursor,"Message snapshot contains an invalid or duplicate message.","invalid_stream_event");messages.push(message.value),messageBytes.set(message.value.id,message.bytes),total+=message.bytes}usage.messages.clear();for(const[id,bytes]of messageBytes)usage.messages.set(id,bytes);return usage.totalBytes=total,commit(state,{...state,messages},usage,cursor)}case"message-start":{const incoming=ownedMessage(source.message,state.limits);if(!incoming)return failEvent(state,cursor,"Message has an invalid shape.","invalid_stream_event");const index=state.messages.findIndex(message2=>message2.id===incoming.value.id);if(index<0&&state.messages.length>=state.limits.maxMessages)return failEvent(state,cursor,"Message count exceeds the configured limit.","stream_limit_exceeded");const existing=index>=0?state.messages[index]:void 0,merged=existing?{...existing,...incoming.value}:incoming.value,message=ownedMessage(merged,state.limits);if(!message)return failEvent(state,cursor,"Message has an invalid shape.","invalid_stream_event");const messages=[...state.messages];return index<0?messages.push(message.value):messages[index]=message.value,replaceUsageEntry(usage,"messages",message.value.id,message.bytes),commit(state,{...state,messages},usage,cursor)}case"message-part-upsert":{if(!validIdentifier(source.messageId,state.limits)||source.role!==void 0&&!MESSAGE_ROLES.has(source.role))return failEvent(state,cursor,"Message part target is invalid.","invalid_stream_event");const part=ownedPart(source.part,state.limits);if(!part)return failEvent(state,cursor,"Message part has an invalid shape.","invalid_stream_event");const messageIndex=state.messages.findIndex(message2=>message2.id===source.messageId);if(messageIndex<0&&state.messages.length>=state.limits.maxMessages)return failEvent(state,cursor,"Message count exceeds the configured limit.","stream_limit_exceeded");const current=messageIndex>=0?state.messages[messageIndex]:{id:source.messageId,role:source.role??"assistant",status:"streaming",parts:[]},parts=[...current.parts??[]],partIndex=parts.findIndex(candidate=>candidate.id===part.value.id);if(parts[partIndex]?.state==="interrupted")return commit(state,state,usage,cursor);if(partIndex<0&&parts.length>=state.limits.maxPartsPerMessage)return failEvent(state,cursor,"Message part count exceeds the configured limit.","stream_limit_exceeded");partIndex<0?parts.push(part.value):parts[partIndex]=part.value;const message=ownedMessage({...current,parts},state.limits);if(!message)return failEvent(state,cursor,"Updated message has an invalid shape.","invalid_stream_event");const messages=[...state.messages];return messageIndex<0?messages.push(message.value):messages[messageIndex]=message.value,replaceUsageEntry(usage,"messages",message.value.id,message.bytes),commit(state,{...state,messages},usage,cursor)}case"message-part-delta":{if(!validIdentifier(source.messageId,state.limits)||!validIdentifier(source.partId,state.limits)||source.partType!=="text"&&source.partType!=="reasoning"||typeof source.delta!="string"||source.role!==void 0&&!MESSAGE_ROLES.has(source.role))return failEvent(state,cursor,"Message delta has an invalid shape.","invalid_stream_event");if(source.delta.length>state.limits.maxDeltaCharacters)return failEvent(state,cursor,"Message delta exceeds the configured limit.","stream_limit_exceeded");const messageIndex=state.messages.findIndex(message2=>message2.id===source.messageId);if(messageIndex<0&&state.messages.length>=state.limits.maxMessages)return failEvent(state,cursor,"Message count exceeds the configured limit.","stream_limit_exceeded");const current=messageIndex>=0?state.messages[messageIndex]:{id:source.messageId,role:source.role??"assistant",status:"streaming",parts:[]},parts=[...current.parts??[]],partIndex=parts.findIndex(part2=>part2.id===source.partId),previous=partIndex>=0?parts[partIndex]:void 0;if(previous?.state==="interrupted")return commit(state,state,usage,cursor);if(previous&&previous.type!=="text"&&previous.type!=="reasoning")return failEvent(state,cursor,"Message delta targets a non-text part.","invalid_stream_event");if(partIndex<0&&parts.length>=state.limits.maxPartsPerMessage)return failEvent(state,cursor,"Message part count exceeds the configured limit.","stream_limit_exceeded");const text=(previous?.text??"")+source.delta;if(text.length>state.limits.maxTextCharactersPerPart)return failEvent(state,cursor,"Message text exceeds the configured limit.","stream_limit_exceeded");const part=source.partType==="reasoning"?{id:source.partId,type:"reasoning",text,state:"streaming"}:{id:source.partId,type:"text",text,state:"streaming"};partIndex<0?parts.push(part):parts[partIndex]=part;const message=ownedMessage({...current,parts},state.limits);if(!message)return failEvent(state,cursor,"Updated message has an invalid shape.","invalid_stream_event");const messages=[...state.messages];return messageIndex<0?messages.push(message.value):messages[messageIndex]=message.value,replaceUsageEntry(usage,"messages",message.value.id,message.bytes),commit(state,{...state,messages},usage,cursor)}case"message-complete":{if(!validIdentifier(source.messageId,state.limits))return failEvent(state,cursor,"Message completion target is invalid.","invalid_stream_event");const index=state.messages.findIndex(message2=>message2.id===source.messageId);if(index<0)return commit(state,state,usage,cursor);const current=state.messages[index],parts=current.parts?.map(part=>part.state==="interrupted"?part:{...part,state:"complete"}),message=ownedMessage({...current,status:current.parts?.some(part=>part.state==="interrupted")?current.status:"sent",...parts?{parts}:{}},state.limits);if(!message)return failEvent(state,cursor,"Completed message has an invalid shape.","invalid_stream_event");const messages=[...state.messages];return messages[index]=message.value,replaceUsageEntry(usage,"messages",message.value.id,message.bytes),commit(state,{...state,messages},usage,cursor)}case"tool-upsert":{const incoming=ownedTool(source.invocation,state.limits);if(!incoming)return failEvent(state,cursor,"Tool invocation has an invalid shape.","invalid_stream_event");const index=state.tools.findIndex(tool2=>tool2.id===incoming.value.id);if(index<0&&state.tools.length>=state.limits.maxTools)return failEvent(state,cursor,"Tool count exceeds the configured limit.","stream_limit_exceeded");const tool=ownedTool(index<0?incoming.value:{...state.tools[index],...incoming.value},state.limits);if(!tool)return failEvent(state,cursor,"Tool invocation has an invalid shape.","invalid_stream_event");const tools=[...state.tools];return index<0?tools.push(tool.value):tools[index]=tool.value,replaceUsageEntry(usage,"tools",tool.value.id,tool.bytes),commit(state,{...state,tools},usage,cursor)}case"state-snapshot":{const snapshot=ownValue(source.snapshot,state.limits);return snapshot?(usage.totalBytes+=snapshot.bytes-usage.sharedStateBytes,usage.sharedStateBytes=snapshot.bytes,commit(state,{...state,sharedState:snapshot.value},usage,cursor)):failEvent(state,cursor,"Shared state snapshot is invalid.","invalid_stream_event")}case"state-delta":{const patch=parseJsonPatch(source.patch,state.limits);if(!patch)return failEvent(state,cursor,"Shared state patch is invalid.","invalid_stream_event");const current=ownValue(state.sharedState,state.limits);if(!current)return failEvent(state,cursor,"Retained shared state is invalid.","invalid_stream_event");let patched=current.value;for(const operation of patch)patched=applyPatchOperation(patched,operation);const snapshot=ownValue(patched,state.limits);return snapshot?(usage.totalBytes+=snapshot.bytes-usage.sharedStateBytes,usage.sharedStateBytes=snapshot.bytes,commit(state,{...state,sharedState:snapshot.value},usage,cursor)):failEvent(state,cursor,"Shared state exceeds the configured limit.","stream_limit_exceeded")}case"error":{if(typeof source.message!="string"||source.message.length>state.limits.maxStatusMessageCharacters||!validOptionalString(source.code,state.limits.maxIdentifierCharacters))return failEvent(state,cursor,"Error event has an invalid shape.","invalid_stream_event");const error={message:source.message,...source.code?{code:source.code}:{}};return commit(state,{...state,status:{kind:"error",message:source.message},error},usage,cursor)}default:return failEvent(state,cursor,"Stream event type is not supported.","invalid_stream_event")}}function reduceAgentStreamEvents(state,events){return events.reduce(reduceAgentStream,state)}export{DEFAULT_AGENT_STREAM_LIMITS,applySharedStatePatch,createAgentStreamState,parseJsonPatch,reduceAgentStream,reduceAgentStreamEvents};
|
|
1
|
+
import{positiveInteger}from"../internal/numbers.js";import{createProviderSnapshotBudget,snapshotProviderValue}from"./snapshot.js";const DEFAULT_AGENT_STREAM_LIMITS=Object.freeze({maxMessages:512,maxPartsPerMessage:512,maxTools:256,maxDeltaCharacters:32768,maxTextCharactersPerPart:262144,maxIdentifierCharacters:1024,maxStatusMessageCharacters:8192,maxPatchOperations:256,maxSnapshotDepth:32,maxSnapshotNodes:1e4,maxSnapshotBytes:1048576,maxRetainedBytes:8388608}),usageByState=new WeakMap,metricsByValue=new WeakMap,ownedMessageLimits=new WeakMap,utf8Encoder=new TextEncoder;function retainedMetrics(value){if(value!==null&&typeof value=="object"){const cached=metricsByValue.get(value);if(cached)return cached;const metrics={bytes:8,nodes:1,depth:0};for(const[key,child]of Object.entries(value)){const childMetrics=retainedMetrics(child);metrics.bytes+=childMetrics.bytes+(Array.isArray(value)?0:utf8Encoder.encode(key).byteLength),metrics.nodes+=childMetrics.nodes,metrics.depth=Math.max(metrics.depth,childMetrics.depth+1),key==="text"&&typeof child=="string"&&(metrics.textBytes=childMetrics.bytes-8,metrics.textTail=child.charCodeAt(child.length-1))}return metricsByValue.set(value,metrics),metrics}return{bytes:8+(typeof value=="string"?utf8Encoder.encode(value).byteLength:0),nodes:1,depth:0}}function appendedTextMetrics(previous,delta){const first=delta.charCodeAt(0),last=previous?.textTail??Number.NaN,paired=last>=55296&&last<=56319&&first>=56320&&first<=57343;return{bytes:(previous?.textBytes??0)+utf8Encoder.encode(delta).byteLength-(paired?2:0),tail:delta.length?delta.charCodeAt(delta.length-1):last}}const FORBIDDEN_PATH_SEGMENTS=new Set(["__proto__","prototype","constructor"]),ARRAY_INDEX=/^(0|[1-9][0-9]*)$/,MESSAGE_ROLES=new Set(["user","assistant","system"]),MESSAGE_STATUSES=new Set(["sending","sent","failed","streaming"]),PART_STATES=new Set(["streaming","complete","interrupted"]),TOOL_STATUSES=new Set(["pending","running","success","error","denied","incomplete"]);function resolveLimits(limits){const resolved=Object.fromEntries(Object.entries(DEFAULT_AGENT_STREAM_LIMITS).map(([key,fallback])=>[key,positiveInteger(limits[key],fallback)]));return resolved.maxSnapshotBytes>resolved.maxRetainedBytes&&(resolved.maxSnapshotBytes=resolved.maxRetainedBytes),Object.freeze(resolved)}function emptyUsage(){return{messages:new Map,tools:new Map,sharedStateBytes:0,totalBytes:0}}function copyUsage(usage){return{messages:new Map(usage.messages),tools:new Map(usage.tools),sharedStateBytes:usage.sharedStateBytes,totalBytes:usage.totalBytes}}function createAgentStreamState(limits={}){const state={generation:0,cursor:0,limits:resolveLimits(limits),status:{kind:"idle"},messages:[],tools:[],sharedState:null};return usageByState.set(state,emptyUsage()),state}function snapshotLimits(limits,maxBytes=limits.maxSnapshotBytes){return{maxDepth:limits.maxSnapshotDepth,maxNodes:limits.maxSnapshotNodes,maxBytes,maxStringCharacters:Math.max(limits.maxTextCharactersPerPart,limits.maxStatusMessageCharacters)}}function ownValue(value,limits){const result=snapshotProviderValue(value,createProviderSnapshotBudget(snapshotLimits(limits)));return result.ok?{value:result.value,bytes:result.bytes}:null}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function validIdentifier(value,limits){return typeof value=="string"&&value.length>0&&value.length<=limits.maxIdentifierCharacters}function validOptionalString(value,maximum){return value===void 0||typeof value=="string"&&value.length<=maximum}function validStatus(value,limits){return!isRecord(value)||!validIdentifier(value.kind,limits)?!1:validOptionalString(value.message,limits.maxStatusMessageCharacters)}function validDocument(value,limits){return!isRecord(value)||!validIdentifier(value.id,limits)||typeof value.name!="string"?!1:["mimeType","uri","version"].every(key=>validOptionalString(value[key],limits.maxSnapshotBytes))}const MAX_TOOL_REDACTION_PATHS=100,MAX_TOOL_REDACTION_PATH_CHARACTERS=4096;function validOptionalFiniteNumber(value){return value===void 0||typeof value=="number"&&Number.isFinite(value)}function validOptionalRedactionPaths(value){return value===void 0?!0:Array.isArray(value)&&value.length<=MAX_TOOL_REDACTION_PATHS&&value.every(path=>typeof path=="string"&&path.length<=MAX_TOOL_REDACTION_PATH_CHARACTERS)}function validTool(value,limits){return isRecord(value)?validIdentifier(value.id,limits)&&validIdentifier(value.name,limits)&&validOptionalString(value.displayName,limits.maxIdentifierCharacters)&&isRecord(value.args)&&TOOL_STATUSES.has(String(value.status))&&validOptionalString(value.error,limits.maxStatusMessageCharacters)&&validOptionalFiniteNumber(value.startedAt)&&validOptionalFiniteNumber(value.endedAt)&&validOptionalRedactionPaths(value.redactedFields):!1}function validInterruption(value,limits){return isRecord(value)&&typeof value.resumable=="boolean"&&validOptionalString(value.reason,limits.maxStatusMessageCharacters)}function validPart(value,limits){if(!isRecord(value)||!validIdentifier(value.id,limits)||typeof value.type!="string"||value.state!==void 0&&!PART_STATES.has(String(value.state))||value.interruption!==void 0&&!validInterruption(value.interruption,limits)||value.metadata!==void 0&&!isRecord(value.metadata))return!1;switch(value.type){case"text":case"reasoning":return typeof value.text=="string"&&value.text.length<=limits.maxTextCharactersPerPart;case"tool-call":return validTool(value.invocation,limits);case"tool-result":{if(!validIdentifier(value.invocationId,limits)||!validOptionalString(value.name,limits.maxIdentifierCharacters))return!1;const hasResult=Object.hasOwn(value,"result");return Object.hasOwn(value,"error")?typeof value.error=="string"&&value.error.length<=limits.maxStatusMessageCharacters:hasResult}case"citation":return isRecord(value.citation)&&validIdentifier(value.citation.id,limits);case"attachment":return validDocument(value.document,limits);case"data":{const hasData=Object.hasOwn(value,"data"),hasWidget=Object.hasOwn(value,"widget");return hasData!==hasWidget&&validOptionalString(value.name,limits.maxIdentifierCharacters)}case"audio":return["src","transcript","mimeType"].every(key=>validOptionalString(value[key],limits.maxSnapshotBytes));case"error":return typeof value.message=="string"&&value.message.length<=limits.maxStatusMessageCharacters&&validOptionalString(value.code,limits.maxIdentifierCharacters)&&(value.retryable===void 0||typeof value.retryable=="boolean");default:return!1}}function ownedPart(value,limits){const owned=ownValue(value,limits);return owned&&validPart(owned.value,limits)?owned:null}function validMessage(value,limits){return!(!isRecord(value)||!validIdentifier(value.id,limits)||!MESSAGE_ROLES.has(value.role)||value.status!==void 0&&!MESSAGE_STATUSES.has(String(value.status))||value.timestamp!==void 0&&typeof value.timestamp!="string"||!validOptionalString(value.text,limits.maxTextCharactersPerPart)||value.metadata!==void 0&&!isRecord(value.metadata)||value.attachments!==void 0&&(!Array.isArray(value.attachments)||!value.attachments.every(item=>validDocument(item,limits)))||value.parts!==void 0&&(!Array.isArray(value.parts)||value.parts.length>limits.maxPartsPerMessage||!value.parts.every(part=>validPart(part,limits))))}function ownedMessage(value,limits){const owned=ownValue(value,limits);return!owned||!validMessage(owned.value,limits)?null:(retainedMetrics(owned.value),ownedMessageLimits.set(owned.value,limits),owned)}function ownedTool(value,limits){const owned=ownValue(value,limits);return owned&&validTool(owned.value,limits)?owned:null}function usageFor(state){const cached=usageByState.get(state);if(cached)return cached;const usage=emptyUsage();for(const message of state.messages){const bytes=ownValue(message,state.limits)?.bytes??state.limits.maxRetainedBytes;usage.messages.set(message.id,bytes),usage.totalBytes+=bytes}for(const tool of state.tools){const bytes=ownValue(tool,state.limits)?.bytes??state.limits.maxRetainedBytes;usage.tools.set(tool.id,bytes),usage.totalBytes+=bytes}const shared=ownValue(state.sharedState,state.limits);return usage.sharedStateBytes=shared?.bytes??state.limits.maxRetainedBytes,usage.totalBytes+=usage.sharedStateBytes,usageByState.set(state,usage),usage}function replaceUsageEntry(usage,collection,id,bytes){const map=usage[collection];usage.totalBytes-=map.get(id)??0,map.set(id,bytes),usage.totalBytes+=bytes}function commit(state,next,usage,cursor){if(usage.totalBytes>state.limits.maxRetainedBytes)return failEvent(state,cursor,"Retained stream state exceeds the configured limit.","stream_limit_exceeded");const committed={...next,generation:cursor.generation,cursor:cursor.sequence};return usageByState.set(committed,usage),committed}function failEvent(state,cursor,message,code){const failed={...state,...cursor?{generation:cursor.generation,cursor:cursor.sequence}:{},status:{kind:"error",message},error:{message,code}};return usageByState.set(failed,usageFor(state)),failed}function pointerSegments(path){if(path==="")return[];if(!path.startsWith("/"))return null;const rawSegments=path.slice(1).split("/");if(rawSegments.some(segment=>/~(?:[^01]|$)/.test(segment)))return null;const segments=rawSegments.map(segment=>segment.replace(/~1/g,"/").replace(/~0/g,"~"));return segments.some(segment=>FORBIDDEN_PATH_SEGMENTS.has(segment))?null:segments}function validPatchKeys(record,operation){const expected=operation==="remove"?["op","path"]:["op","path","value"],keys=Object.keys(record).sort();return keys.length===expected.length&&keys.every((key,index)=>key===expected.sort()[index])}function parseJsonPatch(value,limits={}){const resolved=resolveLimits(limits),owned=ownValue(value,resolved);if(!owned||!Array.isArray(owned.value)||owned.value.length>resolved.maxPatchOperations)return null;const operations=[];for(const candidate of owned.value){if(!isRecord(candidate))return null;const operation=candidate.op,path=candidate.path;if(operation!=="add"&&operation!=="replace"&&operation!=="remove"||typeof path!="string"||pointerSegments(path)===null||!validPatchKeys(candidate,operation))return null;operations.push(operation==="remove"?{op:operation,path}:{op:operation,path,value:candidate.value})}return operations}function arrayIndex(segment){if(!ARRAY_INDEX.test(segment))return null;const index=Number(segment);return Number.isSafeInteger(index)?index:null}function applyPatchOperation(root,operation){const segments=pointerSegments(operation.path);if(!segments)return root;if(!segments.length)return operation.op==="remove"?null:operation.value;let parent=root;for(const segment of segments.slice(0,-1))if(Array.isArray(parent)){const index=arrayIndex(segment);if(index===null||index>=parent.length)return root;parent=parent[index]}else if(isRecord(parent)){if(!Object.hasOwn(parent,segment))return root;parent=parent[segment]}else return root;const key=segments.at(-1);if(key===void 0)return root;if(Array.isArray(parent)){if(key==="-")return operation.op==="add"&&parent.push(operation.value),root;const index=arrayIndex(key);return index===null||(operation.op==="add"?index<=parent.length&&parent.splice(index,0,operation.value):operation.op==="remove"?index<parent.length&&parent.splice(index,1):index<parent.length&&(parent[index]=operation.value)),root}return isRecord(parent)&&(operation.op==="add"?parent[key]=operation.value:operation.op==="remove"?Object.hasOwn(parent,key)&&delete parent[key]:Object.hasOwn(parent,key)&&(parent[key]=operation.value)),root}function applySharedStatePatch(value,patch){const limits=DEFAULT_AGENT_STREAM_LIMITS,root=ownValue(value,limits),operations=parseJsonPatch(patch,limits);if(!root)return null;if(!operations)return root.value;let next=root.value;for(const operation of operations)next=applyPatchOperation(next,operation);return next}function baseCursor(event){const generation=event.generation,sequence=event.sequence;return typeof generation=="number"&&Number.isSafeInteger(generation)&&generation>=0&&typeof sequence=="number"&&Number.isSafeInteger(sequence)&&sequence>0?{generation,sequence}:null}function shouldIgnore(state,type,cursor){return type==="run-start"?cursor.generation<=state.generation:type==="reset"?cursor.generation<state.generation||cursor.generation===state.generation&&cursor.sequence<=state.cursor:cursor.generation!==state.generation||cursor.sequence<=state.cursor}function reduceAgentStream(state,event){const eventSnapshot=snapshotProviderValue(event,createProviderSnapshotBudget(snapshotLimits(state.limits)));if(!eventSnapshot.ok)return eventSnapshot.failure==="limit"?failEvent(state,void 0,"Stream event exceeds the configured limit.","stream_limit_exceeded"):failEvent(state,void 0,"Stream event is not valid serializable data.","invalid_stream_event");const source=eventSnapshot.value;if(!isRecord(source))return failEvent(state,void 0,"Stream event is not a record.","invalid_stream_event");const cursor=baseCursor(source);if(!cursor||typeof source.type!="string")return failEvent(state,void 0,"Stream event generation, sequence, or type is invalid.","invalid_stream_event");if(shouldIgnore(state,source.type,cursor))return state;const usage=copyUsage(usageFor(state));switch(source.type){case"reset":{const reset=createAgentStreamState(state.limits);return commit(state,reset,emptyUsage(),cursor)}case"run-start":{if(!validIdentifier(source.runId,state.limits))return failEvent(state,cursor,"Run start has an invalid run id.","invalid_stream_event");const started=createAgentStreamState(state.limits);return started.runId=source.runId,started.status={kind:"running"},commit(state,started,emptyUsage(),cursor)}case"stream-interrupt":case"stream-resume":{if(source.runId!==state.runId||!state.runId)return state;const interrupting=source.type==="stream-interrupt";if(interrupting&&!validInterruption(source.interruption,state.limits))return failEvent(state,cursor,"Stream interruption has an invalid shape.","invalid_stream_event");if(!interrupting&&state.interruption?.resumable!==!0)return state;const interruption=interrupting?source.interruption:void 0,messages=[];for(const current of state.messages){const parts=current.parts?.map(part=>{if(interrupting)return part.state==="streaming"?{...part,state:"interrupted",interruption}:part;if(part.state!=="interrupted"||part.interruption?.resumable!==!0)return part;const{interruption:_interruption,...resumed}=part;return{...resumed,state:"streaming"}}),message=ownedMessage({...current,...parts?{parts}:{}},state.limits);if(!message)return failEvent(state,cursor,"Interrupted message exceeds the configured limit.","stream_limit_exceeded");messages.push(message.value),replaceUsageEntry(usage,"messages",message.value.id,message.bytes)}return commit(state,{...state,messages,interruption},usage,cursor)}case"run-status":{if(!validStatus(source.status,state.limits)||source.runId!==void 0&&!validIdentifier(source.runId,state.limits))return failEvent(state,cursor,"Run status has an invalid shape.","invalid_stream_event");const status=source.status,error=status.kind==="error"?{message:status.message??state.error?.message??"Agent run failed",...state.error?.code&&(!status.message||status.message===state.error.message)?{code:state.error.code}:{}}:void 0;return commit(state,{...state,runId:source.runId??state.runId,status,error},usage,cursor)}case"messages-snapshot":{if(!Array.isArray(source.messages)||source.messages.length>state.limits.maxMessages)return failEvent(state,cursor,"Message snapshot exceeds the configured limit.","stream_limit_exceeded");const messages=[],messageBytes=new Map;let total=usage.totalBytes-[...usage.messages.values()].reduce((sum,bytes)=>sum+bytes,0);for(const candidate of source.messages){const message=ownedMessage(candidate,state.limits);if(!message||messageBytes.has(message.value.id))return failEvent(state,cursor,"Message snapshot contains an invalid or duplicate message.","invalid_stream_event");messages.push(message.value),messageBytes.set(message.value.id,message.bytes),total+=message.bytes}usage.messages.clear();for(const[id,bytes]of messageBytes)usage.messages.set(id,bytes);return usage.totalBytes=total,commit(state,{...state,messages},usage,cursor)}case"message-start":{const incoming=ownedMessage(source.message,state.limits);if(!incoming)return failEvent(state,cursor,"Message has an invalid shape.","invalid_stream_event");const index=state.messages.findIndex(message2=>message2.id===incoming.value.id);if(index<0&&state.messages.length>=state.limits.maxMessages)return failEvent(state,cursor,"Message count exceeds the configured limit.","stream_limit_exceeded");const existing=index>=0?state.messages[index]:void 0,merged=existing?{...existing,...incoming.value}:incoming.value,message=ownedMessage(merged,state.limits);if(!message)return failEvent(state,cursor,"Message has an invalid shape.","invalid_stream_event");const messages=[...state.messages];return index<0?messages.push(message.value):messages[index]=message.value,replaceUsageEntry(usage,"messages",message.value.id,message.bytes),commit(state,{...state,messages},usage,cursor)}case"message-part-upsert":{if(!validIdentifier(source.messageId,state.limits)||source.role!==void 0&&!MESSAGE_ROLES.has(source.role))return failEvent(state,cursor,"Message part target is invalid.","invalid_stream_event");const part=ownedPart(source.part,state.limits);if(!part)return failEvent(state,cursor,"Message part has an invalid shape.","invalid_stream_event");const messageIndex=state.messages.findIndex(message2=>message2.id===source.messageId);if(messageIndex<0&&state.messages.length>=state.limits.maxMessages)return failEvent(state,cursor,"Message count exceeds the configured limit.","stream_limit_exceeded");const current=messageIndex>=0?state.messages[messageIndex]:{id:source.messageId,role:source.role??"assistant",status:"streaming",parts:[]},parts=[...current.parts??[]],partIndex=parts.findIndex(candidate=>candidate.id===part.value.id);if(parts[partIndex]?.state==="interrupted")return commit(state,state,usage,cursor);if(partIndex<0&&parts.length>=state.limits.maxPartsPerMessage)return failEvent(state,cursor,"Message part count exceeds the configured limit.","stream_limit_exceeded");partIndex<0?parts.push(part.value):parts[partIndex]=part.value;const message=ownedMessage({...current,parts},state.limits);if(!message)return failEvent(state,cursor,"Updated message has an invalid shape.","invalid_stream_event");const messages=[...state.messages];return messageIndex<0?messages.push(message.value):messages[messageIndex]=message.value,replaceUsageEntry(usage,"messages",message.value.id,message.bytes),commit(state,{...state,messages},usage,cursor)}case"message-part-delta":{if(!validIdentifier(source.messageId,state.limits)||!validIdentifier(source.partId,state.limits)||source.partType!=="text"&&source.partType!=="reasoning"||typeof source.delta!="string"||source.role!==void 0&&!MESSAGE_ROLES.has(source.role))return failEvent(state,cursor,"Message delta has an invalid shape.","invalid_stream_event");if(source.delta.length>state.limits.maxDeltaCharacters)return failEvent(state,cursor,"Message delta exceeds the configured limit.","stream_limit_exceeded");const messageIndex=state.messages.findIndex(message2=>message2.id===source.messageId);if(messageIndex<0&&state.messages.length>=state.limits.maxMessages)return failEvent(state,cursor,"Message count exceeds the configured limit.","stream_limit_exceeded");const retained=messageIndex>=0?state.messages[messageIndex]:{id:source.messageId,role:source.role??"assistant",status:"streaming",parts:[]},current=ownedMessageLimits.get(retained)===state.limits?retained:ownedMessage(retained,state.limits)?.value;if(!current)return failEvent(state,cursor,"Updated message has an invalid shape.","invalid_stream_event");const parts=[...current.parts??[]],partIndex=parts.findIndex(part2=>part2.id===source.partId),previous=partIndex>=0?parts[partIndex]:void 0;if(previous?.state==="interrupted")return commit(state,state,usage,cursor);if(previous&&previous.type!=="text"&&previous.type!=="reasoning")return failEvent(state,cursor,"Message delta targets a non-text part.","invalid_stream_event");if(partIndex<0&&parts.length>=state.limits.maxPartsPerMessage)return failEvent(state,cursor,"Message part count exceeds the configured limit.","stream_limit_exceeded");const text=(previous?.text??"")+source.delta;if(text.length>state.limits.maxTextCharactersPerPart)return failEvent(state,cursor,"Message text exceeds the configured limit.","stream_limit_exceeded");const priorMetrics=previous?retainedMetrics(previous):void 0,appended=appendedTextMetrics(priorMetrics,source.delta),part=Object.assign(Object.create(null),{id:source.partId,type:source.partType,text:"",state:"streaming"}),partMetrics=retainedMetrics(part);partMetrics.bytes+=appended.bytes,partMetrics.textBytes=appended.bytes,partMetrics.textTail=appended.tail,(part.type==="text"||part.type==="reasoning")&&(part.text=text);const currentMetrics=retainedMetrics(current),messageMetrics={bytes:currentMetrics.bytes+partMetrics.bytes-(priorMetrics?.bytes??0)+(current.parts?0:13),nodes:currentMetrics.nodes+partMetrics.nodes-(priorMetrics?.nodes??0)+(current.parts?0:1),depth:Math.max(currentMetrics.depth,partMetrics.depth+2)};if(messageMetrics.bytes>state.limits.maxSnapshotBytes||messageMetrics.nodes>state.limits.maxSnapshotNodes||messageMetrics.depth>state.limits.maxSnapshotDepth)return failEvent(state,cursor,"Updated message has an invalid shape.","invalid_stream_event");partIndex<0?parts.push(part):parts[partIndex]=part;const message=Object.assign(Object.create(null),current,{parts});metricsByValue.set(message,messageMetrics),ownedMessageLimits.set(message,state.limits);const messages=[...state.messages];return messageIndex<0?messages.push(message):messages[messageIndex]=message,replaceUsageEntry(usage,"messages",message.id,messageMetrics.bytes),commit(state,{...state,messages},usage,cursor)}case"message-complete":{if(!validIdentifier(source.messageId,state.limits))return failEvent(state,cursor,"Message completion target is invalid.","invalid_stream_event");const index=state.messages.findIndex(message2=>message2.id===source.messageId);if(index<0)return commit(state,state,usage,cursor);const current=state.messages[index],parts=current.parts?.map(part=>part.state==="interrupted"?part:{...part,state:"complete"}),message=ownedMessage({...current,status:current.parts?.some(part=>part.state==="interrupted")?current.status:"sent",...parts?{parts}:{}},state.limits);if(!message)return failEvent(state,cursor,"Completed message has an invalid shape.","invalid_stream_event");const messages=[...state.messages];return messages[index]=message.value,replaceUsageEntry(usage,"messages",message.value.id,message.bytes),commit(state,{...state,messages},usage,cursor)}case"tool-upsert":{const incoming=ownedTool(source.invocation,state.limits);if(!incoming)return failEvent(state,cursor,"Tool invocation has an invalid shape.","invalid_stream_event");const index=state.tools.findIndex(tool2=>tool2.id===incoming.value.id);if(index<0&&state.tools.length>=state.limits.maxTools)return failEvent(state,cursor,"Tool count exceeds the configured limit.","stream_limit_exceeded");const tool=ownedTool(index<0?incoming.value:{...state.tools[index],...incoming.value},state.limits);if(!tool)return failEvent(state,cursor,"Tool invocation has an invalid shape.","invalid_stream_event");const tools=[...state.tools];return index<0?tools.push(tool.value):tools[index]=tool.value,replaceUsageEntry(usage,"tools",tool.value.id,tool.bytes),commit(state,{...state,tools},usage,cursor)}case"state-snapshot":{const snapshot=ownValue(source.snapshot,state.limits);return snapshot?(usage.totalBytes+=snapshot.bytes-usage.sharedStateBytes,usage.sharedStateBytes=snapshot.bytes,commit(state,{...state,sharedState:snapshot.value},usage,cursor)):failEvent(state,cursor,"Shared state snapshot is invalid.","invalid_stream_event")}case"state-delta":{const patch=parseJsonPatch(source.patch,state.limits);if(!patch)return failEvent(state,cursor,"Shared state patch is invalid.","invalid_stream_event");const current=ownValue(state.sharedState,state.limits);if(!current)return failEvent(state,cursor,"Retained shared state is invalid.","invalid_stream_event");let patched=current.value;for(const operation of patch)patched=applyPatchOperation(patched,operation);const snapshot=ownValue(patched,state.limits);return snapshot?(usage.totalBytes+=snapshot.bytes-usage.sharedStateBytes,usage.sharedStateBytes=snapshot.bytes,commit(state,{...state,sharedState:snapshot.value},usage,cursor)):failEvent(state,cursor,"Shared state exceeds the configured limit.","stream_limit_exceeded")}case"error":{if(typeof source.message!="string"||source.message.length>state.limits.maxStatusMessageCharacters||!validOptionalString(source.code,state.limits.maxIdentifierCharacters))return failEvent(state,cursor,"Error event has an invalid shape.","invalid_stream_event");const error={message:source.message,...source.code?{code:source.code}:{}};return commit(state,{...state,status:{kind:"error",message:source.message},error},usage,cursor)}default:return failEvent(state,cursor,"Stream event type is not supported.","invalid_stream_event")}}function reduceAgentStreamEvents(state,events){return events.reduce(reduceAgentStream,state)}export{DEFAULT_AGENT_STREAM_LIMITS,applySharedStatePatch,createAgentStreamState,parseJsonPatch,reduceAgentStream,reduceAgentStreamEvents};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type McpAppProtocol='legacy'|'mcp-apps';export type McpAppRequestId=string|number;export type McpAppRequestMethod='tools/call'|'tools/list'|'resources/list'|'resources/templates/list'|'resources/read'|'ui/message'|'ui/open-link'|'ui/update-model-context';export type McpAppNotificationMethod='ui/notifications/tool-input'|'ui/notifications/tool-input-partial'|'ui/notifications/tool-result'|'ui/notifications/tool-cancelled'|'ui/notifications/host-context-changed';
|
|
2
|
+
/** Supported capabilities only; permissions for browser APIs belong to the resource instead.*/
|
|
3
|
+
export interface McpAppHostCapabilities{readonly serverTools?:Readonly<Record<string,never>>;readonly serverResources?:Readonly<Record<string,never>>;readonly openLinks?:Readonly<Record<string,never>>;readonly logging?:Readonly<Record<string,never>>;readonly message?:{readonly text?:Readonly<Record<string,never>>;};readonly updateModelContext?:{readonly text?:Readonly<Record<string,never>>;readonly structuredContent?:Readonly<Record<string,never>>;};}export interface McpAppRequestDetail{requestId:McpAppRequestId;
|
|
4
|
+
/** Opaque identity for this request instance, independent of reusable wire IDs.*/
|
|
5
|
+
requestToken:string;method:McpAppRequestMethod;params:Readonly<Record<string,unknown>>;frameGeneration:number;
|
|
6
|
+
/** Aborted when cancelled, timed out, replaced, disconnected, or torn down.*/
|
|
7
|
+
signal:AbortSignal;}export type McpAppResponseOptions={frameGeneration:number;requestToken:string;}&({result:Readonly<Record<string,unknown>>;error?:never;}|{result?:never;error:{code:number;message:string;data?:unknown;};});export declare function mcpRecord(value:unknown):Record<string,unknown> |null;
|
|
8
|
+
/** Bound wire values before normalization; undefined optional object fields are omitted by JSON.*/
|
|
9
|
+
export declare function boundedMcpValue(value:unknown):boolean;
|
|
10
|
+
/** A session has one document and one negotiation; changing either requires a new session.*/
|
|
11
|
+
export declare class McpAppSession{private readonly options;private phase;private readonly pending;private teardown?;private capabilities;private hostContext;private pendingHostContext;constructor(options:{generation:number;capabilities:McpAppHostCapabilities;context:Record<string,unknown>;send:(message:Record<string,unknown>)=>void;request:(detail:McpAppRequestDetail)=>void;initialized:()=>void;resize:(height:number)=>void;log:(level:string,data:unknown)=>void;});private send;private error;receive(data:unknown):void;private clearRequest;respond(id:McpAppRequestId,options:McpAppResponseOptions):boolean;
|
|
12
|
+
/** Retain host context for negotiation and deliver changes only once the app is ready.*/
|
|
13
|
+
updateHostContext(params:Record<string,unknown>):boolean;notify(method:McpAppNotificationMethod,params:Record<string,unknown>):boolean;teardownResource():Promise<boolean>;close(acknowledged?:boolean):void;}
|
|
14
|
+
/** Only trusted code runs in this outer sandbox. App bytes are assigned to a second opaque frame.*/
|
|
15
|
+
export declare const MCP_APP_PROXY_DOCUMENT="<!doctype html><html><head><meta name=\"referrer\" content=\"no-referrer\"></head>\n<body style=\"margin:0\"><script>\n(() => {\n let port, nonce, app, stopped = false, loaded = false;\n const envelope = message => ({ channel: 'lyra-mcp-app', version: 1, type: 'mcp-apps', nonce, message });\n addEventListener('message', event => {\n if (!port && event.source === parent && event.data?.type === 'host-context' && event.ports[0]) {\n port = event.ports[0]; nonce = event.data.nonce;\n port.onmessage = incoming => {\n const data = incoming.data;\n if (stopped || data?.nonce !== nonce) return;\n if (data.type === 'mcp-resource' && !app) {\n app = document.createElement('iframe');\n app.title = data.title;\n app.setAttribute('sandbox', 'allow-forms allow-scripts');\n app.setAttribute('referrerpolicy', 'no-referrer');\n app.setAttribute('allow', data.allow);\n app.style.cssText = 'border:0;width:100%;height:100vh;display:block';\n app.addEventListener('load', () => {\n if (!loaded) { loaded = true; return; }\n stopped = true;\n port.postMessage({ channel: 'lyra-mcp-app', version: 1, type: 'mcp-navigation', nonce });\n port.close(); app.remove();\n });\n if (typeof data.html === 'string') app.srcdoc = data.html;\n else app.src = data.src;\n document.body.append(app);\n } else if (data.type === 'mcp-apps' && app) app.contentWindow.postMessage(data.message, '*');\n };\n port.start();\n } else if (!stopped && app && event.source === app.contentWindow && event.origin === 'null' && event.data?.jsonrpc === '2.0') {\n port.postMessage(envelope(event.data));\n }\n });\n})();\n</script></body></html>";
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const PROTOCOL_VERSION="2026-01-26",MAX_PENDING=64,REQUEST_TIMEOUT=3e4;function mcpRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function boundedMcpValue(value){const seen=new WeakSet,pending=[{value,depth:0}];let count=0,characters=0;for(;pending.length;){const current=pending.pop();if(++count>1e4||current.depth>32)return!1;const item=current.value;if(typeof item=="string")characters+=item.length;else if(typeof item=="number"){if(!Number.isFinite(item))return!1}else if(item!==null&&typeof item=="object"){if(seen.has(item)||Array.isArray(item)&&item.length>1e4)return!1;seen.add(item);const prototype=Object.getPrototypeOf(item);if(!Array.isArray(item)&&prototype!==Object.prototype&&prototype!==null)return!1;const entries=Object.entries(Object.getOwnPropertyDescriptors(item));if(entries.length+count+pending.length>1e4||Array.isArray(item)&&entries.length!==item.length+1)return!1;for(const[key,descriptor]of entries)if(!(Array.isArray(item)&&key==="length")){if(!("value"in descriptor))return!1;characters+=key.length,!(descriptor.value===void 0&&!Array.isArray(item))&&pending.push({value:descriptor.value,depth:current.depth+1})}}else if(item!==null&&typeof item!="boolean")return!1;if(characters>1048576)return!1}return!0}function validId(value){return typeof value=="string"?value.length>0&&value.length<=256:typeof value=="number"&&Number.isSafeInteger(value)}function textContent(value){return Array.isArray(value)&&value.every(item=>{const block=mcpRecord(item);return block?.type==="text"&&typeof block.text=="string"})}function enabled(value){return mcpRecord(value)!==null}class McpAppSession{constructor(options){this.options=options,this.phase="new",this.pending=new Map,this.capabilities={},this.pendingHostContext=!1,this.hostContext=options.context}send(message){if(this.phase!=="closed"&&boundedMcpValue(message)){const normalized=JSON.parse(JSON.stringify(message));this.options.send({jsonrpc:"2.0",...normalized})}}error(id,code,message){this.send({id,error:{code,message}})}receive(data){if(this.phase==="closed"||!boundedMcpValue(data))return;const message=mcpRecord(JSON.parse(JSON.stringify(data)));if(!message||message.jsonrpc!=="2.0")return;const id=message.id,method=message.method,params=mcpRecord(message.params);if(method===void 0){if(this.teardown&&id===this.teardown.id&&"result"in message!="error"in message&&(mcpRecord(message.result)||mcpRecord(message.error))){const acknowledged=mcpRecord(message.result)!==null;this.close(acknowledged)}return}if(typeof method!="string"||"id"in message&&!validId(id)||"result"in message||"error"in message)return;if(method==="ui/initialize"&&validId(id)){const info=mcpRecord(params?.appInfo);if(this.phase!=="new"){this.error(id,-32600,"Already initialized");return}if(typeof params?.protocolVersion!="string"||!info||typeof info.name!="string"||typeof info.version!="string"||!mcpRecord(params.appCapabilities)){this.error(id,-32602,"Invalid initialization parameters");return}const offered=mcpRecord(this.options.capabilities)??{};this.capabilities={...enabled(offered.serverTools)?{serverTools:{}}:{},...enabled(offered.serverResources)?{serverResources:{}}:{},...enabled(offered.openLinks)?{openLinks:{}}:{},...enabled(offered.logging)?{logging:{}}:{},...enabled(mcpRecord(offered.message)?.text)?{message:{text:{}}}:{},...enabled(offered.updateModelContext)?{updateModelContext:{...enabled(mcpRecord(offered.updateModelContext)?.text)?{text:{}}:{},...enabled(mcpRecord(offered.updateModelContext)?.structuredContent)?{structuredContent:{}}:{}}}:{}},this.phase="initializing",this.send({id,result:{protocolVersion:PROTOCOL_VERSION,hostInfo:{name:"Lyra UI",version:"1"},hostCapabilities:this.capabilities,hostContext:this.hostContext}});return}if(method==="ui/notifications/initialized"&&id===void 0&&this.phase==="initializing"){this.phase="ready",this.pendingHostContext&&(this.pendingHostContext=!1,this.notify("ui/notifications/host-context-changed",this.hostContext)),this.options.initialized();return}if(this.phase!=="ready"){validId(id)&&this.error(id,-32600,"App is not ready");return}if(method==="notifications/cancelled"&&id===void 0){const requestId=params?.requestId;validId(requestId)&&this.clearRequest(requestId,!0);return}if(method==="ui/notifications/size-changed"&&id===void 0){typeof params?.height=="number"&&Number.isFinite(params.height)&&this.options.resize(params.height);return}if(method==="notifications/message"&&id===void 0&&this.capabilities.logging){typeof params?.level=="string"&&this.options.log(params.level,params.data);return}if(!validId(id))return;if(this.pending.has(id)){this.clearRequest(id,!0),this.error(id,-32600,"Duplicate request id");return}if(method==="ping"){this.send({id,result:{}});return}if(method==="ui/request-display-mode"){["inline","fullscreen","pip"].includes(String(params?.mode))?this.send({id,result:{mode:"inline"}}):this.error(id,-32602,"Invalid display mode");return}const capability={"tools/call":"serverTools","tools/list":"serverTools","resources/list":"serverResources","resources/templates/list":"serverResources","resources/read":"serverResources","ui/message":"message","ui/open-link":"openLinks","ui/update-model-context":"updateModelContext"}[method];if(!capability||!this.capabilities[capability]){this.error(id,-32601,"Method not available");return}const requestParams=params??{};let valid=message.params===void 0||params!==null;if(method==="tools/call"&&(valid&&=typeof requestParams.name=="string"&&requestParams.name.length>0&&(requestParams.arguments===void 0||mcpRecord(requestParams.arguments)!==null)),method==="resources/read"&&(valid&&=typeof requestParams.uri=="string"&&requestParams.uri.length>0),["tools/list","resources/list","resources/templates/list"].includes(method)&&(valid&&=requestParams.cursor===void 0||typeof requestParams.cursor=="string"),method==="ui/message"&&(valid&&=requestParams.role==="user"&&textContent(requestParams.content)),method==="ui/update-model-context"&&(valid&&=(requestParams.content===void 0||!!this.capabilities.updateModelContext?.text&&textContent(requestParams.content))&&(requestParams.structuredContent===void 0||!!this.capabilities.updateModelContext?.structuredContent&&mcpRecord(requestParams.structuredContent)!==null)),method==="ui/open-link")try{valid&&=["https:","http:","mailto:"].includes(new URL(String(requestParams.url)).protocol)}catch{valid=!1}if(!valid){this.error(id,-32602,"Invalid request parameters");return}if(this.pending.size>=64){this.error(id,-32e3,"Too many pending requests");return}const controller=new AbortController,requestToken=crypto.randomUUID(),timer=setTimeout(()=>{this.error(id,-32e3,"Host request timed out"),this.clearRequest(id,!0)},3e4);this.pending.set(id,{requestToken,controller,timer}),this.options.request({requestId:id,requestToken,method,params:requestParams,frameGeneration:this.options.generation,signal:controller.signal})}clearRequest(id,abort){const request=this.pending.get(id);request&&(this.pending.delete(id),clearTimeout(request.timer),abort&&request.controller.abort())}respond(id,options){const request=this.pending.get(id);if(this.phase!=="ready"||!request||options?.frameGeneration!==this.options.generation||options.requestToken!==request.requestToken||!boundedMcpValue(options))return!1;const value=mcpRecord(JSON.parse(JSON.stringify(options))),error=mcpRecord(value.error),result=mcpRecord(value.result);return"result"in value=="error"in value||!result&&(!error||!Number.isInteger(error.code)||typeof error.message!="string")?!1:(this.send({id,...result?{result}:{error}}),this.clearRequest(id,!1),!0)}updateHostContext(params){if(this.phase==="closing"||this.phase==="closed"||!mcpRecord(params)||!boundedMcpValue(params))return!1;const context={...this.hostContext,...JSON.parse(JSON.stringify(params))};return boundedMcpValue(context)?(this.hostContext=context,this.phase==="ready"?this.notify("ui/notifications/host-context-changed",context):this.phase==="initializing"&&(this.pendingHostContext=!0),!0):!1}notify(method,params){return this.phase!=="ready"||!["ui/notifications/tool-input","ui/notifications/tool-input-partial","ui/notifications/tool-result","ui/notifications/tool-cancelled","ui/notifications/host-context-changed"].includes(method)||!mcpRecord(params)||!boundedMcpValue(params)?!1:(this.send({method,params}),!0)}teardownResource(){if(this.phase!=="ready")return Promise.resolve(!1);this.phase="closing";for(const id of this.pending.keys())this.clearRequest(id,!0);return new Promise(resolve=>{const id=`teardown:${crypto.randomUUID()}`,timer=setTimeout(()=>this.close(!1),1e3);this.teardown={id,resolve,timer},this.send({id,method:"ui/resource-teardown",params:{}})})}close(acknowledged=!1){this.phase="closed";for(const id of this.pending.keys())this.clearRequest(id,!0);this.teardown&&(clearTimeout(this.teardown.timer),this.teardown.resolve(acknowledged),this.teardown=void 0)}}const MCP_APP_PROXY_DOCUMENT=`<!doctype html><html><head><meta name="referrer" content="no-referrer"></head>
|
|
2
|
+
<body style="margin:0"><script>
|
|
3
|
+
(() => {
|
|
4
|
+
let port, nonce, app, stopped = false, loaded = false;
|
|
5
|
+
const envelope = message => ({ channel: 'lyra-mcp-app', version: 1, type: 'mcp-apps', nonce, message });
|
|
6
|
+
addEventListener('message', event => {
|
|
7
|
+
if (!port && event.source === parent && event.data?.type === 'host-context' && event.ports[0]) {
|
|
8
|
+
port = event.ports[0]; nonce = event.data.nonce;
|
|
9
|
+
port.onmessage = incoming => {
|
|
10
|
+
const data = incoming.data;
|
|
11
|
+
if (stopped || data?.nonce !== nonce) return;
|
|
12
|
+
if (data.type === 'mcp-resource' && !app) {
|
|
13
|
+
app = document.createElement('iframe');
|
|
14
|
+
app.title = data.title;
|
|
15
|
+
app.setAttribute('sandbox', 'allow-forms allow-scripts');
|
|
16
|
+
app.setAttribute('referrerpolicy', 'no-referrer');
|
|
17
|
+
app.setAttribute('allow', data.allow);
|
|
18
|
+
app.style.cssText = 'border:0;width:100%;height:100vh;display:block';
|
|
19
|
+
app.addEventListener('load', () => {
|
|
20
|
+
if (!loaded) { loaded = true; return; }
|
|
21
|
+
stopped = true;
|
|
22
|
+
port.postMessage({ channel: 'lyra-mcp-app', version: 1, type: 'mcp-navigation', nonce });
|
|
23
|
+
port.close(); app.remove();
|
|
24
|
+
});
|
|
25
|
+
if (typeof data.html === 'string') app.srcdoc = data.html;
|
|
26
|
+
else app.src = data.src;
|
|
27
|
+
document.body.append(app);
|
|
28
|
+
} else if (data.type === 'mcp-apps' && app) app.contentWindow.postMessage(data.message, '*');
|
|
29
|
+
};
|
|
30
|
+
port.start();
|
|
31
|
+
} else if (!stopped && app && event.source === app.contentWindow && event.origin === 'null' && event.data?.jsonrpc === '2.0') {
|
|
32
|
+
port.postMessage(envelope(event.data));
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
})();
|
|
36
|
+
<\/script></body></html>`;export{MCP_APP_PROXY_DOCUMENT,McpAppSession,boundedMcpValue,mcpRecord};
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';export interface McpAppPermissions{readonly camera?:boolean;readonly microphone?:boolean;readonly geolocation?:boolean;readonly clipboardRead?:boolean;readonly clipboardWrite?:boolean;}export interface McpAppCsp{readonly connectDomains?:readonly string[];
|
|
1
|
+
import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{McpAppProtocol,McpAppHostCapabilities,McpAppRequestDetail,McpAppRequestId,McpAppResponseOptions,McpAppNotificationMethod}from'./mcp-app-protocol.js';export type{McpAppProtocol,McpAppHostCapabilities,McpAppRequestDetail,McpAppRequestId,McpAppResponseOptions,McpAppRequestMethod,McpAppNotificationMethod}from'./mcp-app-protocol.js';export interface McpAppPermissions{readonly camera?:boolean;readonly microphone?:boolean;readonly geolocation?:boolean;readonly clipboardRead?:boolean;readonly clipboardWrite?:boolean;}export interface McpAppCsp{readonly connectDomains?:readonly string[];
|
|
2
|
+
/** HTTP(S) origins authorized by the embedding host. In mcp-apps mode these also allow
|
|
3
|
+
* external scripts and styles; legacy mode keeps scripts and styles inline-only. */
|
|
4
|
+
readonly resourceDomains?:readonly string[];readonly frameDomains?:readonly string[];}interface McpAppResourceBase{readonly uri:string;readonly title?:string;readonly permissions?:McpAppPermissions;readonly metadata?:Readonly<Record<string,unknown>>;}
|
|
2
5
|
/** An executable app resource with exactly one document source.*/
|
|
3
6
|
export type McpAppResource=McpAppResourceBase&({
|
|
4
7
|
/** Executable app document. It is assigned only to a uniquely-origin sandboxed iframe.*/
|
|
@@ -9,7 +12,7 @@ readonly src:string;readonly html?:never;readonly csp?:never;});export interface
|
|
|
9
12
|
* valid `resource` replacement, adoption, or reconnect starts a fresh generation, so a host
|
|
10
13
|
* that hands this value back to `postToolResult()` has its asynchronous reply dropped instead
|
|
11
14
|
* of delivered into whatever unrelated app is mounted by the time it resolves. */
|
|
12
|
-
frameGeneration:number;}export type McpAppToolResultOptions={frameGeneration:number;result:unknown;error?:never;}|{frameGeneration:number;error:string;result?:never;};export interface LyraMcpAppEventMap{'lr-mcp-ready':CustomEvent<{uri:string;}>;'lr-mcp-tool-call':CustomEvent<McpAppToolCallDetail>;'lr-mcp-send-message':CustomEvent<{message:unknown;}>;'lr-mcp-open-link':CustomEvent<{href:string;}>;'lr-mcp-log':CustomEvent<{level:string;value:unknown;}>;'lr-mcp-resize':CustomEvent<{height:number;}>;}
|
|
15
|
+
frameGeneration:number;}export type McpAppToolResultOptions={frameGeneration:number;result:unknown;error?:never;}|{frameGeneration:number;error:string;result?:never;};export interface LyraMcpAppEventMap{'lr-mcp-ready':CustomEvent<{uri:string;}>;'lr-mcp-initialized':CustomEvent<{uri:string;frameGeneration:number;}>;'lr-mcp-request':CustomEvent<McpAppRequestDetail>;'lr-mcp-tool-call':CustomEvent<McpAppToolCallDetail>;'lr-mcp-send-message':CustomEvent<{message:unknown;}>;'lr-mcp-open-link':CustomEvent<{href:string;}>;'lr-mcp-log':CustomEvent<{level:string;value:unknown;}>;'lr-mcp-resize':CustomEvent<{height:number;}>;}
|
|
13
16
|
/**
|
|
14
17
|
* `<lr-mcp-app>` — hosts an MCP App-style executable UI resource in a uniquely-origin sandbox.
|
|
15
18
|
* Inline resources receive a trusted leading CSP meta before any caller-controlled HTML token, so
|
|
@@ -24,6 +27,13 @@ frameGeneration:number;}export type McpAppToolResultOptions={frameGeneration:num
|
|
|
24
27
|
* snapshots. Create and reassign a new resource record after changes.
|
|
25
28
|
*
|
|
26
29
|
* @customElement lr-mcp-app
|
|
30
|
+
* Set protocol to mcp-apps for the MCP Apps 2026-01-26 host subset: negotiation, tool data,
|
|
31
|
+
* host context, capability-gated tool/resource requests, inline display fallback, cancellation
|
|
32
|
+
* and graceful teardown. This mode uses a
|
|
33
|
+
* trusted outer proxy; the executable app uses standard JSON-RPC window messages inside its own
|
|
34
|
+
* opaque sandbox. The default legacy bridge remains separate.
|
|
35
|
+
* @event lr-mcp-initialized - The official app completed negotiation. `detail: { uri, frameGeneration }`.
|
|
36
|
+
* @event lr-mcp-request - A capability-gated official request. `detail: { requestId, requestToken, method, params, frameGeneration, signal }`.
|
|
27
37
|
* @event lr-mcp-ready - The frame loaded. `detail: { uri }`.
|
|
28
38
|
* @event lr-mcp-tool-call - The frame requested a tool.
|
|
29
39
|
* `detail: { requestId?, name, args, frameGeneration }`. `frameGeneration` is an opaque id for
|
|
@@ -45,6 +55,11 @@ frameGeneration:number;}export type McpAppToolResultOptions={frameGeneration:num
|
|
|
45
55
|
export declare class LyraMcpApp extends LyraElement<LyraMcpAppEventMap>{protected static collectionSupport:import("../../../internal/lyra-element.js").LyraCollectionSupport;protected static readonly ownedCollectionProperties:readonly string[];static styles:import("lit").CSSResultGroup[];
|
|
46
56
|
/** Clone-owned resource snapshot. Reassign a new record after changing its CSP collections.*/
|
|
47
57
|
resource:McpAppResource|null;
|
|
58
|
+
/** Transport dialect. Changing it remounts the app; legacy remains the default.*/
|
|
59
|
+
protocol:McpAppProtocol;
|
|
60
|
+
/** Clone-owned capabilities for official negotiation. Empty denies external actions; changing
|
|
61
|
+
* these capabilities remounts the app so grants cannot drift during a session. */
|
|
62
|
+
hostCapabilities:McpAppHostCapabilities;
|
|
48
63
|
/** Initial frame height: a number of pixels, or a CSS length in `px`, `rem`, `em`, `vw` or `vh`
|
|
49
64
|
* (resolved when set). Clamped to at least 120px and at most `max-height`; an unresolvable value
|
|
50
65
|
* uses the 320px default. */
|
|
@@ -57,7 +72,19 @@ maxHeight:number|string;
|
|
|
57
72
|
label:string;
|
|
58
73
|
/** Programmatic iframe title when no authored host `aria-label` attribute is present. An empty
|
|
59
74
|
* value cannot leave the executable frame unnamed. */
|
|
60
|
-
accessibleLabel:string|null;private loaded;private frameHeight;private frameGeneration;private frame?;private readonly announcements;private suppressNextResourceAnnouncement;private frameNonce?;private framePort?;private bootstrapPort?;private resourceAvailable;private invalidateFrame;private closeFramePort;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(_changed:PropertyValues<this>):void;private createFrameNonce;private onLoad;private onPortMessage;private heightPx;private maxHeightPx;private handleMessage;private post;
|
|
75
|
+
accessibleLabel:string|null;private loaded;private frameHeight;private frameGeneration;private protocolSession?;private deliveredEnvironment?;private pendingEnvironment?;private frame?;private readonly announcements;private suppressNextResourceAnnouncement;private frameNonce?;private framePort?;private bootstrapPort?;private resourceAvailable;private invalidateFrame;private closeFramePort;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(_changed:PropertyValues<this>):void;private createFrameNonce;private onLoad;private onPortMessage;private heightPx;private maxHeightPx;private handleMessage;private post;
|
|
76
|
+
/** Publish host context to the current app; official sessions retain updates during initialization.
|
|
77
|
+
* Locale and direction changes also publish automatically without replacing the loaded frame. */
|
|
78
|
+
postHostContext(context:unknown):void;
|
|
79
|
+
/** Replies to one official request instance. Return its requestToken and frameGeneration;
|
|
80
|
+
* unknown, cancelled, duplicate and stale replies are ignored even when wire IDs are reused. */
|
|
81
|
+
postMcpResponse(requestId:McpAppRequestId,options:McpAppResponseOptions):boolean;
|
|
82
|
+
/** Sends supported official tool/context notifications only after the app signals initialized.*/
|
|
83
|
+
postMcpNotification(method:McpAppNotificationMethod,params:Record<string,unknown>,frameGeneration:number):boolean;
|
|
84
|
+
/** Gives an initialized official app up to one second to acknowledge resource teardown.
|
|
85
|
+
* Returns whether it acknowledged; the session then rejects new requests. Remove or replace
|
|
86
|
+
* the resource after awaiting this method. Disconnection instead closes immediately. */
|
|
87
|
+
teardownApp():Promise<boolean>;
|
|
61
88
|
/** Resolves a prior `lr-mcp-tool-call`. The required frame generation binds the asynchronous
|
|
62
89
|
* reply to the frame that requested it; stale, uncorrelated, and ambiguous replies fail closed. */
|
|
63
|
-
postToolResult(requestId:string,options:McpAppToolResultOptions):void;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-mcp-app':LyraMcpApp;}}
|
|
90
|
+
postToolResult(requestId:string,options:McpAppToolResultOptions):void;private proxyDocument;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-mcp-app':LyraMcpApp;}}
|