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

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/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.16",
29432
+ version: "0.1.18",
29433
29433
  type: "module",
29434
29434
  engines: {
29435
29435
  node: ">=22.12.0"
@@ -37769,6 +37769,10 @@ var EMPTY_COMPLETION_RESULT = {
37769
37769
  }
37770
37770
  };
37771
37771
 
37772
+ // src/chat.ts
37773
+ import { randomBytes } from "node:crypto";
37774
+ import { performance } from "node:perf_hooks";
37775
+
37772
37776
  // src/message.ts
37773
37777
  var chatMessageSchema = external_exports.object({
37774
37778
  intent: external_exports.string().min(1).refine((value) => Boolean(value.trim())),
@@ -37778,6 +37782,79 @@ var chatMessageSchema = external_exports.object({
37778
37782
  // src/chat.ts
37779
37783
  import { PluginError } from "vivix-studio/sdk/shared";
37780
37784
  var inputError = (code, message, hint) => new PluginError(code, message, hint);
37785
+ function uuidv72(time3 = Date.now()) {
37786
+ const bytes = randomBytes(16);
37787
+ bytes.writeUIntBE(time3, 0, 6);
37788
+ bytes[6] = bytes[6] & 15 | 112;
37789
+ bytes[8] = bytes[8] & 63 | 128;
37790
+ const hex3 = bytes.toString("hex");
37791
+ return `${hex3.slice(0, 8)}-${hex3.slice(8, 12)}-${hex3.slice(12, 16)}-${hex3.slice(16, 20)}-${hex3.slice(20)}`;
37792
+ }
37793
+ function safeRecordChatTelemetry(host, event) {
37794
+ try {
37795
+ host.recordChatTelemetry?.(event);
37796
+ } catch {
37797
+ }
37798
+ }
37799
+ async function withHostInteractionContext(host, context, fn) {
37800
+ if (typeof host.withInteractionContext === "function")
37801
+ return host.withInteractionContext(context, fn);
37802
+ return fn();
37803
+ }
37804
+ function isPlainRecord(value) {
37805
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
37806
+ }
37807
+ var cardBindingMeta = /* @__PURE__ */ new Map();
37808
+ function rememberCardBindings(bindings, meta3) {
37809
+ for (const token of Object.values(bindings)) {
37810
+ if (!token) continue;
37811
+ if (cardBindingMeta.size >= 2048 && !cardBindingMeta.has(token)) {
37812
+ const oldest = cardBindingMeta.keys().next().value;
37813
+ if (oldest !== void 0) cardBindingMeta.delete(oldest);
37814
+ }
37815
+ cardBindingMeta.set(token, meta3);
37816
+ }
37817
+ }
37818
+ function extractExposedActionsFromRender(rawActions) {
37819
+ if (!Array.isArray(rawActions)) return [];
37820
+ const items = rawActions.filter(isPlainRecord);
37821
+ const footerItems = items.filter((item) => item.placement !== "header");
37822
+ const firstFooter = footerItems[0];
37823
+ const primaryFooter = footerItems.find((item) => item.emphasis === "primary") ?? (firstFooter && firstFooter.emphasis === void 0 ? firstFooter : void 0);
37824
+ return items.flatMap((item) => {
37825
+ const actionId = typeof item.id === "string" && item.id ? item.id : void 0;
37826
+ if (!actionId) return [];
37827
+ const placement = item.placement === "header" ? "header" : "footer";
37828
+ const emphasis = typeof item.emphasis === "string" && item.emphasis ? item.emphasis : placement === "footer" ? item === primaryFooter ? "primary" : "secondary" : "secondary";
37829
+ const targetObj = isPlainRecord(item.target) ? item.target : void 0;
37830
+ const dispatchMode = typeof item.prompt === "string" ? "prompt" : targetObj?.mode === "native" ? "native" : "deliver";
37831
+ return [{ action_id: actionId, placement, emphasis, dispatch_mode: dispatchMode }];
37832
+ });
37833
+ }
37834
+ function extractRenderedCardMeta(sourceChat, sourceTarget, projected, bindingContext) {
37835
+ const viewProps = isPlainRecord(projected.view?.props) ? projected.view.props : void 0;
37836
+ const render = isPlainRecord(viewProps?.render) ? viewProps.render : isPlainRecord(bindingContext) && typeof bindingContext.componentId === "string" ? bindingContext : void 0;
37837
+ const componentId = typeof render?.componentId === "string" && render.componentId || typeof projected.structuredContent.componentId === "string" && projected.structuredContent.componentId || sourceChat.component;
37838
+ const renderProps = isPlainRecord(render?.props) ? render.props : void 0;
37839
+ const viewMode = typeof renderProps?.view === "string" && renderProps.view || typeof viewProps?.view === "string" && viewProps.view || (projected.view ? null : "headless");
37840
+ if (render && Array.isArray(render.actions)) {
37841
+ return {
37842
+ componentId,
37843
+ viewMode,
37844
+ exposedActions: extractExposedActionsFromRender(render.actions)
37845
+ };
37846
+ }
37847
+ const declared = actionsFor(sourceChat, sourceTarget, bindingContext);
37848
+ const exposedActions = Object.entries(declared).filter(
37849
+ ([name]) => !(sourceChat.component === "chat-components/renderer@1" && (name === "upload" || name === "readMedia"))
37850
+ ).map(([name, binding]) => ({
37851
+ action_id: name,
37852
+ placement: "footer",
37853
+ emphasis: "primary",
37854
+ dispatch_mode: "prepareMessage" in binding && typeof binding.prepareMessage === "function" ? "prompt" : name.startsWith("deliver.") ? "deliver" : "native"
37855
+ }));
37856
+ return { componentId, viewMode, exposedActions };
37857
+ }
37781
37858
  var readOperation = (catalog, target2) => {
37782
37859
  const value = catalog.get(target2);
37783
37860
  if (!value) return;
@@ -37793,7 +37870,8 @@ var operationId = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/
37793
37870
  var targetSchema = external_exports.object({ instanceId: external_exports.string().regex(/^[a-z][a-z0-9-]*$/), operationId }).strict();
37794
37871
  var options = {
37795
37872
  requestKey: external_exports.string().min(1).max(200).refine((value) => Boolean(value.trim())).optional(),
37796
- approval: external_exports.string().min(1).optional()
37873
+ approval: external_exports.string().min(1).optional(),
37874
+ fromInteractionId: external_exports.string().min(1).max(200).refine((value) => Boolean(value.trim())).optional()
37797
37875
  };
37798
37876
  var jsonObjectInput = external_exports.preprocess(
37799
37877
  (value) => {
@@ -37813,6 +37891,7 @@ var chatActionSchema = external_exports.object({
37813
37891
  binding: external_exports.string().min(1).max(65536),
37814
37892
  action: operationId,
37815
37893
  input: jsonObjectInput.optional(),
37894
+ cardInstanceId: external_exports.string().min(1).max(200).refine((value) => Boolean(value.trim())).optional(),
37816
37895
  ...options
37817
37896
  }).strict();
37818
37897
  var projectionSchema = external_exports.object({
@@ -37957,8 +38036,8 @@ async function project(runtime, source, chat, result, projector, ui, action, bin
37957
38036
  );
37958
38037
  }
37959
38038
  const bindings = await actionBindings(runtime, source, chat, value.bindingContext);
37960
- const { bindingContext: _private, ...publicValue } = value;
37961
- return {
38039
+ const { bindingContext: projectedBindingContext, ...publicValue } = value;
38040
+ const projected = {
37962
38041
  ...publicValue,
37963
38042
  structuredContent: {
37964
38043
  ...value.structuredContent,
@@ -37981,6 +38060,12 @@ async function project(runtime, source, chat, result, projector, ui, action, bin
37981
38060
  ui
37982
38061
  } : void 0
37983
38062
  };
38063
+ Object.defineProperty(projected, "_bindingContext", {
38064
+ value: projectedBindingContext,
38065
+ enumerable: false,
38066
+ configurable: true
38067
+ });
38068
+ return projected;
37984
38069
  }
37985
38070
  function chatTargets(catalog, source, context) {
37986
38071
  const chat = readOperation(catalog, source)?.chat;
@@ -38008,17 +38093,31 @@ function readChatBundle(host, scope, target2, expected) {
38008
38093
  }
38009
38094
  async function runChat(host, projectId, raw) {
38010
38095
  const request = chatRunSchema.parse(raw);
38011
- return host.withOperations(
38012
- typeof projectId === "string" ? { kind: "project", id: projectId } : projectId,
38096
+ const scope = typeof projectId === "string" ? { kind: "project", id: projectId } : projectId;
38097
+ const telemetryProjectId = scope.kind === "project" ? scope.id : null;
38098
+ const cardInstanceId = uuidv72();
38099
+ const startedAt = performance.now();
38100
+ const requestedComponentId = isPlainRecord(request.input) && typeof request.input.componentId === "string" ? request.input.componentId : void 0;
38101
+ let resolvedComponentId = requestedComponentId ?? `${request.target.instanceId}/${request.target.operationId}`;
38102
+ const execute = () => host.withOperations(
38103
+ scope,
38013
38104
  (catalog) => chatTargets(catalog, request.target, request.input),
38014
38105
  async (runtime) => {
38015
38106
  const source = sourceOperation(runtime, request.target);
38107
+ resolvedComponentId = requestedComponentId ?? source.chat.component;
38016
38108
  const ui = await runtime.component(request.target, source.chat.component);
38017
- const result = await runtime.invoke(request.target, request.input, {
38109
+ const invokeOptions = request.fromInteractionId ? {
38110
+ requestKey: request.requestKey,
38111
+ approval: request.approval,
38112
+ fromInteractionId: request.fromInteractionId,
38113
+ triggerSource: "chat_component_explicit",
38114
+ callerSurface: "mcp"
38115
+ } : {
38018
38116
  requestKey: request.requestKey,
38019
38117
  approval: request.approval
38020
- });
38021
- return await project(
38118
+ };
38119
+ const result = await runtime.invoke(request.target, request.input, invokeOptions);
38120
+ const projected = await project(
38022
38121
  runtime,
38023
38122
  request.target,
38024
38123
  source.chat,
@@ -38026,126 +38125,301 @@ async function runChat(host, projectId, raw) {
38026
38125
  source.chat.projectResult,
38027
38126
  ui
38028
38127
  );
38128
+ const meta3 = extractRenderedCardMeta(
38129
+ source.chat,
38130
+ request.target,
38131
+ projected,
38132
+ projected._bindingContext
38133
+ );
38134
+ resolvedComponentId = meta3.componentId;
38135
+ if (projected.view) {
38136
+ projected.view = {
38137
+ ...projected.view,
38138
+ cardInstanceId,
38139
+ componentId: meta3.componentId
38140
+ };
38141
+ }
38142
+ const bindings = isPlainRecord(projected.structuredContent.bindings) ? projected.structuredContent.bindings : {};
38143
+ rememberCardBindings(bindings, {
38144
+ cardInstanceId,
38145
+ componentId: meta3.componentId,
38146
+ actions: new Map(meta3.exposedActions.map((item) => [item.action_id, item]))
38147
+ });
38148
+ safeRecordChatTelemetry(host, {
38149
+ event_name: "chat.card.rendered",
38150
+ project_id: telemetryProjectId,
38151
+ card_instance_id: cardInstanceId,
38152
+ component_id: meta3.componentId,
38153
+ view_mode: meta3.viewMode,
38154
+ exposed_actions: meta3.exposedActions,
38155
+ status: "ok",
38156
+ duration_ms: Math.max(0, Math.round(performance.now() - startedAt))
38157
+ });
38158
+ return projected;
38029
38159
  }
38030
38160
  );
38161
+ try {
38162
+ return request.fromInteractionId ? await withHostInteractionContext(
38163
+ host,
38164
+ {
38165
+ fromInteractionId: request.fromInteractionId,
38166
+ triggerSource: "chat_component_explicit",
38167
+ callerSurface: "mcp"
38168
+ },
38169
+ execute
38170
+ ) : await execute();
38171
+ } catch (error62) {
38172
+ safeRecordChatTelemetry(host, {
38173
+ event_name: "chat.card.rendered",
38174
+ project_id: telemetryProjectId,
38175
+ card_instance_id: cardInstanceId,
38176
+ component_id: resolvedComponentId,
38177
+ status: "error",
38178
+ duration_ms: Math.max(0, Math.round(performance.now() - startedAt)),
38179
+ error: error62
38180
+ });
38181
+ throw error62;
38182
+ }
38183
+ }
38184
+ function resolveActionClickMeta(request, sourceChat, bindingContext, isPrompt) {
38185
+ const isChatComponentsRenderer = sourceChat?.component === "chat-components/renderer@1";
38186
+ if (isChatComponentsRenderer && (request.action === "upload" || request.action === "readMedia")) {
38187
+ return {
38188
+ skipTelemetry: true,
38189
+ cardInstanceId: "",
38190
+ componentId: sourceChat.component,
38191
+ actionId: request.action,
38192
+ placement: "footer",
38193
+ emphasis: "secondary",
38194
+ dispatchMode: "native"
38195
+ };
38196
+ }
38197
+ const cached2 = cardBindingMeta.get(request.binding);
38198
+ const cardInstanceId = request.cardInstanceId ?? cached2?.cardInstanceId ?? uuidv72();
38199
+ const renderCtx = isPlainRecord(bindingContext) && typeof bindingContext.componentId === "string" ? bindingContext : void 0;
38200
+ const inputActionId = isPlainRecord(request.input) && typeof request.input.actionId === "string" && request.input.actionId ? request.input.actionId : void 0;
38201
+ const inputComponentId = isPlainRecord(request.input) && typeof request.input.componentId === "string" && request.input.componentId ? request.input.componentId : void 0;
38202
+ const componentId = typeof renderCtx?.componentId === "string" && renderCtx.componentId || inputComponentId || cached2?.componentId || sourceChat?.component || `${request.target.instanceId}/${request.target.operationId}`;
38203
+ const actionId = renderCtx || isChatComponentsRenderer ? inputActionId ?? request.action : request.action;
38204
+ const fromRender = renderCtx ? extractExposedActionsFromRender(renderCtx.actions).find((item) => item.action_id === actionId) : void 0;
38205
+ const fromCache = cached2?.actions.get(actionId);
38206
+ const dispatchMode = isPrompt ? "prompt" : fromRender?.dispatch_mode && fromRender.dispatch_mode !== "download" ? fromRender.dispatch_mode : fromCache?.dispatch_mode && fromCache.dispatch_mode !== "download" ? fromCache.dispatch_mode : request.action.startsWith("deliver.") ? "deliver" : "native";
38207
+ const placement = fromRender?.placement ?? fromCache?.placement ?? "footer";
38208
+ const emphasis = fromRender?.emphasis ?? fromCache?.emphasis ?? "primary";
38209
+ return {
38210
+ skipTelemetry: false,
38211
+ cardInstanceId,
38212
+ componentId,
38213
+ actionId,
38214
+ placement,
38215
+ emphasis,
38216
+ dispatchMode
38217
+ };
38031
38218
  }
38032
38219
  async function actionChat(host, projectId, raw) {
38033
38220
  const request = chatActionSchema.parse(raw);
38221
+ const scope = typeof projectId === "string" ? { kind: "project", id: projectId } : projectId;
38222
+ const telemetryProjectId = scope.kind === "project" ? scope.id : null;
38223
+ const cardInteractionId = uuidv72();
38224
+ const startedAt = performance.now();
38034
38225
  let destinationTarget;
38035
- return host.withOperations(
38036
- typeof projectId === "string" ? { kind: "project", id: projectId } : projectId,
38037
- (catalog) => {
38038
- const targets = catalog.bindingTargets(request.binding);
38039
- destinationTarget = targets[0];
38040
- try {
38041
- return [
38042
- ...targets,
38043
- ...chatTargets(catalog, request.target, catalog.bindingContext(request.binding))
38044
- ];
38045
- } catch {
38046
- return [...targets, request.target];
38047
- }
38048
- },
38049
- async (runtime) => {
38050
- const bindingContext = runtime.bindingContext(request.binding);
38051
- const current = readOperation(runtime, request.target);
38052
- const prepared = current?.chat && Object.hasOwn(current.chat.actions, request.action) ? current.chat.actions[request.action] : void 0;
38053
- if (prepared?.prepareMessage) {
38054
- if (destinationTarget.instanceId !== request.target.instanceId || destinationTarget.operationId !== request.target.operationId || await runtime.bind(request.target, [request.target], bindingContext) !== request.binding)
38055
- throw inputError(
38056
- "CHAT_ACTION_DENIED",
38057
- "The message binding does not belong to this card.",
38058
- "Use the original card and its source binding."
38059
- );
38060
- const context = {
38061
- projectId: runtime.scope.id,
38062
- target: { ...request.target },
38063
- action: request.action,
38064
- bindingContext
38065
- };
38066
- const message = chatMessageSchema.parse(await prepared.prepareMessage(request, context));
38067
- return {
38068
- text: "Message prepared. Awaiting chat client confirmation.",
38069
- structuredContent: {
38070
- protocolVersion: 1,
38071
- projectId: runtime.scope.id,
38072
- target: { ...request.target },
38073
- action: request.action
38074
- },
38075
- message
38076
- };
38077
- }
38078
- const invocation = await runtime.invokeBound(
38079
- request.binding,
38080
- { target: request.target, action: request.action, input: request.input },
38081
- { requestKey: request.requestKey, approval: request.approval },
38082
- async () => {
38083
- const source2 = sourceOperation(runtime, request.target);
38084
- const binding2 = declaredAction(
38085
- source2.chat,
38086
- request.target,
38087
- request.action,
38088
- bindingContext
38089
- );
38090
- const target2 = binding2.target;
38091
- if (target2.instanceId !== destinationTarget.instanceId || target2.operationId !== destinationTarget.operationId)
38092
- throw inputError(
38093
- "CHAT_ACTION_DENIED",
38094
- "The binding does not belong to this action.",
38095
- "Use the binding published for this card action."
38096
- );
38097
- if (await runtime.bind(target2, [request.target], bindingContext) !== request.binding)
38226
+ let telemetryMeta;
38227
+ try {
38228
+ return await host.withOperations(
38229
+ scope,
38230
+ (catalog) => {
38231
+ const targets = catalog.bindingTargets(request.binding);
38232
+ destinationTarget = targets[0];
38233
+ try {
38234
+ return [
38235
+ ...targets,
38236
+ ...chatTargets(catalog, request.target, catalog.bindingContext(request.binding))
38237
+ ];
38238
+ } catch {
38239
+ return [...targets, request.target];
38240
+ }
38241
+ },
38242
+ async (runtime) => {
38243
+ let bindingContext;
38244
+ try {
38245
+ bindingContext = runtime.bindingContext(request.binding);
38246
+ } catch (error62) {
38247
+ const currentOnFail = readOperation(runtime, request.target);
38248
+ telemetryMeta = resolveActionClickMeta(request, currentOnFail?.chat, void 0, false);
38249
+ throw error62;
38250
+ }
38251
+ const current = readOperation(runtime, request.target);
38252
+ const prepared = current?.chat && Object.hasOwn(current.chat.actions, request.action) ? current.chat.actions[request.action] : void 0;
38253
+ telemetryMeta = resolveActionClickMeta(
38254
+ request,
38255
+ current?.chat,
38256
+ bindingContext,
38257
+ Boolean(prepared?.prepareMessage)
38258
+ );
38259
+ if (prepared?.prepareMessage) {
38260
+ if (destinationTarget.instanceId !== request.target.instanceId || destinationTarget.operationId !== request.target.operationId || await runtime.bind(request.target, [request.target], bindingContext) !== request.binding)
38098
38261
  throw inputError(
38099
38262
  "CHAT_ACTION_DENIED",
38100
- "The binding does not belong to this source.",
38101
- "Use the original card and its published action binding."
38263
+ "The message binding does not belong to this card.",
38264
+ "Use the original card and its source binding."
38102
38265
  );
38103
38266
  const context = {
38104
38267
  projectId: runtime.scope.id,
38105
38268
  target: { ...request.target },
38106
38269
  action: request.action,
38107
- destination: { ...target2 },
38108
- bindingContext
38270
+ bindingContext,
38271
+ interactionId: cardInteractionId
38109
38272
  };
38110
- const input2 = binding2.mapInput ? await binding2.mapInput(request, context) : request.input ?? {};
38111
- await binding2.validate?.(input2, context);
38112
- return input2;
38113
- }
38114
- );
38115
- const source = readOperation(runtime, request.target);
38116
- let currentBinding;
38117
- try {
38118
- currentBinding = await runtime.bind(invocation.target, [request.target], bindingContext);
38119
- } catch {
38120
- }
38121
- if (!source?.chat || currentBinding !== request.binding) {
38122
- return {
38123
- text: "The original action completed. Reopen the operation to view the current card.",
38124
- structuredContent: {
38125
- protocolVersion: 1,
38126
- projectId: runtime.scope.id,
38127
- target: request.target,
38128
- action: request.action,
38129
- outcome: "succeeded",
38130
- result: invocation.result
38273
+ const message = chatMessageSchema.parse(await prepared.prepareMessage(request, context));
38274
+ if (!telemetryMeta.skipTelemetry) {
38275
+ safeRecordChatTelemetry(host, {
38276
+ event_name: "chat.card.action_clicked",
38277
+ project_id: telemetryProjectId,
38278
+ card_interaction_id: cardInteractionId,
38279
+ card_instance_id: telemetryMeta.cardInstanceId,
38280
+ component_id: telemetryMeta.componentId,
38281
+ action_id: telemetryMeta.actionId,
38282
+ placement: telemetryMeta.placement,
38283
+ emphasis: telemetryMeta.emphasis,
38284
+ dispatch_mode: "prompt",
38285
+ status: "ok",
38286
+ duration_ms: Math.max(0, Math.round(performance.now() - startedAt))
38287
+ });
38131
38288
  }
38289
+ return {
38290
+ text: "Message prepared. Awaiting chat client confirmation.",
38291
+ structuredContent: {
38292
+ protocolVersion: 1,
38293
+ projectId: runtime.scope.id,
38294
+ target: { ...request.target },
38295
+ action: request.action
38296
+ },
38297
+ message
38298
+ };
38299
+ }
38300
+ const invokeOptions = telemetryMeta.skipTelemetry ? { requestKey: request.requestKey, approval: request.approval } : {
38301
+ requestKey: request.requestKey,
38302
+ approval: request.approval,
38303
+ fromInteractionId: cardInteractionId,
38304
+ triggerSource: "chat_component_direct",
38305
+ callerSurface: "chat_component"
38132
38306
  };
38307
+ const invokeAction = () => runtime.invokeBound(
38308
+ request.binding,
38309
+ { target: request.target, action: request.action, input: request.input },
38310
+ invokeOptions,
38311
+ async () => {
38312
+ const source2 = sourceOperation(runtime, request.target);
38313
+ const binding2 = declaredAction(
38314
+ source2.chat,
38315
+ request.target,
38316
+ request.action,
38317
+ bindingContext
38318
+ );
38319
+ const target2 = binding2.target;
38320
+ if (target2.instanceId !== destinationTarget.instanceId || target2.operationId !== destinationTarget.operationId)
38321
+ throw inputError(
38322
+ "CHAT_ACTION_DENIED",
38323
+ "The binding does not belong to this action.",
38324
+ "Use the binding published for this card action."
38325
+ );
38326
+ if (await runtime.bind(target2, [request.target], bindingContext) !== request.binding)
38327
+ throw inputError(
38328
+ "CHAT_ACTION_DENIED",
38329
+ "The binding does not belong to this source.",
38330
+ "Use the original card and its published action binding."
38331
+ );
38332
+ const context = {
38333
+ projectId: runtime.scope.id,
38334
+ target: { ...request.target },
38335
+ action: request.action,
38336
+ destination: { ...target2 },
38337
+ bindingContext
38338
+ };
38339
+ const input2 = binding2.mapInput ? await binding2.mapInput(request, context) : request.input ?? {};
38340
+ await binding2.validate?.(input2, context);
38341
+ return input2;
38342
+ }
38343
+ );
38344
+ const invocation = telemetryMeta.skipTelemetry ? await invokeAction() : await withHostInteractionContext(
38345
+ host,
38346
+ {
38347
+ cardInteractionId,
38348
+ fromInteractionId: cardInteractionId,
38349
+ triggerSource: "chat_component_direct",
38350
+ callerSurface: "chat_component"
38351
+ },
38352
+ invokeAction
38353
+ );
38354
+ if (!telemetryMeta.skipTelemetry) {
38355
+ safeRecordChatTelemetry(host, {
38356
+ event_name: "chat.card.action_clicked",
38357
+ project_id: telemetryProjectId,
38358
+ card_interaction_id: cardInteractionId,
38359
+ card_instance_id: telemetryMeta.cardInstanceId,
38360
+ component_id: telemetryMeta.componentId,
38361
+ action_id: telemetryMeta.actionId,
38362
+ placement: telemetryMeta.placement,
38363
+ emphasis: telemetryMeta.emphasis,
38364
+ dispatch_mode: telemetryMeta.dispatchMode,
38365
+ status: "ok",
38366
+ duration_ms: Math.max(0, Math.round(performance.now() - startedAt))
38367
+ });
38368
+ }
38369
+ const source = readOperation(runtime, request.target);
38370
+ let currentBinding;
38371
+ try {
38372
+ currentBinding = await runtime.bind(invocation.target, [request.target], bindingContext);
38373
+ } catch {
38374
+ }
38375
+ if (!source?.chat || currentBinding !== request.binding) {
38376
+ return {
38377
+ text: "The original action completed. Reopen the operation to view the current card.",
38378
+ structuredContent: {
38379
+ protocolVersion: 1,
38380
+ projectId: runtime.scope.id,
38381
+ target: request.target,
38382
+ action: request.action,
38383
+ outcome: "succeeded",
38384
+ result: invocation.result
38385
+ }
38386
+ };
38387
+ }
38388
+ const binding = declaredAction(source.chat, request.target, request.action, bindingContext);
38389
+ const operation = readyDestination(runtime, invocation.target);
38390
+ const ui = await runtime.component(request.target, source.chat.component);
38391
+ return project(
38392
+ runtime,
38393
+ request.target,
38394
+ source.chat,
38395
+ invocation.result,
38396
+ binding.projectResult ?? operation.chat?.projectResult ?? source.chat.projectResult,
38397
+ ui,
38398
+ request.action,
38399
+ bindingContext
38400
+ );
38133
38401
  }
38134
- const binding = declaredAction(source.chat, request.target, request.action, bindingContext);
38135
- const operation = readyDestination(runtime, invocation.target);
38136
- const ui = await runtime.component(request.target, source.chat.component);
38137
- return project(
38138
- runtime,
38139
- request.target,
38140
- source.chat,
38141
- invocation.result,
38142
- binding.projectResult ?? operation.chat?.projectResult ?? source.chat.projectResult,
38143
- ui,
38144
- request.action,
38145
- bindingContext
38146
- );
38402
+ );
38403
+ } catch (error62) {
38404
+ const fallbackMeta = telemetryMeta ?? resolveActionClickMeta(request, void 0, void 0, false);
38405
+ if (!fallbackMeta.skipTelemetry) {
38406
+ safeRecordChatTelemetry(host, {
38407
+ event_name: "chat.card.action_clicked",
38408
+ project_id: telemetryProjectId,
38409
+ card_interaction_id: cardInteractionId,
38410
+ card_instance_id: fallbackMeta.cardInstanceId,
38411
+ component_id: fallbackMeta.componentId,
38412
+ action_id: fallbackMeta.actionId,
38413
+ placement: fallbackMeta.placement,
38414
+ emphasis: fallbackMeta.emphasis,
38415
+ dispatch_mode: fallbackMeta.dispatchMode,
38416
+ status: "error",
38417
+ duration_ms: Math.max(0, Math.round(performance.now() - startedAt)),
38418
+ error: error62
38419
+ });
38147
38420
  }
38148
- );
38421
+ throw error62;
38422
+ }
38149
38423
  }
38150
38424
  function declaredAction(chat, source, action, context) {
38151
38425
  const actions = actionsFor(chat, source, context);
@@ -38510,7 +38784,8 @@ var common = {
38510
38784
  scope: scopeSchema.optional(),
38511
38785
  target,
38512
38786
  requestKey: external_exports.string().min(1).max(200).optional(),
38513
- approval: identifier.optional()
38787
+ approval: identifier.optional(),
38788
+ fromInteractionId: external_exports.string().min(1).max(200).optional()
38514
38789
  };
38515
38790
  var routing = (value, context) => {
38516
38791
  if (value.projectId !== void 0 && value.scope !== void 0)
@@ -38524,8 +38799,30 @@ var actionInput = external_exports.object({
38524
38799
  ...common,
38525
38800
  binding: external_exports.string().min(1).max(65536),
38526
38801
  action: identifier,
38527
- input: jsonObjectInput.optional()
38802
+ input: jsonObjectInput.optional(),
38803
+ cardInstanceId: external_exports.string().min(1).max(200).optional()
38528
38804
  }).strict().superRefine(routing);
38805
+ var cardTelemetryInput = external_exports.discriminatedUnion("event", [
38806
+ external_exports.object({
38807
+ event: external_exports.literal("mounted"),
38808
+ cardInstanceId: external_exports.string().min(1).max(200),
38809
+ componentId: external_exports.string().min(1).max(200),
38810
+ projectId: external_exports.string().min(1).max(512).nullable().optional()
38811
+ }).strict(),
38812
+ external_exports.object({
38813
+ event: external_exports.literal("download_clicked"),
38814
+ cardInteractionId: external_exports.string().min(1).max(200).optional(),
38815
+ cardInstanceId: external_exports.string().min(1).max(200),
38816
+ componentId: external_exports.string().min(1).max(200),
38817
+ projectId: external_exports.string().min(1).max(512).nullable().optional(),
38818
+ actionId: external_exports.string().min(1).max(200).optional(),
38819
+ placement: external_exports.string().min(1).max(64).optional(),
38820
+ emphasis: external_exports.string().min(1).max(64).optional(),
38821
+ status: external_exports.enum(["ok", "error"]),
38822
+ durationMs: external_exports.number().int().nonnegative().optional(),
38823
+ errorMessage: external_exports.string().max(1e3).optional()
38824
+ }).strict()
38825
+ ]);
38529
38826
  function mapChatResult(result) {
38530
38827
  const { bindings: _bindings, ...structuredContent } = result.structuredContent;
38531
38828
  return {
@@ -38546,10 +38843,54 @@ function mapChatResult(result) {
38546
38843
  }
38547
38844
  function createChatServer(options2) {
38548
38845
  const host = options2.host;
38846
+ const mountedInstances = options2.mountedInstances ?? /* @__PURE__ */ new Set();
38549
38847
  const server = new McpServer(
38550
38848
  { name: "vivix-studio-chat", version: package_default.version },
38551
38849
  {
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."
38850
+ 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. On the immediate continuation turn after receiving a chat-component-action callback with interactionId, pass that exact value as optional fromInteractionId on run_studio_action (or --from-interaction on CLI calls). 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."
38851
+ }
38852
+ );
38853
+ server.registerTool(
38854
+ "report_card_telemetry",
38855
+ {
38856
+ title: "Report card telemetry",
38857
+ description: "Record MCP App card mount exposure and built-in media download interactions. App-only telemetry callback; does not mutate business state.",
38858
+ inputSchema: cardTelemetryInput,
38859
+ annotations: { readOnlyHint: true, openWorldHint: false },
38860
+ _meta: { ui: { visibility: ["app"] } }
38861
+ },
38862
+ async (input2) => {
38863
+ if (input2.event === "mounted") {
38864
+ if (!mountedInstances.has(input2.cardInstanceId)) {
38865
+ if (mountedInstances.size >= 4096) {
38866
+ const oldest = mountedInstances.values().next().value;
38867
+ if (oldest !== void 0) mountedInstances.delete(oldest);
38868
+ }
38869
+ mountedInstances.add(input2.cardInstanceId);
38870
+ safeRecordChatTelemetry(host, {
38871
+ event_name: "chat.card.mounted",
38872
+ project_id: input2.projectId ?? null,
38873
+ card_instance_id: input2.cardInstanceId,
38874
+ component_id: input2.componentId
38875
+ });
38876
+ }
38877
+ return { content: [{ type: "text", text: "Card mount recorded." }] };
38878
+ }
38879
+ safeRecordChatTelemetry(host, {
38880
+ event_name: "chat.card.action_clicked",
38881
+ project_id: input2.projectId ?? null,
38882
+ card_interaction_id: input2.cardInteractionId ?? uuidv72(),
38883
+ card_instance_id: input2.cardInstanceId,
38884
+ component_id: input2.componentId,
38885
+ action_id: input2.actionId ?? "download",
38886
+ placement: input2.placement ?? "inline",
38887
+ emphasis: input2.emphasis ?? "secondary",
38888
+ dispatch_mode: "download",
38889
+ status: input2.status,
38890
+ duration_ms: input2.durationMs,
38891
+ ...input2.errorMessage ? { error: new Error(input2.errorMessage) } : {}
38892
+ });
38893
+ return { content: [{ type: "text", text: "Card download telemetry recorded." }] };
38553
38894
  }
38554
38895
  );
38555
38896
  server.registerTool(
@@ -38834,6 +39175,7 @@ function activate(context) {
38834
39175
  return { value: normalized, description: normalized?.description };
38835
39176
  });
38836
39177
  const readHtml = () => readFile(new URL("./chat-ui/index.html", import.meta.url), "utf8");
39178
+ const mountedInstances = /* @__PURE__ */ new Set();
38837
39179
  context.http.register({
38838
39180
  id: "mcp",
38839
39181
  method: "POST",
@@ -38848,7 +39190,8 @@ function activate(context) {
38848
39190
  const server = createChatServer({
38849
39191
  host: context.host,
38850
39192
  readHtml,
38851
- resourceDomains: context.config.resourceDomains
39193
+ resourceDomains: context.config.resourceDomains,
39194
+ mountedInstances
38852
39195
  });
38853
39196
  try {
38854
39197
  await server.connect(transport);