@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/index.js
ADDED
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @meshad/sdk — embeddable MeshAd for AI agents and CLIs.
|
|
5
|
+
*
|
|
6
|
+
* const { init } = require('@meshad/sdk');
|
|
7
|
+
* const meshad = init({ terminalType: 'other' });
|
|
8
|
+
* const ask = meshad.withMeshAd(callModel); // ad only while the user waits
|
|
9
|
+
* const answer = await ask(prompt); // the SDK never sees `prompt`
|
|
10
|
+
*
|
|
11
|
+
* The host reports TIMING ONLY — "a request started", "a token arrived",
|
|
12
|
+
* "the user typed". No lifecycle method accepts content, and the adapters
|
|
13
|
+
* pass values through without looking at them. What may leave the process
|
|
14
|
+
* is fixed by the closed @meshad/schema allowlist, validated here before
|
|
15
|
+
* anything is queued (see README "O que sai do processo").
|
|
16
|
+
*
|
|
17
|
+
* Guarantees (identical to the official CLI):
|
|
18
|
+
* - ads render only with a valid Ed25519 signature (CLI's own verifier);
|
|
19
|
+
* - drawn with the CLI's own renderer: bottom rows, `sponsored` label,
|
|
20
|
+
* synchronous clear on the first token / user input;
|
|
21
|
+
* - never shown when non-interactive (no TTY, CI, MESHAD_DISABLE=1,
|
|
22
|
+
* `meshad pause`); a disabled SDK makes zero network requests;
|
|
23
|
+
* - all egress goes through lib/net.js, locked to the API origin;
|
|
24
|
+
* - batching ≤20 events or 30s, retry with backoff + jitter, offline queue.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const crypto = require('node:crypto');
|
|
28
|
+
const { TERMINAL_TYPES } = require('@meshad/schema');
|
|
29
|
+
const { AgentIdleFsm, DEFAULTS: FSM_DEFAULTS } = require('./lib/fsm');
|
|
30
|
+
const { TelemetryQueue, BATCH_INTERVAL_MS } = require('./lib/telemetry');
|
|
31
|
+
const { AdPack } = require('./lib/ads');
|
|
32
|
+
const { createEgress, DEFAULT_API_URL } = require('./lib/net');
|
|
33
|
+
const { TerminalAdRenderer } = require('./lib/terminal');
|
|
34
|
+
const { formatAd } = require('./lib/render');
|
|
35
|
+
const { canonicalAdJson, verifyAd } = require('./lib/signature');
|
|
36
|
+
const env_ = require('./lib/env');
|
|
37
|
+
|
|
38
|
+
const SDK_VERSION = require('./package.json').version;
|
|
39
|
+
const MAX_DURATION_MS = 86400000; // schema ceiling for duration_ms
|
|
40
|
+
const TICK_MS = 100;
|
|
41
|
+
|
|
42
|
+
function safeCall(fn, ...args) {
|
|
43
|
+
if (typeof fn !== 'function') return;
|
|
44
|
+
try {
|
|
45
|
+
fn(...args);
|
|
46
|
+
} catch {
|
|
47
|
+
/* host callback errors never break the pipeline */
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const clampMs = (v) => Math.min(MAX_DURATION_MS, Math.max(0, Math.round(v)));
|
|
52
|
+
|
|
53
|
+
class MeshAdSdk {
|
|
54
|
+
constructor({
|
|
55
|
+
terminalType,
|
|
56
|
+
apiUrl,
|
|
57
|
+
anonId,
|
|
58
|
+
stateDir,
|
|
59
|
+
useCliIdentity = true,
|
|
60
|
+
publisherKey,
|
|
61
|
+
renderer = 'terminal',
|
|
62
|
+
stream = process.stdout,
|
|
63
|
+
interactive,
|
|
64
|
+
disabled = false,
|
|
65
|
+
onAd = null,
|
|
66
|
+
onClear = null,
|
|
67
|
+
minWaitMs,
|
|
68
|
+
idleThresholdMs,
|
|
69
|
+
cooldownMs,
|
|
70
|
+
maxPerSession,
|
|
71
|
+
capPerHour,
|
|
72
|
+
maxDisplayMs,
|
|
73
|
+
env = process.env,
|
|
74
|
+
fetchImpl,
|
|
75
|
+
now = Date.now,
|
|
76
|
+
tickMs = TICK_MS,
|
|
77
|
+
backoffBaseMs,
|
|
78
|
+
} = {}) {
|
|
79
|
+
if (!TERMINAL_TYPES.includes(terminalType)) {
|
|
80
|
+
throw new Error(`terminalType must be one of: ${TERMINAL_TYPES.join(', ')} (closed enum, see @meshad/schema)`);
|
|
81
|
+
}
|
|
82
|
+
if (renderer !== 'terminal' && renderer !== 'headless') {
|
|
83
|
+
throw new Error("renderer must be 'terminal' or 'headless'");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
this.terminalType = terminalType;
|
|
87
|
+
this.apiUrl = (apiUrl || env.MESHAD_API_URL || DEFAULT_API_URL).replace(/\/+$/, '');
|
|
88
|
+
this.now = now;
|
|
89
|
+
this.onAd = onAd;
|
|
90
|
+
this.onClear = onClear;
|
|
91
|
+
this.renderMode = renderer;
|
|
92
|
+
this._publisherKey = publisherKey || null;
|
|
93
|
+
this._tickMs = tickMs;
|
|
94
|
+
|
|
95
|
+
const cliState = useCliIdentity ? env_.readCliState(env) : null;
|
|
96
|
+
const gate = env_.gate({ env, stream, interactive, renderer, disabled, cliState, now: now() });
|
|
97
|
+
this.enabled = gate.enabled;
|
|
98
|
+
this.disabledReason = gate.reason;
|
|
99
|
+
|
|
100
|
+
// Identity: explicit > the user's own `meshad init` id > host state dir > ephemeral.
|
|
101
|
+
if (anonId) {
|
|
102
|
+
if (!env_.UUID_RE.test(anonId)) throw new Error('anonId must be a lowercase UUID');
|
|
103
|
+
this.anonId = anonId;
|
|
104
|
+
this.anonIdSource = 'host';
|
|
105
|
+
} else if (cliState && cliState.anonId) {
|
|
106
|
+
this.anonId = cliState.anonId;
|
|
107
|
+
this.anonIdSource = 'cli';
|
|
108
|
+
} else if (stateDir && this.enabled) {
|
|
109
|
+
this.anonId = env_.loadOrCreateAnonId(stateDir, crypto.randomUUID);
|
|
110
|
+
this.anonIdSource = 'state_dir';
|
|
111
|
+
} else {
|
|
112
|
+
this.anonId = crypto.randomUUID();
|
|
113
|
+
this.anonIdSource = 'ephemeral';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
this.fsm = new AgentIdleFsm({ minWaitMs, idleThresholdMs, cooldownMs, maxPerSession, capPerHour, maxDisplayMs });
|
|
117
|
+
this._egress = createEgress({ apiUrl: this.apiUrl, fetchImpl });
|
|
118
|
+
this._telemetry = new TelemetryQueue({ apiUrl: this.apiUrl, egress: this._egress, backoffBaseMs });
|
|
119
|
+
this._pack = new AdPack({
|
|
120
|
+
apiUrl: this.apiUrl,
|
|
121
|
+
egress: this._egress,
|
|
122
|
+
anonId: this.anonId,
|
|
123
|
+
terminalType,
|
|
124
|
+
now,
|
|
125
|
+
});
|
|
126
|
+
this._terminal = renderer === 'terminal' && this.enabled ? new TerminalAdRenderer({ stream, env }) : null;
|
|
127
|
+
this._displayedAd = null;
|
|
128
|
+
this._ticker = null;
|
|
129
|
+
this._flushTimer = null;
|
|
130
|
+
this._destroyed = false;
|
|
131
|
+
this.deviceLink = this._publisherKey ? 'pending' : 'not_requested';
|
|
132
|
+
|
|
133
|
+
if (!this.enabled) {
|
|
134
|
+
this.ready = Promise.resolve();
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
this._flushTimer = setInterval(() => this._telemetry.flush().catch(() => {}), BATCH_INTERVAL_MS);
|
|
139
|
+
this._flushTimer.unref?.();
|
|
140
|
+
this._onExit = () => this._terminal && this._terminal.hide(); // never leave a scroll region behind
|
|
141
|
+
this._onBeforeExit = () => {
|
|
142
|
+
if (this._telemetry.pending > 0 && !this._exitFlushed) {
|
|
143
|
+
this._exitFlushed = true;
|
|
144
|
+
this._telemetry.flush().catch(() => {});
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
process.on('exit', this._onExit);
|
|
148
|
+
process.on('beforeExit', this._onBeforeExit);
|
|
149
|
+
|
|
150
|
+
// Pre-fetch off the hot path; the render path only ever reads memory.
|
|
151
|
+
this.ready = Promise.all([
|
|
152
|
+
this._pack.refresh().catch(() => {}),
|
|
153
|
+
this._publisherKey ? this._linkDevice() : null,
|
|
154
|
+
]).then(() => {});
|
|
155
|
+
this._prefetch = this.ready; // 0.1 name, kept for compatibility
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/* ── lifecycle events (timing only — none of these accept content) ───── */
|
|
159
|
+
|
|
160
|
+
/** A model/agent request started: the user is now waiting. */
|
|
161
|
+
onRequestStart() {
|
|
162
|
+
if (!this._live()) return;
|
|
163
|
+
this._apply(this.fsm.requestStart(this.now()));
|
|
164
|
+
this._pack.refreshIfStale();
|
|
165
|
+
this._syncTicker();
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The first token of the response arrived — hides the ad immediately. */
|
|
169
|
+
onFirstToken() {
|
|
170
|
+
this._activity('first_token');
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Another token arrived. O(1); call it per chunk without worry. */
|
|
174
|
+
onStreamToken() {
|
|
175
|
+
this._activity('stream_token');
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** A tool call started (it counts as work in flight; the host likely printed a line). */
|
|
179
|
+
onToolCallStart() {
|
|
180
|
+
if (!this._live()) return;
|
|
181
|
+
const now = this.now();
|
|
182
|
+
this._apply(this.fsm.activity(now, 'tool_start'));
|
|
183
|
+
this._apply(this.fsm.requestStart(now));
|
|
184
|
+
this._syncTicker();
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** A tool call finished (its result is about to be visible). */
|
|
188
|
+
onToolCallEnd() {
|
|
189
|
+
if (!this._live()) return;
|
|
190
|
+
this._apply(this.fsm.requestEnd(this.now()));
|
|
191
|
+
this._syncTicker();
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** The user typed / interacted — hides the ad immediately. */
|
|
195
|
+
onUserInput() {
|
|
196
|
+
this._activity('user_input');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** The request finished. Returns { impression, duration_ms } (0.1 shape). */
|
|
200
|
+
onRequestEnd() {
|
|
201
|
+
if (!this._live()) return { impression: false, duration_ms: 0 };
|
|
202
|
+
const result = this._apply(this.fsm.requestEnd(this.now()));
|
|
203
|
+
this._syncTicker();
|
|
204
|
+
return result;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/* ── 0.1 API (frozen contract v1) ────────────────────────────────────── */
|
|
208
|
+
|
|
209
|
+
onProcessingStart() {
|
|
210
|
+
this.onRequestStart();
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
onProcessingEnd() {
|
|
214
|
+
return this.onRequestEnd();
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** The verified ad on screen right now, or null. Also advances the clock. */
|
|
218
|
+
currentAd() {
|
|
219
|
+
if (!this._live()) return null;
|
|
220
|
+
this._tick();
|
|
221
|
+
return this.fsm.state === 'showing' ? this._displayedAd : null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Report a click on a displayed ad (only the ad_id leaves the process). */
|
|
225
|
+
click(adId) {
|
|
226
|
+
if (!this._live() || !adId) return;
|
|
227
|
+
this._enqueue('click', { ad_id: adId });
|
|
228
|
+
this._telemetry.flush().catch(() => {});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Publisher balance (GET /v1/publisher/me). Defaults to the `publisherKey` given at init. */
|
|
232
|
+
async getBalance(apiKey = this._publisherKey) {
|
|
233
|
+
if (!apiKey) throw new Error('getBalance needs a publisher API key');
|
|
234
|
+
const res = await this._egress(`${this.apiUrl}/v1/publisher/me`, {
|
|
235
|
+
headers: { authorization: `Bearer ${apiKey}` },
|
|
236
|
+
signal: AbortSignal.timeout(5000),
|
|
237
|
+
});
|
|
238
|
+
if (!res.ok) throw new Error(`getBalance failed: HTTP ${res.status}`);
|
|
239
|
+
const me = await res.json();
|
|
240
|
+
return { lifetime_micros: me.lifetime_micros, pending_micros: me.pending_micros, available_micros: me.available_micros };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Deliver queued events now. */
|
|
244
|
+
async flush() {
|
|
245
|
+
if (!this.enabled) return { flushed: true, remaining: 0 };
|
|
246
|
+
return this._telemetry.flush();
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Hide anything on screen, close the open wait, stop timers, flush. */
|
|
250
|
+
async destroy() {
|
|
251
|
+
if (this._destroyed) return;
|
|
252
|
+
if (this.enabled) {
|
|
253
|
+
this._apply(this.fsm.stop(this.now()));
|
|
254
|
+
this._syncTicker();
|
|
255
|
+
clearInterval(this._flushTimer);
|
|
256
|
+
process.removeListener('exit', this._onExit);
|
|
257
|
+
process.removeListener('beforeExit', this._onBeforeExit);
|
|
258
|
+
await this._telemetry.flush().catch(() => {});
|
|
259
|
+
}
|
|
260
|
+
this._destroyed = true;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/* ── adapters ────────────────────────────────────────────────────────── */
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Wrap any async call (a model request, an agent step). The wrapped function
|
|
267
|
+
* has the same signature and return value; arguments and results pass
|
|
268
|
+
* through untouched — the SDK never reads them.
|
|
269
|
+
*/
|
|
270
|
+
withMeshAd(asyncFn) {
|
|
271
|
+
if (typeof asyncFn !== 'function') throw new TypeError('withMeshAd expects a function');
|
|
272
|
+
const sdk = this;
|
|
273
|
+
return async function meshAdWrapped(...args) {
|
|
274
|
+
sdk.onRequestStart();
|
|
275
|
+
try {
|
|
276
|
+
return await asyncFn.apply(this, args);
|
|
277
|
+
} finally {
|
|
278
|
+
sdk.onRequestEnd();
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Track an AsyncIterable stream (SSE chunks, a Node Readable, an SDK stream).
|
|
285
|
+
* Yields exactly what the source yields; only the *arrival* of each item is
|
|
286
|
+
* observed: the first one fires onFirstToken, the rest onStreamToken, and
|
|
287
|
+
* the end (done, error or break) fires onRequestEnd.
|
|
288
|
+
*/
|
|
289
|
+
trackStream(source, { requestStarted = false } = {}) {
|
|
290
|
+
if (!source || typeof source[Symbol.asyncIterator] !== 'function') {
|
|
291
|
+
throw new TypeError('trackStream expects an AsyncIterable');
|
|
292
|
+
}
|
|
293
|
+
const sdk = this;
|
|
294
|
+
return {
|
|
295
|
+
[Symbol.asyncIterator]() {
|
|
296
|
+
const it = source[Symbol.asyncIterator]();
|
|
297
|
+
let first = true;
|
|
298
|
+
let ended = false;
|
|
299
|
+
const end = () => {
|
|
300
|
+
if (ended) return;
|
|
301
|
+
ended = true;
|
|
302
|
+
sdk.onRequestEnd();
|
|
303
|
+
};
|
|
304
|
+
if (!requestStarted) sdk.onRequestStart();
|
|
305
|
+
return {
|
|
306
|
+
async next(...a) {
|
|
307
|
+
let r;
|
|
308
|
+
try {
|
|
309
|
+
r = await it.next(...a);
|
|
310
|
+
} catch (e) {
|
|
311
|
+
end();
|
|
312
|
+
throw e;
|
|
313
|
+
}
|
|
314
|
+
if (r.done) end();
|
|
315
|
+
else if (first) {
|
|
316
|
+
first = false;
|
|
317
|
+
sdk.onFirstToken();
|
|
318
|
+
} else sdk.onStreamToken();
|
|
319
|
+
return r;
|
|
320
|
+
},
|
|
321
|
+
async return(value) {
|
|
322
|
+
end();
|
|
323
|
+
return typeof it.return === 'function' ? it.return(value) : { done: true, value };
|
|
324
|
+
},
|
|
325
|
+
async throw(err) {
|
|
326
|
+
end();
|
|
327
|
+
if (typeof it.throw === 'function') return it.throw(err);
|
|
328
|
+
throw err;
|
|
329
|
+
},
|
|
330
|
+
[Symbol.asyncIterator]() {
|
|
331
|
+
return this;
|
|
332
|
+
},
|
|
333
|
+
};
|
|
334
|
+
},
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Non-sensitive state for debugging an integration. */
|
|
339
|
+
diagnostics() {
|
|
340
|
+
return {
|
|
341
|
+
sdk_version: SDK_VERSION,
|
|
342
|
+
enabled: this.enabled,
|
|
343
|
+
disabled_reason: this.disabledReason,
|
|
344
|
+
state: this.fsm.state,
|
|
345
|
+
renderer: this.renderMode,
|
|
346
|
+
terminal_type: this.terminalType,
|
|
347
|
+
anon_id_source: this.anonIdSource,
|
|
348
|
+
device_link: this.deviceLink,
|
|
349
|
+
ads_cached: this._pack.ads.length,
|
|
350
|
+
invalid_signatures_dropped: this._pack.invalidDropped,
|
|
351
|
+
events_pending: this._telemetry.pending,
|
|
352
|
+
shown_this_session: this.fsm.shownCount,
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/* ── internals ───────────────────────────────────────────────────────── */
|
|
357
|
+
|
|
358
|
+
_live() {
|
|
359
|
+
return this.enabled && !this._destroyed;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
_activity(reason) {
|
|
363
|
+
if (!this._live()) return;
|
|
364
|
+
this._apply(this.fsm.activity(this.now(), reason));
|
|
365
|
+
this._syncTicker();
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
_tick() {
|
|
369
|
+
const next = this._pack.peek();
|
|
370
|
+
this._apply(this.fsm.tick(this.now(), { adAvailable: !!next, minWaitMs: next ? next.min_wait_ms : 0 }));
|
|
371
|
+
this._syncTicker();
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** Run the ticker only while something time-driven can happen. */
|
|
375
|
+
_syncTicker() {
|
|
376
|
+
const needed = this._live() && (this.fsm.inFlight > 0 || this.fsm.state !== 'idle');
|
|
377
|
+
if (needed && !this._ticker) {
|
|
378
|
+
this._ticker = setInterval(() => this._tick(), this._tickMs);
|
|
379
|
+
this._ticker.unref?.();
|
|
380
|
+
} else if (!needed && this._ticker) {
|
|
381
|
+
clearInterval(this._ticker);
|
|
382
|
+
this._ticker = null;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
_enqueue(event, extra = {}) {
|
|
387
|
+
this._telemetry.enqueue({
|
|
388
|
+
event,
|
|
389
|
+
ts: new Date(this.now()).toISOString(),
|
|
390
|
+
anon_id: this.anonId,
|
|
391
|
+
terminal_type: this.terminalType,
|
|
392
|
+
sdk_version: SDK_VERSION,
|
|
393
|
+
...extra,
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** Perform FSM actions in order ('clear' is always first when present). */
|
|
398
|
+
_apply(actions) {
|
|
399
|
+
let impression = false;
|
|
400
|
+
let duration = 0;
|
|
401
|
+
let hiddenAd = null; // the ad a 'clear' just took down — what an impression refers to
|
|
402
|
+
for (const action of actions) {
|
|
403
|
+
switch (action.type) {
|
|
404
|
+
case 'idle_start':
|
|
405
|
+
this._enqueue('idle_start');
|
|
406
|
+
break;
|
|
407
|
+
case 'display': {
|
|
408
|
+
const ad = this._pack.next();
|
|
409
|
+
const drawn = ad && (this._terminal ? this._terminal.show(ad) : true);
|
|
410
|
+
if (!drawn) {
|
|
411
|
+
// Nothing reached the screen (terminal too small to disclose, write
|
|
412
|
+
// failed): undo the display so no impression can ever be counted.
|
|
413
|
+
this.fsm.abortDisplay();
|
|
414
|
+
break;
|
|
415
|
+
}
|
|
416
|
+
this._displayedAd = ad;
|
|
417
|
+
safeCall(this.onAd, ad);
|
|
418
|
+
break;
|
|
419
|
+
}
|
|
420
|
+
case 'clear':
|
|
421
|
+
hiddenAd = this._displayedAd;
|
|
422
|
+
this._displayedAd = null;
|
|
423
|
+
if (this._terminal) this._terminal.hide();
|
|
424
|
+
safeCall(this.onClear, action.reason);
|
|
425
|
+
break;
|
|
426
|
+
case 'impression':
|
|
427
|
+
if (hiddenAd) {
|
|
428
|
+
this._enqueue('impression', { ad_id: hiddenAd.ad_id, duration_ms: clampMs(action.displayed_ms) });
|
|
429
|
+
impression = true;
|
|
430
|
+
}
|
|
431
|
+
break;
|
|
432
|
+
case 'idle_end':
|
|
433
|
+
duration = clampMs(action.duration_ms);
|
|
434
|
+
this._enqueue('idle_end', { duration_ms: duration });
|
|
435
|
+
break;
|
|
436
|
+
default:
|
|
437
|
+
break;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return { impression, duration_ms: duration };
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** Credit this device's waits to the publisher (POST /v1/publisher/devices). */
|
|
444
|
+
async _linkDevice() {
|
|
445
|
+
try {
|
|
446
|
+
const res = await this._egress(`${this.apiUrl}/v1/publisher/devices`, {
|
|
447
|
+
method: 'POST',
|
|
448
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${this._publisherKey}` },
|
|
449
|
+
body: JSON.stringify({ anon_id: this.anonId, platform: env_.platform(), sdk_version: SDK_VERSION }),
|
|
450
|
+
signal: AbortSignal.timeout(5000),
|
|
451
|
+
});
|
|
452
|
+
this.deviceLink = res.ok ? 'linked' : `failed_http_${res.status}`;
|
|
453
|
+
} catch {
|
|
454
|
+
this.deviceLink = 'failed_network';
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function init(config) {
|
|
460
|
+
return new MeshAdSdk(config);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** Functional form: `withMeshAd(asyncFn, meshad)`. */
|
|
464
|
+
function withMeshAd(asyncFn, meshad) {
|
|
465
|
+
if (!meshad || typeof meshad.withMeshAd !== 'function') throw new TypeError('withMeshAd(asyncFn, meshad): pass the instance from init()');
|
|
466
|
+
return meshad.withMeshAd(asyncFn);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** Functional form: `trackStream(iterable, meshad, opts)`. */
|
|
470
|
+
function trackStream(source, meshad, opts) {
|
|
471
|
+
if (!meshad || typeof meshad.trackStream !== 'function') throw new TypeError('trackStream(source, meshad): pass the instance from init()');
|
|
472
|
+
return meshad.trackStream(source, opts);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Frozen public API surface (roadmap P2-B2). The conformance test guards it:
|
|
477
|
+
* removing or renaming any of these fails CI. 0.2 only ADDS methods, so the
|
|
478
|
+
* contract version stays 1. Bump SDK_API_VERSION only on an intentional,
|
|
479
|
+
* documented breaking change.
|
|
480
|
+
*/
|
|
481
|
+
const SDK_API_VERSION = 1;
|
|
482
|
+
const API_CONTRACT = Object.freeze({
|
|
483
|
+
version: SDK_API_VERSION,
|
|
484
|
+
factory: 'init',
|
|
485
|
+
instanceMethods: Object.freeze([
|
|
486
|
+
// v1 (0.1)
|
|
487
|
+
'onProcessingStart',
|
|
488
|
+
'currentAd',
|
|
489
|
+
'onProcessingEnd',
|
|
490
|
+
'click',
|
|
491
|
+
'getBalance',
|
|
492
|
+
'flush',
|
|
493
|
+
'destroy',
|
|
494
|
+
// v1 additions (0.2)
|
|
495
|
+
'onRequestStart',
|
|
496
|
+
'onFirstToken',
|
|
497
|
+
'onStreamToken',
|
|
498
|
+
'onToolCallStart',
|
|
499
|
+
'onToolCallEnd',
|
|
500
|
+
'onUserInput',
|
|
501
|
+
'onRequestEnd',
|
|
502
|
+
'withMeshAd',
|
|
503
|
+
'trackStream',
|
|
504
|
+
'diagnostics',
|
|
505
|
+
]),
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
module.exports = {
|
|
509
|
+
init,
|
|
510
|
+
withMeshAd,
|
|
511
|
+
trackStream,
|
|
512
|
+
MeshAdSdk,
|
|
513
|
+
AgentIdleFsm,
|
|
514
|
+
formatAd,
|
|
515
|
+
canonicalAdJson,
|
|
516
|
+
verifyAd,
|
|
517
|
+
SDK_VERSION,
|
|
518
|
+
SDK_API_VERSION,
|
|
519
|
+
API_CONTRACT,
|
|
520
|
+
FSM_DEFAULTS,
|
|
521
|
+
};
|
package/lib/ads.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Ad pack: pre-fetch, MANDATORY Ed25519 verification, in-memory rotation.
|
|
5
|
+
*
|
|
6
|
+
* Same contract as the CLI's AdCache (apps/cli/src/adcache.js), minus the disk:
|
|
7
|
+
* - GET /v1/keys/public (DER-SPKI base64, algorithm must be ed25519);
|
|
8
|
+
* - GET /v1/ads/pack?anon_id&terminal_type&max — the auction runs there,
|
|
9
|
+
* never during a wait;
|
|
10
|
+
* - every ad is verified with the CLI's own canonicalization (vendored
|
|
11
|
+
* signature.js); a bad signature is dropped silently and counted;
|
|
12
|
+
* - the render path only ever reads memory; refresh is stale-while-revalidate
|
|
13
|
+
* on the pack's TTL, and concurrent refreshes share one flight.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const { verifyAd } = require('./signature');
|
|
17
|
+
|
|
18
|
+
class AdPack {
|
|
19
|
+
constructor({ apiUrl, egress, anonId, terminalType, now, max = 8, timeoutMs = 3000 }) {
|
|
20
|
+
this.apiUrl = apiUrl;
|
|
21
|
+
this.egress = egress;
|
|
22
|
+
this.anonId = anonId;
|
|
23
|
+
this.terminalType = terminalType;
|
|
24
|
+
this.now = now;
|
|
25
|
+
this.max = max;
|
|
26
|
+
this.timeoutMs = timeoutMs;
|
|
27
|
+
this.ads = [];
|
|
28
|
+
this.fetchedAt = 0;
|
|
29
|
+
this.ttlMs = 0;
|
|
30
|
+
this.cursor = 0;
|
|
31
|
+
this.invalidDropped = 0;
|
|
32
|
+
this._publicKey = null;
|
|
33
|
+
this._inflight = null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async _get(pathname) {
|
|
37
|
+
const res = await this.egress(`${this.apiUrl}${pathname}`, { signal: AbortSignal.timeout(this.timeoutMs) });
|
|
38
|
+
if (!res.ok) throw new Error(`GET ${pathname.split('?')[0]} → ${res.status}`);
|
|
39
|
+
return res.json();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async publicKey() {
|
|
43
|
+
if (this._publicKey) return this._publicKey;
|
|
44
|
+
const body = await this._get('/v1/keys/public');
|
|
45
|
+
if (!body || body.algorithm !== 'ed25519' || !body.public_key_b64) throw new Error('unexpected /v1/keys/public response');
|
|
46
|
+
this._publicKey = body.public_key_b64;
|
|
47
|
+
return this._publicKey;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
isFresh() {
|
|
51
|
+
return this.ads.length > 0 && this.now() < this.fetchedAt + this.ttlMs;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Refresh in the background if stale. Never throws, never blocks rendering. */
|
|
55
|
+
refreshIfStale() {
|
|
56
|
+
if (this.isFresh()) return this._inflight || Promise.resolve(this.ads);
|
|
57
|
+
return this.refresh().catch(() => this.ads);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
refresh() {
|
|
61
|
+
if (this._inflight) return this._inflight;
|
|
62
|
+
this._inflight = (async () => {
|
|
63
|
+
const q = new URLSearchParams({ anon_id: this.anonId, terminal_type: this.terminalType, max: String(this.max) });
|
|
64
|
+
const [key, pack] = await Promise.all([this.publicKey(), this._get(`/v1/ads/pack?${q}`)]);
|
|
65
|
+
const all = Array.isArray(pack && pack.ads) ? pack.ads : [];
|
|
66
|
+
const verified = all.filter((ad) => verifyAd(ad, key));
|
|
67
|
+
this.invalidDropped += all.length - verified.length;
|
|
68
|
+
this.ads = verified;
|
|
69
|
+
this.cursor = 0;
|
|
70
|
+
this.fetchedAt = this.now();
|
|
71
|
+
this.ttlMs = (Number(pack && pack.ttl_seconds) || 900) * 1000;
|
|
72
|
+
return verified;
|
|
73
|
+
})().finally(() => {
|
|
74
|
+
this._inflight = null;
|
|
75
|
+
});
|
|
76
|
+
return this._inflight;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The ad the next display would use, without consuming it. */
|
|
80
|
+
peek() {
|
|
81
|
+
return this.ads.length ? this.ads[this.cursor % this.ads.length] : null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Rotate through the ranked pack: each wait shows the next ad (as the CLI does). */
|
|
85
|
+
next() {
|
|
86
|
+
const ad = this.peek();
|
|
87
|
+
if (ad) this.cursor = (this.cursor + 1) % this.ads.length;
|
|
88
|
+
return ad;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
module.exports = { AdPack };
|
package/lib/creative.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Resolves `require('./creative')` inside the vendored render.js to the
|
|
5
|
+
* canonical @meshad/creative package — the same span→SGR table the CLI
|
|
6
|
+
* vendors, so an advertiser still never supplies a single escape byte.
|
|
7
|
+
*/
|
|
8
|
+
module.exports = require('@meshad/creative');
|