@supersolutions/super-chat-core 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/anthropic.d.ts +3 -3
- package/dist/index.d.ts +1465 -989
- package/dist/index.js +2101 -361
- package/dist/index.js.map +1 -1
- package/dist/{map-in-ByQRBLJ2.d.ts → map-in-C5lFV2DR.d.ts} +1 -1
- package/dist/{map-in-B1lLaNxO.d.ts → map-in-CXwWaHl2.d.ts} +1 -1
- package/dist/openai.d.ts +3 -3
- package/dist/{types-C3VavKYX.d.ts → types-y3SK7HwA.d.ts} +6 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -156,31 +156,31 @@ function scanLines(src) {
|
|
|
156
156
|
}
|
|
157
157
|
return out;
|
|
158
158
|
}
|
|
159
|
-
var isBlank = (
|
|
159
|
+
var isBlank = (text3) => text3.trim() === "";
|
|
160
160
|
var FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})(.*)$/;
|
|
161
161
|
var INDENTED = /^(?: {4}|\t)/;
|
|
162
162
|
var LIST_ITEM = /^ {0,3}(?:[-*+]|\d{1,9}[.)])(?:\s|$)/;
|
|
163
163
|
var QUOTE = /^ {0,3}>/;
|
|
164
|
-
function fenceOpen(
|
|
165
|
-
const m = FENCE_OPEN.exec(
|
|
164
|
+
function fenceOpen(text3) {
|
|
165
|
+
const m = FENCE_OPEN.exec(text3);
|
|
166
166
|
if (!m) return null;
|
|
167
167
|
const marker = m[1];
|
|
168
168
|
const char = marker[0];
|
|
169
169
|
if (char === "`" && m[2].includes("`")) return null;
|
|
170
170
|
return { marker, char };
|
|
171
171
|
}
|
|
172
|
-
function closesFence(
|
|
173
|
-
const m = /^ {0,3}(`{3,}|~{3,})\s*$/.exec(
|
|
172
|
+
function closesFence(text3, open) {
|
|
173
|
+
const m = /^ {0,3}(`{3,}|~{3,})\s*$/.exec(text3);
|
|
174
174
|
if (!m) return false;
|
|
175
175
|
const marker = m[1];
|
|
176
176
|
return marker[0] === open.char && marker.length >= open.marker.length;
|
|
177
177
|
}
|
|
178
|
-
function continues(construct,
|
|
179
|
-
if (construct === "list") return LIST_ITEM.test(
|
|
180
|
-
if (construct === "quote") return QUOTE.test(
|
|
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);
|
|
181
181
|
return false;
|
|
182
182
|
}
|
|
183
|
-
var constructOf = (
|
|
183
|
+
var constructOf = (text3) => QUOTE.test(text3) ? "quote" : LIST_ITEM.test(text3) ? "list" : "other";
|
|
184
184
|
function splitBlocks(src) {
|
|
185
185
|
const lines = scanLines(src);
|
|
186
186
|
const blocks = [];
|
|
@@ -233,25 +233,69 @@ function splitBlocks(src) {
|
|
|
233
233
|
return blocks;
|
|
234
234
|
}
|
|
235
235
|
|
|
236
|
+
// src/content/turn-layout.ts
|
|
237
|
+
function hasTurnOrder(parts) {
|
|
238
|
+
return parts.some((p) => p.type === "artifact" && p.kind.startsWith("card:") && typeof p.callId === "string");
|
|
239
|
+
}
|
|
240
|
+
function layoutTurn(parts, cards, options = {}) {
|
|
241
|
+
const byCall = /* @__PURE__ */ new Map();
|
|
242
|
+
for (const card of cards) {
|
|
243
|
+
if (!card.callId) continue;
|
|
244
|
+
const list = byCall.get(card.callId);
|
|
245
|
+
if (list) list.push(card);
|
|
246
|
+
else byCall.set(card.callId, [card]);
|
|
247
|
+
}
|
|
248
|
+
const segments = [];
|
|
249
|
+
const placed = /* @__PURE__ */ new Set();
|
|
250
|
+
let textCount = 0;
|
|
251
|
+
let crossedCall = false;
|
|
252
|
+
for (const part of parts) {
|
|
253
|
+
if (part.type === "text") {
|
|
254
|
+
if (!part.text) continue;
|
|
255
|
+
const last = segments[segments.length - 1];
|
|
256
|
+
if (last?.type === "text") {
|
|
257
|
+
last.text += (crossedCall ? "\n\n" : "") + part.text;
|
|
258
|
+
} else {
|
|
259
|
+
segments.push({ type: "text", key: `text:${textCount}`, text: part.text });
|
|
260
|
+
textCount += 1;
|
|
261
|
+
}
|
|
262
|
+
crossedCall = false;
|
|
263
|
+
} else if (part.type === "tool-call") {
|
|
264
|
+
const owned = byCall.get(part.callId) ?? [];
|
|
265
|
+
for (const card of owned) placed.add(card.id);
|
|
266
|
+
if (owned.length || options.keepEmptyOutputs) {
|
|
267
|
+
segments.push({ type: "output", key: `call:${part.callId}`, callId: part.callId, cards: owned });
|
|
268
|
+
crossedCall = false;
|
|
269
|
+
} else {
|
|
270
|
+
crossedCall = true;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
for (const card of cards) {
|
|
275
|
+
if (!placed.has(card.id)) segments.push({ type: "card", key: `card:${card.id}`, card });
|
|
276
|
+
}
|
|
277
|
+
return segments;
|
|
278
|
+
}
|
|
279
|
+
|
|
236
280
|
// src/content/quotes.ts
|
|
237
|
-
function quoteDrift(
|
|
281
|
+
function quoteDrift(quote2, current) {
|
|
238
282
|
if (!current) return { status: "removed" };
|
|
239
|
-
if (current.revision ===
|
|
240
|
-
return { status: "moved", revision: current.revision, intact: current.markdown.includes(
|
|
283
|
+
if (current.revision === quote2.revision) return void 0;
|
|
284
|
+
return { status: "moved", revision: current.revision, intact: current.markdown.includes(quote2.text) };
|
|
241
285
|
}
|
|
242
286
|
async function checkQuoteDrift(quotes, documents) {
|
|
243
287
|
const lookups = /* @__PURE__ */ new Map();
|
|
244
288
|
return Promise.all(
|
|
245
|
-
quotes.map(async (
|
|
246
|
-
let lookup = lookups.get(
|
|
289
|
+
quotes.map(async (quote2) => {
|
|
290
|
+
let lookup = lookups.get(quote2.docId);
|
|
247
291
|
if (!lookup) {
|
|
248
|
-
lookup = documents.get(
|
|
249
|
-
lookups.set(
|
|
292
|
+
lookup = documents.get(quote2.docId).catch(() => null);
|
|
293
|
+
lookups.set(quote2.docId, lookup);
|
|
250
294
|
}
|
|
251
295
|
const current = await lookup;
|
|
252
|
-
const { drift: _unchecked, ...rest } =
|
|
296
|
+
const { drift: _unchecked, ...rest } = quote2;
|
|
253
297
|
if (current === null) return rest;
|
|
254
|
-
const drift = quoteDrift(
|
|
298
|
+
const drift = quoteDrift(quote2, current);
|
|
255
299
|
return drift ? { ...rest, drift } : rest;
|
|
256
300
|
})
|
|
257
301
|
);
|
|
@@ -264,8 +308,8 @@ var driftNote = (drift) => {
|
|
|
264
308
|
`;
|
|
265
309
|
};
|
|
266
310
|
var QUOTES_METADATA_KEY = "documentQuotes";
|
|
267
|
-
var fence = (
|
|
268
|
-
const longest = [...
|
|
311
|
+
var fence = (text3) => {
|
|
312
|
+
const longest = [...text3.matchAll(/`{3,}/g)].reduce((n, m) => Math.max(n, m[0].length), 2);
|
|
269
313
|
return "`".repeat(longest + 1);
|
|
270
314
|
};
|
|
271
315
|
function formatQuotes(quotes) {
|
|
@@ -280,12 +324,12 @@ ${q.text}
|
|
|
280
324
|
${f}`;
|
|
281
325
|
}).join("\n\n");
|
|
282
326
|
}
|
|
283
|
-
function withQuotes(
|
|
327
|
+
function withQuotes(text3, quotes) {
|
|
284
328
|
const prefix = formatQuotes(quotes);
|
|
285
|
-
if (!prefix) return
|
|
286
|
-
return
|
|
329
|
+
if (!prefix) return text3;
|
|
330
|
+
return text3.trim() ? `${prefix}
|
|
287
331
|
|
|
288
|
-
${
|
|
332
|
+
${text3}` : prefix;
|
|
289
333
|
}
|
|
290
334
|
function quotesOf(metadata) {
|
|
291
335
|
const raw = metadata?.[QUOTES_METADATA_KEY];
|
|
@@ -685,11 +729,11 @@ function createGenerateImageTool(provider, options = {}) {
|
|
|
685
729
|
// src/tokens/estimate.ts
|
|
686
730
|
var LATIN_CHARS_PER_TOKEN = 3.7;
|
|
687
731
|
var CJK_CHARS_PER_TOKEN = 1.1;
|
|
688
|
-
function estimateTokens(
|
|
689
|
-
if (!
|
|
732
|
+
function estimateTokens(text3) {
|
|
733
|
+
if (!text3) return 0;
|
|
690
734
|
let cjk = 0;
|
|
691
735
|
let other = 0;
|
|
692
|
-
for (const ch of
|
|
736
|
+
for (const ch of text3) {
|
|
693
737
|
const code = ch.codePointAt(0);
|
|
694
738
|
const isCjk = code >= 12352 && code <= 12543 || // kana
|
|
695
739
|
code >= 13312 && code <= 19903 || // CJK ext A
|
|
@@ -970,12 +1014,12 @@ var SkillRegistry = class {
|
|
|
970
1014
|
const matched = this.matcher(list, ctx.query).filter((m) => m.skill.mode === "matched" && !forced.has(m.skill.id)).slice(0, this.maxMatched);
|
|
971
1015
|
const out = [];
|
|
972
1016
|
for (const skill of always) {
|
|
973
|
-
const
|
|
1017
|
+
const text3 = await renderSkill(skill, ctx);
|
|
974
1018
|
out.push({
|
|
975
1019
|
id: skill.id,
|
|
976
1020
|
name: skill.name,
|
|
977
|
-
text:
|
|
978
|
-
tokens: estimateTokens(
|
|
1021
|
+
text: text3,
|
|
1022
|
+
tokens: estimateTokens(text3),
|
|
979
1023
|
// Sort key: `always` outranks any matched score so it survives packing.
|
|
980
1024
|
score: 1e3 + (skill.priority ?? 0),
|
|
981
1025
|
mode: skill.mode,
|
|
@@ -983,12 +1027,12 @@ var SkillRegistry = class {
|
|
|
983
1027
|
});
|
|
984
1028
|
}
|
|
985
1029
|
for (const m of matched) {
|
|
986
|
-
const
|
|
1030
|
+
const text3 = await renderSkill(m.skill, ctx, m.sections);
|
|
987
1031
|
out.push({
|
|
988
1032
|
id: m.skill.id,
|
|
989
1033
|
name: m.skill.name,
|
|
990
|
-
text:
|
|
991
|
-
tokens: estimateTokens(
|
|
1034
|
+
text: text3,
|
|
1035
|
+
tokens: estimateTokens(text3),
|
|
992
1036
|
score: m.score,
|
|
993
1037
|
mode: m.skill.mode,
|
|
994
1038
|
tools: m.skill.tools ?? []
|
|
@@ -1132,9 +1176,9 @@ ${summary}`
|
|
|
1132
1176
|
}
|
|
1133
1177
|
function buildSummaryPrompt(messages) {
|
|
1134
1178
|
const transcript = messages.map((m) => {
|
|
1135
|
-
const
|
|
1179
|
+
const text3 = messageText(m);
|
|
1136
1180
|
const calls = m.parts.filter((p) => p.type === "tool-call").map((p) => `\u2192 called ${p.name}`).join(" ");
|
|
1137
|
-
return `${m.role}: ${
|
|
1181
|
+
return `${m.role}: ${text3}${calls ? ` ${calls}` : ""}`.trim();
|
|
1138
1182
|
}).filter((line) => line.length > line.indexOf(":") + 1).join("\n");
|
|
1139
1183
|
return [
|
|
1140
1184
|
"Compress this conversation span into a brief the assistant can act on.",
|
|
@@ -1175,8 +1219,8 @@ var ContextBuilder = class {
|
|
|
1175
1219
|
const unlockedTools = new Set(input.baseTools ?? []);
|
|
1176
1220
|
let skills = [];
|
|
1177
1221
|
if (this.opts.identity?.trim()) {
|
|
1178
|
-
const
|
|
1179
|
-
layers.push({ id: "identity", kind: "identity", text:
|
|
1222
|
+
const text3 = this.opts.identity.trim();
|
|
1223
|
+
layers.push({ id: "identity", kind: "identity", text: text3, tokens: counter3(text3), pinned: true, priority: 1e3 });
|
|
1180
1224
|
}
|
|
1181
1225
|
if (this.opts.skills) {
|
|
1182
1226
|
const started = Date.now();
|
|
@@ -1738,7 +1782,7 @@ function createDocumentTools(opts) {
|
|
|
1738
1782
|
}
|
|
1739
1783
|
const from = num(i["from"]) ?? 0;
|
|
1740
1784
|
const to = num(i["to"]) ?? from;
|
|
1741
|
-
const
|
|
1785
|
+
const text3 = spanOf(doc.markdown, from, to);
|
|
1742
1786
|
return {
|
|
1743
1787
|
output: {
|
|
1744
1788
|
docId: doc.id,
|
|
@@ -1748,8 +1792,8 @@ function createDocumentTools(opts) {
|
|
|
1748
1792
|
// Truncation is REPORTED, not silent: a model that believes it has
|
|
1749
1793
|
// read a whole section will quote text that is not there, and the
|
|
1750
1794
|
// edit will then be refused for a reason that looks like its fault.
|
|
1751
|
-
truncated:
|
|
1752
|
-
text:
|
|
1795
|
+
truncated: text3.length > maxSpanChars,
|
|
1796
|
+
text: text3.slice(0, maxSpanChars)
|
|
1753
1797
|
}
|
|
1754
1798
|
};
|
|
1755
1799
|
}
|
|
@@ -1759,6 +1803,8 @@ function createDocumentTools(opts) {
|
|
|
1759
1803
|
description: "Propose changes to a document. The user sees them as a diff and accepts them one at a time; nothing is written until they do.",
|
|
1760
1804
|
inputSchema: EDIT_SCHEMA,
|
|
1761
1805
|
side: "confirm",
|
|
1806
|
+
// The diff is the approval, and only this tool can compute it.
|
|
1807
|
+
confirmation: "tool",
|
|
1762
1808
|
async execute(input, ctx) {
|
|
1763
1809
|
const i = input ?? {};
|
|
1764
1810
|
const docId = str(i["docId"]);
|
|
@@ -1970,9 +2016,9 @@ function quotedPrintable(body) {
|
|
|
1970
2016
|
let current = "";
|
|
1971
2017
|
for (let i = 0; i < bytes.length; i += 1) {
|
|
1972
2018
|
const b = bytes[i];
|
|
1973
|
-
const
|
|
2019
|
+
const printable2 = b >= 32 && b <= 126 && b !== 61;
|
|
1974
2020
|
const trailing = (b === 32 || b === 9) && i === bytes.length - 1;
|
|
1975
|
-
const token =
|
|
2021
|
+
const token = printable2 && !trailing ? String.fromCharCode(b) : `=${b.toString(16).toUpperCase().padStart(2, "0")}`;
|
|
1976
2022
|
if (current.length + token.length > 75) {
|
|
1977
2023
|
out.push(`${current}=`);
|
|
1978
2024
|
current = "";
|
|
@@ -2073,14 +2119,14 @@ var CardRegistry = class {
|
|
|
2073
2119
|
if (!isObj(spec) || typeof spec["kind"] !== "string") return void 0;
|
|
2074
2120
|
const def = this.kinds.get(spec["kind"]);
|
|
2075
2121
|
if (!def?.partial || def.interactive) return void 0;
|
|
2076
|
-
let
|
|
2122
|
+
let preview2;
|
|
2077
2123
|
try {
|
|
2078
|
-
|
|
2124
|
+
preview2 = def.partial(spec);
|
|
2079
2125
|
} catch {
|
|
2080
2126
|
return void 0;
|
|
2081
2127
|
}
|
|
2082
|
-
if (!isObj(
|
|
2083
|
-
return def.validate(
|
|
2128
|
+
if (!isObj(preview2) || preview2["kind"] !== def.kind) return void 0;
|
|
2129
|
+
return def.validate(preview2).ok ? preview2 : void 0;
|
|
2084
2130
|
}
|
|
2085
2131
|
/** The catalogue text embedded in the `visualize` tool description. */
|
|
2086
2132
|
describe() {
|
|
@@ -3089,147 +3135,1944 @@ var BUILTIN_CARDS = [
|
|
|
3089
3135
|
emailCard
|
|
3090
3136
|
];
|
|
3091
3137
|
|
|
3092
|
-
// src/
|
|
3093
|
-
|
|
3094
|
-
|
|
3138
|
+
// src/surfaces/types.ts
|
|
3139
|
+
var SURFACE_CARD_KIND = "surface";
|
|
3140
|
+
var SURFACE_FORMAT_VERSION = 1;
|
|
3141
|
+
var SURFACE_LIMITS = {
|
|
3142
|
+
components: 200,
|
|
3143
|
+
depth: 16,
|
|
3144
|
+
dataChars: 64e3,
|
|
3145
|
+
specChars: 2e5,
|
|
3146
|
+
surfaces: 24,
|
|
3147
|
+
listItems: 200,
|
|
3148
|
+
queryRows: 2e3,
|
|
3149
|
+
actionUpdates: 8,
|
|
3150
|
+
tabs: 12
|
|
3151
|
+
};
|
|
3152
|
+
var SURFACE_EVENT_METADATA_KEY = "surfaceEvent";
|
|
3153
|
+
|
|
3154
|
+
// src/surfaces/pointer.ts
|
|
3155
|
+
var FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
3156
|
+
var isForbiddenKey = (key) => FORBIDDEN_SEGMENTS.has(key);
|
|
3157
|
+
function parsePointer(pointer) {
|
|
3158
|
+
if (typeof pointer !== "string") return void 0;
|
|
3159
|
+
if (pointer === "" || pointer === "/") return [];
|
|
3160
|
+
if (!pointer.startsWith("/")) return void 0;
|
|
3161
|
+
const segments = pointer.slice(1).split("/").map((s) => s.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
3162
|
+
if (segments.length > SURFACE_LIMITS.depth) return void 0;
|
|
3163
|
+
if (segments.some((s) => s === "" || FORBIDDEN_SEGMENTS.has(s))) return void 0;
|
|
3164
|
+
return segments;
|
|
3165
|
+
}
|
|
3166
|
+
var isContainer = (v) => typeof v === "object" && v !== null;
|
|
3167
|
+
var isIndex = (s) => /^(0|[1-9]\d*)$/.test(s);
|
|
3168
|
+
function child(value, key) {
|
|
3169
|
+
if (Array.isArray(value)) return isIndex(key) ? value[Number(key)] : void 0;
|
|
3170
|
+
if (!isContainer(value)) return void 0;
|
|
3171
|
+
return Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
|
|
3172
|
+
}
|
|
3173
|
+
function getAt(data, pointer) {
|
|
3174
|
+
const segments = parsePointer(pointer);
|
|
3175
|
+
if (!segments) return void 0;
|
|
3176
|
+
let current = data;
|
|
3177
|
+
for (const segment of segments) current = child(current, segment);
|
|
3178
|
+
return current;
|
|
3179
|
+
}
|
|
3180
|
+
function writeAt(node, segments, index, value) {
|
|
3181
|
+
if (index === segments.length) return value;
|
|
3182
|
+
const key = segments[index];
|
|
3183
|
+
if (Array.isArray(node)) {
|
|
3184
|
+
const at = key === "-" ? node.length : isIndex(key) ? Number(key) : -1;
|
|
3185
|
+
if (at < 0 || at > node.length) throw new RangeError(key);
|
|
3186
|
+
const next = [...node];
|
|
3187
|
+
next[at] = writeAt(node[at], segments, index + 1, value);
|
|
3188
|
+
return next;
|
|
3189
|
+
}
|
|
3190
|
+
const base = isContainer(node) ? node : {};
|
|
3191
|
+
return { ...base, [key]: writeAt(child(base, key), segments, index + 1, value) };
|
|
3192
|
+
}
|
|
3193
|
+
function setAt(data, pointer, value) {
|
|
3194
|
+
const segments = parsePointer(pointer);
|
|
3195
|
+
if (!segments) return void 0;
|
|
3196
|
+
if (!segments.length) {
|
|
3197
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
3198
|
+
}
|
|
3095
3199
|
try {
|
|
3096
|
-
return
|
|
3200
|
+
return writeAt(data, segments, 0, value);
|
|
3097
3201
|
} catch {
|
|
3098
3202
|
return void 0;
|
|
3099
3203
|
}
|
|
3100
3204
|
}
|
|
3101
|
-
function
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
|
|
3205
|
+
function removeAt(data, pointer) {
|
|
3206
|
+
const segments = parsePointer(pointer);
|
|
3207
|
+
if (!segments?.length) return void 0;
|
|
3208
|
+
const parentPath = segments.slice(0, -1);
|
|
3209
|
+
const key = segments[segments.length - 1];
|
|
3210
|
+
let parent = data;
|
|
3211
|
+
for (const segment of parentPath) parent = child(parent, segment);
|
|
3212
|
+
if (!isContainer(parent)) return data;
|
|
3213
|
+
const without2 = Array.isArray(parent) ? parent.filter((_, i) => String(i) !== key) : Object.fromEntries(Object.entries(parent).filter(([k]) => k !== key));
|
|
3214
|
+
if (!parentPath.length) return without2;
|
|
3215
|
+
return writeAt(data, parentPath, 0, without2);
|
|
3216
|
+
}
|
|
3217
|
+
|
|
3218
|
+
// src/surfaces/safety.ts
|
|
3219
|
+
var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["dangerouslysetinnerhtml", "innerhtml", "outerhtml", "srcdoc"]);
|
|
3220
|
+
var SCRIPT_SCHEMES = /^(javascript|vbscript|livescript|data:text\/html|data:application\/xhtml|data:image\/svg)/;
|
|
3221
|
+
var MARKUP = /<\s*\/?\s*[a-z][a-z0-9-]*(\s[^<>]*)?\/?>|<\s*(script|iframe|object|embed|style|svg|math)\b/i;
|
|
3222
|
+
var compact = (s) => (
|
|
3223
|
+
// eslint-disable-next-line no-control-regex
|
|
3224
|
+
s.replace(/[\u0000-\u0020\u007f-\u009f\u200b-\u200f\u2028\u2029\ufeff]/g, "").toLowerCase()
|
|
3225
|
+
);
|
|
3226
|
+
var isScriptUrl = (s) => {
|
|
3227
|
+
const c = compact(s.slice(0, 256));
|
|
3228
|
+
return SCRIPT_SCHEMES.test(c) && (c.startsWith("data:") || /^[a-z]+:/.test(c));
|
|
3229
|
+
};
|
|
3230
|
+
function findUnsafe(value, opts = {}) {
|
|
3231
|
+
const markup = opts.markup === true;
|
|
3232
|
+
let visited = 0;
|
|
3233
|
+
const walk = (node, path, depth) => {
|
|
3234
|
+
visited += 1;
|
|
3235
|
+
if (visited > 5e4 || depth > 32) return { path, reason: "is nested too deeply to inspect" };
|
|
3236
|
+
if (typeof node === "string") {
|
|
3237
|
+
if (isScriptUrl(node)) return { path, reason: "is a URL that runs script" };
|
|
3238
|
+
if (markup && MARKUP.test(node)) return { path, reason: "contains HTML" };
|
|
3239
|
+
return void 0;
|
|
3240
|
+
}
|
|
3241
|
+
if (typeof node === "function") return { path, reason: "is executable" };
|
|
3242
|
+
if (typeof node !== "object" || node === null) return void 0;
|
|
3243
|
+
if (Array.isArray(node)) {
|
|
3244
|
+
for (let i = 0; i < node.length; i += 1) {
|
|
3245
|
+
const found = walk(node[i], `${path}/${i}`, depth + 1);
|
|
3246
|
+
if (found) return found;
|
|
3247
|
+
}
|
|
3248
|
+
return void 0;
|
|
3249
|
+
}
|
|
3250
|
+
for (const key of Object.keys(node)) {
|
|
3251
|
+
if (isForbiddenKey(key) || DANGEROUS_KEYS.has(key.toLowerCase())) {
|
|
3252
|
+
return { path: `${path}/${key}`, reason: "is not an allowed key" };
|
|
3253
|
+
}
|
|
3254
|
+
const found = walk(node[key], `${path}/${key}`, depth + 1);
|
|
3255
|
+
if (found) return found;
|
|
3256
|
+
}
|
|
3105
3257
|
return void 0;
|
|
3106
|
-
}
|
|
3258
|
+
};
|
|
3259
|
+
return walk(value, opts.path ?? "", 0);
|
|
3260
|
+
}
|
|
3261
|
+
function safeSurfaceUrl(url, use) {
|
|
3262
|
+
if (typeof url !== "string") return void 0;
|
|
3263
|
+
const trimmed = url.trim();
|
|
3264
|
+
if (/[\u0000-\u001f\u007f]/.test(trimmed)) return void 0;
|
|
3265
|
+
if (/^https?:\/\/[^\s]+$/i.test(trimmed)) return trimmed;
|
|
3266
|
+
if (use === "image" && /^data:image\/(png|jpeg|jpg|gif|webp);base64,[a-z0-9+/=]+$/i.test(trimmed)) return trimmed;
|
|
3267
|
+
return void 0;
|
|
3107
3268
|
}
|
|
3108
|
-
var DEFAULT_PRESETS = ["observer", "draft", "executor"];
|
|
3109
3269
|
|
|
3110
|
-
// src/
|
|
3111
|
-
var
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
|
|
3121
|
-
|
|
3270
|
+
// src/surfaces/schema-check.ts
|
|
3271
|
+
var typeOf = (v) => {
|
|
3272
|
+
if (v === null) return "null";
|
|
3273
|
+
if (Array.isArray(v)) return "array";
|
|
3274
|
+
return typeof v;
|
|
3275
|
+
};
|
|
3276
|
+
var matchesType = (value, type) => {
|
|
3277
|
+
if (type === "integer") return typeof value === "number" && Number.isInteger(value);
|
|
3278
|
+
if (type === "number") return typeof value === "number" && Number.isFinite(value);
|
|
3279
|
+
return typeOf(value) === type;
|
|
3280
|
+
};
|
|
3281
|
+
var quote = (values) => values.map((v) => JSON.stringify(v)).join(", ");
|
|
3282
|
+
function checkSchema(schema, value, path = "", opts = {}) {
|
|
3283
|
+
const out = [];
|
|
3284
|
+
const max = opts.maxProblems ?? 6;
|
|
3285
|
+
const walk = (s, v, at) => {
|
|
3286
|
+
if (out.length >= max) return;
|
|
3287
|
+
if (opts.isDynamic?.(v) && s["x-static"] !== true) return;
|
|
3288
|
+
const label = at || "value";
|
|
3289
|
+
const anyOf = s["anyOf"];
|
|
3290
|
+
if (Array.isArray(anyOf)) {
|
|
3291
|
+
const passes = anyOf.some((option) => checkSchema(option, v, at, opts).length === 0);
|
|
3292
|
+
if (!passes) out.push({ path: at, message: `${label} does not match any allowed form.`, expected: s.description });
|
|
3293
|
+
return;
|
|
3294
|
+
}
|
|
3295
|
+
if (s.const !== void 0 && v !== s.const) {
|
|
3296
|
+
out.push({ path: at, message: `${label} must be ${JSON.stringify(s.const)}.` });
|
|
3297
|
+
return;
|
|
3298
|
+
}
|
|
3299
|
+
if (s.enum && !s.enum.includes(v)) {
|
|
3300
|
+
out.push({ path: at, message: `${label} is ${JSON.stringify(v)}.`, expected: `One of: ${quote(s.enum)}` });
|
|
3301
|
+
return;
|
|
3302
|
+
}
|
|
3303
|
+
if (s.type !== void 0) {
|
|
3304
|
+
const types = Array.isArray(s.type) ? s.type : [s.type];
|
|
3305
|
+
if (!types.some((t) => matchesType(v, t))) {
|
|
3306
|
+
out.push({ path: at, message: `${label} must be ${types.join(" or ")}, got ${typeOf(v)}.` });
|
|
3307
|
+
return;
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
if (typeof v === "number") {
|
|
3311
|
+
if (s.minimum != null && v < s.minimum) out.push({ path: at, message: `${label} must be at least ${s.minimum}.` });
|
|
3312
|
+
if (s.maximum != null && v > s.maximum) out.push({ path: at, message: `${label} must be at most ${s.maximum}.` });
|
|
3313
|
+
}
|
|
3314
|
+
if (typeof v === "string") {
|
|
3315
|
+
const min = s["minLength"];
|
|
3316
|
+
const maxLength = s["maxLength"];
|
|
3317
|
+
if (typeof min === "number" && v.length < min) out.push({ path: at, message: `${label} must not be empty.` });
|
|
3318
|
+
if (typeof maxLength === "number" && v.length > maxLength) {
|
|
3319
|
+
out.push({ path: at, message: `${label} is longer than ${maxLength} characters.` });
|
|
3320
|
+
}
|
|
3321
|
+
}
|
|
3322
|
+
if (Array.isArray(v)) {
|
|
3323
|
+
const minItems = s["minItems"];
|
|
3324
|
+
const maxItems = s["maxItems"];
|
|
3325
|
+
if (typeof minItems === "number" && v.length < minItems) out.push({ path: at, message: `${label} needs at least ${minItems} item(s).` });
|
|
3326
|
+
if (typeof maxItems === "number" && v.length > maxItems) out.push({ path: at, message: `${label} allows at most ${maxItems} item(s).` });
|
|
3327
|
+
if (s.items && !Array.isArray(s.items)) {
|
|
3328
|
+
const items = s.items;
|
|
3329
|
+
v.forEach((item, i) => walk(items, item, `${at}/${i}`));
|
|
3330
|
+
}
|
|
3331
|
+
}
|
|
3332
|
+
if (typeOf(v) === "object") {
|
|
3333
|
+
const record = v;
|
|
3334
|
+
for (const key of s.required ?? []) {
|
|
3335
|
+
if (record[key] === void 0) out.push({ path: `${at}/${key}`, message: `${at ? `${at}/` : ""}${key} is required.` });
|
|
3336
|
+
}
|
|
3337
|
+
const properties = s.properties ?? {};
|
|
3338
|
+
for (const [key, item] of Object.entries(record)) {
|
|
3339
|
+
const propSchema = properties[key];
|
|
3340
|
+
if (propSchema) walk(propSchema, item, `${at}/${key}`);
|
|
3341
|
+
else if (s.additionalProperties === false) {
|
|
3342
|
+
out.push({
|
|
3343
|
+
path: `${at}/${key}`,
|
|
3344
|
+
message: `Unknown prop "${key}".`,
|
|
3345
|
+
expected: `Allowed: ${Object.keys(properties).join(", ") || "(none)"}`
|
|
3346
|
+
});
|
|
3347
|
+
} else if (typeof s.additionalProperties === "object") walk(s.additionalProperties, item, `${at}/${key}`);
|
|
3348
|
+
}
|
|
3349
|
+
}
|
|
3350
|
+
};
|
|
3351
|
+
walk(schema, value, path);
|
|
3352
|
+
return out.slice(0, max);
|
|
3353
|
+
}
|
|
3354
|
+
|
|
3355
|
+
// src/surfaces/bindings.ts
|
|
3356
|
+
var BINDING_KEYS = ["$path", "$item", "$template", "$query"];
|
|
3357
|
+
var isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
3358
|
+
function isSurfaceBinding(value) {
|
|
3359
|
+
if (!isPlainObject(value)) return false;
|
|
3360
|
+
const keys = Object.keys(value);
|
|
3361
|
+
return keys.length === 1 && BINDING_KEYS.includes(keys[0]);
|
|
3362
|
+
}
|
|
3363
|
+
function usesBinding(value, key) {
|
|
3364
|
+
if (Array.isArray(value)) return value.some((v) => usesBinding(v, key));
|
|
3365
|
+
if (!isPlainObject(value)) return false;
|
|
3366
|
+
if (isSurfaceBinding(value)) {
|
|
3367
|
+
if (key in value) return true;
|
|
3368
|
+
if ("$query" in value) return usesBinding(value.$query.where?.map((w) => w?.value), key);
|
|
3369
|
+
return key === "$item" && "$template" in value && /\{\.[^{}]*\}/.test(String(value.$template));
|
|
3370
|
+
}
|
|
3371
|
+
return Object.values(value).some((v) => usesBinding(v, key));
|
|
3372
|
+
}
|
|
3373
|
+
var TEMPLATE_TOKEN = /\{(\/[^{}]*|\.[^{}]*)\}/g;
|
|
3374
|
+
var itemField = (item, field) => {
|
|
3375
|
+
if (!field) return item;
|
|
3376
|
+
return getAt(item, field.startsWith("/") ? field : `/${field.replace(/\./g, "/")}`);
|
|
3377
|
+
};
|
|
3378
|
+
var printable = (v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean" ? String(v) : "";
|
|
3379
|
+
function formatTemplate(template, scope) {
|
|
3380
|
+
return template.replace(
|
|
3381
|
+
TEMPLATE_TOKEN,
|
|
3382
|
+
(_, token) => printable(token.startsWith(".") ? itemField(scope.item, token.slice(1)) : getAt(scope.data, token))
|
|
3383
|
+
);
|
|
3384
|
+
}
|
|
3385
|
+
var asNumber = (v) => {
|
|
3386
|
+
if (typeof v === "number") return Number.isFinite(v) ? v : void 0;
|
|
3387
|
+
if (typeof v === "string" && v.trim() !== "") {
|
|
3388
|
+
const n = Number(v);
|
|
3389
|
+
return Number.isFinite(n) ? n : void 0;
|
|
3122
3390
|
}
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3391
|
+
return void 0;
|
|
3392
|
+
};
|
|
3393
|
+
var sameValue = (a, b) => a === b || a != null && b != null && String(a) === String(b);
|
|
3394
|
+
function compare(left, op, right) {
|
|
3395
|
+
switch (op) {
|
|
3396
|
+
case "eq":
|
|
3397
|
+
return sameValue(left, right);
|
|
3398
|
+
case "ne":
|
|
3399
|
+
return !sameValue(left, right);
|
|
3400
|
+
case "in":
|
|
3401
|
+
return Array.isArray(right) && right.some((r) => sameValue(left, r));
|
|
3402
|
+
case "contains":
|
|
3403
|
+
return String(left ?? "").toLowerCase().includes(String(right ?? "").toLowerCase());
|
|
3404
|
+
default: {
|
|
3405
|
+
const a = asNumber(left);
|
|
3406
|
+
const b = asNumber(right);
|
|
3407
|
+
if (a === void 0 || b === void 0) return false;
|
|
3408
|
+
return op === "gt" ? a > b : op === "gte" ? a >= b : op === "lt" ? a < b : op === "lte" ? a <= b : false;
|
|
3409
|
+
}
|
|
3410
|
+
}
|
|
3411
|
+
}
|
|
3412
|
+
function rowField(row, field) {
|
|
3413
|
+
return isPlainObject(row) && Object.prototype.hasOwnProperty.call(row, field) ? row[field] : void 0;
|
|
3414
|
+
}
|
|
3415
|
+
var clauseApplies = (clause, value) => {
|
|
3416
|
+
if (value === void 0 || value === null || value === "") return false;
|
|
3417
|
+
if (Array.isArray(value) && value.length === 0) return false;
|
|
3418
|
+
return clause.ignore === void 0 || !sameValue(value, clause.ignore);
|
|
3419
|
+
};
|
|
3420
|
+
var tidy = (n) => Math.round(n * 1e6) / 1e6;
|
|
3421
|
+
function aggregate(rows, spec) {
|
|
3422
|
+
if (spec.op === "count") return rows.length;
|
|
3423
|
+
const values = rows.map((r) => asNumber(rowField(r, spec.field ?? ""))).filter((n) => n !== void 0);
|
|
3424
|
+
if (!values.length) return 0;
|
|
3425
|
+
switch (spec.op) {
|
|
3426
|
+
case "sum":
|
|
3427
|
+
return tidy(values.reduce((a, b) => a + b, 0));
|
|
3428
|
+
case "avg":
|
|
3429
|
+
return tidy(values.reduce((a, b) => a + b, 0) / values.length);
|
|
3430
|
+
case "min":
|
|
3431
|
+
return values.reduce((a, b) => Math.min(a, b));
|
|
3432
|
+
case "max":
|
|
3433
|
+
return values.reduce((a, b) => Math.max(a, b));
|
|
3434
|
+
}
|
|
3435
|
+
}
|
|
3436
|
+
var order = (a, b) => {
|
|
3437
|
+
const x = asNumber(a);
|
|
3438
|
+
const y = asNumber(b);
|
|
3439
|
+
if (x !== void 0 && y !== void 0) return x - y;
|
|
3440
|
+
return String(a ?? "").localeCompare(String(b ?? ""));
|
|
3441
|
+
};
|
|
3442
|
+
function runSurfaceQuery(query, scope) {
|
|
3443
|
+
const source = getAt(scope.data, query.from);
|
|
3444
|
+
let rows = Array.isArray(source) ? source.slice(0, SURFACE_LIMITS.queryRows) : [];
|
|
3445
|
+
for (const clause of query.where ?? []) {
|
|
3446
|
+
const value = resolveSurfaceValue(clause.value, scope);
|
|
3447
|
+
if (!clauseApplies(clause, value)) continue;
|
|
3448
|
+
rows = rows.filter((row) => compare(rowField(row, clause.field), clause.op ?? "eq", value));
|
|
3449
|
+
}
|
|
3450
|
+
const direction = query.sortDir === "desc" ? -1 : 1;
|
|
3451
|
+
const limit = (list) => typeof query.limit === "number" && query.limit >= 0 ? list.slice(0, query.limit) : list;
|
|
3452
|
+
if (query.groupBy) {
|
|
3453
|
+
const groups = /* @__PURE__ */ new Map();
|
|
3454
|
+
for (const row of rows) {
|
|
3455
|
+
const key = printable(rowField(row, query.groupBy));
|
|
3456
|
+
const bucket = groups.get(key);
|
|
3457
|
+
if (bucket) bucket.push(row);
|
|
3458
|
+
else groups.set(key, [row]);
|
|
3459
|
+
}
|
|
3460
|
+
let pairs = [...groups].map(([key, bucket]) => ({ key, value: aggregate(bucket, query.aggregate ?? { op: "count" }) }));
|
|
3461
|
+
if (query.sortBy === "key" || query.sortBy === "value") {
|
|
3462
|
+
const by = query.sortBy;
|
|
3463
|
+
pairs = [...pairs].sort((a, b) => order(a[by], b[by]) * direction);
|
|
3464
|
+
}
|
|
3465
|
+
const limited = limit(pairs);
|
|
3466
|
+
return query.shape === "rows" ? limited : limited.map((p) => [p.key, p.value]);
|
|
3467
|
+
}
|
|
3468
|
+
if (query.aggregate) return aggregate(rows, query.aggregate);
|
|
3469
|
+
if (query.sortBy) {
|
|
3470
|
+
const by = query.sortBy;
|
|
3471
|
+
rows = [...rows].sort((a, b) => order(rowField(a, by), rowField(b, by)) * direction);
|
|
3472
|
+
}
|
|
3473
|
+
rows = limit(rows);
|
|
3474
|
+
return query.select ? rows.map((r) => rowField(r, query.select)) : rows;
|
|
3475
|
+
}
|
|
3476
|
+
function resolveSurfaceValue(value, scope, depth = 0) {
|
|
3477
|
+
if (depth > SURFACE_LIMITS.depth * 2) return void 0;
|
|
3478
|
+
if (Array.isArray(value)) return value.map((v) => resolveSurfaceValue(v, scope, depth + 1));
|
|
3479
|
+
if (!isPlainObject(value)) return value;
|
|
3480
|
+
if (isSurfaceBinding(value)) {
|
|
3481
|
+
if ("$path" in value) return getAt(scope.data, value.$path);
|
|
3482
|
+
if ("$item" in value) return itemField(scope.item, value.$item);
|
|
3483
|
+
if ("$template" in value) return formatTemplate(value.$template, scope);
|
|
3484
|
+
return runSurfaceQuery(value.$query, scope);
|
|
3485
|
+
}
|
|
3486
|
+
const out = {};
|
|
3487
|
+
for (const [key, item] of Object.entries(value)) out[key] = resolveSurfaceValue(item, scope, depth + 1);
|
|
3488
|
+
return out;
|
|
3489
|
+
}
|
|
3490
|
+
function evaluateSurfaceCondition(condition, scope) {
|
|
3491
|
+
if (!condition) return true;
|
|
3492
|
+
const current = getAt(scope.data, condition.path);
|
|
3493
|
+
const op = condition.op ?? (condition.value === void 0 ? "truthy" : "eq");
|
|
3494
|
+
if (op === "truthy") return Boolean(current) && !(Array.isArray(current) && current.length === 0);
|
|
3495
|
+
if (op === "falsy") return !current || Array.isArray(current) && current.length === 0;
|
|
3496
|
+
return compare(current, op, condition.value);
|
|
3497
|
+
}
|
|
3498
|
+
function resolveSurfaceAction(action, scope) {
|
|
3499
|
+
switch (action.type) {
|
|
3500
|
+
case "set":
|
|
3501
|
+
return { type: "set", updates: action.updates.map((u) => ({ path: u.path, value: resolveSurfaceValue(u.value, scope) })) };
|
|
3502
|
+
case "tool":
|
|
3503
|
+
return { ...action, args: resolveSurfaceValue(action.args ?? {}, scope) };
|
|
3504
|
+
case "event":
|
|
3505
|
+
return { ...action, context: resolveSurfaceValue(action.context ?? {}, scope) };
|
|
3506
|
+
}
|
|
3507
|
+
}
|
|
3508
|
+
function bindingProblems(binding) {
|
|
3509
|
+
if ("$path" in binding) {
|
|
3510
|
+
return parsePointer(binding.$path) ? [] : [`$path ${JSON.stringify(binding.$path)} is not a JSON Pointer such as "/filters/region".`];
|
|
3511
|
+
}
|
|
3512
|
+
if ("$item" in binding) {
|
|
3513
|
+
return typeof binding.$item === "string" ? [] : ["$item must be a field name of the current row."];
|
|
3514
|
+
}
|
|
3515
|
+
if ("$template" in binding) return typeof binding.$template === "string" ? [] : ["$template must be a string."];
|
|
3516
|
+
const query = binding.$query;
|
|
3517
|
+
if (!isPlainObject(query)) return ["$query must be an object with a `from` pointer."];
|
|
3518
|
+
const out = [];
|
|
3519
|
+
if (!parsePointer(query.from)) out.push(`$query.from ${JSON.stringify(query.from)} is not a JSON Pointer to an array.`);
|
|
3520
|
+
const allowed = /* @__PURE__ */ new Set(["from", "where", "groupBy", "aggregate", "sortBy", "sortDir", "limit", "select", "shape"]);
|
|
3521
|
+
for (const key of Object.keys(query)) if (!allowed.has(key)) out.push(`$query has no "${key}". Allowed: ${[...allowed].join(", ")}.`);
|
|
3522
|
+
if (query.where !== void 0 && !Array.isArray(query.where)) out.push("$query.where must be an array of { field, op, value }.");
|
|
3523
|
+
for (const clause of Array.isArray(query.where) ? query.where : []) {
|
|
3524
|
+
if (!isPlainObject(clause) || typeof clause.field !== "string") out.push("Each $query.where clause needs a string `field`.");
|
|
3525
|
+
else if (clause.op !== void 0 && !["eq", "ne", "gt", "gte", "lt", "lte", "in", "contains"].includes(clause.op)) {
|
|
3526
|
+
out.push(`$query.where op "${String(clause.op)}" is not one of eq, ne, gt, gte, lt, lte, in, contains.`);
|
|
3527
|
+
}
|
|
3528
|
+
}
|
|
3529
|
+
if (query.aggregate !== void 0) {
|
|
3530
|
+
const ops = ["count", "sum", "avg", "min", "max"];
|
|
3531
|
+
if (!isPlainObject(query.aggregate) || !ops.includes(String(query.aggregate.op))) out.push(`$query.aggregate.op must be one of ${ops.join(", ")}.`);
|
|
3532
|
+
else if (query.aggregate.op !== "count" && typeof query.aggregate.field !== "string") out.push(`$query.aggregate "${query.aggregate.op}" needs a \`field\`.`);
|
|
3533
|
+
}
|
|
3534
|
+
if (query.sortDir !== void 0 && query.sortDir !== "asc" && query.sortDir !== "desc") out.push('$query.sortDir must be "asc" or "desc".');
|
|
3535
|
+
if (query.shape !== void 0 && query.shape !== "points" && query.shape !== "rows") out.push('$query.shape must be "points" or "rows".');
|
|
3536
|
+
return out;
|
|
3537
|
+
}
|
|
3538
|
+
|
|
3539
|
+
// src/surfaces/primitives.ts
|
|
3540
|
+
var TONES = ["neutral", "positive", "negative", "warning", "info"];
|
|
3541
|
+
var FORMATS2 = ["text", "number", "currency", "percent", "bytes", "duration", "datetime", "code"];
|
|
3542
|
+
var GAPS = ["none", "xs", "sm", "md", "lg"];
|
|
3543
|
+
var fixed = (schema) => ({ ...schema, "x-static": true });
|
|
3544
|
+
var childIds = fixed({ type: "array", items: { type: "string" }, description: "Component ids, in display order." });
|
|
3545
|
+
var childId = (description) => fixed({ type: "string", description });
|
|
3546
|
+
var boundValue = {
|
|
3547
|
+
type: "object",
|
|
3548
|
+
required: ["$path"],
|
|
3549
|
+
properties: { $path: { type: "string" } },
|
|
3550
|
+
additionalProperties: false,
|
|
3551
|
+
description: 'Two-way binding, e.g. { "$path": "/filters/region" }.',
|
|
3552
|
+
"x-static": true
|
|
3553
|
+
};
|
|
3554
|
+
var CONDITION_SCHEMA = fixed({
|
|
3555
|
+
type: "object",
|
|
3556
|
+
required: ["path"],
|
|
3557
|
+
properties: {
|
|
3558
|
+
path: { type: "string" },
|
|
3559
|
+
op: { type: "string", enum: ["truthy", "falsy", "eq", "ne", "gt", "gte", "lt", "lte", "in"] },
|
|
3560
|
+
value: {}
|
|
3561
|
+
},
|
|
3562
|
+
additionalProperties: false
|
|
3563
|
+
});
|
|
3564
|
+
var ACTION_SCHEMA = fixed({
|
|
3565
|
+
type: "object",
|
|
3566
|
+
required: ["type"],
|
|
3567
|
+
description: 'One of { "type": "set", "updates": [{ "path", "value" }] }, { "type": "tool", "tool", "args", "resultPath" }, { "type": "event", "name", "context" }.'
|
|
3568
|
+
});
|
|
3569
|
+
var props = (properties, required = []) => ({
|
|
3570
|
+
type: "object",
|
|
3571
|
+
properties,
|
|
3572
|
+
required,
|
|
3573
|
+
additionalProperties: false
|
|
3574
|
+
});
|
|
3575
|
+
var text2 = (description) => ({ type: "string", ...description ? { description } : {} });
|
|
3576
|
+
var SURFACE_PRIMITIVES = [
|
|
3577
|
+
{
|
|
3578
|
+
name: "Stack",
|
|
3579
|
+
category: "layout",
|
|
3580
|
+
summary: "Arrange children in a column or a row.",
|
|
3581
|
+
props: props(
|
|
3582
|
+
{
|
|
3583
|
+
children: childIds,
|
|
3584
|
+
direction: { type: "string", enum: ["vertical", "horizontal"] },
|
|
3585
|
+
gap: { type: "string", enum: GAPS },
|
|
3586
|
+
align: { type: "string", enum: ["start", "center", "end", "stretch"] },
|
|
3587
|
+
justify: { type: "string", enum: ["start", "center", "end", "between"] },
|
|
3588
|
+
wrap: { type: "boolean" }
|
|
3589
|
+
},
|
|
3590
|
+
["children"]
|
|
3591
|
+
),
|
|
3592
|
+
slots: (p) => p["children"] ?? []
|
|
3593
|
+
},
|
|
3594
|
+
{
|
|
3595
|
+
name: "Grid",
|
|
3596
|
+
category: "layout",
|
|
3597
|
+
summary: "Equal columns that collapse on narrow containers.",
|
|
3598
|
+
props: props(
|
|
3599
|
+
{
|
|
3600
|
+
children: childIds,
|
|
3601
|
+
columns: { type: "integer", minimum: 1, maximum: 4 },
|
|
3602
|
+
gap: { type: "string", enum: GAPS }
|
|
3603
|
+
},
|
|
3604
|
+
["children"]
|
|
3605
|
+
),
|
|
3606
|
+
slots: (p) => p["children"] ?? []
|
|
3607
|
+
},
|
|
3608
|
+
{
|
|
3609
|
+
name: "Section",
|
|
3610
|
+
category: "layout",
|
|
3611
|
+
summary: "A titled group of children.",
|
|
3612
|
+
props: props(
|
|
3613
|
+
{
|
|
3614
|
+
title: text2(),
|
|
3615
|
+
description: text2(),
|
|
3616
|
+
tone: { type: "string", enum: TONES },
|
|
3617
|
+
children: childIds
|
|
3618
|
+
},
|
|
3619
|
+
["children"]
|
|
3620
|
+
),
|
|
3621
|
+
slots: (p) => p["children"] ?? []
|
|
3622
|
+
},
|
|
3623
|
+
{
|
|
3624
|
+
name: "Tabs",
|
|
3625
|
+
category: "layout",
|
|
3626
|
+
summary: "Switch between named panels. Keyboard accessible.",
|
|
3627
|
+
props: props(
|
|
3628
|
+
{
|
|
3629
|
+
label: text2("Names the tab list for screen readers."),
|
|
3630
|
+
value: { ...boundValue, description: "Optional binding for the selected tab id." },
|
|
3631
|
+
tabs: fixed({
|
|
3632
|
+
type: "array",
|
|
3633
|
+
minItems: 1,
|
|
3634
|
+
maxItems: 12,
|
|
3635
|
+
items: {
|
|
3636
|
+
type: "object",
|
|
3637
|
+
required: ["id", "label", "child"],
|
|
3638
|
+
properties: { id: { type: "string" }, label: { type: "string" }, child: { type: "string" } },
|
|
3639
|
+
additionalProperties: false
|
|
3640
|
+
}
|
|
3641
|
+
})
|
|
3642
|
+
},
|
|
3643
|
+
["tabs"]
|
|
3644
|
+
),
|
|
3645
|
+
slots: (p) => (p["tabs"] ?? []).map((t) => t.child)
|
|
3646
|
+
},
|
|
3647
|
+
{
|
|
3648
|
+
name: "List",
|
|
3649
|
+
category: "layout",
|
|
3650
|
+
summary: "Repeat one template for each row of an array; the template reads rows with $item.",
|
|
3651
|
+
props: props(
|
|
3652
|
+
{
|
|
3653
|
+
items: { type: "array", description: "A $path or $query that yields an array." },
|
|
3654
|
+
child: childId("The template component rendered once per row."),
|
|
3655
|
+
emptyText: text2("Shown when there are no rows."),
|
|
3656
|
+
gap: { type: "string", enum: GAPS }
|
|
3657
|
+
},
|
|
3658
|
+
["items", "child"]
|
|
3659
|
+
),
|
|
3660
|
+
slots: (p) => typeof p["child"] === "string" ? [p["child"]] : [],
|
|
3661
|
+
templateSlots: (p) => typeof p["child"] === "string" ? [p["child"]] : []
|
|
3662
|
+
},
|
|
3663
|
+
{ name: "Divider", category: "layout", summary: "A horizontal rule between groups.", props: props({}) },
|
|
3664
|
+
{
|
|
3665
|
+
name: "Text",
|
|
3666
|
+
category: "display",
|
|
3667
|
+
summary: "Plain text. Never parsed as HTML or Markdown.",
|
|
3668
|
+
props: props(
|
|
3669
|
+
{
|
|
3670
|
+
text: { type: ["string", "number"] },
|
|
3671
|
+
variant: { type: "string", enum: ["title", "heading", "body", "caption", "label", "code"] },
|
|
3672
|
+
tone: { type: "string", enum: TONES }
|
|
3673
|
+
},
|
|
3674
|
+
["text"]
|
|
3675
|
+
)
|
|
3676
|
+
},
|
|
3677
|
+
{
|
|
3678
|
+
name: "Metric",
|
|
3679
|
+
category: "display",
|
|
3680
|
+
summary: "One headline number with a label and optional change.",
|
|
3681
|
+
props: props(
|
|
3682
|
+
{
|
|
3683
|
+
label: text2(),
|
|
3684
|
+
value: { type: ["string", "number", "null"] },
|
|
3685
|
+
format: { type: "string", enum: FORMATS2 },
|
|
3686
|
+
delta: { type: "number" },
|
|
3687
|
+
deltaFormat: { type: "string", enum: FORMATS2 },
|
|
3688
|
+
hint: text2(),
|
|
3689
|
+
tone: { type: "string", enum: TONES }
|
|
3690
|
+
},
|
|
3691
|
+
["label", "value"]
|
|
3692
|
+
)
|
|
3693
|
+
},
|
|
3694
|
+
{
|
|
3695
|
+
name: "Badge",
|
|
3696
|
+
category: "display",
|
|
3697
|
+
summary: "A short status label.",
|
|
3698
|
+
props: props({ text: { type: ["string", "number"] }, tone: { type: "string", enum: TONES } }, ["text"])
|
|
3699
|
+
},
|
|
3700
|
+
{
|
|
3701
|
+
name: "Image",
|
|
3702
|
+
category: "display",
|
|
3703
|
+
summary: "An http(s) image with required alt text.",
|
|
3704
|
+
props: props({ src: text2(), alt: text2(), caption: text2() }, ["src", "alt"])
|
|
3705
|
+
},
|
|
3706
|
+
{
|
|
3707
|
+
name: "Link",
|
|
3708
|
+
category: "display",
|
|
3709
|
+
summary: "An http(s) link that opens in a new tab.",
|
|
3710
|
+
props: props({ text: text2(), href: text2() }, ["text", "href"])
|
|
3711
|
+
},
|
|
3712
|
+
{
|
|
3713
|
+
name: "Field",
|
|
3714
|
+
category: "input",
|
|
3715
|
+
summary: "Text, number, date or multi-line input bound to the data model.",
|
|
3716
|
+
props: props(
|
|
3717
|
+
{
|
|
3718
|
+
label: text2(),
|
|
3719
|
+
value: boundValue,
|
|
3720
|
+
type: { type: "string", enum: ["text", "number", "date", "textarea"] },
|
|
3721
|
+
placeholder: text2(),
|
|
3722
|
+
helper: text2(),
|
|
3723
|
+
min: { type: "number" },
|
|
3724
|
+
max: { type: "number" },
|
|
3725
|
+
step: { type: "number" }
|
|
3726
|
+
},
|
|
3727
|
+
["label", "value"]
|
|
3728
|
+
)
|
|
3729
|
+
},
|
|
3730
|
+
{
|
|
3731
|
+
name: "Select",
|
|
3732
|
+
category: "input",
|
|
3733
|
+
summary: "Choose one option; writes its value to the data model.",
|
|
3734
|
+
props: props(
|
|
3735
|
+
{
|
|
3736
|
+
label: text2(),
|
|
3737
|
+
value: boundValue,
|
|
3738
|
+
options: {
|
|
3739
|
+
type: "array",
|
|
3740
|
+
items: {
|
|
3741
|
+
type: "object",
|
|
3742
|
+
required: ["value", "label"],
|
|
3743
|
+
properties: { value: { type: ["string", "number", "boolean"] }, label: { type: "string" } },
|
|
3744
|
+
additionalProperties: false
|
|
3745
|
+
}
|
|
3746
|
+
},
|
|
3747
|
+
helper: text2()
|
|
3748
|
+
},
|
|
3749
|
+
["label", "value", "options"]
|
|
3750
|
+
)
|
|
3751
|
+
},
|
|
3752
|
+
{
|
|
3753
|
+
name: "Toggle",
|
|
3754
|
+
category: "input",
|
|
3755
|
+
summary: "An on/off switch bound to a boolean.",
|
|
3756
|
+
props: props({ label: text2(), value: boundValue, helper: text2() }, ["label", "value"])
|
|
3757
|
+
},
|
|
3758
|
+
{
|
|
3759
|
+
name: "Slider",
|
|
3760
|
+
category: "input",
|
|
3761
|
+
summary: "Pick a number in a range.",
|
|
3762
|
+
props: props(
|
|
3763
|
+
{
|
|
3764
|
+
label: text2(),
|
|
3765
|
+
value: boundValue,
|
|
3766
|
+
min: { type: "number" },
|
|
3767
|
+
max: { type: "number" },
|
|
3768
|
+
step: { type: "number" },
|
|
3769
|
+
format: { type: "string", enum: FORMATS2 }
|
|
3770
|
+
},
|
|
3771
|
+
["label", "value", "min", "max"]
|
|
3772
|
+
)
|
|
3773
|
+
},
|
|
3774
|
+
{
|
|
3775
|
+
name: "Button",
|
|
3776
|
+
category: "action",
|
|
3777
|
+
summary: "Runs one action when pressed: set local state, call an allowed tool, or send the agent an event.",
|
|
3778
|
+
props: props(
|
|
3779
|
+
{
|
|
3780
|
+
label: text2(),
|
|
3781
|
+
action: ACTION_SCHEMA,
|
|
3782
|
+
variant: { type: "string", enum: ["primary", "secondary", "ghost", "danger"] },
|
|
3783
|
+
disabledWhen: CONDITION_SCHEMA
|
|
3784
|
+
},
|
|
3785
|
+
["label", "action"]
|
|
3786
|
+
)
|
|
3128
3787
|
}
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3788
|
+
];
|
|
3789
|
+
|
|
3790
|
+
// src/surfaces/catalogue.ts
|
|
3791
|
+
var CARD_ENTRY_PREFIX = "Card:";
|
|
3792
|
+
var CARD_COMPONENT = {
|
|
3793
|
+
name: "Card",
|
|
3794
|
+
category: "card",
|
|
3795
|
+
summary: "Embed any card kind. `spec` may contain bindings.",
|
|
3796
|
+
props: {
|
|
3797
|
+
type: "object",
|
|
3798
|
+
required: ["kind", "spec"],
|
|
3799
|
+
additionalProperties: false,
|
|
3800
|
+
properties: {
|
|
3801
|
+
kind: { type: "string", description: "A registered card kind.", "x-static": true },
|
|
3802
|
+
spec: { type: "object", description: "The card body, without `kind`.", "x-static": true },
|
|
3803
|
+
bind: { type: "string", description: "Interactive kinds only: JSON Pointer that stores the answer.", "x-static": true },
|
|
3804
|
+
action: ACTION_SCHEMA
|
|
3805
|
+
}
|
|
3133
3806
|
}
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3807
|
+
};
|
|
3808
|
+
var SurfaceCatalogue = class {
|
|
3809
|
+
cards;
|
|
3810
|
+
definitions = /* @__PURE__ */ new Map();
|
|
3811
|
+
constructor(options = {}) {
|
|
3812
|
+
this.cards = options.cards;
|
|
3813
|
+
for (const def of SURFACE_PRIMITIVES) this.definitions.set(def.name, def);
|
|
3814
|
+
this.definitions.set(CARD_COMPONENT.name, CARD_COMPONENT);
|
|
3815
|
+
for (const def of options.components ?? []) this.register(def);
|
|
3816
|
+
}
|
|
3817
|
+
/** Add a host component. A built-in name cannot be replaced: its meaning is part of the format. */
|
|
3818
|
+
register(def) {
|
|
3819
|
+
const existing = this.definitions.get(def.name);
|
|
3820
|
+
if (existing && existing.category !== "custom") throw new Error(`Surface component "${def.name}" is built in and cannot be replaced.`);
|
|
3821
|
+
if (def.name.startsWith(CARD_ENTRY_PREFIX)) throw new Error(`Surface component names cannot start with "${CARD_ENTRY_PREFIX}".`);
|
|
3822
|
+
this.definitions.set(def.name, { ...def, category: "custom" });
|
|
3139
3823
|
return this;
|
|
3140
3824
|
}
|
|
3141
|
-
/**
|
|
3142
|
-
* Change notification, so a UI (or an inspector hook) re-reads after a LATE
|
|
3143
|
-
* registration — tools imported from an MCP server arrive long after mount,
|
|
3144
|
-
* and a registry nobody can observe leaves them invisible until reload.
|
|
3145
|
-
*/
|
|
3146
|
-
subscribe(listener) {
|
|
3147
|
-
this.listeners.add(listener);
|
|
3148
|
-
return () => {
|
|
3149
|
-
this.listeners.delete(listener);
|
|
3150
|
-
};
|
|
3151
|
-
}
|
|
3152
|
-
/** Monotonic change counter — a stable snapshot value for useSyncExternalStore. */
|
|
3153
|
-
getVersion() {
|
|
3154
|
-
return this.version;
|
|
3155
|
-
}
|
|
3156
|
-
touch() {
|
|
3157
|
-
this.version += 1;
|
|
3158
|
-
this.reversePresetIndex = null;
|
|
3159
|
-
for (const l of this.listeners) l();
|
|
3160
|
-
}
|
|
3161
3825
|
get(name) {
|
|
3162
|
-
return this.
|
|
3826
|
+
return this.definitions.get(name);
|
|
3163
3827
|
}
|
|
3164
3828
|
has(name) {
|
|
3165
|
-
return this.
|
|
3829
|
+
return this.definitions.has(name);
|
|
3166
3830
|
}
|
|
3167
|
-
|
|
3168
|
-
|
|
3831
|
+
/** Card kinds usable inside a surface. A surface cannot contain a surface. */
|
|
3832
|
+
cardKinds() {
|
|
3833
|
+
return (this.cards?.list() ?? []).filter((k) => k.kind !== SURFACE_CARD_KIND);
|
|
3169
3834
|
}
|
|
3170
|
-
|
|
3171
|
-
|
|
3835
|
+
/** Every addressable entry: components by name, cards as `Card:<kind>`. */
|
|
3836
|
+
names() {
|
|
3837
|
+
return [...this.definitions.keys(), ...this.cardKinds().map((k) => `${CARD_ENTRY_PREFIX}${k.kind}`)];
|
|
3172
3838
|
}
|
|
3173
|
-
/**
|
|
3174
|
-
|
|
3175
|
-
|
|
3839
|
+
/** One line per entry. Cheap enough to hand over whenever the model asks what exists. */
|
|
3840
|
+
index() {
|
|
3841
|
+
const lines = [...this.definitions.values()].map((d) => `- ${d.name} (${d.category}): ${d.summary}`);
|
|
3842
|
+
for (const k of this.cardKinds()) {
|
|
3843
|
+
lines.push(`- ${CARD_ENTRY_PREFIX}${k.kind}${k.interactive ? " (interactive, needs `bind`)" : ""}: ${k.summary}`);
|
|
3844
|
+
}
|
|
3845
|
+
return lines.join("\n");
|
|
3176
3846
|
}
|
|
3177
|
-
/**
|
|
3178
|
-
|
|
3179
|
-
|
|
3847
|
+
/** The full schema of one entry, or `undefined` for a name that does not exist. */
|
|
3848
|
+
schemaOf(name) {
|
|
3849
|
+
if (name.startsWith(CARD_ENTRY_PREFIX)) {
|
|
3850
|
+
const kind = name.slice(CARD_ENTRY_PREFIX.length);
|
|
3851
|
+
const def2 = this.cardKinds().find((k) => k.kind === kind);
|
|
3852
|
+
if (!def2) return void 0;
|
|
3853
|
+
return { name, summary: def2.summary, props: def2.schema, ...def2.interactive ? { interactive: true } : {} };
|
|
3854
|
+
}
|
|
3855
|
+
const def = this.definitions.get(name);
|
|
3856
|
+
return def ? { name: def.name, summary: def.summary, props: def.props } : void 0;
|
|
3180
3857
|
}
|
|
3181
|
-
|
|
3182
|
-
|
|
3183
|
-
|
|
3184
|
-
|
|
3185
|
-
|
|
3186
|
-
|
|
3187
|
-
|
|
3188
|
-
|
|
3189
|
-
|
|
3858
|
+
};
|
|
3859
|
+
|
|
3860
|
+
// src/surfaces/validate.ts
|
|
3861
|
+
var ID = /^[A-Za-z0-9_.:-]{1,64}$/;
|
|
3862
|
+
var isSurfaceId = (value) => typeof value === "string" && ID.test(value);
|
|
3863
|
+
var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
3864
|
+
var RESERVED = /* @__PURE__ */ new Set(["id", "component", "visibleWhen"]);
|
|
3865
|
+
function collectBindings(value, out = []) {
|
|
3866
|
+
if (Array.isArray(value)) for (const v of value) collectBindings(v, out);
|
|
3867
|
+
else if (isSurfaceBinding(value)) {
|
|
3868
|
+
out.push(value);
|
|
3869
|
+
if ("$query" in value && isObject(value.$query) && Array.isArray(value.$query.where)) {
|
|
3870
|
+
for (const clause of value.$query.where) collectBindings(isObject(clause) ? clause["value"] : void 0, out);
|
|
3871
|
+
}
|
|
3872
|
+
} else if (isObject(value)) for (const v of Object.values(value)) collectBindings(v, out);
|
|
3873
|
+
return out;
|
|
3874
|
+
}
|
|
3875
|
+
function bindingIssues(value, componentId) {
|
|
3876
|
+
return collectBindings(value).flatMap(
|
|
3877
|
+
(binding) => bindingProblems(binding).map((message2) => ({
|
|
3878
|
+
code: "invalid-binding",
|
|
3879
|
+
componentId,
|
|
3880
|
+
message: message2,
|
|
3881
|
+
fix: 'Use { "$path": "/a/b" }, { "$template": "Text {/a}" }, { "$query": { "from": "/rows" } }, or { "$item": "field" } inside a List.'
|
|
3882
|
+
}))
|
|
3883
|
+
);
|
|
3884
|
+
}
|
|
3885
|
+
function validateSurfaceAction(action, componentId, ctx) {
|
|
3886
|
+
const bad = (message2, fix, code = "invalid-action") => [
|
|
3887
|
+
{ code, componentId, path: "/action", message: message2, fix }
|
|
3888
|
+
];
|
|
3889
|
+
const closed = 'Use { "type": "set", "updates": [...] }, { "type": "tool", "tool": "name", "args": {} } or { "type": "event", "name": "name" }.';
|
|
3890
|
+
if (!isObject(action)) return bad("action must be an object.", closed);
|
|
3891
|
+
const onlyKeys = (allowed) => {
|
|
3892
|
+
const extra = Object.keys(action).filter((k) => !allowed.includes(k));
|
|
3893
|
+
return extra.length ? bad(`action has no "${extra[0]}". Actions cannot carry code or URLs.`, `Allowed keys: ${allowed.join(", ")}.`) : [];
|
|
3894
|
+
};
|
|
3895
|
+
const typed = action;
|
|
3896
|
+
switch (typed.type) {
|
|
3897
|
+
case "set": {
|
|
3898
|
+
const extra = onlyKeys(["type", "updates"]);
|
|
3899
|
+
if (extra.length) return extra;
|
|
3900
|
+
if (!Array.isArray(typed.updates) || !typed.updates.length || typed.updates.length > SURFACE_LIMITS.actionUpdates) {
|
|
3901
|
+
return bad(`set needs 1 to ${SURFACE_LIMITS.actionUpdates} updates.`, 'Send "updates": [{ "path": "/a", "value": 1 }].');
|
|
3190
3902
|
}
|
|
3903
|
+
for (const update of typed.updates) {
|
|
3904
|
+
if (!isObject(update) || !parsePointer(update.path)) return bad("Each update needs a JSON Pointer `path`.", 'Send { "path": "/a", "value": 1 }.');
|
|
3905
|
+
}
|
|
3906
|
+
return bindingIssues(typed.updates, componentId);
|
|
3907
|
+
}
|
|
3908
|
+
case "tool": {
|
|
3909
|
+
const extra = onlyKeys(["type", "tool", "args", "resultPath"]);
|
|
3910
|
+
if (extra.length) return extra;
|
|
3911
|
+
if (typeof typed.tool !== "string" || !typed.tool) return bad("A tool action needs a `tool` name.", 'Send { "type": "tool", "tool": "name" }.');
|
|
3912
|
+
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.");
|
|
3913
|
+
if (typed.resultPath !== void 0 && !parsePointer(typed.resultPath)) return bad("`resultPath` must be a JSON Pointer.", 'Send "resultPath": "/result".');
|
|
3914
|
+
if (ctx.actionTools && !ctx.actionTools.includes(typed.tool)) {
|
|
3915
|
+
return bad(
|
|
3916
|
+
`Tool "${typed.tool}" is not available to this surface.`,
|
|
3917
|
+
ctx.actionTools.length ? `Available: ${ctx.actionTools.slice(0, 24).join(", ")}.` : 'No tools are available; use an "event" action instead.',
|
|
3918
|
+
"tool-not-allowed"
|
|
3919
|
+
);
|
|
3920
|
+
}
|
|
3921
|
+
return bindingIssues(typed.args, componentId);
|
|
3191
3922
|
}
|
|
3192
|
-
|
|
3193
|
-
|
|
3923
|
+
case "event": {
|
|
3924
|
+
const extra = onlyKeys(["type", "name", "context"]);
|
|
3925
|
+
if (extra.length) return extra;
|
|
3926
|
+
if (!isSurfaceId(typed.name)) return bad("An event needs a short `name`.", 'Send { "type": "event", "name": "apply" }.');
|
|
3927
|
+
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.");
|
|
3928
|
+
return bindingIssues(typed.context, componentId);
|
|
3929
|
+
}
|
|
3930
|
+
default:
|
|
3931
|
+
return bad(`Unknown action type ${JSON.stringify(action.type)}.`, closed);
|
|
3932
|
+
}
|
|
3933
|
+
}
|
|
3934
|
+
function validateCard(raw, ctx) {
|
|
3935
|
+
const id = raw.id;
|
|
3936
|
+
const kind = raw["kind"];
|
|
3937
|
+
const registry = ctx.catalogue.cards;
|
|
3938
|
+
const available = ctx.catalogue.cardKinds().map((k) => k.kind);
|
|
3939
|
+
if (typeof kind !== "string" || kind === SURFACE_CARD_KIND || !registry?.has(kind)) {
|
|
3940
|
+
return [{ code: "invalid-card", componentId: id, path: "/kind", message: `Unknown card kind ${JSON.stringify(kind)}.`, fix: `One of: ${available.join(", ") || "(no card registry)"}.` }];
|
|
3941
|
+
}
|
|
3942
|
+
const spec = raw["spec"];
|
|
3943
|
+
if (!isObject(spec)) return [{ code: "invalid-card", componentId: id, path: "/spec", message: "Card `spec` must be an object.", fix: "Send the card body as `spec`." }];
|
|
3944
|
+
const issues = bindingIssues(spec, id);
|
|
3945
|
+
if (registry.isInteractive(kind) && !parsePointer(raw["bind"])) {
|
|
3946
|
+
issues.push({
|
|
3947
|
+
code: "invalid-card",
|
|
3948
|
+
componentId: id,
|
|
3949
|
+
path: "/bind",
|
|
3950
|
+
message: `Interactive card "${kind}" needs \`bind\`, the place its answer is stored.`,
|
|
3951
|
+
fix: 'Add "bind": "/answers/decision".'
|
|
3952
|
+
});
|
|
3194
3953
|
}
|
|
3195
|
-
|
|
3196
|
-
|
|
3197
|
-
|
|
3198
|
-
|
|
3199
|
-
|
|
3200
|
-
|
|
3201
|
-
|
|
3202
|
-
|
|
3203
|
-
|
|
3204
|
-
|
|
3205
|
-
|
|
3206
|
-
|
|
3207
|
-
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
|
|
3212
|
-
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3954
|
+
if (raw["action"] !== void 0) issues.push(...validateSurfaceAction(raw["action"], id, ctx));
|
|
3955
|
+
if (issues.length) return issues;
|
|
3956
|
+
if (usesBinding(spec, "$item")) return [];
|
|
3957
|
+
if (ctx.deferBoundCards && (usesBinding(spec, "$path") || usesBinding(spec, "$query") || usesBinding(spec, "$template"))) return [];
|
|
3958
|
+
const verdict = registry.validate({ ...resolveSurfaceValue(spec, { data: ctx.data }), kind });
|
|
3959
|
+
return verdict.ok ? [] : [{ code: "invalid-card", componentId: id, path: "/spec", message: verdict.error, fix: verdict.expected ?? `Call describeSurfaceComponents for ${"`"}Card:${kind}${"`"}.` }];
|
|
3960
|
+
}
|
|
3961
|
+
function validateSurfaceComponent(raw, ctx) {
|
|
3962
|
+
if (!isObject(raw)) return [{ code: "invalid-shape", message: "Each component must be an object.", fix: 'Send { "id": "a", "component": "Text", "text": "Hello" }.' }];
|
|
3963
|
+
const id = raw["id"];
|
|
3964
|
+
if (!isSurfaceId(id)) return [{ code: "invalid-shape", message: `Component id ${JSON.stringify(id)} is invalid.`, fix: "Use 1 to 64 letters, digits, or . _ : -" }];
|
|
3965
|
+
const component = raw;
|
|
3966
|
+
const name = component.component;
|
|
3967
|
+
const def = typeof name === "string" ? ctx.catalogue.get(name) : void 0;
|
|
3968
|
+
if (!def) {
|
|
3969
|
+
return [{
|
|
3970
|
+
code: "unknown-component",
|
|
3971
|
+
componentId: id,
|
|
3972
|
+
path: "/component",
|
|
3973
|
+
message: `Unknown component ${JSON.stringify(name)}.`,
|
|
3974
|
+
fix: `One of: ${ctx.catalogue.names().filter((n) => !n.startsWith("Card:")).join(", ")}. Cards use "component": "Card" with a "kind".`
|
|
3975
|
+
}];
|
|
3976
|
+
}
|
|
3977
|
+
const isCard = def.name === "Card";
|
|
3978
|
+
const unsafe = findUnsafe(raw, { markup: !isCard && def.category !== "custom" });
|
|
3979
|
+
if (unsafe) {
|
|
3980
|
+
return [{ code: "unsafe-content", componentId: id, path: unsafe.path, message: `${unsafe.path || "The component"} ${unsafe.reason}.`, fix: "Send plain text and http(s) URLs only. Surfaces cannot carry script, HTML or CSS." }];
|
|
3981
|
+
}
|
|
3982
|
+
const props2 = Object.fromEntries(Object.entries(raw).filter(([k]) => !RESERVED.has(k)));
|
|
3983
|
+
const issues = checkSchema(def.props, props2, "", { isDynamic: isSurfaceBinding }).map((p) => ({
|
|
3984
|
+
code: "invalid-prop",
|
|
3985
|
+
componentId: id,
|
|
3986
|
+
path: p.path,
|
|
3987
|
+
message: `${def.name}: ${p.message}`,
|
|
3988
|
+
fix: p.expected ?? `Call describeSurfaceComponents for ${def.name}.`
|
|
3989
|
+
}));
|
|
3990
|
+
if (raw["visibleWhen"] !== void 0) {
|
|
3991
|
+
const condition = raw["visibleWhen"];
|
|
3992
|
+
if (!isObject(condition) || !parsePointer(condition["path"])) {
|
|
3993
|
+
issues.push({ code: "invalid-binding", componentId: id, path: "/visibleWhen", message: "visibleWhen needs a JSON Pointer `path`.", fix: 'Send { "path": "/showDetails" }.' });
|
|
3217
3994
|
}
|
|
3218
|
-
|
|
3219
|
-
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
|
|
3995
|
+
}
|
|
3996
|
+
if (issues.length) return issues;
|
|
3997
|
+
if (isCard) return validateCard(component, ctx);
|
|
3998
|
+
const out = bindingIssues(props2, id);
|
|
3999
|
+
for (const key of ["value"]) {
|
|
4000
|
+
const bound = props2[key];
|
|
4001
|
+
if (def.category === "input" && isObject(bound) && !parsePointer(bound["$path"])) {
|
|
4002
|
+
out.push({ code: "invalid-binding", componentId: id, path: `/${key}`, message: `${def.name}.value must be a writable $path.`, fix: 'Send "value": { "$path": "/filters/region" }.' });
|
|
3223
4003
|
}
|
|
3224
|
-
for (const name of resolution.deny ?? []) allowed.delete(name);
|
|
3225
|
-
return [...allowed].map((n) => this.tools.get(n)).filter((t) => t !== void 0).sort((a, b) => a.name.localeCompare(b.name));
|
|
3226
4004
|
}
|
|
3227
|
-
|
|
3228
|
-
|
|
3229
|
-
|
|
3230
|
-
|
|
3231
|
-
|
|
3232
|
-
|
|
4005
|
+
if (props2["action"] !== void 0) out.push(...validateSurfaceAction(props2["action"], id, ctx));
|
|
4006
|
+
if (props2["disabledWhen"] !== void 0 && !parsePointer(props2["disabledWhen"].path)) {
|
|
4007
|
+
out.push({ code: "invalid-binding", componentId: id, path: "/disabledWhen", message: "disabledWhen needs a JSON Pointer `path`.", fix: 'Send { "path": "/busy" }.' });
|
|
4008
|
+
}
|
|
4009
|
+
return out;
|
|
4010
|
+
}
|
|
4011
|
+
function validateSurfaceComponents(raw, ctx) {
|
|
4012
|
+
const components = [];
|
|
4013
|
+
const issues = [];
|
|
4014
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4015
|
+
for (const entry of raw) {
|
|
4016
|
+
const found = validateSurfaceComponent(entry, ctx);
|
|
4017
|
+
if (found.length) {
|
|
4018
|
+
issues.push(...found);
|
|
4019
|
+
continue;
|
|
4020
|
+
}
|
|
4021
|
+
const component = entry;
|
|
4022
|
+
if (seen.has(component.id)) {
|
|
4023
|
+
issues.push({ code: "duplicate-id", componentId: component.id, message: `Component id "${component.id}" is used twice.`, fix: "Give every component its own id." });
|
|
4024
|
+
continue;
|
|
4025
|
+
}
|
|
4026
|
+
seen.add(component.id);
|
|
4027
|
+
components.push(component);
|
|
4028
|
+
}
|
|
4029
|
+
return { components, issues };
|
|
4030
|
+
}
|
|
4031
|
+
function validateSurfaceGraph(root, components, catalogue, rejected = /* @__PURE__ */ new Set()) {
|
|
4032
|
+
const byId = new Map(components.map((c) => [c.id, c]));
|
|
4033
|
+
const issues = [];
|
|
4034
|
+
if (!byId.has(root)) {
|
|
4035
|
+
if (!rejected.has(root)) issues.push({ code: "missing-root", componentId: root, message: `Root "${root}" is not in the component list.`, fix: "Add a component with that id, or set `root` to one that exists." });
|
|
4036
|
+
return issues;
|
|
4037
|
+
}
|
|
4038
|
+
const slotsOf = (c) => {
|
|
4039
|
+
try {
|
|
4040
|
+
return catalogue.get(c.component)?.slots?.(c) ?? [];
|
|
4041
|
+
} catch {
|
|
4042
|
+
return [];
|
|
4043
|
+
}
|
|
4044
|
+
};
|
|
4045
|
+
const templatesOf = (c) => {
|
|
4046
|
+
try {
|
|
4047
|
+
return catalogue.get(c.component)?.templateSlots?.(c) ?? [];
|
|
4048
|
+
} catch {
|
|
4049
|
+
return [];
|
|
4050
|
+
}
|
|
4051
|
+
};
|
|
4052
|
+
const reported = /* @__PURE__ */ new Set();
|
|
4053
|
+
const once = (key, issue) => {
|
|
4054
|
+
if (reported.has(key)) return;
|
|
4055
|
+
reported.add(key);
|
|
4056
|
+
issues.push(issue);
|
|
4057
|
+
};
|
|
4058
|
+
const visit = (id, trail, inTemplate) => {
|
|
4059
|
+
const component = byId.get(id);
|
|
4060
|
+
if (!component) return;
|
|
4061
|
+
if (trail.includes(id)) {
|
|
4062
|
+
once(`cycle:${id}`, { code: "cycle", componentId: id, message: `Component "${id}" contains itself.`, fix: "Remove the reference that loops back." });
|
|
4063
|
+
return;
|
|
4064
|
+
}
|
|
4065
|
+
if (trail.length >= SURFACE_LIMITS.depth) {
|
|
4066
|
+
once(`depth:${id}`, { code: "too-deep", componentId: id, message: `Nesting is deeper than ${SURFACE_LIMITS.depth} levels.`, fix: "Flatten the layout." });
|
|
4067
|
+
return;
|
|
4068
|
+
}
|
|
4069
|
+
if (!inTemplate && usesBinding(component, "$item")) {
|
|
4070
|
+
once(`item:${id}`, { code: "invalid-binding", componentId: id, message: `"${id}" reads $item outside a List template.`, fix: "Use $path here, or move it under a List's `child`." });
|
|
4071
|
+
}
|
|
4072
|
+
const templates = templatesOf(component);
|
|
4073
|
+
for (const child2 of slotsOf(component)) {
|
|
4074
|
+
if (!byId.has(child2)) {
|
|
4075
|
+
if (!rejected.has(child2)) once(`missing:${child2}`, { code: "missing-child", componentId: id, message: `"${id}" references "${child2}", which does not exist.`, fix: `Add a component with id "${child2}" or remove the reference.` });
|
|
4076
|
+
continue;
|
|
4077
|
+
}
|
|
4078
|
+
visit(child2, [...trail, id], inTemplate || templates.includes(child2));
|
|
4079
|
+
}
|
|
4080
|
+
};
|
|
4081
|
+
visit(root, [], false);
|
|
4082
|
+
return issues;
|
|
4083
|
+
}
|
|
4084
|
+
|
|
4085
|
+
// src/surfaces/operations.ts
|
|
4086
|
+
var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
4087
|
+
var fatal = (issue) => ({ issues: [issue] });
|
|
4088
|
+
function dataIssue(data) {
|
|
4089
|
+
const unsafe = findUnsafe(data);
|
|
4090
|
+
if (unsafe) {
|
|
4091
|
+
return { code: "unsafe-content", path: unsafe.path, message: `data${unsafe.path} ${unsafe.reason}.`, fix: "Store plain values and http(s) URLs only." };
|
|
4092
|
+
}
|
|
4093
|
+
if (JSON.stringify(data).length > SURFACE_LIMITS.dataChars) {
|
|
4094
|
+
return { code: "limit-exceeded", path: "/data", message: `data is larger than ${SURFACE_LIMITS.dataChars} characters.`, fix: "Send a summary or fewer rows." };
|
|
4095
|
+
}
|
|
4096
|
+
return void 0;
|
|
4097
|
+
}
|
|
4098
|
+
var tooMany = (count) => ({
|
|
4099
|
+
code: "limit-exceeded",
|
|
4100
|
+
message: `A surface may hold ${SURFACE_LIMITS.components} components; this has ${count}.`,
|
|
4101
|
+
fix: "Use a List template instead of repeating components."
|
|
4102
|
+
});
|
|
4103
|
+
function persistentIssues(components, issues) {
|
|
4104
|
+
const present = new Set(components.map((c) => c.id));
|
|
4105
|
+
return issues.filter((i) => !i.componentId || !present.has(i.componentId) || i.code === "missing-child" || i.code === "cycle" || i.code === "too-deep" || i.code === "invalid-binding");
|
|
4106
|
+
}
|
|
4107
|
+
function buildSurface(input, ctx, opts = {}) {
|
|
4108
|
+
if (!isObject2(input)) return fatal({ code: "invalid-shape", message: "Surface must be an object.", fix: "Send surfaceId, root and components." });
|
|
4109
|
+
const { surfaceId, root, components, data, title } = input;
|
|
4110
|
+
if (!isSurfaceId(surfaceId)) return fatal({ code: "invalid-shape", path: "/surfaceId", message: "surfaceId is missing or invalid.", fix: 'Send a short id such as "overview".' });
|
|
4111
|
+
if (!isSurfaceId(root)) return fatal({ code: "missing-root", path: "/root", message: "root must be the id of a component.", fix: 'Send "root": "main" and a component with that id.' });
|
|
4112
|
+
if (!Array.isArray(components) || !components.length) return fatal({ code: "invalid-shape", path: "/components", message: "components must be a non-empty array.", fix: 'Send [{ "id": "main", "component": "Stack", "children": [] }].' });
|
|
4113
|
+
if (components.length > SURFACE_LIMITS.components) return fatal(tooMany(components.length));
|
|
4114
|
+
if (data !== void 0 && !isObject2(data)) return fatal({ code: "invalid-data", path: "/data", message: "data must be an object.", fix: 'Send "data": { "filters": {} }.' });
|
|
4115
|
+
const model = data ?? {};
|
|
4116
|
+
const bad = dataIssue(model);
|
|
4117
|
+
if (bad) return fatal(bad);
|
|
4118
|
+
if (JSON.stringify(components).length > SURFACE_LIMITS.specChars) {
|
|
4119
|
+
return fatal({ code: "limit-exceeded", path: "/components", message: `components exceed ${SURFACE_LIMITS.specChars} characters.`, fix: "Move repeated content into data and use a List." });
|
|
4120
|
+
}
|
|
4121
|
+
const validation = { catalogue: ctx.catalogue, data: model, actionTools: ctx.actionTools };
|
|
4122
|
+
const checked = validateSurfaceComponents(components, validation);
|
|
4123
|
+
const rejected = new Set(checked.issues.flatMap((i) => i.componentId ? [i.componentId] : []));
|
|
4124
|
+
const graph = validateSurfaceGraph(root, checked.components, ctx.catalogue, rejected);
|
|
4125
|
+
const issues = [...checked.issues, ...graph];
|
|
4126
|
+
const kept = persistentIssues(checked.components, issues);
|
|
4127
|
+
return {
|
|
4128
|
+
issues,
|
|
4129
|
+
spec: {
|
|
4130
|
+
kind: SURFACE_CARD_KIND,
|
|
4131
|
+
version: SURFACE_FORMAT_VERSION,
|
|
4132
|
+
surfaceId,
|
|
4133
|
+
...typeof title === "string" && title ? { title } : {},
|
|
4134
|
+
root,
|
|
4135
|
+
components: checked.components,
|
|
4136
|
+
data: model,
|
|
4137
|
+
revision: opts.revision ?? 1,
|
|
4138
|
+
...opts.originCallId ? { originCallId: opts.originCallId } : {},
|
|
4139
|
+
...kept.length ? { issues: kept } : {}
|
|
4140
|
+
}
|
|
4141
|
+
};
|
|
4142
|
+
}
|
|
4143
|
+
function applySurfaceOperations(spec, operations, ctx) {
|
|
4144
|
+
if (!Array.isArray(operations) || !operations.length) {
|
|
4145
|
+
return fatal({ code: "invalid-shape", path: "/operations", message: "operations must be a non-empty array.", fix: 'Send [{ "op": "setData", "path": "/a", "value": 1 }].' });
|
|
4146
|
+
}
|
|
4147
|
+
const issues = [];
|
|
4148
|
+
let data = spec.data;
|
|
4149
|
+
const ops = operations;
|
|
4150
|
+
for (const op of ops) {
|
|
4151
|
+
if (!isObject2(op)) continue;
|
|
4152
|
+
if (op.op === "setData") {
|
|
4153
|
+
const unsafe = findUnsafe(op.value);
|
|
4154
|
+
const next = unsafe ? void 0 : setAt(data, op.path, op.value);
|
|
4155
|
+
if (next) data = next;
|
|
4156
|
+
else issues.push({ code: unsafe ? "unsafe-content" : "invalid-data", path: op.path, message: unsafe ? `The value ${unsafe.path} ${unsafe.reason}.` : `Cannot write to ${JSON.stringify(op.path)}.`, fix: 'Use a JSON Pointer such as "/filters/region" with a plain value.' });
|
|
4157
|
+
} else if (op.op === "removeData") {
|
|
4158
|
+
const next = removeAt(data, op.path);
|
|
4159
|
+
if (next) data = next;
|
|
4160
|
+
else issues.push({ code: "invalid-data", path: op.path, message: `Cannot remove ${JSON.stringify(op.path)}.`, fix: 'Use a JSON Pointer such as "/filters/region".' });
|
|
4161
|
+
}
|
|
4162
|
+
}
|
|
4163
|
+
const bad = dataIssue(data);
|
|
4164
|
+
if (bad) return fatal(bad);
|
|
4165
|
+
const validation = { catalogue: ctx.catalogue, data, actionTools: ctx.actionTools };
|
|
4166
|
+
const byId = new Map(spec.components.map((c) => [c.id, c]));
|
|
4167
|
+
const rejected = new Set((spec.issues ?? []).flatMap((i) => i.componentId && !byId.has(i.componentId) ? [i.componentId] : []));
|
|
4168
|
+
const carried = /* @__PURE__ */ new Map();
|
|
4169
|
+
for (const issue of spec.issues ?? []) {
|
|
4170
|
+
if (issue.componentId && rejected.has(issue.componentId)) carried.set(issue.componentId, [...carried.get(issue.componentId) ?? [], issue]);
|
|
4171
|
+
}
|
|
4172
|
+
let root = spec.root;
|
|
4173
|
+
let title = spec.title;
|
|
4174
|
+
for (const op of ops) {
|
|
4175
|
+
if (!isObject2(op)) {
|
|
4176
|
+
issues.push({ code: "invalid-shape", message: "Each operation must be an object.", fix: "Send { op, ... }." });
|
|
4177
|
+
continue;
|
|
4178
|
+
}
|
|
4179
|
+
switch (op.op) {
|
|
4180
|
+
case "setData":
|
|
4181
|
+
case "removeData":
|
|
4182
|
+
break;
|
|
4183
|
+
case "upsertComponents": {
|
|
4184
|
+
if (!Array.isArray(op.components)) {
|
|
4185
|
+
issues.push({ code: "invalid-shape", path: "/components", message: "upsertComponents needs a `components` array.", fix: "Send the changed components in full." });
|
|
4186
|
+
break;
|
|
4187
|
+
}
|
|
4188
|
+
for (const raw of op.components) {
|
|
4189
|
+
const found = validateSurfaceComponent(raw, validation);
|
|
4190
|
+
const id = isObject2(raw) && typeof raw["id"] === "string" ? raw["id"] : void 0;
|
|
4191
|
+
if (found.length) {
|
|
4192
|
+
issues.push(...found);
|
|
4193
|
+
if (id && !byId.has(id)) {
|
|
4194
|
+
rejected.add(id);
|
|
4195
|
+
carried.set(id, found);
|
|
4196
|
+
}
|
|
4197
|
+
continue;
|
|
4198
|
+
}
|
|
4199
|
+
const component = raw;
|
|
4200
|
+
byId.set(component.id, component);
|
|
4201
|
+
rejected.delete(component.id);
|
|
4202
|
+
carried.delete(component.id);
|
|
4203
|
+
}
|
|
4204
|
+
break;
|
|
4205
|
+
}
|
|
4206
|
+
case "removeComponents": {
|
|
4207
|
+
const ids = new Set(Array.isArray(op.ids) ? op.ids : []);
|
|
4208
|
+
for (const id of ids) {
|
|
4209
|
+
byId.delete(id);
|
|
4210
|
+
rejected.delete(id);
|
|
4211
|
+
carried.delete(id);
|
|
4212
|
+
}
|
|
4213
|
+
for (const [id, component] of byId) {
|
|
4214
|
+
const children = component["children"];
|
|
4215
|
+
if (Array.isArray(children) && children.some((c) => ids.has(c))) {
|
|
4216
|
+
byId.set(id, { ...component, children: children.filter((c) => !ids.has(c)) });
|
|
4217
|
+
}
|
|
4218
|
+
}
|
|
4219
|
+
break;
|
|
4220
|
+
}
|
|
4221
|
+
case "setRoot":
|
|
4222
|
+
if (isSurfaceId(op.root)) root = op.root;
|
|
4223
|
+
else issues.push({ code: "missing-root", path: "/root", message: "setRoot needs a component id.", fix: 'Send { "op": "setRoot", "root": "main" }.' });
|
|
4224
|
+
break;
|
|
4225
|
+
case "setTitle":
|
|
4226
|
+
if (typeof op.title === "string") title = op.title;
|
|
4227
|
+
else issues.push({ code: "invalid-shape", path: "/title", message: "setTitle needs a string `title`.", fix: 'Send { "op": "setTitle", "title": "Overview" }.' });
|
|
4228
|
+
break;
|
|
4229
|
+
default:
|
|
4230
|
+
issues.push({
|
|
4231
|
+
code: "invalid-shape",
|
|
4232
|
+
message: `Unknown operation ${JSON.stringify(op.op)}.`,
|
|
4233
|
+
fix: "Use upsertComponents, removeComponents, setRoot, setTitle, setData or removeData."
|
|
4234
|
+
});
|
|
4235
|
+
}
|
|
4236
|
+
}
|
|
4237
|
+
const components = [...byId.values()];
|
|
4238
|
+
if (components.length > SURFACE_LIMITS.components) return fatal(tooMany(components.length));
|
|
4239
|
+
const graph = validateSurfaceGraph(root, components, ctx.catalogue, rejected);
|
|
4240
|
+
issues.push(...graph);
|
|
4241
|
+
const kept = [...[...carried.values()].flat(), ...graph];
|
|
4242
|
+
const { issues: _previous, title: _title, ...rest } = spec;
|
|
4243
|
+
return {
|
|
4244
|
+
issues,
|
|
4245
|
+
spec: {
|
|
4246
|
+
...rest,
|
|
4247
|
+
...title ? { title } : {},
|
|
4248
|
+
root,
|
|
4249
|
+
components,
|
|
4250
|
+
data,
|
|
4251
|
+
revision: spec.revision + 1,
|
|
4252
|
+
...kept.length ? { issues: kept } : {}
|
|
4253
|
+
}
|
|
4254
|
+
};
|
|
4255
|
+
}
|
|
4256
|
+
function previewSurface(partial, catalogue) {
|
|
4257
|
+
if (!isObject2(partial)) return void 0;
|
|
4258
|
+
const { surfaceId, root, components, data, title } = partial;
|
|
4259
|
+
if (!isSurfaceId(surfaceId) || !isSurfaceId(root) || !Array.isArray(components)) return void 0;
|
|
4260
|
+
const model = isObject2(data) && !findUnsafe(data) ? data : {};
|
|
4261
|
+
const validation = { catalogue, data: model };
|
|
4262
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4263
|
+
const valid = [];
|
|
4264
|
+
for (const raw of components.slice(0, SURFACE_LIMITS.components)) {
|
|
4265
|
+
if (validateSurfaceComponent(raw, validation).length) continue;
|
|
4266
|
+
const component = raw;
|
|
4267
|
+
if (seen.has(component.id)) continue;
|
|
4268
|
+
seen.add(component.id);
|
|
4269
|
+
valid.push(component);
|
|
4270
|
+
}
|
|
4271
|
+
if (!valid.length) return void 0;
|
|
4272
|
+
return {
|
|
4273
|
+
kind: SURFACE_CARD_KIND,
|
|
4274
|
+
version: SURFACE_FORMAT_VERSION,
|
|
4275
|
+
surfaceId,
|
|
4276
|
+
...typeof title === "string" && title ? { title } : {},
|
|
4277
|
+
root,
|
|
4278
|
+
components: valid,
|
|
4279
|
+
data: model,
|
|
4280
|
+
revision: 0
|
|
4281
|
+
};
|
|
4282
|
+
}
|
|
4283
|
+
function sanitizeSurfaceSpec(spec, catalogue) {
|
|
4284
|
+
const components = Array.isArray(spec.components) ? spec.components.slice(0, SURFACE_LIMITS.components) : [];
|
|
4285
|
+
const data = isObject2(spec.data) && !findUnsafe(spec.data) ? spec.data : {};
|
|
4286
|
+
const checked = validateSurfaceComponents(components, { catalogue, data, deferBoundCards: true });
|
|
4287
|
+
const rejected = new Set(checked.issues.flatMap((i) => i.componentId ? [i.componentId] : []));
|
|
4288
|
+
const root = typeof spec.root === "string" ? spec.root : "";
|
|
4289
|
+
const graph = validateSurfaceGraph(root, checked.components, catalogue, rejected);
|
|
4290
|
+
const previous = (spec.issues ?? []).filter((i) => i?.componentId && !checked.components.some((c) => c.id === i.componentId));
|
|
4291
|
+
const issues = [...checked.issues, ...graph, ...previous];
|
|
4292
|
+
const { issues: _old, ...rest } = spec;
|
|
4293
|
+
return { ...rest, root, components: checked.components, data, ...issues.length ? { issues } : {} };
|
|
4294
|
+
}
|
|
4295
|
+
|
|
4296
|
+
// src/surfaces/ledger.ts
|
|
4297
|
+
var CARD_ID_PREFIX = "surface:";
|
|
4298
|
+
var SURFACE_ARTIFACT_KIND = `card:${SURFACE_CARD_KIND}`;
|
|
4299
|
+
var surfaceCardId = (surfaceId) => `${CARD_ID_PREFIX}${surfaceId}`;
|
|
4300
|
+
function isSurfaceSpec(value) {
|
|
4301
|
+
return typeof value === "object" && value !== null && value.kind === SURFACE_CARD_KIND && typeof value.surfaceId === "string";
|
|
4302
|
+
}
|
|
4303
|
+
function expiredStub(surfaceId) {
|
|
4304
|
+
return { kind: SURFACE_CARD_KIND, version: SURFACE_FORMAT_VERSION, surfaceId, root: "", components: [], data: {}, revision: 0, expired: true };
|
|
4305
|
+
}
|
|
4306
|
+
function foldSurfaces(messages) {
|
|
4307
|
+
const out = {};
|
|
4308
|
+
for (const message2 of messages) {
|
|
4309
|
+
for (const part of message2.parts) {
|
|
4310
|
+
if (part.type !== "artifact" || part.kind !== SURFACE_ARTIFACT_KIND) continue;
|
|
4311
|
+
const data = part.data;
|
|
4312
|
+
if (data?.expired === true && part.id.startsWith(CARD_ID_PREFIX)) {
|
|
4313
|
+
const surfaceId = part.id.slice(CARD_ID_PREFIX.length);
|
|
4314
|
+
out[surfaceId] = expiredStub(surfaceId);
|
|
4315
|
+
} else if (isSurfaceSpec(part.data)) {
|
|
4316
|
+
out[part.data.surfaceId] = part.data;
|
|
4317
|
+
}
|
|
4318
|
+
}
|
|
4319
|
+
}
|
|
4320
|
+
return out;
|
|
4321
|
+
}
|
|
4322
|
+
var SurfaceLedger = class {
|
|
4323
|
+
surfaces = /* @__PURE__ */ new Map();
|
|
4324
|
+
constructor(initial = {}) {
|
|
4325
|
+
for (const [id, spec] of Object.entries(initial)) this.surfaces.set(id, spec);
|
|
4326
|
+
}
|
|
4327
|
+
get(surfaceId) {
|
|
4328
|
+
return this.surfaces.get(surfaceId);
|
|
4329
|
+
}
|
|
4330
|
+
put(spec) {
|
|
4331
|
+
this.surfaces.set(spec.surfaceId, spec);
|
|
4332
|
+
}
|
|
4333
|
+
list() {
|
|
4334
|
+
return [...this.surfaces.values()];
|
|
4335
|
+
}
|
|
4336
|
+
/** Surfaces still on screen. */
|
|
4337
|
+
live() {
|
|
4338
|
+
return this.list().filter((s) => !s.deleted && !s.expired);
|
|
4339
|
+
}
|
|
4340
|
+
};
|
|
4341
|
+
|
|
4342
|
+
// src/surfaces/tools.ts
|
|
4343
|
+
var SURFACE_TOOL_NAMES = ["createSurface", "updateSurface", "deleteSurface", "readSurface", "describeSurfaceComponents"];
|
|
4344
|
+
var SURFACE_GUIDE = [
|
|
4345
|
+
"A surface is an interface you assemble from a flat list of components that reference each other by id.",
|
|
4346
|
+
"",
|
|
4347
|
+
'Shape: { "surfaceId": "overview", "title": "Overview", "data": { "region": "all", "rows": [] }, "root": "main", "components": [',
|
|
4348
|
+
' { "id": "main", "component": "Stack", "children": ["region", "total"] },',
|
|
4349
|
+
' { "id": "region", "component": "Select", "label": "Region", "value": { "$path": "/region" }, "options": [{ "value": "all", "label": "All" }] },',
|
|
4350
|
+
' { "id": "total", "component": "Metric", "label": "Total", "format": "number", "value": { "$query": { "from": "/rows", "where": [{ "field": "region", "value": { "$path": "/region" }, "ignore": "all" }], "aggregate": { "op": "sum", "field": "amount" } } } }',
|
|
4351
|
+
"] }",
|
|
4352
|
+
"",
|
|
4353
|
+
"Send `data` first, then `root`, then components parents before children, so the interface can draw as it streams.",
|
|
4354
|
+
"",
|
|
4355
|
+
"Bindings work in any prop: $path reads the data model, $template interpolates ({/path}, {.rowField}), $query filters, groups and aggregates rows, and $item reads the current row inside a List.",
|
|
4356
|
+
"Controls write to their `value` $path, so neighbours update with no call to you. Use `visibleWhen` to show parts conditionally.",
|
|
4357
|
+
'Cards are blocks: { "id": "trend", "component": "Card", "kind": "chart", "spec": { ... } }. Interactive card kinds also need `bind`.',
|
|
4358
|
+
"",
|
|
4359
|
+
"Button actions are exactly: set (local state), tool (a tool you may already call; it follows the same approval rules) and event (returns to you as a new message).",
|
|
4360
|
+
"Never send code, HTML, CSS or script URLs. Change an existing surface with updateSurface rather than creating another. Call readSurface before acting on what the person has chosen."
|
|
4361
|
+
].join("\n");
|
|
4362
|
+
var toCorrections = (issues) => issues.slice(0, 12);
|
|
4363
|
+
function outcome(spec, issues) {
|
|
4364
|
+
const card = { card: spec, cardId: surfaceCardId(spec.surfaceId) };
|
|
4365
|
+
const facts = { surfaceId: spec.surfaceId, revision: spec.revision, components: spec.components.length };
|
|
4366
|
+
if (!issues.length) return { output: { ok: true, ...facts }, ...card };
|
|
4367
|
+
return {
|
|
4368
|
+
output: { ok: false, partial: true, ...facts, corrections: toCorrections(issues), next: "The valid parts are on screen. Send the corrected parts with updateSurface." },
|
|
4369
|
+
failure: "invalid-input",
|
|
4370
|
+
...card
|
|
4371
|
+
};
|
|
4372
|
+
}
|
|
4373
|
+
var refused = (issues) => ({
|
|
4374
|
+
output: { ok: false, rendered: false, corrections: toCorrections(issues) },
|
|
4375
|
+
failure: "invalid-input"
|
|
4376
|
+
});
|
|
4377
|
+
var unavailable = (surfaceId, ledger) => {
|
|
4378
|
+
const spec = typeof surfaceId === "string" ? ledger.get(surfaceId) : void 0;
|
|
4379
|
+
return {
|
|
4380
|
+
output: {
|
|
4381
|
+
ok: false,
|
|
4382
|
+
error: spec?.expired ? `Surface "${String(surfaceId)}" expired from saved history. Call createSurface to rebuild it.` : `No surface "${String(surfaceId)}".`,
|
|
4383
|
+
available: ledger.live().map((s) => s.surfaceId)
|
|
4384
|
+
},
|
|
4385
|
+
failure: "not-found"
|
|
4386
|
+
};
|
|
4387
|
+
};
|
|
4388
|
+
function createSurfaceTools(options) {
|
|
4389
|
+
const { catalogue } = options;
|
|
4390
|
+
const standalone = new SurfaceLedger();
|
|
4391
|
+
const ledgerOf = (ctx) => ctx.surfaces ?? standalone;
|
|
4392
|
+
const createSurface = {
|
|
4393
|
+
name: "createSurface",
|
|
4394
|
+
side: "read",
|
|
4395
|
+
description: "Assemble an interactive interface from a flat component list: layout, text, metrics, inputs, buttons and any card. Use it when the person will explore, filter, compare or act, rather than just read. Call describeSurfaceComponents first for the format and each component's props.",
|
|
4396
|
+
inputSchema: {
|
|
4397
|
+
type: "object",
|
|
4398
|
+
required: ["surfaceId", "root", "components"],
|
|
4399
|
+
properties: {
|
|
4400
|
+
surfaceId: { type: "string", description: "Stable id for later updates." },
|
|
4401
|
+
title: { type: "string" },
|
|
4402
|
+
data: { type: "object", description: "Initial state that components bind to.", additionalProperties: true },
|
|
4403
|
+
root: { type: "string", description: "Id of the top component." },
|
|
4404
|
+
components: {
|
|
4405
|
+
type: "array",
|
|
4406
|
+
items: { type: "object", required: ["id", "component"], additionalProperties: true }
|
|
4407
|
+
}
|
|
4408
|
+
},
|
|
4409
|
+
additionalProperties: false
|
|
4410
|
+
},
|
|
4411
|
+
loading: { kind: "generic", label: "Building the interface" },
|
|
4412
|
+
partialCard: (input) => previewSurface(input, catalogue),
|
|
4413
|
+
execute(input, ctx) {
|
|
4414
|
+
const ledger = ledgerOf(ctx);
|
|
4415
|
+
const surfaceId = input?.surfaceId;
|
|
4416
|
+
const prior = typeof surfaceId === "string" ? ledger.get(surfaceId) : void 0;
|
|
4417
|
+
const replacing = prior && !prior.deleted && !prior.expired ? prior : void 0;
|
|
4418
|
+
if (!replacing && ledger.live().length >= SURFACE_LIMITS.surfaces) {
|
|
4419
|
+
return refused([{ code: "limit-exceeded", message: `A thread may hold ${SURFACE_LIMITS.surfaces} surfaces.`, fix: "Update or delete an existing surface." }]);
|
|
4420
|
+
}
|
|
4421
|
+
const built = buildSurface(input, { catalogue, actionTools: ctx.surfaceActionTools }, {
|
|
4422
|
+
revision: (prior?.revision ?? 0) + 1,
|
|
4423
|
+
originCallId: replacing?.originCallId ?? ctx.callId
|
|
4424
|
+
});
|
|
4425
|
+
if (!built.spec) return refused(built.issues);
|
|
4426
|
+
ledger.put(built.spec);
|
|
4427
|
+
return outcome(built.spec, built.issues);
|
|
4428
|
+
}
|
|
4429
|
+
};
|
|
4430
|
+
const updateSurface = {
|
|
4431
|
+
name: "updateSurface",
|
|
4432
|
+
side: "read",
|
|
4433
|
+
description: "Patch a surface in place. Operations: upsertComponents { components }, removeComponents { ids }, setRoot { root }, setTitle { title }, setData { path, value }, removeData { path }.",
|
|
4434
|
+
inputSchema: {
|
|
4435
|
+
type: "object",
|
|
4436
|
+
required: ["surfaceId", "operations"],
|
|
4437
|
+
properties: {
|
|
4438
|
+
surfaceId: { type: "string" },
|
|
4439
|
+
operations: { type: "array", items: { type: "object", required: ["op"], additionalProperties: true } },
|
|
4440
|
+
expectedRevision: { type: "number", description: "Refuse the patch if the surface has changed since this revision." }
|
|
4441
|
+
},
|
|
4442
|
+
additionalProperties: false
|
|
4443
|
+
},
|
|
4444
|
+
execute(input, ctx) {
|
|
4445
|
+
const ledger = ledgerOf(ctx);
|
|
4446
|
+
const { surfaceId, operations, expectedRevision } = input ?? {};
|
|
4447
|
+
const current = surfaceId ? ledger.get(surfaceId) : void 0;
|
|
4448
|
+
if (!current || current.deleted || current.expired) return unavailable(surfaceId, ledger);
|
|
4449
|
+
if (expectedRevision != null && expectedRevision !== current.revision) {
|
|
4450
|
+
return refused([{
|
|
4451
|
+
code: "stale-revision",
|
|
4452
|
+
message: `The surface is at revision ${current.revision}, not ${expectedRevision}. The person may have changed it.`,
|
|
4453
|
+
fix: "Call readSurface, then patch against the current revision."
|
|
4454
|
+
}]);
|
|
4455
|
+
}
|
|
4456
|
+
const built = applySurfaceOperations(current, operations, { catalogue, actionTools: ctx.surfaceActionTools });
|
|
4457
|
+
if (!built.spec) return refused(built.issues);
|
|
4458
|
+
ledger.put(built.spec);
|
|
4459
|
+
return outcome(built.spec, built.issues);
|
|
4460
|
+
}
|
|
4461
|
+
};
|
|
4462
|
+
const deleteSurface = {
|
|
4463
|
+
name: "deleteSurface",
|
|
4464
|
+
side: "read",
|
|
4465
|
+
description: "Remove a surface from the conversation.",
|
|
4466
|
+
inputSchema: {
|
|
4467
|
+
type: "object",
|
|
4468
|
+
required: ["surfaceId"],
|
|
4469
|
+
properties: { surfaceId: { type: "string" } },
|
|
4470
|
+
additionalProperties: false
|
|
4471
|
+
},
|
|
4472
|
+
execute(input, ctx) {
|
|
4473
|
+
const ledger = ledgerOf(ctx);
|
|
4474
|
+
const { surfaceId } = input ?? {};
|
|
4475
|
+
const current = surfaceId ? ledger.get(surfaceId) : void 0;
|
|
4476
|
+
if (!current || current.deleted) return unavailable(surfaceId, ledger);
|
|
4477
|
+
const tombstone = {
|
|
4478
|
+
kind: SURFACE_CARD_KIND,
|
|
4479
|
+
version: SURFACE_FORMAT_VERSION,
|
|
4480
|
+
surfaceId: current.surfaceId,
|
|
4481
|
+
...current.title ? { title: current.title } : {},
|
|
4482
|
+
root: "",
|
|
4483
|
+
components: [],
|
|
4484
|
+
data: {},
|
|
4485
|
+
revision: current.revision + 1,
|
|
4486
|
+
...current.originCallId ? { originCallId: current.originCallId } : {},
|
|
4487
|
+
deleted: true
|
|
4488
|
+
};
|
|
4489
|
+
ledger.put(tombstone);
|
|
4490
|
+
return { output: { ok: true, surfaceId: current.surfaceId, deleted: true }, card: tombstone, cardId: surfaceCardId(current.surfaceId) };
|
|
4491
|
+
}
|
|
4492
|
+
};
|
|
4493
|
+
const readSurface = {
|
|
4494
|
+
name: "readSurface",
|
|
4495
|
+
side: "read",
|
|
4496
|
+
description: "Read a surface's current state, including what the person has changed. Omit surfaceId to list surfaces.",
|
|
4497
|
+
inputSchema: {
|
|
4498
|
+
type: "object",
|
|
4499
|
+
properties: {
|
|
4500
|
+
surfaceId: { type: "string" },
|
|
4501
|
+
paths: { type: "array", items: { type: "string" }, description: "JSON Pointers to read instead of the whole data model." }
|
|
4502
|
+
},
|
|
4503
|
+
additionalProperties: false
|
|
4504
|
+
},
|
|
4505
|
+
execute(input, ctx) {
|
|
4506
|
+
const ledger = ledgerOf(ctx);
|
|
4507
|
+
const { surfaceId, paths } = input ?? {};
|
|
4508
|
+
if (!surfaceId) {
|
|
4509
|
+
return { output: { ok: true, surfaces: ledger.live().map((s) => ({ surfaceId: s.surfaceId, title: s.title, revision: s.revision })) } };
|
|
4510
|
+
}
|
|
4511
|
+
const spec = ledger.get(surfaceId);
|
|
4512
|
+
if (!spec || spec.deleted || spec.expired) return unavailable(surfaceId, ledger);
|
|
4513
|
+
return {
|
|
4514
|
+
output: {
|
|
4515
|
+
ok: true,
|
|
4516
|
+
surfaceId,
|
|
4517
|
+
...spec.title ? { title: spec.title } : {},
|
|
4518
|
+
revision: spec.revision,
|
|
4519
|
+
root: spec.root,
|
|
4520
|
+
components: spec.components.map((c) => ({ id: c.id, component: c.component })),
|
|
4521
|
+
...Array.isArray(paths) ? { values: Object.fromEntries(paths.map((p) => [p, getAt(spec.data, p)])) } : { data: spec.data },
|
|
4522
|
+
...spec.issues?.length ? { issues: toCorrections(spec.issues) } : {}
|
|
4523
|
+
}
|
|
4524
|
+
};
|
|
4525
|
+
}
|
|
4526
|
+
};
|
|
4527
|
+
const describeSurfaceComponents = {
|
|
4528
|
+
name: "describeSurfaceComponents",
|
|
4529
|
+
side: "read",
|
|
4530
|
+
description: 'Look up the surface format. No arguments returns the guide and component index; `components` returns those schemas, such as ["Select", "Card:chart"].',
|
|
4531
|
+
inputSchema: {
|
|
4532
|
+
type: "object",
|
|
4533
|
+
properties: {
|
|
4534
|
+
components: { type: "array", items: { type: "string" } },
|
|
4535
|
+
maxTokens: { type: "number", description: "Budget for the returned schemas. Default 1500." }
|
|
4536
|
+
},
|
|
4537
|
+
additionalProperties: false
|
|
4538
|
+
},
|
|
4539
|
+
execute(input) {
|
|
4540
|
+
const { components, maxTokens } = input ?? {};
|
|
4541
|
+
if (!Array.isArray(components) || !components.length) {
|
|
4542
|
+
return { output: { ok: true, guide: SURFACE_GUIDE, index: catalogue.index() } };
|
|
4543
|
+
}
|
|
4544
|
+
const known = components.flatMap((name) => {
|
|
4545
|
+
const schema = catalogue.schemaOf(name);
|
|
4546
|
+
return schema ? [schema] : [];
|
|
4547
|
+
});
|
|
4548
|
+
const unknown = components.filter((name) => !catalogue.schemaOf(name));
|
|
4549
|
+
const budget = Math.max(200, Math.min(maxTokens ?? 1500, 6e3));
|
|
4550
|
+
const packed = packByPriority(known, budget, estimateJsonTokens);
|
|
4551
|
+
return {
|
|
4552
|
+
output: {
|
|
4553
|
+
ok: true,
|
|
4554
|
+
schemas: packed.included,
|
|
4555
|
+
...packed.dropped.length ? { omitted: packed.dropped.map((d) => d.item.name), next: "Request the omitted components in another call." } : {},
|
|
4556
|
+
...unknown.length ? { unknown, available: catalogue.names() } : {}
|
|
4557
|
+
}
|
|
4558
|
+
};
|
|
4559
|
+
}
|
|
4560
|
+
};
|
|
4561
|
+
return [createSurface, updateSurface, deleteSurface, readSurface, describeSurfaceComponents];
|
|
4562
|
+
}
|
|
4563
|
+
|
|
4564
|
+
// src/surfaces/disclosure.ts
|
|
4565
|
+
var SURFACE_SKILL_ID = "surface-authoring";
|
|
4566
|
+
function createSurfaceSkill(catalogue) {
|
|
4567
|
+
return {
|
|
4568
|
+
id: SURFACE_SKILL_ID,
|
|
4569
|
+
name: "Building interfaces",
|
|
4570
|
+
description: "How to assemble an interactive surface from components, bindings and actions.",
|
|
4571
|
+
mode: "manual",
|
|
4572
|
+
aliases: ["surface", "interface", "dashboard", "filter", "form"],
|
|
4573
|
+
tools: ["createSurface", "updateSurface", "deleteSurface", "readSurface", "describeSurfaceComponents"],
|
|
4574
|
+
body: () => [SURFACE_GUIDE, "", "Components:", catalogue.index()].join("\n")
|
|
4575
|
+
};
|
|
4576
|
+
}
|
|
4577
|
+
function createSurfaceContextSource() {
|
|
4578
|
+
return {
|
|
4579
|
+
id: "surfaces",
|
|
4580
|
+
run({ messages }) {
|
|
4581
|
+
const live = Object.values(foldSurfaces(messages)).filter((s) => !s.deleted && !s.expired);
|
|
4582
|
+
if (!live.length) return {};
|
|
4583
|
+
const text3 = [
|
|
4584
|
+
"Surfaces on screen. Call readSurface for their current state before relying on it:",
|
|
4585
|
+
...live.map((s) => `- ${s.surfaceId}${s.title ? ` (${s.title})` : ""}, revision ${s.revision}`)
|
|
4586
|
+
].join("\n");
|
|
4587
|
+
return { layers: [{ id: "surfaces", kind: "custom", text: text3, tokens: estimateTokens(text3), priority: 400 }] };
|
|
4588
|
+
}
|
|
4589
|
+
};
|
|
4590
|
+
}
|
|
4591
|
+
|
|
4592
|
+
// src/runtime/channel.ts
|
|
4593
|
+
var EventChannel = class {
|
|
4594
|
+
queue = [];
|
|
4595
|
+
waiting = [];
|
|
4596
|
+
closed = false;
|
|
4597
|
+
/** Enqueue an event, handing it straight to a waiting consumer if there is one. */
|
|
4598
|
+
push(value) {
|
|
4599
|
+
if (this.closed) return;
|
|
4600
|
+
const resolve = this.waiting.shift();
|
|
4601
|
+
if (resolve) resolve({ value, done: false });
|
|
4602
|
+
else this.queue.push(value);
|
|
4603
|
+
}
|
|
4604
|
+
/** No more events. Consumers drain what is buffered, then finish. */
|
|
4605
|
+
close() {
|
|
4606
|
+
if (this.closed) return;
|
|
4607
|
+
this.closed = true;
|
|
4608
|
+
for (const resolve of this.waiting) resolve({ value: void 0, done: true });
|
|
4609
|
+
this.waiting = [];
|
|
4610
|
+
}
|
|
4611
|
+
[Symbol.asyncIterator]() {
|
|
4612
|
+
return {
|
|
4613
|
+
next: () => {
|
|
4614
|
+
if (this.queue.length) return Promise.resolve({ value: this.queue.shift(), done: false });
|
|
4615
|
+
if (this.closed) return Promise.resolve({ value: void 0, done: true });
|
|
4616
|
+
return new Promise((resolve) => this.waiting.push(resolve));
|
|
4617
|
+
}
|
|
4618
|
+
};
|
|
4619
|
+
}
|
|
4620
|
+
};
|
|
4621
|
+
|
|
4622
|
+
// src/runtime/execute-tools.ts
|
|
4623
|
+
var MAX_ERROR_CHARS = 400;
|
|
4624
|
+
function compactError(e) {
|
|
4625
|
+
if (e instanceof AgentError) {
|
|
4626
|
+
return { error: e.message.slice(0, MAX_ERROR_CHARS), kind: e.kind };
|
|
4627
|
+
}
|
|
4628
|
+
const message2 = e instanceof Error ? e.message : String(e);
|
|
4629
|
+
return { error: message2.slice(0, MAX_ERROR_CHARS) || "Tool failed with no message." };
|
|
4630
|
+
}
|
|
4631
|
+
var PREVIEW_CHARS = 200;
|
|
4632
|
+
var PREVIEW_FIELDS = 8;
|
|
4633
|
+
var preview = (value) => {
|
|
4634
|
+
const text3 = typeof value === "string" ? value : JSON.stringify(value) ?? String(value);
|
|
4635
|
+
return text3.length > PREVIEW_CHARS ? `${text3.slice(0, PREVIEW_CHARS)}\u2026` : text3;
|
|
4636
|
+
};
|
|
4637
|
+
function approvalCard(tool, input) {
|
|
4638
|
+
const fields = typeof input === "object" && input !== null && !Array.isArray(input) ? Object.entries(input).slice(0, PREVIEW_FIELDS).map(([label, value]) => ({ label, value: preview(value), mono: true })) : input === void 0 || input === null ? [] : [{ label: "Input", value: preview(input), mono: true }];
|
|
4639
|
+
return {
|
|
4640
|
+
kind: "confirm",
|
|
4641
|
+
title: `Allow ${tool.name}?`,
|
|
4642
|
+
description: preview(tool.description),
|
|
4643
|
+
summary: fields.length ? fields : [{ label: "Tool", value: tool.name, mono: true }],
|
|
4644
|
+
confirmLabel: "Allow",
|
|
4645
|
+
cancelLabel: "Decline"
|
|
4646
|
+
};
|
|
4647
|
+
}
|
|
4648
|
+
async function confirmationRefusal(tool, call, opts) {
|
|
4649
|
+
if (!opts.requestCard) return `"${tool.name}" needs the user's approval and this host cannot ask for it.`;
|
|
4650
|
+
if (tool.confirmation === "tool") return void 0;
|
|
4651
|
+
const answer = await opts.requestCard(call.callId, approvalCard(tool, call.input));
|
|
4652
|
+
if (opts.signal?.aborted) return "The run was stopped before this was approved.";
|
|
4653
|
+
return answer?.confirmed === true ? void 0 : "The user declined.";
|
|
4654
|
+
}
|
|
4655
|
+
var isToolResult = (v) => typeof v === "object" && v !== null && "output" in v && Object.keys(v).every((k) => ["output", "card", "failure", "cardId", "unlockTools"].includes(k));
|
|
4656
|
+
async function executeToolCall(call, opts) {
|
|
4657
|
+
const started = Date.now();
|
|
4658
|
+
const tool = opts.toolIndex ? opts.toolIndex.get(call.name) : opts.tools.find((t) => t.name === call.name);
|
|
4659
|
+
if (!tool) {
|
|
4660
|
+
return {
|
|
4661
|
+
callId: call.callId,
|
|
4662
|
+
name: call.name,
|
|
4663
|
+
output: {
|
|
4664
|
+
error: `Unknown tool "${call.name}".`,
|
|
4665
|
+
availableTools: opts.tools.map((t) => t.name)
|
|
4666
|
+
},
|
|
4667
|
+
failure: "not-found",
|
|
4668
|
+
ms: Date.now() - started
|
|
4669
|
+
};
|
|
4670
|
+
}
|
|
4671
|
+
let emittedCard;
|
|
4672
|
+
let settled = false;
|
|
4673
|
+
const ctx = {
|
|
4674
|
+
vars: opts.vars,
|
|
4675
|
+
signal: opts.signal,
|
|
4676
|
+
callId: call.callId,
|
|
4677
|
+
...opts.surfaces ? { surfaces: opts.surfaces } : {},
|
|
4678
|
+
...opts.surfaceActionTools ? { surfaceActionTools: opts.surfaceActionTools } : {},
|
|
4679
|
+
emitCard: (spec) => {
|
|
4680
|
+
if (settled) return;
|
|
4681
|
+
const card = makeCard(spec, call.callId);
|
|
4682
|
+
emittedCard = card;
|
|
4683
|
+
opts.onCard?.(card);
|
|
4684
|
+
},
|
|
4685
|
+
...opts.requestCard ? {
|
|
4686
|
+
requestCard: (spec) => settled ? Promise.reject(new AgentError("cancelled", `Tool "${call.name}" already finished.`)) : opts.requestCard(call.callId, spec)
|
|
4687
|
+
} : {}
|
|
4688
|
+
};
|
|
4689
|
+
try {
|
|
4690
|
+
if (tool.side === "confirm") {
|
|
4691
|
+
const refusal = await confirmationRefusal(tool, call, opts);
|
|
4692
|
+
if (refusal) return { callId: call.callId, name: call.name, output: { error: refusal }, failure: "denied", ms: Date.now() - started };
|
|
4693
|
+
}
|
|
4694
|
+
const raw = tool.execute ? await withTimeout(Promise.resolve(tool.execute(call.input, ctx)), opts.timeoutMs, call.name) : opts.onHostTool ? await withTimeout(opts.onHostTool(call), opts.timeoutMs, call.name) : (() => {
|
|
4695
|
+
throw new AgentError("not-supported", `Tool "${call.name}" has no executor and no host handler.`);
|
|
4696
|
+
})();
|
|
4697
|
+
const result = isToolResult(raw) ? raw : { output: raw };
|
|
4698
|
+
let card = emittedCard;
|
|
4699
|
+
let output = result.output;
|
|
4700
|
+
if (result.card) {
|
|
4701
|
+
card = makeCard(result.card, call.callId, result.cardId);
|
|
4702
|
+
output = withCard(asRecord(result.output), card.spec, card.id);
|
|
4703
|
+
opts.onCard?.(card);
|
|
4704
|
+
} else if (isCardCarrier(result.output)) {
|
|
4705
|
+
const embedded = result.output[CARD_KEY];
|
|
4706
|
+
card = { ...embedded, callId: call.callId };
|
|
4707
|
+
opts.onCard?.(card);
|
|
4708
|
+
}
|
|
4709
|
+
return {
|
|
4710
|
+
callId: call.callId,
|
|
4711
|
+
name: call.name,
|
|
4712
|
+
output,
|
|
4713
|
+
...card ? { card } : {},
|
|
4714
|
+
...result.failure ? { failure: result.failure } : {},
|
|
4715
|
+
...result.unlockTools?.length ? { unlockTools: result.unlockTools } : {},
|
|
4716
|
+
ms: Date.now() - started
|
|
4717
|
+
};
|
|
4718
|
+
} catch (e) {
|
|
4719
|
+
const err = toAgentError(e);
|
|
4720
|
+
return {
|
|
4721
|
+
callId: call.callId,
|
|
4722
|
+
name: call.name,
|
|
4723
|
+
output: compactError(err),
|
|
4724
|
+
failure: err.kind === "cancelled" ? "denied" : "execution-error",
|
|
4725
|
+
ms: Date.now() - started
|
|
4726
|
+
};
|
|
4727
|
+
} finally {
|
|
4728
|
+
settled = true;
|
|
4729
|
+
}
|
|
4730
|
+
}
|
|
4731
|
+
async function executeToolCalls(calls, opts) {
|
|
4732
|
+
const toolIndex = opts.toolIndex ?? new Map(opts.tools.map((t) => [t.name, t]));
|
|
4733
|
+
const callOpts = opts.toolIndex ? opts : { ...opts, toolIndex };
|
|
4734
|
+
const interactive = calls.filter((c) => toolIndex.get(c.name)?.side === "confirm");
|
|
4735
|
+
const concurrent = calls.filter((c) => !interactive.includes(c));
|
|
4736
|
+
const settle = async (c) => {
|
|
4737
|
+
const outcome2 = await executeToolCall(c, callOpts);
|
|
4738
|
+
opts.onOutcome?.(outcome2);
|
|
4739
|
+
return outcome2;
|
|
4740
|
+
};
|
|
4741
|
+
const concurrentResults = await Promise.all(concurrent.map(settle));
|
|
4742
|
+
const serialResults = [];
|
|
4743
|
+
for (const c of interactive) serialResults.push(await settle(c));
|
|
4744
|
+
const byId = new Map([...concurrentResults, ...serialResults].map((r) => [r.callId, r]));
|
|
4745
|
+
return calls.map((c) => byId.get(c.callId)).filter(Boolean);
|
|
4746
|
+
}
|
|
4747
|
+
function asRecord(value) {
|
|
4748
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) return value;
|
|
4749
|
+
return { result: value };
|
|
4750
|
+
}
|
|
4751
|
+
function withTimeout(promise, ms, name) {
|
|
4752
|
+
if (!ms) return promise;
|
|
4753
|
+
return Promise.race([
|
|
4754
|
+
promise,
|
|
4755
|
+
new Promise(
|
|
4756
|
+
(_, reject) => setTimeout(() => reject(new AgentError("timeout", `Tool "${name}" timed out after ${ms}ms.`)), ms)
|
|
4757
|
+
)
|
|
4758
|
+
]);
|
|
4759
|
+
}
|
|
4760
|
+
|
|
4761
|
+
// src/runtime/metering.ts
|
|
4762
|
+
function usageSource(usage) {
|
|
4763
|
+
return Object.values(usage).some((value) => typeof value === "number") ? "provider" : "unavailable";
|
|
4764
|
+
}
|
|
4765
|
+
function combineMeteringSources(sources) {
|
|
4766
|
+
if (!sources.length) return "unavailable";
|
|
4767
|
+
const unique = new Set(sources);
|
|
4768
|
+
return unique.size === 1 ? sources[0] : "mixed";
|
|
4769
|
+
}
|
|
4770
|
+
async function deliverMetering(sink, record) {
|
|
4771
|
+
if (!sink) return;
|
|
4772
|
+
try {
|
|
4773
|
+
await sink.record(record);
|
|
4774
|
+
} catch (error) {
|
|
4775
|
+
try {
|
|
4776
|
+
await sink.onError?.(error, record);
|
|
4777
|
+
} catch {
|
|
4778
|
+
}
|
|
4779
|
+
}
|
|
4780
|
+
}
|
|
4781
|
+
|
|
4782
|
+
// src/surfaces/action-run.ts
|
|
4783
|
+
var NOT_ACTIONABLE = /* @__PURE__ */ new Set([...SURFACE_TOOL_NAMES, "visualize", "updateCard", "loadSkill"]);
|
|
4784
|
+
function surfaceActionTools(tools, resolution) {
|
|
4785
|
+
return tools.resolve({ presets: resolution.presets, ...resolution.deny ? { deny: resolution.deny } : {} }).filter((t) => !NOT_ACTIONABLE.has(t.name));
|
|
4786
|
+
}
|
|
4787
|
+
function authorizeSurfaceTool(name, args, tools, resolution) {
|
|
4788
|
+
const tool = surfaceActionTools(tools, resolution).find((t) => t.name === name);
|
|
4789
|
+
if (!tool) return { ok: false, reason: `"${name}" is not permitted here.` };
|
|
4790
|
+
const problems = checkSchema(tool.inputSchema, args ?? {});
|
|
4791
|
+
if (problems.length) return { ok: false, reason: `"${name}" received invalid input: ${problems[0].message}` };
|
|
4792
|
+
return { ok: true, tool };
|
|
4793
|
+
}
|
|
4794
|
+
async function* runSurfaceToolAction(config) {
|
|
4795
|
+
const runId = nextId("run");
|
|
4796
|
+
const callId = nextId("call_surface");
|
|
4797
|
+
const startedAt = Date.now();
|
|
4798
|
+
yield { type: "run-start", runId, mode: "sync" };
|
|
4799
|
+
yield { type: "step-start", step: 0 };
|
|
4800
|
+
yield { type: "tool-call", callId, name: config.tool.name, input: config.args };
|
|
4801
|
+
const channel = new EventChannel();
|
|
4802
|
+
const onUserDecision = config.onUserDecision;
|
|
4803
|
+
const running = executeToolCall(
|
|
4804
|
+
{ callId, name: config.tool.name, input: config.args },
|
|
4805
|
+
{
|
|
4806
|
+
tools: [config.tool],
|
|
4807
|
+
vars: config.vars ?? {},
|
|
4808
|
+
signal: config.signal,
|
|
4809
|
+
timeoutMs: config.toolTimeoutMs,
|
|
4810
|
+
onCard: (card) => channel.push({ type: "card", card }),
|
|
4811
|
+
onHostTool: config.onHostTool,
|
|
4812
|
+
requestCard: onUserDecision ? async (id, spec) => {
|
|
4813
|
+
const card = makeCard(spec, id);
|
|
4814
|
+
channel.push({ type: "awaiting-user", callId: id, card });
|
|
4815
|
+
const action = await onUserDecision(id, card);
|
|
4816
|
+
channel.push({ type: "user-responded", callId: id, action });
|
|
4817
|
+
return action.type === "cancel" || action.type === "dismiss" ? { cancelled: true, reason: "The user declined." } : action.value ?? { confirmed: true };
|
|
4818
|
+
} : void 0
|
|
4819
|
+
}
|
|
4820
|
+
).then((outcome3) => {
|
|
4821
|
+
channel.push({
|
|
4822
|
+
type: "tool-result",
|
|
4823
|
+
callId: outcome3.callId,
|
|
4824
|
+
name: outcome3.name,
|
|
4825
|
+
output: outcome3.output,
|
|
4826
|
+
...outcome3.failure ? { failure: outcome3.failure } : {},
|
|
4827
|
+
ms: outcome3.ms
|
|
4828
|
+
});
|
|
4829
|
+
return outcome3;
|
|
4830
|
+
}).finally(() => channel.close());
|
|
4831
|
+
for await (const event of channel) yield event;
|
|
4832
|
+
const outcome2 = await running;
|
|
4833
|
+
const finishedAt = Date.now();
|
|
4834
|
+
const finishReason = outcome2.failure === "denied" && config.signal?.aborted ? "cancelled" : "stop";
|
|
4835
|
+
const record = {
|
|
4836
|
+
scope: "run",
|
|
4837
|
+
id: `${runId}:run`,
|
|
4838
|
+
runId,
|
|
4839
|
+
provider: config.provider,
|
|
4840
|
+
requestedModel: config.model,
|
|
4841
|
+
mode: "sync",
|
|
4842
|
+
status: finishReason === "cancelled" ? "cancelled" : outcome2.failure ? "failed" : "completed",
|
|
4843
|
+
usage: {},
|
|
4844
|
+
source: "unavailable",
|
|
4845
|
+
startedAt,
|
|
4846
|
+
finishedAt,
|
|
4847
|
+
durationMs: finishedAt - startedAt,
|
|
4848
|
+
steps: 0,
|
|
4849
|
+
finishReason,
|
|
4850
|
+
metadata: { ...config.meteringMetadata, trigger: "surface-action", surfaceId: config.surfaceId, componentId: config.componentId, tool: config.tool.name }
|
|
4851
|
+
};
|
|
4852
|
+
await deliverMetering(config.meter, record);
|
|
4853
|
+
yield { type: "metering", record };
|
|
4854
|
+
yield { type: "run-finish", runId, finishReason, usage: {}, steps: 0 };
|
|
4855
|
+
}
|
|
4856
|
+
|
|
4857
|
+
// src/surfaces/a2ui.ts
|
|
4858
|
+
var A2UI_VERSION = "v0.9.1";
|
|
4859
|
+
var SURFACE_A2UI_CATALOG_ID = "urn:supersolutions:super-chat:surface-catalog:v1";
|
|
4860
|
+
var toDynamic = (value) => {
|
|
4861
|
+
if (Array.isArray(value)) return value.map(toDynamic);
|
|
4862
|
+
if (typeof value !== "object" || value === null) return value;
|
|
4863
|
+
if (isSurfaceBinding(value)) {
|
|
4864
|
+
if ("$path" in value) return { path: value.$path };
|
|
4865
|
+
if ("$item" in value) return { path: value.$item };
|
|
4866
|
+
if ("$template" in value) {
|
|
4867
|
+
return { call: "formatString", args: { value: value.$template.replace(/\{(\/[^{}]*)\}/g, "$${$1}").replace(/\{\.([^{}]*)\}/g, "$${$1}") } };
|
|
4868
|
+
}
|
|
4869
|
+
return { call: "superchat.query", args: toDynamic(value.$query) };
|
|
4870
|
+
}
|
|
4871
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, toDynamic(v)]));
|
|
4872
|
+
};
|
|
4873
|
+
var toAction = (action) => {
|
|
4874
|
+
switch (action.type) {
|
|
4875
|
+
case "event":
|
|
4876
|
+
return { event: { name: action.name, ...action.context ? { context: toDynamic(action.context) } : {} } };
|
|
4877
|
+
case "set":
|
|
4878
|
+
return { functionCall: { call: "superchat.set", args: { updates: toDynamic(action.updates) } } };
|
|
4879
|
+
case "tool":
|
|
4880
|
+
return { event: { name: "superchat.tool", context: toDynamic({ tool: action.tool, args: action.args ?? {}, resultPath: action.resultPath }) } };
|
|
4881
|
+
}
|
|
4882
|
+
};
|
|
4883
|
+
var TEXT_VARIANTS = { title: "h2", heading: "h4", body: "body", caption: "caption", label: "caption", code: "body" };
|
|
4884
|
+
function toComponents(component, rename) {
|
|
4885
|
+
const { id, component: name, visibleWhen: _visibleWhen, ...rest } = component;
|
|
4886
|
+
const base = { id: rename(id) };
|
|
4887
|
+
const props2 = toDynamic(rest);
|
|
4888
|
+
const children = Array.isArray(rest["children"]) ? rest["children"].map(rename) : void 0;
|
|
4889
|
+
switch (name) {
|
|
4890
|
+
case "Stack":
|
|
4891
|
+
return [{ ...base, component: rest["direction"] === "horizontal" ? "Row" : "Column", children, ...rest["justify"] ? { justify: rest["justify"] === "between" ? "spaceBetween" : rest["justify"] } : {}, ...rest["align"] ? { align: rest["align"] } : {} }];
|
|
4892
|
+
case "Text":
|
|
4893
|
+
return [{ ...base, component: "Text", text: props2["text"], ...typeof rest["variant"] === "string" ? { variant: TEXT_VARIANTS[rest["variant"]] } : {} }];
|
|
4894
|
+
case "Image":
|
|
4895
|
+
return [{ ...base, component: "Image", url: props2["src"] }];
|
|
4896
|
+
case "Divider":
|
|
4897
|
+
return [{ ...base, component: "Divider" }];
|
|
4898
|
+
case "Tabs":
|
|
4899
|
+
return [{ ...base, component: "Tabs", tabs: rest["tabs"].map((t) => ({ title: t.label, child: rename(t.child) })) }];
|
|
4900
|
+
case "List": {
|
|
4901
|
+
const items = rest["items"];
|
|
4902
|
+
const path = isSurfaceBinding(items) && "$path" in items ? items.$path : void 0;
|
|
4903
|
+
return path ? [{ ...base, component: "List", children: { path, componentId: rename(rest["child"]) } }] : [{ ...base, component: name, ...props2, child: rename(rest["child"]) }];
|
|
4904
|
+
}
|
|
4905
|
+
case "Field":
|
|
4906
|
+
return [{ ...base, component: rest["type"] === "date" ? "DateTimeInput" : "TextField", label: props2["label"], value: props2["value"] }];
|
|
4907
|
+
case "Select":
|
|
4908
|
+
return [{ ...base, component: "ChoicePicker", label: props2["label"], value: props2["value"], options: props2["options"], variant: "mutuallyExclusive" }];
|
|
4909
|
+
case "Toggle":
|
|
4910
|
+
return [{ ...base, component: "CheckBox", label: props2["label"], value: props2["value"] }];
|
|
4911
|
+
case "Slider":
|
|
4912
|
+
return [{ ...base, component: "Slider", label: props2["label"], value: props2["value"], min: props2["min"], max: props2["max"] }];
|
|
4913
|
+
case "Button": {
|
|
4914
|
+
const labelId = rename(`${id}__label`);
|
|
4915
|
+
return [
|
|
4916
|
+
{ ...base, component: "Button", child: labelId, variant: rest["variant"] === "primary" ? "primary" : "borderless", action: toAction(rest["action"]) },
|
|
4917
|
+
{ id: labelId, component: "Text", text: props2["label"] }
|
|
4918
|
+
];
|
|
4919
|
+
}
|
|
4920
|
+
default:
|
|
4921
|
+
return [{ ...base, component: name, ...props2, ...children ? { children } : {} }];
|
|
4922
|
+
}
|
|
4923
|
+
}
|
|
4924
|
+
function toA2uiMessages(spec) {
|
|
4925
|
+
const { surfaceId } = spec;
|
|
4926
|
+
if (spec.deleted) return [{ version: A2UI_VERSION, deleteSurface: { surfaceId } }];
|
|
4927
|
+
const rename = (id) => id === spec.root ? "root" : id === "root" ? `${spec.root}__swapped` : id;
|
|
4928
|
+
return [
|
|
4929
|
+
{ version: A2UI_VERSION, createSurface: { surfaceId, catalogId: SURFACE_A2UI_CATALOG_ID, sendDataModel: true } },
|
|
4930
|
+
{ version: A2UI_VERSION, updateComponents: { surfaceId, components: spec.components.flatMap((c) => toComponents(c, rename)) } },
|
|
4931
|
+
{ version: A2UI_VERSION, updateDataModel: { surfaceId, path: "/", value: spec.data } }
|
|
4932
|
+
];
|
|
4933
|
+
}
|
|
4934
|
+
|
|
4935
|
+
// src/tools/types.ts
|
|
4936
|
+
function resolvePartialCard(tool, partialInput) {
|
|
4937
|
+
if (!tool?.partialCard) return void 0;
|
|
4938
|
+
try {
|
|
4939
|
+
return tool.partialCard(partialInput);
|
|
4940
|
+
} catch {
|
|
4941
|
+
return void 0;
|
|
4942
|
+
}
|
|
4943
|
+
}
|
|
4944
|
+
function resolveToolLoading(loading, input) {
|
|
4945
|
+
try {
|
|
4946
|
+
return typeof loading === "function" ? loading(input) : loading;
|
|
4947
|
+
} catch {
|
|
4948
|
+
return void 0;
|
|
4949
|
+
}
|
|
4950
|
+
}
|
|
4951
|
+
var DEFAULT_PRESETS = ["observer", "draft", "executor"];
|
|
4952
|
+
|
|
4953
|
+
// src/tools/registry.ts
|
|
4954
|
+
var ToolRegistry = class {
|
|
4955
|
+
tools = /* @__PURE__ */ new Map();
|
|
4956
|
+
presets = /* @__PURE__ */ new Map();
|
|
4957
|
+
listeners = /* @__PURE__ */ new Set();
|
|
4958
|
+
version = 0;
|
|
4959
|
+
// Reverse of `presets`: tool name → presets that grant it. Lazily rebuilt —
|
|
4960
|
+
// `touch()` just nulls it out, so a burst of register()/addToPreset() calls
|
|
4961
|
+
// pays for one rebuild on the next presetsFor()/resolve(), not one per call.
|
|
4962
|
+
reversePresetIndex = null;
|
|
4963
|
+
constructor(tools = []) {
|
|
4964
|
+
for (const t of tools) this.register(t);
|
|
4965
|
+
}
|
|
4966
|
+
register(tool, presets = []) {
|
|
4967
|
+
this.tools.set(tool.name, tool);
|
|
4968
|
+
for (const p of presets) this.addToPreset(p, tool.name);
|
|
4969
|
+
this.touch();
|
|
4970
|
+
return this;
|
|
4971
|
+
}
|
|
4972
|
+
/** Register several tools into the same preset — the common bulk case. */
|
|
4973
|
+
registerAll(tools, presets = []) {
|
|
4974
|
+
for (const t of tools) this.register(t, presets);
|
|
4975
|
+
return this;
|
|
4976
|
+
}
|
|
4977
|
+
addToPreset(preset, ...names) {
|
|
4978
|
+
const set = this.presets.get(preset) ?? /* @__PURE__ */ new Set();
|
|
4979
|
+
for (const n of names) set.add(n);
|
|
4980
|
+
this.presets.set(preset, set);
|
|
4981
|
+
this.touch();
|
|
4982
|
+
return this;
|
|
4983
|
+
}
|
|
4984
|
+
/**
|
|
4985
|
+
* Change notification, so a UI (or an inspector hook) re-reads after a LATE
|
|
4986
|
+
* registration — tools imported from an MCP server arrive long after mount,
|
|
4987
|
+
* and a registry nobody can observe leaves them invisible until reload.
|
|
4988
|
+
*/
|
|
4989
|
+
subscribe(listener) {
|
|
4990
|
+
this.listeners.add(listener);
|
|
4991
|
+
return () => {
|
|
4992
|
+
this.listeners.delete(listener);
|
|
4993
|
+
};
|
|
4994
|
+
}
|
|
4995
|
+
/** Monotonic change counter — a stable snapshot value for useSyncExternalStore. */
|
|
4996
|
+
getVersion() {
|
|
4997
|
+
return this.version;
|
|
4998
|
+
}
|
|
4999
|
+
touch() {
|
|
5000
|
+
this.version += 1;
|
|
5001
|
+
this.reversePresetIndex = null;
|
|
5002
|
+
for (const l of this.listeners) l();
|
|
5003
|
+
}
|
|
5004
|
+
get(name) {
|
|
5005
|
+
return this.tools.get(name) ?? this.tools.get(normalizeToolName(name));
|
|
5006
|
+
}
|
|
5007
|
+
has(name) {
|
|
5008
|
+
return this.get(name) !== void 0;
|
|
5009
|
+
}
|
|
5010
|
+
list() {
|
|
5011
|
+
return [...this.tools.values()];
|
|
5012
|
+
}
|
|
5013
|
+
presetNames() {
|
|
5014
|
+
return [...this.presets.keys()];
|
|
5015
|
+
}
|
|
5016
|
+
/** Tool names in a preset that are actually registered. */
|
|
5017
|
+
namesInPreset(preset) {
|
|
5018
|
+
return [...this.presets.get(preset) ?? []].filter((n) => this.tools.has(n)).sort();
|
|
5019
|
+
}
|
|
5020
|
+
/** Which presets grant `name`. Used by the UI to explain why a tool is available. */
|
|
5021
|
+
presetsFor(name) {
|
|
5022
|
+
return this.reverseIndex().get(name) ?? [];
|
|
5023
|
+
}
|
|
5024
|
+
/** Tool name → presets that grant it, rebuilt on demand after the last mutation. */
|
|
5025
|
+
reverseIndex() {
|
|
5026
|
+
if (this.reversePresetIndex) return this.reversePresetIndex;
|
|
5027
|
+
const index = /* @__PURE__ */ new Map();
|
|
5028
|
+
for (const [preset, names] of this.presets) {
|
|
5029
|
+
for (const name of names) {
|
|
5030
|
+
const grants = index.get(name);
|
|
5031
|
+
if (grants) grants.push(preset);
|
|
5032
|
+
else index.set(name, [preset]);
|
|
5033
|
+
}
|
|
5034
|
+
}
|
|
5035
|
+
this.reversePresetIndex = index;
|
|
5036
|
+
return index;
|
|
5037
|
+
}
|
|
5038
|
+
/**
|
|
5039
|
+
* Resolve the tool set for a run.
|
|
5040
|
+
*
|
|
5041
|
+
* Two distinct grants, and keeping them separate is a security property:
|
|
5042
|
+
*
|
|
5043
|
+
* PRESETS grant AUTHORITY. Whether the caller may act at all.
|
|
5044
|
+
* `allow` grants RELEVANCE. Usually a matched skill saying "these are the
|
|
5045
|
+
* tools my instructions describe".
|
|
5046
|
+
*
|
|
5047
|
+
* A skill must therefore never be able to escalate past the capability tier.
|
|
5048
|
+
* So `allow` can surface a tool that belongs to NO preset (private by
|
|
5049
|
+
* default, unlocked by the skill that documents it), but a tool that IS in a
|
|
5050
|
+
* preset still requires that preset to be enabled. Otherwise any skill could
|
|
5051
|
+
* hand out the executor tier just by naming a tool.
|
|
5052
|
+
*
|
|
5053
|
+
* A name listed in a preset but never registered is skipped rather than
|
|
5054
|
+
* throwing — presets are configuration and often outlive the tools they name.
|
|
5055
|
+
*/
|
|
5056
|
+
resolve(resolution) {
|
|
5057
|
+
const allowed = /* @__PURE__ */ new Set();
|
|
5058
|
+
for (const preset of resolution.presets) {
|
|
5059
|
+
for (const name of this.presets.get(preset) ?? []) allowed.add(name);
|
|
5060
|
+
}
|
|
5061
|
+
for (const name of resolution.allow ?? []) {
|
|
5062
|
+
const grants = this.presetsFor(name);
|
|
5063
|
+
const skillGated = grants.length === 0;
|
|
5064
|
+
const withinTier = grants.some((g) => resolution.presets.includes(g));
|
|
5065
|
+
if (skillGated || withinTier) allowed.add(name);
|
|
5066
|
+
}
|
|
5067
|
+
for (const name of resolution.deny ?? []) allowed.delete(name);
|
|
5068
|
+
return [...allowed].map((n) => this.tools.get(n)).filter((t) => t !== void 0).sort((a, b) => a.name.localeCompare(b.name));
|
|
5069
|
+
}
|
|
5070
|
+
/** Provider-facing specs. The adapter turns these into its own wire shape. */
|
|
5071
|
+
toSpecs(tools) {
|
|
5072
|
+
return tools.map((t) => ({
|
|
5073
|
+
name: t.name,
|
|
5074
|
+
description: t.description,
|
|
5075
|
+
parameters: t.inputSchema,
|
|
3233
5076
|
...t.strict ? { strict: true } : {}
|
|
3234
5077
|
}));
|
|
3235
5078
|
}
|
|
@@ -3252,9 +5095,9 @@ function setOwn(target, key, value) {
|
|
|
3252
5095
|
if (key === "__proto__") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
|
|
3253
5096
|
else target[key] = value;
|
|
3254
5097
|
}
|
|
3255
|
-
function visible(
|
|
3256
|
-
const last =
|
|
3257
|
-
return last >= 55296 && last <= 56319 ?
|
|
5098
|
+
function visible(text3) {
|
|
5099
|
+
const last = text3.charCodeAt(text3.length - 1);
|
|
5100
|
+
return last >= 55296 && last <= 56319 ? text3.slice(0, -1) : text3;
|
|
3258
5101
|
}
|
|
3259
5102
|
var PartialJsonParser = class {
|
|
3260
5103
|
stack = [];
|
|
@@ -3328,27 +5171,27 @@ var PartialJsonParser = class {
|
|
|
3328
5171
|
snapshot() {
|
|
3329
5172
|
if (this.done) return this.root;
|
|
3330
5173
|
if (this.cache?.at === this.changes) return this.cache.value;
|
|
3331
|
-
let
|
|
5174
|
+
let child2 = void 0;
|
|
3332
5175
|
let hasChild = false;
|
|
3333
5176
|
if (this.token?.type === "string" && !this.token.isKey) {
|
|
3334
|
-
|
|
5177
|
+
child2 = visible(this.token.text);
|
|
3335
5178
|
hasChild = true;
|
|
3336
5179
|
}
|
|
3337
5180
|
for (let i = this.stack.length - 1; i >= 0; i -= 1) {
|
|
3338
5181
|
const frame = this.stack[i];
|
|
3339
5182
|
if (frame.type === "object") {
|
|
3340
5183
|
const copy = { ...frame.value };
|
|
3341
|
-
if (hasChild && frame.key !== void 0) setOwn(copy, frame.key,
|
|
3342
|
-
|
|
5184
|
+
if (hasChild && frame.key !== void 0) setOwn(copy, frame.key, child2);
|
|
5185
|
+
child2 = copy;
|
|
3343
5186
|
} else {
|
|
3344
5187
|
const copy = frame.value.slice();
|
|
3345
|
-
if (hasChild) copy.push(
|
|
3346
|
-
|
|
5188
|
+
if (hasChild) copy.push(child2);
|
|
5189
|
+
child2 = copy;
|
|
3347
5190
|
}
|
|
3348
5191
|
hasChild = true;
|
|
3349
5192
|
}
|
|
3350
|
-
this.cache = { at: this.changes, value:
|
|
3351
|
-
return
|
|
5193
|
+
this.cache = { at: this.changes, value: child2 };
|
|
5194
|
+
return child2;
|
|
3352
5195
|
}
|
|
3353
5196
|
structural(c) {
|
|
3354
5197
|
const frame = this.stack[this.stack.length - 1];
|
|
@@ -3483,9 +5326,9 @@ var PartialJsonParser = class {
|
|
|
3483
5326
|
return i;
|
|
3484
5327
|
}
|
|
3485
5328
|
};
|
|
3486
|
-
function parsePartialJson(
|
|
5329
|
+
function parsePartialJson(text3) {
|
|
3487
5330
|
const parser = new PartialJsonParser();
|
|
3488
|
-
parser.push(
|
|
5331
|
+
parser.push(text3);
|
|
3489
5332
|
return { value: parser.snapshot(), complete: parser.complete };
|
|
3490
5333
|
}
|
|
3491
5334
|
|
|
@@ -3631,6 +5474,7 @@ function createUpdateCardTool(cards) {
|
|
|
3631
5474
|
}
|
|
3632
5475
|
function createBuiltinTools(opts) {
|
|
3633
5476
|
const tools = [createVisualizeTool({ cards: opts.cards }), createUpdateCardTool(opts.cards)];
|
|
5477
|
+
if (opts.surfaces) tools.push(...createSurfaceTools({ catalogue: opts.surfaces }));
|
|
3634
5478
|
if (opts.skills && opts.skills.list().some((s) => s.mode === "manual")) {
|
|
3635
5479
|
tools.push(createLoadSkillTool(opts.skills));
|
|
3636
5480
|
}
|
|
@@ -3788,173 +5632,14 @@ function upsertCard(cards, card) {
|
|
|
3788
5632
|
const i = cards.findIndex((c) => c.id === card.id);
|
|
3789
5633
|
if (i === -1) return [...cards, card];
|
|
3790
5634
|
const next = [...cards];
|
|
3791
|
-
|
|
5635
|
+
const home = cards[i].callId;
|
|
5636
|
+
next[i] = home ? { ...card, callId: home } : card;
|
|
3792
5637
|
return next;
|
|
3793
5638
|
}
|
|
3794
5639
|
function markCallDone(parts, callId, status) {
|
|
3795
5640
|
return parts.map((p) => p.type === "tool-call" && p.callId === callId ? { ...p, status } : p);
|
|
3796
5641
|
}
|
|
3797
5642
|
|
|
3798
|
-
// src/runtime/metering.ts
|
|
3799
|
-
function usageSource(usage) {
|
|
3800
|
-
return Object.values(usage).some((value) => typeof value === "number") ? "provider" : "unavailable";
|
|
3801
|
-
}
|
|
3802
|
-
function combineMeteringSources(sources) {
|
|
3803
|
-
if (!sources.length) return "unavailable";
|
|
3804
|
-
const unique = new Set(sources);
|
|
3805
|
-
return unique.size === 1 ? sources[0] : "mixed";
|
|
3806
|
-
}
|
|
3807
|
-
async function deliverMetering(sink, record) {
|
|
3808
|
-
if (!sink) return;
|
|
3809
|
-
try {
|
|
3810
|
-
await sink.record(record);
|
|
3811
|
-
} catch (error) {
|
|
3812
|
-
try {
|
|
3813
|
-
await sink.onError?.(error, record);
|
|
3814
|
-
} catch {
|
|
3815
|
-
}
|
|
3816
|
-
}
|
|
3817
|
-
}
|
|
3818
|
-
|
|
3819
|
-
// src/runtime/execute-tools.ts
|
|
3820
|
-
var MAX_ERROR_CHARS = 400;
|
|
3821
|
-
function compactError(e) {
|
|
3822
|
-
if (e instanceof AgentError) {
|
|
3823
|
-
return { error: e.message.slice(0, MAX_ERROR_CHARS), kind: e.kind };
|
|
3824
|
-
}
|
|
3825
|
-
const message2 = e instanceof Error ? e.message : String(e);
|
|
3826
|
-
return { error: message2.slice(0, MAX_ERROR_CHARS) || "Tool failed with no message." };
|
|
3827
|
-
}
|
|
3828
|
-
var isToolResult = (v) => typeof v === "object" && v !== null && "output" in v && Object.keys(v).every((k) => ["output", "card", "failure", "cardId", "unlockTools"].includes(k));
|
|
3829
|
-
async function executeToolCall(call, opts) {
|
|
3830
|
-
const started = Date.now();
|
|
3831
|
-
const tool = opts.toolIndex ? opts.toolIndex.get(call.name) : opts.tools.find((t) => t.name === call.name);
|
|
3832
|
-
if (!tool) {
|
|
3833
|
-
return {
|
|
3834
|
-
callId: call.callId,
|
|
3835
|
-
name: call.name,
|
|
3836
|
-
output: {
|
|
3837
|
-
error: `Unknown tool "${call.name}".`,
|
|
3838
|
-
availableTools: opts.tools.map((t) => t.name)
|
|
3839
|
-
},
|
|
3840
|
-
failure: "not-found",
|
|
3841
|
-
ms: Date.now() - started
|
|
3842
|
-
};
|
|
3843
|
-
}
|
|
3844
|
-
let emittedCard;
|
|
3845
|
-
let settled = false;
|
|
3846
|
-
const ctx = {
|
|
3847
|
-
vars: opts.vars,
|
|
3848
|
-
signal: opts.signal,
|
|
3849
|
-
callId: call.callId,
|
|
3850
|
-
emitCard: (spec) => {
|
|
3851
|
-
if (settled) return;
|
|
3852
|
-
const card = makeCard(spec, call.callId);
|
|
3853
|
-
emittedCard = card;
|
|
3854
|
-
opts.onCard?.(card);
|
|
3855
|
-
},
|
|
3856
|
-
...opts.requestCard ? {
|
|
3857
|
-
requestCard: (spec) => settled ? Promise.reject(new AgentError("cancelled", `Tool "${call.name}" already finished.`)) : opts.requestCard(call.callId, spec)
|
|
3858
|
-
} : {}
|
|
3859
|
-
};
|
|
3860
|
-
try {
|
|
3861
|
-
const raw = tool.execute ? await withTimeout(Promise.resolve(tool.execute(call.input, ctx)), opts.timeoutMs, call.name) : opts.onHostTool ? await withTimeout(opts.onHostTool(call), opts.timeoutMs, call.name) : (() => {
|
|
3862
|
-
throw new AgentError("not-supported", `Tool "${call.name}" has no executor and no host handler.`);
|
|
3863
|
-
})();
|
|
3864
|
-
const result = isToolResult(raw) ? raw : { output: raw };
|
|
3865
|
-
let card = emittedCard;
|
|
3866
|
-
let output = result.output;
|
|
3867
|
-
if (result.card) {
|
|
3868
|
-
card = makeCard(result.card, call.callId, result.cardId);
|
|
3869
|
-
output = withCard(asRecord(result.output), card.spec, card.id);
|
|
3870
|
-
opts.onCard?.(card);
|
|
3871
|
-
} else if (isCardCarrier(result.output)) {
|
|
3872
|
-
const embedded = result.output[CARD_KEY];
|
|
3873
|
-
card = { ...embedded, callId: call.callId };
|
|
3874
|
-
opts.onCard?.(card);
|
|
3875
|
-
}
|
|
3876
|
-
return {
|
|
3877
|
-
callId: call.callId,
|
|
3878
|
-
name: call.name,
|
|
3879
|
-
output,
|
|
3880
|
-
...card ? { card } : {},
|
|
3881
|
-
...result.failure ? { failure: result.failure } : {},
|
|
3882
|
-
...result.unlockTools?.length ? { unlockTools: result.unlockTools } : {},
|
|
3883
|
-
ms: Date.now() - started
|
|
3884
|
-
};
|
|
3885
|
-
} catch (e) {
|
|
3886
|
-
const err = toAgentError(e);
|
|
3887
|
-
return {
|
|
3888
|
-
callId: call.callId,
|
|
3889
|
-
name: call.name,
|
|
3890
|
-
output: compactError(err),
|
|
3891
|
-
failure: err.kind === "cancelled" ? "denied" : "execution-error",
|
|
3892
|
-
ms: Date.now() - started
|
|
3893
|
-
};
|
|
3894
|
-
} finally {
|
|
3895
|
-
settled = true;
|
|
3896
|
-
}
|
|
3897
|
-
}
|
|
3898
|
-
async function executeToolCalls(calls, opts) {
|
|
3899
|
-
const toolIndex = opts.toolIndex ?? new Map(opts.tools.map((t) => [t.name, t]));
|
|
3900
|
-
const callOpts = opts.toolIndex ? opts : { ...opts, toolIndex };
|
|
3901
|
-
const interactive = calls.filter((c) => toolIndex.get(c.name)?.side === "confirm");
|
|
3902
|
-
const concurrent = calls.filter((c) => !interactive.includes(c));
|
|
3903
|
-
const settle = async (c) => {
|
|
3904
|
-
const outcome = await executeToolCall(c, callOpts);
|
|
3905
|
-
opts.onOutcome?.(outcome);
|
|
3906
|
-
return outcome;
|
|
3907
|
-
};
|
|
3908
|
-
const concurrentResults = await Promise.all(concurrent.map(settle));
|
|
3909
|
-
const serialResults = [];
|
|
3910
|
-
for (const c of interactive) serialResults.push(await settle(c));
|
|
3911
|
-
const byId = new Map([...concurrentResults, ...serialResults].map((r) => [r.callId, r]));
|
|
3912
|
-
return calls.map((c) => byId.get(c.callId)).filter(Boolean);
|
|
3913
|
-
}
|
|
3914
|
-
function asRecord(value) {
|
|
3915
|
-
if (typeof value === "object" && value !== null && !Array.isArray(value)) return value;
|
|
3916
|
-
return { result: value };
|
|
3917
|
-
}
|
|
3918
|
-
function withTimeout(promise, ms, name) {
|
|
3919
|
-
if (!ms) return promise;
|
|
3920
|
-
return Promise.race([
|
|
3921
|
-
promise,
|
|
3922
|
-
new Promise(
|
|
3923
|
-
(_, reject) => setTimeout(() => reject(new AgentError("timeout", `Tool "${name}" timed out after ${ms}ms.`)), ms)
|
|
3924
|
-
)
|
|
3925
|
-
]);
|
|
3926
|
-
}
|
|
3927
|
-
|
|
3928
|
-
// src/runtime/channel.ts
|
|
3929
|
-
var EventChannel = class {
|
|
3930
|
-
queue = [];
|
|
3931
|
-
waiting = [];
|
|
3932
|
-
closed = false;
|
|
3933
|
-
/** Enqueue an event, handing it straight to a waiting consumer if there is one. */
|
|
3934
|
-
push(value) {
|
|
3935
|
-
if (this.closed) return;
|
|
3936
|
-
const resolve = this.waiting.shift();
|
|
3937
|
-
if (resolve) resolve({ value, done: false });
|
|
3938
|
-
else this.queue.push(value);
|
|
3939
|
-
}
|
|
3940
|
-
/** No more events. Consumers drain what is buffered, then finish. */
|
|
3941
|
-
close() {
|
|
3942
|
-
if (this.closed) return;
|
|
3943
|
-
this.closed = true;
|
|
3944
|
-
for (const resolve of this.waiting) resolve({ value: void 0, done: true });
|
|
3945
|
-
this.waiting = [];
|
|
3946
|
-
}
|
|
3947
|
-
[Symbol.asyncIterator]() {
|
|
3948
|
-
return {
|
|
3949
|
-
next: () => {
|
|
3950
|
-
if (this.queue.length) return Promise.resolve({ value: this.queue.shift(), done: false });
|
|
3951
|
-
if (this.closed) return Promise.resolve({ value: void 0, done: true });
|
|
3952
|
-
return new Promise((resolve) => this.waiting.push(resolve));
|
|
3953
|
-
}
|
|
3954
|
-
};
|
|
3955
|
-
}
|
|
3956
|
-
};
|
|
3957
|
-
|
|
3958
5643
|
// src/runtime/stop.ts
|
|
3959
5644
|
var stepCountIs = (n) => (ctx) => ctx.step >= n;
|
|
3960
5645
|
var afterTool = (...names) => (ctx) => ctx.outcomes.some((o) => names.includes(o.name) && !o.failure);
|
|
@@ -3984,6 +5669,7 @@ async function* runAgent(messages, config) {
|
|
|
3984
5669
|
const maxSteps = config.maxSteps ?? 8;
|
|
3985
5670
|
const vars = config.vars ?? {};
|
|
3986
5671
|
const runStartedAt = Date.now();
|
|
5672
|
+
const surfaces = config.surfaces ?? new SurfaceLedger(foldSurfaces(messages));
|
|
3987
5673
|
yield { type: "run-start", runId, mode };
|
|
3988
5674
|
const history = [...messages];
|
|
3989
5675
|
let totalUsage = {};
|
|
@@ -4207,14 +5893,16 @@ async function* runAgent(messages, config) {
|
|
|
4207
5893
|
vars,
|
|
4208
5894
|
signal: config.signal,
|
|
4209
5895
|
timeoutMs: config.toolTimeoutMs,
|
|
5896
|
+
surfaces,
|
|
5897
|
+
surfaceActionTools: surfaceActionTools(config.tools, config.toolResolution).map((t) => t.name),
|
|
4210
5898
|
onCard: (card) => channel.push({ type: "card", card }),
|
|
4211
|
-
onOutcome: (
|
|
5899
|
+
onOutcome: (outcome2) => channel.push({
|
|
4212
5900
|
type: "tool-result",
|
|
4213
|
-
callId:
|
|
4214
|
-
name:
|
|
4215
|
-
output:
|
|
4216
|
-
...
|
|
4217
|
-
ms:
|
|
5901
|
+
callId: outcome2.callId,
|
|
5902
|
+
name: outcome2.name,
|
|
5903
|
+
output: outcome2.output,
|
|
5904
|
+
...outcome2.failure ? { failure: outcome2.failure } : {},
|
|
5905
|
+
ms: outcome2.ms
|
|
4218
5906
|
}),
|
|
4219
5907
|
onHostTool: config.onHostTool,
|
|
4220
5908
|
requestCard: config.onUserDecision ? async (callId, spec) => {
|
|
@@ -4229,15 +5917,15 @@ async function* runAgent(messages, config) {
|
|
|
4229
5917
|
const outcomes = await running;
|
|
4230
5918
|
const providerParts = [];
|
|
4231
5919
|
const persistedParts = [];
|
|
4232
|
-
for (const
|
|
5920
|
+
for (const outcome2 of outcomes) {
|
|
4233
5921
|
const base = {
|
|
4234
5922
|
type: "tool-result",
|
|
4235
|
-
callId:
|
|
4236
|
-
name:
|
|
4237
|
-
...
|
|
5923
|
+
callId: outcome2.callId,
|
|
5924
|
+
name: outcome2.name,
|
|
5925
|
+
...outcome2.failure ? { failure: outcome2.failure } : {}
|
|
4238
5926
|
};
|
|
4239
|
-
providerParts.push({ ...base, output: stripCardPayload(
|
|
4240
|
-
persistedParts.push({ ...base, output:
|
|
5927
|
+
providerParts.push({ ...base, output: stripCardPayload(outcome2.output) });
|
|
5928
|
+
persistedParts.push({ ...base, output: outcome2.output });
|
|
4241
5929
|
}
|
|
4242
5930
|
const createdAt = Date.now();
|
|
4243
5931
|
const toolId = nextId("tool");
|
|
@@ -4724,7 +6412,7 @@ function createMemorySource(store, opts = {}) {
|
|
|
4724
6412
|
async run({ vars }) {
|
|
4725
6413
|
const entries = (await store.list(vars)).slice(0, opts.maxEntries ?? 50);
|
|
4726
6414
|
if (!entries.length) return {};
|
|
4727
|
-
const
|
|
6415
|
+
const text3 = [
|
|
4728
6416
|
"Things you remember about this user, from earlier conversations:",
|
|
4729
6417
|
...entries.map((e) => `- ${e.key}: ${e.value}`),
|
|
4730
6418
|
"Apply them without re-asking. Update them with the `remember` tool when they change."
|
|
@@ -4734,8 +6422,8 @@ function createMemorySource(store, opts = {}) {
|
|
|
4734
6422
|
{
|
|
4735
6423
|
id: opts.id ?? "memory",
|
|
4736
6424
|
kind: "memory",
|
|
4737
|
-
text:
|
|
4738
|
-
tokens: estimateTokens(
|
|
6425
|
+
text: text3,
|
|
6426
|
+
tokens: estimateTokens(text3),
|
|
4739
6427
|
priority: opts.priority ?? 500
|
|
4740
6428
|
}
|
|
4741
6429
|
]
|
|
@@ -4781,7 +6469,7 @@ function createRetrievalSource(retriever, opts = {}) {
|
|
|
4781
6469
|
opts.limit ?? 5
|
|
4782
6470
|
);
|
|
4783
6471
|
if (!chunks.length) return {};
|
|
4784
|
-
const
|
|
6472
|
+
const text3 = [
|
|
4785
6473
|
"Reference material retrieved for this question. Ground your answer in it when relevant:",
|
|
4786
6474
|
...chunks.map(
|
|
4787
6475
|
(c, i) => `[${i + 1}] ${c.title ?? c.id}${c.source ? ` (${c.source})` : ""}
|
|
@@ -4794,8 +6482,8 @@ ${c.text.trim()}`
|
|
|
4794
6482
|
{
|
|
4795
6483
|
id: opts.id ?? "retrieval",
|
|
4796
6484
|
kind: "custom",
|
|
4797
|
-
text:
|
|
4798
|
-
tokens: estimateTokens(
|
|
6485
|
+
text: text3,
|
|
6486
|
+
tokens: estimateTokens(text3),
|
|
4799
6487
|
priority: opts.priority ?? 400
|
|
4800
6488
|
}
|
|
4801
6489
|
]
|
|
@@ -4874,7 +6562,7 @@ ${body}`);
|
|
|
4874
6562
|
}
|
|
4875
6563
|
}
|
|
4876
6564
|
if (!blocks.length) return {};
|
|
4877
|
-
const
|
|
6565
|
+
const text3 = [
|
|
4878
6566
|
"Current state of the application the user is looking at. This is live \u2014 it reflects the screen right now, not the conversation:",
|
|
4879
6567
|
...blocks,
|
|
4880
6568
|
"Refer to it directly rather than asking the user to repeat what is already on screen."
|
|
@@ -4884,8 +6572,8 @@ ${body}`);
|
|
|
4884
6572
|
{
|
|
4885
6573
|
id: opts.id ?? "app-state",
|
|
4886
6574
|
kind: "environment",
|
|
4887
|
-
text:
|
|
4888
|
-
tokens: estimateTokens(
|
|
6575
|
+
text: text3,
|
|
6576
|
+
tokens: estimateTokens(text3),
|
|
4889
6577
|
priority: opts.priority ?? 600
|
|
4890
6578
|
}
|
|
4891
6579
|
]
|
|
@@ -5217,9 +6905,9 @@ function createMcpSkill(serverName, defs, opts = {}) {
|
|
|
5217
6905
|
}
|
|
5218
6906
|
function elicitViaCard(requestCard) {
|
|
5219
6907
|
return async (params) => {
|
|
5220
|
-
const
|
|
6908
|
+
const props2 = params.requestedSchema?.properties ?? {};
|
|
5221
6909
|
const required = new Set(params.requestedSchema?.required ?? []);
|
|
5222
|
-
const fields = Object.entries(
|
|
6910
|
+
const fields = Object.entries(props2).map(([name, p]) => {
|
|
5223
6911
|
const label = p.title ?? name;
|
|
5224
6912
|
if (Array.isArray(p.enum) && p.enum.length) {
|
|
5225
6913
|
return {
|
|
@@ -5257,19 +6945,22 @@ function elicitViaCard(requestCard) {
|
|
|
5257
6945
|
};
|
|
5258
6946
|
}
|
|
5259
6947
|
var textOf = (content) => content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
|
|
5260
|
-
function parseMaybeJson(
|
|
5261
|
-
const trimmed =
|
|
5262
|
-
if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return
|
|
6948
|
+
function parseMaybeJson(text3) {
|
|
6949
|
+
const trimmed = text3.trim();
|
|
6950
|
+
if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return text3;
|
|
5263
6951
|
try {
|
|
5264
6952
|
return JSON.parse(trimmed);
|
|
5265
6953
|
} catch {
|
|
5266
|
-
return
|
|
6954
|
+
return text3;
|
|
5267
6955
|
}
|
|
5268
6956
|
}
|
|
5269
6957
|
export {
|
|
6958
|
+
A2UI_VERSION,
|
|
5270
6959
|
ANTHROPIC_OFFICIAL_PROFILE,
|
|
5271
6960
|
AgentError,
|
|
5272
6961
|
BUILTIN_CARDS,
|
|
6962
|
+
CARD_COMPONENT,
|
|
6963
|
+
CARD_ENTRY_PREFIX,
|
|
5273
6964
|
CARD_KEY,
|
|
5274
6965
|
CardRegistry,
|
|
5275
6966
|
ContextBuilder,
|
|
@@ -5284,29 +6975,46 @@ export {
|
|
|
5284
6975
|
PartialJsonParser,
|
|
5285
6976
|
QUOTES_METADATA_KEY,
|
|
5286
6977
|
SSEDecoder,
|
|
6978
|
+
SURFACE_A2UI_CATALOG_ID,
|
|
6979
|
+
SURFACE_ARTIFACT_KIND,
|
|
6980
|
+
SURFACE_CARD_KIND,
|
|
6981
|
+
SURFACE_EVENT_METADATA_KEY,
|
|
6982
|
+
SURFACE_FORMAT_VERSION,
|
|
6983
|
+
SURFACE_GUIDE,
|
|
6984
|
+
SURFACE_LIMITS,
|
|
6985
|
+
SURFACE_PRIMITIVES,
|
|
6986
|
+
SURFACE_SKILL_ID,
|
|
6987
|
+
SURFACE_TOOL_NAMES,
|
|
5287
6988
|
SkillRegistry,
|
|
6989
|
+
SurfaceCatalogue,
|
|
6990
|
+
SurfaceLedger,
|
|
5288
6991
|
THREAD_SCHEMA_VERSION,
|
|
5289
6992
|
ToolRegistry,
|
|
5290
6993
|
afterTool,
|
|
5291
6994
|
appendReasoning,
|
|
5292
6995
|
appendText,
|
|
5293
6996
|
applyEdits,
|
|
6997
|
+
applySurfaceOperations,
|
|
5294
6998
|
assistantMessage,
|
|
6999
|
+
authorizeSurfaceTool,
|
|
5295
7000
|
awaitJob,
|
|
5296
7001
|
backoffDelay,
|
|
5297
7002
|
base64ToBytes,
|
|
7003
|
+
bindingProblems,
|
|
5298
7004
|
buildAnthropicRequest,
|
|
5299
7005
|
buildChatRequest,
|
|
5300
7006
|
buildEml,
|
|
5301
7007
|
buildMailto,
|
|
5302
7008
|
buildResponsesRequest,
|
|
5303
7009
|
buildSummaryPrompt,
|
|
7010
|
+
buildSurface,
|
|
5304
7011
|
buildUrl,
|
|
5305
7012
|
bytesToBase64,
|
|
5306
7013
|
calloutCard,
|
|
5307
7014
|
chartCard,
|
|
5308
7015
|
check,
|
|
5309
7016
|
checkQuoteDrift,
|
|
7017
|
+
checkSchema,
|
|
5310
7018
|
checklistCard,
|
|
5311
7019
|
childrenOf,
|
|
5312
7020
|
choiceCard,
|
|
@@ -5353,6 +7061,9 @@ export {
|
|
|
5353
7061
|
createRememberTool,
|
|
5354
7062
|
createRestThreadStore,
|
|
5355
7063
|
createRetrievalSource,
|
|
7064
|
+
createSurfaceContextSource,
|
|
7065
|
+
createSurfaceSkill,
|
|
7066
|
+
createSurfaceTools,
|
|
5356
7067
|
createUpdateCardTool,
|
|
5357
7068
|
createVisualizeTool,
|
|
5358
7069
|
deliverMetering,
|
|
@@ -5365,14 +7076,20 @@ export {
|
|
|
5365
7076
|
errorFromResponse,
|
|
5366
7077
|
estimateJsonTokens,
|
|
5367
7078
|
estimateTokens,
|
|
7079
|
+
evaluateSurfaceCondition,
|
|
5368
7080
|
executeToolCall,
|
|
5369
7081
|
executeToolCalls,
|
|
5370
7082
|
file,
|
|
7083
|
+
findUnsafe,
|
|
7084
|
+
foldSurfaces,
|
|
5371
7085
|
formCard,
|
|
5372
7086
|
formatQuotes,
|
|
7087
|
+
formatTemplate,
|
|
5373
7088
|
funnelCard,
|
|
5374
7089
|
gaugeCard,
|
|
5375
7090
|
generatedMediaUrl,
|
|
7091
|
+
getAt,
|
|
7092
|
+
hasTurnOrder,
|
|
5376
7093
|
hunksOf,
|
|
5377
7094
|
image,
|
|
5378
7095
|
importMcpTools,
|
|
@@ -5380,6 +7097,10 @@ export {
|
|
|
5380
7097
|
isAgentError,
|
|
5381
7098
|
isCardCarrier,
|
|
5382
7099
|
isMultipartBody,
|
|
7100
|
+
isScriptUrl,
|
|
7101
|
+
isSurfaceBinding,
|
|
7102
|
+
isSurfaceId,
|
|
7103
|
+
isSurfaceSpec,
|
|
5383
7104
|
isTerminal,
|
|
5384
7105
|
isTextPart,
|
|
5385
7106
|
isToolCallPart,
|
|
@@ -5388,6 +7109,7 @@ export {
|
|
|
5388
7109
|
kindFromStatus,
|
|
5389
7110
|
lastUserText,
|
|
5390
7111
|
latestLeaf,
|
|
7112
|
+
layoutTurn,
|
|
5391
7113
|
linkLinear,
|
|
5392
7114
|
makeCard,
|
|
5393
7115
|
mapMcpResult,
|
|
@@ -5403,24 +7125,34 @@ export {
|
|
|
5403
7125
|
outlineOf,
|
|
5404
7126
|
packByPriority,
|
|
5405
7127
|
parsePartialJson,
|
|
7128
|
+
parsePointer,
|
|
5406
7129
|
parseRetryAfter,
|
|
5407
7130
|
parseSSE,
|
|
5408
7131
|
parseSSEJson,
|
|
5409
7132
|
pathTo,
|
|
7133
|
+
previewSurface,
|
|
5410
7134
|
progressCard,
|
|
5411
7135
|
quoteDrift,
|
|
5412
7136
|
quotesOf,
|
|
5413
7137
|
reap,
|
|
5414
7138
|
reduceRunEvent,
|
|
7139
|
+
removeAt,
|
|
5415
7140
|
renderSkill,
|
|
5416
7141
|
repairToolArguments,
|
|
5417
7142
|
resolvePartialCard,
|
|
7143
|
+
resolveSurfaceAction,
|
|
7144
|
+
resolveSurfaceValue,
|
|
5418
7145
|
resolveToolLoading,
|
|
5419
7146
|
resumeJobs,
|
|
5420
7147
|
runAgent,
|
|
7148
|
+
runSurfaceQuery,
|
|
7149
|
+
runSurfaceToolAction,
|
|
5421
7150
|
safeCutIndex,
|
|
7151
|
+
safeSurfaceUrl,
|
|
7152
|
+
sanitizeSurfaceSpec,
|
|
5422
7153
|
scoreSkill,
|
|
5423
7154
|
searchBlocks,
|
|
7155
|
+
setAt,
|
|
5424
7156
|
shouldStop,
|
|
5425
7157
|
siblingsOf,
|
|
5426
7158
|
spanOf,
|
|
@@ -5429,10 +7161,13 @@ export {
|
|
|
5429
7161
|
stepCountIs,
|
|
5430
7162
|
stripCardPayload,
|
|
5431
7163
|
stripUiOnlyParts,
|
|
7164
|
+
surfaceActionTools,
|
|
7165
|
+
surfaceCardId,
|
|
5432
7166
|
tableCard,
|
|
5433
7167
|
text,
|
|
5434
7168
|
threadSnapshot,
|
|
5435
7169
|
timelineCard,
|
|
7170
|
+
toA2uiMessages,
|
|
5436
7171
|
toAgentError,
|
|
5437
7172
|
tokenBudgetExceeded,
|
|
5438
7173
|
tokenize,
|
|
@@ -5445,6 +7180,11 @@ export {
|
|
|
5445
7180
|
usageSource,
|
|
5446
7181
|
userDeclined,
|
|
5447
7182
|
userMessage,
|
|
7183
|
+
usesBinding,
|
|
7184
|
+
validateSurfaceAction,
|
|
7185
|
+
validateSurfaceComponent,
|
|
7186
|
+
validateSurfaceComponents,
|
|
7187
|
+
validateSurfaceGraph,
|
|
5448
7188
|
withCard,
|
|
5449
7189
|
withQuotes,
|
|
5450
7190
|
withRetry
|