@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/README.md
CHANGED
|
@@ -1,3 +1,108 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @meshad/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
SDK para embutir o MeshAd em agentes de IA e CLIs. O anúncio aparece **somente
|
|
4
|
+
enquanto o usuário está esperando** (modelo ou ferramenta) e some no primeiro
|
|
5
|
+
token ou na primeira tecla — com as mesmas garantias de privacidade do cliente
|
|
6
|
+
oficial (`meshad`). CommonJS, Node 22+, tipos `.d.ts` inclusos.
|
|
7
|
+
|
|
8
|
+
## Instalação
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm install @meshad/sdk
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Integração em 5 minutos
|
|
15
|
+
|
|
16
|
+
```js
|
|
17
|
+
const { init } = require('@meshad/sdk');
|
|
18
|
+
|
|
19
|
+
const meshad = init({
|
|
20
|
+
terminalType: 'other', // seu terminal_type registrado
|
|
21
|
+
stateDir: path.join(os.homedir(), '.meu-agente'), // anon id estável
|
|
22
|
+
publisherKey: process.env.MESHAD_PUBLISHER_KEY, // opcional: quem recebe o crédito
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const callModel = meshad.withMeshAd(myModelCall); // qualquer função async
|
|
26
|
+
process.stdin.on('data', () => meshad.onUserInput()); // digitar esconde o anúncio
|
|
27
|
+
// ao sair: await meshad.destroy();
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Streams: `for await (const chunk of meshad.trackStream(stream)) …` — o primeiro
|
|
31
|
+
item esconde o anúncio sem que o SDK inspecione o conteúdo.
|
|
32
|
+
|
|
33
|
+
Controle manual (ciclo de vida, só temporização, nunca conteúdo):
|
|
34
|
+
`onRequestStart`, `onToolCallStart/End`, `onFirstToken`, `onStreamToken`,
|
|
35
|
+
`onUserInput`, `onRequestEnd`.
|
|
36
|
+
|
|
37
|
+
UI própria (Ink, VS Code): `init({ renderer: 'headless', onAd, onClear })`.
|
|
38
|
+
|
|
39
|
+
Exemplos executáveis em [`examples/`](./examples):
|
|
40
|
+
`MESHAD_DEMO=1 node examples/fake-agent.js` e `node examples/stream.js`.
|
|
41
|
+
|
|
42
|
+
## Quando o anúncio aparece
|
|
43
|
+
|
|
44
|
+
Máquina de estados `idle → waiting → showing → cooldown`:
|
|
45
|
+
|
|
46
|
+
- só aparece após `minWaitMs` (padrão 8 s) sem tokens/atividade; resposta rápida não mostra nada;
|
|
47
|
+
- esconde imediatamente no primeiro token, início de ferramenta ou input do usuário;
|
|
48
|
+
- limites: `cooldownMs` (60 s), `maxPerSession` (10), `capPerHour` (6), `maxDisplayMs` (5 min);
|
|
49
|
+
- nunca em ambiente não interativo (sem TTY, `CI=true`, `TERM=dumb`); `NO_COLOR` é respeitado.
|
|
50
|
+
|
|
51
|
+
## Privacidade
|
|
52
|
+
|
|
53
|
+
O SDK nunca lê, recebe, armazena ou envia prompt, código, resposta, caminhos,
|
|
54
|
+
nome de repositório ou qualquer conteúdo do usuário. Os eventos de ciclo de vida
|
|
55
|
+
não carregam argumentos. Todo evento é validado contra o allowlist fechado do
|
|
56
|
+
`@meshad/schema` antes de ser enfileirado, e a saída de rede é travada na origem da API.
|
|
57
|
+
|
|
58
|
+
### O que sai do processo
|
|
59
|
+
|
|
60
|
+
| Requisição | Campos |
|
|
61
|
+
| --- | --- |
|
|
62
|
+
| `GET /v1/keys/public` | nenhum |
|
|
63
|
+
| `GET /v1/ads/pack` | query: `anon_id`, `terminal_type`, `max` |
|
|
64
|
+
| `POST /v1/telemetry/events` | por evento: `event`, `ts`, `anon_id`, `terminal_type`, `sdk_version`; opcionais `duration_ms`, `ad_id` |
|
|
65
|
+
| `POST /v1/publisher/devices` (só com `publisherKey`) | `anon_id`, `platform`, `sdk_version` |
|
|
66
|
+
| `GET /v1/publisher/me` (só com `publisherKey`) | nenhum |
|
|
67
|
+
|
|
68
|
+
Headers: apenas `content-type` e `authorization` (a `publisherKey`, só para a API).
|
|
69
|
+
Prova: `test/privacy-canary.test.js` roda uma sessão completa com strings-canário
|
|
70
|
+
(prompt, resposta, caminhos, repo, cwd, hostname, usuário) e falha se qualquer
|
|
71
|
+
uma aparecer em qualquer URL, header ou body — este quadro é o mesmo allowlist do teste.
|
|
72
|
+
|
|
73
|
+
## Atribuição ao publisher
|
|
74
|
+
|
|
75
|
+
`terminalType` credita o parceiro da ferramenta de IA (o evento carrega
|
|
76
|
+
`terminal_type`). Com `publisherKey`, o SDK vincula o dispositivo
|
|
77
|
+
(`POST /v1/publisher/devices`, `anon_id` → conta) e as esperas passam a creditar
|
|
78
|
+
também o publisher. Sem `stateDir`/`anonId`, o id é efêmero e não acumula crédito.
|
|
79
|
+
|
|
80
|
+
## Opt-out do usuário final
|
|
81
|
+
|
|
82
|
+
Sempre vence a configuração do host:
|
|
83
|
+
|
|
84
|
+
- `MESHAD_DISABLE=1` no ambiente: nenhum anúncio, nenhuma requisição, nenhum timer;
|
|
85
|
+
- `meshad pause` / `meshad pause forever` (o SDK respeita a config do CLI oficial);
|
|
86
|
+
- `init({ disabled: true })` é o kill switch do host.
|
|
87
|
+
|
|
88
|
+
`CI=true` e ausência de TTY também desligam. `interactive: true` (GUIs) nunca
|
|
89
|
+
sobrepõe `MESHAD_DISABLE`, CI nem pause.
|
|
90
|
+
|
|
91
|
+
## Verificar um anúncio
|
|
92
|
+
|
|
93
|
+
Todo anúncio é assinado (Ed25519) e verificado antes de ser exibido; assinatura
|
|
94
|
+
inválida ou chave diferente → o anúncio é descartado. Para auditar a instalação
|
|
95
|
+
e as chaves, rode `meshad verify` (CLI oficial).
|
|
96
|
+
|
|
97
|
+
## Pendências
|
|
98
|
+
|
|
99
|
+
- Nenhuma mudança na API/schema neste release. O crédito do publisher depende de
|
|
100
|
+
`anon_id` estável (veja acima); `terminalType` fora do enum fechado usa `other`
|
|
101
|
+
até o registro do parceiro.
|
|
102
|
+
|
|
103
|
+
## Desenvolvimento
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
npm test # unitários (+ integração com a API se MESHAD_DATABASE_URL estiver definido)
|
|
107
|
+
npm run typecheck
|
|
108
|
+
```
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A fake AI agent CLI with MeshAd embedded. Simulates model latency and a tool
|
|
6
|
+
* call, so you can watch the ad appear only while you are actually waiting and
|
|
7
|
+
* vanish the instant the answer starts — or the instant you type.
|
|
8
|
+
*
|
|
9
|
+
* MESHAD_DEMO=1 node examples/fake-agent.js # no API needed
|
|
10
|
+
* MESHAD_API_URL=http://localhost:4000 node examples/fake-agent.js
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const os = require('node:os');
|
|
14
|
+
const path = require('node:path');
|
|
15
|
+
const readline = require('node:readline/promises');
|
|
16
|
+
const { init } = require('..'); // in your project: require('@meshad/sdk')
|
|
17
|
+
const { demoNetwork } = require('./lib/demo-network');
|
|
18
|
+
|
|
19
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
20
|
+
|
|
21
|
+
// ── your agent's own code (the SDK never sees any of it) ────────────────────
|
|
22
|
+
async function fakeModel(prompt) {
|
|
23
|
+
await sleep(4000 + Math.random() * 4000); // "thinking"
|
|
24
|
+
return `You asked: "${prompt}". I'd start by reading the failing test.`;
|
|
25
|
+
}
|
|
26
|
+
async function fakeTool(name) {
|
|
27
|
+
process.stdout.write(` ⏺ ${name}\n`);
|
|
28
|
+
await sleep(3000); // e.g. running a test suite
|
|
29
|
+
return 'ok';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// ── MeshAd integration: the whole thing ─────────────────────────────────────
|
|
33
|
+
const meshad = init({
|
|
34
|
+
terminalType: 'other', // your registered terminal_type
|
|
35
|
+
stateDir: path.join(os.homedir(), '.fake-agent'), // stable anon id → publisher credit
|
|
36
|
+
publisherKey: process.env.MESHAD_PUBLISHER_KEY, // optional: who gets paid
|
|
37
|
+
minWaitMs: 2000,
|
|
38
|
+
...demoNetwork(), // demo only — drop this line
|
|
39
|
+
});
|
|
40
|
+
const callModel = meshad.withMeshAd(fakeModel); // ad only while the user waits
|
|
41
|
+
const runTool = meshad.withMeshAd(async (name) => { // tools: hidden at start/end
|
|
42
|
+
meshad.onToolCallStart();
|
|
43
|
+
try { return await fakeTool(name); } finally { meshad.onToolCallEnd(); }
|
|
44
|
+
});
|
|
45
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
async function main() {
|
|
48
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
49
|
+
rl.on('line', () => meshad.onUserInput()); // typing hides the ad immediately
|
|
50
|
+
if (process.argv.includes('--debug')) console.error(meshad.diagnostics());
|
|
51
|
+
try {
|
|
52
|
+
for (;;) {
|
|
53
|
+
const prompt = (await rl.question('\nyou › ')).trim();
|
|
54
|
+
if (!prompt || prompt === 'exit') break;
|
|
55
|
+
await runTool('Bash(npm test)');
|
|
56
|
+
const answer = await callModel(prompt);
|
|
57
|
+
console.log(`agent › ${answer}`);
|
|
58
|
+
}
|
|
59
|
+
} finally {
|
|
60
|
+
rl.close();
|
|
61
|
+
await meshad.destroy(); // clears the screen area and flushes telemetry
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
main();
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* MESHAD_DEMO=1 — run the examples with no API and no account.
|
|
5
|
+
*
|
|
6
|
+
* Swaps the network for an in-memory fake: one demo ad signed with a throwaway
|
|
7
|
+
* Ed25519 key (verified by the SDK exactly like a real one), and a telemetry
|
|
8
|
+
* sink that, on exit, prints every request the SDK would have sent — the
|
|
9
|
+
* quickest way to see with your own eyes that no prompt or answer leaves.
|
|
10
|
+
*
|
|
11
|
+
* Not part of the integration: in a real tool you pass nothing and the SDK
|
|
12
|
+
* talks to https://api.meshad.io (or $MESHAD_API_URL).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const crypto = require('node:crypto');
|
|
16
|
+
const { canonicalAdJson } = require('../..');
|
|
17
|
+
|
|
18
|
+
function demoNetwork() {
|
|
19
|
+
if (process.env.MESHAD_DEMO !== '1') return {};
|
|
20
|
+
const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
|
|
21
|
+
const ad = {
|
|
22
|
+
ad_id: 'ad_demo0000001',
|
|
23
|
+
campaign_id: 'cmp_demo',
|
|
24
|
+
format: 'text_line',
|
|
25
|
+
min_wait_ms: 2000,
|
|
26
|
+
render: { text: '▲ Demo Cloud — deploy in one command', lines: ['▲ Demo Cloud — deploy in one command'], cta: 'mesh.io/demo', color: 'cyan', emoji: null },
|
|
27
|
+
};
|
|
28
|
+
ad.signature = crypto.sign(null, Buffer.from(canonicalAdJson(ad)), privateKey).toString('base64');
|
|
29
|
+
const sent = [];
|
|
30
|
+
const reply = (status, body) => ({ ok: status < 400, status, json: async () => body });
|
|
31
|
+
|
|
32
|
+
process.on('exit', () => {
|
|
33
|
+
process.stderr.write(`\n[MESHAD_DEMO] everything the SDK sent (${sent.length} request(s)):\n`);
|
|
34
|
+
for (const r of sent) process.stderr.write(` ${r.method} ${r.url}${r.body ? `\n ${r.body}` : ''}\n`);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
apiUrl: 'https://demo.meshad.invalid',
|
|
39
|
+
fetchImpl: async (url, opts = {}) => {
|
|
40
|
+
const u = new URL(url);
|
|
41
|
+
sent.push({ method: opts.method || 'GET', url: `${u.pathname}${u.search}`, body: opts.body || null });
|
|
42
|
+
if (u.pathname === '/v1/keys/public') {
|
|
43
|
+
return reply(200, { algorithm: 'ed25519', public_key_b64: publicKey.export({ type: 'spki', format: 'der' }).toString('base64') });
|
|
44
|
+
}
|
|
45
|
+
if (u.pathname === '/v1/ads/pack') return reply(200, { pack_id: 'pk_demo', ttl_seconds: 900, ads: [ad] });
|
|
46
|
+
if (u.pathname === '/v1/telemetry/events') return reply(202, { accepted: JSON.parse(opts.body).events.length });
|
|
47
|
+
return reply(404, {});
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
module.exports = { demoNetwork };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Streaming: wrap any AsyncIterable (SSE chunks, an SDK's stream, a Node
|
|
6
|
+
* Readable) with trackStream(). The ad may appear while waiting for the first
|
|
7
|
+
* token and disappears on it; chunks are passed through untouched — the SDK
|
|
8
|
+
* only notices that *something* arrived, never what.
|
|
9
|
+
*
|
|
10
|
+
* MESHAD_DEMO=1 node examples/stream.js
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const { init } = require('..'); // in your project: require('@meshad/sdk')
|
|
14
|
+
const { demoNetwork } = require('./lib/demo-network');
|
|
15
|
+
|
|
16
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
17
|
+
|
|
18
|
+
/** Stand-in for client.messages.stream(...) / an SSE response body. */
|
|
19
|
+
async function* fakeStream(prompt) {
|
|
20
|
+
await sleep(6000); // time to first token: the model is thinking
|
|
21
|
+
for (const word of `Here is a plan for "${prompt}": first, reproduce the bug; then bisect.`.split(' ')) {
|
|
22
|
+
await sleep(80);
|
|
23
|
+
yield { type: 'text_delta', text: `${word} ` };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function main() {
|
|
28
|
+
const meshad = init({ terminalType: 'other', minWaitMs: 2000, ...demoNetwork() });
|
|
29
|
+
|
|
30
|
+
process.stdout.write('agent › ');
|
|
31
|
+
for await (const chunk of meshad.trackStream(fakeStream('fix the flaky test'))) {
|
|
32
|
+
process.stdout.write(chunk.text);
|
|
33
|
+
}
|
|
34
|
+
process.stdout.write('\n');
|
|
35
|
+
|
|
36
|
+
await meshad.destroy();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
main();
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
// Type definitions for @meshad/sdk 0.2
|
|
2
|
+
// Hand-written and kept dependency-free (no @types/node needed by consumers).
|
|
3
|
+
|
|
4
|
+
/** Closed enum from @meshad/schema. New vendors use 'other' until registered. */
|
|
5
|
+
export type TerminalType =
|
|
6
|
+
| 'claude-code'
|
|
7
|
+
| 'gemini-cli'
|
|
8
|
+
| 'codex'
|
|
9
|
+
| 'aider'
|
|
10
|
+
| 'opencode'
|
|
11
|
+
| 'cursor'
|
|
12
|
+
| 'windsurf'
|
|
13
|
+
| 'kiro'
|
|
14
|
+
| 'continue'
|
|
15
|
+
| 'other';
|
|
16
|
+
|
|
17
|
+
export type AdFormat = 'text_line' | 'text_block' | 'rich_panel' | 'ascii_panel';
|
|
18
|
+
|
|
19
|
+
export interface ArtSpan {
|
|
20
|
+
t: string;
|
|
21
|
+
fg?: string;
|
|
22
|
+
bg?: string;
|
|
23
|
+
bold?: boolean;
|
|
24
|
+
underline?: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface AdFrame {
|
|
28
|
+
art_lines: ArtSpan[][];
|
|
29
|
+
hold_ms?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A verified ad, exactly as signed by the network. */
|
|
33
|
+
export interface SignedAd {
|
|
34
|
+
ad_id: string;
|
|
35
|
+
campaign_id: string;
|
|
36
|
+
format: AdFormat | string;
|
|
37
|
+
min_wait_ms: number;
|
|
38
|
+
render: {
|
|
39
|
+
text: string;
|
|
40
|
+
lines: string[];
|
|
41
|
+
cta: string;
|
|
42
|
+
color: string;
|
|
43
|
+
emoji: string | null;
|
|
44
|
+
art_lines?: ArtSpan[][];
|
|
45
|
+
frames?: AdFrame[];
|
|
46
|
+
transition?: 'cut' | 'wipe' | 'typewriter' | string;
|
|
47
|
+
loop?: boolean;
|
|
48
|
+
};
|
|
49
|
+
price_micros?: number;
|
|
50
|
+
pricing_model?: 'cpm' | 'cpc' | string;
|
|
51
|
+
signature: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export type FsmState = 'idle' | 'waiting' | 'showing' | 'cooldown';
|
|
55
|
+
|
|
56
|
+
export type ClearReason =
|
|
57
|
+
| 'first_token'
|
|
58
|
+
| 'stream_token'
|
|
59
|
+
| 'tool_start'
|
|
60
|
+
| 'user_input'
|
|
61
|
+
| 'request_end'
|
|
62
|
+
| 'activity'
|
|
63
|
+
| 'max_display'
|
|
64
|
+
| 'stop';
|
|
65
|
+
|
|
66
|
+
export type DisabledReason =
|
|
67
|
+
| 'MESHAD_DISABLE'
|
|
68
|
+
| 'CI'
|
|
69
|
+
| 'paused'
|
|
70
|
+
| 'not_interactive'
|
|
71
|
+
| 'dumb_terminal'
|
|
72
|
+
| 'disabled_by_host';
|
|
73
|
+
|
|
74
|
+
/** Minimal shape of the terminal stream the renderer draws on (process.stdout fits). */
|
|
75
|
+
export interface TerminalStream {
|
|
76
|
+
isTTY?: boolean;
|
|
77
|
+
columns?: number;
|
|
78
|
+
rows?: number;
|
|
79
|
+
write(chunk: string): unknown;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface FetchLikeResponse {
|
|
83
|
+
ok: boolean;
|
|
84
|
+
status: number;
|
|
85
|
+
json(): Promise<any>;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export type FetchLike = (url: string, init?: any) => Promise<FetchLikeResponse>;
|
|
89
|
+
|
|
90
|
+
export interface MeshAdOptions {
|
|
91
|
+
/** Your agent's terminal_type (closed enum). Required. */
|
|
92
|
+
terminalType: TerminalType;
|
|
93
|
+
/** API base URL. Default: $MESHAD_API_URL or https://api.meshad.io. */
|
|
94
|
+
apiUrl?: string;
|
|
95
|
+
/** Stable anonymous id (lowercase UUID). Default: the user's `meshad init` id, else `stateDir`, else ephemeral. */
|
|
96
|
+
anonId?: string;
|
|
97
|
+
/** Directory where the SDK may persist its anon id (file `meshad-anon-id`, mode 0600). */
|
|
98
|
+
stateDir?: string;
|
|
99
|
+
/** Reuse anon_id / honour `meshad pause` from the official CLI config. Default true. */
|
|
100
|
+
useCliIdentity?: boolean;
|
|
101
|
+
/** Publisher API key: links this device so its waits are credited (POST /v1/publisher/devices). */
|
|
102
|
+
publisherKey?: string;
|
|
103
|
+
/** 'terminal' draws with the CLI renderer; 'headless' only calls onAd/onClear. Default 'terminal'. */
|
|
104
|
+
renderer?: 'terminal' | 'headless';
|
|
105
|
+
/** Stream to draw on and probe for a TTY. Default process.stdout. */
|
|
106
|
+
stream?: TerminalStream;
|
|
107
|
+
/** Force past the TTY probe (VS Code, GUIs). Never overrides MESHAD_DISABLE, CI or `meshad pause`. */
|
|
108
|
+
interactive?: boolean;
|
|
109
|
+
/** Host-level kill switch. */
|
|
110
|
+
disabled?: boolean;
|
|
111
|
+
/** Called when an ad becomes visible (headless UIs draw it here). */
|
|
112
|
+
onAd?: ((ad: SignedAd) => void) | null;
|
|
113
|
+
/** Called when the ad must disappear — remove it immediately. */
|
|
114
|
+
onClear?: ((reason: ClearReason) => void) | null;
|
|
115
|
+
/** Quiet time before an ad may appear. Default 8000. */
|
|
116
|
+
minWaitMs?: number;
|
|
117
|
+
/** Quiet time before a wait counts (idle_start). Default 1500. */
|
|
118
|
+
idleThresholdMs?: number;
|
|
119
|
+
/** Gap after an ad hides before the next one. Default 60000. */
|
|
120
|
+
cooldownMs?: number;
|
|
121
|
+
/** Max ads per SDK instance. Default 10. */
|
|
122
|
+
maxPerSession?: number;
|
|
123
|
+
/** Max ads per sliding hour. Default 6. */
|
|
124
|
+
capPerHour?: number;
|
|
125
|
+
/** An ad never stays up longer than this. Default 300000. */
|
|
126
|
+
maxDisplayMs?: number;
|
|
127
|
+
/** Environment to read (tests). Default process.env. */
|
|
128
|
+
env?: Record<string, string | undefined>;
|
|
129
|
+
/** Injected fetch (tests, proxies). Still locked to the API origin. */
|
|
130
|
+
fetchImpl?: FetchLike;
|
|
131
|
+
/** Injected clock (tests). */
|
|
132
|
+
now?: () => number;
|
|
133
|
+
/** Ticker period while a request is in flight. Default 100. */
|
|
134
|
+
tickMs?: number;
|
|
135
|
+
/** Telemetry retry base delay. Default 250. */
|
|
136
|
+
backoffBaseMs?: number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export interface RequestEndResult {
|
|
140
|
+
impression: boolean;
|
|
141
|
+
duration_ms: number;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface FlushResult {
|
|
145
|
+
flushed: boolean;
|
|
146
|
+
remaining: number;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface Balance {
|
|
150
|
+
lifetime_micros: number;
|
|
151
|
+
pending_micros: number;
|
|
152
|
+
available_micros: number;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export interface Diagnostics {
|
|
156
|
+
sdk_version: string;
|
|
157
|
+
enabled: boolean;
|
|
158
|
+
disabled_reason: DisabledReason | null;
|
|
159
|
+
state: FsmState;
|
|
160
|
+
renderer: 'terminal' | 'headless';
|
|
161
|
+
terminal_type: TerminalType;
|
|
162
|
+
anon_id_source: 'host' | 'cli' | 'state_dir' | 'ephemeral';
|
|
163
|
+
device_link: 'not_requested' | 'pending' | 'linked' | string;
|
|
164
|
+
ads_cached: number;
|
|
165
|
+
invalid_signatures_dropped: number;
|
|
166
|
+
events_pending: number;
|
|
167
|
+
shown_this_session: number;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export interface TrackStreamOptions {
|
|
171
|
+
/** Set when you already called onRequestStart() for this request. */
|
|
172
|
+
requestStarted?: boolean;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export declare class MeshAdSdk {
|
|
176
|
+
constructor(options: MeshAdOptions);
|
|
177
|
+
|
|
178
|
+
readonly enabled: boolean;
|
|
179
|
+
readonly disabledReason: DisabledReason | null;
|
|
180
|
+
readonly anonId: string;
|
|
181
|
+
readonly terminalType: TerminalType;
|
|
182
|
+
/** Resolves once the first pack fetch (and device link, if any) settled. */
|
|
183
|
+
readonly ready: Promise<void>;
|
|
184
|
+
|
|
185
|
+
// lifecycle — timing only, no content
|
|
186
|
+
onRequestStart(): void;
|
|
187
|
+
onFirstToken(): void;
|
|
188
|
+
onStreamToken(): void;
|
|
189
|
+
onToolCallStart(): void;
|
|
190
|
+
onToolCallEnd(): void;
|
|
191
|
+
onUserInput(): void;
|
|
192
|
+
onRequestEnd(): RequestEndResult;
|
|
193
|
+
|
|
194
|
+
// 0.1 API (frozen contract v1)
|
|
195
|
+
onProcessingStart(): void;
|
|
196
|
+
onProcessingEnd(): RequestEndResult;
|
|
197
|
+
currentAd(): SignedAd | null;
|
|
198
|
+
click(adId: string): void;
|
|
199
|
+
getBalance(apiKey?: string): Promise<Balance>;
|
|
200
|
+
flush(): Promise<FlushResult>;
|
|
201
|
+
destroy(): Promise<void>;
|
|
202
|
+
|
|
203
|
+
// adapters
|
|
204
|
+
withMeshAd<A extends unknown[], R>(fn: (...args: A) => R | Promise<R>): (...args: A) => Promise<Awaited<R>>;
|
|
205
|
+
trackStream<T>(source: AsyncIterable<T>, options?: TrackStreamOptions): AsyncIterable<T>;
|
|
206
|
+
|
|
207
|
+
diagnostics(): Diagnostics;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export declare function init(options: MeshAdOptions): MeshAdSdk;
|
|
211
|
+
|
|
212
|
+
export declare function withMeshAd<A extends unknown[], R>(
|
|
213
|
+
fn: (...args: A) => R | Promise<R>,
|
|
214
|
+
meshad: MeshAdSdk,
|
|
215
|
+
): (...args: A) => Promise<Awaited<R>>;
|
|
216
|
+
|
|
217
|
+
export declare function trackStream<T>(
|
|
218
|
+
source: AsyncIterable<T>,
|
|
219
|
+
meshad: MeshAdSdk,
|
|
220
|
+
options?: TrackStreamOptions,
|
|
221
|
+
): AsyncIterable<T>;
|
|
222
|
+
|
|
223
|
+
/** Render an ad to ANSI lines with the CLI's formatter (for custom terminal UIs). */
|
|
224
|
+
export declare function formatAd(ad: SignedAd, cols?: number, rows?: number): string[];
|
|
225
|
+
|
|
226
|
+
/** Canonical bytes the network signs. */
|
|
227
|
+
export declare function canonicalAdJson(ad: SignedAd): string;
|
|
228
|
+
|
|
229
|
+
/** True iff `ad.signature` is a valid Ed25519 signature by `publicKeyB64` (DER-SPKI base64). */
|
|
230
|
+
export declare function verifyAd(ad: SignedAd, publicKeyB64: string): boolean;
|
|
231
|
+
|
|
232
|
+
export type FsmAction =
|
|
233
|
+
| { type: 'idle_start' }
|
|
234
|
+
| { type: 'display' }
|
|
235
|
+
| { type: 'clear'; reason: ClearReason }
|
|
236
|
+
| { type: 'impression'; displayed_ms: number }
|
|
237
|
+
| { type: 'idle_end'; duration_ms: number };
|
|
238
|
+
|
|
239
|
+
export interface FsmOptions {
|
|
240
|
+
minWaitMs?: number;
|
|
241
|
+
idleThresholdMs?: number;
|
|
242
|
+
cooldownMs?: number;
|
|
243
|
+
maxPerSession?: number;
|
|
244
|
+
capPerHour?: number;
|
|
245
|
+
capWindowMs?: number;
|
|
246
|
+
maxDisplayMs?: number;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** The pure, clock-injected state machine behind the SDK. */
|
|
250
|
+
export declare class AgentIdleFsm {
|
|
251
|
+
constructor(options?: FsmOptions);
|
|
252
|
+
readonly state: FsmState;
|
|
253
|
+
readonly inFlight: number;
|
|
254
|
+
readonly shownCount: number;
|
|
255
|
+
canDisplay(now: number): boolean;
|
|
256
|
+
requestStart(now: number): FsmAction[];
|
|
257
|
+
activity(now: number, reason?: ClearReason): FsmAction[];
|
|
258
|
+
requestEnd(now: number): FsmAction[];
|
|
259
|
+
tick(now: number, options?: { adAvailable?: boolean; minWaitMs?: number }): FsmAction[];
|
|
260
|
+
abortDisplay(): void;
|
|
261
|
+
stop(now: number): FsmAction[];
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export declare const FSM_DEFAULTS: Readonly<Required<Omit<FsmOptions, 'capWindowMs'>>>;
|
|
265
|
+
export declare const SDK_VERSION: string;
|
|
266
|
+
export declare const SDK_API_VERSION: number;
|
|
267
|
+
export declare const API_CONTRACT: Readonly<{
|
|
268
|
+
version: number;
|
|
269
|
+
factory: 'init';
|
|
270
|
+
instanceMethods: readonly string[];
|
|
271
|
+
}>;
|