notaryos 1.0.0 → 2.0.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/index.d.ts CHANGED
@@ -17,7 +17,27 @@
17
17
  *
18
18
  * @packageDocumentation
19
19
  */
20
- declare const SDK_VERSION = "1.0.0";
20
+ declare const SDK_VERSION = "2.0.0";
21
+ /** Standardized error codes mirroring the backend API. */
22
+ declare const NotaryErrorCode: {
23
+ readonly ERR_RECEIPT_NOT_FOUND: "ERR_RECEIPT_NOT_FOUND";
24
+ readonly ERR_INVALID_SIGNATURE: "ERR_INVALID_SIGNATURE";
25
+ readonly ERR_INVALID_STRUCTURE: "ERR_INVALID_STRUCTURE";
26
+ readonly ERR_INVALID_TIMESTAMP: "ERR_INVALID_TIMESTAMP";
27
+ readonly ERR_UNKNOWN_SIGNER: "ERR_UNKNOWN_SIGNER";
28
+ readonly ERR_UNSUPPORTED_ALGORITHM: "ERR_UNSUPPORTED_ALGORITHM";
29
+ readonly ERR_CHAIN_BROKEN: "ERR_CHAIN_BROKEN";
30
+ readonly ERR_CHAIN_MISSING: "ERR_CHAIN_MISSING";
31
+ readonly ERR_PAYLOAD_TOO_LARGE: "ERR_PAYLOAD_TOO_LARGE";
32
+ readonly ERR_RATE_LIMIT_EXCEEDED: "ERR_RATE_LIMIT_EXCEEDED";
33
+ readonly ERR_INVALID_API_KEY: "ERR_INVALID_API_KEY";
34
+ readonly ERR_INSUFFICIENT_SCOPE: "ERR_INSUFFICIENT_SCOPE";
35
+ readonly ERR_VALIDATION_FAILED: "ERR_VALIDATION_FAILED";
36
+ readonly ERR_INTERNAL_ERROR: "ERR_INTERNAL_ERROR";
37
+ readonly ERR_DATABASE_ERROR: "ERR_DATABASE_ERROR";
38
+ readonly ERR_SIGNING_ERROR: "ERR_SIGNING_ERROR";
39
+ };
40
+ type NotaryErrorCodeType = (typeof NotaryErrorCode)[keyof typeof NotaryErrorCode];
21
41
  /** Client configuration options. */
