@supersolutions/super-chat-core 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,11 +8,11 @@ import {
8
8
  isTerminal,
9
9
  reap,
10
10
  resumeJobs
11
- } from "./chunk-MHGENDQX.js";
11
+ } from "./chunk-HKGDZQS6.js";
12
12
  import {
13
13
  buildAnthropicRequest,
14
14
  createAnthropicProvider
15
- } from "./chunk-JMM3X3GB.js";
15
+ } from "./chunk-ZMPT7BBM.js";
16
16
  import {
17
17
  AgentError,
18
18
  DEFAULT_RETRY,
@@ -26,10 +26,12 @@ import {
26
26
  parseRetryAfter,
27
27
  parseSSE,
28
28
  parseSSEJson,
29
+ readObject,
29
30
  repairToolArguments,
31
+ text,
30
32
  toAgentError,
31
33
  withRetry
32
- } from "./chunk-32DPF33V.js";
34
+ } from "./chunk-CJ6WV4KB.js";
33
35
 
34
36
  // src/content/parts.ts
35
37
  var counter = 0;
@@ -37,7 +39,7 @@ function nextId(prefix = "msg") {
37
39
  counter += 1;
38
40
  return `${prefix}_${Date.now().toString(36)}${counter.toString(36)}`;
39
41
  }
40
- var text = (value) => ({ type: "text", text: value });
42
+ var text2 = (value) => ({ type: "text", text: value });
41
43
  var image = (source, opts = {}) => ({ type: "image", source, ...opts });
42
44
  var file = (source, mediaType, filename) => ({
43
45
  type: "file",
@@ -51,7 +53,7 @@ function message(role, parts, id) {
51
53
  return {
52
54
  id: id ?? nextId(role === "assistant" ? "asst" : role),
53
55
  role,
54
- parts: typeof parts === "string" ? [text(parts)] : parts,
56
+ parts: typeof parts === "string" ? [text2(parts)] : parts,
55
57
  createdAt: Date.now()
56
58
  };
57
59
  }
@@ -156,31 +158,31 @@ function scanLines(src) {
156
158
  }
157
159
  return out;
158
160
  }
159
- var isBlank = (text3) => text3.trim() === "";
161
+ var isBlank = (text4) => text4.trim() === "";
160
162
  var FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})(.*)$/;
161
163
  var INDENTED = /^(?: {4}|\t)/;
162
164
  var LIST_ITEM = /^ {0,3}(?:[-*+]|\d{1,9}[.)])(?:\s|$)/;
163
165
  var QUOTE = /^ {0,3}>/;
