@supercuts-walrus/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # Supercuts TypeScript SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Supercuts gives agents private negotiation and settlement tools, with Walrus
4
+ Memory to carry policy and outcome context into later deals. The SDK exposes
5
+ that workflow through typed role clients while the runtime enforces the owner's
6
+ mandate and verifies payment evidence.
7
+
8
+ `@supercuts-walrus/sdk` is a typed, role-scoped wrapper over the one-request Supercuts
9
+ subprocess seam. Wallet keys, state keys, witnesses, and service credentials stay
10
+ inside the Supercuts process; the SDK receives intents and verified receipts.
11
+
12
+ Install the SDK. It installs the matching backend runtime automatically:
13
+
14
+ ```sh
15
+ pnpm add @supercuts-walrus/sdk@0.1.0
16
+ ```
17
+
18
+ ```ts
19
+ import { BuyerClient, initializeProfile } from "@supercuts-walrus/sdk";
20
+
21
+ await initializeProfile({ home: "/private/buyer" }, { role: "buyer", mock: true });
22
+ const buyer = await BuyerClient.connect({
23
+ home: "/private/buyer",
24
+ approvalProvider: {
25
+ async approve(intent) {
26
+ // Show intent.summary and intent.parameters in trusted operator UI.
27
+ return { approved: true };
28
+ },
29
+ },
30
+ });
31
+ const receipt = await buyer.deposit(100n);
32
+ ```
33
+
34
+ Mock receipts are always labeled as non-funded. The approval provider belongs in
35
+ trusted host code, outside model-controlled tool arguments.
36
+
37
+ For Testnet, initialize with `deploymentConfig`, owner-only `suiKeyFile` and
38
+ `tatumKeyFile`, and the write/Tatum gRPC endpoints instead of `mock: true`.
39
+ Live buyer methods include operation-bound deposit/withdrawal, accepted shielded
40
+ agreement settlement, and `payX402Resource(operationId, resourceUrl)`. The x402
41
+ method obtains amount, asset, and payee from the resource's 402 challenge; it
42
+ does not accept caller-supplied payment requirements.
43
+
44
+ Use `planSettlement(...)` before negotiation or payment when the owner mandate
45
+ requires plans, then pass the returned `planHash` to `payX402Resource`,
46
+ `payX402`, `settleShielded`, or `settleAcceptedShielded`. Typed
47
+ `rememberSettlement` writes are always assigned `agent_observation` provenance;
48
+ they can be cited but cannot expand authority or act as owner policy. Recall
49
+ returns blob ID, kind, provenance, and distance only, never decrypted text.
50
+
51
+ Unsupported live role commands fail closed with `LIVE_COMMAND_UNAVAILABLE`.
52
+ Mock and Testnet receipts remain distinct.
@@ -0,0 +1,589 @@
1
+ export declare const SEAM_PROTOCOL: 1;
2
+ export declare const SDK_VERSION: string;
3
+ export type Role = "buyer" | "seller" | "auditor";
4
+ export type Rail = "shielded" | "x402";
5
+ export type OperationId = string & {
6
+ readonly __brand: "OperationId";
7
+ };
8
+ export type SessionId = string & {
9
+ readonly __brand: "SessionId";
10
+ };
11
+ export type TransactionDigest = string & {
12
+ readonly __brand: "TransactionDigest";
13
+ };
14
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
15
+ [key: string]: JsonValue;
16
+ };
17
+ export type DealState = "created" | "discovered" | "planned" | "awaiting_approval" | "review_required" | "funding_required" | "negotiating" | "agreed" | "evidence_ready" | "payment_pending" | "paid" | "delivery_pending" | "delivered" | "outcome_pending" | "complete" | "failed" | "unresolved";
18
+ export interface ExecuteDealInput {
19
+ operationId: string;
20
+ capabilityId?: string;
21
+ capabilityClass?: string;
22
+ input: Record<string, unknown>;
23
+ budget: {
24
+ asset: string;
25
+ maximum: string;
26
+ };
27
+ privacyHint?: "any" | "shielded";
28
+ requestedRail?: Rail;
29
+ }
30
+ export interface DealView {
31
+ version: "supercuts.deal.v2";
32
+ dealId: string;
33
+ operationId: string;
34
+ state: DealState;
35
+ rail?: Rail;
36
+ visibility?: "shielded-direct-payment" | "public-x402";
37
+ planHash?: string;
38
+ paymentDigest?: string;
39
+ deliveryHash?: string;
40
+ evidence: {
41
+ agreement: "pending" | "verified";
42
+ payment: "pending" | "finalized";
43
+ delivery: "pending" | "verified";
44
+ outcomeMemory: "pending" | "indexed" | "unresolved";
45
+ };
46
+ nextAction?: "resume" | "check_memory" | "reconcile_memory" | "fund_buyer" | "owner_approval" | "owner_review";
47
+ timingsMs?: Record<string, number>;
48
+ }
49
+ export interface DealReconciliation {
50
+ resolved: boolean;
51
+ state: string;
52
+ blobId?: string;
53
+ }
54
+ export interface DealEvidenceView {
55
+ version: "supercuts.deal-evidence.v1";
56
+ dealId: string;
57
+ transcriptBlobIds: string[];
58
+ agreementBlobId?: string;
59
+ deliveryBlobId?: string;
60
+ outcomeMemoryBlobId?: string;
61
+ ciphertextReadback: "pending" | "verified" | "unresolved";
62
+ inventory: "pending" | "indexed" | "missing" | "unresolved";
63
+ paymentFinalized: boolean;
64
+ paymentDigest?: string;
65
+ }
66
+ export interface DealDelivery {
67
+ dealId: string;
68
+ contentType: string;
69
+ artifactSha256: string;
70
+ artifact: Uint8Array;
71
+ }
72
+ export interface DealPolicySummary {
73
+ perDealCeiling: string;
74
+ totalBudget: string;
75
+ remainingBudget: string;
76
+ expiresAt: number;
77
+ defaultRail: "shielded";
78
+ allowPublicX402: boolean;
79
+ allowedAssets: string[];
80
+ allowedCapabilityIds?: string[];
81
+ allowedCapabilityClasses?: string[];
82
+ }
83
+ export interface DealCatalogEntry {
84
+ origin: string;
85
+ manifest: CapabilityManifest;
86
+ manifestBlobId: string;
87
+ }
88
+ export interface CapabilityManifest {
89
+ protocol: "supercuts.capability.v1";
90
+ capabilityId: string;
91
+ sellerId: string;
92
+ capability: string;
93
+ description: string;
94
+ inputSchema: Readonly<Record<string, unknown>>;
95
+ outputSchema: Readonly<Record<string, unknown>>;
96
+ supportedRails: Rail[];
97
+ priceBand: {
98
+ minimum: string;
99
+ maximum: string;
100
+ };
101
+ asset: string;
102
+ endpoint: string;
103
+ expiresAt: number;
104
+ manifestHash: string;
105
+ }
106
+ export interface ProcurementTask {
107
+ taskId: string;
108
+ request: string;
109
+ privacy: "public" | "confidential";
110
+ maximumAmount: bigint;
111
+ asset: string;
112
+ requiredCapability: string;
113
+ }
114
+ export interface SettlementIntent {
115
+ operationId: OperationId;
116
+ dealId: string;
117
+ rail: Rail;
118
+ amount: bigint;
119
+ asset: string;
120
+ counterparty: string;
121
+ requestId: string;
122
+ }
123
+ export interface DeliveryReceipt {
124
+ requestId: string;
125
+ operationId: OperationId;
126
+ artifactSha256: string;
127
+ deliveredAt: number;
128
+ observation: "artifact-delivered";
129
+ }
130
+ export interface MemoryFact {
131
+ kind: "task" | "capability_choice" | "offer" | "agreed_cost" | "seller_responsiveness" | "settlement_rail" | "delivery_hash" | "latency" | "retry_behavior" | "outcome" | "privacy_policy";
132
+ subject: string;
133
+ observation: string;
134
+ operationId: OperationId;
135
+ createdAt: number;
136
+ }
137
+ export interface SettlementMemoryV1 {
138
+ version: "supercuts.settlement-memory.v1";
139
+ kind: "privacy_rule" | "budget_limit" | "reliability" | "quality" | "outcome";
140
+ provenance?: "agent_observation";
141
+ scope: {
142
+ counterparty?: string;
143
+ capabilityId?: string;
144
+ capabilityClass?: string;
145
+ network?: "sui:testnet";
146
+ asset?: string;
147
+ };
148
+ createdAt: number;
149
+ evidenceHash?: string;
150
+ observation?: string;
151
+ signal: {
152
+ requiresShielded?: boolean;
153
+ maximumAmount?: string;
154
+ reliability?: number;
155
+ quality?: number;
156
+ outcome?: "succeeded" | "failed" | "unresolved";
157
+ };
158
+ }
159
+ export interface SettlementCitation {
160
+ blobId: string;
161
+ kind: SettlementMemoryV1["kind"] | "legacy";
162
+ provenance: "owner_policy" | "verified_outcome" | "agent_observation" | "legacy_untrusted";
163
+ distance: number;
164
+ }
165
+ export interface SettlementPlanV1 {
166
+ version: "supercuts.settlement-plan.v1";
167
+ planHash: string;
168
+ operationId: string;
169
+ status: "approved" | "review_required";
170
+ mandateHash: string;
171
+ manifestHash: string;
172
+ capabilityId: string;
173
+ capabilityClass: string;
174
+ sellerId: string;
175
+ endpoint: string;
176
+ network: "sui:testnet";
177
+ asset: string;
178
+ rail: Rail;
179
+ openingAmount: string;
180
+ maximumAmount: string;
181
+ manifestMinimum: string;
182
+ manifestMaximum: string;
183
+ riskLevel: "low" | "medium" | "review_required";
184
+ createdAt: number;
185
+ expiresAt: number;
186
+ citations: SettlementCitation[];
187
+ reasonCodes: string[];
188
+ approvedFromPlanHash?: string;
189
+ }
190
+ export interface DemoEvent {
191
+ schema: "supercuts.demo.v1";
192
+ sequence: number;
193
+ runId: string;
194
+ timestamp: string;
195
+ actor: string;
196
+ stage: string;
197
+ status: string;
198
+ mode: "live" | "recorded-funded-run";
199
+ publicDetails: Readonly<Record<string, unknown>>;
200
+ evidenceHashes: string[];
201
+ explorerLinks: string[];
202
+ }
203
+ export interface AuthorizationIntent {
204
+ challengeId: string;
205
+ intentHash: string;
206
+ role: Role;
207
+ command: string;
208
+ summary: string;
209
+ parameters: Record<string, string | boolean>;
210
+ expiresAt: number;
211
+ }
212
+ export interface ApprovalDecision {
213
+ approved: boolean;
214
+ reason?: string;
215
+ }
216
+ export interface ApprovalProvider {
217
+ approve(intent: Readonly<AuthorizationIntent>): Promise<ApprovalDecision>;
218
+ }
219
+ export interface SupercutsSdkConfig {
220
+ home: string;
221
+ approvalProvider?: ApprovalProvider;
222
+ seamPath?: string;
223
+ timeoutMs?: number;
224
+ }
225
+ export interface MockInitializeOptions {
226
+ role: Role;
227
+ mock: true;
228
+ artifactManifest?: string;
229
+ maxAmount?: bigint;
230
+ allowedCounterparties?: string[];
231
+ requireShielded?: boolean;
232
+ maxMemoryDistance?: number;
233
+ }
234
+ export interface LiveInitializeOptions {
235
+ role: Role;
236
+ mock?: false;
237
+ deploymentConfig: string;
238
+ suiKeyFile: string;
239
+ tatumKeyFile: string;
240
+ writeGrpc: string;
241
+ tatumGrpc: string;
242
+ snarkjsPath?: string;
243
+ converterPath?: string;
244
+ rapidsnarkPath?: string;
245
+ memoryConfigFile?: string;
246
+ walrusPublisher?: string;
247
+ walrusAggregator?: string;
248
+ maxAmount?: bigint;
249
+ allowedCounterparties?: string[];
250
+ requireShielded?: boolean;
251
+ maxMemoryDistance?: number;
252
+ }
253
+ export type InitializeOptions = MockInitializeOptions | LiveInitializeOptions;
254
+ export interface DoctorReport {
255
+ role: Role;
256
+ network: "testnet";
257
+ packageId: string;
258
+ poolId: string;
259
+ asset: string;
260
+ verifierVersion: number;
261
+ artifactManifestSha256: string;
262
+ keyPermissions: "owner-only";
263
+ rpc: string;
264
+ healthy: true;
265
+ }
266
+ export interface Status {
267
+ role: Role;
268
+ network: "testnet";
269
+ operations: number;
270
+ mock: boolean;
271
+ }
272
+ export interface WalletBalance {
273
+ available: bigint;
274
+ notes: number;
275
+ }
276
+ export interface QueuedExit {
277
+ operationId: string;
278
+ commitment: string;
279
+ payoutAddress: string;
280
+ amount: bigint;
281
+ exactExit: boolean;
282
+ windowStart: number;
283
+ executeAt: number;
284
+ windowEnd: number;
285
+ status: "queued" | "submitted" | "finalized";
286
+ visibility?: string;
287
+ }
288
+ export interface TransactionReceipt {
289
+ transactionDigest: TransactionDigest;
290
+ finalized: boolean;
291
+ evidence: string;
292
+ amount?: bigint;
293
+ commitment?: string;
294
+ }
295
+ export interface OfferState {
296
+ sessionId: SessionId;
297
+ revision: number;
298
+ state: string;
299
+ termsHash?: string;
300
+ transcriptCommitment: string;
301
+ }
302
+ export interface PaymentQuote {
303
+ rail: Rail;
304
+ amount: bigint;
305
+ counterparty: string;
306
+ asset: string;
307
+ policyDecision: "allowed";
308
+ visibility: string;
309
+ }
310
+ export interface PaymentReceipt {
311
+ operationId: OperationId;
312
+ status: "broadcast" | "finalized" | "unresolved";
313
+ rail: Rail;
314
+ amount: bigint;
315
+ counterparty: string;
316
+ asset: string;
317
+ requestId: string;
318
+ transactionDigest: TransactionDigest;
319
+ policyDecision: "allowed";
320
+ tatumVerified: boolean;
321
+ visibility: string;
322
+ evidence: string;
323
+ }
324
+ export interface MemoryStatus {
325
+ namespace: string;
326
+ completed: number;
327
+ jobs: Array<{
328
+ operationId: string;
329
+ blobId: string;
330
+ status: string;
331
+ }>;
332
+ }
333
+ export interface Capability {
334
+ capabilityId: string;
335
+ seller: string;
336
+ service: string;
337
+ terms: string;
338
+ blobId: string;
339
+ visibility: "public-capability";
340
+ }
341
+ export interface DisclosureReference {
342
+ package: string;
343
+ packageHash: string;
344
+ auditor: string;
345
+ dealId: string;
346
+ }
347
+ export interface AuditResult {
348
+ dealId: string;
349
+ agreementVerified: boolean;
350
+ paymentVerified: boolean;
351
+ transactionDigest: TransactionDigest;
352
+ evidence: string;
353
+ }
354
+ export declare class SupercutsSdkError extends Error {
355
+ readonly code: string;
356
+ readonly retryable: boolean;
357
+ readonly recovery?: string | undefined;
358
+ constructor(code: string, message: string, retryable: boolean, recovery?: string | undefined);
359
+ }
360
+ export declare class SeamUnavailable extends Error {
361
+ constructor(message: string);
362
+ }
363
+ export declare function operationId(value: string): OperationId;
364
+ export declare function sessionId(value: string): SessionId;
365
+ declare class Seam {
366
+ #private;
367
+ private readonly config;
368
+ constructor(config: SupercutsSdkConfig);
369
+ call<T>(method: string, params?: Record<string, unknown>, withHome?: boolean): Promise<T>;
370
+ }
371
+ type Arguments = Record<string, unknown>;
372
+ declare abstract class RoleClient {
373
+ protected readonly config: SupercutsSdkConfig;
374
+ protected readonly seam: Seam;
375
+ protected constructor(config: SupercutsSdkConfig);
376
+ doctor(): Promise<DoctorReport>;
377
+ status(): Promise<Status>;
378
+ protected ensureCompatible(): Promise<void>;
379
+ protected read<T>(command: string, args?: Arguments): Promise<T>;
380
+ protected mutate<T>(command: string, args: Arguments): Promise<T>;
381
+ }
382
+ declare const paymentArgs: (input: {
383
+ operationId: OperationId;
384
+ amount: bigint;
385
+ counterparty: string;
386
+ asset?: string;
387
+ requestId?: string;
388
+ broadcastOnly?: boolean;
389
+ planHash?: string;
390
+ }) => Arguments;
391
+ declare const exitArgs: (input: {
392
+ operationId: OperationId;
393
+ commitment: string;
394
+ amount: bigint;
395
+ exactExit?: boolean;
396
+ windowStart: number;
397
+ windowEnd: number;
398
+ }) => Arguments;
399
+ export declare class BuyerClient extends RoleClient {
400
+ listDealCapabilities(): Promise<DealCatalogEntry[]>;
401
+ getDealPolicy(): Promise<DealPolicySummary>;
402
+ static connect(config: SupercutsSdkConfig): Promise<BuyerClient>;
403
+ executeDeal(input: ExecuteDealInput): Promise<DealView>;
404
+ getDeal(operationId: string): Promise<DealView>;
405
+ resumeDeal(operationId: string): Promise<DealView>;
406
+ reconcileDealOutcome(operationId: string): Promise<DealReconciliation>;
407
+ getDealEvidence(dealId: string): Promise<DealEvidenceView>;
408
+ getDealDelivery(dealId: string): Promise<DealDelivery>;
409
+ discoverSellers(capabilities: Capability[]): Promise<Capability[]>;
410
+ discoverCapabilities(manifests: CapabilityManifest[]): Promise<CapabilityManifest[]>;
411
+ discoverCapabilityBlobs(blobIds: string[]): Promise<Array<CapabilityManifest & {
412
+ blobId: string;
413
+ }>>;
414
+ planSettlement(input: {
415
+ operationId: OperationId;
416
+ manifest: CapabilityManifest;
417
+ alternatives?: CapabilityManifest[];
418
+ requestedAmount?: bigint;
419
+ privacyHint?: "any" | "shielded";
420
+ requestedRail?: Rail;
421
+ }): Promise<SettlementPlanV1>;
422
+ deposit(amount: bigint, id?: OperationId): Promise<TransactionReceipt>;
423
+ balance(): Promise<WalletBalance>;
424
+ recover(): Promise<{
425
+ recovered: number;
426
+ source: string;
427
+ }>;
428
+ withdraw(commitment: string, recipient?: string, id?: OperationId): Promise<TransactionReceipt>;
429
+ queueExit(input: Parameters<typeof exitArgs>[0]): Promise<QueuedExit>;
430
+ exitStatus(id: OperationId): Promise<QueuedExit>;
431
+ finalizeExit(id: OperationId, digest: string, approvalId?: OperationId): Promise<Record<string, unknown>>;
432
+ openOffer(session?: SessionId): Promise<OfferState>;
433
+ propose(session: SessionId, revision: number, terms: Readonly<Record<string, JsonValue>>): Promise<OfferState>;
434
+ accept(session: SessionId, revision: number, terms: Readonly<Record<string, JsonValue>>): Promise<OfferState>;
435
+ acceptCryptographicAgreement(session: SessionId, agreement: Readonly<Record<string, JsonValue>>, plan?: {
436
+ planHash: string;
437
+ manifest: CapabilityManifest;
438
+ }): Promise<{
439
+ sessionId: string;
440
+ revision: string;
441
+ state: "accepted";
442
+ dealCommitment: string;
443
+ expiry: string;
444
+ paymentAmount: string;
445
+ }>;
446
+ showOffer(session: SessionId): Promise<OfferState>;
447
+ quote(input: {
448
+ rail: Rail;
449
+ amount: bigint;
450
+ counterparty: string;
451
+ asset?: string;
452
+ }): Promise<PaymentQuote>;
453
+ settleShielded(input: Parameters<typeof paymentArgs>[0]): Promise<PaymentReceipt>;
454
+ settleAcceptedShielded(operationId: OperationId, session: SessionId, planHash?: string): Promise<PaymentReceipt>;
455
+ payX402(input: Parameters<typeof paymentArgs>[0]): Promise<PaymentReceipt>;
456
+ payX402Resource(id: OperationId, resourceUrl: string, planHash?: string): Promise<PaymentReceipt & {
457
+ response: Uint8Array;
458
+ responseSha256: string;
459
+ }>;
460
+ paymentStatus(operationId: OperationId, reconcile?: boolean): Promise<PaymentReceipt>;
461
+ reconcilePayment(operationId: OperationId): Promise<PaymentReceipt>;
462
+ fetchResource(input: {
463
+ requestId: string;
464
+ operationId: OperationId;
465
+ response: Uint8Array;
466
+ }): Promise<{
467
+ requestId: string;
468
+ responseHash: string;
469
+ body: Uint8Array;
470
+ deliveryStatus: string;
471
+ }>;
472
+ remember(operationId: OperationId, fact: string): Promise<{
473
+ operationId: string;
474
+ namespace: string;
475
+ blobId: string;
476
+ status: string;
477
+ }>;
478
+ rememberSettlement(operationId: OperationId, memory: Omit<SettlementMemoryV1, "provenance">): Promise<{
479
+ operationId: string;
480
+ namespace: string;
481
+ blobId: string;
482
+ status: string;
483
+ provenance: "agent_observation";
484
+ }>;
485
+ recall(query: string): Promise<{
486
+ namespace: string;
487
+ citations: SettlementCitation[];
488
+ effect: string;
489
+ }>;
490
+ memoryStatus(): Promise<MemoryStatus>;
491
+ syncMemoryInventory(blobId?: string): Promise<{
492
+ namespace: string;
493
+ indexed: number;
494
+ deleted: number;
495
+ cursor: string | null;
496
+ blobId?: string;
497
+ present?: boolean;
498
+ expiresAt?: string;
499
+ }>;
500
+ requestDisclosure(input: {
501
+ dealId: string;
502
+ auditor: string;
503
+ paymentDigest: TransactionDigest;
504
+ transcriptRoot: string;
505
+ }): Promise<DisclosureReference>;
506
+ }
507
+ export declare class SellerClient extends RoleClient {
508
+ static connect(config: SupercutsSdkConfig): Promise<SellerClient>;
509
+ publishCapability(input: {
510
+ capabilityId?: string;
511
+ seller: string;
512
+ service: string;
513
+ terms: string;
514
+ }): Promise<Capability>;
515
+ publishManifest(manifest: CapabilityManifest, id?: OperationId): Promise<CapabilityManifest & {
516
+ blobId: string;
517
+ visibility: "public-capability";
518
+ }>;
519
+ counter(session: SessionId, revision: number, terms: Readonly<Record<string, JsonValue>>): Promise<OfferState>;
520
+ prepareCryptographicAgreement(session: SessionId, draft: Readonly<Record<string, JsonValue>>): Promise<{
521
+ sessionId: string;
522
+ revision: string;
523
+ state: "counter";
524
+ dealCommitment: string;
525
+ agreement: string;
526
+ }>;
527
+ showOffer(session: SessionId): Promise<OfferState>;
528
+ paymentStatus(operationId: OperationId): Promise<PaymentReceipt>;
529
+ recoverPayment(commitment: string, amount: bigint): Promise<{
530
+ recovered: number;
531
+ source: string;
532
+ }>;
533
+ balance(): Promise<WalletBalance>;
534
+ withdraw(commitment: string, recipient?: string, id?: OperationId): Promise<TransactionReceipt>;
535
+ queueExit(input: Parameters<typeof exitArgs>[0]): Promise<QueuedExit>;
536
+ exitStatus(id: OperationId): Promise<QueuedExit>;
537
+ finalizeExit(id: OperationId, digest: string, approvalId?: OperationId): Promise<Record<string, unknown>>;
538
+ serveResource(requestId: string, body: Uint8Array): Promise<{
539
+ requestId: string;
540
+ responseHash: string;
541
+ deliveryStatus: string;
542
+ }>;
543
+ fetchResource(input: {
544
+ requestId: string;
545
+ operationId: OperationId;
546
+ response: Uint8Array;
547
+ }): Promise<{
548
+ requestId: string;
549
+ responseHash: string;
550
+ body: Uint8Array;
551
+ deliveryStatus: string;
552
+ }>;
553
+ remember(operationId: OperationId, fact: string): Promise<{
554
+ operationId: string;
555
+ namespace: string;
556
+ blobId: string;
557
+ status: string;
558
+ }>;
559
+ recall(query: string): Promise<{
560
+ namespace: string;
561
+ citations: SettlementCitation[];
562
+ effect: string;
563
+ }>;
564
+ memoryStatus(): Promise<MemoryStatus>;
565
+ syncMemoryInventory(blobId?: string): Promise<{
566
+ namespace: string;
567
+ indexed: number;
568
+ deleted: number;
569
+ cursor: string | null;
570
+ blobId?: string;
571
+ present?: boolean;
572
+ expiresAt?: string;
573
+ }>;
574
+ }
575
+ export declare class AuditorClient extends RoleClient {
576
+ static connect(config: SupercutsSdkConfig): Promise<AuditorClient>;
577
+ verify(input: {
578
+ package: string;
579
+ auditor: string;
580
+ dealId: string;
581
+ }): Promise<AuditResult>;
582
+ }
583
+ export declare function initializeProfile(config: Omit<SupercutsSdkConfig, "approvalProvider">, options: InitializeOptions): Promise<{
584
+ role: Role;
585
+ home: string;
586
+ network: "testnet";
587
+ mock: boolean;
588
+ }>;
589
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,193 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { createRequire } from "node:module";
4
+ import { existsSync } from "node:fs";
5
+ export const SEAM_PROTOCOL = 1;
6
+ const require = createRequire(import.meta.url);
7
+ export const SDK_VERSION = require("../package.json").version;
8
+ export class SupercutsSdkError extends Error {
9
+ code;
10
+ retryable;
11
+ recovery;
12
+ constructor(code, message, retryable, recovery) {
13
+ super(message);
14
+ this.code = code;
15
+ this.retryable = retryable;
16
+ this.recovery = recovery;
17
+ this.name = "SupercutsSdkError";
18
+ }
19
+ }
20
+ export class SeamUnavailable extends Error {
21
+ constructor(message) { super(message); this.name = "SeamUnavailable"; }
22
+ }
23
+ export function operationId(value) { if (!value || value.length > 256)
24
+ throw new TypeError("operation ID must contain 1..256 characters"); return value; }
25
+ export function sessionId(value) { if (!value || value.length > 256)
26
+ throw new TypeError("session ID must contain 1..256 characters"); return value; }
27
+ function defaultSeamPath() {
28
+ try {
29
+ return require.resolve("@supercuts-walrus/backend/seam");
30
+ }
31
+ catch {
32
+ throw new SeamUnavailable(`@supercuts-walrus/backend@${SDK_VERSION} is missing. Reinstall @supercuts-walrus/sdk to restore its runtime dependency.`);
33
+ }
34
+ }
35
+ class Seam {
36
+ config;
37
+ #path;
38
+ #timeout;
39
+ constructor(config) {
40
+ this.config = config;
41
+ this.#path = config.seamPath ?? defaultSeamPath();
42
+ this.#timeout = config.timeoutMs ?? 300_000;
43
+ if (!Number.isSafeInteger(this.#timeout) || this.#timeout <= 0)
44
+ throw new TypeError("timeoutMs must be a positive integer");
45
+ if (!existsSync(this.#path))
46
+ throw new SeamUnavailable(`Supercuts runtime file is missing at ${this.#path}. Reinstall @supercuts-walrus/sdk and @supercuts-walrus/backend.`);
47
+ }
48
+ async call(method, params, withHome = true) {
49
+ const request = { protocol: SEAM_PROTOCOL, requestId: randomUUID(), method, ...(withHome ? { home: this.config.home } : {}), ...(params ? { params } : {}) };
50
+ return await new Promise((resolve, reject) => {
51
+ const child = spawn(process.execPath, [this.#path], { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env } });
52
+ let stdout = "", stderrBytes = 0, done = false;
53
+ const timer = setTimeout(() => { child.kill("SIGKILL"); finish(new SeamUnavailable(`${method} exceeded ${this.#timeout}ms. Retry the operation with the same operation ID after checking the role journal.`)); }, this.#timeout);
54
+ const finish = (error, value) => { if (done)
55
+ return; done = true; clearTimeout(timer); error ? reject(error) : resolve(value); };
56
+ child.stdout.setEncoding("utf8");
57
+ child.stdout.on("data", (chunk) => { stdout += chunk; if (stdout.length > 2 * 1024 * 1024) {
58
+ child.kill("SIGKILL");
59
+ finish(new SeamUnavailable("seam response exceeded 2 MiB"));
60
+ } });
61
+ child.stderr.on("data", (chunk) => { stderrBytes += chunk.length; });
62
+ child.on("error", (error) => finish(new SeamUnavailable(`could not start Supercuts seam: ${error.message}`)));
63
+ child.stdin.on("error", () => finish(new SeamUnavailable("Supercuts seam closed its input before accepting the request. Check the backend installation and retry with the same operation ID.")));
64
+ child.on("close", (code, signal) => {
65
+ if (done)
66
+ return;
67
+ let response;
68
+ try {
69
+ response = JSON.parse(stdout);
70
+ }
71
+ catch {
72
+ return finish(new SeamUnavailable(`seam returned invalid JSON (exit ${code ?? signal ?? "unknown"}; ${stderrBytes} stderr bytes). Check the installed backend and retry with the same operation ID.`));
73
+ }
74
+ if (!response || response.protocol !== SEAM_PROTOCOL || response.requestId !== request.requestId || typeof response.ok !== "boolean")
75
+ return finish(new SeamUnavailable("seam response protocol or shape is invalid. Reinstall matching SDK and backend versions."));
76
+ if (!response.ok)
77
+ return finish(new SupercutsSdkError(response.error?.code ?? "INTERNAL_ERROR", response.error?.message ?? "Supercuts returned no detail", Boolean(response.error?.retryable), response.error?.recovery));
78
+ if (response.result === undefined)
79
+ return finish(new SeamUnavailable("seam success response omitted its result. Check backend compatibility."));
80
+ finish(undefined, response.result);
81
+ });
82
+ child.stdin.end(JSON.stringify(request));
83
+ });
84
+ }
85
+ }
86
+ class RoleClient {
87
+ config;
88
+ seam;
89
+ constructor(config) {
90
+ this.config = config;
91
+ this.seam = new Seam(config);
92
+ }
93
+ async doctor() { return this.read("doctor"); }
94
+ async status() { return this.read("status"); }
95
+ async ensureCompatible() { const version = await this.seam.call("version", undefined, false); if (version.protocol !== SEAM_PROTOCOL || version.packageVersion !== SDK_VERSION)
96
+ throw new SeamUnavailable(`Supercuts backend ${version.packageVersion}/protocol ${version.protocol} is incompatible with SDK ${SDK_VERSION}/protocol ${SEAM_PROTOCOL}. Install matching versions.`); }
97
+ async read(command, args = {}) { return this.seam.call("command.execute", { command, arguments: args }); }
98
+ async mutate(command, args) {
99
+ const provider = this.config.approvalProvider;
100
+ if (!provider)
101
+ throw new SupercutsSdkError("SDK_APPROVAL_PROVIDER_REQUIRED", `${command} requires an ApprovalProvider`, false);
102
+ const intent = await this.seam.call("authorization.preview", { command, arguments: args });
103
+ const decision = await provider.approve(Object.freeze(intent));
104
+ if (!decision.approved)
105
+ throw new SupercutsSdkError("AUTHORIZATION_DENIED", decision.reason ?? "the approval provider denied this intent", false);
106
+ const approval = await this.seam.call("authorization.approve", { challengeId: intent.challengeId });
107
+ return this.seam.call("command.execute", { command, arguments: args, approvalToken: approval.token });
108
+ }
109
+ }
110
+ const paymentArgs = (input) => ({
111
+ "operation-id": input.operationId, amount: input.amount.toString(), counterparty: input.counterparty,
112
+ ...(input.asset ? { asset: input.asset } : {}), ...(input.requestId ? { "request-id": input.requestId } : {}), ...(input.broadcastOnly ? { "broadcast-only": true } : {}), ...(input.planHash ? { "plan-hash": input.planHash } : {}),
113
+ });
114
+ const payment = (value) => ({ ...value, amount: BigInt(value.amount) });
115
+ const queuedExit = (value) => ({ ...value, amount: BigInt(value.amount) });
116
+ const exitArgs = (input) => ({ "operation-id": input.operationId, commitment: input.commitment, amount: input.amount.toString(), "exact-exit": input.exactExit === true, "window-start": String(input.windowStart), "window-end": String(input.windowEnd) });
117
+ export class BuyerClient extends RoleClient {
118
+ async listDealCapabilities() { const result = await this.seam.call("deal.catalog"); return result.capabilities; }
119
+ async getDealPolicy() { return this.seam.call("deal.policy"); }
120
+ static async connect(config) { const client = new BuyerClient(config); await client.ensureCompatible(); const report = await client.doctor(); if (report.role !== "buyer")
121
+ throw new SupercutsSdkError("SDK_ROLE_MISMATCH", `expected buyer profile, found ${report.role}`, false); return client; }
122
+ async executeDeal(input) { return this.seam.call("deal.execute", { input }); }
123
+ async getDeal(operationId) { return this.seam.call("deal.get", { operationId }); }
124
+ async resumeDeal(operationId) { return this.seam.call("deal.resume", { operationId }); }
125
+ async reconcileDealOutcome(operationId) { return this.seam.call("deal.reconcile", { operationId }); }
126
+ async getDealEvidence(dealId) { return this.seam.call("deal.evidence", { dealId }); }
127
+ async getDealDelivery(dealId) { const value = await this.seam.call("deal.delivery", { dealId }); return { ...value, artifact: Buffer.from(value.artifact, "base64") }; }
128
+ async discoverSellers(capabilities) { const value = await this.read("capability.discover", { capabilities }); return value.capabilities; }
129
+ async discoverCapabilities(manifests) { const value = await this.read("capability.discover", { capabilities: manifests }); return value.capabilities; }
130
+ async discoverCapabilityBlobs(blobIds) { const value = await this.read("capability.discover", { "blob-ids": blobIds }); return value.capabilities; }
131
+ async planSettlement(input) { return this.mutate("settlement.plan", { "operation-id": input.operationId, manifest: input.manifest, ...(input.alternatives ? { alternatives: input.alternatives } : {}), ...(input.requestedAmount !== undefined ? { "requested-amount": input.requestedAmount.toString() } : {}), ...(input.privacyHint ? { "privacy-hint": input.privacyHint } : {}), ...(input.requestedRail ? { "requested-rail": input.requestedRail } : {}) }); }
132
+ async deposit(amount, id = operationId(randomUUID())) { const value = await this.mutate("wallet.deposit", { amount: amount.toString(), "operation-id": id }); return { ...value, amount: BigInt(value.amount) }; }
133
+ async balance() { const value = await this.read("wallet.balance"); return { ...value, available: BigInt(value.available) }; }
134
+ async recover() { return this.mutate("wallet.recover", {}); }
135
+ async withdraw(commitment, recipient, id = operationId(randomUUID())) { const value = await this.mutate("wallet.withdraw", { commitment, "operation-id": id, ...(recipient ? { recipient } : {}) }); return { ...value, amount: BigInt(value.amount) }; }
136
+ async queueExit(input) { return queuedExit(await this.mutate("wallet.exit.queue", exitArgs(input))); }
137
+ async exitStatus(id) { return queuedExit(await this.read("wallet.exit.status", { "operation-id": id })); }
138
+ async finalizeExit(id, digest, approvalId = operationId(randomUUID())) { return this.mutate("wallet.exit.finalize", { "operation-id": approvalId, "exit-id": id, digest }); }
139
+ async openOffer(session) { return this.mutate("offer.open", session ? { session } : {}); }
140
+ async propose(session, revision, terms) { return this.mutate("offer.propose", { session, revision, terms: JSON.stringify(terms) }); }
141
+ async accept(session, revision, terms) { return this.mutate("offer.accept", { session, revision, terms: JSON.stringify(terms) }); }
142
+ async acceptCryptographicAgreement(session, agreement, plan) { return this.mutate("offer.accept", { session, agreement: Buffer.from(JSON.stringify(agreement)).toString("base64url"), ...(plan ? { "plan-hash": plan.planHash, manifest: plan.manifest } : {}) }); }
143
+ async showOffer(session) { return this.read("offer.show", { session }); }
144
+ async quote(input) { const value = await this.read("pay.quote", { rail: input.rail, amount: input.amount.toString(), counterparty: input.counterparty, ...(input.asset ? { asset: input.asset } : {}) }); return { ...value, amount: BigInt(value.amount) }; }
145
+ async settleShielded(input) { return payment(await this.mutate("pay.shielded", paymentArgs(input))); }
146
+ async settleAcceptedShielded(operationId, session, planHash) { return payment(await this.mutate("pay.shielded", { "operation-id": operationId, session, ...(planHash ? { "plan-hash": planHash } : {}) })); }
147
+ async payX402(input) { return payment(await this.mutate("pay.x402", paymentArgs(input))); }
148
+ async payX402Resource(id, resourceUrl, planHash) { const value = await this.mutate("pay.x402", { "operation-id": id, "resource-url": resourceUrl, ...(planHash ? { "plan-hash": planHash } : {}) }); return { ...value, amount: BigInt(value.amount), response: Buffer.from(value.response, "base64"), responseSha256: String(value.responseSha256) }; }
149
+ async paymentStatus(operationId, reconcile = false) { return payment(await this.read("pay.status", { "operation-id": operationId, ...(reconcile ? { reconcile: true } : {}) })); }
150
+ async reconcilePayment(operationId) { return this.paymentStatus(operationId, true); }
151
+ async fetchResource(input) { const value = await this.read("resource.fetch", { "request-id": input.requestId, "operation-id": input.operationId, response: Buffer.from(input.response).toString("base64") }); return { ...value, body: Buffer.from(value.body, "base64") }; }
152
+ async remember(operationId, fact) { return this.mutate("memory.remember", { "operation-id": operationId, fact }); }
153
+ async rememberSettlement(operationId, memory) { return this.mutate("memory.remember", { "operation-id": operationId, memory }); }
154
+ async recall(query) { return this.read("memory.recall", { query }); }
155
+ async memoryStatus() { return this.read("memory.status"); }
156
+ async syncMemoryInventory(blobId) { return this.read("memory.inventory", blobId ? { "blob-id": blobId } : {}); }
157
+ async requestDisclosure(input) { return this.mutate("disclose", { "deal-id": input.dealId, auditor: input.auditor, "payment-digest": input.paymentDigest, "transcript-root": input.transcriptRoot }); }
158
+ }
159
+ export class SellerClient extends RoleClient {
160
+ static async connect(config) { const client = new SellerClient(config); await client.ensureCompatible(); const report = await client.doctor(); if (report.role !== "seller")
161
+ throw new SupercutsSdkError("SDK_ROLE_MISMATCH", `expected seller profile, found ${report.role}`, false); return client; }
162
+ async publishCapability(input) { return this.mutate("capability.publish", { ...(input.capabilityId ? { "capability-id": input.capabilityId } : {}), seller: input.seller, service: input.service, terms: input.terms }); }
163
+ async publishManifest(manifest, id = operationId(randomUUID())) { return this.mutate("capability.publish", { manifest, "operation-id": id }); }
164
+ async counter(session, revision, terms) { return this.mutate("offer.counter", { session, revision, terms: JSON.stringify(terms) }); }
165
+ async prepareCryptographicAgreement(session, draft) { return this.mutate("offer.counter", { session, agreement: Buffer.from(JSON.stringify(draft)).toString("base64url") }); }
166
+ async showOffer(session) { return this.read("offer.show", { session }); }
167
+ async paymentStatus(operationId) { return payment(await this.read("pay.status", { "operation-id": operationId })); }
168
+ async recoverPayment(commitment, amount) { return this.mutate("wallet.recover", { commitment, amount: amount.toString() }); }
169
+ async balance() { const value = await this.read("wallet.balance"); return { ...value, available: BigInt(value.available) }; }
170
+ async withdraw(commitment, recipient, id = operationId(randomUUID())) { const value = await this.mutate("wallet.withdraw", { commitment, "operation-id": id, ...(recipient ? { recipient } : {}) }); return { ...value, amount: BigInt(value.amount) }; }
171
+ async queueExit(input) { return queuedExit(await this.mutate("wallet.exit.queue", exitArgs(input))); }
172
+ async exitStatus(id) { return queuedExit(await this.read("wallet.exit.status", { "operation-id": id })); }
173
+ async finalizeExit(id, digest, approvalId = operationId(randomUUID())) { return this.mutate("wallet.exit.finalize", { "operation-id": approvalId, "exit-id": id, digest }); }
174
+ async serveResource(requestId, body) { return this.mutate("resource.serve", { "request-id": requestId, body: Buffer.from(body).toString("base64") }); }
175
+ async fetchResource(input) { const value = await this.read("resource.fetch", { "request-id": input.requestId, "operation-id": input.operationId, response: Buffer.from(input.response).toString("base64") }); return { ...value, body: Buffer.from(value.body, "base64") }; }
176
+ async remember(operationId, fact) { return this.mutate("memory.remember", { "operation-id": operationId, fact }); }
177
+ async recall(query) { return this.read("memory.recall", { query }); }
178
+ async memoryStatus() { return this.read("memory.status"); }
179
+ async syncMemoryInventory(blobId) { return this.read("memory.inventory", blobId ? { "blob-id": blobId } : {}); }
180
+ }
181
+ export class AuditorClient extends RoleClient {
182
+ static async connect(config) { const client = new AuditorClient(config); await client.ensureCompatible(); const report = await client.doctor(); if (report.role !== "auditor")
183
+ throw new SupercutsSdkError("SDK_ROLE_MISMATCH", `expected auditor profile, found ${report.role}`, false); return client; }
184
+ async verify(input) { return this.read("audit.verify", { package: input.package, auditor: input.auditor, "deal-id": input.dealId }); }
185
+ }
186
+ export async function initializeProfile(config, options) {
187
+ const seam = new Seam(config);
188
+ const version = await seam.call("version", undefined, false);
189
+ if (version.protocol !== SEAM_PROTOCOL || version.packageVersion !== SDK_VERSION)
190
+ throw new SeamUnavailable("installed Supercuts backend is incompatible with this SDK");
191
+ const live = options.mock === true ? {} : { "deployment-config": options.deploymentConfig, "sui-key-file": options.suiKeyFile, "tatum-key-file": options.tatumKeyFile, "write-grpc": options.writeGrpc, "tatum-grpc": options.tatumGrpc, ...(options.snarkjsPath ? { snarkjs: options.snarkjsPath } : {}), ...(options.converterPath ? { converter: options.converterPath } : {}), ...(options.rapidsnarkPath ? { rapidsnark: options.rapidsnarkPath } : {}), ...(options.memoryConfigFile ? { "memory-config-file": options.memoryConfigFile } : {}), ...(options.walrusPublisher ? { "walrus-publisher": options.walrusPublisher } : {}), ...(options.walrusAggregator ? { "walrus-aggregator": options.walrusAggregator } : {}) };
192
+ return seam.call("initialize", { role: options.role, ...(options.mock ? { mock: true } : live), ...(options.mock && options.artifactManifest ? { "artifact-manifest": options.artifactManifest } : {}), ...(options.maxAmount !== undefined ? { "max-amount": options.maxAmount.toString() } : {}), ...(options.allowedCounterparties ? { "allow-counterparty": options.allowedCounterparties.join(",") } : {}), ...(options.requireShielded ? { "require-shielded": true } : {}), ...(options.maxMemoryDistance !== undefined ? { "max-memory-distance": String(options.maxMemoryDistance) } : {}) });
193
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@supercuts-walrus/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Typed, role-scoped TypeScript SDK for Supercuts",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "engines": {
20
+ "node": ">=22.13"
21
+ },
22
+ "dependencies": {
23
+ "@supercuts-walrus/backend": "0.1.0"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^22.10.0",
27
+ "tsx": "^4.19.2",
28
+ "typescript": "^5.7.2"
29
+ },
30
+ "scripts": {
31
+ "build": "tsc -p tsconfig.json",
32
+ "check": "tsc --noEmit -p tsconfig.json",
33
+ "pretest": "pnpm --dir ../.. build",
34
+ "test": "tsx --test test/**/*.test.ts"
35
+ }
6
36
  }