File size: 11,627 Bytes
e18726e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Renders chat canvas payloads into text and metadata for transcript output.
import { expectDefined, safeParseJsonRecord } from "@openclaw/normalization-core";
import { asFiniteNumber } from "@openclaw/normalization-core/number-coercion";
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
import { parseFenceSpans } from "../../packages/markdown-core/src/fences.js";

// Extracts assistant-message canvas previews from tool JSON or markdown embed
// shortcodes. The returned text strips consumed shortcodes for channel delivery.
type CanvasSurface = "assistant_message" | "node_panel";
type CanvasSandbox = "strict" | "scripts";

type McpAppPreviewDescriptor = {
  viewId: string;
  serverName?: string;
  toolName?: string;
  uiResourceUri?: string;
  toolCallId?: string;
  originSessionKey?: string;
  resultMetaState?: "unavailable";
};

type CanvasPreview = {
  kind: "canvas";
  surface: CanvasSurface;
  render: "url";
  title?: string;
  preferredHeight?: number;
  url?: string;
  viewId?: string;
  className?: string;
  style?: string;
  sandbox?: CanvasSandbox;
  boardWidgetName?: string;
  mcpApp?: McpAppPreviewDescriptor;
};

function getRecordStringField(
  record: Record<string, unknown> | undefined,
  key: string,
): string | undefined {
  const value = record?.[key];
  return typeof value === "string" && value.trim() ? value : undefined;
}

function getRecordNumberField(
  record: Record<string, unknown> | undefined,
  key: string,
): number | undefined {
  const value = record?.[key];
  return asFiniteNumber(value);
}

function getNestedRecord(
  record: Record<string, unknown> | undefined,
  key: string,
): Record<string, unknown> | undefined {
  const value = record?.[key];
  return asOptionalRecord(value);
}

function coerceMcpAppDescriptor(
  record: Record<string, unknown> | undefined,
): McpAppPreviewDescriptor | undefined {
  const viewId = getRecordStringField(record, "viewId");
  if (!viewId || viewId.length > 128) {
    return undefined;
  }
  const serverName = getRecordStringField(record, "serverName");
  const toolName = getRecordStringField(record, "toolName");
  const uiResourceUri = getRecordStringField(record, "uiResourceUri");
  const toolCallId = getRecordStringField(record, "toolCallId");
  const originSessionKey = getRecordStringField(record, "originSessionKey");
  const resultMetaState = record?.resultMetaState === "unavailable" ? "unavailable" : undefined;
  const hasCompleteDescriptor = Boolean(
    serverName &&
    serverName.length <= 256 &&
    toolName &&
    toolName.length <= 256 &&
    uiResourceUri?.startsWith("ui://") &&
    uiResourceUri.length <= 2048 &&
    toolCallId &&
    toolCallId.length <= 512,
  );
  return hasCompleteDescriptor
    ? {
        viewId,
        serverName,
        toolName,
        uiResourceUri,
        toolCallId,
        ...(originSessionKey && originSessionKey.length <= 512 ? { originSessionKey } : {}),
        ...(resultMetaState ? { resultMetaState } : {}),
      }
    : { viewId };
}

function normalizeSurface(value: string | undefined): CanvasSurface | undefined {
  return value === "assistant_message" || value === "node_panel" ? value : undefined;
}

function normalizeSandbox(value: string | undefined): CanvasSandbox | undefined {
  return value === "strict" || value === "scripts" ? value : undefined;
}

function normalizePreferredHeight(value: number | undefined): number | undefined {
  return typeof value === "number" && Number.isFinite(value) && value >= 160
    ? Math.min(Math.trunc(value), 1200)
    : undefined;
}

export function isCanvasBoardWidgetName(value: unknown): value is string {
  return typeof value === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/u.test(value);
}

