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