@xmoon76/dsh-pi-tui 0.5.3 → 0.5.4
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/README.en.md +174 -150
- package/README.md +118 -103
- package/cordis.patch.yml +54 -2
- package/dist/builtins.mjs +2 -2
- package/dist/client-bootstrap-F5DHFI9t.mjs +5576 -0
- package/dist/context-summary-DAisTA_7.mjs +8557 -0
- package/dist/dispose-cause-CNFuUnjR.mjs +24 -0
- package/dist/entry-control-DvSrndWd.mjs +111 -0
- package/dist/extension/advanced.d.mts +1 -1
- package/dist/extension/unstable.d.mts +1 -1
- package/dist/{extensions-DzpBiiYb.d.mts → extensions-Bte3XOt5.d.mts} +1 -1
- package/dist/{extensions-a-rxanjw.mjs → extensions-CcuMY4n2.mjs} +722 -324
- package/dist/extensions.d.mts +2 -2
- package/dist/extensions.mjs +1 -1
- package/dist/host-bootstrap-DAgKknbY.mjs +119 -0
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +45243 -27018
- package/dist/local-client.mjs +323 -0
- package/dist/local-host.mjs +176 -0
- package/dist/{performance-host-BJT6scGF.mjs → performance-host-CcDJjjVA.mjs} +1 -1
- package/dist/performance-host.mjs +1 -1
- package/dist/{performance-view-jvvd8Jn7.mjs → performance-view-CfGvLZyD.mjs} +1 -1
- package/dist/{public-types-gZi3iFNh.d.mts → public-types-Dgf1bDke.d.mts} +3 -3
- package/dist/runtime-status-0lp9CM0V.mjs +1923 -0
- package/dist/{runtime-BtPH-UUb.mjs → runtime-vc4mdr-R.mjs} +1395 -1088
- package/dist/{session-BZLxhrPQ.mjs → session-tdJHLnJR.mjs} +3329 -281
- package/dist/{startup-D5Xu8diR.mjs → startup-JaVZoTIl.mjs} +54 -13
- package/dist/startup.d.mts +2 -1
- package/dist/startup.mjs +1 -1
- package/dist/{terminal-progress-source-BlmksrSD.mjs → terminal-progress-source-xor3vakJ.mjs} +102 -46
- package/dist/visual-tools.d.mts +62 -0
- package/dist/visual-tools.mjs +556 -0
- package/generated/dsh-presets/README.md +1 -1
- package/package.json +132 -113
- package/dist/context-summary-CxUpNkA9.mjs +0 -2951
|
@@ -0,0 +1,1923 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { eastAsianWidth } from "get-east-asian-width";
|
|
3
|
+
import { SaxesParser } from "saxes";
|
|
4
|
+
//#region src/domain/transcript/visual-text.ts
|
|
5
|
+
/** The generating chart tool. */
|
|
6
|
+
const CHART_TOOL_NAME = "dsh_pi_tui_chart";
|
|
7
|
+
/** The generating SVG tool. */
|
|
8
|
+
const SVG_TOOL_NAME = "dsh_pi_tui_svg";
|
|
9
|
+
/** The publication tool (deliberately NOT namespaced). */
|
|
10
|
+
const PRESENT_VISUAL_TOOL_NAME = "present_visual";
|
|
11
|
+
/** Whether one model tool name is one of the three official visual tools. */
|
|
12
|
+
function isVisualToolName(name) {
|
|
13
|
+
return name === "dsh_pi_tui_chart" || name === "dsh_pi_tui_svg" || name === "present_visual";
|
|
14
|
+
}
|
|
15
|
+
/** Prefix of the durable publication receipt block. */
|
|
16
|
+
const VISUAL_PUBLISHED_PREFIX = "visual-published-v1:";
|
|
17
|
+
/** The one accepted reference spelling (lowercase hex, exactly 20 digits). */
|
|
18
|
+
const VISUAL_REFERENCE_PATTERN$1 = /^sv1_[0-9a-f]{20}$/u;
|
|
19
|
+
/** Parse exactly `<ref block>`; anything else is human text. */
|
|
20
|
+
function parseOfficialReferenceBlock(text) {
|
|
21
|
+
if (!text.startsWith("visual-ref-v1:")) return void 0;
|
|
22
|
+
const ref = text.slice(14);
|
|
23
|
+
return VISUAL_REFERENCE_PATTERN$1.test(ref) ? ref : void 0;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The official serializers' own value bounds.
|
|
27
|
+
*
|
|
28
|
+
* These mirror `domain/visual/constants.ts`. They are duplicated here rather
|
|
29
|
+
* than imported because `domain/transcript/**` may only import its own subtree
|
|
30
|
+
* (the architecture gate is closed-world there). They serve ONE purpose: the
|
|
31
|
+
* readable projection must refuse a machine-SHAPED line that the official
|
|
32
|
+
* serializer could not have produced. Drawing semantics and every budget that
|
|
33
|
+
* governs admission stay owned by `domain/visual/**`.
|
|
34
|
+
*/
|
|
35
|
+
const FACT_LIMITS = {
|
|
36
|
+
chartMaxPoints: 12,
|
|
37
|
+
chartMaxTitleCodePoints: 100,
|
|
38
|
+
chartMaxUnitCodePoints: 32,
|
|
39
|
+
chartMaxLabelCodePoints: 48,
|
|
40
|
+
svgMaxSourceBytes: 131072,
|
|
41
|
+
svgMaxTitleCodePoints: 100,
|
|
42
|
+
svgMaxDescriptionCodePoints: 500
|
|
43
|
+
};
|
|
44
|
+
const CHART_KINDS$1 = /* @__PURE__ */ new Set(["bars", "spark"]);
|
|
45
|
+
const DIGEST_PATTERN$1 = /^[0-9a-f]{64}$/u;
|
|
46
|
+
function isRecord$2(value) {
|
|
47
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
48
|
+
}
|
|
49
|
+
function hasOnlyKeys$2(value, keys) {
|
|
50
|
+
const allowed = new Set(keys);
|
|
51
|
+
return Object.keys(value).every((key) => allowed.has(key));
|
|
52
|
+
}
|
|
53
|
+
function codePointLength$1(text) {
|
|
54
|
+
let count = 0;
|
|
55
|
+
for (const _ of text) count += 1;
|
|
56
|
+
return count;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Whether one string is a NON-EMPTY string within the official code-point
|
|
60
|
+
* budget.
|
|
61
|
+
*
|
|
62
|
+
* This deliberately mirrors the official serializers' rule EXACTLY: they reject
|
|
63
|
+
* the empty string, never a whitespace-only one (`chartCoreProblem` accepts
|
|
64
|
+
* `unit: " "` and `label: " "`, and `svgArgsShapeProblem` uses `trim()` only for
|
|
65
|
+
* the title/description it requires to be meaningful). A filter that were
|
|
66
|
+
* stricter than the serializer would fail to recognise a fact the tool really
|
|
67
|
+
* produced and leak the machine line into human-facing output.
|
|
68
|
+
*/
|
|
69
|
+
/**
|
|
70
|
+
* Whether one string is a MEANINGFUL bounded text.
|
|
71
|
+
*
|
|
72
|
+
* The chart title and the SVG title/description are the official serializers'
|
|
73
|
+
* `trim() !== ''` fields, so they keep the stricter rule.
|
|
74
|
+
*/
|
|
75
|
+
function isOfficialMeaningfulText(value, max) {
|
|
76
|
+
return typeof value === "string" && value.trim() !== "" && codePointLength$1(value) <= max;
|
|
77
|
+
}
|
|
78
|
+
function isOfficialNonEmptyText(value, max) {
|
|
79
|
+
return typeof value === "string" && value !== "" && codePointLength$1(value) <= max;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Parse exactly `<fact block>` down to a fully valid official fact.
|
|
83
|
+
*
|
|
84
|
+
* The line must satisfy the official serializer's own value rules — the chart
|
|
85
|
+
* kind enum, the ordered series of finite numbered points with non-empty
|
|
86
|
+
* bounded labels, the bounded title/unit, the SVG's 64-hex digest and bounded
|
|
87
|
+
* credential — so ordinary prose that merely carries the right KEY SETS is not
|
|
88
|
+
* mistaken for a machine block.
|
|
89
|
+
* @param text - one result block's text.
|
|
90
|
+
* @returns the fact type when the line is a valid official fact.
|
|
91
|
+
*/
|
|
92
|
+
function parseOfficialFactBlock(text) {
|
|
93
|
+
if (!text.startsWith("visual-v1:")) return void 0;
|
|
94
|
+
let parsed;
|
|
95
|
+
try {
|
|
96
|
+
parsed = JSON.parse(text.slice(10));
|
|
97
|
+
} catch {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (!isRecord$2(parsed) || parsed.version !== 1) return void 0;
|
|
101
|
+
if (parsed.type === "chart") {
|
|
102
|
+
if (!hasOnlyKeys$2(parsed, [
|
|
103
|
+
"version",
|
|
104
|
+
"type",
|
|
105
|
+
"kind",
|
|
106
|
+
"title",
|
|
107
|
+
"unit",
|
|
108
|
+
"series"
|
|
109
|
+
])) return void 0;
|
|
110
|
+
if (typeof parsed.kind !== "string" || !CHART_KINDS$1.has(parsed.kind)) return void 0;
|
|
111
|
+
if (!isOfficialMeaningfulText(parsed.title, FACT_LIMITS.chartMaxTitleCodePoints)) return void 0;
|
|
112
|
+
if (parsed.unit !== void 0 && !isOfficialNonEmptyText(parsed.unit, FACT_LIMITS.chartMaxUnitCodePoints)) return void 0;
|
|
113
|
+
if (!Array.isArray(parsed.series)) return void 0;
|
|
114
|
+
const series = parsed.series;
|
|
115
|
+
if (series.length < 2 || series.length > FACT_LIMITS.chartMaxPoints) return void 0;
|
|
116
|
+
for (const point of series) {
|
|
117
|
+
if (!isRecord$2(point) || !hasOnlyKeys$2(point, ["label", "value"])) return void 0;
|
|
118
|
+
if (!isOfficialNonEmptyText(point.label, FACT_LIMITS.chartMaxLabelCodePoints)) return void 0;
|
|
119
|
+
if (typeof point.value !== "number" || !Number.isFinite(point.value)) return void 0;
|
|
120
|
+
}
|
|
121
|
+
return { type: "chart" };
|
|
122
|
+
}
|
|
123
|
+
if (parsed.type === "svg") {
|
|
124
|
+
if (!hasOnlyKeys$2(parsed, [
|
|
125
|
+
"version",
|
|
126
|
+
"type",
|
|
127
|
+
"title",
|
|
128
|
+
"description",
|
|
129
|
+
"digest",
|
|
130
|
+
"bytes"
|
|
131
|
+
])) return void 0;
|
|
132
|
+
if (!isOfficialMeaningfulText(parsed.title, FACT_LIMITS.svgMaxTitleCodePoints)) return void 0;
|
|
133
|
+
if (!isOfficialMeaningfulText(parsed.description, FACT_LIMITS.svgMaxDescriptionCodePoints)) return void 0;
|
|
134
|
+
if (typeof parsed.digest !== "string" || !DIGEST_PATTERN$1.test(parsed.digest)) return void 0;
|
|
135
|
+
if (typeof parsed.bytes !== "number" || !Number.isSafeInteger(parsed.bytes)) return void 0;
|
|
136
|
+
if (parsed.bytes < 0 || parsed.bytes > FACT_LIMITS.svgMaxSourceBytes) return void 0;
|
|
137
|
+
return { type: "svg" };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** Parse exactly `<receipt block>` with its full official shape. */
|
|
141
|
+
function parseOfficialReceiptBlock(text) {
|
|
142
|
+
if (!text.startsWith("visual-published-v1:")) return void 0;
|
|
143
|
+
let parsed;
|
|
144
|
+
try {
|
|
145
|
+
parsed = JSON.parse(text.slice(20));
|
|
146
|
+
} catch {
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
|
|
150
|
+
const record = parsed;
|
|
151
|
+
if (Object.keys(record).length !== 2 || record.version !== 1 || !Array.isArray(record.published)) return void 0;
|
|
152
|
+
if (record.published.length === 0 || record.published.length > 8) return void 0;
|
|
153
|
+
const published = [];
|
|
154
|
+
for (const entry of record.published) {
|
|
155
|
+
if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return void 0;
|
|
156
|
+
const fields = entry;
|
|
157
|
+
if (Object.keys(fields).length !== 1 || typeof fields.ref !== "string") return void 0;
|
|
158
|
+
if (!VISUAL_REFERENCE_PATTERN$1.test(fields.ref)) return void 0;
|
|
159
|
+
published.push({ ref: fields.ref });
|
|
160
|
+
}
|
|
161
|
+
if (new Set(published.map((entry) => entry.ref)).size !== published.length) return void 0;
|
|
162
|
+
return {
|
|
163
|
+
version: 1,
|
|
164
|
+
published
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* The length of the official machine-block SUFFIX this exact tool can produce.
|
|
169
|
+
*
|
|
170
|
+
* Each tool has one canonical tail composition, and a result carries at most
|
|
171
|
+
* that composition:
|
|
172
|
+
*
|
|
173
|
+
* - a generator: optionally one `visual-ref-v1` block immediately followed by
|
|
174
|
+
* one `visual-v1` fact block of the MATCHING type, or the fact block alone
|
|
175
|
+
* (the reference is only projected for a root call inside an open step);
|
|
176
|
+
* - the publication tool: one `visual-published-v1` receipt block.
|
|
177
|
+
*
|
|
178
|
+
* Suffix entries are validated as a SEQUENCE, not independently: a reference
|
|
179
|
+
* after the fact, a second reference, a second fact, or a reference without a
|
|
180
|
+
* fact is not something the official serializer can emit, so those blocks stay
|
|
181
|
+
* human text.
|
|
182
|
+
* @param toolName - the durable `tool/call` name.
|
|
183
|
+
* @param texts - the result's text blocks, in order.
|
|
184
|
+
* @returns how many TRAILING blocks are official machine blocks (0 when none).
|
|
185
|
+
*/
|
|
186
|
+
function officialMachineSuffixLength(toolName, texts) {
|
|
187
|
+
const last = texts[texts.length - 1];
|
|
188
|
+
if (last === void 0) return 0;
|
|
189
|
+
if (toolName === "present_visual") {
|
|
190
|
+
if (parseOfficialReceiptBlock(last) === void 0) return 0;
|
|
191
|
+
const before = texts[texts.length - 2];
|
|
192
|
+
if (before !== void 0 && parseOfficialReceiptBlock(before) !== void 0) return 0;
|
|
193
|
+
return 1;
|
|
194
|
+
}
|
|
195
|
+
const expectedType = toolName === "dsh_pi_tui_chart" ? "chart" : toolName === "dsh_pi_tui_svg" ? "svg" : void 0;
|
|
196
|
+
if (expectedType === void 0) return 0;
|
|
197
|
+
if (parseOfficialFactBlock(last)?.type === expectedType) {
|
|
198
|
+
const before = texts[texts.length - 2];
|
|
199
|
+
if (before !== void 0 && parseOfficialReferenceBlock(before) !== void 0) {
|
|
200
|
+
const beforeThat = texts[texts.length - 3];
|
|
201
|
+
if (beforeThat !== void 0 && parseOfficialReferenceBlock(beforeThat) !== void 0) return 0;
|
|
202
|
+
if (beforeThat !== void 0 && parseOfficialFactBlock(beforeThat) !== void 0) return 0;
|
|
203
|
+
return 2;
|
|
204
|
+
}
|
|
205
|
+
if (before !== void 0 && parseOfficialFactBlock(before) !== void 0) return 0;
|
|
206
|
+
return 1;
|
|
207
|
+
}
|
|
208
|
+
return 0;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* The human-readable projection of one result.
|
|
212
|
+
*
|
|
213
|
+
* Only the three official tools lose their official TAIL machine blocks, and
|
|
214
|
+
* only blocks that pass the exact grammar above. Block POSITION plus the
|
|
215
|
+
* controlled tool name plus that grammar decide identity — never a global
|
|
216
|
+
* string replace — so another tool keeps its full text, and an official tool's
|
|
217
|
+
* ordinary prose that resembles a machine line survives too.
|
|
218
|
+
* @param input - the tool name, the final result blocks (when the row has them)
|
|
219
|
+
* or its flat text.
|
|
220
|
+
* @returns the human blocks and their joined text.
|
|
221
|
+
*/
|
|
222
|
+
function humanFacingVisualResult(input) {
|
|
223
|
+
const { toolName, blocks, text } = input;
|
|
224
|
+
if (!isVisualToolName(toolName)) return {
|
|
225
|
+
blocks: blocks === void 0 ? [{
|
|
226
|
+
type: "text",
|
|
227
|
+
text
|
|
228
|
+
}] : [...blocks],
|
|
229
|
+
text
|
|
230
|
+
};
|
|
231
|
+
if (blocks === void 0) {
|
|
232
|
+
const lines = text.split("\n");
|
|
233
|
+
const trimmed = officialMachineSuffixLength(toolName, lines);
|
|
234
|
+
const human = lines.slice(0, lines.length - trimmed).join("\n");
|
|
235
|
+
return {
|
|
236
|
+
blocks: human === "" ? [] : [{
|
|
237
|
+
type: "text",
|
|
238
|
+
text: human
|
|
239
|
+
}],
|
|
240
|
+
text: human
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
const texts = [];
|
|
244
|
+
for (const block of blocks) if (block.type === "text") texts.push(block.text);
|
|
245
|
+
let remaining = officialMachineSuffixLength(toolName, texts);
|
|
246
|
+
let end = blocks.length;
|
|
247
|
+
while (remaining > 0 && end > 0) {
|
|
248
|
+
const block = blocks[end - 1];
|
|
249
|
+
if (block === void 0) break;
|
|
250
|
+
end -= 1;
|
|
251
|
+
if (block.type === "text") remaining -= 1;
|
|
252
|
+
else {
|
|
253
|
+
end = blocks.length;
|
|
254
|
+
break;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const human = blocks.slice(0, end);
|
|
258
|
+
const humanText = human.filter((block) => block.type === "text").map((block) => block.text).join("\n");
|
|
259
|
+
return {
|
|
260
|
+
blocks: [...human],
|
|
261
|
+
text: humanText
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
//#endregion
|
|
265
|
+
//#region src/domain/visual/constants.ts
|
|
266
|
+
/**
|
|
267
|
+
* Shared vocabulary for the two PR-D visual facts.
|
|
268
|
+
*
|
|
269
|
+
* PR-D's revised data contract (2026-10-23 Owner decision) deliberately does
|
|
270
|
+
* NOT use DSH `output.presentationMeta`: a content-only `tools/post-execute`
|
|
271
|
+
* replacement keeps the original durable meta, and pinned DSH has no supported
|
|
272
|
+
* seam to clear it. The FINAL durable `tool/result` content is therefore the
|
|
273
|
+
* only admission source for a chart or an SVG drawing.
|
|
274
|
+
*
|
|
275
|
+
* A visual fact rides in its own TEXT content block with this versioned prefix;
|
|
276
|
+
* the human-readable text stays a separate content block. Both renderers parse
|
|
277
|
+
* the SAME fact, and a policy replacement that removes the machine line removes
|
|
278
|
+
* the drawing along with it.
|
|
279
|
+
* @module @xmoon76/dsh-pi-tui/domain/visual/constants
|
|
280
|
+
*/
|
|
281
|
+
/** Prefix of the versioned machine-readable visual fact line. */
|
|
282
|
+
const VISUAL_FACT_PREFIX = "visual-v1:";
|
|
283
|
+
/** Whole chart input budget, separate from the per-field limits. */
|
|
284
|
+
const CHART_MAX_INPUT_BYTES = 16384;
|
|
285
|
+
/** SVG product limits (v1). The client's own native-SVG gate is ~256 KiB. */
|
|
286
|
+
const SVG_MAX_SOURCE_BYTES = 131072;
|
|
287
|
+
/** The SVG raster budget (v1; deployment policy, not a safety proof). */
|
|
288
|
+
const SVG_MAX_RASTER_SIDE = 2048;
|
|
289
|
+
const SVG_MAX_RASTER_PIXELS = 4e6;
|
|
290
|
+
const SVG_MAX_PNG_BYTES = 4194304;
|
|
291
|
+
/** The maximum time one isolated raster child may run. */
|
|
292
|
+
const SVG_RASTER_TIMEOUT_MS = 3e3;
|
|
293
|
+
//#endregion
|
|
294
|
+
//#region src/domain/visual/svg-admission.ts
|
|
295
|
+
/**
|
|
296
|
+
* The bounded, value-level SVG admission gate (PR-D D3).
|
|
297
|
+
*
|
|
298
|
+
* The gate is a strict whitelist over a mature streaming XML parser (`saxes`),
|
|
299
|
+
* not a regex over SVG text. It ADMITS or REJECTS the source verbatim: the two
|
|
300
|
+
* renderers must see the SAME document, so nothing is rewritten here.
|
|
301
|
+
*
|
|
302
|
+
* Scope: static, self-contained figures. Scripts, foreignObject, CSS, animation,
|
|
303
|
+
* external references, entities/DOCTYPE and out-of-budget geometry are refused.
|
|
304
|
+
* This is the pre-filter in front of the native rasterizer, not a replacement
|
|
305
|
+
* for process isolation.
|
|
306
|
+
* @module @xmoon76/dsh-pi-tui/domain/visual/svg-admission
|
|
307
|
+
*/
|
|
308
|
+
const SVG_NS = "http://www.w3.org/2000/svg";
|
|
309
|
+
const XLINK_NS = "http://www.w3.org/1999/xlink";
|
|
310
|
+
const XMLNS_NS = "http://www.w3.org/2000/xmlns/";
|
|
311
|
+
const LIMITS = {
|
|
312
|
+
maxNodes: 5e3,
|
|
313
|
+
maxDepth: 64,
|
|
314
|
+
maxAttrs: 64,
|
|
315
|
+
maxCoord: 1e5,
|
|
316
|
+
maxDim: SVG_MAX_RASTER_SIDE,
|
|
317
|
+
maxViewBoxArea: SVG_MAX_RASTER_PIXELS,
|
|
318
|
+
maxPathCommands: 512,
|
|
319
|
+
maxPathLength: 8192
|
|
320
|
+
};
|
|
321
|
+
const ALLOWED_ELEMENTS = /* @__PURE__ */ new Set([
|
|
322
|
+
"svg",
|
|
323
|
+
"g",
|
|
324
|
+
"defs",
|
|
325
|
+
"title",
|
|
326
|
+
"desc",
|
|
327
|
+
"linearGradient",
|
|
328
|
+
"radialGradient",
|
|
329
|
+
"stop",
|
|
330
|
+
"path",
|
|
331
|
+
"circle",
|
|
332
|
+
"ellipse",
|
|
333
|
+
"line",
|
|
334
|
+
"polyline",
|
|
335
|
+
"polygon",
|
|
336
|
+
"rect",
|
|
337
|
+
"mask",
|
|
338
|
+
"clipPath",
|
|
339
|
+
"text",
|
|
340
|
+
"tspan",
|
|
341
|
+
"symbol",
|
|
342
|
+
"use"
|
|
343
|
+
]);
|
|
344
|
+
const ALLOWED_ATTRIBUTES = /* @__PURE__ */ new Set([
|
|
345
|
+
"viewBox",
|
|
346
|
+
"width",
|
|
347
|
+
"height",
|
|
348
|
+
"x",
|
|
349
|
+
"y",
|
|
350
|
+
"x1",
|
|
351
|
+
"y1",
|
|
352
|
+
"x2",
|
|
353
|
+
"y2",
|
|
354
|
+
"cx",
|
|
355
|
+
"cy",
|
|
356
|
+
"r",
|
|
357
|
+
"rx",
|
|
358
|
+
"ry",
|
|
359
|
+
"d",
|
|
360
|
+
"fill",
|
|
361
|
+
"stroke",
|
|
362
|
+
"stroke-width",
|
|
363
|
+
"stroke-linecap",
|
|
364
|
+
"stroke-linejoin",
|
|
365
|
+
"opacity",
|
|
366
|
+
"fill-opacity",
|
|
367
|
+
"stroke-opacity",
|
|
368
|
+
"transform",
|
|
369
|
+
"id",
|
|
370
|
+
"class",
|
|
371
|
+
"offset",
|
|
372
|
+
"stop-color",
|
|
373
|
+
"stop-opacity",
|
|
374
|
+
"gradientUnits",
|
|
375
|
+
"mask",
|
|
376
|
+
"clip-path",
|
|
377
|
+
"fill-rule",
|
|
378
|
+
"font-family",
|
|
379
|
+
"font-size",
|
|
380
|
+
"font-weight",
|
|
381
|
+
"text-anchor",
|
|
382
|
+
"dominant-baseline",
|
|
383
|
+
"dx",
|
|
384
|
+
"dy",
|
|
385
|
+
"letter-spacing"
|
|
386
|
+
]);
|
|
387
|
+
const URI_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src"]);
|
|
388
|
+
const PAINT_ATTRIBUTES = /* @__PURE__ */ new Set([
|
|
389
|
+
"fill",
|
|
390
|
+
"stroke",
|
|
391
|
+
"stop-color",
|
|
392
|
+
"clip-path",
|
|
393
|
+
"mask"
|
|
394
|
+
]);
|
|
395
|
+
const NUMBER_OR_LENGTH_ATTRIBUTES = /* @__PURE__ */ new Set([
|
|
396
|
+
"x",
|
|
397
|
+
"y",
|
|
398
|
+
"cx",
|
|
399
|
+
"cy",
|
|
400
|
+
"r",
|
|
401
|
+
"rx",
|
|
402
|
+
"ry",
|
|
403
|
+
"x1",
|
|
404
|
+
"y1",
|
|
405
|
+
"x2",
|
|
406
|
+
"y2",
|
|
407
|
+
"dx",
|
|
408
|
+
"dy",
|
|
409
|
+
"stroke-width",
|
|
410
|
+
"stop-opacity",
|
|
411
|
+
"opacity",
|
|
412
|
+
"fill-opacity",
|
|
413
|
+
"stroke-opacity",
|
|
414
|
+
"font-size",
|
|
415
|
+
"letter-spacing"
|
|
416
|
+
]);
|
|
417
|
+
const SHORT_NAME_ATTRIBUTES = /* @__PURE__ */ new Set([
|
|
418
|
+
"fill-rule",
|
|
419
|
+
"stroke-linecap",
|
|
420
|
+
"stroke-linejoin",
|
|
421
|
+
"text-anchor",
|
|
422
|
+
"dominant-baseline",
|
|
423
|
+
"font-weight",
|
|
424
|
+
"gradientUnits",
|
|
425
|
+
"font-family",
|
|
426
|
+
"class",
|
|
427
|
+
"id"
|
|
428
|
+
]);
|
|
429
|
+
const LENGTH_PATTERN = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)(px|pt|pc|mm|cm|in|em|ex|ch|rem|vw|vh|%)?$/;
|
|
430
|
+
const NUMBER_PATTERN = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
|
|
431
|
+
const COLOR_PATTERN = /^(#[0-9a-fA-F]{3,8}|[a-zA-Z]+|rgb\([^)]*\)|rgba\([^)]*\)|hsl\([^)]*\))$/;
|
|
432
|
+
const TRANSFORM_PATTERN = /^[a-zA-Z]+\([^)]*\)(?:\s*,?\s*[a-zA-Z]+\([^)]*\))*$/;
|
|
433
|
+
const PAINT_URL_PATTERN = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"]*))\s*\)/g;
|
|
434
|
+
const NUMBER_TOKEN_PATTERN = /[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g;
|
|
435
|
+
const UNIT_PX = {
|
|
436
|
+
px: 1,
|
|
437
|
+
pt: 4 / 3,
|
|
438
|
+
pc: 16,
|
|
439
|
+
in: 96,
|
|
440
|
+
mm: 96 / 25.4,
|
|
441
|
+
cm: 960 / 25.4
|
|
442
|
+
};
|
|
443
|
+
const RELATIVE_UNITS = /* @__PURE__ */ new Set([
|
|
444
|
+
"em",
|
|
445
|
+
"ex",
|
|
446
|
+
"ch",
|
|
447
|
+
"rem",
|
|
448
|
+
"vw",
|
|
449
|
+
"vh",
|
|
450
|
+
"%"
|
|
451
|
+
]);
|
|
452
|
+
/** Internal rejection; converted to a verdict at the boundary. */
|
|
453
|
+
var SvgReject = class extends Error {};
|
|
454
|
+
function reject(reason) {
|
|
455
|
+
throw new SvgReject(reason);
|
|
456
|
+
}
|
|
457
|
+
function checkNumber(value, what) {
|
|
458
|
+
const text = value.trim();
|
|
459
|
+
if (text === "" || !NUMBER_PATTERN.test(text)) reject(`${what}: ${clip(value)} is not a finite number`);
|
|
460
|
+
const number = Number(text);
|
|
461
|
+
if (!Number.isFinite(number)) reject(`${what}: ${clip(value)} is not finite`);
|
|
462
|
+
if (Math.abs(number) > LIMITS.maxCoord) reject(`${what}: ${number} exceeds ${LIMITS.maxCoord}`);
|
|
463
|
+
return number;
|
|
464
|
+
}
|
|
465
|
+
function checkLength(value, what, limit) {
|
|
466
|
+
const text = value.trim();
|
|
467
|
+
const match = LENGTH_PATTERN.exec(text);
|
|
468
|
+
if (match === null) reject(`${what}: ${clip(value)} is not a bounded length`);
|
|
469
|
+
const raw = Number(match[1]);
|
|
470
|
+
if (!Number.isFinite(raw)) reject(`${what}: ${clip(value)} is not finite`);
|
|
471
|
+
if (raw < 0) reject(`${what}: a negative length ${clip(value)}`);
|
|
472
|
+
const unit = match[2];
|
|
473
|
+
if (unit !== void 0 && RELATIVE_UNITS.has(unit)) reject(`${what}: relative units (${clip(unit)}) are outside the bounded static subset`);
|
|
474
|
+
const px = raw * (unit === void 0 ? 1 : UNIT_PX[unit]);
|
|
475
|
+
if (px > limit) reject(`${what}: ${clip(value)} is ${Math.round(px)}px > ${limit}px`);
|
|
476
|
+
return px;
|
|
477
|
+
}
|
|
478
|
+
function checkPaint(value, what) {
|
|
479
|
+
const text = value.trim();
|
|
480
|
+
if (text === "" || text === "none" || text === "inherit") return;
|
|
481
|
+
const lower = text.toLowerCase();
|
|
482
|
+
if (lower.includes("var(") || lower.includes("currentcolor")) reject(`${what}: theme-dependent paint is outside the v1 fixed-colour subset`);
|
|
483
|
+
for (const match of text.matchAll(PAINT_URL_PATTERN)) {
|
|
484
|
+
const target = (match[1] ?? match[2] ?? match[3] ?? "").trim();
|
|
485
|
+
if (!target.startsWith("#")) reject(`${what}: url(${clip(target)}) is not a local fragment`);
|
|
486
|
+
}
|
|
487
|
+
const residue = text.replaceAll(PAINT_URL_PATTERN, "").trim();
|
|
488
|
+
for (const token of residue.split(/\s+/u)) {
|
|
489
|
+
if (token === "" || token === "none" || token === "inherit") continue;
|
|
490
|
+
if (!COLOR_PATTERN.test(token)) reject(`${what}: ${clip(token)} is not a colour`);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
function checkTransform(value, what) {
|
|
494
|
+
const text = value.trim();
|
|
495
|
+
if (!TRANSFORM_PATTERN.test(text)) reject(`${what}: ${clip(value)} is not a bounded transform list`);
|
|
496
|
+
for (const token of text.match(NUMBER_TOKEN_PATTERN) ?? []) if (Math.abs(Number(token)) > LIMITS.maxCoord) reject(`${what}: a coordinate ${clip(token)} exceeds ${LIMITS.maxCoord}`);
|
|
497
|
+
}
|
|
498
|
+
function checkPath(value, what) {
|
|
499
|
+
const text = value.trim();
|
|
500
|
+
if (Buffer.byteLength(text, "utf8") > LIMITS.maxPathLength) reject(`${what}: path data exceeds ${LIMITS.maxPathLength} bytes`);
|
|
501
|
+
let commands = 0;
|
|
502
|
+
for (const char of text) if (/[a-zA-Z]/u.test(char)) commands += 1;
|
|
503
|
+
if (commands > LIMITS.maxPathCommands) reject(`${what}: ${commands} commands > ${LIMITS.maxPathCommands}`);
|
|
504
|
+
for (const token of text.match(NUMBER_TOKEN_PATTERN) ?? []) {
|
|
505
|
+
const number = Number(token);
|
|
506
|
+
if (!Number.isFinite(number) || Math.abs(number) > LIMITS.maxCoord) reject(`${what}: a coordinate ${clip(token)} exceeds ${LIMITS.maxCoord}`);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
function clip(text) {
|
|
510
|
+
return text.length > 48 ? `${text.slice(0, 48)}…` : text;
|
|
511
|
+
}
|
|
512
|
+
function attributeProblem(attribute) {
|
|
513
|
+
const { name, local, uri, value } = attribute;
|
|
514
|
+
const what = `attribute ${name}`;
|
|
515
|
+
if (value.length > 4096) reject(`${what}: value exceeds 4096 characters`);
|
|
516
|
+
if (uri === XMLNS_NS) {
|
|
517
|
+
if (value !== SVG_NS && value !== XLINK_NS) reject(`namespace ${name}=${clip(value)} is not the SVG or XLink namespace`);
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
if (uri === XLINK_NS) {
|
|
521
|
+
if (local !== "href") reject(`${what} is not in the safe subset`);
|
|
522
|
+
if (!value.startsWith("#")) reject(`${what}=${clip(value)} is not a local fragment`);
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
if (uri !== "") reject(`${what} uses an unsupported namespace`);
|
|
526
|
+
if (URI_ATTRIBUTES.has(local)) {
|
|
527
|
+
if (!value.startsWith("#")) reject(`${what}=${clip(value)} is not a local fragment`);
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
if (!ALLOWED_ATTRIBUTES.has(local) && !local.startsWith("data-")) reject(`${what} is not in the safe subset`);
|
|
531
|
+
if (local === "width" || local === "height") {
|
|
532
|
+
checkLength(value, what, LIMITS.maxDim);
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
if (local === "offset") {
|
|
536
|
+
const text = value.trim();
|
|
537
|
+
if (text.endsWith("%")) {
|
|
538
|
+
const percent = Number(text.slice(0, -1));
|
|
539
|
+
if (!Number.isFinite(percent) || percent < 0 || percent > 100) reject(`${what}: a stop offset must be a 0–100% fraction`);
|
|
540
|
+
} else {
|
|
541
|
+
const fraction = checkNumber(text, what);
|
|
542
|
+
if (fraction < 0 || fraction > 1) reject(`${what}: a stop offset must be between 0 and 1`);
|
|
543
|
+
}
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
if (local === "d") {
|
|
547
|
+
checkPath(value, what);
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
if (local === "transform") {
|
|
551
|
+
checkTransform(value, what);
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
if (PAINT_ATTRIBUTES.has(local)) {
|
|
555
|
+
checkPaint(value, what);
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
if (NUMBER_OR_LENGTH_ATTRIBUTES.has(local)) {
|
|
559
|
+
try {
|
|
560
|
+
checkNumber(value, what);
|
|
561
|
+
} catch (error) {
|
|
562
|
+
if (!(error instanceof SvgReject)) throw error;
|
|
563
|
+
checkLength(value, what, LIMITS.maxDim);
|
|
564
|
+
}
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
if (SHORT_NAME_ATTRIBUTES.has(local)) {
|
|
568
|
+
if (value.length > 128) reject(`${what} exceeds 128 characters`);
|
|
569
|
+
if (value.includes("url(")) reject(`${what} carries a url()`);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
function rootGeometryProblem(state, attributes) {
|
|
573
|
+
const viewBox = attributes.get("viewBox");
|
|
574
|
+
if (viewBox !== void 0) {
|
|
575
|
+
const parts = viewBox.value.replaceAll(",", " ").trim().split(/\s+/u);
|
|
576
|
+
if (parts.length !== 4) reject("viewBox needs 4 numbers");
|
|
577
|
+
const numbers = parts.map((part) => checkNumber(part, "viewBox component"));
|
|
578
|
+
const width = numbers[2];
|
|
579
|
+
const height = numbers[3];
|
|
580
|
+
if (width <= 0 || height <= 0) reject("viewBox width and height must be positive");
|
|
581
|
+
if (width > LIMITS.maxDim || height > LIMITS.maxDim) reject(`viewBox ${width}×${height} exceeds ${LIMITS.maxDim}px per side`);
|
|
582
|
+
if (width * height > LIMITS.maxViewBoxArea) reject(`viewBox area ${Math.round(width * height)} > ${LIMITS.maxViewBoxArea}`);
|
|
583
|
+
state.viewBoxWidth = width;
|
|
584
|
+
state.viewBoxHeight = height;
|
|
585
|
+
}
|
|
586
|
+
const width = attributes.get("width");
|
|
587
|
+
const height = attributes.get("height");
|
|
588
|
+
if (width !== void 0) state.rootWidth = checkLength(width.value, "attribute width", LIMITS.maxDim);
|
|
589
|
+
if (height !== void 0) state.rootHeight = checkLength(height.value, "attribute height", LIMITS.maxDim);
|
|
590
|
+
}
|
|
591
|
+
function openTag(state, node) {
|
|
592
|
+
state.nodes += 1;
|
|
593
|
+
state.depth += 1;
|
|
594
|
+
state.maxDepth = Math.max(state.maxDepth, state.depth);
|
|
595
|
+
if (state.nodes > LIMITS.maxNodes) reject(`nodes > ${LIMITS.maxNodes}`);
|
|
596
|
+
if (state.depth > LIMITS.maxDepth) reject(`depth > ${LIMITS.maxDepth}`);
|
|
597
|
+
if (state.depth === 1) {
|
|
598
|
+
if (node.local !== "svg") reject(`the root is <${clip(node.local)}>, not <svg>`);
|
|
599
|
+
if (node.uri !== SVG_NS) reject("the root is not in the SVG namespace");
|
|
600
|
+
state.rootSeen = true;
|
|
601
|
+
} else if (node.uri !== SVG_NS) reject(`element <${clip(node.local)}> is not in the SVG namespace`);
|
|
602
|
+
if (!ALLOWED_ELEMENTS.has(node.local)) reject(`element <${clip(node.local)}> is not in the safe subset`);
|
|
603
|
+
const attributes = Object.values(node.attributes);
|
|
604
|
+
if (attributes.length > LIMITS.maxAttrs) reject(`attribute count > ${LIMITS.maxAttrs}`);
|
|
605
|
+
for (const attribute of attributes) attributeProblem(attribute);
|
|
606
|
+
if (state.depth > 1 && attributes.some((attribute) => attribute.local === "viewBox")) reject("viewBox is allowed only on the root");
|
|
607
|
+
if (state.depth === 1) {
|
|
608
|
+
if (attributes.every((attribute) => attribute.local !== "xmlns" && attribute.name !== "xmlns")) reject("the root has no xmlns");
|
|
609
|
+
rootGeometryProblem(state, new Map(attributes.map((attribute) => [attribute.local, attribute])));
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
function closeTag(state) {
|
|
613
|
+
state.depth -= 1;
|
|
614
|
+
}
|
|
615
|
+
function viewportGeometry(state) {
|
|
616
|
+
return {
|
|
617
|
+
width: state.rootWidth ?? state.viewBoxWidth ?? 300,
|
|
618
|
+
height: state.rootHeight ?? state.viewBoxHeight ?? 150
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
function finalGeometry(state) {
|
|
622
|
+
if (state.viewBoxWidth !== void 0 && state.viewBoxHeight !== void 0) return {
|
|
623
|
+
width: state.viewBoxWidth,
|
|
624
|
+
height: state.viewBoxHeight
|
|
625
|
+
};
|
|
626
|
+
if (state.rootWidth !== void 0 && state.rootHeight !== void 0) return {
|
|
627
|
+
width: state.rootWidth,
|
|
628
|
+
height: state.rootHeight
|
|
629
|
+
};
|
|
630
|
+
return reject("the SVG needs a bounded viewBox or explicit width/height");
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* Run the bounded admission gate over one SVG source.
|
|
634
|
+
* @param source - the complete standalone SVG text.
|
|
635
|
+
* @returns the verdict; a rejection carries a model/user-readable reason.
|
|
636
|
+
*/
|
|
637
|
+
function admitSvg(source) {
|
|
638
|
+
const bytes = Buffer.byteLength(source, "utf8");
|
|
639
|
+
if (bytes > 131072) return {
|
|
640
|
+
ok: false,
|
|
641
|
+
reason: `SVG source ${bytes} bytes > ${SVG_MAX_SOURCE_BYTES} bytes`
|
|
642
|
+
};
|
|
643
|
+
const parser = new SaxesParser({ xmlns: true });
|
|
644
|
+
const state = {
|
|
645
|
+
parser,
|
|
646
|
+
nodes: 0,
|
|
647
|
+
depth: 0,
|
|
648
|
+
maxDepth: 0,
|
|
649
|
+
rootSeen: false
|
|
650
|
+
};
|
|
651
|
+
try {
|
|
652
|
+
parser.on("error", (error) => reject(`XML: ${error.message}`));
|
|
653
|
+
parser.on("doctype", () => reject("a DOCTYPE declaration is refused"));
|
|
654
|
+
parser.on("processinginstruction", () => reject("a processing instruction is outside the safe subset"));
|
|
655
|
+
parser.on("opentag", (node) => openTag(state, node));
|
|
656
|
+
parser.on("closetag", () => closeTag(state));
|
|
657
|
+
parser.write(source);
|
|
658
|
+
parser.close();
|
|
659
|
+
const dimensions = finalGeometry(state);
|
|
660
|
+
if (dimensions.width * dimensions.height > 4e6) reject(`raster pixels ${Math.round(dimensions.width * dimensions.height)} > ${SVG_MAX_RASTER_PIXELS}`);
|
|
661
|
+
const viewport = viewportGeometry(state);
|
|
662
|
+
if (!(viewport.width > 0) || !(viewport.height > 0)) reject("the SVG viewport must have a positive width and height");
|
|
663
|
+
return {
|
|
664
|
+
ok: true,
|
|
665
|
+
bytes,
|
|
666
|
+
width: dimensions.width,
|
|
667
|
+
height: dimensions.height,
|
|
668
|
+
viewportWidth: viewport.width,
|
|
669
|
+
viewportHeight: viewport.height
|
|
670
|
+
};
|
|
671
|
+
} catch (error) {
|
|
672
|
+
if (error instanceof SvgReject) return {
|
|
673
|
+
ok: false,
|
|
674
|
+
reason: error.message
|
|
675
|
+
};
|
|
676
|
+
return {
|
|
677
|
+
ok: false,
|
|
678
|
+
reason: `XML: ${error instanceof Error ? error.message : String(error)}`
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
//#endregion
|
|
683
|
+
//#region src/domain/visual/chart.ts
|
|
684
|
+
const CHART_ARGS_KEYS = [
|
|
685
|
+
"kind",
|
|
686
|
+
"title",
|
|
687
|
+
"unit",
|
|
688
|
+
"series"
|
|
689
|
+
];
|
|
690
|
+
const CHART_FACT_KEYS = [
|
|
691
|
+
"version",
|
|
692
|
+
"type",
|
|
693
|
+
"kind",
|
|
694
|
+
"title",
|
|
695
|
+
"unit",
|
|
696
|
+
"series"
|
|
697
|
+
];
|
|
698
|
+
const CHART_POINT_KEYS = ["label", "value"];
|
|
699
|
+
const CHART_KINDS = ["bars", "spark"];
|
|
700
|
+
function isRecord$1(value) {
|
|
701
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
702
|
+
}
|
|
703
|
+
function hasOnlyKeys$1(value, keys) {
|
|
704
|
+
const allowed = new Set(keys);
|
|
705
|
+
return Object.keys(value).every((key) => allowed.has(key));
|
|
706
|
+
}
|
|
707
|
+
/** Count Unicode code points, not UTF-16 units. */
|
|
708
|
+
function codePointLength(text) {
|
|
709
|
+
let count = 0;
|
|
710
|
+
for (const _ of text) count += 1;
|
|
711
|
+
return count;
|
|
712
|
+
}
|
|
713
|
+
/** Display width in terminal cells (East Asian wide/fullwidth count double). */
|
|
714
|
+
function displayWidth(text) {
|
|
715
|
+
let width = 0;
|
|
716
|
+
for (const char of text) width += eastAsianWidth(char.codePointAt(0) ?? 0);
|
|
717
|
+
return width;
|
|
718
|
+
}
|
|
719
|
+
/** Deterministic, locale-independent number text. */
|
|
720
|
+
function formatChartNumber(value) {
|
|
721
|
+
return Object.is(value, -0) ? "0" : String(value);
|
|
722
|
+
}
|
|
723
|
+
/** Validate one chart point object and narrow it. */
|
|
724
|
+
function parsePoint(value) {
|
|
725
|
+
if (!isRecord$1(value) || !hasOnlyKeys$1(value, CHART_POINT_KEYS)) return void 0;
|
|
726
|
+
const { label, value: pointValue } = value;
|
|
727
|
+
if (typeof label !== "string" || label === "" || codePointLength(label) > 48) return void 0;
|
|
728
|
+
if (typeof pointValue !== "number" || !Number.isFinite(pointValue)) return void 0;
|
|
729
|
+
return {
|
|
730
|
+
label,
|
|
731
|
+
value: pointValue
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
/** Validate the kind/title/unit/series core shared by args and the fact. */
|
|
735
|
+
function chartCoreProblem(kind, title, unit, series) {
|
|
736
|
+
if (typeof kind !== "string" || !CHART_KINDS.includes(kind)) return "kind must be \"bars\" or \"spark\"";
|
|
737
|
+
if (typeof title !== "string" || title.trim() === "" || codePointLength(title) > 100) return `title must be a non-empty string of at most 100 Unicode code points`;
|
|
738
|
+
if (unit !== void 0 && (typeof unit !== "string" || unit === "" || codePointLength(unit) > 32)) return `unit must be a non-empty string of at most 32 Unicode code points`;
|
|
739
|
+
if (!Array.isArray(series) || series.length < 2 || series.length > 12) return `series must contain between 2 and 12 points`;
|
|
740
|
+
for (const [index, point] of series.entries()) if (parsePoint(point) === void 0) return `series[${index}] must be a finite number with a non-empty label of at most 48 Unicode code points`;
|
|
741
|
+
}
|
|
742
|
+
/** Validate model-supplied chart arguments, including the whole-input budget. */
|
|
743
|
+
function chartArgsProblem(args) {
|
|
744
|
+
if (!isRecord$1(args) || !hasOnlyKeys$1(args, CHART_ARGS_KEYS)) return "arguments must contain only kind, title, unit and series";
|
|
745
|
+
const problem = chartCoreProblem(args.kind, args.title, args.unit, args.series);
|
|
746
|
+
if (problem !== void 0) return problem;
|
|
747
|
+
if (Buffer.byteLength(JSON.stringify(args), "utf8") > 16384) return `chart input exceeds ${CHART_MAX_INPUT_BYTES} bytes`;
|
|
748
|
+
}
|
|
749
|
+
/** Build the canonical fact from already-validated arguments. */
|
|
750
|
+
function chartFactFromArgs(args) {
|
|
751
|
+
return {
|
|
752
|
+
version: 1,
|
|
753
|
+
type: "chart",
|
|
754
|
+
kind: args.kind,
|
|
755
|
+
title: args.title,
|
|
756
|
+
...args.unit === void 0 ? {} : { unit: args.unit },
|
|
757
|
+
series: args.series.map((point) => ({
|
|
758
|
+
label: point.label,
|
|
759
|
+
value: point.value
|
|
760
|
+
}))
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
/** Strict parse of one durable machine-line fact. */
|
|
764
|
+
function parseChartFact(value) {
|
|
765
|
+
if (!isRecord$1(value) || !hasOnlyKeys$1(value, CHART_FACT_KEYS)) return void 0;
|
|
766
|
+
if (value.version !== 1 || value.type !== "chart") return void 0;
|
|
767
|
+
if (chartCoreProblem(value.kind, value.title, value.unit, value.series) !== void 0) return void 0;
|
|
768
|
+
const series = [];
|
|
769
|
+
for (const raw of value.series) {
|
|
770
|
+
const point = parsePoint(raw);
|
|
771
|
+
if (point === void 0) return void 0;
|
|
772
|
+
series.push(point);
|
|
773
|
+
}
|
|
774
|
+
return {
|
|
775
|
+
version: 1,
|
|
776
|
+
type: "chart",
|
|
777
|
+
kind: value.kind,
|
|
778
|
+
title: value.title,
|
|
779
|
+
...value.unit === void 0 ? {} : { unit: value.unit },
|
|
780
|
+
series
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
/** The unit suffix used after one value (never parsed back as a number). */
|
|
784
|
+
function valueText(fact, point) {
|
|
785
|
+
const number = formatChartNumber(point.value);
|
|
786
|
+
return fact.unit === void 0 ? number : `${number} ${fact.unit}`;
|
|
787
|
+
}
|
|
788
|
+
/** The per-point value rows shared by every renderer (no title duplication). */
|
|
789
|
+
function chartValueRows(fact) {
|
|
790
|
+
return [...fact.series.map((point) => `${point.label} ${valueText(fact, point)}`), `${fact.series.length} supplied value${fact.series.length === 1 ? "" : "s"}`];
|
|
791
|
+
}
|
|
792
|
+
/** The final fact's display title (title + unit), the committed label. */
|
|
793
|
+
function chartDisplayTitle(fact) {
|
|
794
|
+
return fact.unit === void 0 ? fact.title : `${fact.title} (${fact.unit})`;
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* The durable, self-contained human text. It repeats the title because this
|
|
798
|
+
* text is also what search, copy and Markdown export read without a card
|
|
799
|
+
* header; the graphical card bodies use {@link chartValueRows} instead.
|
|
800
|
+
*/
|
|
801
|
+
function chartHumanText(fact) {
|
|
802
|
+
return [chartDisplayTitle(fact), ...chartValueRows(fact)].join("\n");
|
|
803
|
+
}
|
|
804
|
+
/** The durable content blocks: readable text plus the versioned fact line. */
|
|
805
|
+
function chartContentBlocks(fact) {
|
|
806
|
+
return [{
|
|
807
|
+
type: "text",
|
|
808
|
+
text: chartHumanText(fact)
|
|
809
|
+
}, {
|
|
810
|
+
type: "text",
|
|
811
|
+
text: `${VISUAL_FACT_PREFIX}${JSON.stringify(fact)}`
|
|
812
|
+
}];
|
|
813
|
+
}
|
|
814
|
+
/** The TSP native chart projection (one summary, the same ordered series). */
|
|
815
|
+
function chartProjection(fact) {
|
|
816
|
+
return {
|
|
817
|
+
kind: fact.kind,
|
|
818
|
+
summary: chartDisplayTitle(fact),
|
|
819
|
+
series: fact.series.map((point) => ({
|
|
820
|
+
label: point.label,
|
|
821
|
+
value: point.value
|
|
822
|
+
}))
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
const SPARK_LEVELS = [
|
|
826
|
+
".",
|
|
827
|
+
":",
|
|
828
|
+
";",
|
|
829
|
+
"+",
|
|
830
|
+
"*",
|
|
831
|
+
"#",
|
|
832
|
+
"%",
|
|
833
|
+
"@"
|
|
834
|
+
];
|
|
835
|
+
/** One sparkline row scaled across the series' own minimum and maximum. */
|
|
836
|
+
function sparkline(values) {
|
|
837
|
+
if (values.length === 0) return "";
|
|
838
|
+
const min = Math.min(...values);
|
|
839
|
+
const max = Math.max(...values);
|
|
840
|
+
if (max === min) return "=".repeat(values.length);
|
|
841
|
+
return values.map((value) => {
|
|
842
|
+
const ratio = (value - min) / (max - min);
|
|
843
|
+
const index = Math.max(0, Math.min(SPARK_LEVELS.length - 1, Math.round(ratio * (SPARK_LEVELS.length - 1))));
|
|
844
|
+
return SPARK_LEVELS[index];
|
|
845
|
+
}).join("");
|
|
846
|
+
}
|
|
847
|
+
/** A bar for one value: magnitude only, with a leading minus sign for negatives. */
|
|
848
|
+
function bar(value, maxAbsolute, budget) {
|
|
849
|
+
if (budget <= 0 || maxAbsolute === 0) return "";
|
|
850
|
+
const length = Math.max(value === 0 ? 1 : 0, Math.round(Math.abs(value) / maxAbsolute * budget));
|
|
851
|
+
const glyphs = "#".repeat(Math.max(0, length));
|
|
852
|
+
return value < 0 ? `-${glyphs}` : glyphs;
|
|
853
|
+
}
|
|
854
|
+
function padEndByWidth(text, width) {
|
|
855
|
+
return `${text}${" ".repeat(Math.max(0, width - displayWidth(text)))}`;
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Width-safe decoration rows: ASCII bars (or a sparkline) are an enhancement,
|
|
859
|
+
* while every label and exact value always appears in the plain list fallback.
|
|
860
|
+
* @param fact - the canonical chart.
|
|
861
|
+
* @param width - the available cells (the component's render width).
|
|
862
|
+
* @param decorated - whether ASCII bars/sparkline decoration may be used.
|
|
863
|
+
*/
|
|
864
|
+
function chartTextRows(fact, width, decorated = true) {
|
|
865
|
+
const safeWidth = Math.max(1, Math.floor(width));
|
|
866
|
+
const values = fact.series.map((point) => valueText(fact, point));
|
|
867
|
+
const labelWidth = Math.max(...fact.series.map((point) => displayWidth(point.label)));
|
|
868
|
+
const valueWidth = Math.max(...values.map((text) => displayWidth(text)));
|
|
869
|
+
const rows = [];
|
|
870
|
+
if (decorated && fact.kind === "spark" && safeWidth >= fact.series.length) rows.push(sparkline(fact.series.map((point) => point.value)));
|
|
871
|
+
const budget = Math.min(24, safeWidth - labelWidth - valueWidth - 6);
|
|
872
|
+
const drawBars = decorated && fact.kind === "bars" && budget >= 2;
|
|
873
|
+
const maxAbsolute = Math.max(...fact.series.map((point) => Math.abs(point.value)));
|
|
874
|
+
fact.series.forEach((point, index) => {
|
|
875
|
+
const label = padEndByWidth(point.label, labelWidth);
|
|
876
|
+
const value = values[index];
|
|
877
|
+
rows.push(drawBars ? `${label} ${padEndByWidth(bar(point.value, maxAbsolute, budget), budget)} ${value}` : `${point.label} ${value}`);
|
|
878
|
+
});
|
|
879
|
+
rows.push(`${fact.series.length} supplied value${fact.series.length === 1 ? "" : "s"}`);
|
|
880
|
+
return rows;
|
|
881
|
+
}
|
|
882
|
+
//#endregion
|
|
883
|
+
//#region src/domain/visual/svg.ts
|
|
884
|
+
/**
|
|
885
|
+
* The canonical SVG fact, its digest credential, and the render-time
|
|
886
|
+
* authorization shared by the TSP and PiTui paths.
|
|
887
|
+
*
|
|
888
|
+
* The SVG SOURCE lives in the durable `tool/call.arguments` (the model wrote
|
|
889
|
+
* it); the tool result carries only a short credential: title, description,
|
|
890
|
+
* source digest and byte count. A renderer may draw the source only when the
|
|
891
|
+
* FINAL result content still carries a well-formed credential whose digest
|
|
892
|
+
* matches the call arguments AND the source passes the admission gate. A
|
|
893
|
+
* content-only policy replacement therefore removes the drawing; a value
|
|
894
|
+
* replacement that changes the digest degrades to text. This never restores a
|
|
895
|
+
* graphic from `meta` (the tool declares none).
|
|
896
|
+
* @module @xmoon76/dsh-pi-tui/domain/visual/svg
|
|
897
|
+
*/
|
|
898
|
+
const SVG_ARGS_KEYS = [
|
|
899
|
+
"title",
|
|
900
|
+
"description",
|
|
901
|
+
"svg"
|
|
902
|
+
];
|
|
903
|
+
const SVG_FACT_KEYS = [
|
|
904
|
+
"version",
|
|
905
|
+
"type",
|
|
906
|
+
"title",
|
|
907
|
+
"description",
|
|
908
|
+
"digest",
|
|
909
|
+
"bytes"
|
|
910
|
+
];
|
|
911
|
+
const DIGEST_PATTERN = /^[0-9a-f]{64}$/u;
|
|
912
|
+
function isRecord(value) {
|
|
913
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
914
|
+
}
|
|
915
|
+
function hasOnlyKeys(value, keys) {
|
|
916
|
+
const allowed = new Set(keys);
|
|
917
|
+
return Object.keys(value).every((key) => allowed.has(key));
|
|
918
|
+
}
|
|
919
|
+
/** Lowercase hex SHA-256 of one source string's UTF-8 bytes. */
|
|
920
|
+
function svgDigest(source) {
|
|
921
|
+
return createHash("sha256").update(Buffer.from(source, "utf8")).digest("hex");
|
|
922
|
+
}
|
|
923
|
+
/** Validate the shape and field budgets of SVG arguments (no admission). */
|
|
924
|
+
function svgArgsShapeProblem(args) {
|
|
925
|
+
if (!isRecord(args) || !hasOnlyKeys(args, SVG_ARGS_KEYS)) return "arguments must contain only title, description and svg";
|
|
926
|
+
const { title, description, svg } = args;
|
|
927
|
+
if (typeof title !== "string" || title.trim() === "" || codePointLength(title) > 100) return `title must be a non-empty string of at most 100 Unicode code points`;
|
|
928
|
+
if (typeof description !== "string" || description.trim() === "" || codePointLength(description) > 500) return `description must be a non-empty string of at most 500 Unicode code points`;
|
|
929
|
+
if (typeof svg !== "string" || svg.trim() === "") return "svg must be a non-empty standalone SVG document";
|
|
930
|
+
}
|
|
931
|
+
/** Validate SVG arguments including the admission gate (the tool boundary). */
|
|
932
|
+
function svgArgsProblem(args) {
|
|
933
|
+
const shape = svgArgsShapeProblem(args);
|
|
934
|
+
if (shape !== void 0) return shape;
|
|
935
|
+
const { svg } = args;
|
|
936
|
+
const admission = admitSvg(svg);
|
|
937
|
+
return admission.ok ? void 0 : `SVG rejected: ${admission.reason}`;
|
|
938
|
+
}
|
|
939
|
+
/** Build the canonical fact from already-admitted arguments. */
|
|
940
|
+
function svgFactFromArgs(args) {
|
|
941
|
+
const bytes = Buffer.byteLength(args.svg, "utf8");
|
|
942
|
+
return {
|
|
943
|
+
version: 1,
|
|
944
|
+
type: "svg",
|
|
945
|
+
title: args.title,
|
|
946
|
+
description: args.description,
|
|
947
|
+
digest: svgDigest(args.svg),
|
|
948
|
+
bytes
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
/** Strict parse of one durable machine-line fact. */
|
|
952
|
+
function parseSvgFact(value) {
|
|
953
|
+
if (!isRecord(value) || !hasOnlyKeys(value, SVG_FACT_KEYS)) return void 0;
|
|
954
|
+
if (value.version !== 1 || value.type !== "svg") return void 0;
|
|
955
|
+
const { title, description, digest, bytes } = value;
|
|
956
|
+
if (typeof title !== "string" || title.trim() === "" || codePointLength(title) > 100) return void 0;
|
|
957
|
+
if (typeof description !== "string" || description.trim() === "" || codePointLength(description) > 500) return void 0;
|
|
958
|
+
if (typeof digest !== "string" || !DIGEST_PATTERN.test(digest)) return void 0;
|
|
959
|
+
if (typeof bytes !== "number" || !Number.isSafeInteger(bytes) || bytes < 0 || bytes > 131072) return void 0;
|
|
960
|
+
return {
|
|
961
|
+
version: 1,
|
|
962
|
+
type: "svg",
|
|
963
|
+
title,
|
|
964
|
+
description,
|
|
965
|
+
digest,
|
|
966
|
+
bytes
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
/** Parse the raw call arguments for the renderers. */
|
|
970
|
+
function parseSvgArgs(argsRaw) {
|
|
971
|
+
let parsed;
|
|
972
|
+
try {
|
|
973
|
+
parsed = JSON.parse(argsRaw);
|
|
974
|
+
} catch {
|
|
975
|
+
return;
|
|
976
|
+
}
|
|
977
|
+
if (svgArgsShapeProblem(parsed) !== void 0) return void 0;
|
|
978
|
+
const { title, description, svg } = parsed;
|
|
979
|
+
return {
|
|
980
|
+
title,
|
|
981
|
+
description,
|
|
982
|
+
svg
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
/** The durable, self-contained human text. */
|
|
986
|
+
function svgHumanText(fact) {
|
|
987
|
+
return [
|
|
988
|
+
fact.title,
|
|
989
|
+
fact.description,
|
|
990
|
+
"SVG source available in the expanded tool call"
|
|
991
|
+
].join("\n");
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* The card-body detail rows. The FINAL fact title is always shown: the card
|
|
995
|
+
* header may describe the original call arguments, while a value replacement
|
|
996
|
+
* changes the committed title.
|
|
997
|
+
*/
|
|
998
|
+
function svgDetailRows(fact) {
|
|
999
|
+
return [
|
|
1000
|
+
fact.title,
|
|
1001
|
+
fact.description,
|
|
1002
|
+
"SVG source available in the expanded tool call"
|
|
1003
|
+
];
|
|
1004
|
+
}
|
|
1005
|
+
/** The durable content blocks: readable text plus the credential line. */
|
|
1006
|
+
function svgContentBlocks(fact) {
|
|
1007
|
+
return [{
|
|
1008
|
+
type: "text",
|
|
1009
|
+
text: svgHumanText(fact)
|
|
1010
|
+
}, {
|
|
1011
|
+
type: "text",
|
|
1012
|
+
text: `${VISUAL_FACT_PREFIX}${JSON.stringify(fact)}`
|
|
1013
|
+
}];
|
|
1014
|
+
}
|
|
1015
|
+
/**
|
|
1016
|
+
* Authorize one SVG drawing from the FINAL result blocks plus the call args.
|
|
1017
|
+
* @param argsRaw - the durable raw call arguments.
|
|
1018
|
+
* @param resultBlocks - the final result content blocks (after policy).
|
|
1019
|
+
* @param admit - the admission implementation (callers may pass a cached one).
|
|
1020
|
+
* @returns ready with the admitted source, or a text-fallback reason.
|
|
1021
|
+
*/
|
|
1022
|
+
function authorizeSvg(argsRaw, resultBlocks, status, admit = admitSvg) {
|
|
1023
|
+
if (status !== "ok") return {
|
|
1024
|
+
state: "text",
|
|
1025
|
+
reason: "the tool result was not successful"
|
|
1026
|
+
};
|
|
1027
|
+
const args = parseSvgArgs(argsRaw);
|
|
1028
|
+
if (args === void 0) return {
|
|
1029
|
+
state: "text",
|
|
1030
|
+
reason: "SVG call arguments are not readable"
|
|
1031
|
+
};
|
|
1032
|
+
const fact = resultFact(resultBlocks);
|
|
1033
|
+
if (fact === void 0) return {
|
|
1034
|
+
state: "text",
|
|
1035
|
+
reason: "SVG result credential is missing"
|
|
1036
|
+
};
|
|
1037
|
+
if (fact.digest !== svgDigest(args.svg) || fact.bytes !== Buffer.byteLength(args.svg, "utf8")) return {
|
|
1038
|
+
state: "text",
|
|
1039
|
+
reason: "SVG result credential does not match the call source"
|
|
1040
|
+
};
|
|
1041
|
+
const admission = admit(args.svg);
|
|
1042
|
+
if (!admission.ok) return {
|
|
1043
|
+
state: "text",
|
|
1044
|
+
reason: `SVG source is not admissible: ${admission.reason}`
|
|
1045
|
+
};
|
|
1046
|
+
return {
|
|
1047
|
+
state: "ready",
|
|
1048
|
+
source: args.svg,
|
|
1049
|
+
fact,
|
|
1050
|
+
admission
|
|
1051
|
+
};
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* The valid SVG credential: the LAST text block is the machine slot. Earlier
|
|
1055
|
+
* blocks (including a human title/description beginning with the same prefix)
|
|
1056
|
+
* are never credential candidates.
|
|
1057
|
+
*/
|
|
1058
|
+
function resultFact(blocks) {
|
|
1059
|
+
if (blocks === void 0) return void 0;
|
|
1060
|
+
let lastText;
|
|
1061
|
+
for (const block of blocks) if (block.type === "text") lastText = block;
|
|
1062
|
+
if (lastText === void 0 || !lastText.text.startsWith("visual-v1:")) return void 0;
|
|
1063
|
+
let parsed;
|
|
1064
|
+
try {
|
|
1065
|
+
parsed = JSON.parse(lastText.text.slice(10));
|
|
1066
|
+
} catch {
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
return parseSvgFact(parsed);
|
|
1070
|
+
}
|
|
1071
|
+
//#endregion
|
|
1072
|
+
//#region src/domain/visual/reference.ts
|
|
1073
|
+
/**
|
|
1074
|
+
* The stable, model-visible visual reference (`sv1_…`) and the credential
|
|
1075
|
+
* machine block that carries it.
|
|
1076
|
+
*
|
|
1077
|
+
* A reference names ONE generating visual tool result. It is derived from the
|
|
1078
|
+
* exact official identity tuple — session, turn, the seq of the open
|
|
1079
|
+
* `step/start`, and the model's `tool/call` id — so the same figure produced
|
|
1080
|
+
* twice is two references, while a replayed log derives the same reference.
|
|
1081
|
+
* The hash is NOT a permission token: every publication re-verifies the tuple
|
|
1082
|
+
* against committed session events.
|
|
1083
|
+
*
|
|
1084
|
+
* The reference rides in its own TEXT content block, `visual-ref-v1:sv1_…`,
|
|
1085
|
+
* inserted before the final `visual-v1:` fact block by the generating tool's
|
|
1086
|
+
* `projectContent`; it is never part of the durable fact itself.
|
|
1087
|
+
* @module @xmoon76/dsh-pi-tui/domain/visual/reference
|
|
1088
|
+
*/
|
|
1089
|
+
/** Prefix of the machine block carrying the stable reference. */
|
|
1090
|
+
const VISUAL_REFERENCE_PREFIX = "visual-ref-v1:";
|
|
1091
|
+
/** The one accepted reference spelling: lowercase hex, exactly 20 digits. */
|
|
1092
|
+
const VISUAL_REFERENCE_PATTERN = /^sv1_[0-9a-f]{20}$/u;
|
|
1093
|
+
/**
|
|
1094
|
+
* The stable reference for one committed generating call.
|
|
1095
|
+
* @param identity - the exact official tuple of the generating result.
|
|
1096
|
+
* @returns the `sv1_` reference.
|
|
1097
|
+
*/
|
|
1098
|
+
function visualReference(identity) {
|
|
1099
|
+
const tuple = [
|
|
1100
|
+
identity.sessionId,
|
|
1101
|
+
String(identity.turn),
|
|
1102
|
+
String(identity.stepStartSeq),
|
|
1103
|
+
identity.callId,
|
|
1104
|
+
""
|
|
1105
|
+
].join("\0");
|
|
1106
|
+
return `sv1_${createHash("sha256").update(tuple, "utf8").digest("hex").slice(0, 20)}`;
|
|
1107
|
+
}
|
|
1108
|
+
/** Serialize the machine block for one reference. */
|
|
1109
|
+
function visualReferenceLine(reference) {
|
|
1110
|
+
return `${VISUAL_REFERENCE_PREFIX}${reference}`;
|
|
1111
|
+
}
|
|
1112
|
+
/** Parse one machine block that carries only a reference. */
|
|
1113
|
+
function parseVisualReferenceLine(text) {
|
|
1114
|
+
if (!text.startsWith("visual-ref-v1:")) return void 0;
|
|
1115
|
+
const reference = text.slice(14);
|
|
1116
|
+
return VISUAL_REFERENCE_PATTERN.test(reference) ? reference : void 0;
|
|
1117
|
+
}
|
|
1118
|
+
//#endregion
|
|
1119
|
+
//#region src/domain/visual/visual-facts.ts
|
|
1120
|
+
/** Serialize one fact as the durable machine line. */
|
|
1121
|
+
function visualFactLine(fact) {
|
|
1122
|
+
return `${VISUAL_FACT_PREFIX}${JSON.stringify(fact)}`;
|
|
1123
|
+
}
|
|
1124
|
+
/** Parse one machine line; unknown or malformed lines are not facts. */
|
|
1125
|
+
function parseVisualFactLine(text) {
|
|
1126
|
+
if (!text.startsWith("visual-v1:")) return void 0;
|
|
1127
|
+
let parsed;
|
|
1128
|
+
try {
|
|
1129
|
+
parsed = JSON.parse(text.slice(10));
|
|
1130
|
+
} catch {
|
|
1131
|
+
return;
|
|
1132
|
+
}
|
|
1133
|
+
if (typeof parsed !== "object" || parsed === null) return void 0;
|
|
1134
|
+
const type = parsed.type;
|
|
1135
|
+
if (type === "chart") return parseChartFact(parsed);
|
|
1136
|
+
if (type === "svg") return parseSvgFact(parsed);
|
|
1137
|
+
}
|
|
1138
|
+
/**
|
|
1139
|
+
* Split one final result's blocks into human blocks, the reference block and
|
|
1140
|
+
* the machine fact.
|
|
1141
|
+
*
|
|
1142
|
+
* The machine slot is the LAST text block. The reference block sits immediately
|
|
1143
|
+
* before it and must be the exact machine line — a human line that merely starts
|
|
1144
|
+
* with the prefix stays human. This is what keeps a legal title such as
|
|
1145
|
+
* `visual-v1: CPU usage` (the first human block) from being mistaken for a
|
|
1146
|
+
* second machine line and invalidating the real credential.
|
|
1147
|
+
*/
|
|
1148
|
+
function visualParts(blocks) {
|
|
1149
|
+
const human = [];
|
|
1150
|
+
let fact;
|
|
1151
|
+
let reference;
|
|
1152
|
+
let lastText = -1;
|
|
1153
|
+
for (let index = blocks.length - 1; index >= 0; index -= 1) if (blocks[index].type === "text") {
|
|
1154
|
+
lastText = index;
|
|
1155
|
+
break;
|
|
1156
|
+
}
|
|
1157
|
+
let referenceIndex = -1;
|
|
1158
|
+
if (lastText > 0 && blocks[lastText].type === "text" && blocks[lastText].text.startsWith("visual-v1:")) {
|
|
1159
|
+
const candidate = blocks[lastText - 1];
|
|
1160
|
+
if (candidate !== void 0 && candidate.type === "text" && parseVisualReferenceLine(candidate.text) !== void 0) referenceIndex = lastText - 1;
|
|
1161
|
+
}
|
|
1162
|
+
for (const [index, block] of blocks.entries()) {
|
|
1163
|
+
if (index === referenceIndex && block.type === "text") {
|
|
1164
|
+
reference = parseVisualReferenceLine(block.text);
|
|
1165
|
+
continue;
|
|
1166
|
+
}
|
|
1167
|
+
if (index === lastText && block.type === "text" && block.text.startsWith("visual-v1:")) {
|
|
1168
|
+
fact = parseVisualFactLine(block.text);
|
|
1169
|
+
continue;
|
|
1170
|
+
}
|
|
1171
|
+
human.push(block);
|
|
1172
|
+
}
|
|
1173
|
+
const text = human.filter((block) => block.type === "text").map((block) => block.text).join("\n");
|
|
1174
|
+
return {
|
|
1175
|
+
human,
|
|
1176
|
+
fact,
|
|
1177
|
+
humanText: text,
|
|
1178
|
+
reference
|
|
1179
|
+
};
|
|
1180
|
+
}
|
|
1181
|
+
/**
|
|
1182
|
+
* The status-gated view of one result: a failed/blocked/running row keeps its
|
|
1183
|
+
* human blocks but never exposes a visual fact. Every renderer/blob sender
|
|
1184
|
+
* uses this so a policy block cannot draw a stale figure.
|
|
1185
|
+
* @param status - the durable tool-result status.
|
|
1186
|
+
* @param blocks - the final result content blocks.
|
|
1187
|
+
* @returns the same shape as {@link visualParts}, with `fact` only for `ok`.
|
|
1188
|
+
*/
|
|
1189
|
+
function visualPartsForStatus(status, blocks) {
|
|
1190
|
+
const parts = visualParts(blocks);
|
|
1191
|
+
return status === "ok" ? parts : {
|
|
1192
|
+
...parts,
|
|
1193
|
+
fact: void 0,
|
|
1194
|
+
reference: void 0
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
1197
|
+
/**
|
|
1198
|
+
* The flat-text fallback: older/synthetic rows may carry the joined result
|
|
1199
|
+
* string instead of `resultBlocks`. Split the machine line(s) out line-wise so
|
|
1200
|
+
* a malformed fact can never leak its JSON into the card body.
|
|
1201
|
+
* @param result - the joined durable result text.
|
|
1202
|
+
* @returns the same parts shape as {@link visualParts}.
|
|
1203
|
+
*/
|
|
1204
|
+
function visualPartsFromText(result) {
|
|
1205
|
+
const lines = result.split("\n");
|
|
1206
|
+
let lastNonEmpty = -1;
|
|
1207
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) if (lines[index] !== "") {
|
|
1208
|
+
lastNonEmpty = index;
|
|
1209
|
+
break;
|
|
1210
|
+
}
|
|
1211
|
+
const hasFact = lastNonEmpty !== -1 && lines[lastNonEmpty].startsWith("visual-v1:");
|
|
1212
|
+
const referenceLine = hasFact && lastNonEmpty > 0 ? parseVisualReferenceLine(lines[lastNonEmpty - 1] ?? "") : void 0;
|
|
1213
|
+
let fact;
|
|
1214
|
+
let reference;
|
|
1215
|
+
const humanLines = [];
|
|
1216
|
+
for (const [index, line] of lines.entries()) {
|
|
1217
|
+
if (referenceLine !== void 0 && index === lastNonEmpty - 1) {
|
|
1218
|
+
reference = referenceLine;
|
|
1219
|
+
continue;
|
|
1220
|
+
}
|
|
1221
|
+
if (index === lastNonEmpty && hasFact) {
|
|
1222
|
+
fact = parseVisualFactLine(line);
|
|
1223
|
+
continue;
|
|
1224
|
+
}
|
|
1225
|
+
humanLines.push(line);
|
|
1226
|
+
}
|
|
1227
|
+
const humanText = humanLines.join("\n").replace(/\n+$/u, "");
|
|
1228
|
+
return {
|
|
1229
|
+
human: humanText === "" ? [] : [{
|
|
1230
|
+
type: "text",
|
|
1231
|
+
text: humanText
|
|
1232
|
+
}],
|
|
1233
|
+
fact,
|
|
1234
|
+
humanText,
|
|
1235
|
+
reference
|
|
1236
|
+
};
|
|
1237
|
+
}
|
|
1238
|
+
//#endregion
|
|
1239
|
+
//#region src/domain/visual/origin.ts
|
|
1240
|
+
/** The empty proof: no seq is attributed to any Session. */
|
|
1241
|
+
const NO_SPANS = Object.freeze([]);
|
|
1242
|
+
/** Whether one value is a structurally usable, non-empty range. */
|
|
1243
|
+
function isValidSpan(span) {
|
|
1244
|
+
return typeof span.sessionId === "string" && span.sessionId !== "" && Number.isSafeInteger(span.startSeq) && Number.isSafeInteger(span.endSeqExclusive) && span.startSeq >= 0 && span.endSeqExclusive > span.startSeq;
|
|
1245
|
+
}
|
|
1246
|
+
/** Freeze one validated range. */
|
|
1247
|
+
function frozenSpan(span) {
|
|
1248
|
+
return Object.freeze({
|
|
1249
|
+
startSeq: span.startSeq,
|
|
1250
|
+
endSeqExclusive: span.endSeqExclusive,
|
|
1251
|
+
sessionId: span.sessionId
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* The ONE always-proven range of a log: a Session's OWN events.
|
|
1256
|
+
*
|
|
1257
|
+
* Events at or after the fork cut belong to the current Session by
|
|
1258
|
+
* construction, so this needs no ancestry read. An empty range covers nothing.
|
|
1259
|
+
* @param sessionId - the owning Session id.
|
|
1260
|
+
* @param startSeq - the first own seq (the inherited cut).
|
|
1261
|
+
* @param endSeqExclusive - the exclusive end (the log length).
|
|
1262
|
+
* @returns one frozen span, or the empty list for an empty/invalid range.
|
|
1263
|
+
*/
|
|
1264
|
+
function ownVisualOriginSpans(sessionId, startSeq, endSeqExclusive) {
|
|
1265
|
+
const span = {
|
|
1266
|
+
startSeq,
|
|
1267
|
+
endSeqExclusive,
|
|
1268
|
+
sessionId
|
|
1269
|
+
};
|
|
1270
|
+
if (!isValidSpan(span)) return NO_SPANS;
|
|
1271
|
+
return Object.freeze([frozenSpan(span)]);
|
|
1272
|
+
}
|
|
1273
|
+
/**
|
|
1274
|
+
* Merge ranges into the canonical ordered, non-overlapping form.
|
|
1275
|
+
*
|
|
1276
|
+
* Adjacent ranges of the SAME Session are coalesced; adjacent ranges of
|
|
1277
|
+
* DIFFERENT Sessions stay separate because the cut is a real identity change.
|
|
1278
|
+
* An overlapping, duplicated or malformed range set is refused as a whole
|
|
1279
|
+
* (`undefined`) instead of silently attributing one seq twice.
|
|
1280
|
+
* @param parts - the candidate ranges, in any order.
|
|
1281
|
+
* @returns the canonical frozen ranges, or undefined for an unusable set.
|
|
1282
|
+
*/
|
|
1283
|
+
function mergeVisualOriginSpans(parts) {
|
|
1284
|
+
const sorted = [...parts].sort((left, right) => left.startSeq - right.startSeq);
|
|
1285
|
+
const spans = [];
|
|
1286
|
+
for (const part of sorted) {
|
|
1287
|
+
if (!isValidSpan(part)) return void 0;
|
|
1288
|
+
const last = spans[spans.length - 1];
|
|
1289
|
+
if (last === void 0) {
|
|
1290
|
+
spans.push(frozenSpan(part));
|
|
1291
|
+
continue;
|
|
1292
|
+
}
|
|
1293
|
+
if (part.startSeq < last.endSeqExclusive) return void 0;
|
|
1294
|
+
if (part.startSeq === last.endSeqExclusive && part.sessionId === last.sessionId) {
|
|
1295
|
+
spans[spans.length - 1] = frozenSpan({
|
|
1296
|
+
startSeq: last.startSeq,
|
|
1297
|
+
endSeqExclusive: part.endSeqExclusive,
|
|
1298
|
+
sessionId: last.sessionId
|
|
1299
|
+
});
|
|
1300
|
+
continue;
|
|
1301
|
+
}
|
|
1302
|
+
spans.push(frozenSpan(part));
|
|
1303
|
+
}
|
|
1304
|
+
return Object.freeze(spans);
|
|
1305
|
+
}
|
|
1306
|
+
/**
|
|
1307
|
+
* Clip proven ranges to one half-open window.
|
|
1308
|
+
*
|
|
1309
|
+
* This is how a descendant reuses an ancestor's proof: the ancestor's full
|
|
1310
|
+
* range list is intersected with the prefix window the descendant inherited.
|
|
1311
|
+
* An invalid input set proves nothing.
|
|
1312
|
+
* @param spans - the proven ranges.
|
|
1313
|
+
* @param startSeq - inclusive window start.
|
|
1314
|
+
* @param endSeqExclusive - exclusive window end.
|
|
1315
|
+
* @returns the clipped ranges, still ordered and non-overlapping.
|
|
1316
|
+
*/
|
|
1317
|
+
function intersectVisualOriginSpans(spans, startSeq, endSeqExclusive) {
|
|
1318
|
+
if (!Number.isSafeInteger(startSeq) || !Number.isSafeInteger(endSeqExclusive) || endSeqExclusive <= startSeq) return NO_SPANS;
|
|
1319
|
+
const merged = mergeVisualOriginSpans(spans);
|
|
1320
|
+
if (merged === void 0) return NO_SPANS;
|
|
1321
|
+
const clipped = [];
|
|
1322
|
+
for (const span of merged) {
|
|
1323
|
+
const start = Math.max(span.startSeq, startSeq);
|
|
1324
|
+
const end = Math.min(span.endSeqExclusive, endSeqExclusive);
|
|
1325
|
+
if (end <= start) continue;
|
|
1326
|
+
clipped.push(frozenSpan({
|
|
1327
|
+
startSeq: start,
|
|
1328
|
+
endSeqExclusive: end,
|
|
1329
|
+
sessionId: span.sessionId
|
|
1330
|
+
}));
|
|
1331
|
+
}
|
|
1332
|
+
return Object.freeze(clipped);
|
|
1333
|
+
}
|
|
1334
|
+
/**
|
|
1335
|
+
* Resolve the proven origin of one seq, once.
|
|
1336
|
+
* @param spans - the proven ranges.
|
|
1337
|
+
* @param seq - one log seq.
|
|
1338
|
+
* @returns the original Session id, or undefined when the seq is unproven.
|
|
1339
|
+
*/
|
|
1340
|
+
function originSessionIdAt(spans, seq) {
|
|
1341
|
+
return createVisualOriginReader(spans)(seq);
|
|
1342
|
+
}
|
|
1343
|
+
/**
|
|
1344
|
+
* Build the ONE seq→origin lookup of a replay scan.
|
|
1345
|
+
*
|
|
1346
|
+
* The ranges are validated once; a malformed set proves nothing. The lookup is
|
|
1347
|
+
* a binary search, so one replay pass costs `O(events · log(spans))` and never
|
|
1348
|
+
* rescans the ranges per event.
|
|
1349
|
+
* @param spans - the proven ranges.
|
|
1350
|
+
* @returns the lookup (undefined for an unproven seq).
|
|
1351
|
+
*/
|
|
1352
|
+
function createVisualOriginReader(spans) {
|
|
1353
|
+
const merged = mergeVisualOriginSpans(spans);
|
|
1354
|
+
if (merged === void 0) return () => void 0;
|
|
1355
|
+
return (seq) => {
|
|
1356
|
+
let low = 0;
|
|
1357
|
+
let high = merged.length - 1;
|
|
1358
|
+
while (low <= high) {
|
|
1359
|
+
const middle = low + high >> 1;
|
|
1360
|
+
const span = merged[middle];
|
|
1361
|
+
if (seq < span.startSeq) high = middle - 1;
|
|
1362
|
+
else if (seq >= span.endSeqExclusive) low = middle + 1;
|
|
1363
|
+
else return span.sessionId;
|
|
1364
|
+
}
|
|
1365
|
+
};
|
|
1366
|
+
}
|
|
1367
|
+
//#endregion
|
|
1368
|
+
//#region src/domain/visual/publication.ts
|
|
1369
|
+
/** The durable event types this authority reads. */
|
|
1370
|
+
const RELEVANT_EVENT_TYPES = /* @__PURE__ */ new Set([
|
|
1371
|
+
"turn/start",
|
|
1372
|
+
"turn/end",
|
|
1373
|
+
"step/start",
|
|
1374
|
+
"step/end",
|
|
1375
|
+
"assistant/message",
|
|
1376
|
+
"tool/call",
|
|
1377
|
+
"tool/result"
|
|
1378
|
+
]);
|
|
1379
|
+
/**
|
|
1380
|
+
* Narrow one raw session event log to the shapes this authority reads.
|
|
1381
|
+
*
|
|
1382
|
+
* The events come from a persisted/observed log — a real external boundary — so
|
|
1383
|
+
* unrelated event types are simply not handed to the authority; every relevant
|
|
1384
|
+
* type still carries its official field set by construction of that log.
|
|
1385
|
+
* @param events - a committed session event log.
|
|
1386
|
+
* @returns the relevant events, unchanged and in order.
|
|
1387
|
+
*/
|
|
1388
|
+
function asVisualSessionEvents(events) {
|
|
1389
|
+
return events.filter((event) => RELEVANT_EVENT_TYPES.has(event.type));
|
|
1390
|
+
}
|
|
1391
|
+
/**
|
|
1392
|
+
* Whether one event is a MODEL-ONLY surface replacement.
|
|
1393
|
+
*
|
|
1394
|
+
* The compaction `ToolResultPruner` appends a second `tool/result` that repeats
|
|
1395
|
+
* the original's turn, step and `callId` and is marked
|
|
1396
|
+
* `surfaceOp: { op: 'replace', … }`. Such a copy rewrites only the model-facing
|
|
1397
|
+
* projection: the append-origin result stays the human-visible history, and
|
|
1398
|
+
* treating the rewrite as a second durable result would mark the generating
|
|
1399
|
+
* source ambiguous and retract an already-accepted publication. The same rule
|
|
1400
|
+
* is applied by the transcript fold and the `/transcript` export. An unmarked
|
|
1401
|
+
* legacy event is never a replacement — absence of the marker is not a rewrite.
|
|
1402
|
+
* @param event - one log event.
|
|
1403
|
+
* @returns true only for an explicit replacement.
|
|
1404
|
+
*/
|
|
1405
|
+
function isModelOnlyReplacement(event) {
|
|
1406
|
+
const surfaceOp = event.surfaceOp;
|
|
1407
|
+
if (surfaceOp === void 0) return false;
|
|
1408
|
+
return surfaceOp.op === "replace";
|
|
1409
|
+
}
|
|
1410
|
+
function callKey(turn, step, callId) {
|
|
1411
|
+
return `${turn}:${step}:${callId}`;
|
|
1412
|
+
}
|
|
1413
|
+
/**
|
|
1414
|
+
* The executing step's `(turn, step)` key, located by its seq range.
|
|
1415
|
+
*
|
|
1416
|
+
* The step's model response lands AFTER its `step/start` and BEFORE the next
|
|
1417
|
+
* step boundary, so the range identifies it exactly even in a multi-step turn.
|
|
1418
|
+
* This reads only the boundary events, not the tool events.
|
|
1419
|
+
* @param events - the authority events.
|
|
1420
|
+
* @param turn - the executing turn.
|
|
1421
|
+
* @param stepStartSeq - the seq of the executing step's `step/start`.
|
|
1422
|
+
* @returns the step key, or undefined when its response is not observed.
|
|
1423
|
+
*/
|
|
1424
|
+
function executingStepKey(events, turn, stepStartSeq) {
|
|
1425
|
+
let nextBoundary = Number.POSITIVE_INFINITY;
|
|
1426
|
+
for (const event of events) {
|
|
1427
|
+
if (event.seq <= stepStartSeq) continue;
|
|
1428
|
+
if (event.type !== "step/start" && event.type !== "step/end" && event.type !== "turn/end") continue;
|
|
1429
|
+
if (event.seq < nextBoundary) nextBoundary = event.seq;
|
|
1430
|
+
}
|
|
1431
|
+
for (const event of events) {
|
|
1432
|
+
if (event.type !== "assistant/message" || isModelOnlyReplacement(event)) continue;
|
|
1433
|
+
if (event.data.turn !== turn) continue;
|
|
1434
|
+
if (event.seq <= stepStartSeq || event.seq >= nextBoundary) continue;
|
|
1435
|
+
return `${event.data.turn}:${event.data.step}`;
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* Index one committed log exactly once.
|
|
1440
|
+
*
|
|
1441
|
+
* Without `originOf` every event belongs to `sessionId` (the pre-lineage
|
|
1442
|
+
* behaviour and the LIVE path, which only ever reads its own committed log).
|
|
1443
|
+
* With `originOf` — a replay over proven fork-inherited ranges — each call is
|
|
1444
|
+
* attributed to the Session its seq originally belonged to, and a call in an
|
|
1445
|
+
* unproven seq is not indexed at all: it can neither be a source nor publish.
|
|
1446
|
+
* @param sessionId - the observed session identity.
|
|
1447
|
+
* @param events - the authority events.
|
|
1448
|
+
* @param originOf - optional proven seq→origin lookup.
|
|
1449
|
+
* @returns the indexed calls and the per-step requested-id counts.
|
|
1450
|
+
*/
|
|
1451
|
+
function indexLog(sessionId, events, originOf) {
|
|
1452
|
+
const originAt = originOf ?? (() => sessionId);
|
|
1453
|
+
const calls = [];
|
|
1454
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
1455
|
+
const stepCallIds = /* @__PURE__ */ new Map();
|
|
1456
|
+
let openStepStartSeq;
|
|
1457
|
+
for (const event of events) {
|
|
1458
|
+
if (isModelOnlyReplacement(event)) continue;
|
|
1459
|
+
switch (event.type) {
|
|
1460
|
+
case "assistant/message": {
|
|
1461
|
+
const key = `${event.data.turn}:${event.data.step}`;
|
|
1462
|
+
let counts = stepCallIds.get(key);
|
|
1463
|
+
if (counts === void 0) {
|
|
1464
|
+
counts = /* @__PURE__ */ new Map();
|
|
1465
|
+
stepCallIds.set(key, counts);
|
|
1466
|
+
}
|
|
1467
|
+
for (const block of event.data.message.content) {
|
|
1468
|
+
if (block.type !== "tool-call" || typeof block.id !== "string") continue;
|
|
1469
|
+
counts.set(block.id, (counts.get(block.id) ?? 0) + 1);
|
|
1470
|
+
}
|
|
1471
|
+
break;
|
|
1472
|
+
}
|
|
1473
|
+
case "turn/start":
|
|
1474
|
+
case "turn/end":
|
|
1475
|
+
case "step/end":
|
|
1476
|
+
openStepStartSeq = void 0;
|
|
1477
|
+
break;
|
|
1478
|
+
case "step/start":
|
|
1479
|
+
openStepStartSeq = event.seq;
|
|
1480
|
+
break;
|
|
1481
|
+
case "tool/call": {
|
|
1482
|
+
if (openStepStartSeq === void 0) break;
|
|
1483
|
+
const originSessionId = originAt(event.seq);
|
|
1484
|
+
if (originSessionId === void 0 || originAt(openStepStartSeq) !== originSessionId) break;
|
|
1485
|
+
const call = {
|
|
1486
|
+
callId: event.data.callId,
|
|
1487
|
+
name: event.data.name,
|
|
1488
|
+
arguments: event.data.arguments,
|
|
1489
|
+
turn: event.data.turn,
|
|
1490
|
+
step: event.data.step,
|
|
1491
|
+
stepStartSeq: openStepStartSeq,
|
|
1492
|
+
callSeq: event.seq,
|
|
1493
|
+
originSessionId,
|
|
1494
|
+
ref: visualReference({
|
|
1495
|
+
sessionId: originSessionId,
|
|
1496
|
+
turn: event.data.turn,
|
|
1497
|
+
stepStartSeq: openStepStartSeq,
|
|
1498
|
+
callId: event.data.callId
|
|
1499
|
+
}),
|
|
1500
|
+
result: void 0,
|
|
1501
|
+
ambiguous: false
|
|
1502
|
+
};
|
|
1503
|
+
const key = callKey(call.turn, call.step, call.callId);
|
|
1504
|
+
const existing = byKey.get(key);
|
|
1505
|
+
if (existing !== void 0) {
|
|
1506
|
+
existing.ambiguous = true;
|
|
1507
|
+
break;
|
|
1508
|
+
}
|
|
1509
|
+
byKey.set(key, call);
|
|
1510
|
+
calls.push(call);
|
|
1511
|
+
break;
|
|
1512
|
+
}
|
|
1513
|
+
case "tool/result": {
|
|
1514
|
+
const key = callKey(event.data.turn, event.data.step, event.data.message.toolCallId);
|
|
1515
|
+
const call = byKey.get(key);
|
|
1516
|
+
if (call === void 0) break;
|
|
1517
|
+
if (originAt(event.seq) !== call.originSessionId) break;
|
|
1518
|
+
if (call.result !== void 0 || event.seq <= call.callSeq) {
|
|
1519
|
+
call.ambiguous = true;
|
|
1520
|
+
break;
|
|
1521
|
+
}
|
|
1522
|
+
call.result = {
|
|
1523
|
+
seq: event.seq,
|
|
1524
|
+
content: event.data.message.content,
|
|
1525
|
+
isError: event.data.message.isError === true
|
|
1526
|
+
};
|
|
1527
|
+
break;
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
return {
|
|
1532
|
+
calls,
|
|
1533
|
+
stepCallIds
|
|
1534
|
+
};
|
|
1535
|
+
}
|
|
1536
|
+
/** The text blocks of one result's content, in order. */
|
|
1537
|
+
function textBlocks(blocks) {
|
|
1538
|
+
const texts = [];
|
|
1539
|
+
for (const block of blocks) if (block.type === "text") texts.push(block.text);
|
|
1540
|
+
return texts;
|
|
1541
|
+
}
|
|
1542
|
+
/**
|
|
1543
|
+
* The reference block the generating tool projected into one FINAL result.
|
|
1544
|
+
*
|
|
1545
|
+
* The projected shape is `… <ref block>\n<visual-v1 fact>`: the fact is the
|
|
1546
|
+
* LAST text block and the reference block is the one immediately before it. A
|
|
1547
|
+
* human line that merely starts with the prefix is never a candidate, because
|
|
1548
|
+
* the position AND the exact machine-only spelling are both required.
|
|
1549
|
+
* @param blocks - the final result content blocks.
|
|
1550
|
+
* @returns the reference, or undefined when the tail shape does not hold.
|
|
1551
|
+
*/
|
|
1552
|
+
function trailingVisualReference(blocks) {
|
|
1553
|
+
const texts = textBlocks(blocks);
|
|
1554
|
+
if (texts.length < 2) return void 0;
|
|
1555
|
+
if (!texts[texts.length - 1].startsWith("visual-v1:")) return void 0;
|
|
1556
|
+
return parseVisualReferenceLine(texts[texts.length - 2]);
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* Qualify one indexed call as a publishable generating occurrence.
|
|
1560
|
+
* @param call - one indexed call occurrence.
|
|
1561
|
+
* @returns the source, or undefined when any qualifier is missing.
|
|
1562
|
+
*/
|
|
1563
|
+
function qualifySource(call) {
|
|
1564
|
+
if (call.ambiguous) return void 0;
|
|
1565
|
+
if (call.name !== "dsh_pi_tui_chart" && call.name !== "dsh_pi_tui_svg") return void 0;
|
|
1566
|
+
const result = call.result;
|
|
1567
|
+
if (result === void 0 || result.isError) return void 0;
|
|
1568
|
+
if (trailingVisualReference(result.content) !== call.ref) return void 0;
|
|
1569
|
+
const fact = visualParts(result.content).fact;
|
|
1570
|
+
if (fact === void 0) return void 0;
|
|
1571
|
+
const base = {
|
|
1572
|
+
ref: call.ref,
|
|
1573
|
+
title: fact.title,
|
|
1574
|
+
turn: call.turn,
|
|
1575
|
+
step: call.step,
|
|
1576
|
+
stepStartSeq: call.stepStartSeq,
|
|
1577
|
+
callSeq: call.callSeq,
|
|
1578
|
+
resultSeq: result.seq,
|
|
1579
|
+
callId: call.callId
|
|
1580
|
+
};
|
|
1581
|
+
if (call.name === "dsh_pi_tui_chart") return fact.type === "chart" ? {
|
|
1582
|
+
source: {
|
|
1583
|
+
...base,
|
|
1584
|
+
type: "chart",
|
|
1585
|
+
chart: fact,
|
|
1586
|
+
svg: void 0,
|
|
1587
|
+
svgSource: void 0,
|
|
1588
|
+
svgAdmissionWidth: void 0
|
|
1589
|
+
},
|
|
1590
|
+
originSessionId: call.originSessionId
|
|
1591
|
+
} : void 0;
|
|
1592
|
+
if (fact.type !== "svg") return void 0;
|
|
1593
|
+
const authorization = authorizeSvg(call.arguments, result.content, "ok");
|
|
1594
|
+
if (authorization.state !== "ready") return void 0;
|
|
1595
|
+
return {
|
|
1596
|
+
source: {
|
|
1597
|
+
...base,
|
|
1598
|
+
type: "svg",
|
|
1599
|
+
chart: void 0,
|
|
1600
|
+
svg: fact,
|
|
1601
|
+
svgSource: authorization.source,
|
|
1602
|
+
svgAdmissionWidth: authorization.admission.width
|
|
1603
|
+
},
|
|
1604
|
+
originSessionId: call.originSessionId
|
|
1605
|
+
};
|
|
1606
|
+
}
|
|
1607
|
+
/**
|
|
1608
|
+
* The qualified sources of an ALREADY indexed log.
|
|
1609
|
+
*
|
|
1610
|
+
* Cold replay builds the index once and derives both the sources and the
|
|
1611
|
+
* publications from it, so the event list is scanned exactly once (plan §2.3).
|
|
1612
|
+
* @param calls - the indexed calls of one committed log.
|
|
1613
|
+
* @returns the qualified sources in durable order.
|
|
1614
|
+
*/
|
|
1615
|
+
function sourcesOf(calls) {
|
|
1616
|
+
const sources = [];
|
|
1617
|
+
for (const call of calls) {
|
|
1618
|
+
const source = qualifySource(call);
|
|
1619
|
+
if (source !== void 0) sources.push(source);
|
|
1620
|
+
}
|
|
1621
|
+
return sources;
|
|
1622
|
+
}
|
|
1623
|
+
/** The last text block's text of one result. */
|
|
1624
|
+
function lastText(blocks) {
|
|
1625
|
+
const texts = textBlocks(blocks);
|
|
1626
|
+
return texts[texts.length - 1];
|
|
1627
|
+
}
|
|
1628
|
+
/** Whether one string is the accepted reference spelling. */
|
|
1629
|
+
function isReferenceSpelling(value) {
|
|
1630
|
+
return parseVisualReferenceLine(`${VISUAL_REFERENCE_PREFIX}${value}`) !== void 0;
|
|
1631
|
+
}
|
|
1632
|
+
/** Structural validation of one receipt JSON body. */
|
|
1633
|
+
function parseReceiptBody(value) {
|
|
1634
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
1635
|
+
const record = value;
|
|
1636
|
+
if (Object.keys(record).length !== 2 || record.version !== 1 || !Array.isArray(record.published)) return void 0;
|
|
1637
|
+
if (record.published.length === 0 || record.published.length > 8) return void 0;
|
|
1638
|
+
const published = [];
|
|
1639
|
+
for (const entry of record.published) {
|
|
1640
|
+
if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return void 0;
|
|
1641
|
+
const fields = entry;
|
|
1642
|
+
if (Object.keys(fields).length !== 1 || typeof fields.ref !== "string") return void 0;
|
|
1643
|
+
published.push({ ref: fields.ref });
|
|
1644
|
+
}
|
|
1645
|
+
return {
|
|
1646
|
+
version: 1,
|
|
1647
|
+
published
|
|
1648
|
+
};
|
|
1649
|
+
}
|
|
1650
|
+
/**
|
|
1651
|
+
* Parse the durable publication receipt of one final result.
|
|
1652
|
+
*
|
|
1653
|
+
* The receipt is the LAST text block; the human summary precedes it. A failed
|
|
1654
|
+
* result never carries one, the JSON body must be exactly
|
|
1655
|
+
* `{version:1, published:[{ref}]}`, and the references must be unique and
|
|
1656
|
+
* well-formed.
|
|
1657
|
+
* @param blocks - the final result content blocks.
|
|
1658
|
+
* @param isError - the durable result failure flag.
|
|
1659
|
+
* @returns the parsed receipt and the preceding human text, or undefined.
|
|
1660
|
+
*/
|
|
1661
|
+
function parsePublicationReceipt(blocks, isError) {
|
|
1662
|
+
if (isError) return void 0;
|
|
1663
|
+
const last = lastText(blocks);
|
|
1664
|
+
if (last === void 0 || !last.startsWith("visual-published-v1:")) return void 0;
|
|
1665
|
+
let parsed;
|
|
1666
|
+
try {
|
|
1667
|
+
parsed = JSON.parse(last.slice(20));
|
|
1668
|
+
} catch {
|
|
1669
|
+
return;
|
|
1670
|
+
}
|
|
1671
|
+
const receipt = parseReceiptBody(parsed);
|
|
1672
|
+
if (receipt === void 0) return void 0;
|
|
1673
|
+
const refs = receipt.published.map((entry) => entry.ref);
|
|
1674
|
+
if (new Set(refs).size !== refs.length) return void 0;
|
|
1675
|
+
if (!refs.every((ref) => isReferenceSpelling(ref))) return void 0;
|
|
1676
|
+
const human = [];
|
|
1677
|
+
for (const block of blocks) if (block.type === "text" && block.text !== last) human.push(block.text);
|
|
1678
|
+
return {
|
|
1679
|
+
receipt,
|
|
1680
|
+
humanText: human.join("\n")
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
/** The references one `present_visual` call requested, or undefined when unreadable. */
|
|
1684
|
+
function requestedReferences(rawArguments) {
|
|
1685
|
+
let parsed;
|
|
1686
|
+
try {
|
|
1687
|
+
parsed = JSON.parse(rawArguments);
|
|
1688
|
+
} catch {
|
|
1689
|
+
return;
|
|
1690
|
+
}
|
|
1691
|
+
const decision = parsePresentVisualArguments(parsed);
|
|
1692
|
+
return decision.ok ? [...decision.refs] : void 0;
|
|
1693
|
+
}
|
|
1694
|
+
/**
|
|
1695
|
+
* The ONE `present_visual` argument contract, shared by live execution and cold
|
|
1696
|
+
* replay.
|
|
1697
|
+
*
|
|
1698
|
+
* The official ToolRuntime does NOT apply a full JSON-Schema pass to a tool's
|
|
1699
|
+
* arguments; the body receives them as-is. The live path therefore validates
|
|
1700
|
+
* with THIS function, and the replay path parses the durable
|
|
1701
|
+
* `tool/call.arguments` with the same one — so a successful receipt can always
|
|
1702
|
+
* be replay-verified, and a replay can never accept a document the live body
|
|
1703
|
+
* would have refused. The document is closed: only `visuals` at the root, only
|
|
1704
|
+
* `ref` per entry, 1–8 entries, well-formed `sv1_` references, no duplicates.
|
|
1705
|
+
* @param args - the model-supplied arguments (already JSON-parsed).
|
|
1706
|
+
* @returns the accepted references, or the verbatim refusal reason.
|
|
1707
|
+
*/
|
|
1708
|
+
function parsePresentVisualArguments(args) {
|
|
1709
|
+
if (typeof args !== "object" || args === null || Array.isArray(args)) return {
|
|
1710
|
+
ok: false,
|
|
1711
|
+
reason: "arguments must be an object with a `visuals` array"
|
|
1712
|
+
};
|
|
1713
|
+
const record = args;
|
|
1714
|
+
if (Object.keys(record).length !== 1 || !Array.isArray(record.visuals)) return {
|
|
1715
|
+
ok: false,
|
|
1716
|
+
reason: "arguments must contain only `visuals`"
|
|
1717
|
+
};
|
|
1718
|
+
const visuals = record.visuals;
|
|
1719
|
+
if (visuals.length === 0 || visuals.length > 8) return {
|
|
1720
|
+
ok: false,
|
|
1721
|
+
reason: `visuals must contain between 1 and 8 items`
|
|
1722
|
+
};
|
|
1723
|
+
const refs = [];
|
|
1724
|
+
for (const entry of visuals) {
|
|
1725
|
+
if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return {
|
|
1726
|
+
ok: false,
|
|
1727
|
+
reason: "every visual must be an object"
|
|
1728
|
+
};
|
|
1729
|
+
const fields = entry;
|
|
1730
|
+
if (Object.keys(fields).length !== 1 || typeof fields.ref !== "string") return {
|
|
1731
|
+
ok: false,
|
|
1732
|
+
reason: "every visual must contain only `ref`"
|
|
1733
|
+
};
|
|
1734
|
+
if (!isReferenceSpelling(fields.ref)) return {
|
|
1735
|
+
ok: false,
|
|
1736
|
+
reason: "every visual ref must look like sv1_ followed by 20 lowercase hex digits"
|
|
1737
|
+
};
|
|
1738
|
+
refs.push(fields.ref);
|
|
1739
|
+
}
|
|
1740
|
+
if (new Set(refs).size !== refs.length) return {
|
|
1741
|
+
ok: false,
|
|
1742
|
+
reason: "present_visual received the same visual ref twice"
|
|
1743
|
+
};
|
|
1744
|
+
return {
|
|
1745
|
+
ok: true,
|
|
1746
|
+
refs
|
|
1747
|
+
};
|
|
1748
|
+
}
|
|
1749
|
+
/**
|
|
1750
|
+
* Whether one generating source may be published by the given publisher.
|
|
1751
|
+
*
|
|
1752
|
+
* Stated once so the live tool body and cold replay cannot disagree: the SAME
|
|
1753
|
+
* original Session recorded both, the same turn, an EARLIER model step, and the
|
|
1754
|
+
* source result committed before the publishing call. The origin check is what
|
|
1755
|
+
* stops a child from publishing a figure it merely inherited.
|
|
1756
|
+
*/
|
|
1757
|
+
function isPublishableBy(qualified, publisher) {
|
|
1758
|
+
return qualified.originSessionId === publisher.originSessionId && qualified.source.turn === publisher.turn && qualified.source.stepStartSeq < publisher.stepStartSeq && qualified.source.resultSeq < publisher.callSeq;
|
|
1759
|
+
}
|
|
1760
|
+
/**
|
|
1761
|
+
* Collect the successfully published visuals of one committed log.
|
|
1762
|
+
*
|
|
1763
|
+
* Cold replay applies the SAME rules as the Host tool body. A publication is
|
|
1764
|
+
* accepted only when the durable `present_visual` call and its successful
|
|
1765
|
+
* result pair exactly, the receipt is present in the FINAL content, and the
|
|
1766
|
+
* requested references equal the receipt's references position by position.
|
|
1767
|
+
* Repeated references keep only their FIRST successful publication.
|
|
1768
|
+
* @param sessionId - the observed session identity.
|
|
1769
|
+
* @param events - the exact committed events, in `seq` order.
|
|
1770
|
+
* @returns the published visuals in durable order, first-wins.
|
|
1771
|
+
*/
|
|
1772
|
+
function collectPublishedVisuals(sessionId, events, originSpans) {
|
|
1773
|
+
const indexed = indexLog(sessionId, events, originSpans === void 0 ? void 0 : createVisualOriginReader(originSpans));
|
|
1774
|
+
const sourcesByRef = /* @__PURE__ */ new Map();
|
|
1775
|
+
for (const qualified of sourcesOf(indexed.calls)) {
|
|
1776
|
+
const ref = qualified.source.ref;
|
|
1777
|
+
sourcesByRef.set(ref, sourcesByRef.has(ref) ? null : qualified);
|
|
1778
|
+
}
|
|
1779
|
+
const published = [];
|
|
1780
|
+
const alreadyPublished = /* @__PURE__ */ new Set();
|
|
1781
|
+
for (const call of indexed.calls) {
|
|
1782
|
+
if (call.ambiguous || call.name !== "present_visual") continue;
|
|
1783
|
+
const result = call.result;
|
|
1784
|
+
if (result === void 0) continue;
|
|
1785
|
+
const parsed = parsePublicationReceipt(result.content, result.isError);
|
|
1786
|
+
if (parsed === void 0) continue;
|
|
1787
|
+
const requested = requestedReferences(call.arguments);
|
|
1788
|
+
if (requested === void 0) continue;
|
|
1789
|
+
const receiptRefs = parsed.receipt.published.map((entry) => entry.ref);
|
|
1790
|
+
if (requested.length !== receiptRefs.length) continue;
|
|
1791
|
+
if (!requested.every((ref, position) => ref === receiptRefs[position])) continue;
|
|
1792
|
+
const accepted = [];
|
|
1793
|
+
let qualified = true;
|
|
1794
|
+
for (const ref of requested) {
|
|
1795
|
+
const source = sourcesByRef.get(ref);
|
|
1796
|
+
if (source === void 0 || source === null || !isPublishableBy(source, call)) {
|
|
1797
|
+
qualified = false;
|
|
1798
|
+
break;
|
|
1799
|
+
}
|
|
1800
|
+
accepted.push({
|
|
1801
|
+
ref,
|
|
1802
|
+
turn: call.turn,
|
|
1803
|
+
step: call.step,
|
|
1804
|
+
stepStartSeq: call.stepStartSeq,
|
|
1805
|
+
callSeq: call.callSeq,
|
|
1806
|
+
resultSeq: result.seq,
|
|
1807
|
+
callId: call.callId,
|
|
1808
|
+
source: source.source
|
|
1809
|
+
});
|
|
1810
|
+
}
|
|
1811
|
+
if (!qualified) continue;
|
|
1812
|
+
for (const entry of accepted) {
|
|
1813
|
+
if (alreadyPublished.has(entry.ref)) continue;
|
|
1814
|
+
alreadyPublished.add(entry.ref);
|
|
1815
|
+
published.push(entry);
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
return published;
|
|
1819
|
+
}
|
|
1820
|
+
/**
|
|
1821
|
+
* Decide one `present_visual` request against the observed committed log.
|
|
1822
|
+
*
|
|
1823
|
+
* This is the SINGLE decision function the Host tool body calls, so the live
|
|
1824
|
+
* path and cold replay cannot diverge. The caller supplies the already-observed
|
|
1825
|
+
* committed events plus the executing call's own identity; the publisher's
|
|
1826
|
+
* durable `tool/call` is located here, never assumed.
|
|
1827
|
+
* @param input - the observed log, the requested references and the publisher
|
|
1828
|
+
* identity.
|
|
1829
|
+
* @returns the receipt to persist, or the verbatim refusal reason.
|
|
1830
|
+
*/
|
|
1831
|
+
function decidePublication(input) {
|
|
1832
|
+
const { sessionId, events, refs, turn, stepStartSeq, callId } = input;
|
|
1833
|
+
const indexed = indexLog(sessionId, events);
|
|
1834
|
+
const stepKey = executingStepKey(events, turn, stepStartSeq);
|
|
1835
|
+
const ids = stepKey === void 0 ? 0 : indexed.stepCallIds.get(stepKey)?.get(callId) ?? 0;
|
|
1836
|
+
if (ids > 1) return {
|
|
1837
|
+
ok: false,
|
|
1838
|
+
reason: `the model response for this step requested "${callId}" ${ids} times; a duplicated call id cannot publish`
|
|
1839
|
+
};
|
|
1840
|
+
const calls = indexed.calls;
|
|
1841
|
+
const publishers = calls.filter((candidate) => candidate.name === "present_visual" && candidate.turn === turn && candidate.stepStartSeq === stepStartSeq && candidate.callId === callId);
|
|
1842
|
+
if (publishers.length !== 1 || publishers[0].ambiguous) return {
|
|
1843
|
+
ok: false,
|
|
1844
|
+
reason: `no unique committed ${PRESENT_VISUAL_TOOL_NAME} call "${callId}" in the current step`
|
|
1845
|
+
};
|
|
1846
|
+
const publisher = publishers[0];
|
|
1847
|
+
const durable = requestedReferences(publisher.arguments);
|
|
1848
|
+
if (durable === void 0) return {
|
|
1849
|
+
ok: false,
|
|
1850
|
+
reason: `the durable ${PRESENT_VISUAL_TOOL_NAME} arguments are not a valid request`
|
|
1851
|
+
};
|
|
1852
|
+
if (durable.length !== refs.length || !durable.every((ref, position) => ref === refs[position])) return {
|
|
1853
|
+
ok: false,
|
|
1854
|
+
reason: "the executing call arguments disagree with the durable tool/call arguments"
|
|
1855
|
+
};
|
|
1856
|
+
const sources = calls.map((call) => qualifySource(call)).filter((source) => source !== void 0);
|
|
1857
|
+
const accepted = [];
|
|
1858
|
+
for (const ref of refs) {
|
|
1859
|
+
const matched = sources.filter((qualified) => qualified.source.ref === ref);
|
|
1860
|
+
if (matched.length > 1) return {
|
|
1861
|
+
ok: false,
|
|
1862
|
+
reason: `visual ref ${ref} is ambiguous: more than one committed source owns it`
|
|
1863
|
+
};
|
|
1864
|
+
const qualified = matched[0];
|
|
1865
|
+
const source = qualified?.source;
|
|
1866
|
+
if (qualified === void 0 || source === void 0) {
|
|
1867
|
+
if (calls.find((candidate) => candidate.ref === ref && candidate.result === void 0) !== void 0) return {
|
|
1868
|
+
ok: false,
|
|
1869
|
+
reason: "Source visual is not committed yet; call present_visual after the generating tool has finished."
|
|
1870
|
+
};
|
|
1871
|
+
return {
|
|
1872
|
+
ok: false,
|
|
1873
|
+
reason: `unknown visual ref ${ref}: no committed ${CHART_TOOL_NAME}/${SVG_TOOL_NAME} result owns it`
|
|
1874
|
+
};
|
|
1875
|
+
}
|
|
1876
|
+
if (source.turn !== turn) return {
|
|
1877
|
+
ok: false,
|
|
1878
|
+
reason: `visual ref ${ref} belongs to turn ${source.turn}, not the current turn ${turn}`
|
|
1879
|
+
};
|
|
1880
|
+
if (source.stepStartSeq === stepStartSeq) return {
|
|
1881
|
+
ok: false,
|
|
1882
|
+
reason: "Call present_visual in a later model step."
|
|
1883
|
+
};
|
|
1884
|
+
if (source.stepStartSeq > stepStartSeq) return {
|
|
1885
|
+
ok: false,
|
|
1886
|
+
reason: `visual ref ${ref} belongs to a later model step`
|
|
1887
|
+
};
|
|
1888
|
+
if (!isPublishableBy(qualified, publisher)) return {
|
|
1889
|
+
ok: false,
|
|
1890
|
+
reason: "Source visual is not committed yet; call present_visual after the generating tool has finished."
|
|
1891
|
+
};
|
|
1892
|
+
accepted.push({ ref });
|
|
1893
|
+
}
|
|
1894
|
+
const count = accepted.length;
|
|
1895
|
+
return {
|
|
1896
|
+
ok: true,
|
|
1897
|
+
receipt: {
|
|
1898
|
+
version: 1,
|
|
1899
|
+
published: accepted
|
|
1900
|
+
},
|
|
1901
|
+
summary: `Selected ${count} visual${count === 1 ? "" : "s"} for presentation.`
|
|
1902
|
+
};
|
|
1903
|
+
}
|
|
1904
|
+
//#endregion
|
|
1905
|
+
//#region src/domain/visual/runtime-status.ts
|
|
1906
|
+
/**
|
|
1907
|
+
* The Host-plane runtime-status contract of the built-in visual tools.
|
|
1908
|
+
*
|
|
1909
|
+
* The contract lives in the domain layer because BOTH the Host row that owns
|
|
1910
|
+
* the three registrations and the Direct config adapter that reports their live
|
|
1911
|
+
* state need it, and `src/runtime/**` may not import `src/app/**`. The three
|
|
1912
|
+
* model-facing tool names are `CHART_TOOL_NAME`, `SVG_TOOL_NAME` and
|
|
1913
|
+
* `PRESENT_VISUAL_TOOL_NAME` in `domain/visual/tools.ts`.
|
|
1914
|
+
*
|
|
1915
|
+
* The status is the Host row's own registration fact — never a second
|
|
1916
|
+
* persisted enable value. The Remote wire exposes no equivalent, so a Remote
|
|
1917
|
+
* read reports the runtime state as unobservable instead of guessing.
|
|
1918
|
+
* @module @xmoon76/dsh-pi-tui/domain/visual/runtime-status
|
|
1919
|
+
*/
|
|
1920
|
+
/** The Host-plane service the visual-tools row provides after it mounts. */
|
|
1921
|
+
const VISUAL_TOOLS_STATUS_SERVICE = "piTuiVisualToolsStatus";
|
|
1922
|
+
//#endregion
|
|
1923
|
+
export { chartValueRows as A, humanFacingVisualResult as B, chartArgsProblem as C, chartHumanText as D, chartFactFromArgs as E, SVG_RASTER_TIMEOUT_MS as F, CHART_TOOL_NAME as I, PRESENT_VISUAL_TOOL_NAME as L, SVG_MAX_PNG_BYTES as M, SVG_MAX_RASTER_PIXELS as N, chartProjection as O, SVG_MAX_RASTER_SIDE as P, SVG_TOOL_NAME as R, svgFactFromArgs as S, chartDisplayTitle as T, isVisualToolName as V, authorizeSvg as _, isModelOnlyReplacement as a, svgDetailRows as b, mergeVisualOriginSpans as c, visualFactLine as d, visualParts as f, visualReferenceLine as g, visualReference as h, decidePublication as i, admitSvg as j, chartTextRows as k, originSessionIdAt as l, visualPartsFromText as m, asVisualSessionEvents as n, parsePresentVisualArguments as o, visualPartsForStatus as p, collectPublishedVisuals as r, intersectVisualOriginSpans as s, VISUAL_TOOLS_STATUS_SERVICE as t, ownVisualOriginSpans as u, svgArgsProblem as v, chartContentBlocks as w, svgDigest as x, svgContentBlocks as y, VISUAL_PUBLISHED_PREFIX as z };
|