@meshad/sdk 0.0.0-stage → 0.2.1
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 +111 -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/env.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Environment gate: should this process EVER show an ad?
|
|
5
|
+
*
|
|
6
|
+
* Decided once, at init. A disabled SDK is fully inert — no ad fetch, no
|
|
7
|
+
* device link, no telemetry, no timers — so opting out also means zero bytes
|
|
8
|
+
* on the network, not just "nothing drawn".
|
|
9
|
+
*
|
|
10
|
+
* Order matters: the end user's explicit opt-out always wins, and the host
|
|
11
|
+
* can force `interactive: true` (VS Code, Ink, a GUI) only past the TTY probe,
|
|
12
|
+
* never past MESHAD_DISABLE, CI or `meshad pause`.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const fs = require('node:fs');
|
|
16
|
+
const os = require('node:os');
|
|
17
|
+
const path = require('node:path');
|
|
18
|
+
|
|
19
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
20
|
+
|
|
21
|
+
function truthy(v) {
|
|
22
|
+
if (v === undefined || v === null) return false;
|
|
23
|
+
const s = String(v).trim().toLowerCase();
|
|
24
|
+
return s !== '' && s !== '0' && s !== 'false' && s !== 'no' && s !== 'off';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The official CLI's config dir — same resolution as apps/cli/src/config.js. */
|
|
28
|
+
function cliConfigDir(env) {
|
|
29
|
+
return env.MESHAD_CONFIG_DIR || path.join(os.homedir(), '.config', 'meshad');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Read ONLY `anon_id` and `paused_until` from the CLI's config, if the user has
|
|
34
|
+
* one. Lets a developer who already ran `meshad init` get credited for waits in
|
|
35
|
+
* any tool that embeds the SDK, and makes `meshad pause` apply everywhere. The
|
|
36
|
+
* CLI's api_key and every other field are deliberately ignored.
|
|
37
|
+
*/
|
|
38
|
+
function readCliState(env) {
|
|
39
|
+
try {
|
|
40
|
+
const raw = JSON.parse(fs.readFileSync(path.join(cliConfigDir(env), 'config.json'), 'utf8'));
|
|
41
|
+
return {
|
|
42
|
+
anonId: typeof raw.anon_id === 'string' && UUID_RE.test(raw.anon_id) ? raw.anon_id : null,
|
|
43
|
+
pausedUntil: raw.paused_until ?? null,
|
|
44
|
+
};
|
|
45
|
+
} catch {
|
|
46
|
+
return { anonId: null, pausedUntil: null };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function isPaused(pausedUntil, now) {
|
|
51
|
+
if (pausedUntil == null) return false;
|
|
52
|
+
if (pausedUntil === 'forever') return true;
|
|
53
|
+
return now < Number(pausedUntil);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @returns {{ enabled: boolean, reason: string|null }}
|
|
58
|
+
* reason ∈ MESHAD_DISABLE | CI | paused | not_interactive | dumb_terminal | disabled_by_host
|
|
59
|
+
*/
|
|
60
|
+
function gate({ env, stream, interactive, renderer, disabled, cliState, now }) {
|
|
61
|
+
if (disabled) return { enabled: false, reason: 'disabled_by_host' };
|
|
62
|
+
if (truthy(env.MESHAD_DISABLE)) return { enabled: false, reason: 'MESHAD_DISABLE' };
|
|
63
|
+
if (truthy(env.CI)) return { enabled: false, reason: 'CI' };
|
|
64
|
+
if (cliState && isPaused(cliState.pausedUntil, now)) return { enabled: false, reason: 'paused' };
|
|
65
|
+
if (renderer === 'terminal' && env.TERM === 'dumb') return { enabled: false, reason: 'dumb_terminal' };
|
|
66
|
+
const tty = !!(stream && stream.isTTY);
|
|
67
|
+
if (interactive === false) return { enabled: false, reason: 'not_interactive' };
|
|
68
|
+
if (interactive !== true && !tty) return { enabled: false, reason: 'not_interactive' };
|
|
69
|
+
// A terminal renderer cannot draw on a pipe even if the host insists.
|
|
70
|
+
if (renderer === 'terminal' && !tty) return { enabled: false, reason: 'not_interactive' };
|
|
71
|
+
return { enabled: true, reason: null };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Persisted anon_id under the host's own state dir (0700 dir, 0600 file). */
|
|
75
|
+
function loadOrCreateAnonId(stateDir, randomUUID) {
|
|
76
|
+
const file = path.join(stateDir, 'meshad-anon-id');
|
|
77
|
+
try {
|
|
78
|
+
const v = fs.readFileSync(file, 'utf8').trim();
|
|
79
|
+
if (UUID_RE.test(v)) return v;
|
|
80
|
+
} catch {
|
|
81
|
+
/* first run */
|
|
82
|
+
}
|
|
83
|
+
const id = randomUUID();
|
|
84
|
+
try {
|
|
85
|
+
fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
86
|
+
fs.writeFileSync(file, `${id}\n`, { mode: 0o600 });
|
|
87
|
+
} catch {
|
|
88
|
+
/* read-only home: an ephemeral id still works, it just won't accrue */
|
|
89
|
+
}
|
|
90
|
+
return id;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function platform() {
|
|
94
|
+
if (process.platform === 'darwin') return 'macos';
|
|
95
|
+
if (process.platform === 'win32') return 'windows';
|
|
96
|
+
return 'linux';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
module.exports = { gate, truthy, readCliState, isPaused, loadOrCreateAnonId, platform, UUID_RE };
|
package/lib/fsm.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Agent idle state machine — pure and clock-injectable. No I/O, no timers.
|
|
5
|
+
*
|
|
6
|
+
* A superset of the CLI's IdleStateMachine (apps/cli/src/fsm.js) for hosts
|
|
7
|
+
* that KNOW their own lifecycle instead of inferring it from output timing:
|
|
8
|
+
*
|
|
9
|
+
* idle ──requestStart──► waiting ──tick(quiet ≥ minWaitMs, caps ok)──► showing
|
|
10
|
+
* ▲ │ ▲ │
|
|
11
|
+
* │ requestEnd │ └── activity (token, tool, user input) ◄───┤ hide
|
|
12
|
+
* └───────────────────────┘ ▼
|
|
13
|
+
* └──────────── tick(now ≥ cooldownUntil, nothing in flight) ◄──── cooldown
|
|
14
|
+
*
|
|
15
|
+
* Inputs carry TIMESTAMPS ONLY — never a token, a prompt, a tool name or a
|
|
16
|
+
* path. The machine cannot leak content because it never receives any.
|
|
17
|
+
*
|
|
18
|
+
* Rules:
|
|
19
|
+
* - an ad appears only after `minWaitMs` of continuous quiet while a request
|
|
20
|
+
* is in flight (quiet = no token, no tool event, no user input);
|
|
21
|
+
* - ANY visible activity (first token, stream token, tool start/end, user
|
|
22
|
+
* input, request end) hides it immediately — `clear` is always the first
|
|
23
|
+
* action returned;
|
|
24
|
+
* - after every hide, `cooldownMs` must pass before the next ad;
|
|
25
|
+
* - at most `maxPerSession` ads per machine and `capPerHour` per sliding hour;
|
|
26
|
+
* - an ad never stays up longer than `maxDisplayMs`;
|
|
27
|
+
* - an impression counts only if the ad was on screen ≥ 2000ms (the same
|
|
28
|
+
* viewability floor the API bills against);
|
|
29
|
+
* - a "wait segment" (idle_start … idle_end) opens only after
|
|
30
|
+
* `idleThresholdMs` of quiet, so a fast response produces no telemetry.
|
|
31
|
+
*
|
|
32
|
+
* The caller drives it and performs the returned actions:
|
|
33
|
+
* {type:'idle_start'} · {type:'display'} · {type:'clear', reason} ·
|
|
34
|
+
* {type:'impression', displayed_ms} · {type:'idle_end', duration_ms}
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
const HOUR_MS = 3600000;
|
|
38
|
+
const MIN_DISPLAY_FOR_IMPRESSION_MS = 2000;
|
|
39
|
+
|
|
40
|
+
const DEFAULTS = Object.freeze({
|
|
41
|
+
minWaitMs: 8000,
|
|
42
|
+
idleThresholdMs: 1500, // same silence threshold `meshad run` uses
|
|
43
|
+
cooldownMs: 60000,
|
|
44
|
+
maxPerSession: 10,
|
|
45
|
+
capPerHour: 6, // matches the API's billable-impressions-per-hour cap
|
|
46
|
+
maxDisplayMs: 5 * 60000,
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
class AgentIdleFsm {
|
|
50
|
+
constructor(opts = {}) {
|
|
51
|
+
const o = { ...DEFAULTS, ...stripUndefined(opts) };
|
|
52
|
+
this.minWaitMs = o.minWaitMs;
|
|
53
|
+
this.idleThresholdMs = Math.min(o.idleThresholdMs, o.minWaitMs);
|
|
54
|
+
this.cooldownMs = o.cooldownMs;
|
|
55
|
+
this.maxPerSession = o.maxPerSession;
|
|
56
|
+
this.capPerHour = o.capPerHour;
|
|
57
|
+
this.capWindowMs = o.capWindowMs || HOUR_MS;
|
|
58
|
+
this.maxDisplayMs = o.maxDisplayMs;
|
|
59
|
+
|
|
60
|
+
this.state = 'idle';
|
|
61
|
+
this.inFlight = 0;
|
|
62
|
+
this.quietSince = null;
|
|
63
|
+
this.waitStartAt = null; // open wait segment (idle_start sent), or null
|
|
64
|
+
this.displayStartAt = null;
|
|
65
|
+
this.cooldownUntil = 0;
|
|
66
|
+
this.shownCount = 0;
|
|
67
|
+
this.history = []; // display timestamps inside the hourly window
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** May an ad be shown right now (caps + cooldown only; not the quiet rule)? */
|
|
71
|
+
canDisplay(now) {
|
|
72
|
+
if (now < this.cooldownUntil) return false;
|
|
73
|
+
if (this.shownCount >= this.maxPerSession) return false;
|
|
74
|
+
this.history = this.history.filter((t) => now - t < this.capWindowMs);
|
|
75
|
+
return this.history.length < this.capPerHour;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** A model/agent request began (nestable: concurrent requests are counted). */
|
|
79
|
+
requestStart(now) {
|
|
80
|
+
const actions = this._catchUp(now);
|
|
81
|
+
this.inFlight++;
|
|
82
|
+
if (this.inFlight === 1) this.quietSince = now;
|
|
83
|
+
if (this.state === 'idle') this.state = 'waiting';
|
|
84
|
+
return actions;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Visible activity: a token arrived, a tool started/finished, the user typed.
|
|
89
|
+
* Hides the ad (clear first), closes the wait segment, restarts the quiet clock.
|
|
90
|
+
*/
|
|
91
|
+
activity(now, reason = 'activity') {
|
|
92
|
+
const actions = this._catchUp(now);
|
|
93
|
+
actions.push(...this._hide(now, reason));
|
|
94
|
+
this._closeSegment(now, actions);
|
|
95
|
+
if (this.inFlight > 0) this.quietSince = now;
|
|
96
|
+
return actions;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A request finished. The response is now on screen — that is activity too. */
|
|
100
|
+
requestEnd(now) {
|
|
101
|
+
if (this.inFlight === 0) return [];
|
|
102
|
+
const actions = this.activity(now, 'request_end');
|
|
103
|
+
this.inFlight--;
|
|
104
|
+
if (this.inFlight === 0) {
|
|
105
|
+
this.quietSince = null;
|
|
106
|
+
if (this.state === 'waiting') this.state = 'idle';
|
|
107
|
+
}
|
|
108
|
+
return actions;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Periodic clock tick. Opens wait segments, expires cooldown, enforces
|
|
113
|
+
* maxDisplayMs and — only when `adAvailable` — promotes waiting → showing.
|
|
114
|
+
*/
|
|
115
|
+
tick(now, { adAvailable = false, minWaitMs = this.minWaitMs } = {}) {
|
|
116
|
+
const actions = this._catchUp(now);
|
|
117
|
+
|
|
118
|
+
if (this.state === 'showing' && now - this.displayStartAt >= this.maxDisplayMs) {
|
|
119
|
+
actions.push(...this._hide(now, 'max_display'));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (
|
|
123
|
+
this.state === 'waiting' &&
|
|
124
|
+
adAvailable &&
|
|
125
|
+
this.inFlight > 0 &&
|
|
126
|
+
now - this.quietSince >= Math.max(this.minWaitMs, minWaitMs) &&
|
|
127
|
+
this.canDisplay(now)
|
|
128
|
+
) {
|
|
129
|
+
this.state = 'showing';
|
|
130
|
+
this.displayStartAt = now;
|
|
131
|
+
this.shownCount++;
|
|
132
|
+
this.history.push(now);
|
|
133
|
+
actions.push({ type: 'display' });
|
|
134
|
+
}
|
|
135
|
+
return actions;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The caller could not actually draw the ad it was told to display. Roll the
|
|
140
|
+
* display back as if it never happened: no cooldown, no cap consumed, and
|
|
141
|
+
* — crucially — no impression can follow.
|
|
142
|
+
*/
|
|
143
|
+
abortDisplay() {
|
|
144
|
+
if (this.state !== 'showing') return;
|
|
145
|
+
this.state = 'waiting';
|
|
146
|
+
this.displayStartAt = null;
|
|
147
|
+
this.shownCount--;
|
|
148
|
+
this.history.pop();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Release everything (shutdown). Clear first, then close the open segment. */
|
|
152
|
+
stop(now) {
|
|
153
|
+
const actions = this._hide(now, 'stop');
|
|
154
|
+
this._closeSegment(now, actions);
|
|
155
|
+
this.inFlight = 0;
|
|
156
|
+
this.quietSince = null;
|
|
157
|
+
this.state = 'idle';
|
|
158
|
+
return actions;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Time-driven transitions that need no decision from the caller: open the
|
|
163
|
+
* wait segment once quiet ≥ idleThresholdMs, leave cooldown once it expires.
|
|
164
|
+
* Never displays — so an event handler catching up on elapsed time cannot
|
|
165
|
+
* flash an ad for 0ms right before hiding it.
|
|
166
|
+
*/
|
|
167
|
+
_catchUp(now) {
|
|
168
|
+
const actions = [];
|
|
169
|
+
if (this.state === 'cooldown' && now >= this.cooldownUntil) {
|
|
170
|
+
this.state = this.inFlight > 0 ? 'waiting' : 'idle';
|
|
171
|
+
}
|
|
172
|
+
if (this.inFlight > 0 && this.waitStartAt === null && now - this.quietSince >= this.idleThresholdMs) {
|
|
173
|
+
this.waitStartAt = this.quietSince; // the wait began when the activity stopped
|
|
174
|
+
actions.push({ type: 'idle_start' });
|
|
175
|
+
}
|
|
176
|
+
return actions;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
_hide(now, reason) {
|
|
180
|
+
if (this.state !== 'showing') return [];
|
|
181
|
+
const actions = [{ type: 'clear', reason }];
|
|
182
|
+
const displayed = Math.max(0, now - this.displayStartAt);
|
|
183
|
+
if (displayed >= MIN_DISPLAY_FOR_IMPRESSION_MS) actions.push({ type: 'impression', displayed_ms: displayed });
|
|
184
|
+
this.displayStartAt = null;
|
|
185
|
+
this.cooldownUntil = now + this.cooldownMs;
|
|
186
|
+
this.state = this.cooldownMs > 0 ? 'cooldown' : this.inFlight > 0 ? 'waiting' : 'idle';
|
|
187
|
+
return actions;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
_closeSegment(now, actions) {
|
|
191
|
+
if (this.waitStartAt === null) return;
|
|
192
|
+
actions.push({ type: 'idle_end', duration_ms: Math.max(0, now - this.waitStartAt) });
|
|
193
|
+
this.waitStartAt = null;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function stripUndefined(o) {
|
|
198
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
module.exports = { AgentIdleFsm, DEFAULTS, MIN_DISPLAY_FOR_IMPRESSION_MS, HOUR_MS };
|
package/lib/net.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The SDK's SINGLE network egress point — same rule as the CLI's net.js.
|
|
5
|
+
* test/egress-boundary.test.js fails the build if any other file under the
|
|
6
|
+
* package references `fetch`, `node:http(s)`, `node:net`, `node:tls` or
|
|
7
|
+
* `node:dgram`.
|
|
8
|
+
*
|
|
9
|
+
* Origin lock: the returned function refuses any URL whose origin differs from
|
|
10
|
+
* the configured API origin, BEFORE a connection is attempted. Nothing the SDK
|
|
11
|
+
* does can reach a third host, whatever an ad or a caller passes in.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const DEFAULT_API_URL = 'https://api.meshad.io';
|
|
15
|
+
|
|
16
|
+
function createEgress({ apiUrl, fetchImpl }) {
|
|
17
|
+
const origin = new URL(apiUrl).origin;
|
|
18
|
+
const doFetch = fetchImpl || ((url, opts) => globalThis.fetch(url, opts));
|
|
19
|
+
return function meshFetch(url, opts = {}) {
|
|
20
|
+
let target;
|
|
21
|
+
try {
|
|
22
|
+
target = new URL(url);
|
|
23
|
+
} catch {
|
|
24
|
+
return Promise.reject(new Error('meshad: refusing egress to an invalid URL'));
|
|
25
|
+
}
|
|
26
|
+
if (target.origin !== origin) {
|
|
27
|
+
return Promise.reject(new Error(`meshad: refusing egress outside ${origin}`));
|
|
28
|
+
}
|
|
29
|
+
return doFetch(target.href, opts);
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
module.exports = { createEgress, DEFAULT_API_URL };
|