@absol-labs/agent 0.12.0-rc.1 → 0.12.0-rc.2

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.
Files changed (113) hide show
  1. package/README.md +1 -1
  2. package/dist/cli/commands/claim.d.ts +32 -0
  3. package/dist/cli/commands/claim.d.ts.map +1 -1
  4. package/dist/cli/commands/claim.js +115 -27
  5. package/dist/cli/commands/claim.js.map +1 -1
  6. package/dist/cli/commands/pay.d.ts +15 -0
  7. package/dist/cli/commands/pay.d.ts.map +1 -1
  8. package/dist/cli/commands/pay.js +131 -7
  9. package/dist/cli/commands/pay.js.map +1 -1
  10. package/dist/cli/commands/reclaim.d.ts.map +1 -1
  11. package/dist/cli/commands/reclaim.js +20 -4
  12. package/dist/cli/commands/reclaim.js.map +1 -1
  13. package/dist/cli/commands/refund.d.ts +19 -1
  14. package/dist/cli/commands/refund.d.ts.map +1 -1
  15. package/dist/cli/commands/refund.js +200 -27
  16. package/dist/cli/commands/refund.js.map +1 -1
  17. package/dist/cli/commands/status.d.ts.map +1 -1
  18. package/dist/cli/commands/status.js +11 -1
  19. package/dist/cli/commands/status.js.map +1 -1
  20. package/dist/cli/commands/watch.d.ts.map +1 -1
  21. package/dist/cli/commands/watch.js +2 -0
  22. package/dist/cli/commands/watch.js.map +1 -1
  23. package/dist/cli/context.d.ts +19 -0
  24. package/dist/cli/context.d.ts.map +1 -1
  25. package/dist/cli/deps.d.ts +20 -0
  26. package/dist/cli/deps.d.ts.map +1 -1
  27. package/dist/cli/deps.js +14 -0
  28. package/dist/cli/deps.js.map +1 -1
  29. package/dist/cli/progress.d.ts +13 -1
  30. package/dist/cli/progress.d.ts.map +1 -1
  31. package/dist/cli/progress.js +7 -1
  32. package/dist/cli/progress.js.map +1 -1
  33. package/dist/cli/run.d.ts.map +1 -1
  34. package/dist/cli/run.js +26 -14
  35. package/dist/cli/run.js.map +1 -1
  36. package/dist/cli/status.d.ts +103 -0
  37. package/dist/cli/status.d.ts.map +1 -1
  38. package/dist/cli/status.js +310 -41
  39. package/dist/cli/status.js.map +1 -1
  40. package/dist/cli/wallet.d.ts +1 -1
  41. package/dist/cli/wallet.d.ts.map +1 -1
  42. package/dist/cli/wallet.js +28 -4
  43. package/dist/cli/wallet.js.map +1 -1
  44. package/dist/gateway/http-server.d.ts +17 -0
  45. package/dist/gateway/http-server.d.ts.map +1 -1
  46. package/dist/gateway/http-server.js +76 -9
  47. package/dist/gateway/http-server.js.map +1 -1
  48. package/dist/gateway/x402-opener-mode.d.ts +39 -2
  49. package/dist/gateway/x402-opener-mode.d.ts.map +1 -1
  50. package/dist/gateway/x402-opener-mode.js +169 -36
  51. package/dist/gateway/x402-opener-mode.js.map +1 -1
  52. package/dist/mcp/server.d.ts +12 -0
  53. package/dist/mcp/server.d.ts.map +1 -1
  54. package/dist/mcp/server.js +28 -9
  55. package/dist/mcp/server.js.map +1 -1
  56. package/dist/mcp/x402-tools.d.ts +8 -3
  57. package/dist/mcp/x402-tools.d.ts.map +1 -1
  58. package/dist/mcp/x402-tools.js +126 -6
  59. package/dist/mcp/x402-tools.js.map +1 -1
  60. package/dist/sdk/client.d.ts +13 -0
  61. package/dist/sdk/client.d.ts.map +1 -1
  62. package/dist/sdk/client.js +15 -0
  63. package/dist/sdk/client.js.map +1 -1
  64. package/dist/x402-buyer/pay.d.ts +22 -0
  65. package/dist/x402-buyer/pay.d.ts.map +1 -1
  66. package/dist/x402-buyer/pay.js +33 -3
  67. package/dist/x402-buyer/pay.js.map +1 -1
  68. package/dist/x402-opener/facilitator-entry.js +4 -1
  69. package/dist/x402-opener/facilitator-entry.js.map +1 -1
  70. package/dist/x402-opener/facilitator-server.d.ts +29 -0
  71. package/dist/x402-opener/facilitator-server.d.ts.map +1 -1
  72. package/dist/x402-opener/facilitator-server.js +67 -1
  73. package/dist/x402-opener/facilitator-server.js.map +1 -1
  74. package/dist/x402-opener/refund-relay.d.ts +30 -4
  75. package/dist/x402-opener/refund-relay.d.ts.map +1 -1
  76. package/dist/x402-opener/refund-relay.js +123 -22
  77. package/dist/x402-opener/refund-relay.js.map +1 -1
  78. package/dist/x402-opener/scheme.d.ts +79 -0
  79. package/dist/x402-opener/scheme.d.ts.map +1 -1
  80. package/dist/x402-opener/scheme.js +326 -40
  81. package/dist/x402-opener/scheme.js.map +1 -1
  82. package/dist/x402-opener/terms.d.ts +61 -1
  83. package/dist/x402-opener/terms.d.ts.map +1 -1
  84. package/dist/x402-opener/terms.js +94 -2
  85. package/dist/x402-opener/terms.js.map +1 -1
  86. package/docs/cli.md +87 -9
  87. package/docs/mcp-reference.md +18 -2
  88. package/docs/quickstart.md +3 -3
  89. package/docs/x402.md +150 -10
  90. package/package.json +3 -3
  91. package/src/cli/commands/claim.ts +167 -32
  92. package/src/cli/commands/pay.ts +150 -8
  93. package/src/cli/commands/reclaim.ts +25 -5
  94. package/src/cli/commands/refund.ts +231 -33
  95. package/src/cli/commands/status.ts +11 -1
  96. package/src/cli/commands/watch.ts +4 -0
  97. package/src/cli/context.ts +16 -0
  98. package/src/cli/deps.ts +37 -0
  99. package/src/cli/progress.ts +21 -2
  100. package/src/cli/run.ts +26 -13
  101. package/src/cli/status.ts +440 -43
  102. package/src/cli/wallet.ts +44 -7
  103. package/src/gateway/http-server.ts +96 -8
  104. package/src/gateway/x402-opener-mode.ts +234 -37
  105. package/src/mcp/server.ts +43 -11
  106. package/src/mcp/x402-tools.ts +171 -7
  107. package/src/sdk/client.ts +25 -0
  108. package/src/x402-buyer/pay.ts +41 -3
  109. package/src/x402-opener/facilitator-entry.ts +4 -1
  110. package/src/x402-opener/facilitator-server.ts +101 -1
  111. package/src/x402-opener/refund-relay.ts +150 -20
  112. package/src/x402-opener/scheme.ts +459 -41
  113. package/src/x402-opener/terms.ts +155 -2
