@vivix-labs/studio-chat-mcp 0.1.14 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,122 @@
1
+ # Studio Chat MCP adapter
2
+
3
+ Studio loads this user-scoped server plugin into its Host process. The plugin owns MCP tools, chat declarations, card action routing, projection and the bundled MCP Apps page. Codex connects to the plugin's authenticated Streamable HTTP route.
4
+
5
+ ## Install and enable
6
+
7
+ The public Studio suite installer installs this Host plugin and its card provider, enables them in user scope, and registers the CLI `stdio` bridge (`vivix-studio agent mcp`) in the agent configuration. Existing server entries and personal Skills are preserved. CLI and Workbench operations are available immediately after installation. The current agent host decides when it exposes MCP tools and interactive cards. Use the unified `vivix-studio` Skill's `chat-interactions.md` for session handling and card routing.
8
+
9
+ Use the paired Studio CLI with SDK API 0.2.6, Node.js 22.12+ and pnpm 10.33.0. Build a standard Studio plugin directory from this repository.
10
+
11
+ ```sh
12
+ pnpm --filter @vivix-labs/studio-chat-mcp package "$PWD/artifacts/studio-chat-host"
13
+ vivix-studio plugin install "$PWD/artifacts/studio-chat-host/studio-chat-mcp"
14
+ vivix-studio plugin enable @vivix-labs/studio-chat-mcp --scope user --instance studio-chat --trust --allow-access host.operations
15
+ ```
16
+
17
+ Open a project and enable its business plugins normally. Discover their ready operations with `vivix-studio plugin describe`. Use ordinary `plugin call <adapter-instance> run --scope user --input <file> --json` or the MCP tools to open a card. The adapter also registers an `action` operation for subsequent clicks.
18
+
19
+ The package exports its chat protocol types from `@vivix-labs/studio-chat-mcp/shared`. Chat components import these types from the adapter package. The CLI SDK does not export chat types.
20
+
21
+ ## Connect an MCP client
22
+
23
+ For any MCP client that speaks `stdio` (Codex, Claude Code, Cursor, Antigravity, etc.), configure the CLI's built-in bridge command:
24
+
25
+ ```toml
26
+ [mcp_servers.vivix-studio-chat]
27
+ command = "vivix-studio"
28
+ args = ["agent", "mcp"]
29
+ ```
30
+
31
+ The bridge automatically starts the shared local Host if it is stopped, discovers the active `studio-chat` route credential, and forwards JSON-RPC messages to the Host over loopback HTTP — surviving Host restarts, port changes, and reboots without updating client configuration.
32
+
33
+ To inspect the underlying Host endpoint directly (e.g., for testing):
34
+
35
+ ```sh
36
+ printf '{}\n' > connection-input.json
37
+ vivix-studio plugin call studio-chat connection --scope user --input connection-input.json --json
38
+ ```
39
+
40
+ The plugin requires Studio plugin API 0.2.6. It exposes discovery and media reads on the same connection as `run_studio_action`, the app-only `studio_card_action`, and `ui://studio/chat/v13.html`. Its connection PID equals the Studio Host PID. Disabling the plugin removes the route through the normal plugin lifecycle. The current bundled MCP dependency requires an explicit Host restart for code upgrades when the generic reloader reports `restart_required`.
41
+
42
+ ## Discover and read through one connection
43
+
44
+ `list_chat_capabilities({})` defaults to `{kind:"user",id:"user"}` and returns ready reusable components, declared chat operations and read-only media queries with their actual `scope` and `target`. Component entries come from the enabled provider's existing `components.list`; the adapter does not keep a second component registry. Generic interactions need a user-scoped component provider and do not create a business project.
45
+
46
+ Pass the returned route to `describe_chat_capability({scope,target,componentId?})`. A component description contains its props, result, selected render input and examples, with local schema references intact. For saved project operations, use the selected project's explicit scope. The Host still enforces grants, readiness, bindings and receipts. Legacy `projectId` input remains supported; supplying both it and `scope` is rejected.
47
+
48
+ `query_studio_media({scope,target,input})` invokes only a discovered media query with read effects and no confirmation. Read its input schema first. Returned records, task output refs and file selections provide the immutable `ref: {storeId,objectId,versionId}` for `resolve_chat_media({scope,ref,fileId?})`.
49
+
50
+ `run_studio_action`, `studio_card_action` and `query_studio_media` treat `input` as a JSON object. A JSON-encoded object string from an MCP client is parsed once and normalized; arrays, scalars, `null` and strings that do not encode an object are rejected before any Host operation runs. Every discovered operation currently declares an object input schema, so this is the adapter contract rather than a per-operation setting.
51
+
52
+ The resolver delegates `{ref,fileId?,access:"https"}` to the existing backend file-access operation. The file service checks the selected bytes, follows a matching saved origin, reuses a usable stored HTTPS URL, or asks the original API provider for a fresh read ticket by its persisted remote ID and original task identity. Ordinary local reads keep their existing behavior. An unmatched local file is an explicit error; resolving never uploads, generates or substitutes another version. The MCP response contains the fixed ref, file ID, MIME type, HTTPS URL and optional expiry, without the Host path.
53
+
54
+ Tool `content` is a short readable receipt. `structuredContent` contains model-readable creative data and routing. Signed action bindings, the script digest and prepared messages travel in `_meta` for the App. The page reads the current registered renderer for the original versioned component ID through a read-only MCP resource, then verifies the response's component ID and script digest before mounting. Historical props use the current compatible appearance. The saved digest remains available for legacy clients. The page also accepts legacy replies whose public data contains bindings. A tool return proves neither that a client displayed the card nor that a click delivered a continuation; those require separate UI evidence.
55
+
56
+ The adapter's `resourceDomains` configuration declares canonical HTTPS origins for media and other resources. Its default is the Official media CDN, `https://static.vivi-x.ai`. Declare any additional verified source origins explicitly in this adapter's configuration. Discovery returns the active `resourceDomains`; a readable URL alone does not establish that a native host permits the iframe to load it. The component's own `mediaOrigins` further restricts each card. Do not use URL proxies, rehosting or disabled checks to evade a host URL-safety rejection.
57
+
58
+ - [Installation-to-card acceptance](acceptance/README.md)
59
+ - [Card page and sandbox](chat-ui/README.md)
60
+
61
+ ## Discover native action targets
62
+
63
+ Search `list_chat_capabilities({scope,kind:"nativeOperation",query,offset,limit})`.
64
+ The default limit is 20, the maximum is 100, and nextOffset identifies the next page.
65
+ Describe the returned target with kind=nativeOperation to read input/output schemas,
66
+ effects, confirm and contract. This includes operations without a chat declaration.
67
+ Discovery reads metadata without invoking business operations; default component
68
+ discovery does not expand into the whole native catalog.
69
+
70
+ An installed source may provide `dynamicActions(context)`. It resolves native
71
+ bindings from initial input or authenticated binding context. The adapter admits
72
+ those exact same-scope targets through host.operations, signs them with the source
73
+ and retains invokeBound recovery. The resolver is installed server code; browser
74
+ input never supplies a destination or callback. Static dependency rules are unchanged.
75
+
76
+ ## Declare a chat operation
77
+
78
+ The App-only `read_local_media` tool reads a supplied absolute image, audio or video `path`
79
+ and byte `offset` directly on the local Host. Each response contains at most
80
+ 256 KiB in `_meta["studio/media"]`; binary data does not enter public tool output.
81
+ Local images support PNG, JPEG and WebP through the same chunk and Blob transport.
82
+ The component receives an optional `readMedia` callback through the sandbox bridge,
83
+ which accepts only paths declared by the original card projection. Later reads
84
+ carry the initial file identity/size/mtime and reject changes. No preview registry,
85
+ public media endpoint, import or CLI SDK change is involved. Existing HTTPS media
86
+ and action dispatch keep their current routes. Use a matching component package
87
+ and adapter; local paths require the Host to share the caller's filesystem.
88
+
89
+ A business plugin publishes `extensions: { chat: { component, projectResult, actions } }`
90
+ on its operation and registers the component in the manifest's `components` field.
91
+ The adapter routes `(action, input)` to the declared destination. Business plugins
92
+ own object identity, validation, input mapping, and writes. See the
93
+ [component contract](chat-ui/README.md) for Props and Host receipt recovery.
94
+
95
+ Card projectors may return optional server-only `bindingContext` JSON. The adapter
96
+ puts it inside the existing signed Host operation bindings, strips the top-level
97
+ field from the public projection, and supplies the authenticated snapshot as
98
+ `ChatActionContext.bindingContext` and `ChatProjectionContext.bindingContext`.
99
+ Browser action input never supplies that context. Updated projections can replace
100
+ it; unchanged legacy cards omit it and keep context-free bindings. The Host keeps
101
+ its existing size limit, scope/caller authentication, generation validation and
102
+ receipt-before-preparation replay. Context is signed for integrity, not encrypted;
103
+ do not put secrets in it.
104
+
105
+ ## Send a follow-up message
106
+
107
+ A declared action can provide `prepareMessage(request, context)` instead of a
108
+ target. The adapter authenticates the original source binding and passes its
109
+ server-owned context to this callback. The callback returns `{intent, data}` with
110
+ a nonempty intent and JSON object data. This read-only path invokes no business
111
+ operation and creates no business receipt.
112
+
113
+ When the client advertises structured model context, the outer MCP App uses
114
+ `updateModelContext` for the exact interaction data, then sends the readable
115
+ request. Clients with messaging but without structured context receive the
116
+ request followed by the complete interaction JSON in the same message.
117
+ The sandbox receives the result status without prepared message metadata.
118
+
119
+ Unsupported or rejected sends retain the draft. Unknown sends retain their
120
+ original request identity and are not automatically resent. The component's
121
+ prompt and target actions remain exclusive per button. If a client advertises
122
+ structured context but the update fails, the page retains the draft.
@@ -16,6 +16,9 @@
16
16
  color: var(--color-text-primary, CanvasText);