function coerceCanvasPreview(
  record: Record<string, unknown> | undefined,
): CanvasPreview | undefined {
  if (!record) {
    return undefined;
  }
  const kind = getRecordStringField(record, "kind")?.trim().toLowerCase();
  if (kind !== "canvas") {
    return undefined;
  }
  const presentation = getNestedRecord(record, "presentation");
  const view = getNestedRecord(record, "view");
  const source = getNestedRecord(record, "source");
  const mcpAppRecord = getNestedRecord(record, "mcpApp");
  const mcpApp = coerceMcpAppDescriptor(mcpAppRecord);
  const mcpAppViewId = mcpApp?.viewId;
  const requestedSurface =
    getRecordStringField(presentation, "target") ?? getRecordStringField(record, "target");
  const surface = requestedSurface ? normalizeSurface(requestedSurface) : "assistant_message";
  if (!surface) {
    return undefined;
  }
  const title = getRecordStringField(presentation, "title") ?? getRecordStringField(view, "title");
  const preferredHeight = normalizePreferredHeight(
    getRecordNumberField(presentation, "preferred_height") ??
      getRecordNumberField(presentation, "preferredHeight") ??
      getRecordNumberField(view, "preferred_height") ??
      getRecordNumberField(view, "preferredHeight"),
  );
  const className =
    getRecordStringField(presentation, "class_name") ??
    getRecordStringField(presentation, "className");
  const style = getRecordStringField(presentation, "style");
  const sandbox = normalizeSandbox(getRecordStringField(presentation, "sandbox"));
  const viewUrl = getRecordStringField(view, "url") ?? getRecordStringField(view, "entryUrl");
  const viewId = getRecordStringField(view, "id") ?? getRecordStringField(view, "docId");
  const requestedBoardWidgetName = getRecordStringField(view, "boardWidgetName");
  const boardWidgetName = isCanvasBoardWidgetName(requestedBoardWidgetName)
    ? requestedBoardWidgetName
    : undefined;
  if (mcpAppViewId && viewId === mcpAppViewId) {
    return {
      kind: "canvas",
      surface,
      render: "url",
      viewId,
      ...(title ? { title } : {}),
      ...(preferredHeight ? { preferredHeight } : {}),
      ...(sandbox ? { sandbox } : {}),
      mcpApp,
    };
  }
  if (viewUrl) {
    return {
      kind: "canvas",
      surface,
      render: "url",
      url: viewUrl,
      ...(viewId ? { viewId } : {}),
      ...(title ? { title } : {}),
      ...(preferredHeight ? { preferredHeight } : {}),
      ...(className ? { className } : {}),
      ...(style ? { style } : {}),
      ...(sandbox ? { sandbox } : {}),
      ...(boardWidgetName ? { boardWidgetName } : {}),
      ...(mcpApp ? { mcpApp } : {}),
    };
  }
  const sourceType = getRecordStringField(source, "type")?.trim().toLowerCase();
  if (sourceType === "url") {
    const url = getRecordStringField(source, "url");
    if (!url) {
      return undefined;
    }
    return {
      kind: "canvas",
      surface,
      render: "url",
      url,
      ...(title ? { title } : {}),
      ...(preferredHeight ? { preferredHeight } : {}),
      ...(className ? { className } : {}),
      ...(style ? { style } : {}),
      ...(sandbox ? { sandbox } : {}),
      ...(mcpApp ? { mcpApp } : {}),
    };
  }
  return undefined;
}

/** Extracts an MCP App Canvas preview from sanitized tool-result details. */
export function extractCanvasFromDetails(value: unknown): CanvasPreview | undefined {
  const details = asOptionalRecord(value);
  return coerceCanvasPreview(asOptionalRecord(details?.mcpAppPreview));
}

