@leashmarket/sdk 0.1.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/dist/client.js ADDED
@@ -0,0 +1,479 @@
1
+ /**
2
+ * `LeashClient` — typed wrapper over the public Leash API.
3
+ *
4
+ * Two modes of authentication:
5
+ *
6
+ * 1. **Anonymous** — `new LeashClient({ baseUrl })`. Public reads
7
+ * (`discover`, `reputation`) work without credentials.
8
+ *
9
+ * 2. **Agent-signed** — pass `{ agentMint, executiveSecretBase58 }`.
10
+ * Authenticated calls (e.g. webhook management) get a fresh
11
+ * `X-Leash-Sig` header per request, signed with the executive
12
+ * keypair.
13
+ *
14
+ * 3. **Legacy API key** — pass `{ apiKey }`. Used until every
15
+ * endpoint accepts X-Leash-Sig; today this is what the chat
16
+ * product issues per user.
17
+ *
18
+ * Each method returns parsed JSON typed against `./types.ts`.
19
+ * Network failures throw `LeashError` so callers can branch on the
20
+ * `status` and `body` properties.
21
+ */
22
+ import { signRequest } from './sign.js';
23
+ export class LeashError extends Error {
24
+ status;
25
+ body;
26
+ constructor(status, message, body) {
27
+ super(message);
28
+ this.status = status;
29
+ this.body = body;
30
+ }
31
+ }
32
+ export class LeashClient {
33
+ baseUrl;
34
+ agentMint;
35
+ executiveSecretBase58;
36
+ apiKey;
37
+ fetchImpl;
38
+ constructor(opts = {}) {
39
+ this.baseUrl = (opts.baseUrl ?? 'https://api.leash.market').replace(/\/+$/, '');
40
+ if (opts.agentMint)
41
+ this.agentMint = opts.agentMint;
42
+ if (opts.executiveSecretBase58)
43
+ this.executiveSecretBase58 = opts.executiveSecretBase58;
44
+ if (opts.apiKey)
45
+ this.apiKey = opts.apiKey;
46
+ this.fetchImpl = opts.fetchImpl ?? globalThis.fetch;
47
+ }
48
+ // ── public reads ──────────────────────────────────────────────────
49
+ async discover(query = {}) {
50
+ const params = new URLSearchParams();
51
+ if (query.capability)
52
+ params.set('capability', query.capability);
53
+ if (query.max_price_usdc != null)
54
+ params.set('max_price_usdc', String(query.max_price_usdc));
55
+ if (query.pricing_type)
56
+ params.set('pricing_type', query.pricing_type);
57
+ if (query.source)
58
+ params.set('source', query.source);
59
+ if (query.limit)
60
+ params.set('limit', String(query.limit));
61
+ return this.requestJson('GET', `/v1/discover${params.toString() ? `?${params}` : ''}`);
62
+ }
63
+ /**
64
+ * Expand a `pay-skills` provider into its endpoint list.
65
+ *
66
+ * Use after {@link discover}: an item with `source === 'pay-skills'`
67
+ * carries an `slug` equal to the provider FQN
68
+ * (e.g. `agentmail/email`). Pass that here to get the absolute
69
+ * endpoint URLs, methods, pricing, and supported stablecoins so the
70
+ * agent can hand a URL to `buyer.fetch()` or `host.pay()`.
71
+ *
72
+ * Mirrors `pay skills endpoints <fqn>` from the pay.sh CLI.
73
+ */
74
+ async paySkillsProvider(fqn) {
75
+ const trimmed = fqn.trim().replace(/^\/+|\/+$/g, '');
76
+ if (!trimmed.includes('/')) {
77
+ throw new LeashError(400, `pay-skills FQN must include at least one '/' (got "${fqn}")`, null);
78
+ }
79
+ return this.requestJson('GET', `/v1/discover/pay-skills/${trimmed
80
+ .split('/')
81
+ .map((seg) => encodeURIComponent(seg))
82
+ .join('/')}`);
83
+ }
84
+ async reputation(args) {
85
+ const params = new URLSearchParams();
86
+ if (args.network)
87
+ params.set('network', args.network);
88
+ return this.requestJson('GET', `/v1/agents/${encodeURIComponent(args.agentMint)}/reputation${params.toString() ? `?${params}` : ''}`);
89
+ }
90
+ // ── agent recording (public) ──────────────────────────────────────
91
+ //
92
+ // Agent provisioning is fully client-side now: the caller mints +
93
+ // delegates locally (see `@leashmarket/mcp::mintAgentLocally`), then
94
+ // POSTs the resulting asset here for the API to write the platform
95
+ // row. Idempotent on `mint`. Works on both devnet and mainnet.
96
+ async recordAgent(input) {
97
+ return this.requestJson('POST', '/v1/agents/record', input);
98
+ }
99
+ // ── receipts (legacy API-key auth for now) ───────────────────────
100
+ async receipts(args) {
101
+ if (!this.apiKey) {
102
+ throw new LeashError(401, 'receipts() requires an API key today. Pass `{ apiKey }` to LeashClient.', null);
103
+ }
104
+ const params = new URLSearchParams();
105
+ if (args.direction)
106
+ params.set('kind', args.direction);
107
+ if (args.limit)
108
+ params.set('limit', String(args.limit));
109
+ return this.requestJson('GET', `/v1/receipts/${encodeURIComponent(args.agentMint)}${params.toString() ? `?${params}` : ''}`);
110
+ }
111
+ /**
112
+ * `GET /v1/receipts/by-hash/{hash}` — direct lookup of a single
113
+ * receipt by its deterministic `receipt_hash`. Network is bound to
114
+ * the API key prefix; cross-network hashes return 404.
115
+ *
116
+ * The response is the same row shape `receipts()` emits, with the
117
+ * full canonical ReceiptV1 in `raw`.
118
+ */
119
+ async getReceipt(hash) {
120
+ if (!this.apiKey) {
121
+ throw new LeashError(401, 'getReceipt() requires an API key today. Pass `{ apiKey }` to LeashClient.', null);
122
+ }
123
+ return this.requestJson('GET', `/v1/receipts/by-hash/${encodeURIComponent(hash)}`);
124
+ }
125
+ /**
126
+ * Walk the paginated `/v1/receipts/{agent}` feed and return every
127
+ * receipt within the rolling `now - days` window. Stops early when
128
+ * `limit` is hit (default 200, max 1000) or when a row falls out of
129
+ * the window. Mirrors the `leash_transaction_history` MCP tool.
130
+ *
131
+ * Stables (USDC/USDG/USDT) are summed as USD 1:1 in the returned
132
+ * totals; non-stable receipts get counted but excluded from the USD
133
+ * math (`non_usd_count`).
134
+ */
135
+ async transactionHistory(args) {
136
+ if (!this.apiKey) {
137
+ throw new LeashError(401, 'transactionHistory() requires an API key today. Pass `{ apiKey }` to LeashClient.', null);
138
+ }
139
+ const days = clampInt(args.days ?? 7, 1, 90);
140
+ const limit = clampInt(args.limit ?? 200, 1, 1000);
141
+ const direction = args.direction ?? 'both';
142
+ const cutoffMs = Date.now() - days * 86_400_000;
143
+ const window = await this.fetchReceiptWindow({
144
+ agent: args.agentMint,
145
+ direction,
146
+ limit,
147
+ cutoffMs,
148
+ });
149
+ const totals = aggregateReceiptUsd(window.items);
150
+ const network = (window.items[0]?.network ?? 'solana-devnet');
151
+ return {
152
+ agent_mint: args.agentMint,
153
+ network,
154
+ range: {
155
+ from: new Date(cutoffMs).toISOString(),
156
+ to: new Date().toISOString(),
157
+ days,
158
+ },
159
+ direction,
160
+ count: window.items.length,
161
+ truncated: window.truncated,
162
+ total_sent_usd: totals.totalSentUsd,
163
+ total_received_usd: totals.totalReceivedUsd,
164
+ net_usd: totals.netUsd,
165
+ sent_count: totals.sentCount,
166
+ received_count: totals.receivedCount,
167
+ non_usd_count: totals.nonUsdCount,
168
+ items: window.items.map((r) => ({
169
+ receipt_hash: r.receipt_hash,
170
+ direction: r.kind === 'spend' ? 'outgoing' : 'incoming',
171
+ decision: r.decision,
172
+ tx_signature: r.tx_sig,
173
+ url: r.raw?.request?.url ?? null,
174
+ method: r.raw?.request?.method ?? null,
175
+ amount: r.raw?.price?.amount ?? null,
176
+ currency: r.raw?.price?.currency ?? null,
177
+ timestamp: r.ingested_at,
178
+ })),
179
+ };
180
+ }
181
+ /**
182
+ * Same window as {@link transactionHistory} but folds the receipts
183
+ * into per-day buckets keyed on UTC ingest date. Days with no
184
+ * activity are emitted with zeros so the timeline is continuous.
185
+ * Mirrors the `leash_daily_transactions` MCP tool.
186
+ */
187
+ async dailyTransactions(args) {
188
+ if (!this.apiKey) {
189
+ throw new LeashError(401, 'dailyTransactions() requires an API key today. Pass `{ apiKey }` to LeashClient.', null);
190
+ }
191
+ const days = clampInt(args.days ?? 7, 1, 90);
192
+ const cutoffMs = Date.now() - days * 86_400_000;
193
+ const window = await this.fetchReceiptWindow({
194
+ agent: args.agentMint,
195
+ direction: 'both',
196
+ limit: 1000,
197
+ cutoffMs,
198
+ });
199
+ const totals = aggregateReceiptUsd(window.items);
200
+ const buckets = bucketReceiptsByDay(window.items, days);
201
+ const network = (window.items[0]?.network ?? 'solana-devnet');
202
+ return {
203
+ agent_mint: args.agentMint,
204
+ network,
205
+ range: {
206
+ from: new Date(cutoffMs).toISOString(),
207
+ to: new Date().toISOString(),
208
+ days,
209
+ },
210
+ daily: buckets,
211
+ totals: {
212
+ sent_count: totals.sentCount,
213
+ sent_usd: totals.totalSentUsd,
214
+ received_count: totals.receivedCount,
215
+ received_usd: totals.totalReceivedUsd,
216
+ net_usd: totals.netUsd,
217
+ non_usd_count: totals.nonUsdCount,
218
+ },
219
+ truncated: window.truncated,
220
+ };
221
+ }
222
+ /**
223
+ * Walk the agent's receipts feed newest-first and stop once a row
224
+ * falls before `cutoffMs`, the cap is hit, or the feed is
225
+ * exhausted. Used by {@link transactionHistory} +
226
+ * {@link dailyTransactions}.
227
+ */
228
+ async fetchReceiptWindow(args) {
229
+ const items = [];
230
+ let cursor = null;
231
+ let truncated = false;
232
+ const maxPages = 10;
233
+ for (let page = 0; page < maxPages; page++) {
234
+ const params = new URLSearchParams();
235
+ params.set('limit', '200');
236
+ if (args.direction === 'outgoing')
237
+ params.set('kind', 'spend');
238
+ else if (args.direction === 'incoming')
239
+ params.set('kind', 'earn');
240
+ if (cursor)
241
+ params.set('cursor', cursor);
242
+ const json = await this.requestJson('GET', `/v1/receipts/${encodeURIComponent(args.agent)}?${params}`);
243
+ let stop = false;
244
+ for (const r of json.items) {
245
+ const ms = Date.parse(r.ingested_at);
246
+ if (Number.isFinite(ms) && ms < args.cutoffMs) {
247
+ stop = true;
248
+ break;
249
+ }
250
+ items.push(r);
251
+ if (items.length >= args.limit) {
252
+ truncated = true;
253
+ stop = true;
254
+ break;
255
+ }
256
+ }
257
+ if (stop || !json.next_cursor)
258
+ break;
259
+ cursor = json.next_cursor;
260
+ }
261
+ return { items, truncated };
262
+ }
263
+ // ── agent webhooks (X-Leash-Sig auth) ────────────────────────────
264
+ /**
265
+ * `POST /v1/agents/{mint}/webhooks` — subscribe the active agent.
266
+ * Returns the secret ONCE; persist it now or you'll have to upsert
267
+ * to rotate. Called transparently with X-Leash-Sig auth.
268
+ */
269
+ async createWebhook(args) {
270
+ this.requireAgentAuth();
271
+ const path = `/v1/agents/${this.agentMint}/webhooks`;
272
+ return this.requestJson('POST', path, {
273
+ url: args.url,
274
+ ...(args.events ? { events: args.events } : {}),
275
+ });
276
+ }
277
+ async listWebhooks() {
278
+ this.requireAgentAuth();
279
+ return this.requestJson('GET', `/v1/agents/${this.agentMint}/webhooks`);
280
+ }
281
+ async deleteWebhook(id) {
282
+ this.requireAgentAuth();
283
+ return this.requestJson('DELETE', `/v1/agents/${this.agentMint}/webhooks/${encodeURIComponent(id)}`);
284
+ }
285
+ // ── payment links (legacy API-key auth) ──────────────────────────
286
+ //
287
+ // These wrap `/v1/payment-links/*`. Today the API authenticates
288
+ // them via the bearer-token API key, so callers must construct
289
+ // `LeashClient` with `{ apiKey }`. We expose them here because they
290
+ // are pure HTTP — no Solana signing — so they belong in the thin
291
+ // client. To *pay* one programmatically, see `@leashmarket/buyer-kit` or
292
+ // `@leashmarket/mcp`'s `pay()` host method (both sign locally).
293
+ async createPaymentLink(input) {
294
+ this.requireApiKey('createPaymentLink');
295
+ return this.requestJson('POST', '/v1/payment-links', input);
296
+ }
297
+ async listPaymentLinks(query = {}) {
298
+ this.requireApiKey('listPaymentLinks');
299
+ const params = new URLSearchParams();
300
+ if (query.ownerAgent)
301
+ params.set('owner_agent', query.ownerAgent);
302
+ if (query.includeDisabled != null) {
303
+ params.set('include_disabled', query.includeDisabled ? 'true' : 'false');
304
+ }
305
+ if (query.cursor)
306
+ params.set('cursor', query.cursor);
307
+ if (query.limit)
308
+ params.set('limit', String(query.limit));
309
+ return this.requestJson('GET', `/v1/payment-links${params.toString() ? `?${params}` : ''}`);
310
+ }
311
+ async getPaymentLink(id) {
312
+ this.requireApiKey('getPaymentLink');
313
+ return this.requestJson('GET', `/v1/payment-links/${encodeURIComponent(id)}`);
314
+ }
315
+ async updatePaymentLink(id, patch) {
316
+ this.requireApiKey('updatePaymentLink');
317
+ return this.requestJson('PATCH', `/v1/payment-links/${encodeURIComponent(id)}`, patch);
318
+ }
319
+ async deletePaymentLink(id) {
320
+ this.requireApiKey('deletePaymentLink');
321
+ return this.requestJson('DELETE', `/v1/payment-links/${encodeURIComponent(id)}`);
322
+ }
323
+ // ── internals ────────────────────────────────────────────────────
324
+ requireApiKey(method) {
325
+ if (!this.apiKey) {
326
+ throw new LeashError(401, `${method}() requires an API key today. Pass \`{ apiKey }\` to LeashClient.`, null);
327
+ }
328
+ }
329
+ requireAgentAuth() {
330
+ if (!this.agentMint || !this.executiveSecretBase58) {
331
+ throw new LeashError(401, 'this method requires an agent identity. Pass `{ agentMint, executiveSecretBase58 }` to LeashClient.', null);
332
+ }
333
+ }
334
+ /**
335
+ * Fire one HTTP request, signing it with X-Leash-Sig when the
336
+ * caller provided an agent identity AND the path is one of the
337
+ * agent-scoped endpoints. Public/legacy paths skip signing and
338
+ * fall back to the API-key bearer if available.
339
+ */
340
+ async requestJson(method, pathWithQuery, body) {
341
+ const url = `${this.baseUrl}${pathWithQuery}`;
342
+ const bodyText = body == null ? undefined : JSON.stringify(body);
343
+ const headers = {
344
+ accept: 'application/json',
345
+ };
346
+ if (bodyText)
347
+ headers['content-type'] = 'application/json';
348
+ const isAgentScoped = this.agentMint &&
349
+ this.executiveSecretBase58 &&
350
+ pathWithQuery.startsWith(`/v1/agents/${this.agentMint}`);
351
+ if (isAgentScoped) {
352
+ const sig = await signRequest({
353
+ method,
354
+ pathWithQuery,
355
+ body: bodyText,
356
+ agentMint: this.agentMint,
357
+ executiveSecretBase58: this.executiveSecretBase58,
358
+ });
359
+ Object.assign(headers, sig);
360
+ }
361
+ else if (this.apiKey) {
362
+ headers['authorization'] = `Bearer ${this.apiKey}`;
363
+ }
364
+ const res = await this.fetchImpl(url, {
365
+ method,
366
+ headers,
367
+ ...(bodyText ? { body: bodyText } : {}),
368
+ });
369
+ const text = await res.text();
370
+ let parsed = null;
371
+ try {
372
+ parsed = text.length > 0 ? JSON.parse(text) : null;
373
+ }
374
+ catch {
375
+ parsed = text;
376
+ }
377
+ if (!res.ok) {
378
+ const message = (parsed && typeof parsed === 'object' && 'message' in parsed
379
+ ? String(parsed.message)
380
+ : `HTTP ${res.status}`) ?? `HTTP ${res.status}`;
381
+ throw new LeashError(res.status, message, parsed);
382
+ }
383
+ return parsed;
384
+ }
385
+ }
386
+ // ────────────────────────────────────────────────────────────────────────────
387
+ // Pure helpers (kept module-local — not exported)
388
+ // ────────────────────────────────────────────────────────────────────────────
389
+ const SDK_USD_STABLES = new Set(['USDC', 'USDG', 'USDT']);
390
+ function clampInt(n, min, max) {
391
+ if (!Number.isFinite(n))
392
+ return min;
393
+ return Math.max(min, Math.min(max, Math.floor(n)));
394
+ }
395
+ function aggregateReceiptUsd(items) {
396
+ let sentCount = 0;
397
+ let receivedCount = 0;
398
+ let nonUsdCount = 0;
399
+ let sentSum = 0;
400
+ let receivedSum = 0;
401
+ for (const r of items) {
402
+ const price = r.raw?.price;
403
+ const amt = parseFloat(price?.amount ?? '');
404
+ const cur = (price?.currency ?? '').toUpperCase();
405
+ if (r.kind === 'spend')
406
+ sentCount++;
407
+ else if (r.kind === 'earn')
408
+ receivedCount++;
409
+ if (!Number.isFinite(amt) || !cur)
410
+ continue;
411
+ if (!SDK_USD_STABLES.has(cur)) {
412
+ nonUsdCount++;
413
+ continue;
414
+ }
415
+ if (r.kind === 'spend')
416
+ sentSum += amt;
417
+ else if (r.kind === 'earn')
418
+ receivedSum += amt;
419
+ }
420
+ const round = (n) => Math.round(n * 1_000_000) / 1_000_000;
421
+ return {
422
+ sentCount,
423
+ receivedCount,
424
+ nonUsdCount,
425
+ totalSentUsd: round(sentSum).toString(),
426
+ totalReceivedUsd: round(receivedSum).toString(),
427
+ netUsd: round(receivedSum - sentSum).toString(),
428
+ };
429
+ }
430
+ function bucketReceiptsByDay(items, days) {
431
+ const map = new Map();
432
+ const today = new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), new Date().getUTCDate()));
433
+ for (let i = 0; i < days; i++) {
434
+ const d = new Date(today.getTime() - i * 86_400_000);
435
+ map.set(formatUtcDate(d), { sentCount: 0, sentSum: 0, receivedCount: 0, receivedSum: 0 });
436
+ }
437
+ for (const r of items) {
438
+ const ingested = new Date(r.ingested_at);
439
+ if (Number.isNaN(ingested.getTime()))
440
+ continue;
441
+ const key = formatUtcDate(ingested);
442
+ let bucket = map.get(key);
443
+ if (!bucket) {
444
+ bucket = { sentCount: 0, sentSum: 0, receivedCount: 0, receivedSum: 0 };
445
+ map.set(key, bucket);
446
+ }
447
+ if (r.kind === 'spend')
448
+ bucket.sentCount++;
449
+ else if (r.kind === 'earn')
450
+ bucket.receivedCount++;
451
+ const price = r.raw?.price;
452
+ const amt = parseFloat(price?.amount ?? '');
453
+ const cur = (price?.currency ?? '').toUpperCase();
454
+ if (!Number.isFinite(amt) || !SDK_USD_STABLES.has(cur))
455
+ continue;
456
+ if (r.kind === 'spend')
457
+ bucket.sentSum += amt;
458
+ else if (r.kind === 'earn')
459
+ bucket.receivedSum += amt;
460
+ }
461
+ const round = (n) => Math.round(n * 1_000_000) / 1_000_000;
462
+ return [...map.entries()]
463
+ .sort((a, b) => (a[0] < b[0] ? 1 : -1))
464
+ .map(([date, b]) => ({
465
+ date,
466
+ sent_count: b.sentCount,
467
+ sent_usd: round(b.sentSum).toString(),
468
+ received_count: b.receivedCount,
469
+ received_usd: round(b.receivedSum).toString(),
470
+ net_usd: round(b.receivedSum - b.sentSum).toString(),
471
+ }));
472
+ }
473
+ function formatUtcDate(d) {
474
+ const y = d.getUTCFullYear();
475
+ const m = String(d.getUTCMonth() + 1).padStart(2, '0');
476
+ const day = String(d.getUTCDate()).padStart(2, '0');
477
+ return `${y}-${m}-${day}`;
478
+ }
479
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAwCxC,MAAM,OAAO,UAAW,SAAQ,KAAK;IAC1B,MAAM,CAAS;IACf,IAAI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O,GAAG,CAAC,IAAI,CAAC,IAAI,GAAG,EAAE,CAAC;AAC5B,CAAC"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * `@leashmarket/sdk` — typed Leash API client.
3
+ *
4
+ * import { LeashClient } from '@leashmarket/sdk';
5
+ *
6
+ * const leash = new LeashClient({ baseUrl: 'https://api.leash.market' });
7
+ * const services = await leash.discover({ capability: 'ocr' });
8
+ * const rep = await leash.reputation({ agentMint: services.items[0].seller_agent_mint! });
9
+ *
10
+ * Browser/Bun/Deno friendly — uses `fetch` + `globalThis.crypto.subtle`
11
+ * with a Node `node:crypto` fallback. No process/fs imports at module
12
+ * load time.
13
+ */
14
+ export { LeashClient, LeashError, type LeashClientOptions } from './client.js';
15
+ export { signRequest, buildEnvelope, type SigningHeaders, type SigningEnvelope } from './sign.js';
16
+ export type { AgentWebhook, AgentWebhookWithSecret, DailyTransactionsResponse, DailyTxBucket, DiscoverItem, DiscoverResponse, EndpointMethod, LeashFeeExtra, PaymentLink, PaymentLinkAcceptsEntry, PaymentLinkCreateInput, PaymentLinkPatchInput, PaymentLinkResponseTemplate, PaymentLinksListResponse, Receipt, ReceiptsResponse, RecordAgentInput, RecordAgentResponse, ReputationSnapshot, StableSymbol, SvmNetwork, TransactionHistoryItem, TransactionHistoryResponse, } from './types.js';
17
+ export declare const LEASH_SDK_VERSION = "0.1.0";
18
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,KAAK,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAC/E,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,KAAK,cAAc,EAAE,KAAK,eAAe,EAAE,MAAM,WAAW,CAAC;AAElG,YAAY,EACV,YAAY,EACZ,sBAAsB,EACtB,yBAAyB,EACzB,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,WAAW,EACX,uBAAuB,EACvB,sBAAsB,EACtB,qBAAqB,EACrB,2BAA2B,EAC3B,wBAAwB,EACxB,OAAO,EACP,gBAAgB,EAChB,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,YAAY,EACZ,UAAU,EACV,sBAAsB,EACtB,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AAEpB,eAAO,MAAM,iBAAiB,UAAU,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `@leashmarket/sdk` — typed Leash API client.
3
+ *
4
+ * import { LeashClient } from '@leashmarket/sdk';
5
+ *
6
+ * const leash = new LeashClient({ baseUrl: 'https://api.leash.market' });
7
+ * const services = await leash.discover({ capability: 'ocr' });
8
+ * const rep = await leash.reputation({ agentMint: services.items[0].seller_agent_mint! });
9
+ *
10
+ * Browser/Bun/Deno friendly — uses `fetch` + `globalThis.crypto.subtle`
11
+ * with a Node `node:crypto` fallback. No process/fs imports at module
12
+ * load time.
13
+ */
14
+ export { LeashClient, LeashError } from './client.js';
15
+ export { signRequest, buildEnvelope } from './sign.js';
16
+ export const LEASH_SDK_VERSION = '0.1.0';
17
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,WAAW,EAAE,UAAU,EAA2B,MAAM,aAAa,CAAC;AAC/E,OAAO,EAAE,WAAW,EAAE,aAAa,EAA6C,MAAM,WAAW,CAAC;AA4BlG,MAAM,CAAC,MAAM,iBAAiB,GAAG,OAAO,CAAC"}
package/dist/sign.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Build the canonical X-Leash-Sig envelope and ed25519 signature for
3
+ * authenticated agent requests.
4
+ *
5
+ * Mirrors `apps/api/src/auth/onchain.ts::buildSigningEnvelope` byte
6
+ * for byte. The two implementations are kept in deliberate sync:
7
+ * `packages/sdk` is browser/Bun/Deno-friendly (uses
8
+ * `@metaplex-foundation/umi` for the eddsa primitives + a pure-JS
9
+ * SHA-256 fallback), while the API uses Node's `node:crypto`.
10
+ *
11
+ * Callers shouldn't need to call this directly — `LeashClient`
12
+ * stamps the headers on every authenticated request — but it's
13
+ * exported for tests and tools that build their own request loop.
14
+ */
15
+ export type SigningEnvelope = {
16
+ method: string;
17
+ pathWithQuery: string;
18
+ timestamp: string;
19
+ body: Uint8Array | string | undefined;
20
+ agentMint: string;
21
+ };
22
+ export type SigningHeaders = {
23
+ 'x-leash-agent': string;
24
+ 'x-leash-timestamp': string;
25
+ 'x-leash-sig': string;
26
+ };
27
+ /**
28
+ * Build the bytes the executive signs. Hashes the request body so we
29
+ * commit to it without copying it verbatim into the canonical string.
30
+ */
31
+ export declare function buildEnvelope(args: SigningEnvelope): Promise<Uint8Array>;
32
+ /**
33
+ * Sign an envelope and return the three headers the API verifier
34
+ * expects. `executiveSecretBase58` must decode to a 64-byte ed25519
35
+ * keypair (the same `solana-keygen output` format used by every
36
+ * other Leash surface).
37
+ */
38
+ export declare function signRequest(args: {
39
+ method: string;
40
+ pathWithQuery: string;
41
+ body: Uint8Array | string | undefined;
42
+ agentMint: string;
43
+ executiveSecretBase58: string;
44
+ /** Override for tests. Defaults to current time. */
45
+ timestamp?: string;
46
+ }): Promise<SigningHeaders>;
47
+ //# sourceMappingURL=sign.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign.d.ts","sourceRoot":"","sources":["../src/sign.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAUH,MAAM,MAAM,eAAe,GAAG;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,UAAU,GAAG,MAAM,GAAG,SAAS,CAAC;IACtC,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC3B,eAAe,EAAE,MAAM,CAAC;IACxB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF;;;GAGG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,UAAU,CAAC,CAgB9E;AAED;;;;;GAKG;AACH,wBAAsB,WAAW,CAAC,IAAI,EAAE;IACtC,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,IAAI,EAAE,UAAU,GAAG,MAAM,GAAG,SAAS,CAAC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,qBAAqB,EAAE,MAAM,CAAC;IAC9B,oDAAoD;IACpD,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG,OAAO,CAAC,cAAc,CAAC,CAoB1B"}