17
17
  background: var(--color-background-primary, Canvas);
18
18
  }
19
+ :root[data-video-gallery] {
20
+ scrollbar-width: none;
21
+ }
19
22
  #summary {
20
23
  margin: 0 0 8px;
21
24
  white-space: pre-wrap;
@@ -151,8 +154,8 @@ Boolean requesting whether a visible border and background is provided by the ho
151
154
  - "model": Tool visible to and callable by the agent
152
155
  - "app": Tool callable by the app from this server only`),csp:h.never().optional(),permissions:h.never().optional()}),mU=h.object({mimeTypes:h.array(h.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),pU=h.object({method:h.literal("ui/download-file"),params:h.object({contents:h.array(h.union([En,Cn])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),fU=h.object({method:h.literal("ui/message"),params:h.object({role:h.literal("user").describe('Message role, currently only "user" is supported.'),content:h.array(Xt).describe("Message content blocks (text, image, etc.).")})}),hU=h.object({method:h.literal("ui/notifications/sandbox-resource-ready"),params:h.object({html:h.string().describe("HTML content to load into the inner iframe."),sandbox:h.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Qv.optional().describe("CSP configuration from resource metadata."),permissions:e_.optional().describe("Sandbox permissions from resource metadata.")})}),XE=h.object({method:h.literal("ui/notifications/tool-result"),params:Zr.describe("Standard MCP tool execution result.")}),Iz=h.object({toolInfo:h.object({id:Tt.optional().describe("JSON-RPC id of the tools/call request."),tool:Vr.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:jE.optional().describe("Current color theme preference."),styles:HE.optional().describe("Style configuration for theming the app."),displayMode:Vc.optional().describe("How the UI is currently displayed."),availableDisplayModes:h.array(Vc).optional().describe("Display modes the host supports."),containerDimensions:h.union([h.object({height:h.number().describe("Fixed container height in pixels.")}),h.object({maxHeight:h.union([h.number(),h.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(h.union([h.object({width:h.number().describe("Fixed container width in pixels.")}),h.object({maxWidth:h.union([h.number(),h.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
153
156
  container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:h.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:h.string().optional().describe("User's timezone in IANA format."),userAgent:h.string().optional().describe("Host application identifier."),platform:h.union([h.literal("web"),h.literal("desktop"),h.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:h.object({touch:h.boolean().optional().describe("Whether the device supports touch input."),hover:h.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:h.object({top:h.number().describe("Top safe area inset in pixels."),right:h.number().describe("Right safe area inset in pixels."),bottom:h.number().describe("Bottom safe area inset in pixels."),left:h.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),QE=h.object({method:h.literal("ui/notifications/host-context-changed"),params:Iz.describe("Partial context update containing only changed fields.")}),gU=h.object({method:h.literal("ui/update-model-context"),params:h.object({content:h.array(Xt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:h.record(h.string(),h.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),vU=h.object({method:h.literal("ui/initialize"),params:h.object({appInfo:Wt.describe("App identification (name and version)."),appCapabilities:GE.describe("Features and capabilities this app provides."),protocolVersion:h.string().describe("Protocol version this app supports.")})}),eC=h.object({protocolVersion:h.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Wt.describe("Host application identification and version."),hostCapabilities:KE.describe("Features and capabilities provided by the host."),hostContext:Iz.describe("Rich context about the host environment.")}).passthrough(),tC={target:"draft-2020-12"};async function kz(e,t){let n=e["~standard"];if(n.jsonSchema)return n.jsonSchema[t](tC);throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function xz(e,t,n=""){let o=await e["~standard"].validate(t);if(o.issues){let r=o.issues.map(i=>{let a=i.path?.map(s=>typeof s=="object"?s.key:s).join(".");return a?`${a}: ${i.message}`:i.message}).join("; ");throw Error(n+r)}return o.value}function rC(e,t){let n={...e,...t};return t.experimental!==void 0&&(n.experimental={...e.experimental,...t.experimental}),t.tools!==void 0&&(n.tools={...e.tools,...t.tools}),n}var Qd=class e extends Lc{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new Wv;_methods=new Yv;setRequestHandler=(...t)=>{let[n,...o]=zz("request",t)??t;this._methods.claim(n,"setRequestHandler"),super.setRequestHandler.call(this,n,...o)};setNotificationHandler=(...t)=>{let[n,...o]=zz("notification",t)??t;this._methods.claim(n,"setNotificationHandler"),super.setNotificationHandler.call(this,n,...o)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...n)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...n)};_assertInitialized(t){if(this._initializedSent)return;let n=`[ext-apps] App.${t}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(n);console.warn(`${n}. This will throw in a future release.`)}eventSchemas={toolinput:qE,toolinputpartial:VE,toolresult:XE,toolcancelled:ZE,hostcontextchanged:QE};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(t,n){n&&this._assertHandlerTiming(t),this._ensureEventSlot(t),this._events.setHandler(t,n)}addEventListener(t,n){this._assertHandlerTiming(t),this._ensureEventSlot(t),this._events.addEventListener(t,n)}removeEventListener(t,n){this._events.removeEventListener(t,n)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let n=this.eventSchemas[t];if(!n)throw Error(`Unknown event: ${String(t)}`);this.setNotificationHandler(n.shape.method.value,{params:n.shape.params},o=>{let r=o;t==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...r}),this._events.dispatch(t,r)}),this._registeredEvents.add(t)}getEventHandler(t){return this._events.getHandler(t)}warnIfRequestHandlerReplaced(t,n,o){n&&o&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,n={},o={autoResize:!0}){super(o),this._appInfo=t,this._appCapabilities=n,this.options=o,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!o.allowUnsafeEval&&h.config({jitless:!0}),this.replaceRequestHandler("ping",r=>(console.log("Received ping:",r.params),{})),this.setEventHandler("hostcontextchanged",void 0)}buildContext(t){return t}registerAppCapabilities(t){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=rC(this._appCapabilities,t)}registerTool(t,n,o){if(this._registeredTools[t])throw Error(`Tool ${t} is already registered`);let r=this,i=()=>{r._initializedSent&&r._appCapabilities.tools?.listChanged&&r.sendToolListChanged()},a=n.inputSchema!==void 0,s={title:n.title,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,annotations:n.annotations,_meta:n._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(c){Object.assign(this,c),i()},remove(){r._registeredTools[t]===s&&(delete r._registeredTools[t],i())},handler:async(c,u)=>{if(!s.enabled)throw Error(`Tool ${t} is disabled`);let d;if(a){let m=s.inputSchema,p=m?await xz(m,c??{},`Invalid input for tool ${t}: `):c??{};d=await o(p,u)}else d=await o(u);return s.outputSchema&&!d.isError&&(d.structuredContent=await xz(s.outputSchema,d.structuredContent,`Invalid output for tool ${t}: `)),d}};return this._registeredTools[t]=s,!this._appCapabilities.tools&&!this.transport&&this.registerAppCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),s}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(t,n)=>{let o=this._registeredTools[t.name];if(!o)throw Error(`Tool ${t.name} not found`);return o.handler(t.arguments,n)},this.onlisttools=async(t,n)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([o,r])=>r.enabled).map(async([o,r])=>{let i={name:o,title:r.title,description:r.description,inputSchema:r.inputSchema?await kz(r.inputSchema,"input"):{type:"object",properties:{}}};return r.outputSchema&&(i.outputSchema=await kz(r.outputSchema,"output")),r.annotations&&(i.annotations=r.annotations),r._meta&&(i._meta=r._meta),i}))}))}async sendToolListChanged(t={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:t})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(t){this.setEventHandler("toolinput",t)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(t){this.setEventHandler("toolinputpartial",t)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(t){this.setEventHandler("toolresult",t)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(t){this.setEventHandler("toolcancelled",t)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(t){this.setEventHandler("hostcontextchanged",t)}_onteardown;get onteardown(){return this._onteardown}set onteardown(t){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,t),this._onteardown=t,this.replaceRequestHandler("ui/resource-teardown",{params:JE.shape.params,result:BE},(n,o)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(n,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",(n,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(n.params,o)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(t){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,t),this._onlisttools=t,this.replaceRequestHandler("tools/list",(n,o)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(n.params,o)})}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${t})`);break}}assertRequestHandlerCapability(t){switch(t){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${t})`);return;default:return}}assertNotificationCapability(t){}async callServerTool(t,n){if(this._assertInitialized("callServerTool"),typeof t=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${t}"). Did you mean: callServerTool({ name: "${t}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:t},{onprogress:()=>{},resetTimeoutOnProgress:!0,...n})}async readServerResource(t,n){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:t},n)}async listServerResources(t,n){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:t},n)}async createSamplingMessage(t,n){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:t},n)}sendMessage(t,n){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:t},LE,n)}sendLog(t){return this.notification({method:"notifications/message",params:t})}updateModelContext(t,n){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:t},Lr,n)}openLink(t,n){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:t},DE,n)}sendOpenLink=this.openLink;downloadFile(t,n){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:t},ME,n)}requestTeardown(t={}){return this.notification({method:"ui/notifications/request-teardown",params:t})}requestDisplayMode(t,n){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:t},WE,n)}sendSizeChanged(t){return this.notification({method:"ui/notifications/size-changed",params:t})}setupSizeChangedNotifications(){let t=!1,n=0,o=0,r=()=>{t||(t=!0,requestAnimationFrame(()=>{t=!1;let a=document.documentElement,s=a.style.height;a.style.height="max-content";let c=Math.ceil(a.getBoundingClientRect().height);a.style.height=s;let u=Math.ceil(window.innerWidth);(u!==n||c!==o)&&(n=u,o=c,this.sendSizeChanged({width:u,height:c}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(t=new Xv(window.parent,window.parent),n){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect(t);let o=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:OE}},eC,n);if(o===void 0)throw Error(`Server sent invalid initialize result: ${o}`);this._hostCapabilities=o.hostCapabilities,this._hostInfo=o.hostInfo,this._hostContext=o.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(o){throw this.close(),o}}};var r_="studio.chat.component.v1";function se(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Zc(e){return{content:e.content,structuredContent:se(e.structuredContent)?e.structuredContent:void 0,_meta:e._meta,isError:e.isError===!0}}function Rz(e){let t=e.content;if(e.isError||e.structuredContent||e._meta?.["studio/view"]||t?.length!==1)return e;let n=t[0]?.text;if(t[0]?.type!=="text"||!n?.startsWith('{"content":')||!n.includes('"studio/view"'))return e;try{let o=JSON.parse(n);if(se(o)&&Array.isArray(o.content)&&se(o.structuredContent)&&se(o._meta)){let r=o._meta["studio/view"];if(se(r)&&se(r.ui)){let i={content:o.content,structuredContent:o.structuredContent,_meta:{"studio/view":{...r,ui:{format:r.ui.format,sha256:r.ui.sha256}}}};if(n_(i))return i}}}catch{}return{isError:!0,content:[{type:"text",text:"The saved Studio card could not be read."}]}}function Pz(e){let t=e.structuredContent,n=t&&{...t,bindings:t.bindings??$t(e).bindings};if(!(!n||n.protocolVersion!==1||!se(n.bindings)||Object.entries(n.bindings).some(([o,r])=>!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(o)||typeof r!="string"||!r)||typeof n.component!="string"||!/^[a-zA-Z0-9._/-]+@[1-9]\d*$/.test(n.component)||typeof n.projectId!="string"||!n.projectId||n.scope!==void 0&&(!se(n.scope)||!["user","project"].includes(String(n.scope.kind))||n.scope.id!==n.projectId||n.scope.kind==="user"&&n.scope.id!=="user")||!se(n.target)||typeof n.target.instanceId!="string"||!n.target.instanceId||typeof n.target.operationId!="string"||!n.target.operationId))return{component:n.component,bindings:n.bindings,projectId:n.projectId,...n.scope!==void 0&&{scope:n.scope},target:{instanceId:n.target.instanceId,operationId:n.target.operationId}}}function t_(e,t){return se(e)&&Object.keys(e).length===Object.keys(t).length&&Object.entries(t).every(([n,o])=>e[n]===o)}function $t(e){let t=e._meta?.["studio/view"];return se(t)?t:{}}function Tz(e,t,n){let o=$t(e),r=new URL(t);if(r.protocol!=="https:"||r.username||r.password||!Array.isArray(o.mediaOrigins)||!o.mediaOrigins.includes(r.origin))throw Error("This media source is not available for download.");let i=a=>Array.isArray(a)?a.some(i):se(a)?Object.entries(a).some(([s,c])=>(s==="src"||s==="downloadUrl")&&c===t||i(c)):!1;if(!i(o.props))throw Error("This media is not part of the current card.");return{type:"resource_link",uri:t,name:n.replace(/[\\/:*?"<>|\x00-\x1f]/g,"_").slice(0,200)||"Media"}}function n_(e){let t=$t(e),n=Pz(e),o=t.ui;if(!(!n||t.protocolVersion!==1||t.component!==n.component||!t_(t.bindings,n.bindings)||t.projectId!==n.projectId||n.scope!==void 0&&(!se(t.scope)||t.scope.kind!==n.scope.kind||t.scope.id!==n.scope.id)||!se(t.target)||t.target.instanceId!==n.target.instanceId||t.target.operationId!==n.target.operationId||!se(t.props)||!se(o)||o.format!=="iife"||o.javascript!==void 0&&(typeof o.javascript!="string"||!o.javascript.trim())||typeof o.sha256!="string"||!/^[a-f0-9]{64}$/.test(o.sha256)))return{id:n.component,...typeof o.javascript=="string"&&{javascript:o.javascript},sha256:o.sha256}}async function nC(e){if(!e.javascript)return!1;let t=new TextEncoder().encode(e.javascript),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")===e.sha256}async function Ez(e,t,n){let o=se(e)&&Array.isArray(e.contents)?e.contents.find(a=>se(a)&&a.uri===t&&a.mimeType==="text/javascript"):void 0,r=se(o?._meta)?o._meta["studio/component"]:void 0;if(!se(o)||typeof o.text!="string"||!se(r)||r.id!==n||r.format!=="iife"||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new Error("The compatible Studio card renderer is invalid.");let i={id:n,javascript:o.text,sha256:r.sha256};if(!await nC(i))throw new Error("The Studio card script failed verification.");return i}function Cz(e){let t=e.scope??{kind:"project",id:e.projectId};return"studio://chat-bundles/"+[t.kind,t.id,e.target.instanceId,e.target.operationId,"components",e.component].map(encodeURIComponent).join("/")}function Un(e){return(e.content??[]).filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
154
- `)}function tm(e){let{ui:t,...n}=$t(e);return{text:Un(e),structuredContent:e.structuredContent,view:n,isError:e.isError===!0}}function fo(e,t){return!e||typeof e!="object"?!1:se(e)&&["image","audio","video"].includes(String(e.kind))&&e.path===t?!0:Object.values(e).some(n=>fo(n,t))}var em=class{constructor(t,n){this.callTool=t;this.sendMessage=n}callTool;sendMessage;result={};identity;pending=!1;lastRequest;receive(t){let n=Pz(t);if(this.identity){let o=t.structuredContent??{};if(o.scope!==void 0){let s=this.identity.scope??{kind:"project",id:this.identity.projectId};if(!se(o.scope)||o.scope.kind!==s.kind||o.scope.id!==s.id)throw new Error("The reply changed the card scope. Reopen the original card.")}for(let s of["projectId","component"])if(o[s]!==void 0&&o[s]!==this.identity[s])throw new Error("The reply belongs to another card. Reopen the original card.");if(o.target!==void 0&&(!se(o.target)||o.target.instanceId!==this.identity.target.instanceId||o.target.operationId!==this.identity.target.operationId))throw new Error("The reply changed the source operation. Reopen the original card.");if(o.bindings!==void 0&&!t_(o.bindings,this.identity.bindings)||n!==void 0&&!t_(n.bindings,this.identity.bindings))throw new Error("The reply changed the action bindings. Reopen the original card.");let r=this.result,{error:i,...a}=r.structuredContent??{};this.result={...r,...t,isError:t.isError===!0,structuredContent:{...a,...o},_meta:{...r._meta,...t._meta,"studio/view":{...$t(r),...$t(t)}}}}else this.result=t,this.identity=n}async action(t,n={},o={}){if(!this.identity)throw new Error("Reopen the operation before using this card.");if(this.pending)throw new Error("Wait for the current card action to finish.");if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(t))throw new Error("Invalid card action.");if(!Object.hasOwn(this.identity.bindings,t))throw new Error("This card does not declare that action.");if(Object.keys(o).some(i=>!["requestKey","approval"].includes(i)))throw new Error("Invalid card invocation options.");let r={...this.identity.scope?.kind==="user"?{scope:this.identity.scope}:{projectId:this.identity.projectId},target:this.identity.target,binding:this.identity.bindings[t],action:t,input:n,requestKey:o.requestKey??`card:${crypto.randomUUID()}`,...o.approval===void 0?{}:{approval:o.approval}};this.lastRequest=r,this.pending=!0;try{let i=await this.callTool({name:"studio_card_action",arguments:r}),a=i._meta?.["studio/message"],{["studio/message"]:s,...c}=i._meta??{},u={...i,_meta:c};if(this.receive(u),a!==void 0&&!i.isError){if(!se(a)||typeof a.intent!="string"||!a.intent.trim()||!se(a.data))throw Error("The adapter returned an invalid prepared message. Your draft is retained.");let d=this.sendMessage?await this.sendMessage(r.requestKey,{intent:a.intent,data:a.data}):{status:"failed",message:"This chat client does not support follow-up messages. Your draft is retained."},m=d.status==="sent",p={...u,content:[{type:"text",text:m?"Sent to this conversation. Business changes are not yet confirmed.":d.message}],isError:!m,structuredContent:{...u.structuredContent,...m?{}:{error:{code:d.status==="unknown"?"PROMPT_MESSAGE_UNKNOWN":"PROMPT_MESSAGE_FAILED"}}}};return this.receive(p),p}return u}finally{this.pending=!1}}};function Oz(e,t){let n=t.mediaOrigins??[];if(!Array.isArray(n)||n.some(i=>{if(typeof i!="string")return!0;try{let a=new URL(i);return a.protocol!=="https:"||a.origin!==i||a.hostname.includes("*")||/["';]/.test(i)}catch{return!0}}))throw new Error("The card declared invalid HTTPS media origins.");let o=["data:","blob:",...[...new Set(n)].sort()].join(" ");return`<!doctype html><meta http-equiv="Content-Security-Policy" content="${`default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; font-src data:; img-src ${o}; media-src ${o}; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'`}"><meta name="referrer" content="no-referrer"><meta name="color-scheme" content="light dark"><div id="root"></div><script>${e.replace(/<\/script/gi,"<\\/script")}<\/script>`}function Nz(){let e="studio.chat.component.v1",t=new Map,n,o=0,r=!1,i,a,s=p=>p==="light"||p==="dark"?p:void 0,c=p=>parent.postMessage({channel:e,...p},"*"),u=(p,f={},g={})=>new Promise((_,z)=>{let E=String(++o);t.set(E,{resolve:_,reject:z}),c({type:"action",id:E,action:p,input:f,options:g})}),d=p=>({data:p.view.props,projectId:p.view.projectId,target:p.view.target,...i&&{theme:i},action:u,...r&&{download:f=>new Promise((g,_)=>{let z=String(++o);t.set(z,{resolve:()=>g(),reject:_}),c({type:"download",id:z,uri:f.uri,name:f.name})})},readMedia:f=>new Promise((g,_)=>{let z=String(++o);t.set(z,{resolve:g,reject:_}),c({type:"read-media",id:z,input:f})})});window.addEventListener("message",p=>{if(p.source!==parent||p.data?.channel!==e)return;let f=p.data;try{if(f.type==="initialize"&&!n){r=f.downloadsAvailable===!0,i=s(f.theme),a=f.result;let g=document.createElement("script");g.textContent=f.javascript,document.head.append(g);let _=globalThis,z=_.StudioComponent??_.StudioChatCard;if(typeof z?.mount!="function")throw new Error("The registered card has no mount export.");if(n=z.mount(document.querySelector("#root"),d(f.result)),!n||typeof n.update!="function"||typeof n.dispose!="function")throw new Error("The registered card returned an invalid mount.")}else if(f.type==="result"&&n)a=f.result,n.update(d(f.result));else if(f.type==="theme-change"&&n&&a){let g=s(f.theme);g!==i&&(i=g,n.update(d(a)))}else f.type==="action-result"||f.type==="download-result"?(t.get(f.id)?.resolve(f.result),t.delete(f.id)):f.type==="media-result"?(t.get(f.id)?.resolve(f.value),t.delete(f.id)):f.type==="media-error"?(t.get(f.id)?.reject(new Error(f.message)),t.delete(f.id)):(f.type==="action-error"||f.type==="download-error")&&(t.get(f.id)?.reject(Object.assign(new Error(f.error.message),f.error)),t.delete(f.id))}catch(g){c({type:"component-error",message:g instanceof Error?g.message:"Card failed."})}}),window.addEventListener("error",()=>c({type:"component-error",message:"The registered card could not render."})),window.addEventListener("unhandledrejection",()=>c({type:"component-error",message:"The registered card could not update."})),document.addEventListener("securitypolicyviolation",p=>{if(!["media-src","img-src"].includes(p.effectiveDirective))return;let f="the media source";try{f=new URL(p.blockedURI).origin}catch{}c({type:"component-error",message:`This chat blocked ${f} (${p.effectiveDirective}). Refreshing the URL alone will not change its resource policy.`})});let m=document.body;new ResizeObserver(()=>{let{marginTop:p,marginBottom:f}=getComputedStyle(m),g=m.getBoundingClientRect().height+parseFloat(p)+parseFloat(f);c({type:"resize",height:Math.ceil(g)})}).observe(m),window.addEventListener("pagehide",()=>n?.dispose()),c({type:"ready"})}async function jz(e,t,n,o){if(!fo($t(e).props,t))throw Error("This file is not declared by the original card.");let r=0,i=1,a="",s="",c;for(;r<i;){let m=await o({path:t,offset:r,...c&&{expected:c}});if(!m||!Number.isSafeInteger(m.totalBytes)||m.totalBytes<=0||m.totalBytes>2147483648||!Number.isSafeInteger(m.nextOffset)||m.nextOffset<=r||m.nextOffset>m.totalBytes||!m.snapshot||m.snapshot.sizeBytes!==m.totalBytes||!/^(?:audio\/|video\/|image\/(?:png|jpeg|webp)$)/.test(m.mimeType)||c&&(m.totalBytes!==i||m.mimeType!==a||JSON.stringify(m.snapshot)!==JSON.stringify(c)))throw Error("The media reply is incomplete or the file changed during download.");let p=atob(m.base64);if(p.length!==m.nextOffset-r)throw Error("The media download chunk is incomplete.");s+=p,r=m.nextOffset,i=m.totalBytes,a=m.mimeType,c=m.snapshot}let u=t.match(/\.[a-z0-9]{1,10}$/i)?.[0]??"",d=Array.from(n.replace(/[\\/:*?"<>|\x00-\x1f]/g,"_")).slice(0,180).join("").replace(/[\ud800-\udfff]/gu,"\uFFFD")||"Media";return u&&!d.toLowerCase().endsWith(u.toLowerCase())&&(d+=u),{type:"resource",resource:{uri:`file:///${encodeURIComponent(d)}`,mimeType:a,blob:btoa(s)}}}var Ge=new Qd({name:"Vivix Studio card",version:"1.0.0"},{},{strict:!0,autoResize:!0}),iC=new cu(Ge),Me=new em(async e=>Zc(await Ge.callServerTool(e)),(e,t)=>iC.send(e,t)),go=document.querySelector("#summary"),ho=document.querySelector("#status"),oC=document.querySelector("#card"),$e,Fc,rm,Az,zt=!1,vr,Uz,i_=0;function _r(e){$e?.contentWindow?.postMessage({channel:r_,...e},"*")}function Hc(e){let t=e instanceof Error?e.message:"Studio could not update this card.",n=Me.lastRequest?.requestKey??Uz;ho.textContent=`${t}${n?`
155
- Request key: ${String(n)}`:""}`}function Dz(){let e=Ge.getHostContext()?.theme;return e==="light"||e==="dark"?e:void 0}Ge.addEventListener("hostcontextchanged",()=>{zt&&_r({type:"theme-change",theme:Dz()})});async function Mz(){let e=++i_,t=Me.result,n=Un(t);go.textContent=n,go.hidden=!n,ho.textContent=t.isError?Un(t)||"Studio rejected the card action.":"";let o=n_(t);if(!Me.identity||!o){vr&&clearTimeout(vr),$e?.remove(),$e=void 0,Fc=void 0,rm=void 0,zt=!1,t.isError||(ho.textContent="The registered card could not load. Reopen the original operation.");return}let r=Oz(`(${Nz.toString()})();`,$t(t)),i=Cz(Me.identity);if($e&&rm===i&&Az===r){go.hidden=!n||zt&&!t.isError,zt&&_r({type:"result",result:tm(t)});return}let a;try{let s=await Ge.readServerResource({uri:i});a=(await Ez(s,i,Me.identity.component)).javascript}catch{if(e!==i_)return;ho.textContent="A compatible Studio card renderer could not be loaded or verified. Reopen the card.",$e?.remove(),$e=void 0,Fc=void 0,rm=void 0,zt=!1;return}e===i_&&(vr&&clearTimeout(vr),$e?.remove(),zt=!1,Fc=a,rm=i,Az=r,$e=document.createElement("iframe"),$e.id="component",$e.title="Studio card",$e.setAttribute("sandbox","allow-scripts"),$e.setAttribute("referrerpolicy","no-referrer"),$e.srcdoc=r,oC.replaceChildren($e),vr=setTimeout(()=>{zt||(ho.textContent="The card did not initialize. Reopen the original operation.")},1e4))}async function aC(e,t,n,o){try{let i=await Me.action(e,t,n);await Mz(),o&&_r({type:"action-result",id:o,result:tm(i)})}catch(r){Hc(r),o&&_r({type:"action-error",id:o,error:{code:"CARD_ACTION_FAILED",message:r instanceof Error?r.message:"Card action failed.",requestKey:Me.lastRequest?.requestKey}})}}async function sC(e,t,n){try{if(!Ge.getHostCapabilities()?.downloadFile)throw Error("Downloads are unavailable in this chat.");let o=fo($t(Me.result).props,e)?await jz(Me.result,e,t,async i=>{let a=await Ge.callServerTool({name:"read_local_media",arguments:{...i}});if(a.isError)throw Error(Un(Zc(a))||"Local media could not be read.");return a._meta?.["studio/media"]}):Tz(Me.result,e,t);if((await Ge.downloadFile({contents:[o]})).isError)throw Error("The download was declined by this chat.");_r({type:"download-result",id:n})}catch(o){_r({type:"download-error",id:n,error:{message:o instanceof Error?o.message:"Download failed."}})}}window.addEventListener("message",e=>{if(!$e||e.source!==$e.contentWindow||!se(e.data))return;let t=e.data;if(t.channel===r_)if(t.type==="ready"){zt=!0,vr&&clearTimeout(vr);let n=Un(Me.result);go.hidden=!Me.result.isError||!n,ho.textContent=Me.result.isError?n:"",Fc&&_r({type:"initialize",javascript:Fc,result:tm(Me.result),downloadsAvailable:!!Ge.getHostCapabilities()?.downloadFile,theme:Dz()})}else if(t.type==="component-error"&&typeof t.message=="string")Hc(new Error(t.message));else if(zt&&t.type==="resize"&&typeof t.height=="number"&&Number.isFinite(t.height))$e.style.height=`${Math.max(120,Math.min(2e3,t.height))}px`;else if(zt&&t.type==="download"&&typeof t.id=="string"&&t.id.length>0&&typeof t.uri=="string"&&typeof t.name=="string")sC(t.uri,t.name,t.id);else if(zt&&t.type==="read-media"&&typeof t.id=="string"&&se(t.input)){let n=$e,o=t.input;(async()=>{try{if(typeof o.path!="string"||!fo($t(Me.result).props,o.path))throw Error("This media path does not belong to the original card.");let r=await Ge.callServerTool({name:"read_local_media",arguments:o});if(r.isError)throw Error(Un(Zc(r))||"Local media could not be read.");let i=r._meta?.["studio/media"];if(!se(i))throw Error("The local media reply is incomplete.");$e===n&&_r({type:"media-result",id:t.id,value:i})}catch(r){$e===n&&_r({type:"media-error",id:t.id,message:r instanceof Error?r.message:"Local media could not be read."})}})()}else zt&&t.type==="action"&&typeof t.id=="string"&&t.id.length>0&&typeof t.action=="string"&&(t.input===void 0||se(t.input))&&(t.options===void 0||se(t.options))&&aC(t.action,t.input??{},t.options??{},t.id)});Ge.ontoolinput=({arguments:e})=>{Uz=typeof e?.requestKey=="string"?e.requestKey:void 0};Ge.ontoolresult=async e=>{try{Me.receive(Rz(Zc(e))),await Mz()}catch(t){Hc(t)}};Ge.ontoolcancelled=()=>{Hc(new Error("The tool was cancelled. Recover with the original request to check whether it was accepted."))};Ge.onteardown=async()=>(vr&&clearTimeout(vr),$e?.remove(),{});Ge.connect().catch(e=>{go.textContent="Studio could not connect to this chat.",go.hidden=!1,Hc(e)});})();
157
+ `)}function tm(e){let{ui:t,...n}=$t(e);return{text:Un(e),structuredContent:e.structuredContent,view:n,isError:e.isError===!0}}function fo(e,t){return!e||typeof e!="object"?!1:se(e)&&["image","audio","video"].includes(String(e.kind))&&e.path===t?!0:Object.values(e).some(n=>fo(n,t))}var em=class{constructor(t,n){this.callTool=t;this.sendMessage=n}callTool;sendMessage;result={};identity;pending=!1;lastRequest;receive(t){let n=Pz(t);if(this.identity){let o=t.structuredContent??{};if(o.scope!==void 0){let s=this.identity.scope??{kind:"project",id:this.identity.projectId};if(!se(o.scope)||o.scope.kind!==s.kind||o.scope.id!==s.id)throw new Error("The reply changed the card scope. Reopen the original card.")}for(let s of["projectId","component"])if(o[s]!==void 0&&o[s]!==this.identity[s])throw new Error("The reply belongs to another card. Reopen the original card.");if(o.target!==void 0&&(!se(o.target)||o.target.instanceId!==this.identity.target.instanceId||o.target.operationId!==this.identity.target.operationId))throw new Error("The reply changed the source operation. Reopen the original card.");if(o.bindings!==void 0&&!t_(o.bindings,this.identity.bindings)||n!==void 0&&!t_(n.bindings,this.identity.bindings))throw new Error("The reply changed the action bindings. Reopen the original card.");let r=this.result,{error:i,...a}=r.structuredContent??{};this.result={...r,...t,isError:t.isError===!0,structuredContent:{...a,...o},_meta:{...r._meta,...t._meta,"studio/view":{...$t(r),...$t(t)}}}}else this.result=t,this.identity=n}async action(t,n={},o={}){if(!this.identity)throw new Error("Reopen the operation before using this card.");if(this.pending)throw new Error("Wait for the current card action to finish.");if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(t))throw new Error("Invalid card action.");if(!Object.hasOwn(this.identity.bindings,t))throw new Error("This card does not declare that action.");if(Object.keys(o).some(i=>!["requestKey","approval"].includes(i)))throw new Error("Invalid card invocation options.");let r={...this.identity.scope?.kind==="user"?{scope:this.identity.scope}:{projectId:this.identity.projectId},target:this.identity.target,binding:this.identity.bindings[t],action:t,input:n,requestKey:o.requestKey??`card:${crypto.randomUUID()}`,...o.approval===void 0?{}:{approval:o.approval}};this.lastRequest=r,this.pending=!0;try{let i=await this.callTool({name:"studio_card_action",arguments:r}),a=i._meta?.["studio/message"],{["studio/message"]:s,...c}=i._meta??{},u={...i,_meta:c};if(this.receive(u),a!==void 0&&!i.isError){if(!se(a)||typeof a.intent!="string"||!a.intent.trim()||!se(a.data))throw Error("The adapter returned an invalid prepared message. Your draft is retained.");let d=this.sendMessage?await this.sendMessage(r.requestKey,{intent:a.intent,data:a.data}):{status:"failed",message:"This chat client does not support follow-up messages. Your draft is retained."},m=d.status==="sent",p={...u,content:[{type:"text",text:m?"Sent to this conversation. Business changes are not yet confirmed.":d.message}],isError:!m,structuredContent:{...u.structuredContent,...m?{}:{error:{code:d.status==="unknown"?"PROMPT_MESSAGE_UNKNOWN":"PROMPT_MESSAGE_FAILED"}}}};return this.receive(p),p}return u}finally{this.pending=!1}}};function Oz(e,t,n=!1){let o=t.mediaOrigins??[];if(!Array.isArray(o)||o.some(s=>{if(typeof s!="string")return!0;try{let c=new URL(s);return c.protocol!=="https:"||c.origin!==s||c.hostname.includes("*")||/["';]/.test(s)}catch{return!0}}))throw new Error("The card declared invalid HTTPS media origins.");let r=["data:","blob:",...[...new Set(o)].sort()].join(" ");return`<!doctype html><meta http-equiv="Content-Security-Policy" content="${`default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; font-src data:; img-src ${r}; media-src ${r}; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'`}"><meta name="referrer" content="no-referrer"><meta name="color-scheme" content="light dark">${n?"<style>html{scrollbar-width:none}body{margin-block:0}</style>":""}<div id="root"></div><script>${e.replace(/<\/script/gi,"<\\/script")}<\/script>`}function Nz(){let e="studio.chat.component.v1",t=new Map,n,o=0,r=!1,i,a,s=p=>p==="light"||p==="dark"?p:void 0,c=p=>parent.postMessage({channel:e,...p},"*"),u=(p,f={},g={})=>new Promise((_,z)=>{let E=String(++o);t.set(E,{resolve:_,reject:z}),c({type:"action",id:E,action:p,input:f,options:g})}),d=p=>({data:p.view.props,projectId:p.view.projectId,target:p.view.target,...i&&{theme:i},action:u,...r&&{download:f=>new Promise((g,_)=>{let z=String(++o);t.set(z,{resolve:()=>g(),reject:_}),c({type:"download",id:z,uri:f.uri,name:f.name})})},readMedia:f=>new Promise((g,_)=>{let z=String(++o);t.set(z,{resolve:g,reject:_}),c({type:"read-media",id:z,input:f})})});window.addEventListener("message",p=>{if(p.source!==parent||p.data?.channel!==e)return;let f=p.data;try{if(f.type==="initialize"&&!n){r=f.downloadsAvailable===!0,i=s(f.theme),a=f.result;let g=document.createElement("script");g.textContent=f.javascript,document.head.append(g);let _=globalThis,z=_.StudioComponent??_.StudioChatCard;if(typeof z?.mount!="function")throw new Error("The registered card has no mount export.");if(n=z.mount(document.querySelector("#root"),d(f.result)),!n||typeof n.update!="function"||typeof n.dispose!="function")throw new Error("The registered card returned an invalid mount.")}else if(f.type==="result"&&n)a=f.result,n.update(d(f.result));else if(f.type==="theme-change"&&n&&a){let g=s(f.theme);g!==i&&(i=g,n.update(d(a)))}else f.type==="action-result"||f.type==="download-result"?(t.get(f.id)?.resolve(f.result),t.delete(f.id)):f.type==="media-result"?(t.get(f.id)?.resolve(f.value),t.delete(f.id)):f.type==="media-error"?(t.get(f.id)?.reject(new Error(f.message)),t.delete(f.id)):(f.type==="action-error"||f.type==="download-error")&&(t.get(f.id)?.reject(Object.assign(new Error(f.error.message),f.error)),t.delete(f.id))}catch(g){c({type:"component-error",message:g instanceof Error?g.message:"Card failed."})}}),window.addEventListener("error",()=>c({type:"component-error",message:"The registered card could not render."})),window.addEventListener("unhandledrejection",()=>c({type:"component-error",message:"The registered card could not update."})),document.addEventListener("securitypolicyviolation",p=>{if(!["media-src","img-src"].includes(p.effectiveDirective))return;let f="the media source";try{f=new URL(p.blockedURI).origin}catch{}c({type:"component-error",message:`This chat blocked ${f} (${p.effectiveDirective}). Refreshing the URL alone will not change its resource policy.`})});let m=document.body;new ResizeObserver(()=>{let{marginTop:p,marginBottom:f}=getComputedStyle(m),g=m.getBoundingClientRect().height+parseFloat(p)+parseFloat(f);c({type:"resize",height:Math.ceil(g)})}).observe(m),window.addEventListener("pagehide",()=>n?.dispose()),c({type:"ready"})}async function jz(e,t,n,o){if(!fo($t(e).props,t))throw Error("This file is not declared by the original card.");let r=0,i=1,a="",s="",c;for(;r<i;){let m=await o({path:t,offset:r,...c&&{expected:c}});if(!m||!Number.isSafeInteger(m.totalBytes)||m.totalBytes<=0||m.totalBytes>2147483648||!Number.isSafeInteger(m.nextOffset)||m.nextOffset<=r||m.nextOffset>m.totalBytes||!m.snapshot||m.snapshot.sizeBytes!==m.totalBytes||!/^(?:audio\/|video\/|image\/(?:png|jpeg|webp)$)/.test(m.mimeType)||c&&(m.totalBytes!==i||m.mimeType!==a||JSON.stringify(m.snapshot)!==JSON.stringify(c)))throw Error("The media reply is incomplete or the file changed during download.");let p=atob(m.base64);if(p.length!==m.nextOffset-r)throw Error("The media download chunk is incomplete.");s+=p,r=m.nextOffset,i=m.totalBytes,a=m.mimeType,c=m.snapshot}let u=t.match(/\.[a-z0-9]{1,10}$/i)?.[0]??"",d=Array.from(n.replace(/[\\/:*?"<>|\x00-\x1f]/g,"_")).slice(0,180).join("").replace(/[\ud800-\udfff]/gu,"\uFFFD")||"Media";return u&&!d.toLowerCase().endsWith(u.toLowerCase())&&(d+=u),{type:"resource",resource:{uri:`file:///${encodeURIComponent(d)}`,mimeType:a,blob:btoa(s)}}}var Ge=new Qd({name:"Vivix Studio card",version:"1.0.0"},{},{strict:!0,autoResize:!0}),iC=new cu(Ge),Me=new em(async e=>Zc(await Ge.callServerTool(e)),(e,t)=>iC.send(e,t)),go=document.querySelector("#summary"),ho=document.querySelector("#status"),oC=document.querySelector("#card"),$e,Fc,rm,Az,zt=!1,vr,Uz,i_=0;function _r(e){$e?.contentWindow?.postMessage({channel:r_,...e},"*")}function Hc(e){let t=e instanceof Error?e.message:"Studio could not update this card.",n=Me.lastRequest?.requestKey??Uz;ho.textContent=`${t}${n?`
158
+ Request key: ${String(n)}`:""}`}function Dz(){let e=Ge.getHostContext()?.theme;return e==="light"||e==="dark"?e:void 0}Ge.addEventListener("hostcontextchanged",()=>{zt&&_r({type:"theme-change",theme:Dz()})});async function Mz(){let e=++i_,t=Me.result,n=Un(t);go.textContent=n,go.hidden=!n,ho.textContent=t.isError?Un(t)||"Studio rejected the card action.":"";let o=n_(t),r=!!o&&t.structuredContent?.componentId==="video-gallery@1";if(document.documentElement.toggleAttribute("data-video-gallery",r),!Me.identity||!o){vr&&clearTimeout(vr),$e?.remove(),$e=void 0,Fc=void 0,rm=void 0,zt=!1,t.isError||(ho.textContent="The registered card could not load. Reopen the original operation.");return}let i=Oz(`(${Nz.toString()})();`,$t(t),r),a=Cz(Me.identity);if($e&&rm===a&&Az===i){go.hidden=!n||zt&&!t.isError,zt&&_r({type:"result",result:tm(t)});return}let s;try{let c=await Ge.readServerResource({uri:a});s=(await Ez(c,a,Me.identity.component)).javascript}catch{if(e!==i_)return;ho.textContent="A compatible Studio card renderer could not be loaded or verified. Reopen the card.",$e?.remove(),$e=void 0,Fc=void 0,rm=void 0,zt=!1;return}e===i_&&(vr&&clearTimeout(vr),$e?.remove(),zt=!1,Fc=s,rm=a,Az=i,$e=document.createElement("iframe"),$e.id="component",$e.title="Studio card",$e.setAttribute("sandbox","allow-scripts"),$e.setAttribute("referrerpolicy","no-referrer"),$e.srcdoc=i,oC.replaceChildren($e),vr=setTimeout(()=>{zt||(ho.textContent="The card did not initialize. Reopen the original operation.")},1e4))}async function aC(e,t,n,o){try{let i=await Me.action(e,t,n);await Mz(),o&&_r({type:"action-result",id:o,result:tm(i)})}catch(r){Hc(r),o&&_r({type:"action-error",id:o,error:{code:"CARD_ACTION_FAILED",message:r instanceof Error?r.message:"Card action failed.",requestKey:Me.lastRequest?.requestKey}})}}async function sC(e,t,n){try{if(!Ge.getHostCapabilities()?.downloadFile)throw Error("Downloads are unavailable in this chat.");let o=fo($t(Me.result).props,e)?await jz(Me.result,e,t,async i=>{let a=await Ge.callServerTool({name:"read_local_media",arguments:{...i}});if(a.isError)throw Error(Un(Zc(a))||"Local media could not be read.");return a._meta?.["studio/media"]}):Tz(Me.result,e,t);if((await Ge.downloadFile({contents:[o]})).isError)throw Error("The download was declined by this chat.");_r({type:"download-result",id:n})}catch(o){_r({type:"download-error",id:n,error:{message:o instanceof Error?o.message:"Download failed."}})}}window.addEventListener("message",e=>{if(!$e||e.source!==$e.contentWindow||!se(e.data))return;let t=e.data;if(t.channel===r_)if(t.type==="ready"){zt=!0,vr&&clearTimeout(vr);let n=Un(Me.result);go.hidden=!Me.result.isError||!n,ho.textContent=Me.result.isError?n:"",Fc&&_r({type:"initialize",javascript:Fc,result:tm(Me.result),downloadsAvailable:!!Ge.getHostCapabilities()?.downloadFile,theme:Dz()})}else if(t.type==="component-error"&&typeof t.message=="string")Hc(new Error(t.message));else if(zt&&t.type==="resize"&&typeof t.height=="number"&&Number.isFinite(t.height))$e.style.height=`${Math.max(120,Math.min(2e3,t.height))}px`;else if(zt&&t.type==="download"&&typeof t.id=="string"&&t.id.length>0&&typeof t.uri=="string"&&typeof t.name=="string")sC(t.uri,t.name,t.id);else if(zt&&t.type==="read-media"&&typeof t.id=="string"&&se(t.input)){let n=$e,o=t.input;(async()=>{try{if(typeof o.path!="string"||!fo($t(Me.result).props,o.path))throw Error("This media path does not belong to the original card.");let r=await Ge.callServerTool({name:"read_local_media",arguments:o});if(r.isError)throw Error(Un(Zc(r))||"Local media could not be read.");let i=r._meta?.["studio/media"];if(!se(i))throw Error("The local media reply is incomplete.");$e===n&&_r({type:"media-result",id:t.id,value:i})}catch(r){$e===n&&_r({type:"media-error",id:t.id,message:r instanceof Error?r.message:"Local media could not be read."})}})()}else zt&&t.type==="action"&&typeof t.id=="string"&&t.id.length>0&&typeof t.action=="string"&&(t.input===void 0||se(t.input))&&(t.options===void 0||se(t.options))&&aC(t.action,t.input??{},t.options??{},t.id)});Ge.ontoolinput=({arguments:e})=>{Uz=typeof e?.requestKey=="string"?e.requestKey:void 0};Ge.ontoolresult=async e=>{try{Me.receive(Rz(Zc(e))),await Mz()}catch(t){Hc(t)}};Ge.ontoolcancelled=()=>{Hc(new Error("The tool was cancelled. Recover with the original request to check whether it was accepted."))};Ge.onteardown=async()=>(vr&&clearTimeout(vr),$e?.remove(),{});Ge.connect().catch(e=>{go.textContent="Studio could not connect to this chat.",go.hidden=!1,Hc(e)});})();
156
159
  /*! Bundled license information:
157
160
 
158
161
  @modelcontextprotocol/client/dist/src-CeKsbNLO.mjs:
package/dist/server.js CHANGED
@@ -29429,7 +29429,7 @@ data:
29429
29429
  // package.json
29430
29430
  var package_default = {
29431
29431
  name: "@vivix-labs/studio-chat-mcp",
29432
- version: "0.1.14",
29432
+ version: "0.1.16",
29433
29433
  type: "module",
29434
29434
  engines: {
29435
29435
  node: ">=22.12.0"
@@ -29457,7 +29457,8 @@ var package_default = {
29457
29457
  files: [
29458
29458
  "dist",
29459
29459
  "studio-plugin.json",
29460
- "skills",
29460
+ "README.md",
29461
+ "docs",
29461
29462
  "LICENSE"
29462
29463
  ],
29463
29464
  exports: {
@@ -38485,7 +38486,7 @@ async function resolveChatMedia(host, scope, ref, fileId) {
38485
38486
  }
38486
38487
 
38487
38488
  // src/chat-server.ts
38488
- var chatResourceUri = "ui://studio/chat/v12.html";
38489
+ var chatResourceUri = "ui://studio/chat/v13.html";
38489
38490
  var historicalChatResourceUris = [
38490
38491
  "ui://studio/chat/v1.html",
38491
38492
  "ui://studio/chat/v2.html",
@@ -38497,7 +38498,8 @@ var historicalChatResourceUris = [
38497
38498
  "ui://studio/chat/v8.html",
38498
38499
  "ui://studio/chat/v9.html",
38499
38500
  "ui://studio/chat/v10.html",
38500
- "ui://studio/chat/v11.html"
38501
+ "ui://studio/chat/v11.html",
38502
+ "ui://studio/chat/v12.html"
38501
38503
  ];
38502
38504
  var chatMimeType = "text/html;profile=mcp-app";
38503
38505
  var defaultResourceDomains = ["https://static.vivi-x.ai"];
@@ -38547,7 +38549,7 @@ function createChatServer(options2) {
38547
38549
  const server = new McpServer(
38548
38550
  { name: "vivix-studio-chat", version: package_default.version },
38549
38551
  {
38550
- instructions: "Use this server for Vivix Studio interactive cards. When a request involves reviewing, choosing, editing, comparing, previewing, or presenting Studio content, call list_chat_capabilities in user scope first, even when the work belongs to a project. If discovery returns a relevant component, immediately call describe_chat_capability for that route and then run_studio_action with the returned scope and target. A discovery call alone is not a completed card flow. Use project scope separately for project media queries or declared project cards. If a project-scope discovery includes a fallback user-scope card, use the scope and target returned on that card. For existing media or project progress, prefer a matching storyboard, media-result, story-progress, or media-query route when its returned inputs can be filled from the current project state. Use Studio CLI plugin operations for multi-step workflow and generation execution unless invoked via a card action. For a full Studio project, project open --no-open only returns the workbenchUrl. If the Host provides a native browser or side-panel handoff, open that exact URL there. In Codex, use the host open_in_codex handoff with a browser target and right placement when available. Do not use CUA to create or open the workbench tab. run_studio_action renders a chat card and does not open the workbench. A successful tool result confirms that the Host accepted the request, but does not confirm that the client displayed a card or opened a sidebar. Recommend a new conversation only when this conversation has just installed Studio or changed the MCP configuration and the tools are absent from the active and deferred host registries. On a later conversation with the tools still absent, report that the host has not exposed interactive cards and continue with the CLI and Workbench. Do not recommend another conversation after list_chat_capabilities or another card tool has succeeded. Terminal-only hosts should continue with the CLI and Workbench. General interactions default to user scope; saved project operations use explicit project scope. Preserve requestKey and original arguments for recovery; never automatically resubmit an uncertain action."
38552
+ instructions: "Use this server for Vivix Studio interactive cards. Whenever a turn involves creative choices, drafts, storyboards, character concepts, comparisons, media previews, or project progress, proactively use a matching native card alongside any project workflow rather than replying in plain text alone. Follow the unified vivix-studio Skill and its references/chat-interactions.md, references/habits-and-proposals.md, and references/project-and-workbench.md references for presentation choice, user collaboration preferences, session handling, media routing, custom visualization, and host handoff. Match card titles, descriptions, and button labels to the user\u2019s conversation language unless asked otherwise. Call list_chat_capabilities before selecting a card, then describe_chat_capability and run_studio_action with the returned scope, target, schemas, and input. General cards use user scope. Use explicit project scope for project operations and queries. Preserve requestKey and original arguments for recovery and never automatically resubmit an uncertain write. A successful tool result means the Host accepted the request, not that the client rendered the card or opened a Workbench panel."
38551
38553
  }
38552
38554
  );
38553
38555
  server.registerTool(
@@ -38681,7 +38683,7 @@ function createChatServer(options2) {
38681
38683
  "describe_chat_capability",
38682
38684
  {
38683
38685
  title: "Read a chat contract",
38684
- description: "Read exact schemas for a discovered route. Pass componentId for a reusable component, or kind=nativeOperation for an operation to bind using target.mode=native. Native operation schemas do not imply a chat view or execution permission. Default interface text to English and preserve original creative content.",
38686
+ description: "Read exact schemas for a discovered route. Pass componentId for a reusable component, or kind=nativeOperation for an operation to bind using target.mode=native. Native operation schemas do not imply a chat view or execution permission. Match interface text to the user\u2019s conversation language unless requested otherwise. Preserve original creative content.",
38685
38687
  inputSchema: external_exports.object({
38686
38688
  scope: scopeSchema.default(userScope),
38687
38689
  target,
@@ -38720,7 +38722,7 @@ function createChatServer(options2) {
38720
38722
  "run_studio_action",
38721
38723
  {
38722
38724
  title: "Run Studio action",
38723
- description: "Open a component or declared project card using the scope, target and contract returned by this connection discovery tools. `input` is a JSON object; a JSON-encoded object string is accepted and normalized. Default interface headings, field labels, group headings and buttons to English unless the user requests another interface language. Preserve story names, story text and user input in their original language. User-scope components work without a business project. Project business operations require the selected project scope. Legacy projectId calls remain supported. Preserve requestKey and original input for uncertain recovery.",
38725
+ description: "Open a component or declared project card using the scope, target and contract returned by this connection discovery tools. `input` is a JSON object; a JSON-encoded object string is accepted and normalized. Match interface headings, field labels, group headings and buttons to the user\u2019s conversation language unless requested otherwise. Preserve story names, story text and user input in their original language. User-scope components work without a business project. Project business operations require the selected project scope. Legacy projectId calls remain supported. Preserve requestKey and original input for uncertain recovery.",
38724
38726
  inputSchema: runInput,
38725
38727
  _meta: { ui: { resourceUri: chatResourceUri } }
38726
38728
  },
package/dist/setup.js CHANGED
@@ -961,10 +961,9 @@ async function enable(id, scope, options = [], additions) {
961
961
  await enable("studio-chat", user, ["--allow-access", "host.operations"]);
962
962
  await enable("chat-components", user);
963
963
  await enable("ui-system", user);
964
- var examples = await present(join(profile, "home-initialization.json")) ? await read(join(profile, "home-initialization.json")) : {};
965
- var drama = examples.projects?.["out-of-steps"]?.projectId;
966
- if (drama && cliCall("project", "list").projects.some((p) => p.id === drama && p.available)) {
967
- const scope = ["--project", drama];
964
+ for (const project of cliCall("project", "list").projects) {
965
+ if (!project.available) continue;
966
+ const scope = ["--project", project.id];
968
967
  const author = cliCall("plugin", "list", ...scope).instances.find((i) => i.id === "authoring");
969
968
  if (author?.package === packages.authoring) {
970
969
  await enable("authoring", scope);
@@ -0,0 +1,46 @@
1
+ # Studio Chat MCP contract
2
+
3
+ Use the unified `vivix-studio` Skill's `chat-interactions.md` for capability
4
+ discovery, presentation choice, defaults, session handling and continuation.
5
+ This document only records the transport details owned by the MCP adapter.
6
+
7
+ ## Discovery and routing
8
+
9
+ - Call `list_chat_capabilities` on this connection before selecting a card.
10
+ - Call `describe_chat_capability` with the returned component or native-operation
11
+ target before constructing input.
12
+ - Call `run_studio_action` with the returned `scope`, `target`, schemas and input.
13
+ - General components use user scope. Project media queries and declared project
14
+ cards use the explicit project scope returned by discovery.
15
+ - Native-operation actions use `target.mode: "native"` and the declared
16
+ `inputBindings`. They do not require a receiver card or a second business API.
17
+
18
+ The adapter projects the installed component through
19
+ `ui://studio/chat/v1.html`. Card buttons return through the app-only
20
+ `studio_card_action` route. The adapter authenticates the original source,
21
+ component, action and target before dispatching a Host operation.
22
+
23
+ ## Media transport
24
+
25
+ Query saved media through the discovered `query_studio_media` route and resolve
26
+ the exact returned reference with `resolve_chat_media`. The file service owns
27
+ origin lookup and ticket refresh. Check the returned `resourceDomains` before
28
+ using an HTTPS preview URL.
29
+
30
+ When the component schema supports local media, pass an absolute local Host
31
+ `path` for PNG, JPEG, WebP, audio or video instead of `src`, and pass exactly
32
+ one of them. Video `poster` values still require HTTPS. Local reads use the
33
+ app-only `read_local_media` channel and load the complete file before display.
34
+ They do not upload, import or generate content.
35
+
36
+ ## Request recovery
37
+
38
+ Choose one `requestKey` before a mutation and preserve the original input,
39
+ scope, source target and action binding through retries. An uncertain or
40
+ `submission_unknown` result must be recovered through the original operation and
41
+ key before any new submission. A changed payload under the same key is a
42
+ conflict. A new key represents a new action.
43
+
44
+ The Host owns access, approval, receipts and leases. A successful adapter result
45
+ means the Host accepted the request. It does not prove that the client rendered
46
+ the card or that a business write, export or generation completed.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vivix-labs/studio-chat-mcp",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=22.12.0"
@@ -28,7 +28,8 @@
28
28
  "files": [
29
29
  "dist",
30
30
  "studio-plugin.json",
31
- "skills",
31
+ "README.md",
32
+ "docs",
32
33
  "LICENSE"
33
34
  ],
34
35
  "exports": {
@@ -5,8 +5,5 @@
5
5
  "studioPluginApi": "^0.2.6"
6
6
  },
7
7
  "requestedAccess": ["host.operations"],
8
- "resources": {
9
- "skills": ["skills/vivix-studio-chat/SKILL.md"]
10
- },
11
8
  "operationExtensions": ["chat"]
12
9
  }
@@ -1,117 +0,0 @@
1
- ---
2
- name: vivix-studio-chat
3
- description: Discover and open a native chat card when it helps with the current inspection, comparison, choice or edit. General interactions need no business project. Saved Studio operations use the chosen project scope. Remote creation uses vivix-studio-mcp.
4
- ---
5
-
6
- # Chat interactions and local Studio cards
7
-
8
- ## Discover a general interaction
9
-
10
- Use the installed `chat-components` Skill's “Choose the presentation for this
11
- turn” rule for native cards and custom UI. Discover a card when it helps with the
12
- user's current task, including a preview that needs no follow-up question.
13
-
14
- Default card headings, field labels, group headings, buttons, placeholders, and
15
- instructions to English, even when the conversation is Chinese. Follow an explicit
16
- request for another interface language. Preserve story names and text, character
17
- names, saved object names, and user input in their original language. A story
18
- choice's `label` is content; its group `label` is interface text. For example, use
19
- `Choose a story` with `《我们先约会》` and its original Chinese synopsis.
20
-
21
- Use this connection's `list_chat_capabilities` (check active session
22
- capabilities when starting or continuing a Studio project), then
23
- `describe_chat_capability` for the selected route and component ID. Reuse the
24
- returned `scope`, `target`, schemas and examples. General conversation components
25
- default to user scope and do not require creating a business project. The MCP
26
- entry point reads the enabled provider's live catalog. Choose from that catalog.
27
-
28
- For a reusable card button calling one native operation, explicitly search this
29
- connection with `kind:"nativeOperation"` and describe the returned target with the
30
- same kind. Read its input schema, effects and confirm. Configure target.mode=native
31
- and inputBindings as described in the installed chat-components interaction guide.
32
- The native operation needs no chat view or receiver envelope. Keep the original
33
- scope and let the Host handle execution, approvals and request-key recovery.
34
-
35
- Prepare props from the user's actual topic, draft or candidates. Open the
36
- returned route with `run_studio_action`, using its actual scope and input.
37
- Scope each prompt action to the clicked operation and use the latest interaction
38
- data. Choose any subsequent presentation from the user's intent for that turn.
39
- Local edits and sent prompts
40
- do not prove a saved business change.
41
-
42
- Read saved media through a discovered `query_studio_media` route after describing
43
- its native input schema. Take the exact `ref` from a returned task, asset or user
44
- selection. Call `resolve_chat_media` with that scope, ref and optional file ID to
45
- get an HTTPS read URL. The file service owns origin lookup and ticket refresh.
46
- Check the connection's returned `resourceDomains` before previewing media. A
47
- readable URL does not prove the native host permits it. Report a URL-safety
48
- rejection separately from expiry or decoding; do not proxy, rehost or disable
49
- checks to evade that rejection. A changed UI resource must be tested in a
50
- connection that actually loads the new resource version.
51
- Use existing valid URLs directly. For PNG/JPEG/WebP images, audio, or video
52
- already available on the local MCP Host, supply its absolute `path` instead of
53
- `src` when the component's schema supports it; use exactly one of the two.
54
- Video `poster` strings still require HTTPS. The card reads `path + offset`
55
- through the App-only `read_local_media` channel and loads the complete file
56
- before display or playback. It needs no preview ID,
57
- import or public URL. A remote MCP Host cannot read a path on the user's computer.
58
- This whole-file preview does not provide progressive long-video playback.
59
-
60
- If the interactive card tools are not active after this conversation has just
61
- installed Studio or changed the MCP configuration, proactively tell the user
62
- in natural language (without mentioning internal protocol/server names or
63
- hardcoding a client name) that interactive cards require starting a new
64
- conversation, while continuing via the CLI and Studio Workbench. On a later
65
- conversation, if the tools are still absent, report that the current host has
66
- not exposed interactive cards and continue via the CLI and Studio Workbench
67
- without asking for another conversation.
68
-
69
- When `list_chat_capabilities`, `describe_chat_capability`, or
70
- `run_studio_action` has succeeded in the current conversation, treat cards as
71
- active and do not suggest starting a new conversation for this task.
72
-
73
- If discovery returns no ready matching capability, report that status and retain
74
- the draft. For an unmet general presentation need, follow the installed
75
- `chat-components` custom-visualization route and `vivix-studio-ui` guidance when
76
- the host supports it. Scope or transport failures are failures to report, not proof
77
- that another CLI profile has no components. A specialized media workflow keeps
78
- its generation steps and uses these interactions at confirmation and review.
79
-
80
- Print a short readable receipt when reporting tool results. Preserve structured
81
- results for the client; do not dump the entire MCP envelope, UI source or bindings
82
- as conversation text. A ready receipt alone does not prove visible rendering.
83
-
84
- ## Open a Studio project operation card
85
-
86
- Use the `vivix-studio-chat` local MCP connection with an opened Studio project.
87
- Use the same-connection discovery tools with the chosen project scope to read
88
- the enabled operation, native schema and `chat` declaration. CLI `plugin describe`
89
- is an alternative only when it addresses that same Host configuration.
90
- Keep the user's chosen project explicit. A plugin being installed does not mean
91
- its instance is enabled or that every operation supports a chat card.
92
-
93
- Call `run_studio_action` with the discovered project `scope`, the declared source
94
- `target: {instanceId, operationId}`, and `input`. For a mutation, choose one
95
- `requestKey` before the first call and preserve it with the original parameters.
96
- Host confirmation and permission rules apply to the operation. If the Host
97
- requires human approval, present its approval instructions to the user.
98
-
99
- The installed plugin supplies the card component; the MCP server supplies the
100
- generic page at `ui://studio/chat/v1.html`. Card buttons call the app-only
101
- `studio_card_action`; this installed adapter resolves the allowed destination from the source
102
- operation. Use the card's original project, source target, and Host action binding throughout. Keep business fields inside `input`.
103
- Business handlers are not individually exposed as MCP tools.
104
-
105
- Report the text and business result even when the current chat cannot render the card.
106
- Reopen an existing object using a declared read operation and its saved identity. A
107
- transport error or `submission_unknown` leaves acceptance uncertain: retain the
108
- original binding, key, and parameters, and recover or replay that same request only
109
- when requested. A changed payload under one key is a conflict; a new key denotes
110
- a new action. After a revision conflict, refresh and let the user review the new
111
- state before another explicit write with a new key.
112
-
113
- This adapter is a user-scoped Studio server plugin running in the Host process.
114
- The MCP client connects to its authenticated HTTP route. If the Host is stopped,
115
- open the project with the CLI. Use the package README for installation and client
116
- connection configuration. Keep local credentials out of tool inputs and chat
117
- messages. Host operation dispatch owns access, approval, receipts and leases.
@@ -1,4 +0,0 @@
1
- interface:
2
- display_name: 'Vivix Studio Chat'
3
- short_description: 'Use local Studio plugin cards in chat'
4
- default_prompt: 'Use $vivix-studio-chat to open the declared card for my local Studio project.'