@purseragents/sdk 0.0.0-stage → 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.
@@ -0,0 +1,91 @@
1
+ import { decodeHeader, encodeHeader, HEADER_REQUIRED, HEADER_RESPONSE, HEADER_SIGNATURE, HEADER_V1_PAYMENT, } from "./x402.js";
2
+ export function requirementsFor(o) {
3
+ return {
4
+ scheme: "exact",
5
+ network: o.network ?? "eip155:4663",
6
+ amount: o.price.toString(),
7
+ asset: o.asset,
8
+ payTo: o.payTo,
9
+ maxTimeoutSeconds: o.maxTimeoutSeconds ?? 120,
10
+ extra: { name: o.tokenName ?? "Global Dollar", version: o.tokenVersion ?? "1" },
11
+ };
12
+ }
13
+ /** Framework-neutral check: returns either the 402 to send, or a verified payment to settle after the work. */
14
+ export async function checkPayment(o, url, headers) {
15
+ const f = o.fetch ?? fetch;
16
+ const req = requirementsFor(o);
17
+ const required = (error) => {
18
+ const body = {
19
+ x402Version: 2,
20
+ ...(error ? { error } : {}),
21
+ resource: { url, description: o.description, mimeType: o.mimeType ?? "application/json", serviceName: o.serviceName },
22
+ accepts: [req],
23
+ };
24
+ return { kind: "pay", status: 402, headers: { [HEADER_REQUIRED]: encodeHeader(body), "content-type": "application/json" }, body };
25
+ };
26
+ const raw = headers.get(HEADER_SIGNATURE) ?? headers.get(HEADER_SIGNATURE.toLowerCase()) ?? headers.get(HEADER_V1_PAYMENT) ?? headers.get(HEADER_V1_PAYMENT.toLowerCase());
27
+ if (!raw)
28
+ return required();
29
+ const payment = decodeHeader(raw);
30
+ if (!payment)
31
+ return required("invalid_payment_header");
32
+ const call = async (path) => {
33
+ const r = await f(`${o.facilitatorUrl.replace(/\/$/, "")}/${path}`, {
34
+ method: "POST",
35
+ headers: { "content-type": "application/json" },
36
+ body: JSON.stringify({ x402Version: 2, paymentPayload: payment, paymentRequirements: req }),
37
+ });
38
+ return (await r.json());
39
+ };
40
+ const v = await call("verify");
41
+ if (!v.isValid)
42
+ return required(v.invalidReason ?? "invalid_payment");
43
+ return { kind: "ok", payment, payer: v.payer, settle: () => call("settle") };
44
+ }
45
+ /** Hono middleware. Settles after the handler answered with a status below 400. */
46
+ export function purserPaywall(o) {
47
+ return async (c, next) => {
48
+ const d = await checkPayment(o, c.req.url, { get: (n) => c.req.header(n) });
49
+ if (d.kind === "pay")
50
+ return c.json(d.body, 402, d.headers);
51
+ c.set?.("x402Payer", d.payer);
52
+ await next();
53
+ if (c.res.status >= 400)
54
+ return;
55
+ const s = await d.settle();
56
+ if (!s.success) {
57
+ c.res = c.json({ error: "payment_failed", reason: s.errorReason }, 402);
58
+ return;
59
+ }
60
+ c.res.headers.set(HEADER_RESPONSE, encodeHeader(s));
61
+ };
62
+ }
63
+ /** Express middleware. Settles when the response finishes with a status below 400. */
64
+ export function purserPaywallExpress(o) {
65
+ return async (req, res, next) => {
66
+ try {
67
+ const url = `${req.protocol}://${req.get?.("host") ?? req.headers.host}${req.originalUrl ?? req.url}`;
68
+ const d = await checkPayment(o, url, { get: (n) => req.headers[n.toLowerCase()] });
69
+ if (d.kind === "pay") {
70
+ for (const [k, v] of Object.entries(d.headers))
71
+ res.setHeader(k, v);
72
+ res.status(402).json(d.body);
73
+ return;
74
+ }
75
+ req.x402Payer = d.payer;
76
+ const end = res.end.bind(res);
77
+ res.end = async (...args) => {
78
+ if (res.statusCode < 400) {
79
+ const s = await d.settle();
80
+ if (s.success)
81
+ res.setHeader(HEADER_RESPONSE, encodeHeader(s));
82
+ }
83
+ return end(...args);
84
+ };
85
+ next();
86
+ }
87
+ catch (e) {
88
+ next(e);
89
+ }
90
+ };
91
+ }
@@ -0,0 +1,583 @@
1
+ /**
2
+ * Purser engine API schema. These types describe every JSON body the engine returns (docs/API.md).
3
+ * The website mirrors this file; keep it free of runtime dependencies.
4
+ *
5
+ * Conventions:
6
+ * - Amounts are strings in base units (wei / token units). `display` fields are human-readable strings.
7
+ * - Addresses are lowercase 0x strings. Compare them case-insensitively.
8
+ * - Times are unix seconds (numbers) unless the field name ends with `Iso`.
9
+ * - A limit of `null` means "no cap"; a threshold of `null` means "never".
10
+ */
11
+ export type Address = `0x${string}`;
12
+ export type Hex = `0x${string}`;
13
+ export type Amount = string;
14
+ export interface TokenInfo {
15
+ address: Address;
16
+ symbol: string;
17
+ decimals: number;
18
+ }
19
+ export interface Money {
20
+ token: TokenInfo;
21
+ amount: Amount;
22
+ display: string;
23
+ usd: string | null;
24
+ }
25
+ export interface TokenRule {
26
+ token: TokenInfo;
27
+ enabled: boolean;
28
+ receivable: boolean;
29
+ maxSingle: Amount | null;
30
+ daily: Amount | null;
31
+ weekly: Amount | null;
32
+ perCounterpartyDaily: Amount | null;
33
+ approvalAbove: Amount | null;
34
+ cosignAbove: Amount | null;
35
+ keepLiquid: Amount;
36
+ }
37
+ export interface AccountConfig {
38
+ agent: Address;
39
+ cosigner: Address | null;
40
+ firewall: Address | null;
41
+ watchdog: Address | null;
42
+ maxPerMinute: number | null;
43
+ hoursUtc: number[];
44
+ weekdays: number[];
45
+ payeeAllowlist: boolean;
46
+ serviceAllowlist: boolean;
47
+ }
48
+ export type AgentKind = "research" | "trading" | "support" | "coding" | "content" | "ops" | "seller" | "custom";
49
+ export interface SpendToday {
50
+ token: TokenInfo;
51
+ spent: Amount;
52
+ remaining: Amount | null;
53
+ display: string;
54
+ }
55
+ export interface AccountSummary {
56
+ safe: Address;
57
+ name: string;
58
+ kind: AgentKind;
59
+ owners: Address[];
60
+ frozen: boolean;
61
+ public: boolean;
62
+ agentId: string | null;
63
+ balanceUsd: string | null;
64
+ spentTodayUsd: string;
65
+ earnedTodayUsd: string;
66
+ receiptsToday: number;
67
+ pendingApprovals: number;
68
+ teamId: string | null;
69
+ createdAt: number;
70
+ }
71
+ export interface Account extends AccountSummary {
72
+ threshold: number;
73
+ config: AccountConfig;
74
+ rules: TokenRule[];
75
+ balances: Money[];
76
+ spentToday: SpendToday[];
77
+ allowlist: Address[];
78
+ services: Hex[];
79
+ treasuryVaults: Address[];
80
+ splits: Split[];
81
+ extensions: Address[];
82
+ approver: Address | null;
83
+ guardian: {
84
+ address: Address;
85
+ delaySeconds: number;
86
+ } | null;
87
+ recovery: {
88
+ executeAfter: number;
89
+ } | null;
90
+ }
91
+ export type ReceiptCategory = "model" | "x402" | "onchain" | "swap" | "stream" | "subscription" | "escrow" | "split" | "internal" | "storefront" | "transfer" | "treasury";
92
+ export type IntentStatus = "blocked" | "needs_cosign" | "queued" | "held" | "approved" | "rejected" | "submitted" | "executed" | "failed" | "ready";
93
+ export interface Receipt {
94
+ id: string;
95
+ safe: Address;
96
+ direction: "out" | "in";
97
+ category: ReceiptCategory;
98
+ money: Money;
99
+ fee: Money | null;
100
+ counterparty: Address;
101
+ counterpartyName: string | null;
102
+ service: string | null;
103
+ memo: string | null;
104
+ status: IntentStatus;
105
+ txHash: Hex | null;
106
+ intentId: string | null;
107
+ verdictId: string | null;
108
+ taskId: string | null;
109
+ customer: string | null;
110
+ model: ModelUsage | null;
111
+ createdAt: number;
112
+ }
113
+ export interface ModelUsage {
114
+ provider: string;
115
+ model: string;
116
+ promptTokens: number;
117
+ completionTokens: number;
118
+ }
119
+ export interface Intent {
120
+ id: string;
121
+ safe: Address;
122
+ kind: "pay" | "call" | "treasury" | "stream" | "subscription" | "escrow";
123
+ digest: Hex;
124
+ status: IntentStatus;
125
+ summary: string;
126
+ money: Money | null;
127
+ to: Address | null;
128
+ verdictId: string | null;
129
+ txHash: Hex | null;
130
+ error: string | null;
131
+ createdAt: number;
132
+ updatedAt: number;
133
+ }
134
+ export interface PayResult {
135
+ intent: Intent;
136
+ verdict: Verdict;
137
+ receipt: Receipt | null;
138
+ }
139
+ export interface PendingApproval {
140
+ id: string;
141
+ safe: Address;
142
+ digest: Hex;
143
+ rejectChallenge: Hex;
144
+ summary: string;
145
+ money: Money | null;
146
+ to: Address | null;
147
+ status: "queued" | "approved" | "rejected";
148
+ createdAt: number;
149
+ }
150
+ export type VerdictDecision = "allow" | "block";
151
+ export interface VerdictReason {
152
+ code: string;
153
+ severity: "info" | "warn" | "block";
154
+ title: string;
155
+ detail: string;
156
+ }
157
+ export interface AssetChange {
158
+ token: TokenInfo;
159
+ from: Address;
160
+ to: Address;
161
+ amount: Amount;
162
+ display: string;
163
+ }
164
+ export interface SimulationSummary {
165
+ backend: "eth_simulateV1" | "debug_traceCall" | "none";
166
+ success: boolean;
167
+ revertReason: string | null;
168
+ gasUsed: string;
169
+ assetChanges: AssetChange[];
170
+ approvals: {
171
+ token: Address;
172
+ owner: Address;
173
+ spender: Address;
174
+ amount: Amount;
175
+ }[];
176
+ calls: {
177
+ from: Address;
178
+ to: Address;
179
+ selector: Hex | null;
180
+ value: Amount;
181
+ }[];
182
+ balanceBefore: Money[];
183
+ balanceAfter: Money[];
184
+ }
185
+ export interface Verdict {
186
+ id: string;
187
+ safe: Address;
188
+ intentId: string | null;
189
+ decision: VerdictDecision;
190
+ summary: string;
191
+ reasons: VerdictReason[];
192
+ simulation: SimulationSummary | null;
193
+ trigger: string | null;
194
+ createdAt: number;
195
+ }
196
+ export interface WatchdogBaseline {
197
+ safe: Address;
198
+ samples: number;
199
+ hourlyMeanUsd: string;
200
+ hourlyStdUsd: string;
201
+ knownCounterparties: number;
202
+ autoFreeze: boolean;
203
+ updatedAt: number;
204
+ }
205
+ export interface WatchdogEvent {
206
+ id: string;
207
+ safe: Address;
208
+ kind: "spike" | "new_counterparty" | "loop" | "burst" | "drain" | "shield";
209
+ severity: "warn" | "critical";
210
+ title: string;
211
+ detail: string;
212
+ action: "alert" | "freeze";
213
+ txHash: Hex | null;
214
+ createdAt: number;
215
+ }
216
+ export interface AuditEntry {
217
+ seq: number;
218
+ ts: number;
219
+ actor: string;
220
+ action: string;
221
+ safe: Address | null;
222
+ data: Record<string, unknown>;
223
+ prevHash: Hex;
224
+ hash: Hex;
225
+ signature: Hex;
226
+ }
227
+ export interface AuditVerifyResult {
228
+ ok: boolean;
229
+ entries: number;
230
+ signer: Address;
231
+ brokenAt: number | null;
232
+ problem: string | null;
233
+ }
234
+ export interface Stream {
235
+ id: string;
236
+ safe: Address;
237
+ payee: Address;
238
+ token: TokenInfo;
239
+ ratePerSecond: Amount;
240
+ start: number;
241
+ end: number;
242
+ settledUntil: number;
243
+ lastBeat: number;
244
+ grace: number;
245
+ status: "active" | "stalled" | "stopped" | "ended";
246
+ accrued: Money;
247
+ paid: Money;
248
+ }
249
+ export interface Subscription {
250
+ id: string;
251
+ safe: Address;
252
+ payee: Address;
253
+ token: TokenInfo;
254
+ amount: Money;
255
+ periodSeconds: number;
256
+ nextDue: number;
257
+ chargesLeft: number;
258
+ active: boolean;
259
+ charged: number;
260
+ }
261
+ export interface StoreService {
262
+ id: string;
263
+ safe: Address;
264
+ name: string;
265
+ description: string;
266
+ pricing: {
267
+ model: "per_call" | "per_minute" | "subscription";
268
+ price: Money;
269
+ periodSeconds: number | null;
270
+ };
271
+ endpoint: string;
272
+ uses: number;
273
+ revenue: Money;
274
+ active: boolean;
275
+ createdAt: number;
276
+ }
277
+ export interface Split {
278
+ to: Address;
279
+ bps: number;
280
+ label: string | null;
281
+ }
282
+ export type InvoiceStatus = "open" | "funded" | "delivered" | "disputed" | "released" | "refunded" | "resolved";
283
+ export interface Invoice {
284
+ id: string;
285
+ payee: Address;
286
+ payer: Address;
287
+ arbiter: Address | null;
288
+ money: Money;
289
+ description: string;
290
+ deadline: number;
291
+ reviewPeriodSeconds: number;
292
+ reviewUntil: number | null;
293
+ status: InvoiceStatus;
294
+ jobId: string | null;
295
+ deliveryHash: Hex | null;
296
+ createdAt: number;
297
+ updatedAt: number;
298
+ }
299
+ export interface TreasuryVault {
300
+ address: Address;
301
+ name: string;
302
+ asset: TokenInfo;
303
+ totalAssets: Money;
304
+ kind: "erc4626";
305
+ }
306
+ export interface TreasuryPosition {
307
+ vault: TreasuryVault;
308
+ shares: Amount;
309
+ assets: Money;
310
+ }
311
+ export interface Treasury {
312
+ safe: Address;
313
+ liquid: Money[];
314
+ positions: TreasuryPosition[];
315
+ allowedVaults: Address[];
316
+ keepLiquid: {
317
+ token: TokenInfo;
318
+ amount: Amount;
319
+ }[];
320
+ }
321
+ export interface Department {
322
+ id: string;
323
+ name: string;
324
+ dailyBudget: Money | null;
325
+ spentToday: Money;
326
+ }
327
+ export interface TeamMember {
328
+ safe: Address;
329
+ name: string;
330
+ departmentId: string | null;
331
+ role: string;
332
+ dailyBudget: Money | null;
333
+ spentToday: Money;
334
+ }
335
+ export interface Team {
336
+ id: string;
337
+ name: string;
338
+ treasury: Address;
339
+ owner: Address;
340
+ departments: Department[];
341
+ members: TeamMember[];
342
+ createdAt: number;
343
+ }
344
+ export interface OrgChartNode {
345
+ id: string;
346
+ label: string;
347
+ kind: "team" | "department" | "agent";
348
+ safe: Address | null;
349
+ children: OrgChartNode[];
350
+ }
351
+ export interface PnlLine {
352
+ key: string;
353
+ label: string;
354
+ income: string;
355
+ spend: string;
356
+ count: number;
357
+ }
358
+ export interface Pnl {
359
+ scope: {
360
+ safe: Address | null;
361
+ teamId: string | null;
362
+ };
363
+ from: number;
364
+ to: number;
365
+ incomeUsd: string;
366
+ spendUsd: string;
367
+ feesUsd: string;
368
+ profitUsd: string;
369
+ byCategory: PnlLine[];
370
+ byModel: PnlLine[];
371
+ byTask: PnlLine[];
372
+ byCustomer: PnlLine[];
373
+ byDay: {
374
+ day: string;
375
+ incomeUsd: string;
376
+ spendUsd: string;
377
+ }[];
378
+ }
379
+ export interface DirectoryEntry {
380
+ id: string;
381
+ name: string;
382
+ url: string;
383
+ payTo: Address;
384
+ source: "storefront" | "x402";
385
+ price: Money | null;
386
+ uses: number;
387
+ payers: number;
388
+ deliveryRate: number | null;
389
+ refunds: number;
390
+ lastUsed: number | null;
391
+ }
392
+ export interface PriceIndexPoint {
393
+ category: string;
394
+ unit: string;
395
+ priceUsd: string;
396
+ samples: number;
397
+ change24h: number | null;
398
+ }
399
+ export interface Economy {
400
+ totals: {
401
+ spendUsd: string;
402
+ earnUsd: string;
403
+ payments: number;
404
+ agents: number;
405
+ services: number;
406
+ blocked: number;
407
+ };
408
+ last24h: {
409
+ spendUsd: string;
410
+ earnUsd: string;
411
+ payments: number;
412
+ };
413
+ topServices: DirectoryEntry[];
414
+ priceIndex: PriceIndexPoint[];
415
+ series: {
416
+ t: number;
417
+ spendUsd: string;
418
+ earnUsd: string;
419
+ }[];
420
+ }
421
+ export interface LeaderboardEntry {
422
+ rank: number;
423
+ safe: Address;
424
+ name: string;
425
+ kind: AgentKind;
426
+ earnedUsd: string;
427
+ spentUsd: string;
428
+ profitUsd: string;
429
+ payments: number;
430
+ }
431
+ export interface PublicAgent {
432
+ safe: Address;
433
+ name: string;
434
+ kind: AgentKind;
435
+ agentId: string | null;
436
+ earnedUsd: string;
437
+ spentUsd: string;
438
+ profitUsd: string;
439
+ receipts: Receipt[];
440
+ rules: TokenRule[];
441
+ services: StoreService[];
442
+ createdAt: number;
443
+ }
444
+ export interface Template {
445
+ id: string;
446
+ name: string;
447
+ kind: AgentKind;
448
+ description: string;
449
+ highlights: string[];
450
+ config: Omit<AccountConfig, "agent" | "cosigner" | "firewall" | "watchdog"> & {
451
+ useFirewall: boolean;
452
+ useWatchdog: boolean;
453
+ };
454
+ rules: Omit<TokenRule, "token" | "enabled" | "receivable">;
455
+ alerts: {
456
+ kind: AlertKind;
457
+ threshold: string | null;
458
+ }[];
459
+ }
460
+ export type AlertKind = "payment_blocked" | "approval_needed" | "frozen" | "spend_over" | "balance_under" | "income";
461
+ export type WebhookEventType = "receipt.created" | "intent.blocked" | "intent.queued" | "intent.executed" | "approval.decided" | "watchdog.alert" | "account.frozen" | "account.unfrozen" | "invoice.updated" | "stream.updated" | "alert";
462
+ export interface Webhook {
463
+ id: string;
464
+ url: string;
465
+ events: WebhookEventType[];
466
+ safe: Address | null;
467
+ active: boolean;
468
+ createdAt: number;
469
+ }
470
+ export interface WebhookDelivery {
471
+ id: string;
472
+ webhookId: string;
473
+ event: WebhookEventType;
474
+ status: "delivered" | "failed" | "pending";
475
+ attempts: number;
476
+ responseCode: number | null;
477
+ createdAt: number;
478
+ }
479
+ export interface Alert {
480
+ id: string;
481
+ safe: Address;
482
+ kind: AlertKind;
483
+ threshold: string | null;
484
+ createdAt: number;
485
+ }
486
+ export interface ApiKey {
487
+ id: string;
488
+ safe: Address;
489
+ name: string;
490
+ prefix: string;
491
+ scopes: ApiScope[];
492
+ sessionAddress: Address | null;
493
+ createdAt: number;
494
+ lastUsedAt: number | null;
495
+ revokedAt: number | null;
496
+ }
497
+ export type ApiScope = "pay" | "models" | "x402" | "call" | "sell" | "read" | "treasury" | "recurring" | "invoices";
498
+ export interface PreparedTx {
499
+ chainId: number;
500
+ to: Address;
501
+ data: Hex;
502
+ value: Amount;
503
+ description: string;
504
+ }
505
+ export interface PreparedSafeTx {
506
+ chainId: number;
507
+ safe: Address;
508
+ to: Address;
509
+ value: Amount;
510
+ data: Hex;
511
+ operation: 0 | 1;
512
+ nonce: string;
513
+ safeTxHash: Hex;
514
+ typedData: unknown;
515
+ description: string;
516
+ }
517
+ export interface Page<T> {
518
+ items: T[];
519
+ next: string | null;
520
+ }
521
+ export interface ApiError {
522
+ error: {
523
+ code: string;
524
+ message: string;
525
+ };
526
+ }
527
+ export interface Health {
528
+ ok: boolean;
529
+ mode: "local" | "fork" | "readonly" | "live";
530
+ chainId: number;
531
+ block: string | null;
532
+ broadcast: boolean;
533
+ contracts: Record<string, Address | null>;
534
+ version: string;
535
+ }
536
+ export type EngineEventType = "receipt" | "intent" | "verdict" | "approval" | "watchdog" | "account" | "stream" | "subscription" | "invoice" | "audit" | "alert" | "demo";
537
+ export interface EngineEvent<T = unknown> {
538
+ id: number;
539
+ type: EngineEventType;
540
+ safe: Address | null;
541
+ ts: number;
542
+ data: T;
543
+ }
544
+ export interface DemoStep {
545
+ step: number;
546
+ title: string;
547
+ detail: string;
548
+ status: "running" | "ok" | "blocked" | "error";
549
+ data?: Record<string, unknown>;
550
+ }
551
+ /** What a Shield match does on an account: refuse the payment, or hold it for the owner. */
552
+ export type ShieldMode = "block" | "warn";
553
+ /** An attacker address on the shared list. Only the attacker's side: never who was attacked or what they hold. */
554
+ export interface ShieldThreat {
555
+ address: Address;
556
+ kind: "planted_payee" | "forwarding_wallet" | "forwarding_code" | "spender";
557
+ what: string;
558
+ attacks: number;
559
+ /** how many accounts it was aimed at, never which */
560
+ accounts: number;
561
+ /** payments to it the Shield stopped on other accounts */
562
+ stoppedElsewhere: number;
563
+ firstSeen: number;
564
+ lastSeen: number;
565
+ }
566
+ /** A one-way fingerprint of a sentence of injected instructions. The sentence itself is not shared. */
567
+ export interface ShieldPrint {
568
+ print: string;
569
+ why: string;
570
+ attacks: number;
571
+ accounts: number;
572
+ stoppedElsewhere: number;
573
+ firstSeen: number;
574
+ lastSeen: number;
575
+ }
576
+ export interface ShieldStats {
577
+ addresses: number;
578
+ prints: number;
579
+ attacksCaught: number;
580
+ stoppedByShield: number;
581
+ accountsProtected: number;
582
+ lastFlaggedAt: number | null;
583
+ }
package/dist/schema.js ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Purser engine API schema. These types describe every JSON body the engine returns (docs/API.md).
3
+ * The website mirrors this file; keep it free of runtime dependencies.
4
+ *
5
+ * Conventions:
6
+ * - Amounts are strings in base units (wei / token units). `display` fields are human-readable strings.
7
+ * - Addresses are lowercase 0x strings. Compare them case-insensitively.
8
+ * - Times are unix seconds (numbers) unless the field name ends with `Iso`.
9
+ * - A limit of `null` means "no cap"; a threshold of `null` means "never".
10
+ */
11
+ export {};