@meshad/sdk 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +107 -2
- package/examples/fake-agent.js +65 -0
- package/examples/lib/demo-network.js +52 -0
- package/examples/stream.js +39 -0
- package/index.d.ts +271 -0
- package/index.js +521 -0
- package/lib/ads.js +92 -0
- package/lib/creative.js +8 -0
- package/lib/env.js +99 -0
- package/lib/fsm.js +201 -0
- package/lib/net.js +33 -0
- package/lib/render.js +515 -0
- package/lib/signature.js +57 -0
- package/lib/telemetry.js +96 -0
- package/lib/terminal.js +61 -0
- package/package.json +28 -4
package/lib/render.js
ADDED
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vendored copy of apps/cli/src/render.js — the reference terminal renderer.
|
|
3
|
+
*
|
|
4
|
+
* The SDK draws ads with the EXACT code the official CLI uses (bottom-row
|
|
5
|
+
* panel fenced by a scroll region, SGR-only sanitization, mandatory
|
|
6
|
+
* `sponsored` label, synchronous clear). Do not edit here: change
|
|
7
|
+
* apps/cli/src/render.js and run `make sync-vendored`;
|
|
8
|
+
* packages/sdk/test/vendor-sync.test.js fails on any drift.
|
|
9
|
+
*/
|
|
10
|
+
'use strict';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Footer renderer — 1 to 6 rows depending on format. Fail-closed: any
|
|
14
|
+
* problem (no TTY, weird terminal, write error) means NO ad — never an
|
|
15
|
+
* exception for the caller, never a corrupted screen.
|
|
16
|
+
*
|
|
17
|
+
* Render: save cursor (ESC 7) → jump to the last N rows → write each line
|
|
18
|
+
* → restore (ESC 8). Clear: same dance, erase exactly the N rows that were
|
|
19
|
+
* last drawn (tracked in `activeHeight`) — both are a single synchronous
|
|
20
|
+
* write per call, clear completes in well under 100ms.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const {
|
|
24
|
+
FG_CODES, MAX_ART_LINES, displayWidth, truncateToWidth, renderLine,
|
|
25
|
+
validateFrames, sliceSpans, DEFAULT_HOLD_MS,
|
|
26
|
+
} = require('./creative');
|
|
27
|
+
|
|
28
|
+
const ESC = '\x1b';
|
|
29
|
+
const SAVE = `${ESC}7`;
|
|
30
|
+
const RESTORE = `${ESC}8`;
|
|
31
|
+
|
|
32
|
+
const COLOR_CODES = { dim: '2', green: '32', cyan: '36', magenta: '35', yellow: '33', blue: '34', red: '31' };
|
|
33
|
+
|
|
34
|
+
/** Text formats stay at 5 rows; `ascii_panel` buys one more for its art. */
|
|
35
|
+
const MAX_ROWS_TEXT = 5;
|
|
36
|
+
const MAX_ROWS_ART = MAX_ART_LINES + 1; // art + the mandatory sponsored row
|
|
37
|
+
|
|
38
|
+
/** Entrance reveal: ~300ms total, then the ad holds still for the rest of the wait. */
|
|
39
|
+
const REVEAL_STEPS = 12;
|
|
40
|
+
const REVEAL_FRAME_MS = 25;
|
|
41
|
+
|
|
42
|
+
/** Art needs room to read as art. Below this the ad degrades to one text line. */
|
|
43
|
+
const MIN_COLS_ART = 60;
|
|
44
|
+
// A framed panel is at most 8 rows; 12 leaves it room plus host breathing
|
|
45
|
+
// space. (Was 20 — a pre-panel threshold that degraded perfectly viable
|
|
46
|
+
// terminals to the flattened one-liner.)
|
|
47
|
+
const MIN_ROWS_ART = 12;
|
|
48
|
+
|
|
49
|
+
function colorCode(color) {
|
|
50
|
+
return COLOR_CODES[color] || COLOR_CODES.dim;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Strip control/newline characters and clamp width — never trust ad content blindly. */
|
|
54
|
+
function sanitizeLine(s, maxWidth) {
|
|
55
|
+
return truncateToWidth(
|
|
56
|
+
String(s ?? '').replace(/[\r\n\x00-\x08\x0b-\x1f]/g, ' '),
|
|
57
|
+
Math.max(0, maxWidth),
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
class LineRenderer {
|
|
62
|
+
constructor(stream = process.stdout) {
|
|
63
|
+
this.stream = stream;
|
|
64
|
+
this.active = false;
|
|
65
|
+
this.activeHeight = 0;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
get enabled() {
|
|
69
|
+
return !!(this.stream && this.stream.isTTY);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Draw `payload` — a single string (legacy text_line callers) or an array
|
|
74
|
+
* of already-ANSI-formatted lines (see formatAd) — on the bottom rows of
|
|
75
|
+
* the screen. Returns true only if actually drawn.
|
|
76
|
+
*/
|
|
77
|
+
render(payload) {
|
|
78
|
+
try {
|
|
79
|
+
if (!this.enabled) return false;
|
|
80
|
+
const lines = Array.isArray(payload) ? payload : [payload];
|
|
81
|
+
const cols = this.stream.columns || 80;
|
|
82
|
+
const rows = this.stream.rows || 24;
|
|
83
|
+
const height = Math.min(lines.length, rows - 1, MAX_ROWS_ART + 2); // +2: panel borders
|
|
84
|
+
if (height <= 0) return false;
|
|
85
|
+
|
|
86
|
+
// Anti-flicker, two layers: (1) overwrite-with-padding instead of
|
|
87
|
+
// erase-then-repaint — a cleared line must never be visible between
|
|
88
|
+
// frames of an animation; the trailing ESC[K only clears what the
|
|
89
|
+
// padding did not reach, after the content is already painted.
|
|
90
|
+
// (2) DEC synchronized output (mode 2026): terminals that support it
|
|
91
|
+
// apply the whole frame atomically; the rest ignore it harmlessly.
|
|
92
|
+
let out = `${ESC}[?2026h`;
|
|
93
|
+
if (!this.active) {
|
|
94
|
+
// First draw: push the host's current line (prompt, spinner) above the
|
|
95
|
+
// ad zone and fence scrolling out of it with a scroll region (DECSTBM).
|
|
96
|
+
// Without this, the shell's own bottom line sits inside the panel and
|
|
97
|
+
// every frame paints over it — "the Thinking… spinner vanished".
|
|
98
|
+
out += `${'\n'.repeat(height)}${ESC}[${height}A`;
|
|
99
|
+
out += `${SAVE}${ESC}[1;${Math.max(1, rows - height)}r${RESTORE}`;
|
|
100
|
+
}
|
|
101
|
+
out += SAVE;
|
|
102
|
+
for (let i = 0; i < height; i++) {
|
|
103
|
+
const targetRow = rows - height + 1 + i;
|
|
104
|
+
const { text: raw, width } = sanitizeAnsiLine(String(lines[i] ?? ''), cols - 1);
|
|
105
|
+
const pad = ' '.repeat(Math.max(0, cols - 1 - width));
|
|
106
|
+
out += `${ESC}[${targetRow};1H${raw}${ESC}[0m${pad}${ESC}[K`;
|
|
107
|
+
}
|
|
108
|
+
out += `${RESTORE}${ESC}[?2026l`;
|
|
109
|
+
this.stream.write(out);
|
|
110
|
+
this.active = true;
|
|
111
|
+
this.activeHeight = height;
|
|
112
|
+
return true;
|
|
113
|
+
} catch {
|
|
114
|
+
this.active = false;
|
|
115
|
+
this.activeHeight = 0;
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Erase every row last drawn. Idempotent, synchronous, <100ms. */
|
|
121
|
+
clear() {
|
|
122
|
+
try {
|
|
123
|
+
if (!this.enabled || !this.active) {
|
|
124
|
+
this.active = false;
|
|
125
|
+
this.activeHeight = 0;
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
const rows = this.stream.rows || 24;
|
|
129
|
+
let out = `${ESC}[?2026h${SAVE}`;
|
|
130
|
+
for (let i = 0; i < this.activeHeight; i++) {
|
|
131
|
+
out += `${ESC}[${rows - this.activeHeight + 1 + i};1H${ESC}[2K`;
|
|
132
|
+
}
|
|
133
|
+
// Release the scroll-region fence (DECSTBM homes the cursor, so this
|
|
134
|
+
// stays inside the SAVE/RESTORE bracket).
|
|
135
|
+
out += `${ESC}[r${RESTORE}${ESC}[?2026l`;
|
|
136
|
+
this.stream.write(out);
|
|
137
|
+
} catch {
|
|
138
|
+
/* fail-closed: nothing to do */
|
|
139
|
+
}
|
|
140
|
+
this.active = false;
|
|
141
|
+
this.activeHeight = 0;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** SGR-only escape: \x1b[ <digits and semicolons> m. Nothing else is an escape. */
|
|
146
|
+
const SGR_RE = /\x1b\[[0-9;]*m/g;
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Last line of defence before bytes reach the terminal. Styling escapes we
|
|
150
|
+
* generated (SGR, i.e. colour/bold/reset) survive; every other escape sequence
|
|
151
|
+
* and control character is erased, so nothing can move the cursor, clear the
|
|
152
|
+
* screen, repaint the palette or open a hyperlink. Width is measured on the
|
|
153
|
+
* visible text only — escapes occupy no columns.
|
|
154
|
+
*/
|
|
155
|
+
function sanitizeAnsiLine(line, maxWidth) {
|
|
156
|
+
const s = String(line ?? '');
|
|
157
|
+
const styles = [];
|
|
158
|
+
// Park the legitimate SGR codes, scrub what is left, then put them back.
|
|
159
|
+
const parked = s.replace(SGR_RE, (m) => {
|
|
160
|
+
styles.push(m);
|
|
161
|
+
return '\x00SGR\x01';
|
|
162
|
+
});
|
|
163
|
+
const scrubbed = parked.replace(/[\r\n\x1b\x02-\x08\x0b-\x1f\x7f]/g, ' ');
|
|
164
|
+
|
|
165
|
+
let width = 0;
|
|
166
|
+
let out = '';
|
|
167
|
+
let i = 0;
|
|
168
|
+
const parts = scrubbed.split('\x00SGR\x01');
|
|
169
|
+
for (const part of parts) {
|
|
170
|
+
const room = Math.max(0, maxWidth - width);
|
|
171
|
+
const text = truncateToWidth(part, room);
|
|
172
|
+
out += text;
|
|
173
|
+
width += displayWidth(text);
|
|
174
|
+
if (i < styles.length) out += styles[i++];
|
|
175
|
+
}
|
|
176
|
+
while (i < styles.length) out += styles[i++]; // keep any trailing reset
|
|
177
|
+
return { text: out, width };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Compose "content <cta · sponsored · hint>" into one line, reserving the
|
|
182
|
+
* suffix's width FIRST and spending what is left on the content.
|
|
183
|
+
*
|
|
184
|
+
* Truncating from the right — which is what a naive clamp does — eats the
|
|
185
|
+
* sponsored label on a narrow terminal and renders an undisclosed ad. The
|
|
186
|
+
* disclosure is not the part that gives way. If the suffix alone does not fit,
|
|
187
|
+
* there is no honest ad to draw, so we return null and nothing is shown.
|
|
188
|
+
*/
|
|
189
|
+
function composeWithSuffix(content, suffix, maxWidth) {
|
|
190
|
+
const suffixWidth = displayWidth(suffix);
|
|
191
|
+
if (suffixWidth > maxWidth) return null; // cannot disclose => do not advertise
|
|
192
|
+
const room = maxWidth - suffixWidth - 2; // 2 = the separating spaces
|
|
193
|
+
if (room <= 0) return suffix;
|
|
194
|
+
|
|
195
|
+
const clean = sanitizeLine(content, Infinity);
|
|
196
|
+
if (displayWidth(clean) <= room) return clean ? `${clean} ${suffix}` : suffix;
|
|
197
|
+
|
|
198
|
+
// Truncated: mark it. A phrase that just stops mid-word reads as a rendering
|
|
199
|
+
// bug; an ellipsis reads as a deliberate cut.
|
|
200
|
+
const body = sanitizeLine(clean, Math.max(0, room - 1)).replace(/[\s.,;:—-]+$/, '');
|
|
201
|
+
return body ? `${body}… ${suffix}` : suffix;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Render an ad into 1-6 already-colored, ANSI-ready lines, per its format:
|
|
206
|
+
* text_line — one line: emoji + text + cta + sponsored label.
|
|
207
|
+
* text_block — 2-4 lines: content lines, then the cta/sponsored line.
|
|
208
|
+
* rich_panel — a bordered box (┌─┐ / │ │ / └─┘) around the same content.
|
|
209
|
+
* ascii_panel — multi-colour art: each line is an array of {t,fg,bg,bold}
|
|
210
|
+
* spans, styled by @meshad/creative. The advertiser never
|
|
211
|
+
* supplies an escape sequence; we synthesize every one.
|
|
212
|
+
* The `sponsored` label and pause hint are non-negotiable and always present.
|
|
213
|
+
*/
|
|
214
|
+
/** The art an ad shows when standing still: its flat art, or its first frame. */
|
|
215
|
+
function firstArt(render) {
|
|
216
|
+
if (Array.isArray(render.art_lines) && render.art_lines.length) return render.art_lines;
|
|
217
|
+
const frames = render.frames;
|
|
218
|
+
if (Array.isArray(frames) && frames.length && Array.isArray(frames[0].art_lines)) return frames[0].art_lines;
|
|
219
|
+
return [];
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function formatAd(ad, cols = 80, rows = 24) {
|
|
223
|
+
const r = (ad && ad.render) || {};
|
|
224
|
+
const code = colorCode(r.color);
|
|
225
|
+
const emojiPrefix = r.emoji ? `${r.emoji} ` : '';
|
|
226
|
+
const suffix = `${r.cta || ''} · sponsored · (meshad pause)`;
|
|
227
|
+
const maxWidth = Math.max(20, cols - 1);
|
|
228
|
+
const contentLines = (Array.isArray(r.lines) && r.lines.length ? r.lines : [r.text || '']).slice(0, 3);
|
|
229
|
+
const wrap = (s) => `\x1b[${code}m${s}`;
|
|
230
|
+
|
|
231
|
+
const format = ad && ad.format;
|
|
232
|
+
|
|
233
|
+
if (format === 'ascii_panel') {
|
|
234
|
+
const art0 = firstArt(r);
|
|
235
|
+
// Degrade to a single text line on a terminal too small for the art to read.
|
|
236
|
+
if (cols >= MIN_COLS_ART && rows >= MIN_ROWS_ART && art0.length) {
|
|
237
|
+
const artInner = Math.min(
|
|
238
|
+
maxWidth - 4,
|
|
239
|
+
Math.max(20, ...art0.slice(0, MAX_ART_LINES).map((line) =>
|
|
240
|
+
(Array.isArray(line) ? line : []).reduce((w, sp) => w + displayWidth((sp && sp.t) || ''), 0)),
|
|
241
|
+
displayWidth(suffix)),
|
|
242
|
+
);
|
|
243
|
+
const art = art0
|
|
244
|
+
.slice(0, MAX_ART_LINES)
|
|
245
|
+
.map((line) => renderLine(line, artInner));
|
|
246
|
+
return framePanel([...art, wrap(sanitizeLine(suffix, artInner))], artInner, code);
|
|
247
|
+
}
|
|
248
|
+
// Flattening keeps only word-bearing spans: bar/box glyphs (▇░█─╱╲…) are
|
|
249
|
+
// meaningless squashed into one line and read as garbage.
|
|
250
|
+
const GLYPH_ONLY = /^[\s▁▂▃▄▅▆▇█░▒▓─│╭╮╰╯╱╲◉●▮▲✓☁~≈]*$/;
|
|
251
|
+
const flat = art0
|
|
252
|
+
.map((line) => (Array.isArray(line) ? line : [])
|
|
253
|
+
.map((s) => ((s && s.t) || ''))
|
|
254
|
+
.filter((tx) => !GLYPH_ONLY.test(tx))
|
|
255
|
+
.join(''))
|
|
256
|
+
.join(' ')
|
|
257
|
+
.replace(/\s+/g, ' ')
|
|
258
|
+
.trim();
|
|
259
|
+
const composed = composeWithSuffix(`${emojiPrefix}${flat || contentLines[0] || ''}`, suffix, maxWidth);
|
|
260
|
+
return composed === null ? [] : [wrap(composed)];
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (format === 'rich_panel' && cols >= 40) {
|
|
264
|
+
// Budget: top border + content + suffix + bottom border must fit the cap.
|
|
265
|
+
const bodyBudget = MAX_ROWS_TEXT - 3; // 2 borders + suffix row
|
|
266
|
+
const rawRows = [
|
|
267
|
+
...contentLines.slice(0, bodyBudget).map((l, i) => `${i === 0 ? emojiPrefix : ''}${l}`),
|
|
268
|
+
suffix,
|
|
269
|
+
];
|
|
270
|
+
const innerWidth = Math.min(maxWidth - 4, Math.max(...rawRows.map((l) => displayWidth(l))));
|
|
271
|
+
const pad = (s) => {
|
|
272
|
+
const clipped = sanitizeLine(s, innerWidth);
|
|
273
|
+
return ` ${clipped}${' '.repeat(Math.max(0, innerWidth - displayWidth(clipped)))} `;
|
|
274
|
+
};
|
|
275
|
+
const top = `┌${'─'.repeat(innerWidth + 2)}┐`;
|
|
276
|
+
const bottom = `└${'─'.repeat(innerWidth + 2)}┘`;
|
|
277
|
+
const panelRows = [top, ...rawRows.map((l) => `│${pad(l)}│`), bottom];
|
|
278
|
+
return panelRows.map(wrap);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (format === 'text_block' || format === 'rich_panel' /* too narrow: degrade */) {
|
|
282
|
+
const blockRows = [...contentLines.map((l, i) => `${i === 0 ? emojiPrefix : ''}${l}`), suffix].map((l) =>
|
|
283
|
+
sanitizeLine(l, maxWidth),
|
|
284
|
+
);
|
|
285
|
+
return blockRows.map(wrap);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// text_line (default, and the fallback for any unknown future format)
|
|
289
|
+
const line = composeWithSuffix(`${emojiPrefix}${contentLines[0] || ''}`, suffix, maxWidth);
|
|
290
|
+
return line === null ? [] : [wrap(line)];
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Frames for the entrance reveal: the art wipes in left-to-right, then holds.
|
|
296
|
+
*
|
|
297
|
+
* The creative is untouched — these are derived client-side from the same signed
|
|
298
|
+
* spans by asking renderLine for a growing width, so animating costs no payload,
|
|
299
|
+
* no second signature and no moderation surface. Nothing is animated after the
|
|
300
|
+
* reveal completes: the ad occupies idle time, it does not compete for attention
|
|
301
|
+
* with what the developer is actually waiting for.
|
|
302
|
+
*
|
|
303
|
+
* The sponsored row is drawn in full from frame one. Disclosure is never
|
|
304
|
+
* partially revealed, not even for 300ms.
|
|
305
|
+
*
|
|
306
|
+
* @returns {string[][]} one entry per frame; a single entry means "do not animate".
|
|
307
|
+
*/
|
|
308
|
+
function revealFrames(ad, cols = 80, rows = 24, steps = REVEAL_STEPS) {
|
|
309
|
+
const final = formatAd(ad, cols, rows);
|
|
310
|
+
const r = (ad && ad.render) || {};
|
|
311
|
+
|
|
312
|
+
// Only ascii_panel animates, and only when it rendered as art (not degraded
|
|
313
|
+
// to the one-line fallback, where there is nothing to wipe in).
|
|
314
|
+
const isArt = ad && ad.format === 'ascii_panel' && final.length > 1;
|
|
315
|
+
if (!isArt) return [final];
|
|
316
|
+
|
|
317
|
+
const maxWidth = Math.max(20, cols - 1);
|
|
318
|
+
const artSpans = firstArt(r).slice(0, MAX_ART_LINES);
|
|
319
|
+
if (!artSpans.length) return [final];
|
|
320
|
+
const widest = Math.max(
|
|
321
|
+
1,
|
|
322
|
+
...artSpans.map((line) =>
|
|
323
|
+
(Array.isArray(line) ? line : []).reduce((w, sp) => w + displayWidth((sp && sp.t) || ''), 0),
|
|
324
|
+
),
|
|
325
|
+
);
|
|
326
|
+
// The panel is at its full size from the very first frame — only the art
|
|
327
|
+
// inside grows. Same width formula as formatAd, so the reveal's final frame
|
|
328
|
+
// can be the static render itself, byte for byte.
|
|
329
|
+
const code = colorCode(r.color);
|
|
330
|
+
const suffixPlain = `${r.cta || ''} · sponsored · (meshad pause)`;
|
|
331
|
+
const innerWidth = Math.min(maxWidth - 4, Math.max(20, widest, displayWidth(suffixPlain)));
|
|
332
|
+
const suffixRow = `\x1b[${code}m${sanitizeLine(suffixPlain, innerWidth)}`;
|
|
333
|
+
const target = Math.min(widest, innerWidth);
|
|
334
|
+
const frameCount = Math.max(1, Math.min(steps, target));
|
|
335
|
+
|
|
336
|
+
const frames = [];
|
|
337
|
+
for (let i = 1; i < frameCount; i++) {
|
|
338
|
+
const width = Math.ceil((target * i) / frameCount);
|
|
339
|
+
frames.push(drawFrame(artSpans.map((line) => sliceSpans(line, 0, width)), suffixRow, innerWidth, code));
|
|
340
|
+
}
|
|
341
|
+
frames.push(final);
|
|
342
|
+
return frames;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
/* ── animation ────────────────────────────────────────────────────────────── */
|
|
347
|
+
|
|
348
|
+
/** Sub-frame durations for the transitions the client draws between frames. */
|
|
349
|
+
const WIPE_STEP_MS = 22;
|
|
350
|
+
const WIPE_STEPS = 14;
|
|
351
|
+
const TYPE_STEP_MS = 18;
|
|
352
|
+
|
|
353
|
+
/** Style one art line, plus the fixed sponsored row, into a drawable frame. */
|
|
354
|
+
/** Visible width of an already-ANSI-styled row. */
|
|
355
|
+
function visibleWidth(s) {
|
|
356
|
+
return displayWidth(String(s).replace(SGR_RE, ''));
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* Wrap fully-rendered rows in a rounded panel. Presentation only — the border
|
|
361
|
+
* is drawn by the client from its own glyphs (no advertiser bytes, outside the
|
|
362
|
+
* signature like every other pixel of chrome). It exists so an ad reads as a
|
|
363
|
+
* clearly bounded object on screen, never as loose terminal output.
|
|
364
|
+
*/
|
|
365
|
+
function framePanel(rows, innerWidth, code) {
|
|
366
|
+
const b = (s) => `\x1b[${code}m${s}\x1b[0m`;
|
|
367
|
+
const top = b(`╭${'─'.repeat(innerWidth + 2)}╮`);
|
|
368
|
+
const bottom = b(`╰${'─'.repeat(innerWidth + 2)}╯`);
|
|
369
|
+
const body = rows.map((row) => {
|
|
370
|
+
const pad = ' '.repeat(Math.max(0, innerWidth - visibleWidth(row)));
|
|
371
|
+
return `${b('│')} ${row}\x1b[0m${pad} ${b('│')}`;
|
|
372
|
+
});
|
|
373
|
+
return [top, ...body, bottom];
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function drawFrame(artSpans, suffixRow, innerWidth, code) {
|
|
377
|
+
return framePanel([...artSpans.map((line) => renderLine(line, innerWidth)), suffixRow], innerWidth, code);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Expand an animated creative into a flat timeline of {lines, ms} steps.
|
|
382
|
+
*
|
|
383
|
+
* Frames come from the creative and are covered by its signature; the steps
|
|
384
|
+
* BETWEEN them (wipe columns, typewriter characters) are derived here from those
|
|
385
|
+
* same signed spans, so a transition adds nothing to the payload and nothing to
|
|
386
|
+
* moderation's surface.
|
|
387
|
+
*
|
|
388
|
+
* The sponsored row is rebuilt into every single step. There is no sub-frame,
|
|
389
|
+
* transitional or otherwise, in which the ad is on screen undisclosed.
|
|
390
|
+
*
|
|
391
|
+
* @returns {{ steps: Array<{lines: string[], ms: number}>, loop: boolean }}
|
|
392
|
+
*/
|
|
393
|
+
function buildTimeline(ad, cols = 80, rows = 24) {
|
|
394
|
+
const r = (ad && ad.render) || {};
|
|
395
|
+
const staticLines = formatAd(ad, cols, rows);
|
|
396
|
+
|
|
397
|
+
const isArt = ad && ad.format === 'ascii_panel' && staticLines.length > 1;
|
|
398
|
+
if (!isArt) return { steps: [{ lines: staticLines, ms: 0 }], loop: false };
|
|
399
|
+
|
|
400
|
+
const { frames } = validateFrames(r.frames ? { frames: r.frames } : { art_lines: r.art_lines || [] });
|
|
401
|
+
if (!frames.length) return { steps: [{ lines: staticLines, ms: 0 }], loop: false };
|
|
402
|
+
|
|
403
|
+
const maxWidth = Math.max(20, cols - 1);
|
|
404
|
+
const transition = r.transition || 'cut';
|
|
405
|
+
const loop = !!r.loop && frames.length > 1;
|
|
406
|
+
|
|
407
|
+
const widthOf = (art) =>
|
|
408
|
+
Math.max(0, ...art.map((line) => (Array.isArray(line) ? line : []).reduce(
|
|
409
|
+
(w, sp) => w + displayWidth((sp && sp.t) || ''), 0)));
|
|
410
|
+
|
|
411
|
+
// The panel width is fixed across every step of every frame — a border that
|
|
412
|
+
// resizes mid-typewriter reads as glitching, not animating.
|
|
413
|
+
const code = colorCode(r.color);
|
|
414
|
+
const suffixPlain = `${r.cta || ''} · sponsored · (meshad pause)`;
|
|
415
|
+
const innerWidth = Math.min(
|
|
416
|
+
maxWidth - 4,
|
|
417
|
+
Math.max(20, ...frames.map((f) => widthOf(f.art_lines.slice(0, MAX_ART_LINES))), displayWidth(suffixPlain)),
|
|
418
|
+
);
|
|
419
|
+
const suffixRow = `\x1b[${code}m${sanitizeLine(suffixPlain, innerWidth)}`;
|
|
420
|
+
|
|
421
|
+
const steps = [];
|
|
422
|
+
|
|
423
|
+
frames.forEach((frame, index) => {
|
|
424
|
+
const art = frame.art_lines.slice(0, MAX_ART_LINES);
|
|
425
|
+
const previous = index > 0 ? frames[index - 1].art_lines.slice(0, MAX_ART_LINES) : null;
|
|
426
|
+
const target = Math.min(Math.max(widthOf(art), previous ? widthOf(previous) : 0), maxWidth);
|
|
427
|
+
|
|
428
|
+
if (transition === 'wipe' && target > 0) {
|
|
429
|
+
// The incoming frame takes the left columns while the outgoing one still
|
|
430
|
+
// holds the right — a real wipe, not a reveal over emptiness.
|
|
431
|
+
const stepCount = Math.max(1, Math.min(WIPE_STEPS, target));
|
|
432
|
+
for (let i = 1; i <= stepCount; i++) {
|
|
433
|
+
const edge = Math.ceil((target * i) / stepCount);
|
|
434
|
+
const composited = art.map((line, row) => {
|
|
435
|
+
const incoming = sliceSpans(line, 0, edge);
|
|
436
|
+
const outgoing = previous ? sliceSpans(previous[row] || [], edge, maxWidth) : [];
|
|
437
|
+
const gap = Math.max(0, edge - incoming.reduce((w, sp) => w + displayWidth(sp.t), 0));
|
|
438
|
+
return [...incoming, ...(gap ? [{ t: ' '.repeat(gap) }] : []), ...outgoing];
|
|
439
|
+
});
|
|
440
|
+
steps.push({ lines: drawFrame(composited, suffixRow, innerWidth, code), ms: WIPE_STEP_MS });
|
|
441
|
+
}
|
|
442
|
+
} else if (transition === 'typewriter' && target > 0) {
|
|
443
|
+
const width = Math.min(widthOf(art), maxWidth);
|
|
444
|
+
for (let w = 1; w <= width; w++) {
|
|
445
|
+
steps.push({ lines: drawFrame(art.map((l) => sliceSpans(l, 0, w)), suffixRow, innerWidth, code), ms: TYPE_STEP_MS });
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
steps.push({ lines: drawFrame(art, suffixRow, innerWidth, code), ms: frame.hold_ms || DEFAULT_HOLD_MS });
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
return { steps, loop };
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Plays a timeline into a LineRenderer. Single-shot by default; `loop` repeats
|
|
457
|
+
* until stop(). Stopping is immediate and idempotent — the FSM calls it the
|
|
458
|
+
* instant the agent's answer lands, and nothing may outlive that.
|
|
459
|
+
*/
|
|
460
|
+
class Animator {
|
|
461
|
+
constructor(renderer, { setTimeoutFn = setTimeout, clearTimeoutFn = clearTimeout } = {}) {
|
|
462
|
+
this.renderer = renderer;
|
|
463
|
+
this.setTimeoutFn = setTimeoutFn;
|
|
464
|
+
this.clearTimeoutFn = clearTimeoutFn;
|
|
465
|
+
this.timer = null;
|
|
466
|
+
this.stopped = false;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** Draw `steps` in order. Returns true if the first frame was drawn. */
|
|
470
|
+
play({ steps, loop }) {
|
|
471
|
+
this.stopped = false;
|
|
472
|
+
if (!steps || !steps.length) return false;
|
|
473
|
+
|
|
474
|
+
let i = 0;
|
|
475
|
+
const tick = () => {
|
|
476
|
+
if (this.stopped) return;
|
|
477
|
+
const step = steps[i];
|
|
478
|
+
this.renderer.render(step.lines);
|
|
479
|
+
i++;
|
|
480
|
+
if (i >= steps.length) {
|
|
481
|
+
if (!loop) return;
|
|
482
|
+
i = 0;
|
|
483
|
+
}
|
|
484
|
+
if (step.ms > 0) {
|
|
485
|
+
this.timer = this.setTimeoutFn(tick, step.ms);
|
|
486
|
+
if (this.timer && typeof this.timer.unref === 'function') this.timer.unref();
|
|
487
|
+
}
|
|
488
|
+
};
|
|
489
|
+
|
|
490
|
+
const drawn = this.renderer.render(steps[0].lines);
|
|
491
|
+
if (!drawn) return false;
|
|
492
|
+
i = 1;
|
|
493
|
+
if (steps.length > 1 || loop) {
|
|
494
|
+
this.timer = this.setTimeoutFn(tick, steps[0].ms || DEFAULT_HOLD_MS);
|
|
495
|
+
if (this.timer && typeof this.timer.unref === 'function') this.timer.unref();
|
|
496
|
+
}
|
|
497
|
+
return true;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** Halt playback and erase. Safe to call at any time, any number of times. */
|
|
501
|
+
stop() {
|
|
502
|
+
this.stopped = true;
|
|
503
|
+
if (this.timer) {
|
|
504
|
+
this.clearTimeoutFn(this.timer);
|
|
505
|
+
this.timer = null;
|
|
506
|
+
}
|
|
507
|
+
this.renderer.clear();
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
module.exports = {
|
|
512
|
+
LineRenderer, formatAd, revealFrames, buildTimeline, Animator, colorCode, COLOR_CODES, FG_CODES,
|
|
513
|
+
REVEAL_STEPS, REVEAL_FRAME_MS,
|
|
514
|
+
MAX_ROWS_TEXT, MAX_ROWS_ART, MIN_COLS_ART, MIN_ROWS_ART,
|
|
515
|
+
};
|
package/lib/signature.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vendored copy of apps/cli/src/signature.js — Ed25519 ad verification.
|
|
3
|
+
*
|
|
4
|
+
* Same canonical bytes as the CLI and the API signer, so the SDK accepts
|
|
5
|
+
* exactly what the CLI accepts (including signed ascii_panel art/frames).
|
|
6
|
+
* Do not edit here: change apps/cli/src/signature.js and run
|
|
7
|
+
* `make sync-vendored`; packages/sdk/test/vendor-sync.test.js fails on drift.
|
|
8
|
+
*/
|
|
9
|
+
'use strict';
|
|
10
|
+
|
|
11
|
+
const crypto = require('node:crypto');
|
|
12
|
+
|
|
13
|
+
/** Canonical JSON over the signed fields — key order is part of the contract. */
|
|
14
|
+
function canonicalAdJson(ad) {
|
|
15
|
+
const render = ad.render || {};
|
|
16
|
+
return JSON.stringify({
|
|
17
|
+
ad_id: ad.ad_id,
|
|
18
|
+
campaign_id: ad.campaign_id,
|
|
19
|
+
format: ad.format,
|
|
20
|
+
min_wait_ms: ad.min_wait_ms,
|
|
21
|
+
render: {
|
|
22
|
+
text: render.text,
|
|
23
|
+
lines: render.lines,
|
|
24
|
+
cta: render.cta,
|
|
25
|
+
color: render.color,
|
|
26
|
+
emoji: render.emoji ?? null,
|
|
27
|
+
// Undefined for text formats (omitted by JSON.stringify, so their bytes
|
|
28
|
+
// are unchanged); for ascii_panel the art is signed with the rest, and a
|
|
29
|
+
// pack that tampers with a single span fails verification.
|
|
30
|
+
art_lines: render.art_lines,
|
|
31
|
+
frames: render.frames,
|
|
32
|
+
transition: render.transition,
|
|
33
|
+
loop: render.loop,
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** True iff ad.signature is a valid Ed25519 signature by publicKeyB64 (DER-SPKI). */
|
|
39
|
+
function verifyAd(ad, publicKeyB64) {
|
|
40
|
+
try {
|
|
41
|
+
const key = crypto.createPublicKey({
|
|
42
|
+
key: Buffer.from(publicKeyB64, 'base64'),
|
|
43
|
+
format: 'der',
|
|
44
|
+
type: 'spki',
|
|
45
|
+
});
|
|
46
|
+
return crypto.verify(
|
|
47
|
+
null,
|
|
48
|
+
Buffer.from(canonicalAdJson(ad), 'utf8'),
|
|
49
|
+
key,
|
|
50
|
+
Buffer.from(String(ad.signature || ''), 'base64')
|
|
51
|
+
);
|
|
52
|
+
} catch {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
module.exports = { canonicalAdJson, verifyAd };
|
package/lib/telemetry.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* In-memory telemetry queue.
|
|
5
|
+
*
|
|
6
|
+
* - every event is validated against @meshad/schema BEFORE it is queued; an
|
|
7
|
+
* out-of-contract event is an SDK bug, so enqueue() throws;
|
|
8
|
+
* - batching: flush when 20 events are queued or every 30s, whichever first;
|
|
9
|
+
* - delivery: POST /v1/telemetry/events, retried with exponential backoff +
|
|
10
|
+
* jitter (max 5 attempts); events leave the queue only on 202 (or on a 4xx,
|
|
11
|
+
* which can never succeed on retry); offline they stay queued;
|
|
12
|
+
* - bounded: past MAX_QUEUE the oldest events are dropped — an SDK that is
|
|
13
|
+
* offline for days must not grow without limit inside someone else's app;
|
|
14
|
+
* - single flight: concurrent flush() calls share one run, so a batch is
|
|
15
|
+
* never sent twice by the SDK itself.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const { validateEvent, validateBatch } = require('@meshad/schema');
|
|
19
|
+
|
|
20
|
+
const BATCH_MAX = 20;
|
|
21
|
+
const BATCH_INTERVAL_MS = 30000;
|
|
22
|
+
const MAX_RETRIES = 5;
|
|
23
|
+
const MAX_QUEUE = 1000;
|
|
24
|
+
const SEND_MAX = 100; // the API's per-request ceiling
|
|
25
|
+
|
|
26
|
+
class TelemetryQueue {
|
|
27
|
+
constructor({ apiUrl, egress, backoffBaseMs = 250, timeoutMs = 3000 }) {
|
|
28
|
+
this.url = `${apiUrl}/v1/telemetry/events`;
|
|
29
|
+
this.egress = egress;
|
|
30
|
+
this.backoffBaseMs = backoffBaseMs;
|
|
31
|
+
this.timeoutMs = timeoutMs;
|
|
32
|
+
this.queue = [];
|
|
33
|
+
this.dropped = 0;
|
|
34
|
+
this._flushing = null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
enqueue(ev) {
|
|
38
|
+
const check = validateEvent(ev);
|
|
39
|
+
if (!check.ok) throw new Error(`schema violation (SDK bug): ${check.errors.join('; ')}`);
|
|
40
|
+
this.queue.push(ev);
|
|
41
|
+
if (this.queue.length > MAX_QUEUE) {
|
|
42
|
+
const excess = this.queue.length - MAX_QUEUE;
|
|
43
|
+
this.queue.splice(0, excess);
|
|
44
|
+
this.dropped += excess;
|
|
45
|
+
}
|
|
46
|
+
if (this.queue.length >= BATCH_MAX) this.flush().catch(() => {});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
get pending() {
|
|
50
|
+
return this.queue.length;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Deliver everything queued. Resolves { flushed, remaining }; never rejects on network errors. */
|
|
54
|
+
flush() {
|
|
55
|
+
if (this._flushing) return this._flushing;
|
|
56
|
+
this._flushing = this._flush().finally(() => {
|
|
57
|
+
this._flushing = null;
|
|
58
|
+
});
|
|
59
|
+
return this._flushing;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async _flush() {
|
|
63
|
+
while (this.queue.length > 0) {
|
|
64
|
+
const batch = this.queue.slice(0, SEND_MAX);
|
|
65
|
+
if (!validateBatch(batch).ok) throw new Error('queue contains an invalid batch (SDK bug)');
|
|
66
|
+
const outcome = await this._send(JSON.stringify({ events: batch }));
|
|
67
|
+
if (outcome === 'unreachable') return { flushed: false, remaining: this.queue.length };
|
|
68
|
+
this.queue.splice(0, batch.length); // accepted, or a 4xx that retrying cannot fix
|
|
69
|
+
}
|
|
70
|
+
return { flushed: true, remaining: 0 };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async _send(body) {
|
|
74
|
+
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
|
75
|
+
try {
|
|
76
|
+
const res = await this.egress(this.url, {
|
|
77
|
+
method: 'POST',
|
|
78
|
+
headers: { 'content-type': 'application/json' },
|
|
79
|
+
body,
|
|
80
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
81
|
+
});
|
|
82
|
+
if (res.status === 202) return 'accepted';
|
|
83
|
+
if (res.status >= 400 && res.status < 500) return 'rejected';
|
|
84
|
+
} catch {
|
|
85
|
+
/* network — retry */
|
|
86
|
+
}
|
|
87
|
+
if (attempt < MAX_RETRIES) {
|
|
88
|
+
const backoff = Math.min(8000, this.backoffBaseMs * 2 ** (attempt - 1));
|
|
89
|
+
await new Promise((r) => setTimeout(r, backoff + Math.random() * (this.backoffBaseMs / 2)));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return 'unreachable';
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
module.exports = { TelemetryQueue, BATCH_MAX, BATCH_INTERVAL_MS, MAX_RETRIES, MAX_QUEUE };
|