package/src/cli/status.ts CHANGED
@@ -75,6 +75,155 @@ export function settlementCoverage(
75
75
  };
76
76
  }
77
77
 
78
+ /**
79
+ * How much of the operator's verified, unclaimed accrual the buyer's no-proof
80
+ * escape hatch (`reclaimUnverified`) could take. All amounts are GROSS
81
+ * cumulative USDC base units (before the protocol fee), the unit the escrow
82
+ * settles in; the operator receives a claimed amount net of the fee.
83
+ *
84
+ * The rule depends on the escrow's generation:
85
+ *
86
+ * - **V2**: the hatch settles the operator at `claimedCumulative`, so every
87
+ * verified-but-unclaimed unit is exposed.
88
+ * - **V3**: the hatch settles the operator at
89
+ * `max(claimedCumulative, provenCumulative)` — the on-chain proven high-water
90
+ * the oracle's `recordProven` keeper (or any claim / reclaim with a proof)
91
+ * writes, and which the operator can redeem with `claimProven`. Only verified
92
+ * value NOBODY has proven on-chain is exposed.
93
+ */
94
+ export interface OperatorHatchExposure {
95
+ /** Verified cumulative from the oracle proof, capped at the deposit (gross). */
96
+ readonly verifiedCumulative: bigint;
97
+ /** What the hatch would still settle to the operator (gross). */
98
+ readonly protectedCumulative: bigint;
99
+ /** `max(0, verifiedCumulative − protectedCumulative)` (gross). */
100
+ readonly atRiskCumulative: bigint;
101
+ /**
102
+ * V3 only: whether `provenCumulative` was read. `false` means it was assumed
103
+ * to be zero (worst case for the operator), never assumed to be protective.
104
+ * Always `true` on V2, which has no such view.
105
+ */
106
+ readonly provenCumulativeKnown: boolean;
107
+ }
108
+
109
+ /**
110
+ * The exposure for a stream that has NOT been reclaimed and has a verified
111
+ * proof. Pure, so the per-generation rule is testable without an RPC. Returns
112
+ * `null` when there is nothing to reason about (no proof, or already reclaimed:
113
+ * a reclaimed stream has no hatch left to open).
114
+ */
115
+ export function operatorHatchExposure(
116
+ stream: Pick<StreamV2, "deposit" | "claimedCumulative" | "reclaimed">,
117
+ verifiedCumulative: bigint | null,
118
+ generation: string,
119
+ provenCumulative: bigint | null,
120
+ ): OperatorHatchExposure | null {
121
+ if (stream.reclaimed || verifiedCumulative === null) return null;
122
+ const verified =
123
+ verifiedCumulative > stream.deposit ? stream.deposit : verifiedCumulative;
124
+ let protectedCumulative = stream.claimedCumulative;
125
+ let provenCumulativeKnown = true;
126
+ if (generation === "v3") {
127
+ if (provenCumulative === null) {
128
+ provenCumulativeKnown = false;
129
+ } else if (provenCumulative > protectedCumulative) {
130
+ protectedCumulative = provenCumulative;
131
+ }
132
+ }
133
+ const atRiskCumulative =
134
+ verified > protectedCumulative ? verified - protectedCumulative : 0n;
135
+ return {
136
+ verifiedCumulative: verified,
137
+ protectedCumulative,
138
+ atRiskCumulative,
139
+ provenCumulativeKnown,
140
+ };
141
+ }
142
+
143
+ /**
144
+ * A stream whose buyer side is over, read from chain state. All amounts gross.
145
+ *
146
+ * Two ways to get here:
147
+ *
148
+ * - `reclaimed`: the buyer reclaimed. Read from the stream tuple, which reclaim
149
+ * WRITES, unlike during the stream's active life. The buyer's refund is
150
+ * deliberately absent: reclaim overwrites `deposit` with the operator's
151
+ * entitlement, so `deposit − settled` is NOT the refund, and the true figure
152
+ * lives only in the reclaim's `BuyerReclaimed` event, which this screen does
153
+ * not scan for (the reclaim block is unknown, so the lookup is not bounded).
154
+ * - `deposit-exhausted`: the stream has stopped (closed, or past expiry) and the
155
+ * operator's floor already covers the whole deposit, so there is nothing to
156
+ * reclaim and the buyer never will. Both buyer exits settle the operator at no
157
+ * less than `max(claimedCumulative, provenCumulative)` (V2:
158
+ * `claimedCumulative`) and revert `NothingToReclaim` when `deposit − floor` is
159
+ * zero, so `reclaimed` stays `false` forever on such a stream.
160
+ */
161
+ export interface FinalSettlement {
162
+ readonly finishedBy: "reclaimed" | "deposit-exhausted";
163
+ /**
164
+ * The operator's entitlement: `settledCumulative` (fixed at reclaim), or the
165
+ * whole `deposit` when it was exhausted.
166
+ */
167
+ readonly settledToOperator: bigint;
168
+ /** `claimedCumulative`: what the operator has redeemed so far. */
169
+ readonly operatorClaimed: bigint;
170
+ /** `settledToOperator − operatorClaimed`, still escrowed for the operator. */
171
+ readonly operatorUnclaimed: bigint;
172
+ }
173
+
174
+ /**
175
+ * Whether the buyer side of a stream is finished, and what the operator holds.
176
+ * Pure, so the rule is testable without an RPC.
177
+ *
178
+ * `stopped` is the escrow's own reclaim gate (closed, or `now >= expiresAt`).
179
+ * `provenCumulative` counts only on V3, and only when it was READ: an
180
+ * unreadable high-water is treated as zero, so it can never make a stream look
181
+ * finished that is not.
182
+ */
183
+ export function finalSettlement(
184
+ stream: Pick<
185
+ StreamV2,
186
+ "reclaimed" | "settledCumulative" | "claimedCumulative" | "deposit"
187
+ >,
188
+ exhaustion?: {
189
+ readonly stopped: boolean;
190
+ readonly generation: string;
191
+ readonly provenCumulative: bigint | null;
192
+ },
193
+ ): FinalSettlement | null {
194
+ if (stream.reclaimed) {
195
+ return settled("reclaimed", stream.settledCumulative, stream);
196
+ }
197
+ if (exhaustion === undefined || !exhaustion.stopped) return null;
198
+ if (stream.deposit <= 0n) return null;
199
+ let operatorFloor = stream.claimedCumulative;
200
+ if (
201
+ exhaustion.generation === "v3" &&
202
+ exhaustion.provenCumulative !== null &&
203
+ exhaustion.provenCumulative > operatorFloor
204
+ ) {
205
+ operatorFloor = exhaustion.provenCumulative;
206
+ }
207
+ if (operatorFloor < stream.deposit) return null;
208
+ return settled("deposit-exhausted", stream.deposit, stream);
209
+ }
210
+
211
+ function settled(
212
+ finishedBy: FinalSettlement["finishedBy"],
213
+ settledToOperator: bigint,
214
+ stream: Pick<StreamV2, "claimedCumulative">,
215
+ ): FinalSettlement {
216
+ return {
217
+ finishedBy,
218
+ settledToOperator,
219
+ operatorClaimed: stream.claimedCumulative,
220
+ operatorUnclaimed:
221
+ settledToOperator > stream.claimedCumulative
222
+ ? settledToOperator - stream.claimedCumulative
223
+ : 0n,
224
+ };
225
+ }
226
+
78
227
  /**
79
228
  * A stream as the CLI reports it.
80
229
  *
@@ -92,6 +241,12 @@ export interface StreamReport {
92
241
  /** Why there is no proof yet, when applicable. */