function parseCanvasAttributes(raw: string): Record<string, string> {
  const attrs: Record<string, string> = {};
  const re = /([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
  let match: RegExpExecArray | null;
  while ((match = re.exec(raw))) {
    const key = match[1]?.trim().toLowerCase();
    const value = (match[2] ?? match[3] ?? "").trim();
    if (key && value) {
      attrs[key] = value;
    }
  }
  return attrs;
}

function defaultCanvasEntryUrl(ref: string): string {
  const encoded = encodeURIComponent(ref.trim());
  return `/__openclaw__/canvas/documents/${encoded}/index.html`;
}

function previewFromShortcode(attrs: Record<string, string>): CanvasPreview | undefined {
  if (attrs.target && normalizeSurface(attrs.target) !== "assistant_message") {
    return undefined;
  }
  const surface = "assistant_message";
  const title = attrs.title?.trim() || undefined;
  const preferredHeight =
    attrs.height && Number.isFinite(Number(attrs.height))
      ? normalizePreferredHeight(Number(attrs.height))
      : undefined;
  const className = attrs.class?.trim() || attrs.class_name?.trim() || undefined;
  const style = attrs.style?.trim() || undefined;
  const ref = attrs.ref?.trim();
  const url = attrs.url?.trim();
  if (url || ref) {
    return {
      kind: "canvas",
      surface,
      render: "url",
      url: url ?? defaultCanvasEntryUrl(expectDefined(ref, "canvas reference")),
      ...(ref ? { viewId: ref } : {}),
      ...(title ? { title } : {}),
      ...(preferredHeight ? { preferredHeight } : {}),
      ...(className ? { className } : {}),
      ...(style ? { style } : {}),
    };
  }
  return undefined;
}

/** Extracts a canvas preview from a JSON-shaped tool or assistant payload. */
export function extractCanvasFromText(
  outputText: string | undefined,
  _toolName?: string,
): CanvasPreview | undefined {
  const parsed = outputText ? safeParseJsonRecord(outputText) : undefined;
  return coerceCanvasPreview(parsed);
}

/** Extracts [embed ...] shortcodes outside code fences and returns stripped text. */
export function extractCanvasShortcodes(text: string | undefined): {
  text: string;
  previews: CanvasPreview[];
} {
  if (!text?.trim() || !text.toLowerCase().includes("[embed")) {
    return { text: text ?? "", previews: [] };
  }
  const fenceSpans = parseFenceSpans(text);
  const matches: Array<{
    start: number;
    end: number;
    attrs: Record<string, string>;
    body?: string;
  }> = [];
  // Exclude a self-closing open tag ("[embed ... /]") from starting a block
  // match by requiring the attrs group not to end with a slash; otherwise the
  // block regex greedily swallows visible text up to a later stray [/embed].
  const blockRe = /\[embed\s+([^\]]*?[^\]/]|)\]([\s\S]*?)\[\/embed\]/gi;
  const selfClosingRe = /\[embed\s+([^\]]*?)\/\]/gi;
  for (const re of [blockRe, selfClosingRe]) {
    // Each regex starts a new ascending pass over the ordered fence spans.
    let fenceIndex = 0;
    let match: RegExpExecArray | null;
    while ((match = re.exec(text))) {
      const start = match.index ?? 0;
      let fence = fenceSpans[fenceIndex];
      while (fence && start >= fence.end) {
        fenceIndex += 1;
        fence = fenceSpans[fenceIndex];
      }
      if (fence && start >= fence.start) {
        // Literal embed examples in code blocks must remain visible text.
        continue;
      }
      matches.push({
        start,
        end: start + match[0].length,
        attrs: parseCanvasAttributes(match[1] ?? ""),
        ...(match[2] !== undefined ? { body: match[2] } : {}),
      });
    }
  }
  if (matches.length === 0) {
    return { text, previews: [] };
  }
  matches.sort((a, b) => a.start - b.start);
  const previews: CanvasPreview[] = [];
  let cursor = 0;
  let stripped = "";
  for (const match of matches) {
    if (match.start < cursor) {
      // Prefer the first non-overlapping shortcode so nested/overlapping input
      // cannot strip arbitrary text outside the matched span.
      continue;
    }
    stripped += text.slice(cursor, match.start);
    const preview = previewFromShortcode(match.attrs);
    if (!preview) {
      stripped += text.slice(match.start, match.end);
    } else {
      previews.push(preview);
    }
    cursor = match.end;
  }
  stripped += text.slice(cursor);
  return {
    text: stripped,
    previews,
  };
}