@supersolutions/super-chat-core 0.4.4 → 0.5.1

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-WFU4HXUG.js";
12
12
  import {
13
13
  buildAnthropicRequest,
14
14
  createAnthropicProvider
15
- } from "./chunk-JMM3X3GB.js";
15
+ } from "./chunk-KUB5GKAM.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-7G4U4NTL.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,12 +326,12 @@ ${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];
@@ -338,7 +340,7 @@ function quotesOf(metadata) {
338
340
 
339
341
  // src/transport/binary.ts
340
342
  var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
341
- var REVERSE = (() => {
343
+ var REVERSE = /* @__PURE__ */ (() => {
342
344
  const table = new Int16Array(128).fill(-1);
343
345
  for (let i = 0; i < ALPHABET.length; i += 1) table[ALPHABET.charCodeAt(i)] = i;
344
346
  return table;
@@ -528,6 +530,10 @@ function createOpenAICompatibleProfile(profile) {
528
530
  return normalizeProviderProfile({ ...profile, protocol: "openai-chat" });
529
531
  }
530
532
  function normalizeProviderProfile(profile) {
533
+ if (typeof profile !== "object" || profile === null) throw new Error("Provider profile must be an object.");
534
+ if (typeof profile.id !== "string") throw new Error("Provider profile id must be a string.");
535
+ if (typeof profile.label !== "string") throw new Error("Provider profile label is required.");
536
+ if (typeof profile.baseUrl !== "string") throw new Error("Provider profile baseUrl must be an absolute URL.");
531
537
  const id = profile.id.trim();
532
538
  const label = profile.label.trim();
533
539
  if (!id || !/^[a-z0-9][a-z0-9._-]*$/i.test(id)) {
@@ -549,11 +555,13 @@ function normalizeProviderProfile(profile) {
549
555
  if (url.search || url.hash) {
550
556
  throw new Error("Provider profile baseUrl cannot include a query or fragment.");
551
557
  }
558
+ let end = url.pathname.length;
559
+ while (end > 0 && url.pathname.charCodeAt(end - 1) === 47) end--;
552
560
  return {
553
561
  ...profile,
554
562
  id,
555
563
  label,
556
- baseUrl: url.toString().replace(/\/$/, "")
564
+ baseUrl: url.origin + url.pathname.slice(0, end)
557
565
  };
558
566
  }
559
567
  function createProviderFromProfile(profileInput, transport) {
@@ -629,20 +637,26 @@ function createOpenAIImageProvider(config) {
629
637
  signal: opts?.signal
630
638
  });
631
639
  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;
640
+ const json = await readObject(res, id);
641
+ const items = Array.isArray(json.data) ? json.data : [];
642
+ if (!items.length) throw new Error(`Provider "${id}" returned no generated images.`);
643
+ const created = typeof json.created === "number" && Number.isFinite(json.created) && json.created >= 0 ? json.created : Math.floor(Date.now() / 1e3);
644
+ const createdAt = created * 1e3;
635
645
  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.`);
646
+ return items.map((entry) => {
647
+ const item = typeof entry === "object" && entry !== null ? entry : {};
648
+ const url = text(item.url) || void 0;
649
+ const b64 = text(item.b64_json) || void 0;
650
+ const revisedPrompt = text(item.revised_prompt);
651
+ if (!url && !b64) throw new Error(`Provider "${id}" returned an image without url or b64_json.`);
638
652
  return {
639
653
  id: nextId("media"),
640
654
  kind: "image",
641
- source: item.url ? { kind: "url", url: item.url } : { kind: "base64", data: item.b64_json },
655
+ source: url ? { kind: "url", url } : { kind: "base64", data: b64 },
642
656
  mediaType: "image/png",
643
657
  provider: id,
644
658
  ...req.model ?? config.defaultModel ? { model: req.model ?? config.defaultModel } : {},
645
- ...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {},
659
+ ...revisedPrompt ? { revisedPrompt } : {},
646
660
  ...dimensions ?? {},
647
661
  createdAt
648
662
  };
@@ -729,11 +743,11 @@ function createGenerateImageTool(provider, options = {}) {
729
743
  // src/tokens/estimate.ts
730
744
  var LATIN_CHARS_PER_TOKEN = 3.7;
731
745
  var CJK_CHARS_PER_TOKEN = 1.1;
732
- function estimateTokens(text3) {
733
- if (!text3) return 0;
746
+ function estimateTokens(text4) {
747
+ if (!text4) return 0;
734
748
  let cjk = 0;
735
749
  let other = 0;
736
- for (const ch of text3) {
750
+ for (const ch of text4) {
737
751
  const code = ch.codePointAt(0);
738
752
  const isCjk = code >= 12352 && code <= 12543 || // kana
739
753
  code >= 13312 && code <= 19903 || // CJK ext A
@@ -902,10 +916,13 @@ function scoreAlias(alias, query, queryTokens) {
902
916
  }
903
917
  return 0;
904
918
  }
905
- function scoreSkill(skill, query) {
919
+ var prepareQuery = (query) => {
906
920
  const q = query.toLowerCase().trim();
921
+ return { q, queryTokens: q ? new Set(tokenize(q)) : /* @__PURE__ */ new Set() };
922
+ };
923
+ function scoreSkill(skill, query, prepared = prepareQuery(query)) {
924
+ const { q, queryTokens } = prepared;
907
925
  if (!q) return { score: 0, reason: "empty query", sections: [] };
908
- const queryTokens = new Set(tokenize(q));
909
926
  let score = 0;
910
927
  const reasons = [];
911
928
  const nameScore = scoreAlias(skill.name, q, queryTokens);
@@ -946,8 +963,9 @@ function scoreSkill(skill, query) {
946
963
  return { score, reason: reasons.join(" ") || "no match", sections };
947
964
  }
948
965
  function matchSkills(skills, query, threshold = 1.5) {
966
+ const prepared = prepareQuery(query);
949
967
  return skills.map((skill) => {
950
- const { score, reason, sections } = scoreSkill(skill, query);
968
+ const { score, reason, sections } = scoreSkill(skill, query, prepared);
951
969
  return { skill, score, reason, sections };
952
970
  }).filter((m) => m.score >= threshold).sort((a, b) => b.score - a.score || a.skill.id.localeCompare(b.skill.id));
953
971
  }
@@ -1014,12 +1032,12 @@ var SkillRegistry = class {
1014
1032
  const matched = this.matcher(list, ctx.query).filter((m) => m.skill.mode === "matched" && !forced.has(m.skill.id)).slice(0, this.maxMatched);
1015
1033
  const out = [];
1016
1034
  for (const skill of always) {
1017
- const text3 = await renderSkill(skill, ctx);
1035
+ const text4 = await renderSkill(skill, ctx);
1018
1036
  out.push({
1019
1037
  id: skill.id,
1020
1038
  name: skill.name,
1021
- text: text3,
1022
- tokens: estimateTokens(text3),
1039
+ text: text4,
1040
+ tokens: estimateTokens(text4),
1023
1041
  // Sort key: `always` outranks any matched score so it survives packing.
1024
1042
  score: 1e3 + (skill.priority ?? 0),
1025
1043
  mode: skill.mode,
@@ -1027,12 +1045,12 @@ var SkillRegistry = class {
1027
1045
  });
1028
1046
  }
1029
1047
  for (const m of matched) {
1030
- const text3 = await renderSkill(m.skill, ctx, m.sections);
1048
+ const text4 = await renderSkill(m.skill, ctx, m.sections);
1031
1049
  out.push({
1032
1050
  id: m.skill.id,
1033
1051
  name: m.skill.name,
1034
- text: text3,
1035
- tokens: estimateTokens(text3),
1052
+ text: text4,
1053
+ tokens: estimateTokens(text4),
1036
1054
  score: m.score,
1037
1055
  mode: m.skill.mode,
1038
1056
  tools: m.skill.tools ?? []
@@ -1164,14 +1182,15 @@ ${summary}`
1164
1182
  const tokensAfter = countMessagesTokens(out, counter3);
1165
1183
  if (tokensAfter > opts.limitTokens) {
1166
1184
  const summaryTokens = countMessageTokens(summaryMessage, counter3);
1185
+ if (summaryTokens >= opts.limitTokens) return trimHistory(messages, opts.limitTokens, counter3, tokensBefore);
1167
1186
  const trimmed = trimHistory(recent, Math.max(0, opts.limitTokens - summaryTokens), counter3, tokensAfter - summaryTokens);
1168
- const messages2 = [summaryMessage, ...trimmed.messages];
1187
+ const fitted = [summaryMessage, ...trimmed.messages];
1169
1188
  return {
1170
- messages: messages2,
1189
+ messages: fitted,
1171
1190
  strategy: "summarize",
1172
1191
  droppedCount: older.length + trimmed.droppedCount,
1173
1192
  tokensBefore,
1174
- tokensAfter: countMessagesTokens(messages2, counter3),
1193
+ tokensAfter: countMessagesTokens(fitted, counter3),
1175
1194
  summary
1176
1195
  };
1177
1196
  }
@@ -1179,9 +1198,9 @@ ${summary}`
1179
1198
  }
1180
1199
  function buildSummaryPrompt(messages) {
1181
1200
  const transcript = messages.map((m) => {
1182
- const text3 = messageText(m);
1201
+ const text4 = messageText(m);
1183
1202
  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();
1203
+ return `${m.role}: ${text4}${calls ? ` ${calls}` : ""}`.trim();
1185
1204
  }).filter((line) => line.length > line.indexOf(":") + 1).join("\n");
1186
1205
  return [
1187
1206
  "Compress this conversation span into a brief the assistant can act on.",
@@ -1222,8 +1241,8 @@ var ContextBuilder = class {
1222
1241
  const unlockedTools = new Set(input.baseTools ?? []);
1223
1242
  let skills = [];
1224
1243
  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 });
1244
+ const text4 = this.opts.identity.trim();
1245
+ layers.push({ id: "identity", kind: "identity", text: text4, tokens: counter3(text4), pinned: true, priority: 1e3 });
1227
1246
  }
1228
1247
  if (this.opts.skills) {
1229
1248
  const started = Date.now();
@@ -1503,6 +1522,9 @@ function hunksOf(applied) {
1503
1522
  }
1504
1523
 
1505
1524
  // src/documents/store.ts
1525
+ var record = () => /* @__PURE__ */ Object.create(null);
1526
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1527
+ 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
1528
  var MAX_HISTORY = 20;
1507
1529
  var counter2 = 0;
1508
1530
  var mintId = () => `doc_${Date.now().toString(36)}${(counter2 += 1).toString(36)}`;
@@ -1566,22 +1588,43 @@ function createMemoryDocumentStore() {
1566
1588
  };
1567
1589
  }
1568
1590
  function createLocalDocumentStore(key = "superchat:documents") {
1591
+ let refused2 = null;
1592
+ const copy = (all) => ({ docs: Object.assign(record(), all.docs), past: Object.assign(record(), all.past) });
1569
1593
  const read = () => {
1594
+ if (refused2) return copy(refused2);
1570
1595
  try {
1571
1596
  const raw = globalThis.localStorage?.getItem(key) ?? null;
1572
1597
  const parsed = raw ? JSON.parse(raw) : null;
1573
- if (typeof parsed !== "object" || parsed === null) return { docs: {}, past: {} };
1598
+ if (typeof parsed !== "object" || parsed === null) return { docs: record(), past: record() };
1574
1599
  const p = parsed;
1575
- return { docs: p.docs ?? {}, past: p.past ?? {} };
1600
+ const docs = record();
1601
+ const past = record();
1602
+ if (isRecord(p.docs)) {
1603
+ for (const [id, doc] of Object.entries(p.docs)) if (isSnapshot(doc)) docs[id] = doc;
1604
+ }
1605
+ if (isRecord(p.past)) {
1606
+ for (const [id, list] of Object.entries(p.past)) if (Array.isArray(list)) past[id] = list.filter(isSnapshot);
1607
+ }
1608
+ return { docs, past };
1576
1609
  } catch {
1577
- return { docs: {}, past: {} };
1610
+ return { docs: record(), past: record() };
1578
1611
  }
1579
1612
  };
1580
1613
  const write = (all) => {
1581
- try {
1582
- globalThis.localStorage?.setItem(key, JSON.stringify(all));
1583
- } catch {
1614
+ const store = globalThis.localStorage;
1615
+ if (!store) {
1616
+ refused2 = all;
1617
+ return;
1618
+ }
1619
+ for (const [attempt, history] of [[all, true], [{ docs: all.docs, past: record() }, false]]) {
1620
+ try {
1621
+ store.setItem(key, JSON.stringify(attempt));
1622
+ refused2 = history ? null : all;
1623
+ return;
1624
+ } catch {
1625
+ }
1584
1626
  }
1627
+ refused2 = all;
1585
1628
  };
1586
1629
  return {
1587
1630
  async list() {
@@ -1785,7 +1828,7 @@ function createDocumentTools(opts) {
1785
1828
  }
1786
1829
  const from = num(i["from"]) ?? 0;
1787
1830
  const to = num(i["to"]) ?? from;
1788
- const text3 = spanOf(doc.markdown, from, to);
1831
+ const text4 = spanOf(doc.markdown, from, to);
1789
1832
  return {
1790
1833
  output: {
1791
1834
  docId: doc.id,
@@ -1795,8 +1838,8 @@ function createDocumentTools(opts) {
1795
1838
  // Truncation is REPORTED, not silent: a model that believes it has
1796
1839
  // read a whole section will quote text that is not there, and the
1797
1840
  // edit will then be refused for a reason that looks like its fault.
1798
- truncated: text3.length > maxSpanChars,
1799
- text: text3.slice(0, maxSpanChars)
1841
+ truncated: text4.length > maxSpanChars,
1842
+ text: text4.slice(0, maxSpanChars)
1800
1843
  }
1801
1844
  };
1802
1845
  }
@@ -2070,6 +2113,37 @@ var check = {
2070
2113
  return value;
2071
2114
  }
2072
2115
  };
2116
+ var typeName = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
2117
+ 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;
2118
+ var SHAPE_ITEMS = 500;
2119
+ function shapeError(value, schema, path, optional = false) {
2120
+ if (!isObj(schema)) return void 0;
2121
+ if ((value === void 0 || value === null) && optional) return void 0;
2122
+ const alts = schema["anyOf"] ?? schema["oneOf"];
2123
+ if (Array.isArray(alts)) {
2124
+ const errors = alts.map((alt) => shapeError(value, alt, path, optional));
2125
+ return errors.some((e) => e === void 0) ? void 0 : errors[0];
2126
+ }
2127
+ const type = schema["type"];
2128
+ if (type !== void 0) {
2129
+ const types = Array.isArray(type) ? type : [type];
2130
+ 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)}).`;
2131
+ }
2132
+ if (Array.isArray(value) && isObj(schema["items"])) {
2133
+ for (let i = 0; i < Math.min(value.length, SHAPE_ITEMS); i++) {
2134
+ const e = shapeError(value[i], schema["items"], `${path}[${i}]`);
2135
+ if (e) return e;
2136
+ }
2137
+ } else if (isObj(value) && isObj(schema["properties"])) {
2138
+ const required = Array.isArray(schema["required"]) ? schema["required"] : [];
2139
+ for (const [key, sub] of Object.entries(schema["properties"])) {
2140
+ if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
2141
+ const e = shapeError(value[key], sub, `${path}.${key}`, !required.includes(key));
2142
+ if (e) return e;
2143
+ }
2144
+ }
2145
+ return void 0;
2146
+ }
2073
2147
  var failed = (v) => isObj(v) && "ok" in v && v.ok === false;
2074
2148
  var CardRegistry = class {
2075
2149
  kinds = /* @__PURE__ */ new Map();
@@ -2150,7 +2224,7 @@ function makeCard(spec, callId, id, placement) {
2150
2224
 
2151
2225
  // src/cards/card-ref.ts
2152
2226
  var CARD_REF_SCHEME = "ref";
2153
- var CARD_REF_LIMITS = Object.freeze({
2227
+ var CARD_REF_LIMITS = /* @__PURE__ */ Object.freeze({
2154
2228
  /** The whole link, in UTF-16 code units. */
2155
2229
  length: 512,
2156
2230
  /** The target (the card's id). */
@@ -2866,13 +2940,14 @@ var calloutCard = {
2866
2940
  };
2867
2941
  var citationsCard = {
2868
2942
  kind: "citations",
2869
- summary: "The sources behind what you just said. Use whenever a claim rests on specific documents \u2014 case law, statutes, papers, filings, articles, internal docs. Quote the passage relied on in `snippet`.",
2943
+ summary: "The sources behind what you just said. Use whenever a claim rests on specific documents \u2014 case law, statutes, papers, filings, articles, internal docs. Quote the passage relied on in `snippet`. To cite a source inside your answer, give the card an `id` and write `[[1]](ref:<card id>?cite=<item id or its number>)` where the claim is made; the reader can hover or press it to see the source.",
2870
2944
  estimateTokens: tokensOf,
2871
2945
  schema: {
2872
2946
  type: "object",
2873
2947
  required: ["kind", "items"],
2874
2948
  properties: {
2875
2949
  kind: { const: "citations" },
2950
+ id: { type: "string", description: "Short name, so the answer can cite into this card with ref:<id>?cite=<n>." },
2876
2951
  title: { type: "string" },
2877
2952
  items: {
2878
2953
  type: "array",
@@ -2880,6 +2955,7 @@ var citationsCard = {
2880
2955
  type: "object",
2881
2956
  required: ["title"],
2882
2957
  properties: {
2958
+ id: { type: "string", description: "Short name of this source for `cite=`; unique in the card." },
2883
2959
  title: { type: "string" },
2884
2960
  source: { type: "string", description: "Publication, court, statute, dataset, site." },
2885
2961
  url: { type: "string" },
@@ -2897,10 +2973,22 @@ var citationsCard = {
2897
2973
  if (failed(s)) return s;
2898
2974
  const items = check.arrayField(s, "items", "citations");
2899
2975
  if (failed(items)) return items;
2976
+ const named = /* @__PURE__ */ new Set();
2900
2977
  for (const i of items) {
2901
2978
  if (!isObj(i) || typeof i["title"] !== "string") {
2902
2979
  return { ok: false, error: "Each citation needs a `title`." };
2903
2980
  }
2981
+ if (i["id"] !== void 0) {
2982
+ if (typeof i["id"] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._~-]{0,63}$/.test(i["id"])) {
2983
+ return { ok: false, error: "A citation `id` is 1 to 64 letters, digits, dot, dash, underscore or tilde, starting with a letter or digit." };
2984
+ }
2985
+ if (named.has(i["id"])) return { ok: false, error: `Two citations share the id "${i["id"]}"; ids must be unique in a card.` };
2986
+ named.add(i["id"]);
2987
+ }
2988
+ }
2989
+ const cardId = s["id"];
2990
+ if (cardId !== void 0 && (typeof cardId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(cardId))) {
2991
+ return { ok: false, error: "citations.id is 1 to 128 letters, digits, dot, underscore, colon or dash, starting with a letter or digit." };
2904
2992
  }
2905
2993
  return ok;
2906
2994
  }
@@ -3178,35 +3266,44 @@ var confirmCard = {
3178
3266
  return ok;
3179
3267
  }
3180
3268
  };
3269
+ var typed = (def) => ({
3270
+ ...def,
3271
+ validate(spec) {
3272
+ const own = def.validate(spec);
3273
+ if (!own.ok) return own;
3274
+ const wrong = shapeError(spec, def.schema, def.kind);
3275
+ return wrong ? { ok: false, error: wrong, expected: "the types in the card's schema" } : own;
3276
+ }
3277
+ });
3181
3278
  var BUILTIN_CARDS = [
3182
3279
  // structured data
3183
- tableCard,
3184
- statsCard,
3185
- comparisonCard,
3186
- keyValueCard,
3187
- treeCard,
3280
+ /* @__PURE__ */ typed(tableCard),
3281
+ /* @__PURE__ */ typed(statsCard),
3282
+ /* @__PURE__ */ typed(comparisonCard),
3283
+ /* @__PURE__ */ typed(keyValueCard),
3284
+ /* @__PURE__ */ typed(treeCard),
3188
3285
  // quantitative shape
3189
- chartCard,
3190
- funnelCard,
3191
- gaugeCard,
3286
+ /* @__PURE__ */ typed(chartCard),
3287
+ /* @__PURE__ */ typed(funnelCard),
3288
+ /* @__PURE__ */ typed(gaugeCard),
3192
3289
  // sequence and state
3193
- timelineCard,
3194
- progressCard,
3195
- checklistCard,
3290
+ /* @__PURE__ */ typed(timelineCard),
3291
+ /* @__PURE__ */ typed(progressCard),
3292
+ /* @__PURE__ */ typed(checklistCard),
3196
3293
  // prose and evidence
3197
- markdownCard,
3198
- documentCard,
3199
- calloutCard,
3200
- citationsCard,
3201
- codeCard,
3202
- diffCard,
3203
- mediaCard,
3294
+ /* @__PURE__ */ typed(markdownCard),
3295
+ /* @__PURE__ */ typed(documentCard),
3296
+ /* @__PURE__ */ typed(calloutCard),
3297
+ /* @__PURE__ */ typed(citationsCard),
3298
+ /* @__PURE__ */ typed(codeCard),
3299
+ /* @__PURE__ */ typed(diffCard),
3300
+ /* @__PURE__ */ typed(mediaCard),
3204
3301
  // interactive — these ask the user and pause the run
3205
- choiceCard,
3206
- formCard,
3207
- confirmCard,
3208
- editReviewCard,
3209
- emailCard
3302
+ /* @__PURE__ */ typed(choiceCard),
3303
+ /* @__PURE__ */ typed(formCard),
3304
+ /* @__PURE__ */ typed(confirmCard),
3305
+ /* @__PURE__ */ typed(editReviewCard),
3306
+ /* @__PURE__ */ typed(emailCard)
3210
3307
  ];
3211
3308
 
3212
3309
  // src/surfaces/types.ts
@@ -3404,12 +3501,12 @@ function checkSchema(schema, value, path = "", opts = {}) {
3404
3501
  }
3405
3502
  }
3406
3503
  if (typeOf(v) === "object") {
3407
- const record = v;
3504
+ const record2 = v;
3408
3505
  for (const key of s.required ?? []) {
3409
- if (record[key] === void 0) out.push({ path: `${at}/${key}`, message: `${at ? `${at}/` : ""}${key} is required.` });
3506
+ if (record2[key] === void 0) out.push({ path: `${at}/${key}`, message: `${at ? `${at}/` : ""}${key} is required.` });
3410
3507
  }
3411
3508
  const properties = s.properties ?? {};
3412
- for (const [key, item] of Object.entries(record)) {
3509
+ for (const [key, item] of Object.entries(record2)) {
3413
3510
  const propSchema = properties[key];
3414
3511
  if (propSchema) walk(propSchema, item, `${at}/${key}`);
3415
3512
  else if (s.additionalProperties === false) {
@@ -3615,7 +3712,7 @@ var TONES = ["neutral", "positive", "negative", "warning", "info"];
3615
3712
  var FORMATS2 = ["text", "number", "currency", "percent", "bytes", "duration", "datetime", "code"];
3616
3713
  var GAPS = ["none", "xs", "sm", "md", "lg"];
3617
3714
  var fixed = (schema) => ({ ...schema, "x-static": true });
3618
- var childIds = fixed({ type: "array", items: { type: "string" }, description: "Component ids, in display order." });
3715
+ var childIds = /* @__PURE__ */ fixed({ type: "array", items: { type: "string" }, description: "Component ids, in display order." });
3619
3716
  var childId = (description) => fixed({ type: "string", description });
3620
3717
  var boundValue = {
3621
3718
  type: "object",
@@ -3625,7 +3722,7 @@ var boundValue = {
3625
3722
  description: 'Two-way binding, e.g. { "$path": "/filters/region" }.',
3626
3723
  "x-static": true
3627
3724
  };
3628
- var CONDITION_SCHEMA = fixed({
3725
+ var CONDITION_SCHEMA = /* @__PURE__ */ fixed({
3629
3726
  type: "object",
3630
3727
  required: ["path"],
3631
3728
  properties: {
@@ -3635,7 +3732,7 @@ var CONDITION_SCHEMA = fixed({
3635
3732
  },
3636
3733
  additionalProperties: false
3637
3734
  });
3638
- var ACTION_SCHEMA = fixed({
3735
+ var ACTION_SCHEMA = /* @__PURE__ */ fixed({
3639
3736
  type: "object",
3640
3737
  required: ["type"],
3641
3738
  description: 'One of { "type": "set", "updates": [{ "path", "value" }] }, { "type": "tool", "tool", "args", "resultPath" }, { "type": "event", "name", "context" }.'
@@ -3646,7 +3743,7 @@ var props = (properties, required = []) => ({
3646
3743
  required,
3647
3744
  additionalProperties: false
3648
3745
  });
3649
- var text2 = (description) => ({ type: "string", ...description ? { description } : {} });
3746
+ var text3 = (description) => ({ type: "string", ...description ? { description } : {} });
3650
3747
  var SURFACE_PRIMITIVES = [
3651
3748
  {
3652
3749
  name: "Stack",
@@ -3685,8 +3782,8 @@ var SURFACE_PRIMITIVES = [
3685
3782
  summary: "A titled group of children.",
3686
3783
  props: props(
3687
3784
  {
3688
- title: text2(),
3689
- description: text2(),
3785
+ title: text3(),
3786
+ description: text3(),
3690
3787
  tone: { type: "string", enum: TONES },
3691
3788
  children: childIds
3692
3789
  },
@@ -3700,7 +3797,7 @@ var SURFACE_PRIMITIVES = [
3700
3797
  summary: "Switch between named panels. Keyboard accessible.",
3701
3798
  props: props(
3702
3799
  {
3703
- label: text2("Names the tab list for screen readers."),
3800
+ label: text3("Names the tab list for screen readers."),
3704
3801
  value: { ...boundValue, description: "Optional binding for the selected tab id." },
3705
3802
  tabs: fixed({
3706
3803
  type: "array",
@@ -3726,7 +3823,7 @@ var SURFACE_PRIMITIVES = [
3726
3823
  {
3727
3824
  items: { type: "array", description: "A $path or $query that yields an array." },
3728
3825
  child: childId("The template component rendered once per row."),
3729
- emptyText: text2("Shown when there are no rows."),
3826
+ emptyText: text3("Shown when there are no rows."),
3730
3827
  gap: { type: "string", enum: GAPS }
3731
3828
  },
3732
3829
  ["items", "child"]
@@ -3754,12 +3851,12 @@ var SURFACE_PRIMITIVES = [
3754
3851
  summary: "One headline number with a label and optional change.",
3755
3852
  props: props(
3756
3853
  {
3757
- label: text2(),
3854
+ label: text3(),
3758
3855
  value: { type: ["string", "number", "null"] },
3759
3856
  format: { type: "string", enum: FORMATS2 },
3760
3857
  delta: { type: "number" },
3761
3858
  deltaFormat: { type: "string", enum: FORMATS2 },
3762
- hint: text2(),
3859
+ hint: text3(),
3763
3860
  tone: { type: "string", enum: TONES }
3764
3861
  },
3765
3862
  ["label", "value"]
@@ -3775,13 +3872,13 @@ var SURFACE_PRIMITIVES = [
3775
3872
  name: "Image",
3776
3873
  category: "display",
3777
3874
  summary: "An http(s) image with required alt text.",
3778
- props: props({ src: text2(), alt: text2(), caption: text2() }, ["src", "alt"])
3875
+ props: props({ src: text3(), alt: text3(), caption: text3() }, ["src", "alt"])
3779
3876
  },
3780
3877
  {
3781
3878
  name: "Link",
3782
3879
  category: "display",
3783
3880
  summary: "An http(s) link that opens in a new tab.",
3784
- props: props({ text: text2(), href: text2() }, ["text", "href"])
3881
+ props: props({ text: text3(), href: text3() }, ["text", "href"])
3785
3882
  },
3786
3883
  {
3787
3884
  name: "Field",
@@ -3789,11 +3886,11 @@ var SURFACE_PRIMITIVES = [
3789
3886
  summary: "Text, number, date or multi-line input bound to the data model.",
3790
3887
  props: props(
3791
3888
  {
3792
- label: text2(),
3889
+ label: text3(),
3793
3890
  value: boundValue,
3794
3891
  type: { type: "string", enum: ["text", "number", "date", "textarea"] },
3795
- placeholder: text2(),
3796
- helper: text2(),
3892
+ placeholder: text3(),
3893
+ helper: text3(),
3797
3894
  min: { type: "number" },
3798
3895
  max: { type: "number" },
3799
3896
  step: { type: "number" }
@@ -3807,7 +3904,7 @@ var SURFACE_PRIMITIVES = [
3807
3904
  summary: "Choose one option; writes its value to the data model.",
3808
3905
  props: props(
3809
3906
  {
3810
- label: text2(),
3907
+ label: text3(),
3811
3908
  value: boundValue,
3812
3909
  options: {
3813
3910
  type: "array",
@@ -3818,7 +3915,7 @@ var SURFACE_PRIMITIVES = [
3818
3915
  additionalProperties: false
3819
3916
  }
3820
3917
  },
3821
- helper: text2()
3918
+ helper: text3()
3822
3919
  },
3823
3920
  ["label", "value", "options"]
3824
3921
  )
@@ -3827,7 +3924,7 @@ var SURFACE_PRIMITIVES = [
3827
3924
  name: "Toggle",
3828
3925
  category: "input",
3829
3926
  summary: "An on/off switch bound to a boolean.",
3830
- props: props({ label: text2(), value: boundValue, helper: text2() }, ["label", "value"])
3927
+ props: props({ label: text3(), value: boundValue, helper: text3() }, ["label", "value"])
3831
3928
  },
3832
3929
  {
3833
3930
  name: "Slider",
@@ -3835,7 +3932,7 @@ var SURFACE_PRIMITIVES = [
3835
3932
  summary: "Pick a number in a range.",
3836
3933
  props: props(
3837
3934
  {
3838
- label: text2(),
3935
+ label: text3(),
3839
3936
  value: boundValue,
3840
3937
  min: { type: "number" },
3841
3938
  max: { type: "number" },
@@ -3851,7 +3948,7 @@ var SURFACE_PRIMITIVES = [
3851
3948
  summary: "Runs one action when pressed: set local state, call an allowed tool, or send the agent an event.",
3852
3949
  props: props(
3853
3950
  {
3854
- label: text2(),
3951
+ label: text3(),
3855
3952
  action: ACTION_SCHEMA,
3856
3953
  variant: { type: "string", enum: ["primary", "secondary", "ghost", "danger"] },
3857
3954
  disabledWhen: CONDITION_SCHEMA
@@ -3966,40 +4063,40 @@ function validateSurfaceAction(action, componentId, ctx) {
3966
4063
  const extra = Object.keys(action).filter((k) => !allowed.includes(k));
3967
4064
  return extra.length ? bad(`action has no "${extra[0]}". Actions cannot carry code or URLs.`, `Allowed keys: ${allowed.join(", ")}.`) : [];
3968
4065
  };
3969
- const typed = action;
3970
- switch (typed.type) {
4066
+ const typed2 = action;
4067
+ switch (typed2.type) {
3971
4068
  case "set": {
3972
4069
  const extra = onlyKeys(["type", "updates"]);
3973
4070
  if (extra.length) return extra;
3974
- if (!Array.isArray(typed.updates) || !typed.updates.length || typed.updates.length > SURFACE_LIMITS.actionUpdates) {
4071
+ if (!Array.isArray(typed2.updates) || !typed2.updates.length || typed2.updates.length > SURFACE_LIMITS.actionUpdates) {
3975
4072
  return bad(`set needs 1 to ${SURFACE_LIMITS.actionUpdates} updates.`, 'Send "updates": [{ "path": "/a", "value": 1 }].');
3976
4073
  }
3977
- for (const update of typed.updates) {
4074
+ for (const update of typed2.updates) {
3978
4075
  if (!isObject(update) || !parsePointer(update.path)) return bad("Each update needs a JSON Pointer `path`.", 'Send { "path": "/a", "value": 1 }.');
3979
4076
  }
3980
- return bindingIssues(typed.updates, componentId);
4077
+ return bindingIssues(typed2.updates, componentId);
3981
4078
  }
3982
4079
  case "tool": {
3983
4080
  const extra = onlyKeys(["type", "tool", "args", "resultPath"]);
3984
4081
  if (extra.length) return extra;
3985
- if (typeof typed.tool !== "string" || !typed.tool) return bad("A tool action needs a `tool` name.", 'Send { "type": "tool", "tool": "name" }.');
3986
- 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.");
3987
- if (typed.resultPath !== void 0 && !parsePointer(typed.resultPath)) return bad("`resultPath` must be a JSON Pointer.", 'Send "resultPath": "/result".');
3988
- if (ctx.actionTools && !ctx.actionTools.includes(typed.tool)) {
4082
+ if (typeof typed2.tool !== "string" || !typed2.tool) return bad("A tool action needs a `tool` name.", 'Send { "type": "tool", "tool": "name" }.');
4083
+ 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.");
4084
+ if (typed2.resultPath !== void 0 && !parsePointer(typed2.resultPath)) return bad("`resultPath` must be a JSON Pointer.", 'Send "resultPath": "/result".');
4085
+ if (ctx.actionTools && !ctx.actionTools.includes(typed2.tool)) {
3989
4086
  return bad(
3990
- `Tool "${typed.tool}" is not available to this surface.`,
4087
+ `Tool "${typed2.tool}" is not available to this surface.`,
3991
4088
  ctx.actionTools.length ? `Available: ${ctx.actionTools.slice(0, 24).join(", ")}.` : 'No tools are available; use an "event" action instead.',
3992
4089
  "tool-not-allowed"
3993
4090
  );
3994
4091
  }
3995
- return bindingIssues(typed.args, componentId);
4092
+ return bindingIssues(typed2.args, componentId);
3996
4093
  }
3997
4094
  case "event": {
3998
4095
  const extra = onlyKeys(["type", "name", "context"]);
3999
4096
  if (extra.length) return extra;
4000
- if (!isSurfaceId(typed.name)) return bad("An event needs a short `name`.", 'Send { "type": "event", "name": "apply" }.');
4001
- 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.");
4002
- return bindingIssues(typed.context, componentId);
4097
+ if (!isSurfaceId(typed2.name)) return bad("An event needs a short `name`.", 'Send { "type": "event", "name": "apply" }.');
4098
+ 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.");
4099
+ return bindingIssues(typed2.context, componentId);
4003
4100
  }
4004
4101
  default:
4005
4102
  return bad(`Unknown action type ${JSON.stringify(action.type)}.`, closed);
@@ -4661,11 +4758,11 @@ function createSurfaceContextSource() {
4661
4758
  run({ messages }) {
4662
4759
  const live = Object.values(foldSurfaces(messages)).filter((s) => !s.deleted && !s.expired);
4663
4760
  if (!live.length) return {};
4664
- const text3 = [
4761
+ const text4 = [
4665
4762
  "Surfaces on screen. Call readSurface for their current state before relying on it:",
4666
4763
  ...live.map((s) => `- ${s.surfaceId}${s.title ? ` (${s.title})` : ""}, revision ${s.revision}`)
4667
4764
  ].join("\n");
4668
- return { layers: [{ id: "surfaces", kind: "custom", text: text3, tokens: estimateTokens(text3), priority: 400 }] };
4765
+ return { layers: [{ id: "surfaces", kind: "custom", text: text4, tokens: estimateTokens(text4), priority: 400 }] };
4669
4766
  }
4670
4767
  };
4671
4768
  }
@@ -4704,12 +4801,12 @@ var EventChannel = class {
4704
4801
  var MAX_FIELDS = 6;
4705
4802
  var MAX_VALUE_CHARS = 160;
4706
4803
  var MAX_DESCRIPTION_CHARS = 240;
4707
- var clip = (text3, max) => text3.length > max ? `${text3.slice(0, max - 1)}\u2026` : text3;
4804
+ var clip = (text4, max) => text4.length > max ? `${text4.slice(0, max - 1)}\u2026` : text4;
4708
4805
  function humanizeFieldName(key) {
4709
4806
  const words = key.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[\s_\-.]+/).filter(Boolean).map((word) => word.toLowerCase());
4710
4807
  if (words.length > 1 && (words[words.length - 1] === "id" || words[words.length - 1] === "ids")) words.pop();
4711
- const text3 = words.join(" ");
4712
- return text3 ? text3.charAt(0).toUpperCase() + text3.slice(1) : key;
4808
+ const text4 = words.join(" ");
4809
+ return text4 ? text4.charAt(0).toUpperCase() + text4.slice(1) : key;
4713
4810
  }
4714
4811
  function plainValue(value) {
4715
4812
  if (typeof value === "string") return value.trim() ? clip(value.trim(), MAX_VALUE_CHARS) : void 0;
@@ -4723,9 +4820,9 @@ function plainValue(value) {
4723
4820
  return void 0;
4724
4821
  }
4725
4822
  function firstSentence(description) {
4726
- const text3 = description.trim().replace(/\s+/g, " ");
4727
- const end = text3.search(/[.!?](\s|$)/);
4728
- return clip(end === -1 ? text3 : text3.slice(0, end + 1), MAX_DESCRIPTION_CHARS);
4823
+ const text4 = description.trim().replace(/\s+/g, " ");
4824
+ const end = text4.search(/[.!?](\s|$)/);
4825
+ return clip(end === -1 ? text4 : text4.slice(0, end + 1), MAX_DESCRIPTION_CHARS);
4729
4826
  }
4730
4827
  function fieldsOf(input) {
4731
4828
  if (input === void 0 || input === null) return [];
@@ -4862,6 +4959,16 @@ async function executeToolCall(call, opts) {
4862
4959
  card = { ...embedded, callId: call.callId };
4863
4960
  opts.onCard?.(card);
4864
4961
  }
4962
+ const unsendable = jsonProblem(output);
4963
+ if (unsendable) {
4964
+ return {
4965
+ callId: call.callId,
4966
+ name: call.name,
4967
+ output: { error: `Tool "${call.name}" returned a value that cannot be sent as JSON (${unsendable}).` },
4968
+ failure: "execution-error",
4969
+ ms: Date.now() - started
4970
+ };
4971
+ }
4865
4972
  return {
4866
4973
  callId: call.callId,
4867
4974
  name: call.name,
@@ -4884,6 +4991,15 @@ async function executeToolCall(call, opts) {
4884
4991
  settled = true;
4885
4992
  }
4886
4993
  }
4994
+ function jsonProblem(value) {
4995
+ if (value === void 0 || typeof value === "string") return void 0;
4996
+ try {
4997
+ if (JSON.stringify(value) === void 0) return `a ${typeof value} has no JSON form`;
4998
+ return void 0;
4999
+ } catch (e) {
5000
+ return (e instanceof Error ? e.message : String(e)).slice(0, 120);
5001
+ }
5002
+ }
4887
5003
  var NOT_ABOUT_INPUT = /* @__PURE__ */ new Set(["denied", "timeout", "not-found"]);
4888
5004
  var MAX_DESCRIBED = 200;
4889
5005
  function explainMissingInput(tool, input, output, failure) {
@@ -4952,13 +5068,13 @@ function combineMeteringSources(sources) {
4952
5068
  const unique = new Set(sources);
4953
5069
  return unique.size === 1 ? sources[0] : "mixed";
4954
5070
  }
4955
- async function deliverMetering(sink, record) {
5071
+ async function deliverMetering(sink, record2) {
4956
5072
  if (!sink) return;
4957
5073
  try {
4958
- await sink.record(record);
5074
+ await sink.record(record2);
4959
5075
  } catch (error) {
4960
5076
  try {
4961
- await sink.onError?.(error, record);
5077
+ await sink.onError?.(error, record2);
4962
5078
  } catch {
4963
5079
  }
4964
5080
  }
@@ -5017,7 +5133,7 @@ async function* runSurfaceToolAction(config) {
5017
5133
  const outcome2 = await running;
5018
5134
  const finishedAt = Date.now();
5019
5135
  const finishReason = outcome2.failure === "denied" && config.signal?.aborted ? "cancelled" : "stop";
5020
- const record = {
5136
+ const record2 = {
5021
5137
  scope: "run",
5022
5138
  id: `${runId}:run`,
5023
5139
  runId,
@@ -5034,8 +5150,8 @@ async function* runSurfaceToolAction(config) {
5034
5150
  finishReason,
5035
5151
  metadata: { ...config.meteringMetadata, trigger: "surface-action", surfaceId: config.surfaceId, componentId: config.componentId, tool: config.tool.name }
5036
5152
  };
5037
- await deliverMetering(config.meter, record);
5038
- yield { type: "metering", record };
5153
+ await deliverMetering(config.meter, record2);
5154
+ yield { type: "metering", record: record2 };
5039
5155
  yield { type: "run-finish", runId, finishReason, usage: {}, steps: 0 };
5040
5156
  }
5041
5157
 
@@ -5075,7 +5191,7 @@ function toComponents(component, rename) {
5075
5191
  case "Stack":
5076
5192
  return [{ ...base, component: rest["direction"] === "horizontal" ? "Row" : "Column", children, ...rest["justify"] ? { justify: rest["justify"] === "between" ? "spaceBetween" : rest["justify"] } : {}, ...rest["align"] ? { align: rest["align"] } : {} }];
5077
5193
  case "Text":
5078
- return [{ ...base, component: "Text", text: props2["text"], ...typeof rest["variant"] === "string" ? { variant: TEXT_VARIANTS[rest["variant"]] } : {} }];
5194
+ return [{ ...base, component: "Text", text: props2["text"], ...typeof rest["variant"] === "string" ? { variant: Object.hasOwn(TEXT_VARIANTS, rest["variant"]) ? TEXT_VARIANTS[rest["variant"]] : void 0 } : {} }];
5079
5195
  case "Image":
5080
5196
  return [{ ...base, component: "Image", url: props2["src"] }];
5081
5197
  case "Divider":
@@ -5280,9 +5396,9 @@ function setOwn(target, key, value) {
5280
5396
  if (key === "__proto__") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
5281
5397
  else target[key] = value;
5282
5398
  }
5283
- function visible(text3) {
5284
- const last = text3.charCodeAt(text3.length - 1);
5285
- return last >= 55296 && last <= 56319 ? text3.slice(0, -1) : text3;
5399
+ function visible(text4) {
5400
+ const last = text4.charCodeAt(text4.length - 1);
5401
+ return last >= 55296 && last <= 56319 ? text4.slice(0, -1) : text4;
5286
5402
  }
5287
5403
  var PartialJsonParser = class {
5288
5404
  stack = [];
@@ -5511,9 +5627,9 @@ var PartialJsonParser = class {
5511
5627
  return i;
5512
5628
  }
5513
5629
  };
5514
- function parsePartialJson(text3) {
5630
+ function parsePartialJson(text4) {
5515
5631
  const parser = new PartialJsonParser();
5516
- parser.push(text3);
5632
+ parser.push(text4);
5517
5633
  return { value: parser.snapshot(), complete: parser.complete };
5518
5634
  }
5519
5635
 
@@ -5841,8 +5957,8 @@ function reduceRunEvent(state, event) {
5841
5957
  return state;
5842
5958
  }
5843
5959
  }
5844
- function without(record, key) {
5845
- const next = { ...record };
5960
+ function without(record2, key) {
5961
+ const next = { ...record2 };
5846
5962
  delete next[key];
5847
5963
  return next;
5848
5964
  }
@@ -5886,7 +6002,7 @@ function shouldStop(conditions, ctx) {
5886
6002
  if (!conditions?.length) return false;
5887
6003
  return conditions.some((c) => c(ctx));
5888
6004
  }
5889
- var DEFAULT_STOP_CONDITIONS = [consecutiveFailures(3)];
6005
+ var DEFAULT_STOP_CONDITIONS = [/* @__PURE__ */ consecutiveFailures(3)];
5890
6006
 
5891
6007
  // src/runtime/run.ts
5892
6008
  async function* runAgent(messages, config) {
@@ -6039,7 +6155,7 @@ async function* runAgent(messages, config) {
6039
6155
  yield { type: "usage", usage: stepUsage };
6040
6156
  }
6041
6157
  const finishedAt3 = Date.now();
6042
- const record3 = {
6158
+ const record4 = {
6043
6159
  scope: "step",
6044
6160
  id: `${runId}:step:${step}`,
6045
6161
  runId,
@@ -6058,8 +6174,8 @@ async function* runAgent(messages, config) {
6058
6174
  ...config.meteringMetadata ? { metadata: config.meteringMetadata } : {},
6059
6175
  error: { kind: error.kind, message: error.message }
6060
6176
  };
6061
- await deliverMetering(config.meter, record3);
6062
- yield { type: "metering", record: record3 };
6177
+ await deliverMetering(config.meter, record4);
6178
+ yield { type: "metering", record: record4 };
6063
6179
  throw error;
6064
6180
  }
6065
6181
  previousResponseId = responseId;
@@ -6071,7 +6187,7 @@ async function* runAgent(messages, config) {
6071
6187
  meteringSources.push(source);
6072
6188
  if (reportedModel) reportedModels.add(reportedModel);
6073
6189
  const finishedAt2 = Date.now();
6074
- const record2 = {
6190
+ const record3 = {
6075
6191
  scope: "step",
6076
6192
  id: `${runId}:step:${step}`,
6077
6193
  runId,
@@ -6090,8 +6206,8 @@ async function* runAgent(messages, config) {
6090
6206
  finishReason: stepFinish,
6091
6207
  ...config.meteringMetadata ? { metadata: config.meteringMetadata } : {}
6092
6208
  };
6093
- await deliverMetering(config.meter, record2);
6094
- yield { type: "metering", record: record2 };
6209
+ await deliverMetering(config.meter, record3);
6210
+ yield { type: "metering", record: record3 };
6095
6211
  yield { type: "step-finish", step, finishReason: stepFinish, ...stepUsage ? { usage: stepUsage } : {} };
6096
6212
  const assistant = assistantMessage(parts);
6097
6213
  working.push(assistant);
@@ -6185,7 +6301,7 @@ _(Reached the ${maxSteps}-step limit while still working \u2014 this may be inco
6185
6301
  };
6186
6302
  }
6187
6303
  const finishedAt = Date.now();
6188
- const record = {
6304
+ const record2 = {
6189
6305
  scope: "run",
6190
6306
  id: `${runId}:run`,
6191
6307
  runId,
@@ -6203,15 +6319,15 @@ _(Reached the ${maxSteps}-step limit while still working \u2014 this may be inco
6203
6319
  ...reportedModels.size ? { reportedModels: [...reportedModels] } : {},
6204
6320
  ...config.meteringMetadata ? { metadata: config.meteringMetadata } : {}
6205
6321
  };
6206
- await deliverMetering(config.meter, record);
6207
- yield { type: "metering", record };
6322
+ await deliverMetering(config.meter, record2);
6323
+ yield { type: "metering", record: record2 };
6208
6324
  yield { type: "run-finish", runId, finishReason, usage: totalUsage, steps: attemptedSteps };
6209
6325
  } catch (e) {
6210
6326
  const error = toAgentError(e, config.provider.id);
6211
6327
  yield { type: "error", error, recoverable: false };
6212
6328
  const terminalReason = error.kind === "cancelled" ? "cancelled" : "error";
6213
6329
  const finishedAt = Date.now();
6214
- const record = {
6330
+ const record2 = {
6215
6331
  scope: "run",
6216
6332
  id: `${runId}:run`,
6217
6333
  runId,
@@ -6230,8 +6346,8 @@ _(Reached the ${maxSteps}-step limit while still working \u2014 this may be inco
6230
6346
  ...config.meteringMetadata ? { metadata: config.meteringMetadata } : {},
6231
6347
  error: { kind: error.kind, message: error.message }
6232
6348
  };
6233
- await deliverMetering(config.meter, record);
6234
- yield { type: "metering", record };
6349
+ await deliverMetering(config.meter, record2);
6350
+ yield { type: "metering", record: record2 };
6235
6351
  yield { type: "run-finish", runId, finishReason: terminalReason, usage: totalUsage, steps: attemptedSteps };
6236
6352
  }
6237
6353
  }
@@ -6338,9 +6454,16 @@ function createLocalFileStore(key = "superchat:files") {
6338
6454
  try {
6339
6455
  const raw = globalThis.localStorage?.getItem(key) ?? null;
6340
6456
  const parsed = raw ? JSON.parse(raw) : {};
6341
- return typeof parsed === "object" && parsed !== null ? parsed : {};
6457
+ const all = /* @__PURE__ */ Object.create(null);
6458
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6459
+ for (const [id, file2] of Object.entries(parsed)) {
6460
+ const f = file2;
6461
+ if (f && typeof f === "object" && f.ref && typeof f.ref.id === "string" && typeof f.createdAt === "number") all[id] = f;
6462
+ }
6463
+ }
6464
+ return all;
6342
6465
  } catch {
6343
- return {};
6466
+ return /* @__PURE__ */ Object.create(null);
6344
6467
  }
6345
6468
  };
6346
6469
  const write = (all) => {
@@ -6371,11 +6494,57 @@ function createLocalFileStore(key = "superchat:files") {
6371
6494
 
6372
6495
  // src/runtime/threads.ts
6373
6496
  var THREAD_SCHEMA_VERSION = 2;
6497
+ function isObject3(v) {
6498
+ return typeof v === "object" && v !== null && !Array.isArray(v);
6499
+ }
6500
+ function mediaSourceReadable(source) {
6501
+ if (!isObject3(source)) return false;
6502
+ if (source.kind === "url") return typeof source.url === "string";
6503
+ if (source.kind === "base64") return typeof source.data === "string";
6504
+ if (source.kind === "providerFile") return typeof source.id === "string" && typeof source.provider === "string";
6505
+ return false;
6506
+ }
6507
+ function partReadable(p) {
6508
+ if (!isObject3(p) || typeof p.type !== "string") return false;
6509
+ switch (p.type) {
6510
+ case "text":
6511
+ case "reasoning":
6512
+ return typeof p.text === "string";
6513
+ case "image":
6514
+ return mediaSourceReadable(p.source) && (p.mediaType === void 0 || typeof p.mediaType === "string");
6515
+ case "file":
6516
+ return mediaSourceReadable(p.source) && typeof p.mediaType === "string" && (p.filename === void 0 || typeof p.filename === "string");
6517
+ case "audio":
6518
+ return mediaSourceReadable(p.source) && typeof p.mediaType === "string" && (p.transcript === void 0 || typeof p.transcript === "string");
6519
+ case "tool-call":
6520
+ case "tool-result":
6521
+ return typeof p.callId === "string" && typeof p.name === "string";
6522
+ case "artifact":
6523
+ return typeof p.id === "string" && typeof p.kind === "string";
6524
+ default:
6525
+ return true;
6526
+ }
6527
+ }
6528
+ function wellFormed(messages) {
6529
+ const out = [];
6530
+ for (const raw of messages) {
6531
+ const m = raw;
6532
+ if (!m || typeof m !== "object" || typeof m.id !== "string" || typeof m.role !== "string" || !Array.isArray(m.parts)) continue;
6533
+ const parts = m.parts.filter(partReadable);
6534
+ const parentOk = m.parentId === void 0 || m.parentId === null || typeof m.parentId === "string";
6535
+ out.push(parts.length === m.parts.length && parentOk ? m : { ...m, parts, ...parentOk ? {} : { parentId: null } });
6536
+ }
6537
+ return out;
6538
+ }
6374
6539
  function migrate(parsed) {
6375
- if (!parsed || !Array.isArray(parsed.messages) || !parsed.meta) return void 0;
6376
- if (parsed.version === THREAD_SCHEMA_VERSION) return parsed;
6540
+ if (!parsed || !Array.isArray(parsed.messages) || !parsed.meta || typeof parsed.meta.id !== "string") return void 0;
6541
+ if (parsed.version === THREAD_SCHEMA_VERSION) {
6542
+ const messages = wellFormed(parsed.messages);
6543
+ const headKnown = typeof parsed.headId === "string" && messages.some((m) => m.id === parsed.headId);
6544
+ return { ...parsed, messages, headId: parsed.headId === null ? null : headKnown ? parsed.headId : messages.at(-1)?.id ?? null };
6545
+ }
6377
6546
  if (parsed.version === 1) {
6378
- const messages = linkLinear(parsed.messages);
6547
+ const messages = linkLinear(wellFormed(parsed.messages));
6379
6548
  return {
6380
6549
  version: THREAD_SCHEMA_VERSION,
6381
6550
  meta: parsed.meta,
@@ -6572,6 +6741,8 @@ function expireArtifacts(messages) {
6572
6741
 
6573
6742
  // src/memory/memory.ts
6574
6743
  var DEFAULT_STORE_CAP = 500;
6744
+ var MAX_KEY_CHARS = 100;
6745
+ var MAX_VALUE_CHARS2 = 2e3;
6575
6746
  function byRecency2(a, b) {
6576
6747
  return b.updatedAt - a.updatedAt;
6577
6748
  }
@@ -6600,9 +6771,9 @@ function createLocalMemoryStore(storageKey = "superchat:memory", opts = {}) {
6600
6771
  try {
6601
6772
  const raw = globalThis.localStorage?.getItem(storageKey) ?? null;
6602
6773
  const parsed = raw ? JSON.parse(raw) : {};
6603
- return typeof parsed === "object" && parsed !== null ? parsed : {};
6774
+ return typeof parsed === "object" && parsed !== null ? Object.assign(/* @__PURE__ */ Object.create(null), parsed) : /* @__PURE__ */ Object.create(null);
6604
6775
  } catch {
6605
- return {};
6776
+ return /* @__PURE__ */ Object.create(null);
6606
6777
  }
6607
6778
  };
6608
6779
  const write = (all) => {
@@ -6632,15 +6803,20 @@ function createLocalMemoryStore(storageKey = "superchat:memory", opts = {}) {
6632
6803
  }
6633
6804
  };
6634
6805
  }
6806
+ var oneLine = (text4) => String(text4).replace(/\s*[\r\n]+\s*/g, " ");
6807
+ var clip2 = (text4) => {
6808
+ const value = String(text4);
6809
+ return value.length > MAX_VALUE_CHARS2 ? `${value.slice(0, MAX_VALUE_CHARS2)}\u2026` : value;
6810
+ };
6635
6811
  function createMemorySource(store, opts = {}) {
6636
6812
  return {
6637
6813
  id: opts.id ?? "memory",
6638
6814
  async run({ vars }) {
6639
6815
  const entries = (await store.list(vars)).slice(0, opts.maxEntries ?? 50);
6640
6816
  if (!entries.length) return {};
6641
- const text3 = [
6817
+ const text4 = [
6642
6818
  "Things you remember about this user, from earlier conversations:",
6643
- ...entries.map((e) => `- ${e.key}: ${e.value}`),
6819
+ ...entries.map((e) => `- ${oneLine(e.key)}: ${oneLine(clip2(e.value))}`),
6644
6820
  "Apply them without re-asking. Update them with the `remember` tool when they change."
6645
6821
  ].join("\n");
6646
6822
  return {
@@ -6648,8 +6824,8 @@ function createMemorySource(store, opts = {}) {
6648
6824
  {
6649
6825
  id: opts.id ?? "memory",
6650
6826
  kind: "memory",
6651
- text: text3,
6652
- tokens: estimateTokens(text3),
6827
+ text: text4,
6828
+ tokens: estimateTokens(text4),
6653
6829
  priority: opts.priority ?? 500
6654
6830
  }
6655
6831
  ]
@@ -6673,7 +6849,13 @@ function createRememberTool(store) {
6673
6849
  },
6674
6850
  async execute(input, ctx) {
6675
6851
  const { key, value } = input ?? {};
6676
- if (!key) return { output: { ok: false, error: "`key` is required." }, failure: "invalid-input" };
6852
+ const invalid = (error) => ({ output: { ok: false, error }, failure: "invalid-input" });
6853
+ if (typeof key !== "string" || !key.trim()) return invalid("`key` is required.");
6854
+ if (key.length > MAX_KEY_CHARS) return invalid(`\`key\` is too long (${key.length} characters, at most ${MAX_KEY_CHARS}). Use a short slug.`);
6855
+ if (value != null && typeof value !== "string") return invalid("`value` must be a string, or null to forget the key.");
6856
+ if (typeof value === "string" && value.length > MAX_VALUE_CHARS2) {
6857
+ return invalid(`\`value\` is too long (${value.length} characters, at most ${MAX_VALUE_CHARS2}). Remember the fact in a sentence or two.`);
6858
+ }
6677
6859
  if (value == null || value === "") {
6678
6860
  await store.remove(key, ctx.vars);
6679
6861
  return { output: { ok: true, forgot: key } };
@@ -6685,17 +6867,36 @@ function createRememberTool(store) {
6685
6867
  }
6686
6868
 
6687
6869
  // src/retrieval/retrieval.ts
6870
+ function readable(hits) {
6871
+ if (!Array.isArray(hits)) return [];
6872
+ const out = [];
6873
+ for (const h of hits) {
6874
+ if (typeof h !== "object" || h === null) continue;
6875
+ const c = h;
6876
+ if (typeof c.text !== "string" || !c.text.trim()) continue;
6877
+ const str2 = (v) => typeof v === "string" && v ? v : void 0;
6878
+ out.push({
6879
+ id: str2(c.id) ?? (typeof c.id === "number" ? String(c.id) : `hit-${out.length + 1}`),
6880
+ text: c.text,
6881
+ ...str2(c.source) ? { source: str2(c.source) } : {},
6882
+ ...str2(c.title) ? { title: str2(c.title) } : {},
6883
+ ...str2(c.uri) ? { uri: str2(c.uri) } : {},
6884
+ ...typeof c.score === "number" && Number.isFinite(c.score) ? { score: c.score } : {}
6885
+ });
6886
+ }
6887
+ return out;
6888
+ }
6688
6889
  function createRetrievalSource(retriever, opts = {}) {
6689
6890
  return {
6690
6891
  id: opts.id ?? "retrieval",
6691
6892
  async run({ query, vars, signal }) {
6692
6893
  if (query.trim().length < (opts.minQueryLength ?? 8)) return {};
6693
- const chunks = (await retriever.retrieve(query, { limit: opts.limit ?? 5, signal, vars })).slice(
6894
+ const chunks = readable(await retriever.retrieve(query, { limit: opts.limit ?? 5, signal, vars })).slice(
6694
6895
  0,
6695
6896
  opts.limit ?? 5
6696
6897
  );
6697
6898
  if (!chunks.length) return {};
6698
- const text3 = [
6899
+ const text4 = [
6699
6900
  "Reference material retrieved for this question. Ground your answer in it when relevant:",
6700
6901
  ...chunks.map(
6701
6902
  (c, i) => `[${i + 1}] ${c.title ?? c.id}${c.source ? ` (${c.source})` : ""}
@@ -6708,8 +6909,8 @@ ${c.text.trim()}`
6708
6909
  {
6709
6910
  id: opts.id ?? "retrieval",
6710
6911
  kind: "custom",
6711
- text: text3,
6712
- tokens: estimateTokens(text3),
6912
+ text: text4,
6913
+ tokens: estimateTokens(text4),
6713
6914
  priority: opts.priority ?? 400
6714
6915
  }
6715
6916
  ]
@@ -6718,7 +6919,7 @@ ${c.text.trim()}`
6718
6919
  };
6719
6920
  }
6720
6921
  function createKeywordRetriever(docs) {
6721
- const chunks = docs.flatMap(
6922
+ const chunks = docs.filter((doc) => typeof doc === "object" && doc !== null && typeof doc.text === "string").flatMap(
6722
6923
  (doc) => doc.text.split(/\n\s*\n/).map((p) => p.trim()).filter((p) => p.length > 0).map((paragraph, i) => ({
6723
6924
  id: `${doc.id}#${i}`,
6724
6925
  text: paragraph,
@@ -6740,21 +6941,14 @@ function createKeywordRetriever(docs) {
6740
6941
  async retrieve(query, opts = {}) {
6741
6942
  const queryTerms = tokenize(query);
6742
6943
  if (!queryTerms.length) return [];
6743
- const seen = /* @__PURE__ */ new Set();
6744
- const candidates = [];
6745
- for (const term of queryTerms) {
6746
- for (const chunk of invertedIndex.get(term) ?? []) {
6747
- if (!seen.has(chunk)) {
6748
- seen.add(chunk);
6749
- candidates.push(chunk);
6750
- }
6751
- }
6752
- }
6753
- candidates.sort((a, b) => a.idx - b.idx);
6754
- const scored = candidates.map((c) => {
6755
- const hits = queryTerms.filter((t) => c.terms.has(t)).length;
6756
- return { chunk: c, score: hits / Math.sqrt(c.terms.size || 1) };
6757
- }).filter((s) => s.score > 0).sort((a, b) => b.score - a.score).slice(0, opts.limit ?? 5);
6944
+ const queryCounts = /* @__PURE__ */ new Map();
6945
+ for (const term of queryTerms) queryCounts.set(term, (queryCounts.get(term) ?? 0) + 1);
6946
+ const hitsOf = /* @__PURE__ */ new Map();
6947
+ for (const [term, count] of queryCounts) {
6948
+ for (const chunk of invertedIndex.get(term) ?? []) hitsOf.set(chunk, (hitsOf.get(chunk) ?? 0) + count);
6949
+ }
6950
+ const candidates = [...hitsOf.keys()].sort((a, b) => a.idx - b.idx);
6951
+ 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);
6758
6952
  return scored.map(({ chunk, score }) => {
6759
6953
  const { terms: _terms, idx: _idx, ...rest } = chunk;
6760
6954
  return { ...rest, score };
@@ -6788,7 +6982,7 @@ ${body}`);
6788
6982
  }
6789
6983
  }
6790
6984
  if (!blocks.length) return {};
6791
- const text3 = [
6985
+ const text4 = [
6792
6986
  "Current state of the application the user is looking at. This is live \u2014 it reflects the screen right now, not the conversation:",
6793
6987
  ...blocks,
6794
6988
  "Refer to it directly rather than asking the user to repeat what is already on screen."
@@ -6798,8 +6992,8 @@ ${body}`);
6798
6992
  {
6799
6993
  id: opts.id ?? "app-state",
6800
6994
  kind: "environment",
6801
- text: text3,
6802
- tokens: estimateTokens(text3),
6995
+ text: text4,
6996
+ tokens: estimateTokens(text4),
6803
6997
  priority: opts.priority ?? 600
6804
6998
  }
6805
6999
  ]
@@ -6848,6 +7042,15 @@ var McpRpcError = class extends Error {
6848
7042
  this.data = data;
6849
7043
  }
6850
7044
  };
7045
+ var isObject4 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
7046
+ function readTool(raw) {
7047
+ if (!isObject4(raw) || typeof raw.name !== "string" || raw.name === "") return void 0;
7048
+ return {
7049
+ name: raw.name,
7050
+ ...typeof raw.description === "string" ? { description: raw.description } : {},
7051
+ inputSchema: isObject4(raw.inputSchema) ? raw.inputSchema : { type: "object" }
7052
+ };
7053
+ }
6851
7054
  var MAX_TOOL_PAGES = 1e3;
6852
7055
  var McpClient = class {
6853
7056
  transport;
@@ -6890,10 +7093,12 @@ var McpClient = class {
6890
7093
  capabilities: this.onElicit ? { elicitation: {} } : {},
6891
7094
  clientInfo: this.clientInfo
6892
7095
  });
7096
+ const reply = isObject4(result) ? result : {};
7097
+ const info = isObject4(reply.serverInfo) && typeof reply.serverInfo.name === "string" ? reply.serverInfo : void 0;
6893
7098
  await this.post({ jsonrpc: "2.0", method: "notifications/initialized" });
6894
7099
  this.handshake = {
6895
- serverInfo: result.serverInfo ?? { name: "unknown" },
6896
- protocolVersion: result.protocolVersion ?? this.protocolVersion
7100
+ serverInfo: info ? { name: info.name, ...typeof info.version === "string" ? { version: info.version } : {} } : { name: "unknown" },
7101
+ protocolVersion: typeof reply.protocolVersion === "string" ? reply.protocolVersion : this.protocolVersion
6897
7102
  };
6898
7103
  return this.handshake;
6899
7104
  }
@@ -6904,8 +7109,14 @@ var McpClient = class {
6904
7109
  const seen = /* @__PURE__ */ new Set();
6905
7110
  let cursor;
6906
7111
  do {
6907
- const page = await this.rpc("tools/list", cursor ? { cursor } : {}, opts);
6908
- if (Array.isArray(page.tools)) tools.push(...page.tools);
7112
+ const reply = await this.rpc("tools/list", cursor ? { cursor } : {}, opts);
7113
+ const page = isObject4(reply) ? reply : {};
7114
+ if (Array.isArray(page.tools)) {
7115
+ for (const raw of page.tools) {
7116
+ const tool = readTool(raw);
7117
+ if (tool) tools.push(tool);
7118
+ }
7119
+ }
6909
7120
  cursor = typeof page.nextCursor === "string" && page.nextCursor !== "" ? page.nextCursor : void 0;
6910
7121
  if (cursor !== void 0) {
6911
7122
  if (seen.has(cursor) || seen.size >= MAX_TOOL_PAGES) {
@@ -6925,7 +7136,12 @@ var McpClient = class {
6925
7136
  await this.ensureConnected();
6926
7137
  try {
6927
7138
  const result = await this.rpc("tools/call", { name, arguments: args ?? {} }, opts);
6928
- return { ...result, content: result.content ?? [] };
7139
+ if (!isObject4(result)) return { content: [{ type: "text", text: "The MCP server sent no result." }], isError: true };
7140
+ return {
7141
+ ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : {},
7142
+ content: Array.isArray(result.content) ? result.content.filter(isObject4) : [],
7143
+ ...result.isError === true ? { isError: true } : {}
7144
+ };
6929
7145
  } catch (e) {
6930
7146
  if (e instanceof McpRpcError) {
6931
7147
  return { content: [{ type: "text", text: e.message }], isError: true };
@@ -7045,7 +7261,7 @@ function createHttpTransport(opts) {
7045
7261
  // src/mcp/import.ts
7046
7262
  var RESERVED_NAMESPACE = "mcp";
7047
7263
  function sanitizeNamespace(raw) {
7048
- const cleaned = (raw ?? "").replace(/[^a-zA-Z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
7264
+ const cleaned = (typeof raw === "string" ? raw : "").replace(/[^a-zA-Z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
7049
7265
  if (!cleaned || cleaned.toLowerCase() === RESERVED_NAMESPACE) return "srv";
7050
7266
  return cleaned;
7051
7267
  }
@@ -7080,15 +7296,20 @@ async function importMcpTools(client, opts = {}) {
7080
7296
  return out;
7081
7297
  }
7082
7298
  function mapMcpResult(result) {
7083
- if (result.isError) {
7084
- return { output: { error: textOf(result.content) || "MCP tool failed." }, failure: "execution-error" };
7299
+ const content = (Array.isArray(result?.content) ? result.content : []).filter((c) => c !== null && typeof c === "object");
7300
+ if (result?.isError === true) {
7301
+ return { output: { error: textOf(content) || "MCP tool failed." }, failure: "execution-error" };
7085
7302
  }
7086
- if (result.structuredContent !== void 0) {
7303
+ if (result?.structuredContent !== void 0) {
7087
7304
  return { output: result.structuredContent };
7088
7305
  }
7089
- const texts = result.content.filter((c) => c.type === "text");
7090
- const resources = result.content.filter((c) => c.type === "resource");
7091
- const image2 = result.content.find((c) => c.type === "image");
7306
+ const texts = content.filter((c) => c.type === "text" && typeof c.text === "string");
7307
+ const resources = content.filter(
7308
+ (c) => c.type === "resource" && c.resource !== null && typeof c.resource === "object" && typeof c.resource.uri === "string"
7309
+ );
7310
+ const image2 = content.find(
7311
+ (c) => c.type === "image" && typeof c.data === "string" && typeof c.mimeType === "string"
7312
+ );
7092
7313
  let output;
7093
7314
  if (texts.length === 1) {
7094
7315
  output = parseMaybeJson(texts[0].text);
@@ -7096,7 +7317,7 @@ function mapMcpResult(result) {
7096
7317
  output = texts.map((t) => t.text).join("\n");
7097
7318
  }
7098
7319
  if (resources.length) {
7099
- const refs = resources.map((r) => ({ uri: r.resource.uri, ...r.resource.text ? { text: r.resource.text } : {} }));
7320
+ const refs = resources.map((r) => ({ uri: r.resource.uri, ...typeof r.resource.text === "string" && r.resource.text ? { text: r.resource.text } : {} }));
7100
7321
  output = output === void 0 ? { resources: refs } : { text: output, resources: refs };
7101
7322
  }
7102
7323
  if (output === void 0) output = image2 ? "(image result)" : null;
@@ -7170,14 +7391,14 @@ function elicitViaCard(requestCard) {
7170
7391
  return { action: "accept", content };
7171
7392
  };
7172
7393
  }
7173
- var textOf = (content) => content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
7174
- function parseMaybeJson(text3) {
7175
- const trimmed = text3.trim();
7176
- if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return text3;
7394
+ var textOf = (content) => content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
7395
+ function parseMaybeJson(text4) {
7396
+ const trimmed = text4.trim();
7397
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return text4;
7177
7398
  try {
7178
7399
  return JSON.parse(trimmed);
7179
7400
  } catch {
7180
- return text3;
7401
+ return text4;
7181
7402
  }
7182
7403
  }
7183
7404
  export {
@@ -7399,7 +7620,7 @@ export {
7399
7620
  surfaceActionTools,
7400
7621
  surfaceCardId,
7401
7622
  tableCard,
7402
- text,
7623
+ text2 as text,
7403
7624
  threadSnapshot,
7404
7625
  timelineCard,
7405
7626
  toA2uiMessages,