93
242
  readonly proofUnavailable: string | null;
94
243
  readonly claimable: bigint | null;
244
+ /**
245
+ * What {@link claimable} was computed against: the oracle's current proof,
246
+ * or — V3, when the latest checkpoint no longer contains the stream — the
247
+ * on-chain proven high-water, which `claimProven` redeems without a proof.
248
+ */
249
+ readonly claimableSource: "checkpoint-proof" | "proven-on-chain" | null;
95
250
  readonly reclaimable: bigint | null;
96
251
  readonly protocolFeeBps: number | null;
97
252
  /**
@@ -120,6 +275,22 @@ export interface StreamReport {
120
275
  * "no overlap".
121
276
  */
122
277
  readonly attesters: AttesterSet;
278
+ /** The escrow generation this report was read against (`v2` / `v3`). */
279
+ readonly escrowGeneration: string;
280
+ /**
281
+ * V3 only: the on-chain proven high-water (`provenCumulativeOf`). `null` on
282
+ * V2, or when the read failed — see {@link provenUnavailable}.
283
+ */
284
+ readonly provenCumulative: bigint | null;
285
+ /** Why a V3 proven high-water could not be read, when applicable. */
286
+ readonly provenUnavailable: string | null;
287
+ /** See {@link operatorHatchExposure}. `null` when not applicable. */
288
+ readonly operatorExposure: OperatorHatchExposure | null;
289
+ /**
290
+ * See {@link finalSettlement}. Non-null exactly when the buyer side is over:
291
+ * reclaimed, or stopped with the whole deposit already the operator's.
292
+ */
293
+ readonly finalSettlement: FinalSettlement | null;
123
294
  }
