@meshad/sdk 0.2.0 → 0.2.2
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 +161 -27
- package/examples/real-agent/README.md +97 -0
- package/examples/real-agent/backends.js +264 -0
- package/examples/real-agent/chat.js +157 -0
- package/examples/real-agent/demo-ads.js +106 -0
- package/examples/real-agent/sdk.js +4 -0
- package/index.d.ts +13 -1
- package/index.js +27 -6
- package/lib/ads.js +7 -2
- package/lib/candidate-selection.js +106 -0
- package/lib/net.js +10 -2
- package/lib/render.js +181 -34
- package/lib/schema/index.js +156 -0
- package/lib/schema/telemetry-schema.json +48 -0
- package/lib/signature.js +6 -0
- package/lib/terminal.js +7 -2
- package/package.json +3 -3
package/lib/render.js
CHANGED
|
@@ -21,8 +21,8 @@
|
|
|
21
21
|
*/
|
|
22
22
|
|
|
23
23
|
const {
|
|
24
|
-
FG_CODES, MAX_ART_LINES, displayWidth, truncateToWidth, renderLine,
|
|
25
|
-
validateFrames, sliceSpans, DEFAULT_HOLD_MS,
|
|
24
|
+
FG_CODES, BG_CODES, ATTR_CODES, CONTROL_CHARS_RE, MAX_ART_LINES, displayWidth, truncateToWidth, renderLine,
|
|
25
|
+
validateFrames, sliceSpans, DEFAULT_HOLD_MS, parseRenderColors, brandFallbacks,
|
|
26
26
|
} = require('./creative');
|
|
27
27
|
|
|
28
28
|
const ESC = '\x1b';
|
|
@@ -46,18 +46,111 @@ const MIN_COLS_ART = 60;
|
|
|
46
46
|
// terminals to the flattened one-liner.)
|
|
47
47
|
const MIN_ROWS_ART = 12;
|
|
48
48
|
|
|
49
|
+
/** Own keys only: `color` is ad content, and "constructor" is not a colour. */
|
|
49
50
|
function colorCode(color) {
|
|
50
|
-
return COLOR_CODES[color]
|
|
51
|
+
return typeof color === 'string' && Object.hasOwn(COLOR_CODES, color) ? COLOR_CODES[color] : COLOR_CODES.dim;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Size bounds, applied BEFORE anything is measured. Width is measured grapheme
|
|
56
|
+
* by grapheme, synchronously, on the host's event loop: a multi-megabyte line
|
|
57
|
+
* would stall the agent for seconds only to be cut to one terminal row.
|
|
58
|
+
* A field is one ad value (a line, the cta, the emoji); a line is a composed
|
|
59
|
+
* row — two fields plus our own chrome — so bounding a row never clips the
|
|
60
|
+
* disclosure off its end.
|
|
61
|
+
*/
|
|
62
|
+
const MAX_FIELD_CHARS = 512;
|
|
63
|
+
const MAX_LINE_CHARS = 2 * MAX_FIELD_CHARS + 64;
|
|
64
|
+
const MAX_ART_ITEMS = 64; // frames, lines per frame, spans per line (the contract allows 12 / 5 / 24)
|
|
65
|
+
|
|
66
|
+
function clipField(value) {
|
|
67
|
+
return String(value).slice(0, MAX_FIELD_CHARS);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Colour depth of this terminal: 'none' (NO_COLOR) | 'truecolor' | '256' | '16'. */
|
|
71
|
+
function brandDepth(env) {
|
|
72
|
+
if (env.NO_COLOR !== undefined) return 'none'; // any value, per no-color.org
|
|
73
|
+
const ct = String(env.COLORTERM || '').toLowerCase();
|
|
74
|
+
if (ct === 'truecolor' || ct === '24bit') return 'truecolor';
|
|
75
|
+
if (/256color/i.test(String(env.TERM || ''))) return '256';
|
|
76
|
+
return '16';
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The SGR opener that styles an ad's chrome and text. A valid `render.colors`
|
|
81
|
+
* brand colour wins (24-bit, nearest xterm-256 index, or nearest basic name by
|
|
82
|
+
* depth; none under NO_COLOR); anything else — unknown `v`, bad hex, absent —
|
|
83
|
+
* falls back to the closed `render.color` name. Every byte is synthesized here
|
|
84
|
+
* from parsed integers: nothing from the advertiser is ever copied through.
|
|
85
|
+
*/
|
|
86
|
+
function openFor(render, env = process.env) {
|
|
87
|
+
const brand = parseRenderColors(render && render.colors);
|
|
88
|
+
if (!brand) return brandDepth(env || {}) === 'none' ? '' : `\x1b[${colorCode(render && render.color)}m`;
|
|
89
|
+
const depth = brandDepth(env || {});
|
|
90
|
+
if (depth === 'none') return '';
|
|
91
|
+
if (depth === 'truecolor') {
|
|
92
|
+
const [r, g, b] = [1, 3, 5].map((i) => parseInt(brand.brand.slice(i, i + 2), 16));
|
|
93
|
+
return `\x1b[38;2;${r};${g};${b}m`;
|
|
94
|
+
}
|
|
95
|
+
const fb = brandFallbacks(brand.brand);
|
|
96
|
+
return depth === '256' ? `\x1b[38;5;${fb.ansi256}m` : `\x1b[${colorCode(fb.ansi16)}m`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* One art line, drawn like `renderLine` — except that a valid brand colour
|
|
101
|
+
* paints the text too, so the art matches the chrome (otherwise: purple bar,
|
|
102
|
+
* cyan text). The span's own fg and bg are replaced by the brand opener (and
|
|
103
|
+
* dropped under NO_COLOR); bold/underline stay. Without a valid brand it is
|
|
104
|
+
* exactly `renderLine`. The opener comes from `openFor`, so no advertiser byte
|
|
105
|
+
* is ever copied through.
|
|
106
|
+
*/
|
|
107
|
+
function artLineRenderer(render, env = process.env) {
|
|
108
|
+
// NO_COLOR: os trechos perdem cor e fundo; negrito e sublinhado ficam (no-color.org só proíbe cor).
|
|
109
|
+
if (brandDepth(env || {}) === 'none') {
|
|
110
|
+
return (line, maxWidth) => renderLine(Array.isArray(line) ? line.map((sp) => (sp && typeof sp === 'object' ? { ...sp, fg: undefined, bg: undefined } : sp)) : line, maxWidth);
|
|
111
|
+
}
|
|
112
|
+
if (!parseRenderColors(render && render.colors)) return renderLine;
|
|
113
|
+
const open = openFor(render, env);
|
|
114
|
+
const brandParams = open ? open.slice(2, -1) : '';
|
|
115
|
+
return (line, maxWidth) => {
|
|
116
|
+
if (!Array.isArray(line)) return '';
|
|
117
|
+
let out = '';
|
|
118
|
+
let width = 0;
|
|
119
|
+
for (const span of line) {
|
|
120
|
+
if (!span || typeof span.t !== 'string' || CONTROL_CHARS_RE.test(span.t)) continue;
|
|
121
|
+
const remaining = maxWidth - width;
|
|
122
|
+
if (remaining <= 0) break;
|
|
123
|
+
const text = truncateToWidth(span.t, remaining);
|
|
124
|
+
if (text.length === 0) continue;
|
|
125
|
+
const codes = [];
|
|
126
|
+
if (span.bold) codes.push(ATTR_CODES.bold);
|
|
127
|
+
if (span.underline) codes.push(ATTR_CODES.underline);
|
|
128
|
+
if (brandParams) codes.push(brandParams);
|
|
129
|
+
out += codes.length ? `${ESC}[${codes.join(';')}m${text}${ESC}[0m` : text;
|
|
130
|
+
width += displayWidth(text);
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
};
|
|
51
134
|
}
|
|
52
135
|
|
|
53
136
|
/** Strip control/newline characters and clamp width — never trust ad content blindly. */
|
|
54
137
|
function sanitizeLine(s, maxWidth) {
|
|
55
138
|
return truncateToWidth(
|
|
56
|
-
String(s ?? '').replace(/[\r\n\x00-\x08\x0b-\x1f]/g, ' '),
|
|
139
|
+
String(s ?? '').slice(0, MAX_LINE_CHARS).replace(/[\r\n\x00-\x08\x0b-\x1f\x7f-\x9f]/g, ' '),
|
|
57
140
|
Math.max(0, maxWidth),
|
|
58
141
|
);
|
|
59
142
|
}
|
|
60
143
|
|
|
144
|
+
/** Art far beyond the creative contract is not a creative; it is dropped unmeasured. */
|
|
145
|
+
function oversizedArt(r) {
|
|
146
|
+
const many = (a) => Array.isArray(a) && a.length > MAX_ART_ITEMS;
|
|
147
|
+
const lineTooBig = (line) => many(line) || (Array.isArray(line)
|
|
148
|
+
&& line.reduce((n, sp) => n + (sp && typeof sp.t === 'string' ? sp.t.length : 0), 0) > MAX_LINE_CHARS);
|
|
149
|
+
const artTooBig = (art) => many(art) || (Array.isArray(art) && art.some(lineTooBig));
|
|
150
|
+
return artTooBig(r.art_lines) || many(r.frames)
|
|
151
|
+
|| (Array.isArray(r.frames) && r.frames.some((f) => f && artTooBig(f.art_lines)));
|
|
152
|
+
}
|
|
153
|
+
|
|
61
154
|
class LineRenderer {
|
|
62
155
|
constructor(stream = process.stdout) {
|
|
63
156
|
this.stream = stream;
|
|
@@ -80,8 +173,11 @@ class LineRenderer {
|
|
|
80
173
|
const lines = Array.isArray(payload) ? payload : [payload];
|
|
81
174
|
const cols = this.stream.columns || 80;
|
|
82
175
|
const rows = this.stream.rows || 24;
|
|
83
|
-
|
|
84
|
-
|
|
176
|
+
// All rows or none. The disclosure is the LAST row, so a payload clipped
|
|
177
|
+
// to a short terminal is an undisclosed ad — and one the caller would
|
|
178
|
+
// count as shown.
|
|
179
|
+
const height = lines.length;
|
|
180
|
+
if (height <= 0 || height > Math.min(rows - 1, MAX_ROWS_ART + 2)) return false; // +2: panel borders
|
|
85
181
|
|
|
86
182
|
// Anti-flicker, two layers: (1) overwrite-with-padding instead of
|
|
87
183
|
// erase-then-repaint — a cleared line must never be visible between
|
|
@@ -160,7 +256,7 @@ function sanitizeAnsiLine(line, maxWidth) {
|
|
|
160
256
|
styles.push(m);
|
|
161
257
|
return '\x00SGR\x01';
|
|
162
258
|
});
|
|
163
|
-
const scrubbed = parked.replace(/[\r\n\x1b\x02-\x08\x0b-\x1f\x7f]/g, ' ');
|
|
259
|
+
const scrubbed = parked.replace(/[\r\n\x1b\x02-\x08\x0b-\x1f\x7f-\x9f]/g, ' ');
|
|
164
260
|
|
|
165
261
|
let width = 0;
|
|
166
262
|
let out = '';
|
|
@@ -177,6 +273,16 @@ function sanitizeAnsiLine(line, maxWidth) {
|
|
|
177
273
|
return { text: out, width };
|
|
178
274
|
}
|
|
179
275
|
|
|
276
|
+
/**
|
|
277
|
+
* The disclosure row: "<cta> · sponsored · (meshad pause)". Sanitized HERE, so
|
|
278
|
+
* every width computed from it is the width that reaches the screen. It is
|
|
279
|
+
* never clipped: where it does not fit whole, the ad is not drawn — clamped
|
|
280
|
+
* from the right, a long CTA is all that would be left of it.
|
|
281
|
+
*/
|
|
282
|
+
function disclosure(r) {
|
|
283
|
+
return sanitizeLine(`${clipField(r.cta || '')} · sponsored · (meshad pause)`, Infinity);
|
|
284
|
+
}
|
|
285
|
+
|
|
180
286
|
/**
|
|
181
287
|
* Compose "content <cta · sponsored · hint>" into one line, reserving the
|
|
182
288
|
* suffix's width FIRST and spending what is left on the content.
|
|
@@ -215,25 +321,47 @@ function composeWithSuffix(content, suffix, maxWidth) {
|
|
|
215
321
|
function firstArt(render) {
|
|
216
322
|
if (Array.isArray(render.art_lines) && render.art_lines.length) return render.art_lines;
|
|
217
323
|
const frames = render.frames;
|
|
218
|
-
if (Array.isArray(frames) && frames.length && Array.isArray(frames[0].art_lines)) return frames[0].art_lines;
|
|
324
|
+
if (Array.isArray(frames) && frames.length && frames[0] && Array.isArray(frames[0].art_lines)) return frames[0].art_lines;
|
|
219
325
|
return [];
|
|
220
326
|
}
|
|
221
327
|
|
|
222
|
-
function formatAd(ad, cols = 80, rows = 24) {
|
|
328
|
+
function formatAd(ad, cols = 80, rows = 24, env = process.env) {
|
|
223
329
|
const r = (ad && ad.render) || {};
|
|
224
|
-
const code =
|
|
225
|
-
const emojiPrefix = r.emoji ? `${r.emoji} ` : '';
|
|
226
|
-
const suffix =
|
|
330
|
+
const code = openFor(r, env);
|
|
331
|
+
const emojiPrefix = r.emoji ? `${clipField(r.emoji)} ` : '';
|
|
332
|
+
const suffix = disclosure(r);
|
|
227
333
|
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) =>
|
|
334
|
+
const contentLines = (Array.isArray(r.lines) && r.lines.length ? r.lines : [r.text || '']).slice(0, 3).map(clipField);
|
|
335
|
+
const wrap = (s) => `${code}${s}`;
|
|
230
336
|
|
|
231
337
|
const format = ad && ad.format;
|
|
232
338
|
|
|
339
|
+
// O pack local do exemplo reserva o rótulo demo junto da divulgação.
|
|
340
|
+
if (ad && ad.campaign_id === 'cmp_demo' && format === 'text_line') {
|
|
341
|
+
const suffixDemo = `${r.cta || ''} · sponsored`;
|
|
342
|
+
const content = `${emojiPrefix}${contentLines[0] || ''}`;
|
|
343
|
+
const separator = content.indexOf(' · ');
|
|
344
|
+
if (separator < 0) return [];
|
|
345
|
+
const prefix = content.slice(0, separator + 3);
|
|
346
|
+
const room = maxWidth - displayWidth(prefix) - displayWidth(` · ${suffixDemo}`);
|
|
347
|
+
if (room < 1) return [];
|
|
348
|
+
const headline = content.slice(separator + 3);
|
|
349
|
+
const clipped = displayWidth(headline) > room
|
|
350
|
+
? `${sanitizeLine(headline, room - 1).replace(/[\s.,;:—-]+$/, '')}…`
|
|
351
|
+
: headline;
|
|
352
|
+
return [wrap(`${prefix}${clipped} · ${suffixDemo}`)];
|
|
353
|
+
}
|
|
354
|
+
|
|
233
355
|
if (format === 'ascii_panel') {
|
|
356
|
+
// A frame that is not even an object is a broken creative, not one to
|
|
357
|
+
// degrade gracefully: drop the ad.
|
|
358
|
+
if (Array.isArray(r.frames) && r.frames.some((f) => !f || typeof f !== 'object')) return [];
|
|
359
|
+
if (oversizedArt(r)) return [];
|
|
360
|
+
const paint = artLineRenderer(r, env);
|
|
234
361
|
const art0 = firstArt(r);
|
|
235
362
|
// Degrade to a single text line on a terminal too small for the art to read.
|
|
236
363
|
if (cols >= MIN_COLS_ART && rows >= MIN_ROWS_ART && art0.length) {
|
|
364
|
+
if (displayWidth(suffix) > maxWidth - 4) return []; // cannot disclose => do not advertise
|
|
237
365
|
const artInner = Math.min(
|
|
238
366
|
maxWidth - 4,
|
|
239
367
|
Math.max(20, ...art0.slice(0, MAX_ART_LINES).map((line) =>
|
|
@@ -242,7 +370,7 @@ function formatAd(ad, cols = 80, rows = 24) {
|
|
|
242
370
|
);
|
|
243
371
|
const art = art0
|
|
244
372
|
.slice(0, MAX_ART_LINES)
|
|
245
|
-
.map((line) =>
|
|
373
|
+
.map((line) => paint(line, artInner));
|
|
246
374
|
return framePanel([...art, wrap(sanitizeLine(suffix, artInner))], artInner, code);
|
|
247
375
|
}
|
|
248
376
|
// Flattening keeps only word-bearing spans: bar/box glyphs (▇░█─╱╲…) are
|
|
@@ -261,6 +389,7 @@ function formatAd(ad, cols = 80, rows = 24) {
|
|
|
261
389
|
}
|
|
262
390
|
|
|
263
391
|
if (format === 'rich_panel' && cols >= 40) {
|
|
392
|
+
if (displayWidth(suffix) > maxWidth - 4) return []; // cannot disclose => do not advertise
|
|
264
393
|
// Budget: top border + content + suffix + bottom border must fit the cap.
|
|
265
394
|
const bodyBudget = MAX_ROWS_TEXT - 3; // 2 borders + suffix row
|
|
266
395
|
const rawRows = [
|
|
@@ -279,6 +408,7 @@ function formatAd(ad, cols = 80, rows = 24) {
|
|
|
279
408
|
}
|
|
280
409
|
|
|
281
410
|
if (format === 'text_block' || format === 'rich_panel' /* too narrow: degrade */) {
|
|
411
|
+
if (displayWidth(suffix) > maxWidth) return []; // cannot disclose => do not advertise
|
|
282
412
|
const blockRows = [...contentLines.map((l, i) => `${i === 0 ? emojiPrefix : ''}${l}`), suffix].map((l) =>
|
|
283
413
|
sanitizeLine(l, maxWidth),
|
|
284
414
|
);
|
|
@@ -305,8 +435,8 @@ function formatAd(ad, cols = 80, rows = 24) {
|
|
|
305
435
|
*
|
|
306
436
|
* @returns {string[][]} one entry per frame; a single entry means "do not animate".
|
|
307
437
|
*/
|
|
308
|
-
function revealFrames(ad, cols = 80, rows = 24, steps = REVEAL_STEPS) {
|
|
309
|
-
const final = formatAd(ad, cols, rows);
|
|
438
|
+
function revealFrames(ad, cols = 80, rows = 24, steps = REVEAL_STEPS, env = process.env) {
|
|
439
|
+
const final = formatAd(ad, cols, rows, env);
|
|
310
440
|
const r = (ad && ad.render) || {};
|
|
311
441
|
|
|
312
442
|
// Only ascii_panel animates, and only when it rendered as art (not degraded
|
|
@@ -326,17 +456,17 @@ function revealFrames(ad, cols = 80, rows = 24, steps = REVEAL_STEPS) {
|
|
|
326
456
|
// The panel is at its full size from the very first frame — only the art
|
|
327
457
|
// inside grows. Same width formula as formatAd, so the reveal's final frame
|
|
328
458
|
// can be the static render itself, byte for byte.
|
|
329
|
-
const code =
|
|
330
|
-
const suffixPlain =
|
|
459
|
+
const code = openFor(r, env);
|
|
460
|
+
const suffixPlain = disclosure(r);
|
|
331
461
|
const innerWidth = Math.min(maxWidth - 4, Math.max(20, widest, displayWidth(suffixPlain)));
|
|
332
|
-
const suffixRow =
|
|
462
|
+
const suffixRow = `${code}${sanitizeLine(suffixPlain, innerWidth)}`;
|
|
333
463
|
const target = Math.min(widest, innerWidth);
|
|
334
464
|
const frameCount = Math.max(1, Math.min(steps, target));
|
|
335
465
|
|
|
336
466
|
const frames = [];
|
|
337
467
|
for (let i = 1; i < frameCount; i++) {
|
|
338
468
|
const width = Math.ceil((target * i) / frameCount);
|
|
339
|
-
frames.push(drawFrame(artSpans.map((line) => sliceSpans(line, 0, width)), suffixRow, innerWidth, code));
|
|
469
|
+
frames.push(drawFrame(artSpans.map((line) => sliceSpans(line, 0, width)), suffixRow, innerWidth, code, artLineRenderer(r, env)));
|
|
340
470
|
}
|
|
341
471
|
frames.push(final);
|
|
342
472
|
return frames;
|
|
@@ -363,7 +493,7 @@ function visibleWidth(s) {
|
|
|
363
493
|
* clearly bounded object on screen, never as loose terminal output.
|
|
364
494
|
*/
|
|
365
495
|
function framePanel(rows, innerWidth, code) {
|
|
366
|
-
const b = (s) =>
|
|
496
|
+
const b = (s) => (code ? `${code}${s}\x1b[0m` : s);
|
|
367
497
|
const top = b(`╭${'─'.repeat(innerWidth + 2)}╮`);
|
|
368
498
|
const bottom = b(`╰${'─'.repeat(innerWidth + 2)}╯`);
|
|
369
499
|
const body = rows.map((row) => {
|
|
@@ -373,8 +503,8 @@ function framePanel(rows, innerWidth, code) {
|
|
|
373
503
|
return [top, ...body, bottom];
|
|
374
504
|
}
|
|
375
505
|
|
|
376
|
-
function drawFrame(artSpans, suffixRow, innerWidth, code) {
|
|
377
|
-
return framePanel([...artSpans.map((line) =>
|
|
506
|
+
function drawFrame(artSpans, suffixRow, innerWidth, code, paint = renderLine) {
|
|
507
|
+
return framePanel([...artSpans.map((line) => paint(line, innerWidth)), suffixRow], innerWidth, code);
|
|
378
508
|
}
|
|
379
509
|
|
|
380
510
|
/**
|
|
@@ -390,9 +520,9 @@ function drawFrame(artSpans, suffixRow, innerWidth, code) {
|
|
|
390
520
|
*
|
|
391
521
|
* @returns {{ steps: Array<{lines: string[], ms: number}>, loop: boolean }}
|
|
392
522
|
*/
|
|
393
|
-
function buildTimeline(ad, cols = 80, rows = 24) {
|
|
523
|
+
function buildTimeline(ad, cols = 80, rows = 24, env = process.env) {
|
|
394
524
|
const r = (ad && ad.render) || {};
|
|
395
|
-
const staticLines = formatAd(ad, cols, rows);
|
|
525
|
+
const staticLines = formatAd(ad, cols, rows, env);
|
|
396
526
|
|
|
397
527
|
const isArt = ad && ad.format === 'ascii_panel' && staticLines.length > 1;
|
|
398
528
|
if (!isArt) return { steps: [{ lines: staticLines, ms: 0 }], loop: false };
|
|
@@ -410,13 +540,14 @@ function buildTimeline(ad, cols = 80, rows = 24) {
|
|
|
410
540
|
|
|
411
541
|
// The panel width is fixed across every step of every frame — a border that
|
|
412
542
|
// resizes mid-typewriter reads as glitching, not animating.
|
|
413
|
-
const code =
|
|
414
|
-
const suffixPlain =
|
|
543
|
+
const code = openFor(r, env);
|
|
544
|
+
const suffixPlain = disclosure(r);
|
|
415
545
|
const innerWidth = Math.min(
|
|
416
546
|
maxWidth - 4,
|
|
417
547
|
Math.max(20, ...frames.map((f) => widthOf(f.art_lines.slice(0, MAX_ART_LINES))), displayWidth(suffixPlain)),
|
|
418
548
|
);
|
|
419
|
-
const suffixRow =
|
|
549
|
+
const suffixRow = `${code}${sanitizeLine(suffixPlain, innerWidth)}`;
|
|
550
|
+
const paint = artLineRenderer(r, env);
|
|
420
551
|
|
|
421
552
|
const steps = [];
|
|
422
553
|
|
|
@@ -437,16 +568,16 @@ function buildTimeline(ad, cols = 80, rows = 24) {
|
|
|
437
568
|
const gap = Math.max(0, edge - incoming.reduce((w, sp) => w + displayWidth(sp.t), 0));
|
|
438
569
|
return [...incoming, ...(gap ? [{ t: ' '.repeat(gap) }] : []), ...outgoing];
|
|
439
570
|
});
|
|
440
|
-
steps.push({ lines: drawFrame(composited, suffixRow, innerWidth, code), ms: WIPE_STEP_MS });
|
|
571
|
+
steps.push({ lines: drawFrame(composited, suffixRow, innerWidth, code, paint), ms: WIPE_STEP_MS });
|
|
441
572
|
}
|
|
442
573
|
} else if (transition === 'typewriter' && target > 0) {
|
|
443
574
|
const width = Math.min(widthOf(art), maxWidth);
|
|
444
575
|
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 });
|
|
576
|
+
steps.push({ lines: drawFrame(art.map((l) => sliceSpans(l, 0, w)), suffixRow, innerWidth, code, paint), ms: TYPE_STEP_MS });
|
|
446
577
|
}
|
|
447
578
|
}
|
|
448
579
|
|
|
449
|
-
steps.push({ lines: drawFrame(art, suffixRow, innerWidth, code), ms: frame.hold_ms || DEFAULT_HOLD_MS });
|
|
580
|
+
steps.push({ lines: drawFrame(art, suffixRow, innerWidth, code, paint), ms: frame.hold_ms || DEFAULT_HOLD_MS });
|
|
450
581
|
});
|
|
451
582
|
|
|
452
583
|
return { steps, loop };
|
|
@@ -508,8 +639,24 @@ class Animator {
|
|
|
508
639
|
}
|
|
509
640
|
}
|
|
510
641
|
|
|
642
|
+
/**
|
|
643
|
+
* Ad content is server-supplied and these run inside the host's timers: a
|
|
644
|
+
* malformed creative costs the ad, never the host. Whatever a formatter throws
|
|
645
|
+
* becomes "nothing to draw".
|
|
646
|
+
*/
|
|
647
|
+
const failClosed = (fn, nothing) => (...args) => {
|
|
648
|
+
try {
|
|
649
|
+
return fn(...args);
|
|
650
|
+
} catch {
|
|
651
|
+
return nothing();
|
|
652
|
+
}
|
|
653
|
+
};
|
|
654
|
+
|
|
511
655
|
module.exports = {
|
|
512
|
-
LineRenderer,
|
|
513
|
-
|
|
656
|
+
LineRenderer, Animator, colorCode, openFor, COLOR_CODES, FG_CODES,
|
|
657
|
+
formatAd: failClosed(formatAd, () => []),
|
|
658
|
+
revealFrames: failClosed(revealFrames, () => [[]]),
|
|
659
|
+
buildTimeline: failClosed(buildTimeline, () => ({ steps: [], loop: false })),
|
|
660
|
+
REVEAL_STEPS, REVEAL_FRAME_MS, sanitizeLine, sanitizeAnsiLine,
|
|
514
661
|
MAX_ROWS_TEXT, MAX_ROWS_ART, MIN_COLS_ART, MIN_ROWS_ART,
|
|
515
662
|
};
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/** Contrato local vendorizado de packages/schema; sincronize com scripts/sync-vendored.mjs. */
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const TELEMETRY_SCHEMA = require('./telemetry-schema.json');
|
|
5
|
+
|
|
6
|
+
const EVENT_TYPES = ['idle_start', 'idle_end', 'impression', 'click', 'heartbeat'];
|
|
7
|
+
const TERMINAL_TYPES = [
|
|
8
|
+
'claude-code', 'gemini-cli', 'codex', 'aider', 'opencode',
|
|
9
|
+
'cursor', 'windsurf', 'kiro', 'continue', 'other',
|
|
10
|
+
];
|
|
11
|
+
const ALLOWED_FIELDS = ['event', 'ts', 'anon_id', 'terminal_type', 'duration_ms', 'ad_id', 'sdk_version', 'surface'];
|
|
12
|
+
/** Where an impression/click happened: the footer ad, or inside a sponsored game. */
|
|
13
|
+
const SURFACES = ['footer', 'game'];
|
|
14
|
+
const REQUIRED_FIELDS = ['event', 'ts', 'anon_id', 'terminal_type', 'sdk_version'];
|
|
15
|
+
|
|
16
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
17
|
+
const AD_ID_RE = /^ad_[A-Za-z0-9]{8,32}$/;
|
|
18
|
+
const SEMVER_RE = /^[0-9]+\.[0-9]+\.[0-9]+$/;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Validate a single telemetry event against the closed allowlist.
|
|
22
|
+
* @returns {{ ok: boolean, errors: string[] }}
|
|
23
|
+
*/
|
|
24
|
+
function validateEvent(ev) {
|
|
25
|
+
const errors = [];
|
|
26
|
+
if (ev === null || typeof ev !== 'object' || Array.isArray(ev)) {
|
|
27
|
+
return { ok: false, errors: ['event must be an object'] };
|
|
28
|
+
}
|
|
29
|
+
for (const key of Object.keys(ev)) {
|
|
30
|
+
if (!ALLOWED_FIELDS.includes(key)) {
|
|
31
|
+
errors.push(`field not in allowlist: ${key}`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
for (const key of REQUIRED_FIELDS) {
|
|
35
|
+
if (!(key in ev)) errors.push(`missing required field: ${key}`);
|
|
36
|
+
}
|
|
37
|
+
if (errors.length) return { ok: false, errors };
|
|
38
|
+
|
|
39
|
+
if (!EVENT_TYPES.includes(ev.event)) errors.push(`invalid event type: ${ev.event}`);
|
|
40
|
+
if (typeof ev.ts !== 'string' || Number.isNaN(Date.parse(ev.ts))) errors.push('ts must be an ISO-8601 timestamp');
|
|
41
|
+
if (typeof ev.anon_id !== 'string' || !UUID_RE.test(ev.anon_id)) errors.push('anon_id must be a lowercase UUID');
|
|
42
|
+
if (!TERMINAL_TYPES.includes(ev.terminal_type)) errors.push(`invalid terminal_type: ${ev.terminal_type}`);
|
|
43
|
+
if (typeof ev.sdk_version !== 'string' || !SEMVER_RE.test(ev.sdk_version)) errors.push('sdk_version must be semver');
|
|
44
|
+
|
|
45
|
+
if ('duration_ms' in ev) {
|
|
46
|
+
if (!Number.isInteger(ev.duration_ms) || ev.duration_ms < 0 || ev.duration_ms > 86400000) {
|
|
47
|
+
errors.push('duration_ms must be an integer in [0, 86400000]');
|
|
48
|
+
}
|
|
49
|
+
if (!['idle_end', 'impression'].includes(ev.event)) {
|
|
50
|
+
errors.push(`duration_ms not allowed on event type: ${ev.event}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if ('ad_id' in ev) {
|
|
54
|
+
if (typeof ev.ad_id !== 'string' || !AD_ID_RE.test(ev.ad_id)) errors.push('ad_id has invalid format');
|
|
55
|
+
if (!['impression', 'click'].includes(ev.event)) {
|
|
56
|
+
errors.push(`ad_id not allowed on event type: ${ev.event}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if ('surface' in ev) {
|
|
60
|
+
if (!SURFACES.includes(ev.surface)) errors.push(`invalid surface: ${ev.surface}`);
|
|
61
|
+
if (!['impression', 'click'].includes(ev.event)) {
|
|
62
|
+
errors.push(`surface not allowed on event type: ${ev.event}`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (ev.event === 'impression' && !('ad_id' in ev)) errors.push('impression requires ad_id');
|
|
66
|
+
if (ev.event === 'click' && !('ad_id' in ev)) errors.push('click requires ad_id');
|
|
67
|
+
if (ev.event === 'idle_end' && !('duration_ms' in ev)) errors.push('idle_end requires duration_ms');
|
|
68
|
+
|
|
69
|
+
return { ok: errors.length === 0, errors };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Same anon_id rule the telemetry contract enforces (lowercase UUID). */
|
|
73
|
+
function isAnonId(value) {
|
|
74
|
+
return typeof value === 'string' && UUID_RE.test(value);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Same terminal_type rule the telemetry contract enforces. */
|
|
78
|
+
function isTerminalType(value) {
|
|
79
|
+
return TERMINAL_TYPES.includes(value);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Validate a batch. The whole batch is rejected if ANY event is invalid —
|
|
84
|
+
* an official client can never legitimately produce a partially valid batch.
|
|
85
|
+
* @returns {{ ok: boolean, results: {ok: boolean, errors: string[]}[] }}
|
|
86
|
+
*/
|
|
87
|
+
function validateBatch(events) {
|
|
88
|
+
if (!Array.isArray(events) || events.length === 0 || events.length > 100) {
|
|
89
|
+
return { ok: false, results: [], batchError: 'events must be an array of 1..100 items' };
|
|
90
|
+
}
|
|
91
|
+
const results = events.map(validateEvent);
|
|
92
|
+
return { ok: results.every((r) => r.ok), results };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
module.exports = {
|
|
96
|
+
TELEMETRY_SCHEMA,
|
|
97
|
+
SCHEMA_VERSION: '1.0.0',
|
|
98
|
+
EVENT_TYPES,
|
|
99
|
+
SURFACES,
|
|
100
|
+
TERMINAL_TYPES,
|
|
101
|
+
ALLOWED_FIELDS,
|
|
102
|
+
REQUIRED_FIELDS,
|
|
103
|
+
validateEvent,
|
|
104
|
+
validateBatch,
|
|
105
|
+
isAnonId,
|
|
106
|
+
isTerminalType,
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
// Taxonomia própria, com identificadores estáveis; categorias sensíveis não são tópicos de perfil.
|
|
110
|
+
const TAXONOMY_V1 = Object.freeze([
|
|
111
|
+
['iab1_tech', 'Tecnologia e computadores', 'Technology and computers', 'permitida'],
|
|
112
|
+
['iab1_devtools', 'Ferramentas de desenvolvimento', 'Developer tools', 'permitida'],
|
|
113
|
+
['iab1_ai', 'IA e software', 'AI and software', 'permitida'],
|
|
114
|
+
['iab1_food', 'Alimentação e delivery', 'Food and delivery', 'permitida'],
|
|
115
|
+
['iab1_auto', 'Automóveis e mobilidade', 'Automotive and mobility', 'permitida'],
|
|
116
|
+
['iab1_home', 'Casa e decoração', 'Home and decor', 'permitida'],
|
|
117
|
+
['iab1_shopping', 'Produtos de consumo e compras', 'Consumer goods and shopping', 'permitida'],
|
|
118
|
+
['iab1_sports', 'Esporte e lazer', 'Sports and leisure', 'permitida'],
|
|
119
|
+
['iab1_travel', 'Viagens', 'Travel', 'permitida'],
|
|
120
|
+
['iab1_education', 'Educação', 'Education', 'permitida'],
|
|
121
|
+
['iab1_culture', 'Cultura e entretenimento', 'Culture and entertainment', 'permitida'],
|
|
122
|
+
['iab1_games', 'Jogos', 'Games', 'permitida'],
|
|
123
|
+
['iab1_business', 'Negócios e produtividade', 'Business and productivity', 'permitida'],
|
|
124
|
+
['iab1_finance', 'Finanças', 'Finance', 'revisão'],
|
|
125
|
+
['iab1_care', 'Cuidados pessoais e bem-estar', 'Personal care and wellness', 'revisão'],
|
|
126
|
+
['iab1_health', 'Saúde e medicamentos', 'Health and medicines', 'restrita'],
|
|
127
|
+
['iab1_alcohol', 'Álcool', 'Alcohol', 'bloqueada'],
|
|
128
|
+
['iab1_gambling', 'Apostas', 'Gambling', 'bloqueada'],
|
|
129
|
+
['iab1_politics', 'Política e eleições', 'Politics and elections', 'bloqueada'],
|
|
130
|
+
['iab1_adult', 'Conteúdo adulto', 'Adult content', 'bloqueada'],
|
|
131
|
+
].map(([id, pt, en, rule]) => Object.freeze({ id, label: Object.freeze({ pt, en }), rule })));
|
|
132
|
+
const TARGETING_FIELDS = ['version', 'category', 'interests_any', 'terminal_type', 'locales', 'countries', 'hours_local'];
|
|
133
|
+
const PROFILE_TOPICS = new Set(TAXONOMY_V1.filter((x) => x.rule === 'permitida').map((x) => x.id));
|
|
134
|
+
|
|
135
|
+
/** Valida os critérios públicos da campanha, sem receber perfil de usuário. */
|
|
136
|
+
function validateTargeting(value) {
|
|
137
|
+
const errors = [];
|
|
138
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return { ok: false, errors: ['targeting deve ser objeto'] };
|
|
139
|
+
for (const key of Object.keys(value)) if (!TARGETING_FIELDS.includes(key)) errors.push(`campo desconhecido: ${key}`);
|
|
140
|
+
if (value.version !== 1) errors.push('version deve ser 1');
|
|
141
|
+
const category = TAXONOMY_V1.find((x) => x.id === value.category);
|
|
142
|
+
if (!category) errors.push('category desconhecida');
|
|
143
|
+
else if (category.rule === 'bloqueada') errors.push('category bloqueada');
|
|
144
|
+
const list = (key, valid) => {
|
|
145
|
+
if (value[key] === undefined) return;
|
|
146
|
+
if (!Array.isArray(value[key]) || value[key].length > 100 || !value[key].every(valid) || new Set(value[key]).size !== value[key].length) errors.push(`${key} inválido`);
|
|
147
|
+
};
|
|
148
|
+
list('interests_any', (x) => PROFILE_TOPICS.has(x));
|
|
149
|
+
list('terminal_type', (x) => TERMINAL_TYPES.includes(x));
|
|
150
|
+
list('locales', (x) => typeof x === 'string' && /^[a-z]{2,3}(?:-[A-Z]{2})?$/.test(x));
|
|
151
|
+
list('countries', (x) => typeof x === 'string' && /^[A-Z]{2}$/.test(x));
|
|
152
|
+
list('hours_local', (x) => Number.isInteger(x) && x >= 0 && x <= 23);
|
|
153
|
+
if (category && category.rule === 'restrita' && Array.isArray(value.interests_any) && value.interests_any.length) errors.push('category restrita não permite interesses');
|
|
154
|
+
return { ok: errors.length === 0, errors };
|
|
155
|
+
}
|
|
156
|
+
Object.assign(module.exports, { TAXONOMY_V1, TARGETING_FIELDS, validateTargeting });
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "https://meshad.io/schemas/telemetry/v1",
|
|
4
|
+
"title": "MeshAd Telemetry Event — v1",
|
|
5
|
+
"description": "The COMPLETE closed allowlist of data that may leave a developer's machine. Any payload containing fields outside this schema MUST be rejected in full by both client and gateway. Changes require a major version, public announcement and re-consent.",
|
|
6
|
+
"type": "object",
|
|
7
|
+
"additionalProperties": false,
|
|
8
|
+
"required": ["event", "ts", "anon_id", "terminal_type", "sdk_version"],
|
|
9
|
+
"properties": {
|
|
10
|
+
"event": {
|
|
11
|
+
"type": "string",
|
|
12
|
+
"enum": ["idle_start", "idle_end", "impression", "click", "heartbeat"]
|
|
13
|
+
},
|
|
14
|
+
"ts": {
|
|
15
|
+
"type": "string",
|
|
16
|
+
"format": "date-time"
|
|
17
|
+
},
|
|
18
|
+
"anon_id": {
|
|
19
|
+
"type": "string",
|
|
20
|
+
"description": "Locally generated random UUID. No relation to hardware. User-rotatable at any time.",
|
|
21
|
+
"pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
|
|
22
|
+
},
|
|
23
|
+
"terminal_type": {
|
|
24
|
+
"type": "string",
|
|
25
|
+
"enum": ["claude-code", "gemini-cli", "codex", "aider", "opencode", "cursor", "windsurf", "kiro", "continue", "other"]
|
|
26
|
+
},
|
|
27
|
+
"duration_ms": {
|
|
28
|
+
"type": "integer",
|
|
29
|
+
"minimum": 0,
|
|
30
|
+
"maximum": 86400000,
|
|
31
|
+
"description": "Only present on idle_end and impression events."
|
|
32
|
+
},
|
|
33
|
+
"ad_id": {
|
|
34
|
+
"type": "string",
|
|
35
|
+
"pattern": "^ad_[A-Za-z0-9]{8,32}$",
|
|
36
|
+
"description": "Only present on impression and click events."
|
|
37
|
+
},
|
|
38
|
+
"surface": {
|
|
39
|
+
"type": "string",
|
|
40
|
+
"enum": ["footer", "game"],
|
|
41
|
+
"description": "Only present on impression and click events: where the ad was shown."
|
|
42
|
+
},
|
|
43
|
+
"sdk_version": {
|
|
44
|
+
"type": "string",
|
|
45
|
+
"pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$"
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
package/lib/signature.js
CHANGED
|
@@ -31,6 +31,12 @@ function canonicalAdJson(ad) {
|
|
|
31
31
|
frames: render.frames,
|
|
32
32
|
transition: render.transition,
|
|
33
33
|
loop: render.loop,
|
|
34
|
+
// Optional playable-game skin id (ascii_panel only). Undefined → omitted,
|
|
35
|
+
// so every ad signed before `game` existed keeps its exact bytes.
|
|
36
|
+
game: render.game,
|
|
37
|
+
// Optional brand colour (`{ v, brand }`). Undefined → omitted, so ads
|
|
38
|
+
// signed before `colors` existed keep their exact bytes. Always AFTER game.
|
|
39
|
+
colors: render.colors,
|
|
34
40
|
},
|
|
35
41
|
});
|
|
36
42
|
}
|
package/lib/terminal.js
CHANGED
|
@@ -46,8 +46,13 @@ class TerminalAdRenderer {
|
|
|
46
46
|
|
|
47
47
|
/** Draw `ad`. Returns true only if something was actually drawn. */
|
|
48
48
|
show(ad) {
|
|
49
|
-
|
|
50
|
-
|
|
49
|
+
try {
|
|
50
|
+
const timeline = buildTimeline(ad, this.stream.columns || 80, this.stream.rows || 24);
|
|
51
|
+
this.visible = !!this.animator.play(timeline);
|
|
52
|
+
} catch {
|
|
53
|
+
// Runs inside the host's ticker: a bad ad is dropped, never thrown.
|
|
54
|
+
this.hide();
|
|
55
|
+
}
|
|
51
56
|
return this.visible;
|
|
52
57
|
}
|
|
53
58
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@meshad/sdk",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "Embeddable MeshAd SDK for AI agents and CLIs — show a signed ad only while the user is actually waiting, with the same privacy guarantees as the official client.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
@@ -21,8 +21,8 @@
|
|
|
21
21
|
"typecheck": "tsc -p tsconfig.json"
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@meshad/creative": "
|
|
25
|
-
"@meshad/schema": "
|
|
24
|
+
"@meshad/creative": "^1.1.0",
|
|
25
|
+
"@meshad/schema": "^1.1.0"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
28
|
"typescript": "^5.6.3"
|