164
- function fenceOpen(text3) {
165
- const m = FENCE_OPEN.exec(text3);
166
+ function fenceOpen(text4) {
167
+ const m = FENCE_OPEN.exec(text4);
166
168
  if (!m) return null;
167
169
  const marker = m[1];
168
170
  const char = marker[0];
169
171
  if (char === "`" && m[2].includes("`")) return null;
170
172
  return { marker, char };
171
173
  }
172
- function closesFence(text3, open) {
173
- const m = /^ {0,3}(`{3,}|~{3,})\s*$/.exec(text3);
174
+ function closesFence(text4, open) {
175
+ const m = /^ {0,3}(`{3,}|~{3,})\s*$/.exec(text4);
174
176
  if (!m) return false;
175
177
  const marker = m[1];
176
178
  return marker[0] === open.char && marker.length >= open.marker.length;
177
179
  }
178
- function continues(construct, text3) {
179
- if (construct === "list") return LIST_ITEM.test(text3) || INDENTED.test(text3);
180
- if (construct === "quote") return QUOTE.test(text3);
180
+ function continues(construct, text4) {
181
+ if (construct === "list") return LIST_ITEM.test(text4) || INDENTED.test(text4);
182
+ if (construct === "quote") return QUOTE.test(text4);
181
183
  return false;
182
184
  }
183
- var constructOf = (text3) => QUOTE.test(text3) ? "quote" : LIST_ITEM.test(text3) ? "list" : "other";
185
+ var constructOf = (text4) => QUOTE.test(text4) ? "quote" : LIST_ITEM.test(text4) ? "list" : "other";
184
186
  function splitBlocks(src) {
185
187
  const lines = scanLines(src);
186
188
  const blocks = [];
@@ -308,8 +310,8 @@ var driftNote = (drift) => {
308
310
  `;
309
311
  };
310
312
  var QUOTES_METADATA_KEY = "documentQuotes";
311
- var fence = (text3) => {
312
- const longest = [...text3.matchAll(/`{3,}/g)].reduce((n, m) => Math.max(n, m[0].length), 2);
313
+ var fence = (text4) => {
314
+ const longest = [...text4.matchAll(/`{3,}/g)].reduce((n, m) => Math.max(n, m[0].length), 2);
313
315
  return "`".repeat(longest + 1);
314
316
  };
315
317
  function formatQuotes(quotes) {
@@ -324,18 +326,85 @@ ${q.text}
324
326
  ${f}`;
325
327
  }).join("\n\n");
326
328
  }
327
- function withQuotes(text3, quotes) {
329
+ function withQuotes(text4, quotes) {
328
330
  const prefix = formatQuotes(quotes);
329
- if (!prefix) return text3;
330
- return text3.trim() ? `${prefix}
331
+ if (!prefix) return text4;
332
+ return text4.trim() ? `${prefix}
331
333
 
332
- ${text3}` : prefix;
334
+ ${text4}` : prefix;
333
335
  }
334
336
  function quotesOf(metadata) {
335
337
  const raw = metadata?.[QUOTES_METADATA_KEY];
336
338
  return Array.isArray(raw) ? raw : [];
337
339
  }
338
340
 
341
+ // src/content/clips.ts
342
+ var CLIPS_METADATA_KEY = "contextClips";
343
+ var MAX_CLIP_CHARS = 8e3;
344
+ var fence2 = (text4) => {
345
+ const longest = [...text4.matchAll(/`{3,}/g)].reduce((n, m) => Math.max(n, m[0].length), 2);
346
+ return "`".repeat(longest + 1);
347
+ };
348
+ var clipped = (text4) => text4.length > MAX_CLIP_CHARS ? `${text4.slice(0, MAX_CLIP_CHARS)}
349
+ [cut: the selection is longer than ${MAX_CLIP_CHARS} characters]` : text4;
350
+ var oneLine = (text4) => text4.trim().replace(/\s+/g, " ");
351
+ function formatExcerpt(clip3) {
352
+ const source = clip3.from?.role === "user" ? "the user's own earlier message" : "an earlier answer in this conversation";
353
+ const body = clipped(clip3.text);
354
+ const f = fence2(body);
355
+ return `Excerpt the user selected from ${source}:
356
+ ${f}text
357
+ ${body}
358
+ ${f}`;
359
+ }
360
+ function formatAnnotations(clip3) {
361
+ const count = clip3.marks.length;
362
+ const where = `${JSON.stringify(clip3.title)} (${clip3.docId}${clip3.revision === void 0 ? "" : ` v${clip3.revision}`})`;
363
+ const lines = clip3.marks.map((mark, i) => {
364
+ const on = mark.quote ? `On "${oneLine(clipped(mark.quote))}"` : mark.blockId ? `On block ${mark.blockId}` : "On the document";
365
+ const block = mark.quote && mark.blockId ? ` (block ${mark.blockId})` : "";
366
+ const who = mark.author ? ` \u2014 ${mark.author}` : "";
367
+ const replies = (mark.replies ?? []).map((r) => `
368
+ Reply${r.author ? ` from ${r.author}` : ""}: ${oneLine(r.text)}`).join("");
369
+ return `${i + 1}. ${on}${block}: ${oneLine(clipped(mark.note))}${who}${replies}`;
370
+ });
371
+ return `The user pinned ${count === 1 ? "1 annotation" : `${count} annotations`} on the document ${where}. They are comments about places in the document, not part of its text:
372
+ ${lines.join("\n")}`;
373
+ }
374
+ function formatClips(clips) {
375
+ return clips.filter((c) => c.kind === "excerpt" ? c.text.trim() : c.marks.length > 0).map((c) => c.kind === "excerpt" ? formatExcerpt(c) : formatAnnotations(c)).join("\n\n");
376
+ }
377
+ function withClips(text4, clips) {
378
+ const prefix = formatClips(clips);
379
+ if (!prefix) return text4;
380
+ return text4.trim() ? `${prefix}
381
+
382
+ ${text4}` : prefix;
383
+ }
384
+ function stripClips(text4, clips) {
385
+ const prefix = formatClips(clips);
386
+ if (!prefix || !text4.startsWith(prefix)) return text4;
387
+ return text4.slice(prefix.length).replace(/^\n+/, "");
388
+ }
389
+ function clipsOf(metadata) {
390
+ const raw = metadata?.[CLIPS_METADATA_KEY];
391
+ if (!Array.isArray(raw)) return [];
392
+ return raw.filter((c) => {
393
+ if (!c || typeof c !== "object") return false;
394
+ const clip3 = c;
395
+ if (clip3.kind === "excerpt") return typeof clip3.id === "string" && typeof clip3.text === "string";
396
+ if (clip3.kind === "annotations") {
397
+ return typeof clip3.id === "string" && typeof clip3.docId === "string" && typeof clip3.title === "string" && Array.isArray(clip3.marks);
398
+ }
399
+ return false;
400
+ });
401
+ }
402
+ function clipPreview(clip3, limit = 90) {
403
+ const text4 = clip3.kind === "excerpt" ? clip3.text : clip3.marks.map((m) => m.note).filter(Boolean).join(" \xB7 ");
404
+ const flat = oneLine(text4);
405
+ return flat.length > limit ? `${flat.slice(0, limit - 1)}\u2026` : flat;
406
+ }
407
+
339
408
  // src/transport/binary.ts
340
409
  var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
341
410
  var REVERSE = /* @__PURE__ */ (() => {
@@ -528,6 +597,10 @@ function createOpenAICompatibleProfile(profile) {
528
597
  return normalizeProviderProfile({ ...profile, protocol: "openai-chat" });
529
598
  }
530
599
  function normalizeProviderProfile(profile) {
600
+ if (typeof profile !== "object" || profile === null) throw new Error("Provider profile must be an object.");
601
+ if (typeof profile.id !== "string") throw new Error("Provider profile id must be a string.");
602
+ if (typeof profile.label !== "string") throw new Error("Provider profile label is required.");
603
+ if (typeof profile.baseUrl !== "string") throw new Error("Provider profile baseUrl must be an absolute URL.");
531
604
  const id = profile.id.trim();
532
605
  const label = profile.label.trim();
533
606
  if (!id || !/^[a-z0-9][a-z0-9._-]*$/i.test(id)) {
@@ -549,11 +622,13 @@ function normalizeProviderProfile(profile) {
549
622
  if (url.search || url.hash) {
550
623
  throw new Error("Provider profile baseUrl cannot include a query or fragment.");
551
624
  }
625
+ let end = url.pathname.length;
626
+ while (end > 0 && url.pathname.charCodeAt(end - 1) === 47) end--;
552
627
  return {
553
628
  ...profile,
554
629
  id,
555
630
  label,
556
- baseUrl: url.toString().replace(/\/$/, "")
631
+ baseUrl: url.origin + url.pathname.slice(0, end)
557
632
  };
558
633
  }
559
634
  function createProviderFromProfile(profileInput, transport) {
@@ -629,20 +704,26 @@ function createOpenAIImageProvider(config) {
629
704
  signal: opts?.signal
630
705
  });
631
706
  if (!res.ok) throw await errorFromResponse(res, id);
632
- const json = await res.json();
633
- if (!json.data?.length) throw new Error(`Provider "${id}" returned no generated images.`);
634
- const createdAt = (json.created ?? Math.floor(Date.now() / 1e3)) * 1e3;
707
+ const json = await readObject(res, id);
708
+ const items = Array.isArray(json.data) ? json.data : [];
709
+ if (!items.length) throw new Error(`Provider "${id}" returned no generated images.`);
710
+ const created = typeof json.created === "number" && Number.isFinite(json.created) && json.created >= 0 ? json.created : Math.floor(Date.now() / 1e3);
711
+ const createdAt = created * 1e3;
635
712
  const dimensions = dimensionsFromSize(req.size);
636
- return json.data.map((item) => {
637
- if (!item.url && !item.b64_json) throw new Error(`Provider "${id}" returned an image without url or b64_json.`);
713
+ return items.map((entry) => {
714
+ const item = typeof entry === "object" && entry !== null ? entry : {};
715
+ const url = text(item.url) || void 0;
716
+ const b64 = text(item.b64_json) || void 0;
717
+ const revisedPrompt = text(item.revised_prompt);
718
+ if (!url && !b64) throw new Error(`Provider "${id}" returned an image without url or b64_json.`);
638
719
  return {
639
720
  id: nextId("media"),
640
721
  kind: "image",
641
- source: item.url ? { kind: "url", url: item.url } : { kind: "base64", data: item.b64_json },
722
+ source: url ? { kind: "url", url } : { kind: "base64", data: b64 },
642
723
  mediaType: "image/png",
643
724
  provider: id,
644
725
  ...req.model ?? config.defaultModel ? { model: req.model ?? config.defaultModel } : {},
645
- ...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {},
726
+ ...revisedPrompt ? { revisedPrompt } : {},
646
727
  ...dimensions ?? {},
647
728
  createdAt
648
729
  };
@@ -729,11 +810,11 @@ function createGenerateImageTool(provider, options = {}) {
729
810
  // src/tokens/estimate.ts
730
811
  var LATIN_CHARS_PER_TOKEN = 3.7;
731
812
  var CJK_CHARS_PER_TOKEN = 1.1;
732
- function estimateTokens(text3) {
733
- if (!text3) return 0;
813
+ function estimateTokens(text4) {
814
+ if (!text4) return 0;
734
815
  let cjk = 0;
735
816
  let other = 0;
736
- for (const ch of text3) {
817
+ for (const ch of text4) {
737
818
  const code = ch.codePointAt(0);
738
819
  const isCjk = code >= 12352 && code <= 12543 || // kana
739
820
  code >= 13312 && code <= 19903 || // CJK ext A
@@ -902,10 +983,13 @@ function scoreAlias(alias, query, queryTokens) {
902
983
  }
903
984
  return 0;
904
985
  }
905
- function scoreSkill(skill, query) {
986
+ var prepareQuery = (query) => {
906
987
  const q = query.toLowerCase().trim();
988
+ return { q, queryTokens: q ? new Set(tokenize(q)) : /* @__PURE__ */ new Set() };
989
+ };
990
+ function scoreSkill(skill, query, prepared = prepareQuery(query)) {
991
+ const { q, queryTokens } = prepared;
907
992
  if (!q) return { score: 0, reason: "empty query", sections: [] };
908
- const queryTokens = new Set(tokenize(q));
909
993
  let score = 0;
910
994
  const reasons = [];
911
995
  const nameScore = scoreAlias(skill.name, q, queryTokens);
@@ -946,8 +1030,9 @@ function scoreSkill(skill, query) {
946
1030
  return { score, reason: reasons.join(" ") || "no match", sections };
947
1031
  }
948
1032
  function matchSkills(skills, query, threshold = 1.5) {
1033
+ const prepared = prepareQuery(query);
949
1034
  return skills.map((skill) => {
950
- const { score, reason, sections } = scoreSkill(skill, query);
1035
+ const { score, reason, sections } = scoreSkill(skill, query, prepared);
951
1036
  return { skill, score, reason, sections };
952
1037
  }).filter((m) => m.score >= threshold).sort((a, b) => b.score - a.score || a.skill.id.localeCompare(b.skill.id));
953
1038
  }
@@ -1014,12 +1099,12 @@ var SkillRegistry = class {
1014
1099
  const matched = this.matcher(list, ctx.query).filter((m) => m.skill.mode === "matched" && !forced.has(m.skill.id)).slice(0, this.maxMatched);
1015
1100
  const out = [];
1016
1101
  for (const skill of always) {
1017
- const text3 = await renderSkill(skill, ctx);
1102
+ const text4 = await renderSkill(skill, ctx);
1018
1103
  out.push({
1019
1104
  id: skill.id,
1020
1105
  name: skill.name,
1021
- text: text3,
1022
- tokens: estimateTokens(text3),
1106
+ text: text4,
1107
+ tokens: estimateTokens(text4),
1023
1108
  // Sort key: `always` outranks any matched score so it survives packing.
1024
1109
  score: 1e3 + (skill.priority ?? 0),
1025
1110
  mode: skill.mode,
@@ -1027,12 +1112,12 @@ var SkillRegistry = class {
1027
1112
  });
1028
1113
  }
1029
1114
  for (const m of matched) {
1030
- const text3 = await renderSkill(m.skill, ctx, m.sections);
1115
+ const text4 = await renderSkill(m.skill, ctx, m.sections);
1031
1116
  out.push({
1032
1117
  id: m.skill.id,
1033
1118
  name: m.skill.name,
1034
- text: text3,
1035
- tokens: estimateTokens(text3),
1119
+ text: text4,
1120
+ tokens: estimateTokens(text4),
1036
1121
  score: m.score,
1037
1122
  mode: m.skill.mode,
1038
1123
  tools: m.skill.tools ?? []
@@ -1164,14 +1249,15 @@ ${summary}`
1164
1249
  const tokensAfter = countMessagesTokens(out, counter3);
1165
1250
  if (tokensAfter > opts.limitTokens) {
1166
1251
  const summaryTokens = countMessageTokens(summaryMessage, counter3);
1252
+ if (summaryTokens >= opts.limitTokens) return trimHistory(messages, opts.limitTokens, counter3, tokensBefore);
1167
1253
  const trimmed = trimHistory(recent, Math.max(0, opts.limitTokens - summaryTokens), counter3, tokensAfter - summaryTokens);
1168
- const messages2 = [summaryMessage, ...trimmed.messages];
1254
+ const fitted = [summaryMessage, ...trimmed.messages];
1169
1255
  return {
1170
- messages: messages2,
1256
+ messages: fitted,
1171
1257
  strategy: "summarize",
1172
1258
  droppedCount: older.length + trimmed.droppedCount,
1173
1259
  tokensBefore,
1174
- tokensAfter: countMessagesTokens(messages2, counter3),
1260
+ tokensAfter: countMessagesTokens(fitted, counter3),
1175
1261
  summary
1176
1262
  };
1177
1263
  }
@@ -1179,9 +1265,9 @@ ${summary}`
1179
1265
  }
1180
1266
  function buildSummaryPrompt(messages) {
1181
1267
  const transcript = messages.map((m) => {
1182
- const text3 = messageText(m);
1268
+ const text4 = messageText(m);
1183
1269
  const calls = m.parts.filter((p) => p.type === "tool-call").map((p) => `\u2192 called ${p.name}`).join(" ");
1184
- return `${m.role}: ${text3}${calls ? ` ${calls}` : ""}`.trim();
1270
+ return `${m.role}: ${text4}${calls ? ` ${calls}` : ""}`.trim();
1185
1271
  }).filter((line) => line.length > line.indexOf(":") + 1).join("\n");
1186
1272
  return [
1187
1273
  "Compress this conversation span into a brief the assistant can act on.",
@@ -1222,8 +1308,8 @@ var ContextBuilder = class {
1222
1308
  const unlockedTools = new Set(input.baseTools ?? []);
1223
1309
  let skills = [];
1224
1310
  if (this.opts.identity?.trim()) {
1225
- const text3 = this.opts.identity.trim();
1226
- layers.push({ id: "identity", kind: "identity", text: text3, tokens: counter3(text3), pinned: true, priority: 1e3 });
1311
+ const text4 = this.opts.identity.trim();
1312
+ layers.push({ id: "identity", kind: "identity", text: text4, tokens: counter3(text4), pinned: true, priority: 1e3 });
1227
1313
  }
1228
1314
  if (this.opts.skills) {
1229
1315
  const started = Date.now();
@@ -1503,6 +1589,9 @@ function hunksOf(applied) {
1503
1589
  }
1504
1590
 
1505
1591
  // src/documents/store.ts
1592
+ var record = () => /* @__PURE__ */ Object.create(null);
1593
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1594
+ var isSnapshot = (v) => isRecord(v) && typeof v.id === "string" && typeof v.markdown === "string" && typeof v.title === "string" && typeof v.revision === "number" && Number.isFinite(v.revision) && typeof v.updatedAt === "number";
1506
1595
  var MAX_HISTORY = 20;
1507
1596
  var counter2 = 0;
1508
1597
  var mintId = () => `doc_${Date.now().toString(36)}${(counter2 += 1).toString(36)}`;
@@ -1566,22 +1655,43 @@ function createMemoryDocumentStore() {
1566
1655
  };
1567
1656
  }
1568
1657
  function createLocalDocumentStore(key = "superchat:documents") {
1658
+ let refused2 = null;
1659
+ const copy = (all) => ({ docs: Object.assign(record(), all.docs), past: Object.assign(record(), all.past) });
1569
1660
  const read = () => {
1661
+ if (refused2) return copy(refused2);
1570
1662
  try {
1571
1663
  const raw = globalThis.localStorage?.getItem(key) ?? null;
1572
1664
  const parsed = raw ? JSON.parse(raw) : null;
1573
- if (typeof parsed !== "object" || parsed === null) return { docs: {}, past: {} };
1665
+ if (typeof parsed !== "object" || parsed === null) return { docs: record(), past: record() };
1574
1666
  const p = parsed;
1575
- return { docs: p.docs ?? {}, past: p.past ?? {} };
1667
+ const docs = record();
1668
+ const past = record();
1669
+ if (isRecord(p.docs)) {
1670
+ for (const [id, doc] of Object.entries(p.docs)) if (isSnapshot(doc)) docs[id] = doc;
1671
+ }
1672
+ if (isRecord(p.past)) {
1673
+ for (const [id, list] of Object.entries(p.past)) if (Array.isArray(list)) past[id] = list.filter(isSnapshot);
1674
+ }
1675
+ return { docs, past };
1576
1676
  } catch {
1577
- return { docs: {}, past: {} };
1677
+ return { docs: record(), past: record() };
1578
1678
  }
1579
1679
  };
1580
1680
  const write = (all) => {
1581
- try {
1582
- globalThis.localStorage?.setItem(key, JSON.stringify(all));
1583
- } catch {
1681
+ const store = globalThis.localStorage;
1682
+ if (!store) {
1683
+ refused2 = all;
1684
+ return;
1685
+ }
1686
+ for (const [attempt, history] of [[all, true], [{ docs: all.docs, past: record() }, false]]) {
1687
+ try {
1688
+ store.setItem(key, JSON.stringify(attempt));
1689
+ refused2 = history ? null : all;
1690
+ return;
1691
+ } catch {
1692
+ }
1584
1693
  }
1694
+ refused2 = all;
1585
1695
  };
1586
1696
  return {
1587
1697
  async list() {
@@ -1785,7 +1895,7 @@ function createDocumentTools(opts) {
1785
1895
  }
1786
1896
  const from = num(i["from"]) ?? 0;
1787
1897
  const to = num(i["to"]) ?? from;
1788
- const text3 = spanOf(doc.markdown, from, to);
1898
+ const text4 = spanOf(doc.markdown, from, to);
1789
1899
  return {
1790
1900
  output: {
1791
1901
  docId: doc.id,
@@ -1795,8 +1905,8 @@ function createDocumentTools(opts) {
1795
1905
  // Truncation is REPORTED, not silent: a model that believes it has
1796
1906
  // read a whole section will quote text that is not there, and the
1797
1907
  // edit will then be refused for a reason that looks like its fault.
1798
- truncated: text3.length > maxSpanChars,
1799
- text: text3.slice(0, maxSpanChars)
1908
+ truncated: text4.length > maxSpanChars,
1909
+ text: text4.slice(0, maxSpanChars)
1800
1910
  }
1801
1911
  };
1802
1912
  }
@@ -2070,6 +2180,37 @@ var check = {
2070
2180
  return value;
2071
2181
  }
2072
2182
  };
2183
+ var typeName = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
2184
+ var isType = (t, v) => t === "string" ? typeof v === "string" : t === "number" || t === "integer" ? typeof v === "number" : t === "boolean" ? typeof v === "boolean" : t === "array" ? Array.isArray(v) : t === "object" ? isObj(v) : t === "null" ? v === null : true;
2185
+ var SHAPE_ITEMS = 500;
2186
+ function shapeError(value, schema, path, optional = false) {
2187
+ if (!isObj(schema)) return void 0;
2188
+ if ((value === void 0 || value === null) && optional) return void 0;
2189
+ const alts = schema["anyOf"] ?? schema["oneOf"];
2190
+ if (Array.isArray(alts)) {
2191
+ const errors = alts.map((alt) => shapeError(value, alt, path, optional));
2192
+ return errors.some((e) => e === void 0) ? void 0 : errors[0];
2193
+ }
2194
+ const type = schema["type"];
2195
+ if (type !== void 0) {
2196
+ const types = Array.isArray(type) ? type : [type];
2197
+ if (!types.some((t) => isType(t, value))) return `${path} must be ${types.length === 1 ? `${/^[aeiou]/.test(String(types[0])) ? "an" : "a"} ${types[0]}` : `one of ${types.join(", ")}`} (got ${typeName(value)}).`;
2198
+ }
2199
+ if (Array.isArray(value) && isObj(schema["items"])) {
2200
+ for (let i = 0; i < Math.min(value.length, SHAPE_ITEMS); i++) {
2201
+ const e = shapeError(value[i], schema["items"], `${path}[${i}]`);
2202
+ if (e) return e;
2203
+ }
2204
+ } else if (isObj(value) && isObj(schema["properties"])) {
2205
+ const required = Array.isArray(schema["required"]) ? schema["required"] : [];
2206
+ for (const [key, sub] of Object.entries(schema["properties"])) {
2207
+ if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
2208
+ const e = shapeError(value[key], sub, `${path}.${key}`, !required.includes(key));
2209
+ if (e) return e;
2210
+ }
2211
+ }
2212
+ return void 0;
2213
+ }
2073
2214
  var failed = (v) => isObj(v) && "ok" in v && v.ok === false;
2074
2215
  var CardRegistry = class {
2075
2216
  kinds = /* @__PURE__ */ new Map();
@@ -3192,35 +3333,44 @@ var confirmCard = {
3192
3333
  return ok;
3193
3334
  }
3194
3335
  };
3336
+ var typed = (def) => ({
3337
+ ...def,
3338
+ validate(spec) {
3339
+ const own = def.validate(spec);
3340
+ if (!own.ok) return own;
3341
+ const wrong = shapeError(spec, def.schema, def.kind);
3342
+ return wrong ? { ok: false, error: wrong, expected: "the types in the card's schema" } : own;
3343
+ }
3344
+ });
3195
3345
  var BUILTIN_CARDS = [
3196
3346
  // structured data
3197
- tableCard,
3198
- statsCard,
3199
- comparisonCard,
3200
- keyValueCard,
3201
- treeCard,
3347
+ /* @__PURE__ */ typed(tableCard),
3348
+ /* @__PURE__ */ typed(statsCard),
3349
+ /* @__PURE__ */ typed(comparisonCard),
3350
+ /* @__PURE__ */ typed(keyValueCard),
3351
+ /* @__PURE__ */ typed(treeCard),
3202
3352
  // quantitative shape
3203
- chartCard,
3204
- funnelCard,
3205
- gaugeCard,
3353
+ /* @__PURE__ */ typed(chartCard),
3354
+ /* @__PURE__ */ typed(funnelCard),
3355
+ /* @__PURE__ */ typed(gaugeCard),
3206
3356
  // sequence and state
3207
- timelineCard,
3208
- progressCard,
3209
- checklistCard,
3357
+ /* @__PURE__ */ typed(timelineCard),
3358
+ /* @__PURE__ */ typed(progressCard),
3359
+ /* @__PURE__ */ typed(checklistCard),
3210
3360
  // prose and evidence
3211
- markdownCard,
3212
- documentCard,
3213
- calloutCard,
3214
- citationsCard,
3215
- codeCard,
3216
- diffCard,
3217
- mediaCard,
3361
+ /* @__PURE__ */ typed(markdownCard),
3362
+ /* @__PURE__ */ typed(documentCard),
3363
+ /* @__PURE__ */ typed(calloutCard),
3364
+ /* @__PURE__ */ typed(citationsCard),
3365
+ /* @__PURE__ */ typed(codeCard),
3366
+ /* @__PURE__ */ typed(diffCard),
3367
+ /* @__PURE__ */ typed(mediaCard),
3218
3368
  // interactive — these ask the user and pause the run
3219
- choiceCard,
3220
- formCard,
3221
- confirmCard,
3222
- editReviewCard,
3223
- emailCard
3369
+ /* @__PURE__ */ typed(choiceCard),
3370
+ /* @__PURE__ */ typed(formCard),
3371
+ /* @__PURE__ */ typed(confirmCard),
3372
+ /* @__PURE__ */ typed(editReviewCard),
3373
+ /* @__PURE__ */ typed(emailCard)
3224
3374
  ];
3225
3375
 
3226
3376
  // src/surfaces/types.ts
@@ -3418,12 +3568,12 @@ function checkSchema(schema, value, path = "", opts = {}) {
3418
3568
  }
3419
3569
  }
3420
3570
  if (typeOf(v) === "object") {
3421
- const record = v;
3571
+ const record2 = v;
3422
3572
  for (const key of s.required ?? []) {
3423
- if (record[key] === void 0) out.push({ path: `${at}/${key}`, message: `${at ? `${at}/` : ""}${key} is required.` });
3573
+ if (record2[key] === void 0) out.push({ path: `${at}/${key}`, message: `${at ? `${at}/` : ""}${key} is required.` });
3424
3574
  }
3425
3575
  const properties = s.properties ?? {};
3426
- for (const [key, item] of Object.entries(record)) {
3576
+ for (const [key, item] of Object.entries(record2)) {
3427
3577
  const propSchema = properties[key];
3428
3578
  if (propSchema) walk(propSchema, item, `${at}/${key}`);
3429
3579
  else if (s.additionalProperties === false) {
@@ -3660,7 +3810,7 @@ var props = (properties, required = []) => ({
3660
3810
  required,
3661
3811
  additionalProperties: false
3662
3812
  });
3663
- var text2 = (description) => ({ type: "string", ...description ? { description } : {} });
3813
+ var text3 = (description) => ({ type: "string", ...description ? { description } : {} });
3664
3814
  var SURFACE_PRIMITIVES = [
3665
3815
  {
3666
3816
  name: "Stack",
@@ -3699,8 +3849,8 @@ var SURFACE_PRIMITIVES = [
3699
3849
  summary: "A titled group of children.",
3700
3850
  props: props(
3701
3851
  {
3702
- title: text2(),
3703
- description: text2(),
3852
+ title: text3(),
3853
+ description: text3(),
3704
3854
  tone: { type: "string", enum: TONES },
3705
3855
  children: childIds
3706
3856
  },
@@ -3714,7 +3864,7 @@ var SURFACE_PRIMITIVES = [
3714
3864
  summary: "Switch between named panels. Keyboard accessible.",
3715
3865
  props: props(
3716
3866
  {
3717
- label: text2("Names the tab list for screen readers."),
3867
+ label: text3("Names the tab list for screen readers."),
3718
3868
  value: { ...boundValue, description: "Optional binding for the selected tab id." },
3719
3869
  tabs: fixed({
3720
3870
  type: "array",
@@ -3740,7 +3890,7 @@ var SURFACE_PRIMITIVES = [
3740
3890
  {
3741
3891
  items: { type: "array", description: "A $path or $query that yields an array." },
3742
3892
  child: childId("The template component rendered once per row."),
3743
- emptyText: text2("Shown when there are no rows."),
3893
+ emptyText: text3("Shown when there are no rows."),
3744
3894
  gap: { type: "string", enum: GAPS }
3745
3895
  },
3746
3896
  ["items", "child"]
@@ -3768,12 +3918,12 @@ var SURFACE_PRIMITIVES = [
3768
3918
  summary: "One headline number with a label and optional change.",
3769
3919
  props: props(
3770
3920
  {
3771
- label: text2(),
3921
+ label: text3(),
3772
3922
  value: { type: ["string", "number", "null"] },
3773
3923
  format: { type: "string", enum: FORMATS2 },
3774
3924
  delta: { type: "number" },
3775
3925
  deltaFormat: { type: "string", enum: FORMATS2 },
3776
- hint: text2(),
3926
+ hint: text3(),
3777
3927
  tone: { type: "string", enum: TONES }
3778
3928
  },
3779
3929
  ["label", "value"]
@@ -3789,13 +3939,13 @@ var SURFACE_PRIMITIVES = [
3789
3939
  name: "Image",
3790
3940
  category: "display",
3791
3941
  summary: "An http(s) image with required alt text.",
3792
- props: props({ src: text2(), alt: text2(), caption: text2() }, ["src", "alt"])
3942
+ props: props({ src: text3(), alt: text3(), caption: text3() }, ["src", "alt"])
3793
3943
  },
3794
3944
  {
3795
3945
  name: "Link",
3796
3946
  category: "display",
3797
3947
  summary: "An http(s) link that opens in a new tab.",
3798
- props: props({ text: text2(), href: text2() }, ["text", "href"])
3948
+ props: props({ text: text3(), href: text3() }, ["text", "href"])
3799
3949
  },
3800
3950
  {
3801
3951
  name: "Field",
@@ -3803,11 +3953,11 @@ var SURFACE_PRIMITIVES = [
3803
3953
  summary: "Text, number, date or multi-line input bound to the data model.",
3804
3954
  props: props(
3805
3955
  {
3806
- label: text2(),
3956
+ label: text3(),
3807
3957
  value: boundValue,
3808
3958
  type: { type: "string", enum: ["text", "number", "date", "textarea"] },
3809
- placeholder: text2(),
3810
- helper: text2(),
3959
+ placeholder: text3(),
3960
+ helper: text3(),
3811
3961
  min: { type: "number" },
3812
3962
  max: { type: "number" },
3813
3963
  step: { type: "number" }
@@ -3821,7 +3971,7 @@ var SURFACE_PRIMITIVES = [
3821
3971
  summary: "Choose one option; writes its value to the data model.",
3822
3972
  props: props(
3823
3973
  {
3824
- label: text2(),
3974
+ label: text3(),
3825
3975
  value: boundValue,
3826
3976
  options: {
3827
3977
  type: "array",
@@ -3832,7 +3982,7 @@ var SURFACE_PRIMITIVES = [
3832
3982
  additionalProperties: false
3833
3983
  }
3834
3984
  },
3835
- helper: text2()
3985
+ helper: text3()
3836
3986
  },
3837
3987
  ["label", "value", "options"]
3838
3988
  )
@@ -3841,7 +3991,7 @@ var SURFACE_PRIMITIVES = [
3841
3991
  name: "Toggle",
3842
3992
  category: "input",
3843
3993
  summary: "An on/off switch bound to a boolean.",
3844
- props: props({ label: text2(), value: boundValue, helper: text2() }, ["label", "value"])
3994
+ props: props({ label: text3(), value: boundValue, helper: text3() }, ["label", "value"])
3845
3995
  },
3846
3996
  {
3847
3997
  name: "Slider",
@@ -3849,7 +3999,7 @@ var SURFACE_PRIMITIVES = [
3849
3999
  summary: "Pick a number in a range.",
3850
4000
  props: props(
3851
4001
  {
3852
- label: text2(),
4002
+ label: text3(),
3853
4003
  value: boundValue,
3854
4004
  min: { type: "number" },
3855
4005
  max: { type: "number" },
@@ -3865,7 +4015,7 @@ var SURFACE_PRIMITIVES = [
3865
4015
  summary: "Runs one action when pressed: set local state, call an allowed tool, or send the agent an event.",
3866
4016
  props: props(
3867
4017
  {
3868
- label: text2(),
4018
+ label: text3(),
3869
4019
  action: ACTION_SCHEMA,
3870
4020
  variant: { type: "string", enum: ["primary", "secondary", "ghost", "danger"] },
3871
4021
  disabledWhen: CONDITION_SCHEMA
@@ -3980,40 +4130,40 @@ function validateSurfaceAction(action, componentId, ctx) {
3980
4130
  const extra = Object.keys(action).filter((k) => !allowed.includes(k));
3981
4131
  return extra.length ? bad(`action has no "${extra[0]}". Actions cannot carry code or URLs.`, `Allowed keys: ${allowed.join(", ")}.`) : [];
3982
4132
  };
3983
- const typed = action;
3984
- switch (typed.type) {
4133
+ const typed2 = action;
4134
+ switch (typed2.type) {
3985
4135
  case "set": {
3986
4136
  const extra = onlyKeys(["type", "updates"]);
3987
4137
  if (extra.length) return extra;
3988
- if (!Array.isArray(typed.updates) || !typed.updates.length || typed.updates.length > SURFACE_LIMITS.actionUpdates) {
4138
+ if (!Array.isArray(typed2.updates) || !typed2.updates.length || typed2.updates.length > SURFACE_LIMITS.actionUpdates) {
3989
4139
  return bad(`set needs 1 to ${SURFACE_LIMITS.actionUpdates} updates.`, 'Send "updates": [{ "path": "/a", "value": 1 }].');
3990
4140
  }
3991
- for (const update of typed.updates) {
4141
+ for (const update of typed2.updates) {
3992
4142
  if (!isObject(update) || !parsePointer(update.path)) return bad("Each update needs a JSON Pointer `path`.", 'Send { "path": "/a", "value": 1 }.');
3993
4143
  }
3994
- return bindingIssues(typed.updates, componentId);
4144
+ return bindingIssues(typed2.updates, componentId);
3995
4145
  }
3996
4146
  case "tool": {
3997
4147
  const extra = onlyKeys(["type", "tool", "args", "resultPath"]);
3998
4148
  if (extra.length) return extra;
3999
- if (typeof typed.tool !== "string" || !typed.tool) return bad("A tool action needs a `tool` name.", 'Send { "type": "tool", "tool": "name" }.');
4000
- if (typed.args !== void 0 && !isObject(typed.args)) return bad("Tool `args` must be an object.", "Send args as an object of literals or bindings.");
4001
- if (typed.resultPath !== void 0 && !parsePointer(typed.resultPath)) return bad("`resultPath` must be a JSON Pointer.", 'Send "resultPath": "/result".');
4002
- if (ctx.actionTools && !ctx.actionTools.includes(typed.tool)) {
4149
+ if (typeof typed2.tool !== "string" || !typed2.tool) return bad("A tool action needs a `tool` name.", 'Send { "type": "tool", "tool": "name" }.');
4150
+ if (typed2.args !== void 0 && !isObject(typed2.args)) return bad("Tool `args` must be an object.", "Send args as an object of literals or bindings.");
4151
+ if (typed2.resultPath !== void 0 && !parsePointer(typed2.resultPath)) return bad("`resultPath` must be a JSON Pointer.", 'Send "resultPath": "/result".');
4152
+ if (ctx.actionTools && !ctx.actionTools.includes(typed2.tool)) {
4003
4153
  return bad(
4004
- `Tool "${typed.tool}" is not available to this surface.`,
4154
+ `Tool "${typed2.tool}" is not available to this surface.`,
4005
4155
  ctx.actionTools.length ? `Available: ${ctx.actionTools.slice(0, 24).join(", ")}.` : 'No tools are available; use an "event" action instead.',
4006
4156
  "tool-not-allowed"
4007
4157
  );
4008
4158
  }
4009
- return bindingIssues(typed.args, componentId);
4159
+ return bindingIssues(typed2.args, componentId);
4010
4160
  }
4011
4161
  case "event": {
4012
4162
  const extra = onlyKeys(["type", "name", "context"]);
4013
4163
  if (extra.length) return extra;
4014
- if (!isSurfaceId(typed.name)) return bad("An event needs a short `name`.", 'Send { "type": "event", "name": "apply" }.');
4015
- if (typed.context !== void 0 && !isObject(typed.context)) return bad("Event `context` must be an object.", "Send context as an object of literals or bindings.");
4016
- return bindingIssues(typed.context, componentId);
4164
+ if (!isSurfaceId(typed2.name)) return bad("An event needs a short `name`.", 'Send { "type": "event", "name": "apply" }.');
4165
+ if (typed2.context !== void 0 && !isObject(typed2.context)) return bad("Event `context` must be an object.", "Send context as an object of literals or bindings.");
4166
+ return bindingIssues(typed2.context, componentId);
4017
4167
  }
4018
4168
  default:
4019
4169
  return bad(`Unknown action type ${JSON.stringify(action.type)}.`, closed);
@@ -4675,11 +4825,11 @@ function createSurfaceContextSource() {
4675
4825
  run({ messages }) {
4676
4826
  const live = Object.values(foldSurfaces(messages)).filter((s) => !s.deleted && !s.expired);
4677
4827
  if (!live.length) return {};
4678
- const text3 = [
4828
+ const text4 = [
4679
4829
  "Surfaces on screen. Call readSurface for their current state before relying on it:",
4680
4830
  ...live.map((s) => `- ${s.surfaceId}${s.title ? ` (${s.title})` : ""}, revision ${s.revision}`)
4681
4831
  ].join("\n");
4682
- return { layers: [{ id: "surfaces", kind: "custom", text: text3, tokens: estimateTokens(text3), priority: 400 }] };
4832
+ return { layers: [{ id: "surfaces", kind: "custom", text: text4, tokens: estimateTokens(text4), priority: 400 }] };
4683
4833
  }
4684
4834
  };
4685
4835
  }
@@ -4718,12 +4868,12 @@ var EventChannel = class {
4718
4868
  var MAX_FIELDS = 6;
4719
4869
  var MAX_VALUE_CHARS = 160;
4720
4870
  var MAX_DESCRIPTION_CHARS = 240;
4721
- var clip = (text3, max) => text3.length > max ? `${text3.slice(0, max - 1)}\u2026` : text3;
4871
+ var clip = (text4, max) => text4.length > max ? `${text4.slice(0, max - 1)}\u2026` : text4;
4722
4872
  function humanizeFieldName(key) {
4723
4873
  const words = key.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[\s_\-.]+/).filter(Boolean).map((word) => word.toLowerCase());
4724
4874
  if (words.length > 1 && (words[words.length - 1] === "id" || words[words.length - 1] === "ids")) words.pop();
4725
- const text3 = words.join(" ");
4726
- return text3 ? text3.charAt(0).toUpperCase() + text3.slice(1) : key;
4875
+ const text4 = words.join(" ");
4876
+ return text4 ? text4.charAt(0).toUpperCase() + text4.slice(1) : key;
4727
4877
  }
4728
4878
  function plainValue(value) {
4729
4879
  if (typeof value === "string") return value.trim() ? clip(value.trim(), MAX_VALUE_CHARS) : void 0;
@@ -4737,9 +4887,9 @@ function plainValue(value) {
4737
4887
  return void 0;
4738
4888
  }
4739
4889
  function firstSentence(description) {
4740
- const text3 = description.trim().replace(/\s+/g, " ");
4741
- const end = text3.search(/[.!?](\s|$)/);
4742
- return clip(end === -1 ? text3 : text3.slice(0, end + 1), MAX_DESCRIPTION_CHARS);
4890
+ const text4 = description.trim().replace(/\s+/g, " ");
4891
+ const end = text4.search(/[.!?](\s|$)/);
4892
+ return clip(end === -1 ? text4 : text4.slice(0, end + 1), MAX_DESCRIPTION_CHARS);
4743
4893
  }
4744
4894
  function fieldsOf(input) {
4745
4895
  if (input === void 0 || input === null) return [];
@@ -4876,6 +5026,16 @@ async function executeToolCall(call, opts) {
4876
5026
  card = { ...embedded, callId: call.callId };
4877
5027
  opts.onCard?.(card);
4878
5028
  }
5029
+ const unsendable = jsonProblem(output);
5030
+ if (unsendable) {
5031
+ return {
5032
+ callId: call.callId,
5033
+ name: call.name,
5034
+ output: { error: `Tool "${call.name}" returned a value that cannot be sent as JSON (${unsendable}).` },
5035
+ failure: "execution-error",
5036
+ ms: Date.now() - started
5037
+ };
5038
+ }
4879
5039
  return {
4880
5040
  callId: call.callId,
4881
5041
  name: call.name,
@@ -4898,6 +5058,15 @@ async function executeToolCall(call, opts) {
4898
5058
  settled = true;
4899
5059
  }
4900
5060
  }
5061
+ function jsonProblem(value) {
5062
+ if (value === void 0 || typeof value === "string") return void 0;
5063
+ try {
5064
+ if (JSON.stringify(value) === void 0) return `a ${typeof value} has no JSON form`;
5065
+ return void 0;
5066
+ } catch (e) {
5067
+ return (e instanceof Error ? e.message : String(e)).slice(0, 120);
5068
+ }
5069
+ }
4901
5070
  var NOT_ABOUT_INPUT = /* @__PURE__ */ new Set(["denied", "timeout", "not-found"]);
4902
5071
  var MAX_DESCRIBED = 200;
4903
5072
  function explainMissingInput(tool, input, output, failure) {
@@ -4966,13 +5135,13 @@ function combineMeteringSources(sources) {
4966
5135
  const unique = new Set(sources);
4967
5136
  return unique.size === 1 ? sources[0] : "mixed";
4968
5137
  }
4969
- async function deliverMetering(sink, record) {
5138
+ async function deliverMetering(sink, record2) {
4970
5139
  if (!sink) return;
4971
5140
  try {
4972
- await sink.record(record);
5141
+ await sink.record(record2);
4973
5142
  } catch (error) {
4974
5143
  try {
4975
- await sink.onError?.(error, record);
5144
+ await sink.onError?.(error, record2);
4976
5145
  } catch {
4977
5146
  }
4978
5147
  }
@@ -5031,7 +5200,7 @@ async function* runSurfaceToolAction(config) {
5031
5200
  const outcome2 = await running;
5032
5201
  const finishedAt = Date.now();
5033
5202
  const finishReason = outcome2.failure === "denied" && config.signal?.aborted ? "cancelled" : "stop";
5034
- const record = {
5203
+ const record2 = {
5035
5204
  scope: "run",
5036
5205
  id: `${runId}:run`,
5037
5206
  runId,
@@ -5048,8 +5217,8 @@ async function* runSurfaceToolAction(config) {
5048
5217
  finishReason,
5049
5218
  metadata: { ...config.meteringMetadata, trigger: "surface-action", surfaceId: config.surfaceId, componentId: config.componentId, tool: config.tool.name }
5050
5219
  };
5051
- await deliverMetering(config.meter, record);
5052
- yield { type: "metering", record };
5220
+ await deliverMetering(config.meter, record2);
5221
+ yield { type: "metering", record: record2 };
5053
5222
  yield { type: "run-finish", runId, finishReason, usage: {}, steps: 0 };
5054
5223
  }
5055
5224
 
@@ -5089,7 +5258,7 @@ function toComponents(component, rename) {
5089
5258
  case "Stack":
5090
5259
  return [{ ...base, component: rest["direction"] === "horizontal" ? "Row" : "Column", children, ...rest["justify"] ? { justify: rest["justify"] === "between" ? "spaceBetween" : rest["justify"] } : {}, ...rest["align"] ? { align: rest["align"] } : {} }];
5091
5260
  case "Text":
5092
- return [{ ...base, component: "Text", text: props2["text"], ...typeof rest["variant"] === "string" ? { variant: TEXT_VARIANTS[rest["variant"]] } : {} }];
5261
+ return [{ ...base, component: "Text", text: props2["text"], ...typeof rest["variant"] === "string" ? { variant: Object.hasOwn(TEXT_VARIANTS, rest["variant"]) ? TEXT_VARIANTS[rest["variant"]] : void 0 } : {} }];
5093
5262
  case "Image":
5094
5263
  return [{ ...base, component: "Image", url: props2["src"] }];
5095
5264
  case "Divider":
@@ -5294,9 +5463,9 @@ function setOwn(target, key, value) {
5294
5463
  if (key === "__proto__") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
5295
5464
  else target[key] = value;
5296
5465
  }
5297
- function visible(text3) {
5298
- const last = text3.charCodeAt(text3.length - 1);
5299
- return last >= 55296 && last <= 56319 ? text3.slice(0, -1) : text3;
5466
+ function visible(text4) {
5467
+ const last = text4.charCodeAt(text4.length - 1);
5468
+ return last >= 55296 && last <= 56319 ? text4.slice(0, -1) : text4;
5300
5469
  }
5301
5470
  var PartialJsonParser = class {
5302
5471
  stack = [];
@@ -5525,9 +5694,9 @@ var PartialJsonParser = class {
5525
5694
  return i;
5526
5695
  }
5527
5696
  };
5528
- function parsePartialJson(text3) {
5697
+ function parsePartialJson(text4) {
5529
5698
  const parser = new PartialJsonParser();
5530
- parser.push(text3);
5699
+ parser.push(text4);
5531
5700
  return { value: parser.snapshot(), complete: parser.complete };
5532
5701
  }
5533
5702
 
@@ -5855,8 +6024,8 @@ function reduceRunEvent(state, event) {
5855
6024
  return state;
5856
6025
  }
5857
6026
  }
5858
- function without(record, key) {
5859
- const next = { ...record };
6027
+ function without(record2, key) {
6028
+ const next = { ...record2 };
5860
6029
  delete next[key];
5861
6030
  return next;
5862
6031
  }
@@ -5920,6 +6089,9 @@ async function* runAgent(messages, config) {
5920
6089
  const meteringSources = [];
5921
6090
  const reportedModels = /* @__PURE__ */ new Set();
5922
6091
  try {
6092
+ if (!Number.isFinite(maxSteps) || maxSteps < 1) {
6093
+ throw new AgentError("invalid-request", `maxSteps must be a number of at least 1, not ${String(config.maxSteps)}.`, { provider: config.provider.id });
6094
+ }
5923
6095
  const baseTools = config.tools.resolve(config.toolResolution);
5924
6096
  const context = await config.contextBuilder.build({
5925
6097
  messages: history,
@@ -6053,7 +6225,7 @@ async function* runAgent(messages, config) {
6053
6225
  yield { type: "usage", usage: stepUsage };
6054
6226
  }
6055
6227
  const finishedAt3 = Date.now();
6056
- const record3 = {
6228
+ const record4 = {
6057
6229
  scope: "step",
6058
6230
  id: `${runId}:step:${step}`,
6059
6231
  runId,
@@ -6072,8 +6244,8 @@ async function* runAgent(messages, config) {
6072
6244
  ...config.meteringMetadata ? { metadata: config.meteringMetadata } : {},
6073
6245
  error: { kind: error.kind, message: error.message }
6074
6246
  };
6075
- await deliverMetering(config.meter, record3);
6076
- yield { type: "metering", record: record3 };
6247
+ await deliverMetering(config.meter, record4);
6248
+ yield { type: "metering", record: record4 };
6077
6249
  throw error;
6078
6250
  }
6079
6251
  previousResponseId = responseId;
@@ -6085,7 +6257,7 @@ async function* runAgent(messages, config) {
6085
6257
  meteringSources.push(source);
6086
6258
  if (reportedModel) reportedModels.add(reportedModel);
6087
6259
  const finishedAt2 = Date.now();
6088
- const record2 = {
6260
+ const record3 = {
6089
6261
  scope: "step",
6090
6262
  id: `${runId}:step:${step}`,
6091
6263
  runId,
@@ -6104,8 +6276,8 @@ async function* runAgent(messages, config) {
6104
6276
  finishReason: stepFinish,
6105
6277
  ...config.meteringMetadata ? { metadata: config.meteringMetadata } : {}
6106
6278
  };
6107
- await deliverMetering(config.meter, record2);
6108
- yield { type: "metering", record: record2 };
6279
+ await deliverMetering(config.meter, record3);
6280
+ yield { type: "metering", record: record3 };
6109
6281
  yield { type: "step-finish", step, finishReason: stepFinish, ...stepUsage ? { usage: stepUsage } : {} };
6110
6282
  const assistant = assistantMessage(parts);
6111
6283
  working.push(assistant);
@@ -6199,7 +6371,7 @@ _(Reached the ${maxSteps}-step limit while still working \u2014 this may be inco
6199
6371
  };
6200
6372
  }
6201
6373
  const finishedAt = Date.now();
6202
- const record = {
6374
+ const record2 = {
6203
6375
  scope: "run",
6204
6376
  id: `${runId}:run`,
6205
6377
  runId,
@@ -6217,15 +6389,15 @@ _(Reached the ${maxSteps}-step limit while still working \u2014 this may be inco
6217
6389
  ...reportedModels.size ? { reportedModels: [...reportedModels] } : {},
6218
6390
  ...config.meteringMetadata ? { metadata: config.meteringMetadata } : {}
6219
6391
  };
6220
- await deliverMetering(config.meter, record);
6221
- yield { type: "metering", record };
6392
+ await deliverMetering(config.meter, record2);
6393
+ yield { type: "metering", record: record2 };
6222
6394
  yield { type: "run-finish", runId, finishReason, usage: totalUsage, steps: attemptedSteps };
6223
6395
  } catch (e) {
6224
6396
  const error = toAgentError(e, config.provider.id);
6225
6397
  yield { type: "error", error, recoverable: false };
6226
6398
  const terminalReason = error.kind === "cancelled" ? "cancelled" : "error";
6227
6399
  const finishedAt = Date.now();
6228
- const record = {
6400
+ const record2 = {
6229
6401
  scope: "run",
6230
6402
  id: `${runId}:run`,
6231
6403
  runId,
@@ -6244,8 +6416,8 @@ _(Reached the ${maxSteps}-step limit while still working \u2014 this may be inco
6244
6416
  ...config.meteringMetadata ? { metadata: config.meteringMetadata } : {},
6245
6417
  error: { kind: error.kind, message: error.message }
6246
6418
  };
6247
- await deliverMetering(config.meter, record);
6248
- yield { type: "metering", record };
6419
+ await deliverMetering(config.meter, record2);
6420
+ yield { type: "metering", record: record2 };
6249
6421
  yield { type: "run-finish", runId, finishReason: terminalReason, usage: totalUsage, steps: attemptedSteps };
6250
6422
  }
6251
6423
  }
@@ -6352,9 +6524,16 @@ function createLocalFileStore(key = "superchat:files") {
6352
6524
  try {
6353
6525
  const raw = globalThis.localStorage?.getItem(key) ?? null;
6354
6526
  const parsed = raw ? JSON.parse(raw) : {};
6355
- return typeof parsed === "object" && parsed !== null ? parsed : {};
6527
+ const all = /* @__PURE__ */ Object.create(null);
6528
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6529
+ for (const [id, file2] of Object.entries(parsed)) {
6530
+ const f = file2;
6531
+ if (f && typeof f === "object" && f.ref && typeof f.ref.id === "string" && typeof f.createdAt === "number") all[id] = f;
6532
+ }
6533
+ }
6534
+ return all;
6356
6535
  } catch {
6357
- return {};
6536
+ return /* @__PURE__ */ Object.create(null);
6358
6537
  }
6359
6538
  };
6360
6539
  const write = (all) => {
@@ -6385,11 +6564,57 @@ function createLocalFileStore(key = "superchat:files") {
6385
6564
 
6386
6565
  // src/runtime/threads.ts
6387
6566
  var THREAD_SCHEMA_VERSION = 2;
6567
+ function isObject3(v) {
6568
+ return typeof v === "object" && v !== null && !Array.isArray(v);
6569
+ }
6570
+ function mediaSourceReadable(source) {
6571
+ if (!isObject3(source)) return false;
6572
+ if (source.kind === "url") return typeof source.url === "string";
6573
+ if (source.kind === "base64") return typeof source.data === "string";
6574
+ if (source.kind === "providerFile") return typeof source.id === "string" && typeof source.provider === "string";
6575
+ return false;
6576
+ }
6577
+ function partReadable(p) {
6578
+ if (!isObject3(p) || typeof p.type !== "string") return false;
6579
+ switch (p.type) {
6580
+ case "text":
6581
+ case "reasoning":
6582
+ return typeof p.text === "string";
6583
+ case "image":
6584
+ return mediaSourceReadable(p.source) && (p.mediaType === void 0 || typeof p.mediaType === "string");
6585
+ case "file":
6586
+ return mediaSourceReadable(p.source) && typeof p.mediaType === "string" && (p.filename === void 0 || typeof p.filename === "string");
6587
+ case "audio":
6588
+ return mediaSourceReadable(p.source) && typeof p.mediaType === "string" && (p.transcript === void 0 || typeof p.transcript === "string");
6589
+ case "tool-call":
6590
+ case "tool-result":
6591
+ return typeof p.callId === "string" && typeof p.name === "string";
6592
+ case "artifact":
6593
+ return typeof p.id === "string" && typeof p.kind === "string";
6594
+ default:
6595
+ return true;
6596
+ }
6597
+ }
6598
+ function wellFormed(messages) {
6599
+ const out = [];
6600
+ for (const raw of messages) {
6601
+ const m = raw;
6602
+ if (!m || typeof m !== "object" || typeof m.id !== "string" || typeof m.role !== "string" || !Array.isArray(m.parts)) continue;
6603
+ const parts = m.parts.filter(partReadable);
6604
+ const parentOk = m.parentId === void 0 || m.parentId === null || typeof m.parentId === "string";
6605
+ out.push(parts.length === m.parts.length && parentOk ? m : { ...m, parts, ...parentOk ? {} : { parentId: null } });
6606
+ }
6607
+ return out;
6608
+ }
6388
6609
  function migrate(parsed) {
6389
- if (!parsed || !Array.isArray(parsed.messages) || !parsed.meta) return void 0;
6390
- if (parsed.version === THREAD_SCHEMA_VERSION) return parsed;
6610
+ if (!parsed || !Array.isArray(parsed.messages) || !parsed.meta || typeof parsed.meta.id !== "string") return void 0;
6611
+ if (parsed.version === THREAD_SCHEMA_VERSION) {
6612
+ const messages = wellFormed(parsed.messages);
6613
+ const headKnown = typeof parsed.headId === "string" && messages.some((m) => m.id === parsed.headId);
6614
+ return { ...parsed, messages, headId: parsed.headId === null ? null : headKnown ? parsed.headId : messages.at(-1)?.id ?? null };
6615
+ }
6391
6616
  if (parsed.version === 1) {
6392
- const messages = linkLinear(parsed.messages);
6617
+ const messages = linkLinear(wellFormed(parsed.messages));
6393
6618
  return {
6394
6619
  version: THREAD_SCHEMA_VERSION,
6395
6620
  meta: parsed.meta,
@@ -6586,6 +6811,8 @@ function expireArtifacts(messages) {
6586
6811
 
6587
6812
  // src/memory/memory.ts
6588
6813
  var DEFAULT_STORE_CAP = 500;
6814
+ var MAX_KEY_CHARS = 100;
6815
+ var MAX_VALUE_CHARS2 = 2e3;
6589
6816
  function byRecency2(a, b) {
6590
6817
  return b.updatedAt - a.updatedAt;
6591
6818
  }
@@ -6614,9 +6841,9 @@ function createLocalMemoryStore(storageKey = "superchat:memory", opts = {}) {
6614
6841
  try {
6615
6842
  const raw = globalThis.localStorage?.getItem(storageKey) ?? null;
6616
6843
  const parsed = raw ? JSON.parse(raw) : {};
6617
- return typeof parsed === "object" && parsed !== null ? parsed : {};
6844
+ return typeof parsed === "object" && parsed !== null ? Object.assign(/* @__PURE__ */ Object.create(null), parsed) : /* @__PURE__ */ Object.create(null);
6618
6845
  } catch {
6619
- return {};
6846
+ return /* @__PURE__ */ Object.create(null);
6620
6847
  }
6621
6848
  };
6622
6849
  const write = (all) => {
@@ -6646,15 +6873,20 @@ function createLocalMemoryStore(storageKey = "superchat:memory", opts = {}) {
6646
6873
  }
6647
6874
  };
6648
6875
  }
6876
+ var oneLine2 = (text4) => String(text4).replace(/\s*[\r\n]+\s*/g, " ");
6877
+ var clip2 = (text4) => {
6878
+ const value = String(text4);
6879
+ return value.length > MAX_VALUE_CHARS2 ? `${value.slice(0, MAX_VALUE_CHARS2)}\u2026` : value;
6880
+ };
6649
6881
  function createMemorySource(store, opts = {}) {
6650
6882
  return {
6651
6883
  id: opts.id ?? "memory",
6652
6884
  async run({ vars }) {
6653
6885
  const entries = (await store.list(vars)).slice(0, opts.maxEntries ?? 50);
6654
6886
  if (!entries.length) return {};
6655
- const text3 = [
6887
+ const text4 = [
6656
6888
  "Things you remember about this user, from earlier conversations:",
6657
- ...entries.map((e) => `- ${e.key}: ${e.value}`),
6889
+ ...entries.map((e) => `- ${oneLine2(e.key)}: ${oneLine2(clip2(e.value))}`),
6658
6890
  "Apply them without re-asking. Update them with the `remember` tool when they change."
6659
6891
  ].join("\n");
6660
6892
  return {
@@ -6662,8 +6894,8 @@ function createMemorySource(store, opts = {}) {
6662
6894
  {
6663
6895
  id: opts.id ?? "memory",
6664
6896
  kind: "memory",
6665
- text: text3,
6666
- tokens: estimateTokens(text3),
6897
+ text: text4,
6898
+ tokens: estimateTokens(text4),
6667
6899
  priority: opts.priority ?? 500
6668
6900
  }
6669
6901
  ]
@@ -6687,7 +6919,13 @@ function createRememberTool(store) {
6687
6919
  },
6688
6920
  async execute(input, ctx) {
6689
6921
  const { key, value } = input ?? {};
6690
- if (!key) return { output: { ok: false, error: "`key` is required." }, failure: "invalid-input" };
6922
+ const invalid = (error) => ({ output: { ok: false, error }, failure: "invalid-input" });
6923
+ if (typeof key !== "string" || !key.trim()) return invalid("`key` is required.");
6924
+ if (key.length > MAX_KEY_CHARS) return invalid(`\`key\` is too long (${key.length} characters, at most ${MAX_KEY_CHARS}). Use a short slug.`);
6925
+ if (value != null && typeof value !== "string") return invalid("`value` must be a string, or null to forget the key.");
6926
+ if (typeof value === "string" && value.length > MAX_VALUE_CHARS2) {
6927
+ return invalid(`\`value\` is too long (${value.length} characters, at most ${MAX_VALUE_CHARS2}). Remember the fact in a sentence or two.`);
6928
+ }
6691
6929
  if (value == null || value === "") {
6692
6930
  await store.remove(key, ctx.vars);
6693
6931
  return { output: { ok: true, forgot: key } };
@@ -6699,17 +6937,36 @@ function createRememberTool(store) {
6699
6937
  }
6700
6938
 
6701
6939
  // src/retrieval/retrieval.ts
6940
+ function readable(hits) {
6941
+ if (!Array.isArray(hits)) return [];
6942
+ const out = [];
6943
+ for (const h of hits) {
6944
+ if (typeof h !== "object" || h === null) continue;
6945
+ const c = h;
6946
+ if (typeof c.text !== "string" || !c.text.trim()) continue;
6947
+ const str2 = (v) => typeof v === "string" && v ? v : void 0;
6948
+ out.push({
6949
+ id: str2(c.id) ?? (typeof c.id === "number" ? String(c.id) : `hit-${out.length + 1}`),
6950
+ text: c.text,
6951
+ ...str2(c.source) ? { source: str2(c.source) } : {},
6952
+ ...str2(c.title) ? { title: str2(c.title) } : {},
6953
+ ...str2(c.uri) ? { uri: str2(c.uri) } : {},
6954
+ ...typeof c.score === "number" && Number.isFinite(c.score) ? { score: c.score } : {}
6955
+ });
6956
+ }
6957
+ return out;
6958
+ }
6702
6959
  function createRetrievalSource(retriever, opts = {}) {
6703
6960
  return {
6704
6961
  id: opts.id ?? "retrieval",
6705
6962
  async run({ query, vars, signal }) {
6706
6963
  if (query.trim().length < (opts.minQueryLength ?? 8)) return {};
6707
- const chunks = (await retriever.retrieve(query, { limit: opts.limit ?? 5, signal, vars })).slice(
6964
+ const chunks = readable(await retriever.retrieve(query, { limit: opts.limit ?? 5, signal, vars })).slice(
6708
6965
  0,
6709
6966
  opts.limit ?? 5
6710
6967
  );
6711
6968
  if (!chunks.length) return {};
6712
- const text3 = [
6969
+ const text4 = [
6713
6970
  "Reference material retrieved for this question. Ground your answer in it when relevant:",
6714
6971
  ...chunks.map(
6715
6972
  (c, i) => `[${i + 1}] ${c.title ?? c.id}${c.source ? ` (${c.source})` : ""}
@@ -6722,8 +6979,8 @@ ${c.text.trim()}`
6722
6979
  {
6723
6980
  id: opts.id ?? "retrieval",
6724
6981
  kind: "custom",
6725
- text: text3,
6726
- tokens: estimateTokens(text3),
6982
+ text: text4,
6983
+ tokens: estimateTokens(text4),
6727
6984
  priority: opts.priority ?? 400
6728
6985
  }
6729
6986
  ]
@@ -6732,7 +6989,7 @@ ${c.text.trim()}`
6732
6989
  };
6733
6990
  }
6734
6991
  function createKeywordRetriever(docs) {
6735
- const chunks = docs.flatMap(
6992
+ const chunks = docs.filter((doc) => typeof doc === "object" && doc !== null && typeof doc.text === "string").flatMap(
6736
6993
  (doc) => doc.text.split(/\n\s*\n/).map((p) => p.trim()).filter((p) => p.length > 0).map((paragraph, i) => ({
6737
6994
  id: `${doc.id}#${i}`,
6738
6995
  text: paragraph,
@@ -6754,21 +7011,14 @@ function createKeywordRetriever(docs) {
6754
7011
  async retrieve(query, opts = {}) {
6755
7012
  const queryTerms = tokenize(query);
6756
7013
  if (!queryTerms.length) return [];
6757
- const seen = /* @__PURE__ */ new Set();
6758
- const candidates = [];
6759
- for (const term of queryTerms) {
6760
- for (const chunk of invertedIndex.get(term) ?? []) {
6761
- if (!seen.has(chunk)) {
6762
- seen.add(chunk);
6763
- candidates.push(chunk);
6764
- }
6765
- }
6766
- }
6767
- candidates.sort((a, b) => a.idx - b.idx);
6768
- const scored = candidates.map((c) => {
6769
- const hits = queryTerms.filter((t) => c.terms.has(t)).length;
6770
- return { chunk: c, score: hits / Math.sqrt(c.terms.size || 1) };
6771
- }).filter((s) => s.score > 0).sort((a, b) => b.score - a.score).slice(0, opts.limit ?? 5);
7014
+ const queryCounts = /* @__PURE__ */ new Map();
7015
+ for (const term of queryTerms) queryCounts.set(term, (queryCounts.get(term) ?? 0) + 1);
7016
+ const hitsOf = /* @__PURE__ */ new Map();
7017
+ for (const [term, count] of queryCounts) {
7018
+ for (const chunk of invertedIndex.get(term) ?? []) hitsOf.set(chunk, (hitsOf.get(chunk) ?? 0) + count);
7019
+ }
7020
+ const candidates = [...hitsOf.keys()].sort((a, b) => a.idx - b.idx);
7021
+ const scored = candidates.map((c) => ({ chunk: c, score: hitsOf.get(c) / Math.sqrt(c.terms.size || 1) })).filter((s) => s.score > 0).sort((a, b) => b.score - a.score).slice(0, opts.limit ?? 5);
6772
7022
  return scored.map(({ chunk, score }) => {
6773
7023
  const { terms: _terms, idx: _idx, ...rest } = chunk;
6774
7024
  return { ...rest, score };
@@ -6802,7 +7052,7 @@ ${body}`);
6802
7052
  }
6803
7053
  }
6804
7054
  if (!blocks.length) return {};
6805
- const text3 = [
7055
+ const text4 = [
6806
7056
  "Current state of the application the user is looking at. This is live \u2014 it reflects the screen right now, not the conversation:",
6807
7057
  ...blocks,
6808
7058
  "Refer to it directly rather than asking the user to repeat what is already on screen."
@@ -6812,8 +7062,8 @@ ${body}`);
6812
7062
  {
6813
7063
  id: opts.id ?? "app-state",
6814
7064
  kind: "environment",
6815
- text: text3,
6816
- tokens: estimateTokens(text3),
7065
+ text: text4,
7066
+ tokens: estimateTokens(text4),
6817
7067
  priority: opts.priority ?? 600
6818
7068
  }
6819
7069
  ]
@@ -6862,6 +7112,15 @@ var McpRpcError = class extends Error {
6862
7112
  this.data = data;
6863
7113
  }
6864
7114
  };
7115
+ var isObject4 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
7116
+ function readTool(raw) {
7117
+ if (!isObject4(raw) || typeof raw.name !== "string" || raw.name === "") return void 0;
7118
+ return {
7119
+ name: raw.name,
7120
+ ...typeof raw.description === "string" ? { description: raw.description } : {},
7121
+ inputSchema: isObject4(raw.inputSchema) ? raw.inputSchema : { type: "object" }
7122
+ };
7123
+ }
6865
7124
  var MAX_TOOL_PAGES = 1e3;
6866
7125
  var McpClient = class {
6867
7126
  transport;
@@ -6904,10 +7163,12 @@ var McpClient = class {
6904
7163
  capabilities: this.onElicit ? { elicitation: {} } : {},
6905
7164
  clientInfo: this.clientInfo
6906
7165
  });
7166
+ const reply = isObject4(result) ? result : {};
7167
+ const info = isObject4(reply.serverInfo) && typeof reply.serverInfo.name === "string" ? reply.serverInfo : void 0;
6907
7168
  await this.post({ jsonrpc: "2.0", method: "notifications/initialized" });
6908
7169
  this.handshake = {
6909
- serverInfo: result.serverInfo ?? { name: "unknown" },
6910
- protocolVersion: result.protocolVersion ?? this.protocolVersion
7170
+ serverInfo: info ? { name: info.name, ...typeof info.version === "string" ? { version: info.version } : {} } : { name: "unknown" },
7171
+ protocolVersion: typeof reply.protocolVersion === "string" ? reply.protocolVersion : this.protocolVersion
6911
7172
  };
6912
7173
  return this.handshake;
6913
7174
  }
@@ -6918,8 +7179,14 @@ var McpClient = class {
6918
7179
  const seen = /* @__PURE__ */ new Set();
6919
7180
  let cursor;
6920
7181
  do {
6921
- const page = await this.rpc("tools/list", cursor ? { cursor } : {}, opts);
6922
- if (Array.isArray(page.tools)) tools.push(...page.tools);
7182
+ const reply = await this.rpc("tools/list", cursor ? { cursor } : {}, opts);
7183
+ const page = isObject4(reply) ? reply : {};
7184
+ if (Array.isArray(page.tools)) {
7185
+ for (const raw of page.tools) {
7186
+ const tool = readTool(raw);
7187
+ if (tool) tools.push(tool);
7188
+ }
7189
+ }
6923
7190
  cursor = typeof page.nextCursor === "string" && page.nextCursor !== "" ? page.nextCursor : void 0;
6924
7191
  if (cursor !== void 0) {
6925
7192
  if (seen.has(cursor) || seen.size >= MAX_TOOL_PAGES) {
@@ -6939,7 +7206,12 @@ var McpClient = class {
6939
7206
  await this.ensureConnected();
6940
7207
  try {
6941
7208
  const result = await this.rpc("tools/call", { name, arguments: args ?? {} }, opts);
6942
- return { ...result, content: result.content ?? [] };
7209
+ if (!isObject4(result)) return { content: [{ type: "text", text: "The MCP server sent no result." }], isError: true };
7210
+ return {
7211
+ ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : {},
7212
+ content: Array.isArray(result.content) ? result.content.filter(isObject4) : [],
7213
+ ...result.isError === true ? { isError: true } : {}
7214
+ };
6943
7215
  } catch (e) {
6944
7216
  if (e instanceof McpRpcError) {
6945
7217
  return { content: [{ type: "text", text: e.message }], isError: true };
@@ -7059,7 +7331,7 @@ function createHttpTransport(opts) {
7059
7331
  // src/mcp/import.ts
7060
7332
  var RESERVED_NAMESPACE = "mcp";
7061
7333
  function sanitizeNamespace(raw) {
7062
- const cleaned = (raw ?? "").replace(/[^a-zA-Z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
7334
+ const cleaned = (typeof raw === "string" ? raw : "").replace(/[^a-zA-Z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
7063
7335
  if (!cleaned || cleaned.toLowerCase() === RESERVED_NAMESPACE) return "srv";
7064
7336
  return cleaned;
7065
7337
  }
@@ -7094,15 +7366,20 @@ async function importMcpTools(client, opts = {}) {
7094
7366
  return out;
7095
7367
  }
7096
7368
  function mapMcpResult(result) {
7097
- if (result.isError) {
7098
- return { output: { error: textOf(result.content) || "MCP tool failed." }, failure: "execution-error" };
7369
+ const content = (Array.isArray(result?.content) ? result.content : []).filter((c) => c !== null && typeof c === "object");
7370
+ if (result?.isError === true) {
7371
+ return { output: { error: textOf(content) || "MCP tool failed." }, failure: "execution-error" };
7099
7372
  }
7100
- if (result.structuredContent !== void 0) {
7373
+ if (result?.structuredContent !== void 0) {
7101
7374
  return { output: result.structuredContent };
7102
7375
  }
7103
- const texts = result.content.filter((c) => c.type === "text");
7104
- const resources = result.content.filter((c) => c.type === "resource");
7105
- const image2 = result.content.find((c) => c.type === "image");
7376
+ const texts = content.filter((c) => c.type === "text" && typeof c.text === "string");
7377
+ const resources = content.filter(
7378
+ (c) => c.type === "resource" && c.resource !== null && typeof c.resource === "object" && typeof c.resource.uri === "string"
7379
+ );
7380
+ const image2 = content.find(
7381
+ (c) => c.type === "image" && typeof c.data === "string" && typeof c.mimeType === "string"
7382
+ );
7106
7383
  let output;
7107
7384
  if (texts.length === 1) {
7108
7385
  output = parseMaybeJson(texts[0].text);
@@ -7110,7 +7387,7 @@ function mapMcpResult(result) {
7110
7387
  output = texts.map((t) => t.text).join("\n");
7111
7388
  }
7112
7389
  if (resources.length) {
7113
- const refs = resources.map((r) => ({ uri: r.resource.uri, ...r.resource.text ? { text: r.resource.text } : {} }));
7390
+ const refs = resources.map((r) => ({ uri: r.resource.uri, ...typeof r.resource.text === "string" && r.resource.text ? { text: r.resource.text } : {} }));
7114
7391
  output = output === void 0 ? { resources: refs } : { text: output, resources: refs };
7115
7392
  }
7116
7393
  if (output === void 0) output = image2 ? "(image result)" : null;
@@ -7184,14 +7461,14 @@ function elicitViaCard(requestCard) {
7184
7461
  return { action: "accept", content };
7185
7462
  };
7186
7463
  }
7187
- var textOf = (content) => content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
7188
- function parseMaybeJson(text3) {
7189
- const trimmed = text3.trim();
7190
- if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return text3;
7464
+ var textOf = (content) => content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
7465
+ function parseMaybeJson(text4) {
7466
+ const trimmed = text4.trim();
7467
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return text4;
7191
7468
  try {
7192
7469
  return JSON.parse(trimmed);
7193
7470
  } catch {
7194
- return text3;
7471
+ return text4;
7195
7472
  }
7196
7473
  }
7197
7474
  export {
@@ -7205,12 +7482,14 @@ export {
7205
7482
  CARD_PLACEMENTS,
7206
7483
  CARD_REF_LIMITS,
7207
7484
  CARD_REF_SCHEME,
7485
+ CLIPS_METADATA_KEY,
7208
7486
  CardRegistry,
7209
7487
  ContextBuilder,
7210
7488
  DEFAULT_PRESETS,
7211
7489
  DEFAULT_RETRY,
7212
7490
  DEFAULT_STOP_CONDITIONS,
7213
7491
  MAILTO_SAFE_LENGTH,
7492
+ MAX_CLIP_CHARS,
7214
7493
  MESSAGE_OVERHEAD_TOKENS,
7215
7494
  McpClient,
7216
7495
  McpRpcError,
@@ -7264,6 +7543,8 @@ export {
7264
7543
  childrenOf,
7265
7544
  choiceCard,
7266
7545
  citationsCard,
7546
+ clipPreview,
7547
+ clipsOf,
7267
7548
  codeCard,
7268
7549
  combineMeteringSources,
7269
7550
  compactError,
@@ -7328,6 +7609,7 @@ export {
7328
7609
  findUnsafe,
7329
7610
  foldSurfaces,
7330
7611
  formCard,
7612
+ formatClips,
7331
7613
  formatQuotes,
7332
7614
  formatTemplate,
7333
7615
  funnelCard,
@@ -7409,11 +7691,12 @@ export {
7409
7691
  statsCard,
7410
7692
  stepCountIs,
7411
7693
  stripCardPayload,
7694
+ stripClips,
7412
7695
  stripUiOnlyParts,
7413
7696
  surfaceActionTools,
7414
7697
  surfaceCardId,
7415
7698
  tableCard,
7416
- text,
7699
+ text2 as text,
7417
7700
  threadSnapshot,
7418
7701
  timelineCard,
7419
7702
  toA2uiMessages,
@@ -7435,6 +7718,7 @@ export {
7435
7718
  validateSurfaceComponents,
7436
7719
  validateSurfaceGraph,
7437
7720
  withCard,
7721
+ withClips,
7438
7722
  withQuotes,
7439
7723
  withRetry
7440
7724
  };