124
295
 
125
296
  export async function readStreamReport(
@@ -144,13 +315,38 @@ export async function readStreamReport(
144
315
  proofUnavailable = describeError(error);
145
316
  }
146
317
 
318
+ let provenCumulative: bigint | null = null;
319
+ let provenUnavailable: string | null = null;
320
+ if (escrowGeneration === "v3") {
321
+ if (read.provenCumulativeOf === undefined) {
322
+ provenUnavailable = "this read client cannot read provenCumulativeOf";
323
+ } else {
324
+ try {
325
+ provenCumulative = await read.provenCumulativeOf(streamId);
326
+ } catch (error) {
327
+ provenUnavailable = describeError(error);
328
+ }
329
+ }
330
+ }
331
+
147
332
  let claimable: bigint | null = null;
333
+ let claimableSource: StreamReport["claimableSource"] = null;
148
334
  let reclaimable: bigint | null = null;
149
335
  if (proof !== null) {
150
336
  [claimable, reclaimable] = await Promise.all([
151
337
  read.claimableForV2(streamId, proof.cumulativeAmount),
152
338
  read.reclaimableForV2(streamId, proof.cumulativeAmount),
153
339
  ]);
340
+ claimableSource = "checkpoint-proof";
341
+ } else if (
342
+ provenCumulative !== null &&
343
+ provenCumulative > stream.claimedCumulative
344
+ ) {
345
+ // The latest checkpoint no longer lists the stream, but a value proven
346
+ // against a signed root is recorded on-chain. `claimableFor` at that value
347
+ // is exactly what `claimProven` pays (same `_payableCumulative` and fee).
348
+ claimable = await read.claimableForV2(streamId, provenCumulative);
349
+ claimableSource = "proven-on-chain";
154
350
  }
155
351
 
156
352
  let protocolFeeBps: number | null = null;
@@ -179,11 +375,19 @@ export async function readStreamReport(
179
375
  latestCheckpointCheckedAt = null;
180
376
  }
181
377
 
182
- const settlement = settlementCoverage(
378
+ const coverage = settlementCoverage(
183
379
  stream,
184
380
  latestCheckpointCheckedAt,
185
381
  now.seconds,
186
382
  );
383
+ const final = finalSettlement(stream, {
384
+ stopped: coverage.stopAt !== null,
385
+ generation: escrowGeneration,
386
+ provenCumulative,
387
+ });
388
+ // A finished stream is settled: there is no checkpoint left to wait for.
389
+ const settlement: SettlementCoverage =
390
+ final !== null ? { ...coverage, pending: false } : coverage;
187
391
  const attesters = await readAttesterSet(read);
188
392
 
189
393
  return {
@@ -192,6 +396,7 @@ export async function readStreamReport(
192
396
  proof,
193
397
  proofUnavailable,
194
398
  claimable,
399
+ claimableSource,
195
400
  reclaimable,
196
401
  protocolFeeBps,
197
402
  escapeHatch,
@@ -200,6 +405,20 @@ export async function readStreamReport(
200
405
  clockSource: now.source,
201
406
  settlement,
202
407
  attesters,
408
+ escrowGeneration,
409
+ provenCumulative,
410
+ provenUnavailable,
411
+ // A finished stream has no hatch left that could take anything.
412
+ operatorExposure:
413
+ final !== null
414
+ ? null
415
+ : operatorHatchExposure(
416
+ stream,
417
+ proof === null ? null : proof.cumulativeAmount,
418
+ escrowGeneration,
419
+ provenCumulative,
420
+ ),
421
+ finalSettlement: final,
203
422
  };
204
423
  }
205
424
 
@@ -242,8 +461,21 @@ export function streamReportJson(report: StreamReport): unknown {
242
461
  // settled-looking number derived from a checkpoint that predates the
243
462
  // stream's stop time. The superseded figure is still available, explicitly
244
463
  // labelled, under `settlement.provisionalReclaimable`.
245
- claimable: report.claimable,
246
- reclaimable: report.settlement.pending ? null : report.reclaimable,
464
+ // A finished stream with nothing left for the operator has nothing
465
+ // claimable, even when no proof was fetched.
466
+ claimable:
467
+ report.claimable ??
468
+ (report.finalSettlement?.operatorUnclaimed === 0n ? 0n : null),
469
+ // `checkpoint-proof`, `proven-on-chain` (V3: what `claimProven` pays), or
470
+ // `null` when `claimable` is.
471
+ claimableSource: report.claimableSource,
472
+ // Nothing is reclaimable from a stream whose buyer side is finished.
473
+ reclaimable:
474
+ report.finalSettlement !== null
475
+ ? 0n
476
+ : report.settlement.pending
477
+ ? null
478
+ : report.reclaimable,
247
479
  settlement: {
248
480
  pending: report.settlement.pending,
249
481
  stopAt: report.settlement.stopAt,
@@ -271,6 +503,39 @@ export function streamReportJson(report: StreamReport): unknown {
271
503
  ready: report.escapeHatch.ready,
272
504
  secondsUntilReady: report.escapeHatch.secondsRemaining,
273
505
  },
506
+ escrowGeneration: report.escrowGeneration,
507
+ // V3 only; `null` on V2 or when unreadable (`provenCumulativeUnavailable`).
508
+ provenCumulative: report.provenCumulative,
509
+ provenCumulativeUnavailable: report.provenUnavailable,
510
+ // True once nothing more is owed to, or can be reclaimed by, the buyer —
511
+ // reclaimed, or stopped with the whole deposit already the operator's —
512
+ // and the escape hatch no longer applies.
513
+ buyerSideFinished: report.finalSettlement !== null,
514
+ // Non-null exactly when `buyerSideFinished`. Gross base units. The buyer's
515
+ // refund is not included: see `FinalSettlement`.
516
+ finalSettlement:
517
+ report.finalSettlement === null
518
+ ? null
519
+ : {
520
+ finishedBy: report.finalSettlement.finishedBy,
521
+ settledToOperator: report.finalSettlement.settledToOperator,
522
+ operatorClaimed: report.finalSettlement.operatorClaimed,
523
+ operatorUnclaimed: report.finalSettlement.operatorUnclaimed,
524
+ },
525
+ // What the buyer's no-proof escape hatch could take from the operator.
526
+ // `null` once reclaimed or before any proof. Gross base units.
527
+ operatorHatchExposure:
528
+ report.operatorExposure === null
529
+ ? null
530
+ : {
531
+ units: "gross",
532
+ verifiedCumulative: report.operatorExposure.verifiedCumulative,
533
+ protectedCumulative: report.operatorExposure.protectedCumulative,
534
+ atRiskCumulative: report.operatorExposure.atRiskCumulative,
535
+ protectedOnChain: report.operatorExposure.atRiskCumulative === 0n,
536
+ provenCumulativeKnown:
537
+ report.operatorExposure.provenCumulativeKnown,
538
+ },
274
539
  };
275
540
  }
276
541
 
@@ -279,10 +544,7 @@ export function streamReportRows(
279
544
  ): (readonly [string, string])[] {
280
545
  const { stream, proof } = report;
281
546
  const rows: (readonly [string, string])[] = [
282
- [
283
- "status",
284
- stream.reclaimed ? `${stream.status} (reclaimed)` : stream.status,
285
- ],
547
+ ["status", describeStatus(report)],
286
548
  ...(stream.opener === null || stream.opener === undefined
287
549
  ? ([["buyer", stream.buyer]] as const)
288
550
  : ([
@@ -291,7 +553,15 @@ export function streamReportRows(
291
553
  ] as const)),
292
554
  ["operator", stream.operator],
293
555
  ["serviceRef", stream.serviceRef],
294
- ["deposit", formatUsdc(stream.deposit)],
556
+ // Reclaim OVERWRITES `deposit` with the operator's entitlement, so after a
557
+ // reclaim the field is what is still escrowed for the operator — not what
558
+ // the buyer put in. Printing it bare would read as "the buyer deposited 0".
559
+ [
560
+ "deposit",
561
+ stream.reclaimed
562
+ ? `${formatUsdc(stream.deposit)} still escrowed for the operator (reclaim replaces the original deposit with the operator's entitlement)`
563
+ : formatUsdc(stream.deposit),
564
+ ],
295
565
  ["rate", `${formatUsdc(stream.ratePerSecond)} / second`],
296
566
  ["opened", formatTimestamp(stream.openedAt)],
297
567
  ["expires", describeDeadline(stream.expiresAt, report.nowSeconds)],
@@ -299,12 +569,12 @@ export function streamReportRows(
299
569
  if (stream.closedAt > 0) {
300
570
  rows.push(["closed", formatTimestamp(stream.closedAt)]);
301
571
  }
302
- rows.push([
303
- "verified accrual",
304
- proof === null
305
- ? `not checkpointed yet (${report.proofUnavailable ?? "no proof"})`
306
- : `${formatUsdc(proof.cumulativeAmount)} @ checkpoint ${proof.checkpointId} (${formatTimestamp(Number(proof.checkedAt))})`,
307
- ]);
572
+ if (report.finalSettlement !== null) {
573
+ rows.push(...finalSettlementRows(report, report.finalSettlement));
574
+ pushTrailingRows(rows, report);
575
+ return rows;
576
+ }
577
+ rows.push(["verified accrual", describeVerifiedAccrual(report)]);
308
578
  // `claim` accepts ANY retained root, so the operator's balance is obtainable
309
579
  // now — it is merely not FINAL until the covering checkpoint lands, and it
310
580
  // can only grow. `reclaim` requires the LATEST root to reach the stop time,
@@ -314,9 +584,11 @@ export function streamReportRows(
314
584
  "operator claimable",
315
585
  report.claimable === null
316
586
  ? "-"
317
- : report.settlement.pending
318
- ? `${formatUsdc(report.claimable)} so far — not final until the checkpoint covering the stop time lands`
319
- : formatUsdc(report.claimable),
587
+ : report.claimableSource === "proven-on-chain"
588
+ ? `${formatUsdc(report.claimable)} (net of the protocol fee) — from the on-chain proven high-water; \`metrik claim\` redeems it with claimProven, no fresh proof needed`
589
+ : report.settlement.pending
590
+ ? `${formatUsdc(report.claimable)} so far (net of the protocol fee) — not final until the checkpoint covering the stop time lands`
591
+ : `${formatUsdc(report.claimable)} (net of the protocol fee)`,
320
592
  ]);
321
593
  rows.push([
322
594
  "buyer reclaimable",
@@ -326,48 +598,173 @@ export function streamReportRows(
326
598
  ? "-"
327
599
  : formatUsdc(report.reclaimable),
328
600
  ]);
601
+ if (report.escrowGeneration === "v3") {
602
+ rows.push([
603
+ "proven on-chain",
604
+ report.provenCumulative === null
605
+ ? `unknown (${report.provenUnavailable ?? "not read"})`
606
+ : `${formatUsdc(report.provenCumulative)} gross (the escrow's proven high-water; the escape hatch cannot take it)`,
607
+ ]);
608
+ }
329
609
  rows.push(["fees paid", formatUsdc(stream.feesPaid)]);
330
- rows.push([
331
- "oracle checkpoint",
332
- report.latestCheckpointCheckedAt === null
333
- ? "-"
334
- : report.latestCheckpointCheckedAt <= 0
335
- ? "none posted yet"
336
- : `latest covers up to ${formatTimestamp(report.latestCheckpointCheckedAt)}`,
337
- ]);
338
- // The no-proof path. Printed for every stream, not only blocked ones: a buyer
339
- // should learn that this exists before they need it.
610
+ rows.push(oracleCheckpointRow(report));
611
+ // The no-proof path. Printed for every live stream, not only blocked ones: a
612
+ // buyer should learn that this exists before they need it.
340
613
  rows.push([
341
614
  "escape hatch",
342
615
  report.escapeHatch === null
343
616
  ? "-"
344
- : `${describeEscapeHatch(report.escapeHatch)} — no-proof reclaim, forfeits the operator's unclaimed earnings`,
617
+ : `${describeEscapeHatch(report.escapeHatch)} — ${
618
+ report.escrowGeneration === "v3"
619
+ ? "no-proof reclaim, refunds only value not proven on-chain; the operator keeps max(claimed, proven high-water)"
620
+ : "no-proof reclaim, forfeits the operator's unclaimed earnings"
621
+ }`,
345
622
  ]);
346
- // The same row, read from the seller's side. `reclaimUnverified` pays the
347
- // buyer the WHOLE remaining deposit with no proof, so an operator who has
348
- // earned but not claimed loses it the moment that window opens. The window is
349
- // `expiresAt + escapeGraceSeconds` and the grace is immutable on the live
350
- // escrow, so the only thing an operator can do about it is claim in time —
351
- // which they cannot do if nothing tells them the deadline exists.
352
- if (
353
- report.escapeHatch !== null &&
354
- report.claimable !== null &&
355
- report.claimable > 0n
356
- ) {
357
- rows.push([
623
+ const operatorRow = operatorExposureRow(report);
624
+ if (operatorRow !== null) rows.push(operatorRow);
625
+ pushTrailingRows(rows, report);
626
+ return rows;
627
+ }
628
+
629
+ /**
630
+ * The same escape-hatch row, read from the seller's side.
631
+ *
632
+ * V2: `reclaimUnverified` settles the operator at `claimedCumulative`, so an
633
+ * operator who has earned but not claimed loses all of it the moment the
634
+ * window opens. The window is fixed and the grace immutable, so the only thing
635
+ * an operator can do about it is claim in time — which they cannot do if
636
+ * nothing tells them the deadline exists.
637
+ *
638
+ * V3: the hatch settles the operator at `max(claimed, provenCumulative)`, so
639
+ * only verified value nobody proved on-chain is exposed. Warning about the
640
+ * WHOLE unclaimed balance there would be false — and would push an operator to
641
+ * spend gas racing a deadline that cannot hurt them.
642
+ */
643
+ function operatorExposureRow(
644
+ report: StreamReport,
645
+ ): readonly [string, string] | null {
646
+ const hatch = report.escapeHatch;
647
+ if (hatch === null || report.claimable === null || report.claimable <= 0n) {
648
+ return null;
649
+ }
650
+ if (report.escrowGeneration !== "v3") {
651
+ return [
358
652
  "operator deadline",
359
- report.escapeHatch.ready
653
+ hatch.ready
360
654
  ? `${formatUsdc(report.claimable)} is unclaimed and the buyer's no-proof reclaim is ALREADY open — it would take this amount from the operator`
361
- : `${formatUsdc(report.claimable)} is unclaimed; \`metrik claim\` it before ${formatTimestamp(report.escapeHatch.readyAt)}, after which a buyer's no-proof reclaim can take it`,
655
+ : `${formatUsdc(report.claimable)} is unclaimed; \`metrik claim\` it before ${formatTimestamp(hatch.readyAt)}, after which a buyer's no-proof reclaim can take it`,
656
+ ];
657
+ }
658
+ const exposure = report.operatorExposure;
659
+ if (exposure === null) return null;
660
+ const units = `(gross: before the protocol fee; \`metrik claim\` pays the operator net of it — ${formatUsdc(report.claimable)} net unclaimed)`;
661
+ if (exposure.atRiskCumulative === 0n) {
662
+ return [
663
+ "operator earnings",
664
+ `${formatUsdc(exposure.verifiedCumulative)} gross verified, all protected on-chain by the proven high-water — a buyer's no-proof reclaim cannot take it, so it can be claimed at any time with \`metrik claim\` ${units}`,
665
+ ];
666
+ }
667
+ const protectedPart = exposure.provenCumulativeKnown
668
+ ? `${formatUsdc(exposure.protectedCumulative)} gross is protected on-chain (claimed or proven high-water)`
669
+ : "the on-chain proven high-water could not be read, so this assumes none of the unclaimed balance is protected";
670
+ return [
671
+ "operator deadline",
672
+ hatch.ready
673
+ ? `${formatUsdc(exposure.atRiskCumulative)} gross of verified accrual is not proven on-chain and the buyer's no-proof reclaim is ALREADY open — it would refund that part to the buyer. ${protectedPart}. ${units}`
674
+ : `${formatUsdc(exposure.atRiskCumulative)} gross of verified accrual is not proven on-chain; \`metrik claim\` it before ${formatTimestamp(hatch.readyAt)}, after which a buyer's no-proof reclaim refunds that part to the buyer. ${protectedPart}. ${units}`,
675
+ ];
676
+ }
677
+
678
+ /**
679
+ * A reclaimed stream, from the state reclaim WROTE. The buyer side is over:
680
+ * no checkpoint to wait for, nothing reclaimable, and no escape hatch left to
681
+ * open (`reclaimUnverified` reverts `AlreadyReclaimed`). So none of those are
682
+ * printed as live items — only what the operator is still owed.
683
+ */
684
+ function finalSettlementRows(
685
+ report: StreamReport,
686
+ settlement: FinalSettlement,
687
+ ): (readonly [string, string])[] {
688
+ const refundTo = report.stream.payer ?? report.stream.buyer;
689
+ const exhausted = settlement.finishedBy === "deposit-exhausted";
690
+ const rows: (readonly [string, string])[] = [
691
+ [
692
+ "buyer side",
693
+ exhausted
694
+ ? `finished — the operator's claimed${report.escrowGeneration === "v3" ? " or proven" : ""} amount already covers the whole deposit, so there is nothing to reclaim (the escrow would revert NothingToReclaim) and the buyer never reclaimed. Nothing more is owed to, or reclaimable by, the buyer.`
695
+ : `finished — the buyer has reclaimed, and the refund was paid to ${refundTo}. Nothing more is owed to, or reclaimable by, the buyer.`,
696
+ ],
697
+ [
698
+ "settled to operator",
699
+ `${formatUsdc(settlement.settledToOperator)} gross (${exhausted ? "the whole deposit" : "fixed at reclaim"})`,
700
+ ],
701
+ ["operator claimed", `${formatUsdc(settlement.operatorClaimed)} gross`],
702
+ [
703
+ "operator unclaimed",
704
+ settlement.operatorUnclaimed === 0n
705
+ ? "none — fully settled"
706
+ : `${formatUsdc(settlement.operatorUnclaimed)} gross, reserved for the operator — the buyer side is finished, so nothing can take it; \`metrik claim\` it at any time (paid net of the protocol fee)`,
707
+ ],
708
+ ];
709
+ if (exhausted && report.provenCumulative !== null) {
710
+ rows.push([
711
+ "proven on-chain",
712
+ `${formatUsdc(report.provenCumulative)} gross (the escrow's proven high-water)`,
362
713
  ]);
363
714
  }
715
+ rows.push(["fees paid", formatUsdc(report.stream.feesPaid)]);
716
+ return rows;
717
+ }
718
+
719
+ function describeStatus(report: StreamReport): string {
720
+ const { stream } = report;
721
+ const final = report.finalSettlement;
722
+ if (final === null) return stream.status;
723
+ if (final.finishedBy === "reclaimed") return `${stream.status} (reclaimed)`;
724
+ const stop = stream.closedAt > 0 ? "closed" : "expired";
725
+ return final.operatorUnclaimed === 0n
726
+ ? `${stream.status} (${stop}, fully settled)`
727
+ : `${stream.status} (${stop}, buyer side finished)`;
728
+ }
729
+
730
+ /**
731
+ * The verified-accrual row. With no current proof on V3, a non-zero proven
732
+ * high-water IS verified accrual — proven against a signed checkpoint root and
733
+ * recorded on-chain — so it is stated rather than "not checkpointed yet", which
734
+ * reads as "nothing verified".
735
+ */
736
+ function describeVerifiedAccrual(report: StreamReport): string {
737
+ const { proof } = report;
738
+ if (proof !== null) {
739
+ return `${formatUsdc(proof.cumulativeAmount)} gross @ checkpoint ${proof.checkpointId} (${formatTimestamp(Number(proof.checkedAt))})`;
740
+ }
741
+ if (report.provenCumulative !== null && report.provenCumulative > 0n) {
742
+ return `${formatUsdc(report.provenCumulative)} gross proven on-chain (provenCumulativeOf) — the latest checkpoint does not contain this stream (${report.proofUnavailable ?? "no proof"}), so this is read from the escrow`;
743
+ }
744
+ return `not checkpointed yet (${report.proofUnavailable ?? "no proof"})`;
745
+ }
746
+
747
+ function oracleCheckpointRow(report: StreamReport): readonly [string, string] {
748
+ return [
749
+ "oracle checkpoint",
750
+ report.latestCheckpointCheckedAt === null
751
+ ? "-"
752
+ : report.latestCheckpointCheckedAt <= 0
753
+ ? "none posted yet"
754
+ : `latest covers up to ${formatTimestamp(report.latestCheckpointCheckedAt)}`,
755
+ ];
756
+ }
757
+
758
+ function pushTrailingRows(
759
+ rows: (readonly [string, string])[],
760
+ report: StreamReport,
761
+ ): void {
364
762
  if (report.protocolFeeBps !== null) {
365
763
  rows.push([
366
764
  "protocol fee",
367
765
  `${report.protocolFeeBps} bps (read from the escrow)`,
368
766
  ]);
369
767
  }
370
- return rows;
371
768
  }
372
769
 
373
770
  /**
package/src/cli/wallet.ts CHANGED
@@ -76,12 +76,25 @@ export {
76
76
  * signs an EIP-712 invocation capability and broadcasts NOTHING; telling its
77
77
  * caller "this command signs a transaction" was simply false.
78
78
  */
79
- export type KeyPurpose = "transaction" | "capability";
79
+ export type KeyPurpose =
80
+ | "transaction"
81
+ | "capability"
82
+ | "payer-close"
83
+ | "x402-payment";
80
84
 
81
85
  const PURPOSE_TEXT: Record<KeyPurpose, string> = {
82
86
  transaction: "signs a transaction",
83
87
  capability:
84
88
  "signs an off-chain EIP-712 invocation capability (no transaction is broadcast)",
89
+ // `metrik refund --close`: the x402 payer signs the opener's EIP-712 `Close`
90
+ // message and the relay broadcasts it, paying the gas. It is NOT an
91
+ // invocation capability, and the key needs no funds at all.
92
+ "payer-close":
93
+ "signs the payer's off-chain EIP-712 Close message (the refund relay broadcasts it and pays the gas)",
94
+ // `metrik pay`: the payer signs an EIP-3009 TransferWithAuthorization and the
95
+ // seller's facilitator settles it. The payer broadcasts nothing.
96
+ "x402-payment":
97
+ "signs an EIP-3009 USDC authorization that the seller's facilitator settles (the payer broadcasts no transaction and needs no gas)",
85
98
  };
86
99
 
87
100
  /** Which environment configured the signer, for output and for error text. */
@@ -122,10 +135,33 @@ export interface CliWallet {
122
135
  readonly readSpendPolicy?: () => Promise<PrivySpendPolicy>;
123
136
  }
124
137
 
125
- const WALLET_HINT =
126
- `export ${PRIVATE_KEY_ENV}=0x… (a funded testnet key), configure a Coinbase CDP wallet with ` +
127
- `${CDP_ENV_VARS.join(", ")}, or configure a Privy wallet with ${PRIVY_WALLET_KEY_ENV} (agent-owned) or ` +
128
- `${PRIVY_SESSION_ENV_VARS.join(", ")} (broker session). All are read from the environment only — never pass a credential as a command-line flag.`;
138
+ const ENV_ONLY =
139
+ "All are read from the environment only — never pass a credential as a command-line flag.";
140
+
141
+ /**
142
+ * How to configure the wallet a purpose needs. "Funded" is said only where a
143
+ * transaction is broadcast: an off-chain signature costs nothing, and telling
144
+ * someone to fund a key for one sends them to a faucet for no reason.
145
+ */
146
+ function walletHint(purpose: KeyPurpose): string {
147
+ if (purpose === "x402-payment") {
148
+ return (
149
+ `export ${PRIVATE_KEY_ENV}=0x… (a testnet key holding USDC; no ETH needed), or configure a Coinbase CDP wallet with ` +
150
+ `${CDP_ENV_VARS.join(", ")}. A Privy wallet cannot pay x402: its broker does not sign EIP-3009. ${ENV_ONLY}`
151
+ );
152
+ }
153
+ if (purpose === "payer-close") {
154
+ return (
155
+ `export ${PRIVATE_KEY_ENV}=0x… (the key that paid; it needs no ETH or USDC), or configure the paying Coinbase CDP wallet with ` +
156
+ `${CDP_ENV_VARS.join(", ")}. A Privy wallet cannot sign the Close. ${ENV_ONLY}`
157
+ );
158
+ }
159
+ return (
160
+ `export ${PRIVATE_KEY_ENV}=0x… (${purpose === "transaction" ? "a funded testnet key" : "a testnet key; it needs no funds for this"}), configure a Coinbase CDP wallet with ` +
161
+ `${CDP_ENV_VARS.join(", ")}, or configure a Privy wallet with ${PRIVY_WALLET_KEY_ENV} (agent-owned) or ` +
162
+ `${PRIVY_SESSION_ENV_VARS.join(", ")} (broker session). ${ENV_ONLY}`
163
+ );
164
+ }
129
165
 
130
166
  export interface ResolveCliWalletOptions {
131
167
  readonly purpose?: KeyPurpose;
@@ -159,9 +195,10 @@ export async function resolveCliWallet(
159
195
  ): Promise<CliWallet> {
160
196
  const wallet = await optionalCliWallet(env, options);
161
197
  if (wallet === null) {
198
+ const purpose = options.purpose ?? "transaction";
162
199
  throw configError(
163
- `this command ${PURPOSE_TEXT[options.purpose ?? "transaction"]} and needs a wallet: none of ${PRIVATE_KEY_ENV}, the CDP variables or the Privy variables are set`,
164
- WALLET_HINT,
200
+ `this command ${PURPOSE_TEXT[purpose]} and needs a wallet: none of ${PRIVATE_KEY_ENV}, the CDP variables or the Privy variables are set`,
201
+ walletHint(purpose),
165
202
  );
166
203
  }
167
204
  return wallet;