@emilia-protocol/sdk 0.1.0 → 0.10.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,898 @@
1
+ // ============================================================================
2
+ // EMILIA Protocol — TypeScript Client
3
+ // ============================================================================
4
+ import { EPError } from './types.js';
5
+ const SDK_VERSION = '1.0.0';
6
+ const DEFAULT_BASE_URL = 'https://emiliaprotocol.ai';
7
+ const DEFAULT_TIMEOUT = 30_000;
8
+ function trustReceiptBody(params) {
9
+ return {
10
+ organization_id: params.organizationId,
11
+ action_type: params.actionType,
12
+ target_resource_id: params.targetResourceId,
13
+ policy_id: params.policyId,
14
+ enforcement_mode: params.enforcementMode,
15
+ before_state: params.beforeState,
16
+ after_state: params.afterState,
17
+ target_changed_fields: params.targetChangedFields,
18
+ amount: params.amount,
19
+ currency: params.currency,
20
+ risk_flags: params.riskFlags,
21
+ actor_role: params.actorRole,
22
+ actor_department: params.actorDepartment,
23
+ business_hours: params.businessHours,
24
+ velocity_same_actor_24h: params.velocitySameActor24h,
25
+ prior_denials_actor_30d: params.priorDenialsActor30d,
26
+ prior_changes_target_30d: params.priorChangesTarget30d,
27
+ destination_age_days: params.destinationAgeDays,
28
+ quorum_policy: params.quorumPolicy,
29
+ metadata: params.metadata,
30
+ };
31
+ }
32
+ // ----------------------------------------------------------------------------
33
+ // EPClient
34
+ // ----------------------------------------------------------------------------
35
+ /**
36
+ * Client for the EMILIA Protocol API.
37
+ *
38
+ * All public methods return typed promises and throw `EPError` on failure.
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * import { EPClient } from '@emilia-protocol/sdk';
43
+ *
44
+ * const ep = new EPClient({ apiKey: process.env.EP_API_KEY });
45
+ *
46
+ * const profile = await ep.trustProfile('merchant-xyz');
47
+ * console.log(profile.current_confidence); // "confident"
48
+ * ```
49
+ */
50
+ export class EPClient {
51
+ baseUrl;
52
+ apiKey;
53
+ timeout;
54
+ fetchImpl;
55
+ constructor(options = {}) {
56
+ this.baseUrl = (options.baseUrl ??
57
+ (typeof process !== 'undefined' ? process.env['EP_BASE_URL'] : undefined) ??
58
+ DEFAULT_BASE_URL).replace(/\/+$/, '');
59
+ this.apiKey =
60
+ options.apiKey ??
61
+ (typeof process !== 'undefined' ? process.env['EP_API_KEY'] : undefined) ??
62
+ '';
63
+ this.timeout = options.timeout ?? DEFAULT_TIMEOUT;
64
+ this.fetchImpl = options.fetchImpl ?? fetch;
65
+ }
66
+ // --------------------------------------------------------------------------
67
+ // Core fetch implementation
68
+ // --------------------------------------------------------------------------
69
+ async request(path, options = {}) {
70
+ // Build URL with query params
71
+ let url = `${this.baseUrl}${path}`;
72
+ if (options.params) {
73
+ const entries = Object.entries(options.params).filter(([, v]) => v !== undefined && v !== null);
74
+ if (entries.length > 0) {
75
+ url += `?${new URLSearchParams(entries.map(([k, v]) => [k, String(v)]))}`;
76
+ }
77
+ }
78
+ const headers = {
79
+ 'Content-Type': 'application/json',
80
+ 'User-Agent': `@emilia-protocol/sdk/${SDK_VERSION}`,
81
+ };
82
+ if (options.auth && this.apiKey) {
83
+ headers['Authorization'] = `Bearer ${this.apiKey}`;
84
+ }
85
+ const controller = new AbortController();
86
+ const timer = setTimeout(() => controller.abort(), this.timeout);
87
+ try {
88
+ const res = await this.fetchImpl(url, {
89
+ method: options.method ?? 'GET',
90
+ headers,
91
+ body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
92
+ signal: controller.signal,
93
+ });
94
+ // Parse JSON regardless of status so we can surface API error messages
95
+ const data = await res.json().catch(() => undefined);
96
+ if (!res.ok) {
97
+ const payload = data;
98
+ const message = typeof payload?.['error'] === 'string'
99
+ ? payload['error']
100
+ : typeof payload?.['detail'] === 'string'
101
+ ? payload['detail']
102
+ : typeof payload?.['title'] === 'string'
103
+ ? payload['title']
104
+ : `EP API error: ${res.status}`;
105
+ const code = typeof payload?.['code'] === 'string'
106
+ ? payload['code']
107
+ : typeof payload?.['type'] === 'string'
108
+ ? payload['type'].split('/').pop()
109
+ : undefined;
110
+ throw new EPError(message, res.status, code);
111
+ }
112
+ return data;
113
+ }
114
+ catch (err) {
115
+ if (err instanceof EPError)
116
+ throw err;
117
+ // AbortError → timeout
118
+ if (err instanceof Error && err.name === 'AbortError') {
119
+ throw new EPError(`Request timed out after ${this.timeout}ms`, undefined, 'timeout');
120
+ }
121
+ throw new EPError(err instanceof Error ? err.message : 'Unknown network error', undefined, 'network_error');
122
+ }
123
+ finally {
124
+ clearTimeout(timer);
125
+ }
126
+ }
127
+ // --------------------------------------------------------------------------
128
+ // Trust Profile & Evaluation
129
+ // --------------------------------------------------------------------------
130
+ /**
131
+ * Get an entity's full trust profile.
132
+ *
133
+ * This is the CANONICAL read surface for EP trust data. Call this before
134
+ * transacting with any counterparty or installing any software.
135
+ *
136
+ * @example
137
+ * ```typescript
138
+ * const profile = await ep.trustProfile('merchant-xyz');
139
+ * console.log(profile.current_confidence); // "confident"
140
+ * console.log(profile.trust_profile?.behavioral?.completion_rate); // 97.2
141
+ * ```
142
+ */
143
+ async trustProfile(entityId) {
144
+ return this.request(`/api/trust/profile/${encodeURIComponent(entityId)}`);
145
+ }
146
+ /**
147
+ * Evaluate an entity against a named trust policy.
148
+ *
149
+ * Returns a canonical TrustDecision with detailed reasoning.
150
+ * Supply `context` for context-aware evaluation (geo, category, value_band, etc.).
151
+ *
152
+ * @example
153
+ * ```typescript
154
+ * const result = await ep.trustEvaluate('merchant-xyz', 'strict', {
155
+ * category: 'furniture',
156
+ * geo: 'US-CA',
157
+ * value_band: 'high',
158
+ * });
159
+ * if (result.decision !== 'allow') console.warn('Reasons:', result.reasons);
160
+ * ```
161
+ */
162
+ async trustEvaluate(entityId, policy = 'standard', context) {
163
+ return this.request('/api/trust/evaluate', {
164
+ method: 'POST',
165
+ body: {
166
+ entity_id: entityId,
167
+ policy,
168
+ ...(context ? { context } : {}),
169
+ },
170
+ });
171
+ }
172
+ /**
173
+ * Pre-action trust gate — call before any high-stakes autonomous action.
174
+ *
175
+ * Combines trust evaluation with delegation verification in a single call.
176
+ * The gate returns allow/review/deny with appeal paths for non-allow decisions.
177
+ *
178
+ * @example
179
+ * ```typescript
180
+ * const gate = await ep.trustGate({
181
+ * entityId: 'payment-agent-v2',
182
+ * action: 'execute_payment',
183
+ * policy: 'strict',
184
+ * valueUsd: 500,
185
+ * });
186
+ * if (gate.decision !== 'allow') throw new Error(`Blocked: ${gate.reasons?.join(', ')}`);
187
+ * ```
188
+ */
189
+ async trustGate(options) {
190
+ return this.request('/api/trust/gate', {
191
+ method: 'POST',
192
+ body: {
193
+ entity_id: options.entityId,
194
+ action: options.action,
195
+ policy: options.policy ?? 'standard',
196
+ value_usd: options.valueUsd ?? null,
197
+ delegation_id: options.delegationId ?? null,
198
+ },
199
+ });
200
+ }
201
+ /**
202
+ * Get domain-specific trust scores for an entity.
203
+ *
204
+ * Optionally filter to a subset of domains. Useful when you need trust
205
+ * context scoped to a specific action category (e.g. "financial" before
206
+ * authorizing a payment).
207
+ *
208
+ * @example
209
+ * ```typescript
210
+ * const scores = await ep.domainScore('agent-v2', ['financial', 'delegation']);
211
+ * console.log(scores.domains.financial?.confidence); // "confident"
212
+ * ```
213
+ */
214
+ async domainScore(entityId, domains) {
215
+ return this.request(`/api/trust/domain-score/${encodeURIComponent(entityId)}`, { params: domains?.length ? { domains: domains.join(',') } : undefined });
216
+ }
217
+ /**
218
+ * EP-SX: Software pre-action enforcement check (experimental).
219
+ *
220
+ * Evaluates a software entity (MCP server, npm package, browser extension,
221
+ * GitHub App, Shopify App, etc.) for installation safety. Returns allow/
222
+ * review/deny with publisher verification, permission class, and provenance.
223
+ *
224
+ * @example
225
+ * ```typescript
226
+ * const preflight = await ep.installPreflight(
227
+ * 'mcp-server-acme-v1',
228
+ * 'mcp_server_safe_v1',
229
+ * { host: 'claude-desktop', permission_class: 'bounded_external_access' },
230
+ * );
231
+ * if (preflight.decision === 'deny') throw new Error('Installation blocked by EP');
232
+ * ```
233
+ */
234
+ async installPreflight(entityId, policy, context) {
235
+ return this.request('/api/trust/install-preflight', {
236
+ method: 'POST',
237
+ body: {
238
+ entity_id: entityId,
239
+ policy: policy ?? 'standard',
240
+ ...(context ? { context } : {}),
241
+ },
242
+ });
243
+ }
244
+ // --------------------------------------------------------------------------
245
+ // Entities
246
+ // --------------------------------------------------------------------------
247
+ /**
248
+ * Register a new entity.
249
+ *
250
+ * Public endpoint — no API key required. Returns the entity record and the
251
+ * first API key. Store the API key securely; it will not be shown again.
252
+ *
253
+ * @example
254
+ * ```typescript
255
+ * const { entity, api_key } = await ep.registerEntity({
256
+ * entityId: 'acme-payment-agent',
257
+ * displayName: 'Acme Payment Agent',
258
+ * entityType: 'agent',
259
+ * description: 'Handles autonomous payment flows for Acme Corp.',
260
+ * capabilities: ['payment', 'refund'],
261
+ * });
262
+ * console.log('Save this key:', api_key); // ep_live_...
263
+ * ```
264
+ */
265
+ async registerEntity(options) {
266
+ return this.request('/api/entities/register', {
267
+ method: 'POST',
268
+ body: {
269
+ entity_id: options.entityId,
270
+ display_name: options.displayName,
271
+ entity_type: options.entityType,
272
+ description: options.description,
273
+ capabilities: options.capabilities,
274
+ },
275
+ });
276
+ }
277
+ /**
278
+ * Search for entities by name, capability, or category.
279
+ *
280
+ * @example
281
+ * ```typescript
282
+ * const { entities } = await ep.searchEntities('payment', 'agent');
283
+ * for (const e of entities) {
284
+ * console.log(e.display_name, e.confidence);
285
+ * }
286
+ * ```
287
+ */
288
+ async searchEntities(query, entityType, minConfidence) {
289
+ return this.request('/api/entities/search', {
290
+ params: {
291
+ q: query,
292
+ type: entityType,
293
+ min_confidence: minConfidence,
294
+ },
295
+ });
296
+ }
297
+ /**
298
+ * Get the entity leaderboard ranked by trust confidence.
299
+ *
300
+ * @example
301
+ * ```typescript
302
+ * const { leaderboard } = await ep.leaderboard(5, 'merchant');
303
+ * leaderboard.forEach(e => console.log(`#${e.rank} ${e.display_name}`));
304
+ * ```
305
+ */
306
+ async leaderboard(limit = 10, entityType) {
307
+ return this.request('/api/leaderboard', {
308
+ params: {
309
+ limit: Math.min(limit, 50),
310
+ type: entityType,
311
+ },
312
+ });
313
+ }
314
+ // --------------------------------------------------------------------------
315
+ // Receipts
316
+ // --------------------------------------------------------------------------
317
+ /**
318
+ * Submit a transaction receipt to the EP ledger.
319
+ *
320
+ * Requires an API key. Receipts are append-only, cryptographically hashed,
321
+ * and chain-linked. `transaction_ref` must be unique per entity.
322
+ *
323
+ * The `agent_behavior` field is the strongest Phase 1 signal — always set it.
324
+ *
325
+ * @example
326
+ * ```typescript
327
+ * const { receipt } = await ep.submitReceipt({
328
+ * entity_id: 'merchant-xyz',
329
+ * transaction_ref: 'order-8821',
330
+ * transaction_type: 'purchase',
331
+ * agent_behavior: 'completed',
332
+ * delivery_accuracy: 98,
333
+ * product_accuracy: 95,
334
+ * price_integrity: 100,
335
+ * });
336
+ * console.log('Receipt ID:', receipt.receipt_id);
337
+ * ```
338
+ */
339
+ async submitReceipt(input) {
340
+ return this.request('/api/receipts/submit', {
341
+ method: 'POST',
342
+ auth: true,
343
+ body: input,
344
+ });
345
+ }
346
+ /**
347
+ * Submit multiple receipts atomically. Maximum 50 per call.
348
+ *
349
+ * Each result in the response array indicates success or failure for that
350
+ * receipt independently — partial success is possible.
351
+ *
352
+ * @example
353
+ * ```typescript
354
+ * const result = await ep.batchSubmit([
355
+ * { entity_id: 'merchant-a', transaction_ref: 'tx-1', transaction_type: 'purchase', agent_behavior: 'completed' },
356
+ * { entity_id: 'merchant-b', transaction_ref: 'tx-2', transaction_type: 'service', agent_behavior: 'completed' },
357
+ * ]);
358
+ * result.results.forEach(r => console.log(r.entity_id, r.success ? 'ok' : r.error));
359
+ * ```
360
+ */
361
+ async batchSubmit(receipts) {
362
+ return this.request('/api/receipts/batch', {
363
+ method: 'POST',
364
+ auth: true,
365
+ body: { receipts: receipts.slice(0, 50) },
366
+ });
367
+ }
368
+ /**
369
+ * Confirm or reject a receipt as the counterparty (bilateral confirmation).
370
+ *
371
+ * The confirmation window is 48 hours from receipt creation. Confirmed
372
+ * receipts receive a higher provenance tier, improving their evidential weight.
373
+ *
374
+ * @example
375
+ * ```typescript
376
+ * await ep.confirmReceipt('ep_rcpt_abc123', true);
377
+ * ```
378
+ */
379
+ async confirmReceipt(receiptId, confirm) {
380
+ return this.request('/api/receipts/confirm', {
381
+ method: 'POST',
382
+ auth: true,
383
+ body: { receipt_id: receiptId, confirm },
384
+ });
385
+ }
386
+ /**
387
+ * Verify a receipt against the on-chain Merkle root.
388
+ *
389
+ * @example
390
+ * ```typescript
391
+ * const { verified, anchored } = await ep.verifyReceipt('ep_rcpt_abc123');
392
+ * if (!verified) console.error('Receipt integrity check failed');
393
+ * ```
394
+ */
395
+ async verifyReceipt(receiptId) {
396
+ return this.request(`/api/verify/${encodeURIComponent(receiptId)}`);
397
+ }
398
+ // --------------------------------------------------------------------------
399
+ // v1 Trust Receipt Enforcement
400
+ // --------------------------------------------------------------------------
401
+ /**
402
+ * Create a v1 pre-action trust receipt for a high-risk mutation.
403
+ *
404
+ * The API derives organization scope from the authenticated API key. If
405
+ * `organizationId` is supplied here, the server treats it as a cross-check.
406
+ */
407
+ async createTrustReceipt(params) {
408
+ return this.request('/api/v1/trust-receipts', {
409
+ method: 'POST',
410
+ auth: true,
411
+ body: trustReceiptBody(params),
412
+ });
413
+ }
414
+ /** Read current receipt state from the append-only v1 audit timeline. */
415
+ async getTrustReceipt(receiptId) {
416
+ return this.request(`/api/v1/trust-receipts/${encodeURIComponent(receiptId)}`, { auth: true });
417
+ }
418
+ /** Request human signoff for a receipt that requires approval. */
419
+ async requestSignoff(params) {
420
+ return this.request('/api/v1/signoffs/request', {
421
+ method: 'POST',
422
+ auth: true,
423
+ body: {
424
+ receipt_id: params.receiptId,
425
+ approver_id: params.approverId,
426
+ expires_in_minutes: params.expiresInMinutes,
427
+ comment: params.comment,
428
+ },
429
+ });
430
+ }
431
+ /**
432
+ * Consume a receipt before mutation. This is the reject-before-write gate:
433
+ * if this call fails, the SDK helper never runs the wrapped mutation.
434
+ */
435
+ async consumeTrustReceipt(receiptId, params) {
436
+ return this.request(`/api/v1/trust-receipts/${encodeURIComponent(receiptId)}/consume`, {
437
+ method: 'POST',
438
+ auth: true,
439
+ body: {
440
+ action_hash: params.actionHash,
441
+ executing_system: params.executingSystem,
442
+ execution_reference_id: params.executionReferenceId,
443
+ },
444
+ });
445
+ }
446
+ /** Emit the post-mutation execution attestation bound to the consumed receipt. */
447
+ async attestExecution(receiptId, params) {
448
+ return this.request(`/api/v1/trust-receipts/${encodeURIComponent(receiptId)}/execution`, {
449
+ method: 'POST',
450
+ auth: true,
451
+ body: {
452
+ executed_action: params.executedAction,
453
+ executing_system: params.executingSystem,
454
+ execution_id: params.executionId,
455
+ executed_at: params.executedAt,
456
+ },
457
+ });
458
+ }
459
+ /** Fetch the signed evidence packet, when the receipt is in a signable state. */
460
+ async getTrustReceiptEvidence(receiptId) {
461
+ return this.request(`/api/v1/trust-receipts/${encodeURIComponent(receiptId)}/evidence`, { auth: true });
462
+ }
463
+ /**
464
+ * Five-minute adoption helper: wrap a dangerous mutation in the v1 receipt
465
+ * lifecycle. The mutation runs only after the receipt is created and consumed.
466
+ * If signoff is required, callers must complete it in `onSignoffRequired`.
467
+ */
468
+ async requireReceipt(params, mutate) {
469
+ const receipt = await this.createTrustReceipt(params);
470
+ if (receipt.decision === 'deny' || receipt.receipt_status === 'denied') {
471
+ throw new EPError('EMILIA denied the action before execution', 403, 'receipt_denied');
472
+ }
473
+ let signoff;
474
+ if (receipt.signoff_required) {
475
+ if (!params.approverId && !params.quorumPolicy) {
476
+ throw new EPError('Receipt requires signoff; pass approverId or quorumPolicy', 409, 'missing_approver_id');
477
+ }
478
+ signoff = await this.requestSignoff({
479
+ receiptId: receipt.receipt_id,
480
+ approverId: params.approverId,
481
+ expiresInMinutes: params.signoffExpiresInMinutes,
482
+ comment: params.signoffComment,
483
+ });
484
+ if (!params.onSignoffRequired) {
485
+ throw new EPError('Receipt requires human signoff before the mutation can run', 409, 'signoff_required');
486
+ }
487
+ const signoffResult = await params.onSignoffRequired({ client: this, receipt, signoff });
488
+ if (signoffResult === false || (typeof signoffResult === 'object' && signoffResult?.approved === false)) {
489
+ throw new EPError('Human signoff was not approved', 403, 'signoff_rejected');
490
+ }
491
+ }
492
+ const consume = await this.consumeTrustReceipt(receipt.receipt_id, {
493
+ actionHash: receipt.action_hash,
494
+ executingSystem: params.executingSystem,
495
+ executionReferenceId: params.executionReferenceId,
496
+ });
497
+ const result = await mutate({ receipt, consume });
498
+ const executedAction = typeof params.executedAction === 'function'
499
+ ? params.executedAction({ receipt, result })
500
+ : params.executedAction ?? receipt.canonical_action;
501
+ const executionId = typeof params.executionId === 'function'
502
+ ? params.executionId(result)
503
+ : params.executionId;
504
+ const execution = await this.attestExecution(receipt.receipt_id, {
505
+ executedAction,
506
+ executingSystem: params.executingSystem,
507
+ executionId,
508
+ });
509
+ const evidence = params.fetchEvidence
510
+ ? await this.getTrustReceiptEvidence(receipt.receipt_id)
511
+ : undefined;
512
+ return { result, receipt, signoff, consume, execution, evidence };
513
+ }
514
+ /**
515
+ * Convenience wrapper for existing functions. The returned function resolves
516
+ * to the full receipt lifecycle result, not just the mutation return value.
517
+ */
518
+ withReceipt(params, mutate) {
519
+ return async (...args) => {
520
+ const resolved = typeof params === 'function' ? params(...args) : params;
521
+ return this.requireReceipt(resolved, () => mutate(...args));
522
+ };
523
+ }
524
+ // --------------------------------------------------------------------------
525
+ // Disputes & Due Process
526
+ // --------------------------------------------------------------------------
527
+ /**
528
+ * File a dispute against a receipt.
529
+ *
530
+ * Requires an API key. Any affected party can challenge. The receipt
531
+ * submitter has 7 days to respond before EP escalates.
532
+ *
533
+ * @example
534
+ * ```typescript
535
+ * const dispute = await ep.fileDispute({
536
+ * receiptId: 'ep_rcpt_abc123',
537
+ * reason: 'inaccurate_signals',
538
+ * description: 'Delivery accuracy was reported as 98 but the item arrived damaged.',
539
+ * evidence: { photo_url: 'https://...' },
540
+ * });
541
+ * console.log('Dispute ID:', dispute.dispute_id);
542
+ * console.log('Respond by:', dispute.response_deadline);
543
+ * ```
544
+ */
545
+ async fileDispute(options) {
546
+ return this.request('/api/disputes/file', {
547
+ method: 'POST',
548
+ auth: true,
549
+ body: {
550
+ receipt_id: options.receiptId,
551
+ reason: options.reason,
552
+ description: options.description ?? null,
553
+ evidence: options.evidence ?? null,
554
+ },
555
+ });
556
+ }
557
+ /**
558
+ * Get the current status of a dispute.
559
+ *
560
+ * Dispute status is public — transparency is a protocol value.
561
+ *
562
+ * @example
563
+ * ```typescript
564
+ * const dispute = await ep.disputeStatus('ep_disp_xyz789');
565
+ * console.log(dispute.status, dispute.resolution);
566
+ * ```
567
+ */
568
+ async disputeStatus(disputeId) {
569
+ return this.request(`/api/disputes/${encodeURIComponent(disputeId)}`);
570
+ }
571
+ /**
572
+ * Respond to a dispute filed against one of your receipts.
573
+ *
574
+ * Requires an API key. Must be called within the response_deadline window.
575
+ *
576
+ * @example
577
+ * ```typescript
578
+ * await ep.respondToDispute({
579
+ * disputeId: 'ep_disp_xyz789',
580
+ * response: 'The delivery accuracy score reflects the state at handoff, confirmed by carrier log.',
581
+ * evidence: { carrier_log_url: 'https://...' },
582
+ * });
583
+ * ```
584
+ */
585
+ async respondToDispute(options) {
586
+ return this.request('/api/disputes/respond', {
587
+ method: 'POST',
588
+ auth: true,
589
+ body: {
590
+ dispute_id: options.disputeId,
591
+ response: options.response,
592
+ evidence: options.evidence ?? null,
593
+ },
594
+ });
595
+ }
596
+ /**
597
+ * Withdraw an open dispute before it reaches resolution.
598
+ *
599
+ * Requires an API key. Only the filer can withdraw.
600
+ *
601
+ * @example
602
+ * ```typescript
603
+ * await ep.withdrawDispute('ep_disp_xyz789');
604
+ * ```
605
+ */
606
+ async withdrawDispute(disputeId) {
607
+ return this.request('/api/disputes/withdraw', {
608
+ method: 'POST',
609
+ auth: true,
610
+ body: { dispute_id: disputeId },
611
+ });
612
+ }
613
+ /**
614
+ * Appeal a dispute resolution.
615
+ *
616
+ * Requires an API key. Only dispute participants may appeal. The dispute must
617
+ * be in upheld, reversed, or dismissed state. The appeal decision is final.
618
+ *
619
+ * "Trust must never be more powerful than appeal." — EP Constitutional Principle
620
+ *
621
+ * @example
622
+ * ```typescript
623
+ * await ep.appealDispute({
624
+ * disputeId: 'ep_disp_xyz789',
625
+ * reason: 'New evidence shows the carrier log was misread. Attaching corrected scan.',
626
+ * evidence: { corrected_scan: 'https://...' },
627
+ * });
628
+ * ```
629
+ */
630
+ async appealDispute(options) {
631
+ return this.request('/api/disputes/appeal', {
632
+ method: 'POST',
633
+ auth: true,
634
+ body: {
635
+ dispute_id: options.disputeId,
636
+ reason: options.reason,
637
+ evidence: options.evidence ?? null,
638
+ },
639
+ });
640
+ }
641
+ /**
642
+ * Report a trust issue as a human.
643
+ *
644
+ * No authentication required. The human appeal channel — use when someone
645
+ * is wrongly downgraded, harmed by a trusted entity, or has observed fraud.
646
+ *
647
+ * @example
648
+ * ```typescript
649
+ * await ep.reportTrustIssue({
650
+ * entityId: 'merchant-xyz',
651
+ * reportType: 'harmed_by_trusted_entity',
652
+ * description: 'I paid for an item marked as delivered but never received it.',
653
+ * contactEmail: 'jane@example.com',
654
+ * });
655
+ * ```
656
+ */
657
+ async reportTrustIssue(options) {
658
+ return this.request('/api/disputes/report', {
659
+ method: 'POST',
660
+ body: {
661
+ entity_id: options.entityId,
662
+ report_type: options.reportType,
663
+ description: options.description,
664
+ contact_email: options.contactEmail ?? null,
665
+ },
666
+ });
667
+ }
668
+ // --------------------------------------------------------------------------
669
+ // Delegation (EP-DX)
670
+ // --------------------------------------------------------------------------
671
+ /**
672
+ * Create a delegation: authorize an agent to act on behalf of a principal.
673
+ *
674
+ * Requires an API key. The delegation record can be verified by any party
675
+ * using `verifyDelegation`.
676
+ *
677
+ * @example
678
+ * ```typescript
679
+ * const delegation = await ep.createDelegation({
680
+ * principalId: 'ep_principal_acme',
681
+ * agentEntityId: 'acme-payment-agent',
682
+ * scope: ['purchase', 'refund'],
683
+ * maxValueUsd: 1000,
684
+ * expiresAt: '2026-12-31T23:59:59Z',
685
+ * });
686
+ * console.log('Delegation ID:', delegation.delegation_id);
687
+ * ```
688
+ */
689
+ async createDelegation(options) {
690
+ return this.request('/api/delegations/create', {
691
+ method: 'POST',
692
+ auth: true,
693
+ body: {
694
+ principal_id: options.principalId,
695
+ agent_entity_id: options.agentEntityId,
696
+ scope: options.scope,
697
+ max_value_usd: options.maxValueUsd ?? null,
698
+ expires_at: options.expiresAt ?? null,
699
+ constraints: options.constraints ?? null,
700
+ },
701
+ });
702
+ }
703
+ /**
704
+ * Verify that a delegation is valid and covers a given action type.
705
+ *
706
+ * @example
707
+ * ```typescript
708
+ * const result = await ep.verifyDelegation('ep_del_abc123', 'purchase');
709
+ * if (!result.valid) throw new Error('Delegation invalid or expired');
710
+ * ```
711
+ */
712
+ async verifyDelegation(delegationId, actionType) {
713
+ return this.request(`/api/delegations/${encodeURIComponent(delegationId)}/verify`, {
714
+ params: { action_type: actionType },
715
+ });
716
+ }
717
+ // --------------------------------------------------------------------------
718
+ // Identity Continuity (EP-IX)
719
+ // --------------------------------------------------------------------------
720
+ /**
721
+ * Look up a principal — the enduring actor behind one or more entities.
722
+ *
723
+ * Returns the principal record, its controlled entities, identity bindings,
724
+ * and continuity claim history.
725
+ *
726
+ * @example
727
+ * ```typescript
728
+ * const result = await ep.principalLookup('ep_principal_acme');
729
+ * console.log('Entities:', result.entities?.map(e => e.entity_id));
730
+ * ```
731
+ */
732
+ async principalLookup(principalId) {
733
+ return this.request(`/api/identity/principal/${encodeURIComponent(principalId)}`);
734
+ }
735
+ /**
736
+ * View entity lineage — predecessors, successors, and continuity decisions.
737
+ *
738
+ * Use to check whether an entity has suspicious continuity gaps that might
739
+ * indicate reputation laundering (whitewashing).
740
+ *
741
+ * @example
742
+ * ```typescript
743
+ * const lineage = await ep.lineage('merchant-xyz');
744
+ * if (lineage.predecessors?.some(p => p.status === 'disputed')) {
745
+ * console.warn('Entity has disputed predecessor — review before transacting');
746
+ * }
747
+ * ```
748
+ */
749
+ async lineage(entityId) {
750
+ return this.request(`/api/identity/lineage/${encodeURIComponent(entityId)}`);
751
+ }
752
+ // --------------------------------------------------------------------------
753
+ // Policies
754
+ // --------------------------------------------------------------------------
755
+ /**
756
+ * List all available trust policies with their requirements and families.
757
+ *
758
+ * Returns 8 policies: 4 core (strict, standard, permissive, discovery) and
759
+ * 4 software-specific (github_private_repo_safe_v1, npm_buildtime_safe_v1,
760
+ * browser_extension_safe_v1, mcp_server_safe_v1).
761
+ *
762
+ * @example
763
+ * ```typescript
764
+ * const { policies } = await ep.listPolicies();
765
+ * policies.forEach(p => console.log(p.name, '-', p.description));
766
+ * ```
767
+ */
768
+ async listPolicies() {
769
+ return this.request('/api/policies');
770
+ }
771
+ // --------------------------------------------------------------------------
772
+ // System
773
+ // --------------------------------------------------------------------------
774
+ /**
775
+ * Public proof metrics — entity count, test count, tool count, policy count.
776
+ *
777
+ * @example
778
+ * ```typescript
779
+ * const stats = await ep.stats();
780
+ * console.log(`${stats.total_entities} entities across ${stats.trust_policies} policies`);
781
+ * ```
782
+ */
783
+ async stats() {
784
+ return this.request('/api/stats');
785
+ }
786
+ /**
787
+ * Health check. Returns subsystem status.
788
+ *
789
+ * @example
790
+ * ```typescript
791
+ * const health = await ep.health();
792
+ * console.log(health.status); // "ok"
793
+ * ```
794
+ */
795
+ async health() {
796
+ return this.request('/api/health');
797
+ }
798
+ // --------------------------------------------------------------------------
799
+ // EP Commit
800
+ // --------------------------------------------------------------------------
801
+ /**
802
+ * Issue a signed EP Commit before a high-stakes action.
803
+ *
804
+ * The commit binds the agent to a specific action type, entity, and policy
805
+ * before execution. Returns decision (allow/deny/review), commit_id, expiry,
806
+ * scope, and appeal path.
807
+ *
808
+ * @example
809
+ * ```typescript
810
+ * const { decision, commit } = await ep.issueCommit({
811
+ * action_type: 'transact',
812
+ * entity_id: 'payment-agent-v2',
813
+ * max_value_usd: 500,
814
+ * policy: 'strict',
815
+ * });
816
+ * if (decision !== 'allow') throw new Error('Commit denied');
817
+ * console.log(commit.commit_id);
818
+ * ```
819
+ */
820
+ async issueCommit(params) {
821
+ return this.request('/api/commit/issue', {
822
+ method: 'POST',
823
+ auth: true,
824
+ body: params,
825
+ });
826
+ }
827
+ /**
828
+ * Verify a commit's signature, status, and validity.
829
+ *
830
+ * @example
831
+ * ```typescript
832
+ * const result = await ep.verifyCommit('epc_abc123');
833
+ * if (!result.valid) console.error('Commit invalid');
834
+ * ```
835
+ */
836
+ async verifyCommit(commitId) {
837
+ return this.request('/api/commit/verify', {
838
+ method: 'POST',
839
+ body: { commit_id: commitId },
840
+ });
841
+ }
842
+ /**
843
+ * Get the current state of a commit.
844
+ *
845
+ * @example
846
+ * ```typescript
847
+ * const { commit } = await ep.getCommitStatus('epc_abc123');
848
+ * console.log(commit.status); // "active" | "revoked" | "expired" | "fulfilled"
849
+ * ```
850
+ */
851
+ async getCommitStatus(commitId) {
852
+ return this.request(`/api/commit/${encodeURIComponent(commitId)}`, {
853
+ auth: true,
854
+ });
855
+ }
856
+ /**
857
+ * Revoke an active commit before it is fulfilled or expires.
858
+ *
859
+ * @example
860
+ * ```typescript
861
+ * await ep.revokeCommit('epc_abc123', 'Action no longer needed');
862
+ * ```
863
+ */
864
+ async revokeCommit(commitId, reason) {
865
+ return this.request(`/api/commit/${encodeURIComponent(commitId)}/revoke`, {
866
+ method: 'POST',
867
+ auth: true,
868
+ body: { reason },
869
+ });
870
+ }
871
+ /**
872
+ * Bind a post-action receipt to a commit, completing the commit-execute-receipt cycle.
873
+ *
874
+ * @example
875
+ * ```typescript
876
+ * await ep.bindReceiptToCommit('epc_abc123', 'ep_rcpt_xyz789');
877
+ * ```
878
+ */
879
+ async bindReceiptToCommit(commitId, receiptId) {
880
+ return this.request(`/api/commit/${encodeURIComponent(commitId)}/receipt`, {
881
+ method: 'POST',
882
+ auth: true,
883
+ body: { receipt_id: receiptId },
884
+ });
885
+ }
886
+ /**
887
+ * Legacy: get the 0-100 compatibility score for an entity.
888
+ *
889
+ * Prefer `trustProfile()` for all new integrations. This endpoint exists
890
+ * for backward compatibility only.
891
+ *
892
+ * @deprecated Use trustProfile() instead.
893
+ */
894
+ async legacyScore(entityId) {
895
+ return this.request(`/api/score/${encodeURIComponent(entityId)}`);
896
+ }
897
+ }
898
+ //# sourceMappingURL=client.js.map