22
42
  interface NotaryConfig {
23
43
  /** Your Notary API key (notary_live_xxx or notary_test_xxx). */
@@ -95,6 +115,47 @@ interface IssueOptions {
95
115
  /** Additional metadata. */
96
116
  metadata?: Record<string, unknown>;
97
117
  }
118
+ /** Paginated history result. */
119
+ interface HistoryResult {
120
+ items: Record<string, unknown>[];
121
+ total: number;
122
+ totalPages: number;
123
+ page: number;
124
+ pageSize: number;
125
+ }
126
+ /** Options for history queries. */
127
+ interface HistoryOptions {
128
+ page?: number;
129
+ pageSize?: number;
130
+ status?: string;
131
+ search?: string;
132
+ startDate?: string;
133
+ endDate?: string;
134
+ clerkToken?: string;
135
+ }
136
+ /** Counterfactual issue options. */
137
+ interface CounterfactualIssueOptions {
138
+ actionNotTaken: string;
139
+ capabilityProof: Record<string, unknown>;
140
+ opportunityContext: Record<string, unknown>;
141
+ decisionReason: string;
142
+ declinationReason?: string;
143
+ provenanceRefs?: string[];
144
+ validityWindowMinutes?: number;
145
+ }
146
+ /** Counterfactual commit options (v2 commit-reveal). */
147
+ interface CounterfactualCommitOptions extends CounterfactualIssueOptions {
148
+ minRevealDelaySeconds?: number;
149
+ maxRevealWindowSeconds?: number;
150
+ }
151
+ /** Auto-receipt configuration. */
152
+ interface AutoReceiptConfig {
153
+ mode?: 'all' | 'errors_only' | 'sample';
154
+ sampleRate?: number;
155
+ fireAndForget?: boolean;
156
+ maxPayloadBytes?: number;
157
+ dryRun?: boolean;
158
+ }
98
159
  /** Base error for all NotaryOS SDK errors. */
99
160
  declare class NotaryError extends Error {
100
161
  code: string;
@@ -115,6 +176,41 @@ declare class RateLimitError extends NotaryError {
115
176
  declare class ValidationError extends NotaryError {
116
177
  constructor(message: string, details?: Record<string, unknown>);
117
178
  }
179
+ /**
180
+ * Sub-client for counterfactual receipt operations (proof of non-action).
181
+ *
182
+ * @example
183
+ * ```typescript
184
+ * const stamp = await notary.counterfactual.issue({
185
+ * actionNotTaken: 'delete_user_data',
186
+ * capabilityProof: { scope: 'data:delete', granted: true },
187
+ * opportunityContext: { user_id: 'u_123' },
188
+ * decisionReason: 'GDPR retention period not yet expired',
189
+ * });
190
+ * ```
191
+ */
192
+ declare class CounterfactualClient {
193
+ private client;
194
+ constructor(client: NotaryClient);
195
+ /** Issue a v1 counterfactual receipt (proof of non-action). */
196
+ issue(options: CounterfactualIssueOptions): Promise<Record<string, unknown>>;
197
+ /** Retrieve/verify a counterfactual receipt by hash (public). */
198
+ get(receiptHash: string): Promise<Record<string, unknown>>;
199
+ /** List counterfactual receipts for a specific agent (public). */
200
+ listByAgent(agentId: string, limit?: number, offset?: number): Promise<Record<string, unknown>>;
201
+ /** Commit a v2 counterfactual receipt (Phase 1 of commit-reveal). */
202
+ commit(options: CounterfactualCommitOptions): Promise<Record<string, unknown>>;
203
+ /** Reveal a committed counterfactual receipt (Phase 2). */
204
+ reveal(receiptHash: string, decisionReasonPlaintext: string): Promise<Record<string, unknown>>;
205
+ /** Check commit-reveal lifecycle status (public). */
206
+ commitStatus(receiptHash: string): Promise<Record<string, unknown>>;
207
+ /** Counter-sign a counterfactual receipt (corroboration). */
208
+ corroborate(receiptHash: string, signals: string[]): Promise<Record<string, unknown>>;
209
+ /** Generate a compliance certificate for a counterfactual receipt (public). */
210
+ certificate(receiptHash: string, format?: string): Promise<Record<string, unknown>>;
211
+ /** Verify counterfactual chain continuity for an agent (public). */
212
+ verifyChain(agentId: string): Promise<Record<string, unknown>>;
213
+ }
118
214
  /**
119
215
  * NotaryOS API client.
120
216
  *
@@ -129,8 +225,11 @@ declare class ValidationError extends NotaryError {
129
225
  * const result = await notary.verify(receipt);
130
226
  * console.log(result.valid); // true
131
227
  *
132
- * // Check service health
133
- * const status = await notary.status();
228
+ * // Counterfactual receipts
229
+ * const stamp = await notary.counterfactual.issue({ ... });
230
+ *
231
+ * // Auto-receipt wrapping
232
+ * const agent = notary.wrap(myAgent, { mode: 'all' });
134
233
  * ```
135
234
  */
136
235
  declare class NotaryClient {
@@ -138,10 +237,15 @@ declare class NotaryClient {
138
237
  private baseUrl;
139
238
  private timeout;
140
239
  private maxRetries;
240
+ private _counterfactual?;
141
241
  static readonly DEFAULT_BASE_URL = "https://api.agenttownsquare.com";
142
242
  static readonly DEFAULT_TIMEOUT = 30000;
143
243
  constructor(config: NotaryConfig);
244
+ /** Access counterfactual receipt operations (enterprise premium). */
245
+ get counterfactual(): CounterfactualClient;
144
246
  private request;
247
+ /** Public GET helper (no API key in headers). */
248
+ private publicGet;
145
249
  private sleep;
146
250
  /**
147
251
  * Issue a signed receipt for an action.
@@ -150,88 +254,61 @@ declare class NotaryClient {
150
254
  * @param payload - Action payload to be receipted
151
255
  * @param options - Optional chaining and metadata
152
256
  * @returns A signed Receipt
153
- *
154
- * @example
155
- * ```typescript
156
- * const receipt = await notary.issue('transfer', { amount: 100, to: 'agent-b' });
157
- * console.log(receipt.receipt_id);
158
- * console.log(receipt.verify_url); // https://...notary/r/abc123
159
- * ```
160
257
  */
161
258
  issue(actionType: string, payload: Record<string, unknown>, options?: IssueOptions): Promise<Receipt>;
162
- /**
163
- * Verify a receipt's signature and integrity.
164
- *
165
- * @param receipt - Receipt object or raw receipt dict
166
- * @returns VerificationResult with validity details
167
- *
168
- * @example
169
- * ```typescript
170
- * const result = await notary.verify(receipt);
171
- * if (result.valid) {
172
- * console.log('Receipt is authentic');
173
- * }
174
- * ```
175
- */
259
+ /** Verify a receipt's signature and integrity. */
176
260
  verify(receipt: Receipt | Record<string, unknown>): Promise<VerificationResult>;
177
261
  /** Verify a receipt by its ID (server-side lookup). */
178
262
  verifyById(receiptId: string): Promise<VerificationResult>;
179
- /**
180
- * Get Notary service status.
181
- *
182
- * @example
183
- * ```typescript
184
- * const status = await notary.status();
185
- * console.log(status.status); // "active"
186
- * ```
187
- */
263
+ /** Get Notary service status. */
188
264
  status(): Promise<ServiceStatus>;
189
265
  /** Get the public key for offline verification. */
190
266
  publicKey(): Promise<PublicKeyInfo>;
191
267
  /** Get authenticated agent info. */
192
268
  me(): Promise<AgentInfo>;
269
+ /** Look up a receipt by hash (public endpoint). */
270
+ lookup(receiptHash: string): Promise<LookupResult>;
271
+ /**
272
+ * Get paginated receipt history (requires Clerk JWT).
273
+ *
274
+ * @param options - Pagination, filters, and Clerk token
275
+ * @returns Paginated history with items, total, totalPages
276
+ */
277
+ history(options?: HistoryOptions): Promise<HistoryResult>;
278
+ /**
279
+ * Get the provenance DAG report for a receipt (public).
280
+ *
281
+ * @param receiptHash - The receipt hash to check
282
+ * @returns Provenance report with grounding status, ancestors, paths
283
+ */
284
+ provenance(receiptHash: string): Promise<Record<string, unknown>>;
193
285
  /**
194
- * Look up a receipt by hash (public endpoint, no API key required for lookup).
286
+ * Wrap an object so method calls are automatically receipted.
287
+ *
288
+ * Uses ES6 Proxy to intercept method calls. Receipts are issued
289
+ * in the background via fire-and-forget (won't slow down your agent).
195
290
  *
196
- * @param receiptHash - Full or partial receipt hash (min 16 chars)
197
- * @returns Lookup result with receipt, verification, and meta
291
+ * @param obj - The agent or object to wrap
292
+ * @param config - Optional auto-receipt configuration
293
+ * @returns A proxied version of the object
198
294
  *
199
295
  * @example
200
296
  * ```typescript
201
- * const result = await notary.lookup('abc123def456...');
202
- * if (result.found && result.verification?.valid) {
203
- * console.log('Receipt is valid!');
204
- * }
297
+ * const agent = notary.wrap(myAgent, { mode: 'all', fireAndForget: true });
298
+ * await agent.processData(input); // auto-receipted!
205
299
  * ```
206
300
  */
207
- lookup(receiptHash: string): Promise<LookupResult>;
301
+ wrap<T extends object>(obj: T, config?: AutoReceiptConfig): T;
208
302
  }
209
303
  /**
210
304
  * Quick receipt verification without API key.
211
- *
212
305
  * Uses the public /verify endpoint — no authentication needed.
213
- *
214
- * @param receipt - Receipt JSON object
215
- * @param baseUrl - API base URL (default: production)
216
- * @returns true if the receipt is valid
217
- *
218
- * @example
219
- * ```typescript
220
- * import { verifyReceipt } from 'notaryos';
221
- *
222
- * const isValid = await verifyReceipt(receiptJson);
223
- * console.log(isValid); // true
224
- * ```
225
306
  */
226
307
  declare function verifyReceipt(receipt: Record<string, unknown>, baseUrl?: string): Promise<boolean>;
227
308
  /**
228
309
  * Compute SHA-256 hash of a payload using Web Crypto API.
229
- *
230
310
  * Matches the server-side hashing for independent verification.
231
- *
232
- * @param payload - String or JSON-serializable object
233
- * @returns Hex-encoded SHA-256 digest
234
311
  */
235
312
  declare function computeHash(payload: Record<string, unknown> | string): Promise<string>;
236
313
 
237
- export { type AgentInfo, AuthenticationError, type IssueOptions, type LookupResult, NotaryClient, type NotaryConfig, NotaryError, type PublicKeyInfo, RateLimitError, type Receipt, SDK_VERSION, type ServiceStatus, ValidationError, type VerificationResult, computeHash, verifyReceipt };
314
+ export { type AgentInfo, AuthenticationError, type AutoReceiptConfig, CounterfactualClient, type CounterfactualCommitOptions, type CounterfactualIssueOptions, type HistoryOptions, type HistoryResult, type IssueOptions, type LookupResult, NotaryClient, type NotaryConfig, NotaryError, NotaryErrorCode, type NotaryErrorCodeType, type PublicKeyInfo, RateLimitError, type Receipt, SDK_VERSION, type ServiceStatus, ValidationError, type VerificationResult, computeHash, verifyReceipt };
package/dist/index.js CHANGED
@@ -21,8 +21,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  AuthenticationError: () => AuthenticationError,
24
+ CounterfactualClient: () => CounterfactualClient,
24
25
  NotaryClient: () => NotaryClient,
25
26
  NotaryError: () => NotaryError,
27
+ NotaryErrorCode: () => NotaryErrorCode,
26
28
  RateLimitError: () => RateLimitError,
27
29
  SDK_VERSION: () => SDK_VERSION,
28
30
  ValidationError: () => ValidationError,
@@ -30,7 +32,27 @@ __export(index_exports, {
30
32
  verifyReceipt: () => verifyReceipt
31
33
  });
32
34
  module.exports = __toCommonJS(index_exports);
33
- var SDK_VERSION = "1.0.0";
35
+ var SDK_VERSION = "2.0.0";
36
+ var NotaryErrorCode = {
37
+ // 4xx Client Errors
38
+ ERR_RECEIPT_NOT_FOUND: "ERR_RECEIPT_NOT_FOUND",
39
+ ERR_INVALID_SIGNATURE: "ERR_INVALID_SIGNATURE",
40
+ ERR_INVALID_STRUCTURE: "ERR_INVALID_STRUCTURE",
41
+ ERR_INVALID_TIMESTAMP: "ERR_INVALID_TIMESTAMP",
42
+ ERR_UNKNOWN_SIGNER: "ERR_UNKNOWN_SIGNER",
43
+ ERR_UNSUPPORTED_ALGORITHM: "ERR_UNSUPPORTED_ALGORITHM",
44
+ ERR_CHAIN_BROKEN: "ERR_CHAIN_BROKEN",
45
+ ERR_CHAIN_MISSING: "ERR_CHAIN_MISSING",
46
+ ERR_PAYLOAD_TOO_LARGE: "ERR_PAYLOAD_TOO_LARGE",
47
+ ERR_RATE_LIMIT_EXCEEDED: "ERR_RATE_LIMIT_EXCEEDED",
48
+ ERR_INVALID_API_KEY: "ERR_INVALID_API_KEY",
49
+ ERR_INSUFFICIENT_SCOPE: "ERR_INSUFFICIENT_SCOPE",
50
+ ERR_VALIDATION_FAILED: "ERR_VALIDATION_FAILED",
51
+ // 5xx Server Errors
52
+ ERR_INTERNAL_ERROR: "ERR_INTERNAL_ERROR",
53
+ ERR_DATABASE_ERROR: "ERR_DATABASE_ERROR",
54
+ ERR_SIGNING_ERROR: "ERR_SIGNING_ERROR"
55
+ };
34
56
  var NotaryError = class extends Error {
35
57
  constructor(message, code = "", status = 0, details = {}) {
36
58
  super(message);
@@ -59,6 +81,79 @@ var ValidationError = class extends NotaryError {
59
81
  this.name = "ValidationError";
60
82
  }
61
83
  };
84
+ var CounterfactualClient = class {
85
+ constructor(client) {
86
+ this.client = client;
87
+ }
88
+ /** Issue a v1 counterfactual receipt (proof of non-action). */
89
+ async issue(options) {
90
+ return this.client["request"]("POST", "/counterfactual/issue", {
91
+ action_not_taken: options.actionNotTaken,
92
+ capability_proof: options.capabilityProof,
93
+ opportunity_context: options.opportunityContext,
94
+ decision_reason: options.decisionReason,
95
+ declination_reason: options.declinationReason || "unknown",
96
+ provenance_refs: options.provenanceRefs,
97
+ validity_window_minutes: options.validityWindowMinutes || 60
98
+ });
99
+ }
100
+ /** Retrieve/verify a counterfactual receipt by hash (public). */
101
+ async get(receiptHash) {
102
+ return this.client["publicGet"](`/v1/notary/counterfactual/r/${receiptHash}`);
103
+ }
104
+ /** List counterfactual receipts for a specific agent (public). */
105
+ async listByAgent(agentId, limit = 50, offset = 0) {
106
+ return this.client["publicGet"](
107
+ `/v1/notary/counterfactual/agent/${agentId}?limit=${limit}&offset=${offset}`
108
+ );
109
+ }
110
+ /** Commit a v2 counterfactual receipt (Phase 1 of commit-reveal). */
111
+ async commit(options) {
112
+ return this.client["request"]("POST", "/counterfactual/commit", {
113
+ action_not_taken: options.actionNotTaken,
114
+ capability_proof: options.capabilityProof,
115
+ opportunity_context: options.opportunityContext,
116
+ decision_reason: options.decisionReason,
117
+ declination_reason: options.declinationReason || "unknown",
118
+ provenance_refs: options.provenanceRefs,
119
+ validity_window_minutes: options.validityWindowMinutes || 60,
120
+ min_reveal_delay_seconds: options.minRevealDelaySeconds || 300,
121
+ max_reveal_window_seconds: options.maxRevealWindowSeconds || 86400
122
+ });
123
+ }
124
+ /** Reveal a committed counterfactual receipt (Phase 2). */
125
+ async reveal(receiptHash, decisionReasonPlaintext) {
126
+ return this.client["request"]("POST", "/counterfactual/reveal", {
127
+ receipt_hash: receiptHash,
128
+ decision_reason_plaintext: decisionReasonPlaintext
129
+ });
130
+ }
131
+ /** Check commit-reveal lifecycle status (public). */
132
+ async commitStatus(receiptHash) {
133
+ return this.client["publicGet"](
134
+ `/v1/notary/counterfactual/commit-status/${receiptHash}`
135
+ );
136
+ }
137
+ /** Counter-sign a counterfactual receipt (corroboration). */
138
+ async corroborate(receiptHash, signals) {
139
+ return this.client["request"]("POST", "/counterfactual/corroborate", {
140
+ receipt_hash: receiptHash,
141
+ corroboration_signals: signals
142
+ });
143
+ }
144
+ /** Generate a compliance certificate for a counterfactual receipt (public). */
145
+ async certificate(receiptHash, format = "markdown") {
146
+ return this.client["publicGet"](
147
+ `/v1/notary/counterfactual/r/${receiptHash}/certificate?format=${format}`
148
+ );
149
+ }
150
+ /** Verify counterfactual chain continuity for an agent (public). */
151
+ async verifyChain(agentId) {
152
+ return this.client["publicGet"](
153
+ `/v1/notary/counterfactual/chain/${agentId}/verify`
154
+ );
155
+ }
156
+ };
62
157
  var _NotaryClient = class _NotaryClient {
63
158
  constructor(config) {
64
159
  const { apiKey, baseUrl, timeout, maxRetries } = config;
@@ -72,6 +167,13 @@ var _NotaryClient = class _NotaryClient {
72
167
  this.timeout = timeout || _NotaryClient.DEFAULT_TIMEOUT;
73
168
  this.maxRetries = maxRetries ?? 2;
74
169
  }
170
+ /** Access counterfactual receipt operations (enterprise premium). */
171
+ get counterfactual() {
172
+ if (!this._counterfactual) {
173
+ this._counterfactual = new CounterfactualClient(this);
174
+ }
175
+ return this._counterfactual;
176
+ }
75
177
  async request(method, path, body) {
76
178
  const url = `${this.baseUrl}/v1/notary${path}`;
77
179
  const headers = {
@@ -139,9 +241,40 @@ var _NotaryClient = class _NotaryClient {
139
241
  }
140
242
  throw lastError || new NotaryError("Request failed", "ERR_UNKNOWN");
141
243
  }
244
+ /** Public GET helper (no API key in headers). */
245
+ async publicGet(path) {
246
+ const url = `${this.baseUrl}${path}`;
247
+ const controller = new AbortController();
248
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
249
+ try {
250
+ const response = await fetch(url, {
251
+ method: "GET",
252
+ headers: {
253
+ "Content-Type": "application/json",
254
+ "User-Agent": `notary-typescript-sdk/${SDK_VERSION}`
255
+ },
256
+ signal: controller.signal
257
+ });
258
+ clearTimeout(timeoutId);
259
+ if (response.status === 404) {
260
+ return { found: false };
261
+ }
262
+ if (!response.ok) {
263
+ throw new NotaryError(response.statusText, "ERR_REQUEST", response.status);
264
+ }
265
+ return await response.json();
266
+ } catch (err) {
267
+ clearTimeout(timeoutId);
268
+ if (err instanceof NotaryError) throw err;
269
+ throw new NotaryError(`Connection failed: ${err.message}`, "ERR_CONNECTION");
270
+ }
271
+ }
142
272
  sleep(ms) {
143
273
  return new Promise((resolve) => setTimeout(resolve, ms));
144
274
  }
275
+ // =========================================================================
276
+ // Core API
277
+ // =========================================================================
145
278
  /**
146
279
  * Issue a signed receipt for an action.
147
280
  *
@@ -149,13 +282,6 @@ var _NotaryClient = class _NotaryClient {
149
282
  * @param payload - Action payload to be receipted
150
283
  * @param options - Optional chaining and metadata
151
284
  * @returns A signed Receipt
152
- *
153
- * @example
154
- * ```typescript
155
- * const receipt = await notary.issue('transfer', { amount: 100, to: 'agent-b' });
156
- * console.log(receipt.receipt_id);
157
- * console.log(receipt.verify_url); // https://...notary/r/abc123
158
- * ```
159
285
  */
160
286
  async issue(actionType, payload, options = {}) {
161
287
  const body = {
@@ -176,20 +302,7 @@ var _NotaryClient = class _NotaryClient {
176
302
  chain_sequence: response.chain_position
177
303
  };
178
304
  }
179
- /**
180
- * Verify a receipt's signature and integrity.
181
- *
182
- * @param receipt - Receipt object or raw receipt dict
183
- * @returns VerificationResult with validity details
184
- *
185
- * @example
186
- * ```typescript
187
- * const result = await notary.verify(receipt);
188
- * if (result.valid) {
189
- * console.log('Receipt is authentic');
190
- * }
191
- * ```
192
- */
305
+ /** Verify a receipt's signature and integrity. */
193
306
  async verify(receipt) {
194
307
  return this.request("POST", "/verify", { receipt });
195
308
  }
@@ -197,15 +310,7 @@ var _NotaryClient = class _NotaryClient {
197
310
  async verifyById(receiptId) {
198
311
  return this.request("POST", "/verify", { receipt_id: receiptId });
199
312
  }
200
- /**
201
- * Get Notary service status.
202
- *
203
- * @example
204
- * ```typescript
205
- * const status = await notary.status();
206
- * console.log(status.status); // "active"
207
- * ```
208
- */
313
+ /** Get Notary service status. */
209
314
  async status() {
210
315
  return this.request("GET", "/status");
211
316
  }
@@ -217,54 +322,150 @@ var _NotaryClient = class _NotaryClient {
217
322
  async me() {
218
323
  return this.request("GET", "/agents/me");
219
324
  }
325
+ /** Look up a receipt by hash (public endpoint). */
326
+ async lookup(receiptHash) {
327
+ return this.publicGet(`/v1/notary/r/${receiptHash}`);
328
+ }
329
+ // =========================================================================
330
+ // History & Provenance
331
+ // =========================================================================
220
332
  /**
221
- * Look up a receipt by hash (public endpoint, no API key required for lookup).
222
- *
223
- * @param receiptHash - Full or partial receipt hash (min 16 chars)
224
- * @returns Lookup result with receipt, verification, and meta
333
+ * Get paginated receipt history (requires Clerk JWT).
225
334
  *
226
- * @example
227
- * ```typescript
228
- * const result = await notary.lookup('abc123def456...');
229
- * if (result.found && result.verification?.valid) {
230
- * console.log('Receipt is valid!');
231
- * }
232
- * ```
335
+ * @param options - Pagination, filters, and Clerk token
336
+ * @returns Paginated history with items, total, totalPages
233
337
  */
234
- async lookup(receiptHash) {
235
- const url = `${this.baseUrl}/v1/notary/r/${receiptHash}`;
338
+ async history(options = {}) {
339
+ const params = new URLSearchParams();
340
+ params.set("page", String(options.page || 1));
341
+ params.set("page_size", String(options.pageSize || 10));
342
+ if (options.status) params.set("status", options.status);
343
+ if (options.search) params.set("search", options.search);
344
+ if (options.startDate) params.set("start_date", options.startDate);
345
+ if (options.endDate) params.set("end_date", options.endDate);
346
+ const url = `${this.baseUrl}/v1/notary/history?${params.toString()}`;
347
+ const headers = {
348
+ "Content-Type": "application/json",
349
+ "User-Agent": `notary-typescript-sdk/${SDK_VERSION}`
350
+ };
351
+ if (options.clerkToken) {
352
+ headers["Authorization"] = `Bearer ${options.clerkToken}`;
353
+ } else {
354
+ headers["X-API-Key"] = this.apiKey;
355
+ }
236
356
  const controller = new AbortController();
237
357
  const timeoutId = setTimeout(() => controller.abort(), this.timeout);
238
358
  try {
239
359
  const response = await fetch(url, {
240
360
  method: "GET",
241
- headers: {
242
- "Content-Type": "application/json",
243
- "User-Agent": `notary-typescript-sdk/${SDK_VERSION}`
244
- },
361
+ headers,
245
362
  signal: controller.signal
246
363
  });
247
364
  clearTimeout(timeoutId);
248
- if (response.status === 404) {
249
- return { found: false, receipt: null, verification: null, meta: null };
250
- }
251
365
  if (!response.ok) {
252
- throw new NotaryError(
253
- response.statusText,
254
- "ERR_LOOKUP",
255
- response.status
256
- );
366
+ throw new NotaryError(response.statusText, "ERR_HISTORY", response.status);
257
367
  }
258
368
  return await response.json();
259
369
  } catch (err) {
260
370
  clearTimeout(timeoutId);
261
371
  if (err instanceof NotaryError) throw err;
262
- throw new NotaryError(
263
- `Connection failed: ${err.message}`,
264
- "ERR_CONNECTION"
265
- );
372
+ throw new NotaryError(`Connection failed: ${err.message}`, "ERR_CONNECTION");
266
373
  }
267
374
  }
375
+ /**
376
+ * Get the provenance DAG report for a receipt (public).
377
+ *
378
+ * @param receiptHash - The receipt hash to check
379
+ * @returns Provenance report with grounding status, ancestors, paths
380
+ */
381
+ async provenance(receiptHash) {
382
+ return this.publicGet(`/v1/notary/r/${receiptHash}/provenance`);
383
+ }
384
+ // =========================================================================
385
+ // Auto-receipting (wrap)
386
+ // =========================================================================
387
+ /**
388
+ * Wrap an object so method calls are automatically receipted.
389
+ *
390
+ * Uses ES6 Proxy to intercept method calls. Receipts are issued
391
+ * in the background via fire-and-forget (won't slow down your agent).
392
+ *
393
+ * @param obj - The agent or object to wrap
394
+ * @param config - Optional auto-receipt configuration
395
+ * @returns A proxied version of the object
396
+ *
397
+ * @example
398
+ * ```typescript
399
+ * const agent = notary.wrap(myAgent, { mode: 'all', fireAndForget: true });
400
+ * await agent.processData(input); // auto-receipted!
401
+ * ```
402
+ */
403
+ wrap(obj, config = {}) {
404
+ const client = this;
405
+ const cfg = {
406
+ mode: config.mode || "all",
407
+ sampleRate: config.sampleRate ?? 1,
408
+ fireAndForget: config.fireAndForget ?? true,
409
+ maxPayloadBytes: config.maxPayloadBytes ?? 4096,
410
+ dryRun: config.dryRun ?? false
411
+ };
412
+ const className = obj.constructor?.name || "UnknownAgent";
413
+ let lastHash;
414
+ return new Proxy(obj, {
415
+ get(target, prop, receiver) {
416
+ const value = Reflect.get(target, prop, receiver);
417
+ if (typeof value !== "function" || typeof prop !== "string" || prop.startsWith("_")) {
418
+ return value;
419
+ }
420
+ return async function(...args) {
421
+ const start = performance.now();
422
+ let status = "success";
423
+ let errorType;
424
+ let result;
425
+ try {
426
+ result = await value.apply(target, args);
427
+ return result;
428
+ } catch (err) {
429
+ status = "error";
430
+ errorType = err.constructor?.name || "Error";
431
+ throw err;
432
+ } finally {
433
+ const shouldReceipt = cfg.mode === "all" || cfg.mode === "errors_only" && status === "error" || cfg.mode === "sample" && Math.random() < cfg.sampleRate;
434
+ if (shouldReceipt) {
435
+ const durationMs = Math.round((performance.now() - start) * 100) / 100;
436
+ const payload = {
437
+ agent: className,
438
+ auto_receipt: true,
439
+ function: prop,
440
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
441
+ duration_ms: durationMs,
442
+ status,
443
+ error_type: errorType,
444
+ arguments: _safeRepr(args),
445
+ result_summary: _safeRepr(result)
446
+ };
447
+ if (cfg.dryRun) {
448
+ console.error(`[NotaryOS DRY RUN] ${String(prop)}: ${JSON.stringify(payload)}`);
449
+ } else if (cfg.fireAndForget) {
450
+ client.issue(String(prop), payload, { previousReceiptHash: lastHash }).then((r) => {
451
+ if (r.receipt_hash) lastHash = r.receipt_hash;
452
+ }).catch(() => {
453
+ });
454
+ } else {
455
+ try {
456
+ const r = await client.issue(String(prop), payload, {
457
+ previousReceiptHash: lastHash
458
+ });
459
+ if (r.receipt_hash) lastHash = r.receipt_hash;
460
+ } catch {
461
+ }
462
+ }
463
+ }
464
+ }
465
+ };
466
+ }
467
+ });
468
+ }
268
469
  };
269
470
  _NotaryClient.DEFAULT_BASE_URL = "https://api.agenttownsquare.com";
270
471
  _NotaryClient.DEFAULT_TIMEOUT = 3e4;
@@ -294,11 +495,22 @@ async function computeHash(payload) {
294
495
  }
295
496
  return hex;
296
497
  }
498
+ function _safeRepr(value, depth = 3) {
499
+ if (depth <= 0) return value != null ? "..." : null;
500
+ if (value === null || value === void 0) return value;
501
+ if (typeof value === "boolean" || typeof value === "number") return value;
502
+ if (typeof value === "string") return value.length > 500 ? value.slice(0, 500) : value;
503
+ if (Array.isArray(value)) return `<array len=${value.length}>`;
504
+ if (typeof value === "object") return `<object keys=${Object.keys(value).length}>`;
505
+ return `<${typeof value}>`;
506
+ }
297
507
  // Annotate the CommonJS export names for ESM import in node:
298
508
  0 && (module.exports = {
299
509
  AuthenticationError,
510
+ CounterfactualClient,
300
511
  NotaryClient,
301
512
  NotaryError,
513
+ NotaryErrorCode,
302
514
  RateLimitError,
303
515
  SDK_VERSION,
304
516
  ValidationError,