@supersolutions/super-chat-core 0.5.0 → 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/anthropic.js +2 -2
- package/dist/{chunk-32DPF33V.js → chunk-7G4U4NTL.js} +62 -18
- package/dist/chunk-7G4U4NTL.js.map +1 -0
- package/dist/{chunk-JMM3X3GB.js → chunk-KUB5GKAM.js} +58 -41
- package/dist/chunk-KUB5GKAM.js.map +1 -0
- package/dist/{chunk-MHGENDQX.js → chunk-WFU4HXUG.js} +188 -101
- package/dist/chunk-WFU4HXUG.js.map +1 -0
- package/dist/index.d.ts +13 -7
- package/dist/index.js +408 -201
- package/dist/index.js.map +1 -1
- package/dist/openai.d.ts +0 -5
- package/dist/openai.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-32DPF33V.js.map +0 -1
- package/dist/chunk-JMM3X3GB.js.map +0 -1
- package/dist/chunk-MHGENDQX.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -8,11 +8,11 @@ import {
|
|
|
8
8
|
isTerminal,
|
|
9
9
|
reap,
|
|
10
10
|
resumeJobs
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-WFU4HXUG.js";
|
|
12
12
|
import {
|
|
13
13
|
buildAnthropicRequest,
|
|
14
14
|
createAnthropicProvider
|
|
15
|
-
} from "./chunk-
|
|
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-
|
|
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
|
|
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" ? [
|
|
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 = (
|
|
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(
|
|
165
|
-
const m = FENCE_OPEN.exec(
|
|
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(
|
|
173
|
-
const m = /^ {0,3}(`{3,}|~{3,})\s*$/.exec(
|
|
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,
|
|
179
|
-
if (construct === "list") return LIST_ITEM.test(
|
|
180
|
-
if (construct === "quote") return QUOTE.test(
|
|
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 = (
|
|
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 = (
|
|
312
|
-
const longest = [...
|
|
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(
|
|
329
|
+
function withQuotes(text4, quotes) {
|
|
328
330
|
const prefix = formatQuotes(quotes);
|
|
329
|
-
if (!prefix) return
|
|
330
|
-
return
|
|
331
|
+
if (!prefix) return text4;
|
|
332
|
+
return text4.trim() ? `${prefix}
|
|
331
333
|
|
|
332
|
-
${
|
|
334
|
+
${text4}` : prefix;
|
|
333
335
|
}
|
|
334
336
|
function quotesOf(metadata) {
|
|
335
337
|
const raw = metadata?.[QUOTES_METADATA_KEY];
|
|
@@ -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.
|
|
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
|
|
633
|
-
|
|
634
|
-
|
|
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
|
|
637
|
-
|
|
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:
|
|
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
|
-
...
|
|
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(
|
|
733
|
-
if (!
|
|
746
|
+
function estimateTokens(text4) {
|
|
747
|
+
if (!text4) return 0;
|
|
734
748
|
let cjk = 0;
|
|
735
749
|
let other = 0;
|
|
736
|
-
for (const ch of
|
|
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
|
-
|
|
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
|
|
1035
|
+
const text4 = await renderSkill(skill, ctx);
|
|
1018
1036
|
out.push({
|
|
1019
1037
|
id: skill.id,
|
|
1020
1038
|
name: skill.name,
|
|
1021
|
-
text:
|
|
1022
|
-
tokens: estimateTokens(
|
|
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
|
|
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:
|
|
1035
|
-
tokens: estimateTokens(
|
|
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
|
|
1187
|
+
const fitted = [summaryMessage, ...trimmed.messages];
|
|
1169
1188
|
return {
|
|
1170
|
-
messages:
|
|
1189
|
+
messages: fitted,
|
|
1171
1190
|
strategy: "summarize",
|
|
1172
1191
|
droppedCount: older.length + trimmed.droppedCount,
|
|
1173
1192
|
tokensBefore,
|
|
1174
|
-
tokensAfter: countMessagesTokens(
|
|
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
|
|
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}: ${
|
|
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
|
|
1226
|
-
layers.push({ id: "identity", kind: "identity", text:
|
|
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:
|
|
1598
|
+
if (typeof parsed !== "object" || parsed === null) return { docs: record(), past: record() };
|
|
1574
1599
|
const p = parsed;
|
|
1575
|
-
|
|
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:
|
|
1610
|
+
return { docs: record(), past: record() };
|
|
1578
1611
|
}
|
|
1579
1612
|
};
|
|
1580
1613
|
const write = (all) => {
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1614
|
+
const store = globalThis.localStorage;
|
|
1615
|
+
if (!store) {
|
|
1616
|
+
refused2 = all;
|
|
1617
|
+
return;
|
|
1584
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
|
+
}
|
|
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
|
|
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:
|
|
1799
|
-
text:
|
|
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();
|
|
@@ -3192,35 +3266,44 @@ var confirmCard = {
|
|
|
3192
3266
|
return ok;
|
|
3193
3267
|
}
|
|
3194
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
|
+
});
|
|
3195
3278
|
var BUILTIN_CARDS = [
|
|
3196
3279
|
// structured data
|
|
3197
|
-
tableCard,
|
|
3198
|
-
statsCard,
|
|
3199
|
-
comparisonCard,
|
|
3200
|
-
keyValueCard,
|
|
3201
|
-
treeCard,
|
|
3280
|
+
/* @__PURE__ */ typed(tableCard),
|
|
3281
|
+
/* @__PURE__ */ typed(statsCard),
|
|
3282
|
+
/* @__PURE__ */ typed(comparisonCard),
|
|
3283
|
+
/* @__PURE__ */ typed(keyValueCard),
|
|
3284
|
+
/* @__PURE__ */ typed(treeCard),
|
|
3202
3285
|
// quantitative shape
|
|
3203
|
-
chartCard,
|
|
3204
|
-
funnelCard,
|
|
3205
|
-
gaugeCard,
|
|
3286
|
+
/* @__PURE__ */ typed(chartCard),
|
|
3287
|
+
/* @__PURE__ */ typed(funnelCard),
|
|
3288
|
+
/* @__PURE__ */ typed(gaugeCard),
|
|
3206
3289
|
// sequence and state
|
|
3207
|
-
timelineCard,
|
|
3208
|
-
progressCard,
|
|
3209
|
-
checklistCard,
|
|
3290
|
+
/* @__PURE__ */ typed(timelineCard),
|
|
3291
|
+
/* @__PURE__ */ typed(progressCard),
|
|
3292
|
+
/* @__PURE__ */ typed(checklistCard),
|
|
3210
3293
|
// prose and evidence
|
|
3211
|
-
markdownCard,
|
|
3212
|
-
documentCard,
|
|
3213
|
-
calloutCard,
|
|
3214
|
-
citationsCard,
|
|
3215
|
-
codeCard,
|
|
3216
|
-
diffCard,
|
|
3217
|
-
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),
|
|
3218
3301
|
// interactive — these ask the user and pause the run
|
|
3219
|
-
choiceCard,
|
|
3220
|
-
formCard,
|
|
3221
|
-
confirmCard,
|
|
3222
|
-
editReviewCard,
|
|
3223
|
-
emailCard
|
|
3302
|
+
/* @__PURE__ */ typed(choiceCard),
|
|
3303
|
+
/* @__PURE__ */ typed(formCard),
|
|
3304
|
+
/* @__PURE__ */ typed(confirmCard),
|
|
3305
|
+
/* @__PURE__ */ typed(editReviewCard),
|
|
3306
|
+
/* @__PURE__ */ typed(emailCard)
|
|
3224
3307
|
];
|
|
3225
3308
|
|
|
3226
3309
|
// src/surfaces/types.ts
|
|
@@ -3418,12 +3501,12 @@ function checkSchema(schema, value, path = "", opts = {}) {
|
|
|
3418
3501
|
}
|
|
3419
3502
|
}
|
|
3420
3503
|
if (typeOf(v) === "object") {
|
|
3421
|
-
const
|
|
3504
|
+
const record2 = v;
|
|
3422
3505
|
for (const key of s.required ?? []) {
|
|
3423
|
-
if (
|
|
3506
|
+
if (record2[key] === void 0) out.push({ path: `${at}/${key}`, message: `${at ? `${at}/` : ""}${key} is required.` });
|
|
3424
3507
|
}
|
|
3425
3508
|
const properties = s.properties ?? {};
|
|
3426
|
-
for (const [key, item] of Object.entries(
|
|
3509
|
+
for (const [key, item] of Object.entries(record2)) {
|
|
3427
3510
|
const propSchema = properties[key];
|
|
3428
3511
|
if (propSchema) walk(propSchema, item, `${at}/${key}`);
|
|
3429
3512
|
else if (s.additionalProperties === false) {
|
|
@@ -3660,7 +3743,7 @@ var props = (properties, required = []) => ({
|
|
|
3660
3743
|
required,
|
|
3661
3744
|
additionalProperties: false
|
|
3662
3745
|
});
|
|
3663
|
-
var
|
|
3746
|
+
var text3 = (description) => ({ type: "string", ...description ? { description } : {} });
|
|
3664
3747
|
var SURFACE_PRIMITIVES = [
|
|
3665
3748
|
{
|
|
3666
3749
|
name: "Stack",
|
|
@@ -3699,8 +3782,8 @@ var SURFACE_PRIMITIVES = [
|
|
|
3699
3782
|
summary: "A titled group of children.",
|
|
3700
3783
|
props: props(
|
|
3701
3784
|
{
|
|
3702
|
-
title:
|
|
3703
|
-
description:
|
|
3785
|
+
title: text3(),
|
|
3786
|
+
description: text3(),
|
|
3704
3787
|
tone: { type: "string", enum: TONES },
|
|
3705
3788
|
children: childIds
|
|
3706
3789
|
},
|
|
@@ -3714,7 +3797,7 @@ var SURFACE_PRIMITIVES = [
|
|
|
3714
3797
|
summary: "Switch between named panels. Keyboard accessible.",
|
|
3715
3798
|
props: props(
|
|
3716
3799
|
{
|
|
3717
|
-
label:
|
|
3800
|
+
label: text3("Names the tab list for screen readers."),
|
|
3718
3801
|
value: { ...boundValue, description: "Optional binding for the selected tab id." },
|
|
3719
3802
|
tabs: fixed({
|
|
3720
3803
|
type: "array",
|
|
@@ -3740,7 +3823,7 @@ var SURFACE_PRIMITIVES = [
|
|
|
3740
3823
|
{
|
|
3741
3824
|
items: { type: "array", description: "A $path or $query that yields an array." },
|
|
3742
3825
|
child: childId("The template component rendered once per row."),
|
|
3743
|
-
emptyText:
|
|
3826
|
+
emptyText: text3("Shown when there are no rows."),
|
|
3744
3827
|
gap: { type: "string", enum: GAPS }
|
|
3745
3828
|
},
|
|
3746
3829
|
["items", "child"]
|
|
@@ -3768,12 +3851,12 @@ var SURFACE_PRIMITIVES = [
|
|
|
3768
3851
|
summary: "One headline number with a label and optional change.",
|
|
3769
3852
|
props: props(
|
|
3770
3853
|
{
|
|
3771
|
-
label:
|
|
3854
|
+
label: text3(),
|
|
3772
3855
|
value: { type: ["string", "number", "null"] },
|
|
3773
3856
|
format: { type: "string", enum: FORMATS2 },
|
|
3774
3857
|
delta: { type: "number" },
|
|
3775
3858
|
deltaFormat: { type: "string", enum: FORMATS2 },
|
|
3776
|
-
hint:
|
|
3859
|
+
hint: text3(),
|
|
3777
3860
|
tone: { type: "string", enum: TONES }
|
|
3778
3861
|
},
|
|
3779
3862
|
["label", "value"]
|
|
@@ -3789,13 +3872,13 @@ var SURFACE_PRIMITIVES = [
|
|
|
3789
3872
|
name: "Image",
|
|
3790
3873
|
category: "display",
|
|
3791
3874
|
summary: "An http(s) image with required alt text.",
|
|
3792
|
-
props: props({ src:
|
|
3875
|
+
props: props({ src: text3(), alt: text3(), caption: text3() }, ["src", "alt"])
|
|
3793
3876
|
},
|
|
3794
3877
|
{
|
|
3795
3878
|
name: "Link",
|
|
3796
3879
|
category: "display",
|
|
3797
3880
|
summary: "An http(s) link that opens in a new tab.",
|
|
3798
|
-
props: props({ text:
|
|
3881
|
+
props: props({ text: text3(), href: text3() }, ["text", "href"])
|
|
3799
3882
|
},
|
|
3800
3883
|
{
|
|
3801
3884
|
name: "Field",
|
|
@@ -3803,11 +3886,11 @@ var SURFACE_PRIMITIVES = [
|
|
|
3803
3886
|
summary: "Text, number, date or multi-line input bound to the data model.",
|
|
3804
3887
|
props: props(
|
|
3805
3888
|
{
|
|
3806
|
-
label:
|
|
3889
|
+
label: text3(),
|
|
3807
3890
|
value: boundValue,
|
|
3808
3891
|
type: { type: "string", enum: ["text", "number", "date", "textarea"] },
|
|
3809
|
-
placeholder:
|
|
3810
|
-
helper:
|
|
3892
|
+
placeholder: text3(),
|
|
3893
|
+
helper: text3(),
|
|
3811
3894
|
min: { type: "number" },
|
|
3812
3895
|
max: { type: "number" },
|
|
3813
3896
|
step: { type: "number" }
|
|
@@ -3821,7 +3904,7 @@ var SURFACE_PRIMITIVES = [
|
|
|
3821
3904
|
summary: "Choose one option; writes its value to the data model.",
|
|
3822
3905
|
props: props(
|
|
3823
3906
|
{
|
|
3824
|
-
label:
|
|
3907
|
+
label: text3(),
|
|
3825
3908
|
value: boundValue,
|
|
3826
3909
|
options: {
|
|
3827
3910
|
type: "array",
|
|
@@ -3832,7 +3915,7 @@ var SURFACE_PRIMITIVES = [
|
|
|
3832
3915
|
additionalProperties: false
|
|
3833
3916
|
}
|
|
3834
3917
|
},
|
|
3835
|
-
helper:
|
|
3918
|
+
helper: text3()
|
|
3836
3919
|
},
|
|
3837
3920
|
["label", "value", "options"]
|
|
3838
3921
|
)
|
|
@@ -3841,7 +3924,7 @@ var SURFACE_PRIMITIVES = [
|
|
|
3841
3924
|
name: "Toggle",
|
|
3842
3925
|
category: "input",
|
|
3843
3926
|
summary: "An on/off switch bound to a boolean.",
|
|
3844
|
-
props: props({ label:
|
|
3927
|
+
props: props({ label: text3(), value: boundValue, helper: text3() }, ["label", "value"])
|
|
3845
3928
|
},
|
|
3846
3929
|
{
|
|
3847
3930
|
name: "Slider",
|
|
@@ -3849,7 +3932,7 @@ var SURFACE_PRIMITIVES = [
|
|
|
3849
3932
|
summary: "Pick a number in a range.",
|
|
3850
3933
|
props: props(
|
|
3851
3934
|
{
|
|
3852
|
-
label:
|
|
3935
|
+
label: text3(),
|
|
3853
3936
|
value: boundValue,
|
|
3854
3937
|
min: { type: "number" },
|
|
3855
3938
|
max: { type: "number" },
|
|
@@ -3865,7 +3948,7 @@ var SURFACE_PRIMITIVES = [
|
|
|
3865
3948
|
summary: "Runs one action when pressed: set local state, call an allowed tool, or send the agent an event.",
|
|
3866
3949
|
props: props(
|
|
3867
3950
|
{
|
|
3868
|
-
label:
|
|
3951
|
+
label: text3(),
|
|
3869
3952
|
action: ACTION_SCHEMA,
|
|
3870
3953
|
variant: { type: "string", enum: ["primary", "secondary", "ghost", "danger"] },
|
|
3871
3954
|
disabledWhen: CONDITION_SCHEMA
|
|
@@ -3980,40 +4063,40 @@ function validateSurfaceAction(action, componentId, ctx) {
|
|
|
3980
4063
|
const extra = Object.keys(action).filter((k) => !allowed.includes(k));
|
|
3981
4064
|
return extra.length ? bad(`action has no "${extra[0]}". Actions cannot carry code or URLs.`, `Allowed keys: ${allowed.join(", ")}.`) : [];
|
|
3982
4065
|
};
|
|
3983
|
-
const
|
|
3984
|
-
switch (
|
|
4066
|
+
const typed2 = action;
|
|
4067
|
+
switch (typed2.type) {
|
|
3985
4068
|
case "set": {
|
|
3986
4069
|
const extra = onlyKeys(["type", "updates"]);
|
|
3987
4070
|
if (extra.length) return extra;
|
|
3988
|
-
if (!Array.isArray(
|
|
4071
|
+
if (!Array.isArray(typed2.updates) || !typed2.updates.length || typed2.updates.length > SURFACE_LIMITS.actionUpdates) {
|
|
3989
4072
|
return bad(`set needs 1 to ${SURFACE_LIMITS.actionUpdates} updates.`, 'Send "updates": [{ "path": "/a", "value": 1 }].');
|
|
3990
4073
|
}
|
|
3991
|
-
for (const update of
|
|
4074
|
+
for (const update of typed2.updates) {
|
|
3992
4075
|
if (!isObject(update) || !parsePointer(update.path)) return bad("Each update needs a JSON Pointer `path`.", 'Send { "path": "/a", "value": 1 }.');
|
|
3993
4076
|
}
|
|
3994
|
-
return bindingIssues(
|
|
4077
|
+
return bindingIssues(typed2.updates, componentId);
|
|
3995
4078
|
}
|
|
3996
4079
|
case "tool": {
|
|
3997
4080
|
const extra = onlyKeys(["type", "tool", "args", "resultPath"]);
|
|
3998
4081
|
if (extra.length) return extra;
|
|
3999
|
-
if (typeof
|
|
4000
|
-
if (
|
|
4001
|
-
if (
|
|
4002
|
-
if (ctx.actionTools && !ctx.actionTools.includes(
|
|
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)) {
|
|
4003
4086
|
return bad(
|
|
4004
|
-
`Tool "${
|
|
4087
|
+
`Tool "${typed2.tool}" is not available to this surface.`,
|
|
4005
4088
|
ctx.actionTools.length ? `Available: ${ctx.actionTools.slice(0, 24).join(", ")}.` : 'No tools are available; use an "event" action instead.',
|
|
4006
4089
|
"tool-not-allowed"
|
|
4007
4090
|
);
|
|
4008
4091
|
}
|
|
4009
|
-
return bindingIssues(
|
|
4092
|
+
return bindingIssues(typed2.args, componentId);
|
|
4010
4093
|
}
|
|
4011
4094
|
case "event": {
|
|
4012
4095
|
const extra = onlyKeys(["type", "name", "context"]);
|
|
4013
4096
|
if (extra.length) return extra;
|
|
4014
|
-
if (!isSurfaceId(
|
|
4015
|
-
if (
|
|
4016
|
-
return bindingIssues(
|
|
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);
|
|
4017
4100
|
}
|
|
4018
4101
|
default:
|
|
4019
4102
|
return bad(`Unknown action type ${JSON.stringify(action.type)}.`, closed);
|
|
@@ -4675,11 +4758,11 @@ function createSurfaceContextSource() {
|
|
|
4675
4758
|
run({ messages }) {
|
|
4676
4759
|
const live = Object.values(foldSurfaces(messages)).filter((s) => !s.deleted && !s.expired);
|
|
4677
4760
|
if (!live.length) return {};
|
|
4678
|
-
const
|
|
4761
|
+
const text4 = [
|
|
4679
4762
|
"Surfaces on screen. Call readSurface for their current state before relying on it:",
|
|
4680
4763
|
...live.map((s) => `- ${s.surfaceId}${s.title ? ` (${s.title})` : ""}, revision ${s.revision}`)
|
|
4681
4764
|
].join("\n");
|
|
4682
|
-
return { layers: [{ id: "surfaces", kind: "custom", text:
|
|
4765
|
+
return { layers: [{ id: "surfaces", kind: "custom", text: text4, tokens: estimateTokens(text4), priority: 400 }] };
|
|
4683
4766
|
}
|
|
4684
4767
|
};
|
|
4685
4768
|
}
|
|
@@ -4718,12 +4801,12 @@ var EventChannel = class {
|
|
|
4718
4801
|
var MAX_FIELDS = 6;
|
|
4719
4802
|
var MAX_VALUE_CHARS = 160;
|
|
4720
4803
|
var MAX_DESCRIPTION_CHARS = 240;
|
|
4721
|
-
var clip = (
|
|
4804
|
+
var clip = (text4, max) => text4.length > max ? `${text4.slice(0, max - 1)}\u2026` : text4;
|
|
4722
4805
|
function humanizeFieldName(key) {
|
|
4723
4806
|
const words = key.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[\s_\-.]+/).filter(Boolean).map((word) => word.toLowerCase());
|
|
4724
4807
|
if (words.length > 1 && (words[words.length - 1] === "id" || words[words.length - 1] === "ids")) words.pop();
|
|
4725
|
-
const
|
|
4726
|
-
return
|
|
4808
|
+
const text4 = words.join(" ");
|
|
4809
|
+
return text4 ? text4.charAt(0).toUpperCase() + text4.slice(1) : key;
|
|
4727
4810
|
}
|
|
4728
4811
|
function plainValue(value) {
|
|
4729
4812
|
if (typeof value === "string") return value.trim() ? clip(value.trim(), MAX_VALUE_CHARS) : void 0;
|
|
@@ -4737,9 +4820,9 @@ function plainValue(value) {
|
|
|
4737
4820
|
return void 0;
|
|
4738
4821
|
}
|
|
4739
4822
|
function firstSentence(description) {
|
|
4740
|
-
const
|
|
4741
|
-
const end =
|
|
4742
|
-
return clip(end === -1 ?
|
|
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);
|
|
4743
4826
|
}
|
|
4744
4827
|
function fieldsOf(input) {
|
|
4745
4828
|
if (input === void 0 || input === null) return [];
|
|
@@ -4876,6 +4959,16 @@ async function executeToolCall(call, opts) {
|
|
|
4876
4959
|
card = { ...embedded, callId: call.callId };
|
|
4877
4960
|
opts.onCard?.(card);
|
|
4878
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
|
+
}
|
|
4879
4972
|
return {
|
|
4880
4973
|
callId: call.callId,
|
|
4881
4974
|
name: call.name,
|
|
@@ -4898,6 +4991,15 @@ async function executeToolCall(call, opts) {
|
|
|
4898
4991
|
settled = true;
|
|
4899
4992
|
}
|
|
4900
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
|
+
}
|
|
4901
5003
|
var NOT_ABOUT_INPUT = /* @__PURE__ */ new Set(["denied", "timeout", "not-found"]);
|
|
4902
5004
|
var MAX_DESCRIBED = 200;
|
|
4903
5005
|
function explainMissingInput(tool, input, output, failure) {
|
|
@@ -4966,13 +5068,13 @@ function combineMeteringSources(sources) {
|
|
|
4966
5068
|
const unique = new Set(sources);
|
|
4967
5069
|
return unique.size === 1 ? sources[0] : "mixed";
|
|
4968
5070
|
}
|
|
4969
|
-
async function deliverMetering(sink,
|
|
5071
|
+
async function deliverMetering(sink, record2) {
|
|
4970
5072
|
if (!sink) return;
|
|
4971
5073
|
try {
|
|
4972
|
-
await sink.record(
|
|
5074
|
+
await sink.record(record2);
|
|
4973
5075
|
} catch (error) {
|
|
4974
5076
|
try {
|
|
4975
|
-
await sink.onError?.(error,
|
|
5077
|
+
await sink.onError?.(error, record2);
|
|
4976
5078
|
} catch {
|
|
4977
5079
|
}
|
|
4978
5080
|
}
|
|
@@ -5031,7 +5133,7 @@ async function* runSurfaceToolAction(config) {
|
|
|
5031
5133
|
const outcome2 = await running;
|
|
5032
5134
|
const finishedAt = Date.now();
|
|
5033
5135
|
const finishReason = outcome2.failure === "denied" && config.signal?.aborted ? "cancelled" : "stop";
|
|
5034
|
-
const
|
|
5136
|
+
const record2 = {
|
|
5035
5137
|
scope: "run",
|
|
5036
5138
|
id: `${runId}:run`,
|
|
5037
5139
|
runId,
|
|
@@ -5048,8 +5150,8 @@ async function* runSurfaceToolAction(config) {
|
|
|
5048
5150
|
finishReason,
|
|
5049
5151
|
metadata: { ...config.meteringMetadata, trigger: "surface-action", surfaceId: config.surfaceId, componentId: config.componentId, tool: config.tool.name }
|
|
5050
5152
|
};
|
|
5051
|
-
await deliverMetering(config.meter,
|
|
5052
|
-
yield { type: "metering", record };
|
|
5153
|
+
await deliverMetering(config.meter, record2);
|
|
5154
|
+
yield { type: "metering", record: record2 };
|
|
5053
5155
|
yield { type: "run-finish", runId, finishReason, usage: {}, steps: 0 };
|
|
5054
5156
|
}
|
|
5055
5157
|
|
|
@@ -5089,7 +5191,7 @@ function toComponents(component, rename) {
|
|
|
5089
5191
|
case "Stack":
|
|
5090
5192
|
return [{ ...base, component: rest["direction"] === "horizontal" ? "Row" : "Column", children, ...rest["justify"] ? { justify: rest["justify"] === "between" ? "spaceBetween" : rest["justify"] } : {}, ...rest["align"] ? { align: rest["align"] } : {} }];
|
|
5091
5193
|
case "Text":
|
|
5092
|
-
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 } : {} }];
|
|
5093
5195
|
case "Image":
|
|
5094
5196
|
return [{ ...base, component: "Image", url: props2["src"] }];
|
|
5095
5197
|
case "Divider":
|
|
@@ -5294,9 +5396,9 @@ function setOwn(target, key, value) {
|
|
|
5294
5396
|
if (key === "__proto__") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
|
|
5295
5397
|
else target[key] = value;
|
|
5296
5398
|
}
|
|
5297
|
-
function visible(
|
|
5298
|
-
const last =
|
|
5299
|
-
return last >= 55296 && last <= 56319 ?
|
|
5399
|
+
function visible(text4) {
|
|
5400
|
+
const last = text4.charCodeAt(text4.length - 1);
|
|
5401
|
+
return last >= 55296 && last <= 56319 ? text4.slice(0, -1) : text4;
|
|
5300
5402
|
}
|
|
5301
5403
|
var PartialJsonParser = class {
|
|
5302
5404
|
stack = [];
|
|
@@ -5525,9 +5627,9 @@ var PartialJsonParser = class {
|
|
|
5525
5627
|
return i;
|
|
5526
5628
|
}
|
|
5527
5629
|
};
|
|
5528
|
-
function parsePartialJson(
|
|
5630
|
+
function parsePartialJson(text4) {
|
|
5529
5631
|
const parser = new PartialJsonParser();
|
|
5530
|
-
parser.push(
|
|
5632
|
+
parser.push(text4);
|
|
5531
5633
|
return { value: parser.snapshot(), complete: parser.complete };
|
|
5532
5634
|
}
|
|
5533
5635
|
|
|
@@ -5855,8 +5957,8 @@ function reduceRunEvent(state, event) {
|
|
|
5855
5957
|
return state;
|
|
5856
5958
|
}
|
|
5857
5959
|
}
|
|
5858
|
-
function without(
|
|
5859
|
-
const next = { ...
|
|
5960
|
+
function without(record2, key) {
|
|
5961
|
+
const next = { ...record2 };
|
|
5860
5962
|
delete next[key];
|
|
5861
5963
|
return next;
|
|
5862
5964
|
}
|
|
@@ -6053,7 +6155,7 @@ async function* runAgent(messages, config) {
|
|
|
6053
6155
|
yield { type: "usage", usage: stepUsage };
|
|
6054
6156
|
}
|
|
6055
6157
|
const finishedAt3 = Date.now();
|
|
6056
|
-
const
|
|
6158
|
+
const record4 = {
|
|
6057
6159
|
scope: "step",
|
|
6058
6160
|
id: `${runId}:step:${step}`,
|
|
6059
6161
|
runId,
|
|
@@ -6072,8 +6174,8 @@ async function* runAgent(messages, config) {
|
|
|
6072
6174
|
...config.meteringMetadata ? { metadata: config.meteringMetadata } : {},
|
|
6073
6175
|
error: { kind: error.kind, message: error.message }
|
|
6074
6176
|
};
|
|
6075
|
-
await deliverMetering(config.meter,
|
|
6076
|
-
yield { type: "metering", record:
|
|
6177
|
+
await deliverMetering(config.meter, record4);
|
|
6178
|
+
yield { type: "metering", record: record4 };
|
|
6077
6179
|
throw error;
|
|
6078
6180
|
}
|
|
6079
6181
|
previousResponseId = responseId;
|
|
@@ -6085,7 +6187,7 @@ async function* runAgent(messages, config) {
|
|
|
6085
6187
|
meteringSources.push(source);
|
|
6086
6188
|
if (reportedModel) reportedModels.add(reportedModel);
|
|
6087
6189
|
const finishedAt2 = Date.now();
|
|
6088
|
-
const
|
|
6190
|
+
const record3 = {
|
|
6089
6191
|
scope: "step",
|
|
6090
6192
|
id: `${runId}:step:${step}`,
|
|
6091
6193
|
runId,
|
|
@@ -6104,8 +6206,8 @@ async function* runAgent(messages, config) {
|
|
|
6104
6206
|
finishReason: stepFinish,
|
|
6105
6207
|
...config.meteringMetadata ? { metadata: config.meteringMetadata } : {}
|
|
6106
6208
|
};
|
|
6107
|
-
await deliverMetering(config.meter,
|
|
6108
|
-
yield { type: "metering", record:
|
|
6209
|
+
await deliverMetering(config.meter, record3);
|
|
6210
|
+
yield { type: "metering", record: record3 };
|
|
6109
6211
|
yield { type: "step-finish", step, finishReason: stepFinish, ...stepUsage ? { usage: stepUsage } : {} };
|
|
6110
6212
|
const assistant = assistantMessage(parts);
|
|
6111
6213
|
working.push(assistant);
|
|
@@ -6199,7 +6301,7 @@ _(Reached the ${maxSteps}-step limit while still working \u2014 this may be inco
|
|
|
6199
6301
|
};
|
|
6200
6302
|
}
|
|
6201
6303
|
const finishedAt = Date.now();
|
|
6202
|
-
const
|
|
6304
|
+
const record2 = {
|
|
6203
6305
|
scope: "run",
|
|
6204
6306
|
id: `${runId}:run`,
|
|
6205
6307
|
runId,
|
|
@@ -6217,15 +6319,15 @@ _(Reached the ${maxSteps}-step limit while still working \u2014 this may be inco
|
|
|
6217
6319
|
...reportedModels.size ? { reportedModels: [...reportedModels] } : {},
|
|
6218
6320
|
...config.meteringMetadata ? { metadata: config.meteringMetadata } : {}
|
|
6219
6321
|
};
|
|
6220
|
-
await deliverMetering(config.meter,
|
|
6221
|
-
yield { type: "metering", record };
|
|
6322
|
+
await deliverMetering(config.meter, record2);
|
|
6323
|
+
yield { type: "metering", record: record2 };
|
|
6222
6324
|
yield { type: "run-finish", runId, finishReason, usage: totalUsage, steps: attemptedSteps };
|
|
6223
6325
|
} catch (e) {
|
|
6224
6326
|
const error = toAgentError(e, config.provider.id);
|
|
6225
6327
|
yield { type: "error", error, recoverable: false };
|
|
6226
6328
|
const terminalReason = error.kind === "cancelled" ? "cancelled" : "error";
|
|
6227
6329
|
const finishedAt = Date.now();
|
|
6228
|
-
const
|
|
6330
|
+
const record2 = {
|
|
6229
6331
|
scope: "run",
|
|
6230
6332
|
id: `${runId}:run`,
|
|
6231
6333
|
runId,
|
|
@@ -6244,8 +6346,8 @@ _(Reached the ${maxSteps}-step limit while still working \u2014 this may be inco
|
|
|
6244
6346
|
...config.meteringMetadata ? { metadata: config.meteringMetadata } : {},
|
|
6245
6347
|
error: { kind: error.kind, message: error.message }
|
|
6246
6348
|
};
|
|
6247
|
-
await deliverMetering(config.meter,
|
|
6248
|
-
yield { type: "metering", record };
|
|
6349
|
+
await deliverMetering(config.meter, record2);
|
|
6350
|
+
yield { type: "metering", record: record2 };
|
|
6249
6351
|
yield { type: "run-finish", runId, finishReason: terminalReason, usage: totalUsage, steps: attemptedSteps };
|
|
6250
6352
|
}
|
|
6251
6353
|
}
|
|
@@ -6352,9 +6454,16 @@ function createLocalFileStore(key = "superchat:files") {
|
|
|
6352
6454
|
try {
|
|
6353
6455
|
const raw = globalThis.localStorage?.getItem(key) ?? null;
|
|
6354
6456
|
const parsed = raw ? JSON.parse(raw) : {};
|
|
6355
|
-
|
|
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;
|
|
6356
6465
|
} catch {
|
|
6357
|
-
return
|
|
6466
|
+
return /* @__PURE__ */ Object.create(null);
|
|
6358
6467
|
}
|
|
6359
6468
|
};
|
|
6360
6469
|
const write = (all) => {
|
|
@@ -6385,11 +6494,57 @@ function createLocalFileStore(key = "superchat:files") {
|
|
|
6385
6494
|
|
|
6386
6495
|
// src/runtime/threads.ts
|
|
6387
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
|
+
}
|
|
6388
6539
|
function migrate(parsed) {
|
|
6389
|
-
if (!parsed || !Array.isArray(parsed.messages) || !parsed.meta) return void 0;
|
|
6390
|
-
if (parsed.version === THREAD_SCHEMA_VERSION)
|
|
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
|
+
}
|
|
6391
6546
|
if (parsed.version === 1) {
|
|
6392
|
-
const messages = linkLinear(parsed.messages);
|
|
6547
|
+
const messages = linkLinear(wellFormed(parsed.messages));
|
|
6393
6548
|
return {
|
|
6394
6549
|
version: THREAD_SCHEMA_VERSION,
|
|
6395
6550
|
meta: parsed.meta,
|
|
@@ -6586,6 +6741,8 @@ function expireArtifacts(messages) {
|
|
|
6586
6741
|
|
|
6587
6742
|
// src/memory/memory.ts
|
|
6588
6743
|
var DEFAULT_STORE_CAP = 500;
|
|
6744
|
+
var MAX_KEY_CHARS = 100;
|
|
6745
|
+
var MAX_VALUE_CHARS2 = 2e3;
|
|
6589
6746
|
function byRecency2(a, b) {
|
|
6590
6747
|
return b.updatedAt - a.updatedAt;
|
|
6591
6748
|
}
|
|
@@ -6614,9 +6771,9 @@ function createLocalMemoryStore(storageKey = "superchat:memory", opts = {}) {
|
|
|
6614
6771
|
try {
|
|
6615
6772
|
const raw = globalThis.localStorage?.getItem(storageKey) ?? null;
|
|
6616
6773
|
const parsed = raw ? JSON.parse(raw) : {};
|
|
6617
|
-
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);
|
|
6618
6775
|
} catch {
|
|
6619
|
-
return
|
|
6776
|
+
return /* @__PURE__ */ Object.create(null);
|
|
6620
6777
|
}
|
|
6621
6778
|
};
|
|
6622
6779
|
const write = (all) => {
|
|
@@ -6646,15 +6803,20 @@ function createLocalMemoryStore(storageKey = "superchat:memory", opts = {}) {
|
|
|
6646
6803
|
}
|
|
6647
6804
|
};
|
|
6648
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
|
+
};
|
|
6649
6811
|
function createMemorySource(store, opts = {}) {
|
|
6650
6812
|
return {
|
|
6651
6813
|
id: opts.id ?? "memory",
|
|
6652
6814
|
async run({ vars }) {
|
|
6653
6815
|
const entries = (await store.list(vars)).slice(0, opts.maxEntries ?? 50);
|
|
6654
6816
|
if (!entries.length) return {};
|
|
6655
|
-
const
|
|
6817
|
+
const text4 = [
|
|
6656
6818
|
"Things you remember about this user, from earlier conversations:",
|
|
6657
|
-
...entries.map((e) => `- ${e.key}: ${e.value}`),
|
|
6819
|
+
...entries.map((e) => `- ${oneLine(e.key)}: ${oneLine(clip2(e.value))}`),
|
|
6658
6820
|
"Apply them without re-asking. Update them with the `remember` tool when they change."
|
|
6659
6821
|
].join("\n");
|
|
6660
6822
|
return {
|
|
@@ -6662,8 +6824,8 @@ function createMemorySource(store, opts = {}) {
|
|
|
6662
6824
|
{
|
|
6663
6825
|
id: opts.id ?? "memory",
|
|
6664
6826
|
kind: "memory",
|
|
6665
|
-
text:
|
|
6666
|
-
tokens: estimateTokens(
|
|
6827
|
+
text: text4,
|
|
6828
|
+
tokens: estimateTokens(text4),
|
|
6667
6829
|
priority: opts.priority ?? 500
|
|
6668
6830
|
}
|
|
6669
6831
|
]
|
|
@@ -6687,7 +6849,13 @@ function createRememberTool(store) {
|
|
|
6687
6849
|
},
|
|
6688
6850
|
async execute(input, ctx) {
|
|
6689
6851
|
const { key, value } = input ?? {};
|
|
6690
|
-
|
|
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
|
+
}
|
|
6691
6859
|
if (value == null || value === "") {
|
|
6692
6860
|
await store.remove(key, ctx.vars);
|
|
6693
6861
|
return { output: { ok: true, forgot: key } };
|
|
@@ -6699,17 +6867,36 @@ function createRememberTool(store) {
|
|
|
6699
6867
|
}
|
|
6700
6868
|
|
|
6701
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
|
+
}
|
|
6702
6889
|
function createRetrievalSource(retriever, opts = {}) {
|
|
6703
6890
|
return {
|
|
6704
6891
|
id: opts.id ?? "retrieval",
|
|
6705
6892
|
async run({ query, vars, signal }) {
|
|
6706
6893
|
if (query.trim().length < (opts.minQueryLength ?? 8)) return {};
|
|
6707
|
-
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(
|
|
6708
6895
|
0,
|
|
6709
6896
|
opts.limit ?? 5
|
|
6710
6897
|
);
|
|
6711
6898
|
if (!chunks.length) return {};
|
|
6712
|
-
const
|
|
6899
|
+
const text4 = [
|
|
6713
6900
|
"Reference material retrieved for this question. Ground your answer in it when relevant:",
|
|
6714
6901
|
...chunks.map(
|
|
6715
6902
|
(c, i) => `[${i + 1}] ${c.title ?? c.id}${c.source ? ` (${c.source})` : ""}
|
|
@@ -6722,8 +6909,8 @@ ${c.text.trim()}`
|
|
|
6722
6909
|
{
|
|
6723
6910
|
id: opts.id ?? "retrieval",
|
|
6724
6911
|
kind: "custom",
|
|
6725
|
-
text:
|
|
6726
|
-
tokens: estimateTokens(
|
|
6912
|
+
text: text4,
|
|
6913
|
+
tokens: estimateTokens(text4),
|
|
6727
6914
|
priority: opts.priority ?? 400
|
|
6728
6915
|
}
|
|
6729
6916
|
]
|
|
@@ -6732,7 +6919,7 @@ ${c.text.trim()}`
|
|
|
6732
6919
|
};
|
|
6733
6920
|
}
|
|
6734
6921
|
function createKeywordRetriever(docs) {
|
|
6735
|
-
const chunks = docs.flatMap(
|
|
6922
|
+
const chunks = docs.filter((doc) => typeof doc === "object" && doc !== null && typeof doc.text === "string").flatMap(
|
|
6736
6923
|
(doc) => doc.text.split(/\n\s*\n/).map((p) => p.trim()).filter((p) => p.length > 0).map((paragraph, i) => ({
|
|
6737
6924
|
id: `${doc.id}#${i}`,
|
|
6738
6925
|
text: paragraph,
|
|
@@ -6754,21 +6941,14 @@ function createKeywordRetriever(docs) {
|
|
|
6754
6941
|
async retrieve(query, opts = {}) {
|
|
6755
6942
|
const queryTerms = tokenize(query);
|
|
6756
6943
|
if (!queryTerms.length) return [];
|
|
6757
|
-
const
|
|
6758
|
-
const
|
|
6759
|
-
|
|
6760
|
-
|
|
6761
|
-
|
|
6762
|
-
|
|
6763
|
-
|
|
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);
|
|
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);
|
|
6772
6952
|
return scored.map(({ chunk, score }) => {
|
|
6773
6953
|
const { terms: _terms, idx: _idx, ...rest } = chunk;
|
|
6774
6954
|
return { ...rest, score };
|
|
@@ -6802,7 +6982,7 @@ ${body}`);
|
|
|
6802
6982
|
}
|
|
6803
6983
|
}
|
|
6804
6984
|
if (!blocks.length) return {};
|
|
6805
|
-
const
|
|
6985
|
+
const text4 = [
|
|
6806
6986
|
"Current state of the application the user is looking at. This is live \u2014 it reflects the screen right now, not the conversation:",
|
|
6807
6987
|
...blocks,
|
|
6808
6988
|
"Refer to it directly rather than asking the user to repeat what is already on screen."
|
|
@@ -6812,8 +6992,8 @@ ${body}`);
|
|
|
6812
6992
|
{
|
|
6813
6993
|
id: opts.id ?? "app-state",
|
|
6814
6994
|
kind: "environment",
|
|
6815
|
-
text:
|
|
6816
|
-
tokens: estimateTokens(
|
|
6995
|
+
text: text4,
|
|
6996
|
+
tokens: estimateTokens(text4),
|
|
6817
6997
|
priority: opts.priority ?? 600
|
|
6818
6998
|
}
|
|
6819
6999
|
]
|
|
@@ -6862,6 +7042,15 @@ var McpRpcError = class extends Error {
|
|
|
6862
7042
|
this.data = data;
|
|
6863
7043
|
}
|
|
6864
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
|
+
}
|
|
6865
7054
|
var MAX_TOOL_PAGES = 1e3;
|
|
6866
7055
|
var McpClient = class {
|
|
6867
7056
|
transport;
|
|
@@ -6904,10 +7093,12 @@ var McpClient = class {
|
|
|
6904
7093
|
capabilities: this.onElicit ? { elicitation: {} } : {},
|
|
6905
7094
|
clientInfo: this.clientInfo
|
|
6906
7095
|
});
|
|
7096
|
+
const reply = isObject4(result) ? result : {};
|
|
7097
|
+
const info = isObject4(reply.serverInfo) && typeof reply.serverInfo.name === "string" ? reply.serverInfo : void 0;
|
|
6907
7098
|
await this.post({ jsonrpc: "2.0", method: "notifications/initialized" });
|
|
6908
7099
|
this.handshake = {
|
|
6909
|
-
serverInfo:
|
|
6910
|
-
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
|
|
6911
7102
|
};
|
|
6912
7103
|
return this.handshake;
|
|
6913
7104
|
}
|
|
@@ -6918,8 +7109,14 @@ var McpClient = class {
|
|
|
6918
7109
|
const seen = /* @__PURE__ */ new Set();
|
|
6919
7110
|
let cursor;
|
|
6920
7111
|
do {
|
|
6921
|
-
const
|
|
6922
|
-
|
|
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
|
+
}
|
|
6923
7120
|
cursor = typeof page.nextCursor === "string" && page.nextCursor !== "" ? page.nextCursor : void 0;
|
|
6924
7121
|
if (cursor !== void 0) {
|
|
6925
7122
|
if (seen.has(cursor) || seen.size >= MAX_TOOL_PAGES) {
|
|
@@ -6939,7 +7136,12 @@ var McpClient = class {
|
|
|
6939
7136
|
await this.ensureConnected();
|
|
6940
7137
|
try {
|
|
6941
7138
|
const result = await this.rpc("tools/call", { name, arguments: args ?? {} }, opts);
|
|
6942
|
-
return {
|
|
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
|
+
};
|
|
6943
7145
|
} catch (e) {
|
|
6944
7146
|
if (e instanceof McpRpcError) {
|
|
6945
7147
|
return { content: [{ type: "text", text: e.message }], isError: true };
|
|
@@ -7059,7 +7261,7 @@ function createHttpTransport(opts) {
|
|
|
7059
7261
|
// src/mcp/import.ts
|
|
7060
7262
|
var RESERVED_NAMESPACE = "mcp";
|
|
7061
7263
|
function sanitizeNamespace(raw) {
|
|
7062
|
-
const cleaned = (raw
|
|
7264
|
+
const cleaned = (typeof raw === "string" ? raw : "").replace(/[^a-zA-Z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
7063
7265
|
if (!cleaned || cleaned.toLowerCase() === RESERVED_NAMESPACE) return "srv";
|
|
7064
7266
|
return cleaned;
|
|
7065
7267
|
}
|
|
@@ -7094,15 +7296,20 @@ async function importMcpTools(client, opts = {}) {
|
|
|
7094
7296
|
return out;
|
|
7095
7297
|
}
|
|
7096
7298
|
function mapMcpResult(result) {
|
|
7097
|
-
|
|
7098
|
-
|
|
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" };
|
|
7099
7302
|
}
|
|
7100
|
-
if (result
|
|
7303
|
+
if (result?.structuredContent !== void 0) {
|
|
7101
7304
|
return { output: result.structuredContent };
|
|
7102
7305
|
}
|
|
7103
|
-
const texts =
|
|
7104
|
-
const resources =
|
|
7105
|
-
|
|
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
|
+
);
|
|
7106
7313
|
let output;
|
|
7107
7314
|
if (texts.length === 1) {
|
|
7108
7315
|
output = parseMaybeJson(texts[0].text);
|
|
@@ -7110,7 +7317,7 @@ function mapMcpResult(result) {
|
|
|
7110
7317
|
output = texts.map((t) => t.text).join("\n");
|
|
7111
7318
|
}
|
|
7112
7319
|
if (resources.length) {
|
|
7113
|
-
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 } : {} }));
|
|
7114
7321
|
output = output === void 0 ? { resources: refs } : { text: output, resources: refs };
|
|
7115
7322
|
}
|
|
7116
7323
|
if (output === void 0) output = image2 ? "(image result)" : null;
|
|
@@ -7184,14 +7391,14 @@ function elicitViaCard(requestCard) {
|
|
|
7184
7391
|
return { action: "accept", content };
|
|
7185
7392
|
};
|
|
7186
7393
|
}
|
|
7187
|
-
var textOf = (content) => content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
|
|
7188
|
-
function parseMaybeJson(
|
|
7189
|
-
const trimmed =
|
|
7190
|
-
if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return
|
|
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;
|
|
7191
7398
|
try {
|
|
7192
7399
|
return JSON.parse(trimmed);
|
|
7193
7400
|
} catch {
|
|
7194
|
-
return
|
|
7401
|
+
return text4;
|
|
7195
7402
|
}
|
|
7196
7403
|
}
|
|
7197
7404
|
export {
|
|
@@ -7413,7 +7620,7 @@ export {
|
|
|
7413
7620
|
surfaceActionTools,
|
|
7414
7621
|
surfaceCardId,
|
|
7415
7622
|
tableCard,
|
|
7416
|
-
text,
|
|
7623
|
+
text2 as text,
|
|
7417
7624
|
threadSnapshot,
|
|
7418
7625
|
timelineCard,
|
|
7419
7626
|
toA2uiMessages,
|