@dvmkit/dvm-cli 0.6.0 → 0.7.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 (51) hide show
  1. package/dist/{_esm-MN4BUYV6.js → _esm-KJAA4KAJ.js} +7 -7
  2. package/dist/{actions-LR65XILR.js → actions-J7VGYDBF.js} +4 -4
  3. package/dist/{ccip-JXYJSXTW.js → ccip-CJFG4PLA.js} +1 -1
  4. package/dist/{chains-LJ7XK6H3.js → chains-J6VIUNUB.js} +4 -4
  5. package/dist/{chunk-MJ4X4BEW.js → chunk-6LP4EGKA.js} +61 -61
  6. package/dist/chunk-6QHVPJNX.js +122 -0
  7. package/dist/chunk-7UAQTHNP.js +77 -0
  8. package/dist/{chunk-BECPI5H5.js → chunk-B4WHUMZM.js} +36 -36
  9. package/dist/{chunk-CJTE5TS3.js → chunk-ESOJUXVY.js} +5 -5
  10. package/dist/{chunk-F55NNH2F.js → chunk-FOWQ7R7S.js} +16 -16
  11. package/dist/{chunk-ID5G54HJ.js → chunk-FPWP4S5S.js} +5 -3
  12. package/dist/{chunk-EE2MREOM.js → chunk-IQV4KG63.js} +5 -3
  13. package/dist/{chunk-R55XNXAR.js → chunk-IUTVV6N5.js} +3 -3
  14. package/dist/{chunk-Z4CZUMUT.js → chunk-JBU7RKQ3.js} +15 -15
  15. package/dist/{chunk-SHZMNEXE.js → chunk-JTMBSEZO.js} +2770 -926
  16. package/dist/{chunk-ERJFRCJO.js → chunk-KDNFUDOG.js} +5 -5
  17. package/dist/chunk-PG7MEKJI.js +43 -0
  18. package/dist/{chunk-WTM2EICO.js → chunk-PUOXBKY2.js} +3 -3
  19. package/dist/{chunk-GZWKCIYN.js → chunk-QXMKABL7.js} +3 -3
  20. package/dist/chunk-R2DSAZBO.js +87 -0
  21. package/dist/chunk-RQYMWLX4.js +409 -0
  22. package/dist/{chunk-FL2ICZW5.js → chunk-SYFKO6BA.js} +3 -3
  23. package/dist/{chunk-LH3QPVN6.js → chunk-TAZWRWM4.js} +8060 -8058
  24. package/dist/chunk-U3YRNLZ5.js +262 -0
  25. package/dist/{chunk-QICJRKB7.js → chunk-VIYUB3XT.js} +11035 -12471
  26. package/dist/chunk-VLZ2K7JL.js +5460 -0
  27. package/dist/{chunk-TZWZTS37.js → chunk-WN5R367B.js} +57 -83
  28. package/dist/{chunk-EZHT2RLJ.js → chunk-X7SEGALJ.js} +3 -3
  29. package/dist/{chunk-XHOFQ3OS.js → chunk-Y3SQD37C.js} +9 -9
  30. package/dist/chunk-ZXVOMXT4.js +765 -0
  31. package/dist/{client-RYDA62DU.js → client-6IHIUB6J.js} +10 -10
  32. package/dist/client-IDO4IAXG.js +36 -0
  33. package/dist/{dist-GKCEIY2A.js → dist-23E7OOCA.js} +9 -9
  34. package/dist/dvm.js +2428 -568
  35. package/dist/{internal-INUTGTXQ.js → internal-7FXJTFBU.js} +325 -508
  36. package/dist/lifecycle-LRS3IBQL.js +36 -0
  37. package/dist/{payout-reporter-3Y2U55ZX-CMKACKA3.js → payout-reporter-WT7XYW42-U2QPDIYC.js} +3 -2
  38. package/dist/{pocket-refill-K5T4LZF6.js → pocket-refill-J5OWRBXH.js} +33 -30
  39. package/dist/{revenue-reporter-MAERPYGK-CCPZXGFA.js → revenue-reporter-7UR3W2SD-C5OMRGK3.js} +3 -2
  40. package/dist/{tempo-AXTE4ZEA.js → tempo-ORFVGUKP.js} +10 -10
  41. package/dist/tempo-lifecycle-HS2NIFKT.js +38 -0
  42. package/dist/tempo-wallet-BA2LKR45.js +43 -0
  43. package/dist/wallet-RPPUCQUR.js +45 -0
  44. package/dist/{x402-R6HPBY5D-VMSW7Z32.js → x402-ZU4GML7Z-RYEACIIT.js} +4 -19
  45. package/package.json +4 -2
  46. package/dist/chunk-3YE43JJR.js +0 -215
  47. package/dist/chunk-4KINCBHL.js +0 -5153
  48. package/dist/chunk-FSYEZERJ.js +0 -1667
  49. package/dist/chunk-VOO5IAK7.js +0 -2318
  50. package/dist/tempo-lifecycle-ZBBLFBMH-HWI4PLYP.js +0 -32
  51. package/dist/tempo-wallet-B5XXV3YH-SRQBMYFV.js +0 -41
package/dist/dvm.js CHANGED
@@ -2,77 +2,35 @@
2
2
  import { createRequire as __dvmCreateRequire } from "node:module";
3
3
  const require = __dvmCreateRequire(import.meta.url);
4
4
  import {
5
- BATCH_SETTLEMENT_ADDRESS,
6
- CAPABILITY_NAME_RE,
7
- CREDIT_DRAIN_RAILS,
8
- CREDIT_FUNDING_MODES,
9
- CREDIT_FUND_RAILS,
10
- DEFAULT_AGENT_MINT_URL,
5
+ assertTempoWalletIdle,
6
+ findSigningIdentityByPubkey,
7
+ resolveSigningIdentity
8
+ } from "./chunk-U3YRNLZ5.js";
9
+ import {
10
+ assertX402WalletIdle
11
+ } from "./chunk-PG7MEKJI.js";
12
+ import {
11
13
  DEFAULT_CREDIT_POSTURE,
12
14
  DEFAULT_RESERVE_LOCKTIME_SECONDS,
13
- FX_CACHE_TTL_MS,
14
- FxRateUnavailableError,
15
15
  NWC_FUNDING_FLOAT_ROLE,
16
- PRIVKEY_HEX_RE,
17
- PersistentCounterSource,
18
- RESUME_MAX_AGE_MS,
19
- RESUME_MAX_ATTEMPTS,
20
- ROUTER_FEEDBACK_CLAIM_HEADER,
21
- SIGNED_REQUEST_AUTH_ID,
22
- WALLET_VERSION,
23
- X402_BATCH_CHANNEL_ABI,
24
16
  abandonPendingSubmission,
25
- abool,
26
- abytes,
27
17
  addPayment,
28
- aexists,
29
- amountBoundsVerdict,
30
- anumber,
31
- aoutput,
32
- asProviderText,
33
- asProviderTextOpt,
34
- assertAgentMnemonicReplaceable,
35
18
  assertFloatBudget,
36
- assertNutSupport,
37
- assertX402ChannelPayer,
38
- assertX402WalletIdle,
39
- attestedDvmIdentity,
40
- authenticatedBuilderPubkey,
41
19
  automaticCreditBoundRail,
42
20
  availableRails,
43
21
  backfillTrustAnchor,
44
- base64,
45
- buildDisplayMintInventory,
46
22
  buildTempoCredential,
47
- canonicalRequestPath,
48
23
  captureFundingReceipt,
49
24
  captureTransportReceipt,
50
- cashOutFromMint,
51
- checkMintHealth,
52
- checkOpts,
53
- clean,
54
25
  commitAgentSpend,
55
- copyBytes,
56
26
  correctPendingFundAmount,
57
- coveringMintsForSpend,
58
- createFxFetcher,
59
- deleteAgentMnemonic,
60
- deriveAgentMasterKeypair,
61
- derivePubkeyFromPrivkey,
62
27
  describeMintBounds,
63
28
  drainReceiptsDisplay,
64
29
  drainReceiptsHint,
65
30
  effectiveCreditPosture,
66
- effectiveFundingMint,
67
31
  effectiveFundingRail,
68
- effectiveMints,
69
32
  enforceGlobalBudget,
70
- entryKind,
71
33
  epochMsToIso,
72
- equalBytes,
73
- expand,
74
- external_exports,
75
- extract,
76
34
  extractBuilderHandle,
77
35
  fetchMissingJobReceipt,
78
36
  fetchTrustAnchor,
@@ -82,242 +40,278 @@ import {
82
40
  formatLocktime,
83
41
  fundAgentWallet,
84
42
  fundCredit,
85
- fundWireAmountMicro,
86
- fxRateFor,
87
- generateAgentMnemonic,
88
- generateSecretKey,
89
- getBalanceByMint,
90
- getOutput,
91
- getPublicKey,
92
- getWallet,
93
- isArtifactMessage,
94
- isCancelMessage,
95
- isCompleteMessage,
96
- isCreditFundRail,
97
- isCreditFundingMode,
98
- isPublicRequestId,
99
- isResumable,
100
- isStablecoinFundRail,
101
- la,
102
- loadAgentWallet,
43
+ fundTimeoutMs,
44
+ inFlightTimeoutSeconds,
103
45
  loadAllJobs,
104
- loadConfiguredMints,
105
46
  loadFloat,
106
47
  loadJob,
107
48
  loadLedger,
108
- loadReceipt,
109
- loadReceipts,
110
- looksLikeMnemonic,
111
49
  markJobTerminal,
112
- microToSats,
113
- mnemonicFingerprint,
114
- msatsToMicro,
50
+ markProofsInFlight,
51
+ meltInFlightTimeoutSeconds,
115
52
  needsTopup,
116
- normalizeFeedbackEndpointHost,
117
- offersX402CreditFunding,
118
53
  parseLocktime,
119
- parseNwcUri,
120
54
  parseStatedBudget,
121
- parseTraceparent,
122
55
  payViaFloat,
123
56
  pickCreditFundRail,
124
57
  planCreditForQuote,
125
58
  planProbeDraw,
126
59
  pollPendingCreditFundings,
60
+ pollUntilPaidOrTimeout,
127
61
  prepareAgentSpend,
128
62
  probeFloat,
129
- probeWallets,
130
- providerTextToString,
131
- readFundValuation,
132
- readX402ChannelOnChain,
63
+ proofKey,
133
64
  receiptDisplay,
134
65
  receiptFailureDetail,
135
66
  receiptHint,
136
67
  receiptIssuedAtIso,
137
68
  receiptJsonFields,
138
69
  receiptTrustFields,
139
- receiveToAgentWallet,
140
- reclaimAtMs,
141
- reconcileRefusedX402Deposits,
142
70
  recordFloatSpend,
143
71
  recordSpend,
144
- recoverPendingSubmission,
145
- refundX402BatchChannel,
146
- releaseAgentReserve,
147
72
  renderReceiptHuman,
148
73
  replayStoredReceipt,
149
- reserveAgentWallet,
74
+ reservedForMarker,
150
75
  resolveFundMint,
151
- resolveX402ChannelRpc,
152
- sa,
153
- saveAgentWallet,
76
+ revertInFlight,
154
77
  saveJob,
155
78
  saveLedger,
156
- signDvmRequestData,
157
- signRequestData,
158
- signedRequestDomain,
159
- sn,
160
- spendableAt,
161
79
  statusSnapshot,
162
- sweepPendingMelts,
163
80
  sweepPendingMints,
164
- sweepPendingSubmissions,
165
81
  sweepStaleInFlight,
166
- tempoCredentialAmountMicro,
167
82
  tierCapOverrides,
168
- toAgentProof,
169
83
  toFloatError,
170
84
  trustLadderFor,
171
85
  trustOverrideCapMicro,
172
- u32,
173
- u64Lengths,
174
86
  unrecordedFloatBudgetWarning,
175
- unsignRequestData,
176
- updateJob,
177
- validateAgentMnemonic,
178
- validateLnAddress,
179
- verifyDrainReceiptChain,
180
- verifyEvent,
181
- verifyJobReceipt,
182
- walletExists,
183
- weakestReceiptVerdict,
184
- windowStart,
185
- withWalletLock,
186
- wrapCipher,
187
- writeAgentMnemonic,
188
- x402ChannelControlledBy,
189
- x402ChannelReservation,
190
- x402CreditChannelNetworks,
191
- x402CreditExactNetworks,
192
- x402FlavourForInstrument,
193
- x402RequiredFromError,
194
- x402ReservationRelease
195
- } from "./chunk-QICJRKB7.js";
196
- import "./chunk-EE2MREOM.js";
197
- import "./chunk-ID5G54HJ.js";
198
- import "./chunk-TZWZTS37.js";
87
+ updateJob
88
+ } from "./chunk-VLZ2K7JL.js";
199
89
  import {
200
- DvmX402ChannelStorage,
201
- X402_BATCH_SETTLEMENT_SCHEME,
202
- X402_DEFAULT_NETWORK,
203
- X402_V1_VERSION,
204
- X402_VERSION,
205
90
  assertSupportedX402Network,
206
- chainIdFromCaip2,
207
- clearPendingX402Funding,
208
91
  connectedX402Payer,
209
- decodePaymentRequiredHeader,
210
- ensureAddress,
211
- findX402Channel,
212
- generateX402PrivateKey,
92
+ loadX402Wallet,
93
+ removeX402Wallet,
94
+ repinX402WalletNetwork,
95
+ saveX402Wallet,
96
+ x402NetworkLabel
97
+ } from "./chunk-6QHVPJNX.js";
98
+ import {
99
+ assertValidBudget,
100
+ costAnchor,
101
+ formatAmount,
102
+ formatAmountBestEffort,
103
+ formatPaymentAmount,
213
104
  getOutputTraceId,
214
105
  info,
215
106
  json,
216
- listPendingX402Fundings,
217
- listPendingX402FundingsForChannel,
218
- listResumableX402ExactFundings,
219
- listResumableX402Fundings,
220
- listX402Channels,
221
- loadX402Wallet,
107
+ monetaryJson,
108
+ parseBudget,
222
109
  raw,
223
- removeX402Wallet,
224
- repinX402WalletNetwork,
225
110
  resolveBtcUsdRate,
226
- resolveX402Asset,
227
- saveX402Wallet,
228
111
  setOutputTraceId,
229
112
  staleRateNotice,
230
113
  tryResolveBtcUsdRate,
231
- tryX402Payment,
232
- withX402ChannelLock,
233
- x402NetworkByCaip2,
234
- x402NetworkLabel,
235
- x402PendingBlockExpiresAt,
236
- x402PendingDepositExpiresAt,
237
- x402PendingFundingJson,
238
- x402PendingRetired,
239
- x402PendingStale,
240
- x402PendingUnsettled,
241
- x402WrongAssetHint
242
- } from "./chunk-SHZMNEXE.js";
114
+ tryX402Payment
115
+ } from "./chunk-RQYMWLX4.js";
243
116
  import {
244
- IDENTITIES_VERSION,
245
- advanceTempoChannelExit,
246
- assertTempoWalletIdle,
247
- createTempoCloseCredential,
248
- deriveIdentityFromPrivkey,
249
- findSigningIdentityByPubkey,
250
- fundingRailLabel,
251
- generateIdentity,
252
- identitiesFileExists,
253
- listResumableTempoChargeFundings,
254
- listTempoChannelAssociations,
255
- loadIdentities,
256
- loadTempoChannelAssociation,
257
- loadTempoChannelController,
258
- offersTempoCreditFunding,
259
- reconcileTempoChannelOnChain,
260
- resolveSigningIdentity,
261
- saveIdentities,
262
- shellQuoteArg,
263
- tempoChannelControlledBy,
264
- tempoSessionChallenge,
265
- tempoSessionChallengeMicro,
266
- withIdentitiesLock,
267
- withTempoChannelLock
268
- } from "./chunk-FSYEZERJ.js";
269
- import "./chunk-Z4CZUMUT.js";
270
- import "./chunk-ERJFRCJO.js";
271
- import "./chunk-R55XNXAR.js";
272
- import "./chunk-XHOFQ3OS.js";
273
- import "./chunk-MJ4X4BEW.js";
117
+ connectedTempoAccount,
118
+ generateTempoKey,
119
+ tempoBalanceCheckHint,
120
+ tempoWrongAssetHint
121
+ } from "./chunk-7UAQTHNP.js";
274
122
  import {
275
- chains_exports
276
- } from "./chunk-BECPI5H5.js";
277
- import "./chunk-N3UJT2NJ.js";
278
- import "./chunk-FL2ICZW5.js";
279
- import "./chunk-WTM2EICO.js";
280
- import "./chunk-EZHT2RLJ.js";
123
+ CREDIT_POSTURES,
124
+ FEEDBACK_POSTURES,
125
+ authorizeProtectedRemoval,
126
+ configSnapshotPath,
127
+ describeConfigBackup,
128
+ ensureConfig,
129
+ isCreditPosture,
130
+ isFeedbackPosture,
131
+ loadConfig,
132
+ pinConfigSnapshot,
133
+ planConfigReset,
134
+ previewConfigRollback,
135
+ retireConfigBackup,
136
+ rollbackConfig,
137
+ updateConfig
138
+ } from "./chunk-ZXVOMXT4.js";
281
139
  import {
140
+ A,
141
+ AGENT_MNEMONIC_FILE,
142
+ BATCH_SETTLEMENT_ADDRESS,
143
+ BTC_RATE_FILE,
144
+ BUDGET_FILE,
145
+ CAPABILITY_NAME_RE,
146
+ CONFIG_AUDIT_FILE,
147
+ CONFIG_BACKUP_FILE,
148
+ CONFIG_DIR,
149
+ CONFIG_FILE,
150
+ CONFIG_PINNED_FILE,
151
+ CREDITS_FILE,
152
+ CREDIT_DRAIN_RAILS,
153
+ CREDIT_FUNDING_MODES,
154
+ CREDIT_FUND_RAILS,
155
+ DEFAULT_AGENT_MINT_URL,
156
+ DvmX402ChannelStorage,
157
+ FAVORITES_FILE,
158
+ FEEDBACK_NUDGES_FILE,
159
+ FxRateUnavailableError,
160
+ IDENTITIES_FILE,
161
+ IDENTITIES_VERSION,
162
+ JOBS_FILE,
163
+ MESSAGES_DIR,
164
+ PAIRINGS_DIR,
165
+ PRIVKEY_HEX_RE,
166
+ PersistentCounterSource,
282
167
  RAIL_FLAGS,
168
+ RECEIPTS_FILE,
169
+ RECENT_SPENDS_CAP,
170
+ RECOVERY_MNEMONIC_FILE,
171
+ REQUEST_INTENTS_DIR,
172
+ ROUTER_FEEDBACK_CLAIM_HEADER,
173
+ SIGNED_REQUEST_AUTH_ID,
283
174
  SUPPORTED_PROTOCOL_VERSION,
175
+ TEMPO_CHANNELS_FILE,
176
+ TEMPO_MODERATO_RPC,
177
+ WALLET_FILE,
178
+ WALLET_VERSION,
179
+ X402_BATCH_CHANNEL_ABI,
180
+ X402_CHANNELS_FILE,
181
+ abool,
182
+ abytes,
183
+ advanceTempoChannelExit,
184
+ aexists,
185
+ amountBoundsVerdict,
186
+ anumber,
187
+ aoutput,
284
188
  applyImplicitReceiptCredit,
285
189
  applyReceiptCredit,
190
+ asProviderText,
191
+ asProviderTextOpt,
192
+ assertAgentMnemonicReplaceable,
193
+ assertNutSupport,
194
+ assertX402ChannelPayer,
195
+ attestedDvmIdentity,
196
+ authenticatedBuilderPubkey,
197
+ base64,
198
+ bindCashuTokenToSubmissionContext,
199
+ canonicalRequestPath,
200
+ cashuSubmissionBindingFingerprint,
201
+ cashuSubmissionBindingFromContext,
202
+ checkMintHealth,
203
+ checkOpts,
204
+ clean,
286
205
  clearCreditSelection,
287
206
  clearPendingDrain,
207
+ clearPendingX402Funding,
288
208
  clearRefillRailUnavailable,
209
+ computeSmartDenominations,
210
+ copyBytes,
211
+ coveringMintsForSpend,
212
+ createFxFetcher,
213
+ createTempoCloseCredential,
214
+ deleteAgentMnemonic,
215
+ deriveAgentMasterKeypair,
216
+ deriveAgentRefundSubkey,
217
+ deriveAgentRefundSubkeyPubkey,
218
+ deriveIdentityFromPrivkey,
219
+ derivePubkeyFromPrivkey,
220
+ deriveTempoAddress,
289
221
  dvmLocationIdentity,
222
+ effectiveFundingMint,
223
+ effectiveMints,
224
+ ensureConfigDir,
225
+ ensureConfigSubdir,
290
226
  ensureProvisionalCredit,
227
+ entryKind,
228
+ equalBytes,
229
+ expand,
230
+ external_exports,
231
+ extract,
291
232
  fetchBtcUsdRate,
292
233
  fetchCoinGeckoSpot,
234
+ fetchLnurlPayInvoice,
235
+ fetchMeltQuote,
236
+ findX402Channel,
293
237
  forgetCredit,
294
238
  formatFiat,
295
- formatStaleness,
296
239
  formatUsd,
297
240
  formatUsdcMicrounits,
241
+ fundWireAmountMicro,
242
+ fxRateFor,
243
+ generateAgentMnemonic,
244
+ generateIdentity2,
245
+ generateSecretKey,
246
+ getBalanceByMint,
247
+ getInputFeesForProofs,
298
248
  getLastKnownBtcRate,
249
+ getOutput,
250
+ getPublicKey,
251
+ getTempoUsdcBalance,
252
+ getWallet,
253
+ identitiesFileExists,
254
+ isArtifactMessage,
255
+ isCancelMessage,
256
+ isCompleteMessage,
257
+ isCreditFundRail,
258
+ isCreditFundingMode,
299
259
  isDrainReceipt,
300
260
  isFundingReceipt,
261
+ isPublicRequestId,
301
262
  isSignedJobReceipt,
263
+ isStablecoinFundRail,
264
+ ki,
265
+ la,
302
266
  listCredits,
303
267
  listFundingMenuSnapshots,
304
268
  listImplicitCredits,
305
269
  listPendingFundings,
270
+ listPendingX402Fundings,
271
+ listPendingX402FundingsForChannel,
272
+ listResumableTempoChargeFundings,
273
+ listResumableX402ExactFundings,
274
+ listResumableX402Fundings,
275
+ listTempoChannelAssociations,
276
+ listX402Channels,
277
+ loadAgentWallet,
306
278
  loadCredit,
279
+ loadIdentities,
307
280
  loadImplicitCredits,
308
281
  loadPendingFunding,
282
+ loadReceipt,
283
+ loadReceipts,
284
+ loadTempoChannelAssociation,
285
+ loadTempoChannelController,
286
+ loadWalletConfiguredMints,
287
+ looksLikeMnemonic,
309
288
  markCredit,
310
289
  markImplicitCreditLost,
311
290
  markRefillDrainNoticed,
312
291
  markRefillRailUnavailable,
313
- msatsToUsd,
314
- msatsToUsdc,
292
+ maxKeysetDenomination,
293
+ meltAmountBounds,
294
+ missingDleqRecoveryDiagnostic,
295
+ mnemonicFingerprint,
315
296
  normalizeCreditEndpoint,
297
+ normalizeFeedbackEndpointHost,
298
+ offersTempoCreditFunding,
299
+ offersX402CreditFunding,
316
300
  parseCreditMenu,
317
301
  parseCreditTerms,
302
+ parseNwcUri,
303
+ parseTraceparent,
318
304
  pendingDrainById,
319
305
  pendingDrainFor,
306
+ prepareP2PKMint,
307
+ providerTextToString,
308
+ readAgentMnemonic,
320
309
  readCompletedCreditHistory,
310
+ readFundValuation,
311
+ readX402ChannelOnChain,
312
+ receiveToAgentWallet,
313
+ reconcileRefusedX402Deposits,
314
+ reconcileTempoChannelOnChain,
321
315
  recordBalanceResponse,
322
316
  recordCreditX402Instrument,
323
317
  recordDrainReceipts,
@@ -325,96 +319,129 @@ import {
325
319
  recordFundingMenuSnapshot,
326
320
  recordPendingDrain,
327
321
  recordRefusedDrawBalance,
328
- settleDrainEvidence,
329
- usdToMsats,
330
- usdcToMsats
331
- } from "./chunk-VOO5IAK7.js";
332
- import {
333
- TEMPO_MODERATO_RPC,
334
- connectedTempoAccount,
335
- deriveTempoAddress,
336
- generateTempoKey,
337
- getTempoUsdcBalance,
322
+ refundX402BatchChannel,
323
+ rehydrateOutputData,
324
+ repairConfigDirMode,
325
+ require_proper_lockfile,
338
326
  resolveTempoAsset,
339
327
  resolveTempoNetwork,
340
- tempoBalanceCheckHint,
328
+ resolveX402ChannelRpc,
329
+ retryMintQuoteOperation,
330
+ sa,
331
+ saveAgentWallet,
332
+ saveIdentities,
333
+ serializeOutputData,
334
+ settleDrainEvidence,
335
+ shellQuoteArg,
336
+ signDvmRequestData,
337
+ signRequestData,
338
+ signedRequestDomain,
339
+ sn,
340
+ swapFeeForProofs,
341
+ tempoChannelControlledBy,
342
+ tempoCredentialAmountMicro,
343
+ tempoSessionChallenge,
344
+ tempoSessionChallengeMicro,
341
345
  tempoTokenReference,
342
- tempoWrongAssetHint,
343
- tryResolveTempoAsset
344
- } from "./chunk-3YE43JJR.js";
346
+ toAgentProof,
347
+ toCashuProofs,
348
+ tryResolveTempoAsset,
349
+ u32,
350
+ u64Lengths,
351
+ unsignRequestData,
352
+ validateAgentMnemonic,
353
+ validateLnAddress,
354
+ verifyDrainReceiptChain,
355
+ verifyEvent,
356
+ verifyJobReceipt,
357
+ walletExists,
358
+ weakestReceiptVerdict,
359
+ windowStart,
360
+ withIdentitiesLock,
361
+ withTempoChannelLock,
362
+ withWalletLock,
363
+ withX402ChannelLock,
364
+ wrapCipher,
365
+ writeAgentMnemonic,
366
+ x402ChannelControlledBy,
367
+ x402ChannelReservation,
368
+ x402CreditChannelNetworks,
369
+ x402CreditExactNetworks,
370
+ x402FlavourForInstrument,
371
+ x402PendingBlockExpiresAt,
372
+ x402PendingDepositExpiresAt,
373
+ x402PendingFundingJson,
374
+ x402PendingRetired,
375
+ x402PendingStale,
376
+ x402PendingUnsettled,
377
+ x402RequiredFromError,
378
+ x402ReservationRelease
379
+ } from "./chunk-VIYUB3XT.js";
380
+ import "./chunk-JBU7RKQ3.js";
381
+ import "./chunk-KDNFUDOG.js";
382
+ import "./chunk-IUTVV6N5.js";
383
+ import "./chunk-Y3SQD37C.js";
384
+ import "./chunk-6LP4EGKA.js";
385
+ import "./chunk-N3UJT2NJ.js";
386
+ import "./chunk-SYFKO6BA.js";
387
+ import "./chunk-PUOXBKY2.js";
345
388
  import {
346
- AGENT_MNEMONIC_FILE,
347
- BTC_RATE_FILE,
348
- BUDGET_FILE,
349
- CONFIG_AUDIT_FILE,
350
- CONFIG_BACKUP_FILE,
351
- CONFIG_DIR,
352
- CONFIG_FILE,
353
- CONFIG_PINNED_FILE,
354
- CREDITS_FILE,
355
- CREDIT_POSTURES,
356
389
  DvmError,
357
- FAVORITES_FILE,
358
- FEEDBACK_NUDGES_FILE,
359
- FEEDBACK_POSTURES,
360
- IDENTITIES_FILE,
361
- JOBS_FILE,
362
- MESSAGES_DIR,
363
- PAIRINGS_DIR,
364
- RECEIPTS_FILE,
365
- RECOVERY_MNEMONIC_FILE,
366
- REQUEST_INTENTS_DIR,
367
- TEMPO_CHANNELS_FILE,
368
- WALLET_FILE,
369
- X402_CHANNELS_FILE,
370
- authorizeProtectedRemoval,
390
+ X402_BATCH_SETTLEMENT_SCHEME,
391
+ X402_DEFAULT_NETWORK,
392
+ X402_V1_VERSION,
393
+ X402_VERSION,
394
+ chainIdFromCaip2,
371
395
  concatBytes,
372
- configSnapshotPath,
373
- describeConfigBackup,
374
- ensureConfig,
375
- ensureConfigDir,
376
- ensureConfigSubdir,
396
+ decodePaymentRequiredHeader,
397
+ ensureAddress,
398
+ generateX402PrivateKey,
377
399
  hexToBytes,
378
400
  hmac,
379
401
  isAbortError,
380
- isCreditPosture,
381
- isFeedbackPosture,
382
402
  isValidEvmPrivateKey,
383
- loadConfig,
384
- pinConfigSnapshot,
385
- planConfigReset,
386
- previewConfigRollback,
403
+ microToSats,
404
+ msatsToMicro,
405
+ msatsToUsd,
406
+ msatsToUsdc,
387
407
  providerProseSources,
388
408
  randomBytes,
389
409
  redactUrl,
390
410
  redactUrlsInText,
391
- repairConfigDirMode,
392
- require_proper_lockfile,
393
411
  resolveRpcHttpTransportOptions,
394
412
  resolveRpcOverride,
395
- retireConfigBackup,
396
- rollbackConfig,
413
+ resolveX402Asset,
397
414
  secp256k1,
398
415
  sha256,
399
416
  transportErrorCode,
400
- updateConfig
401
- } from "./chunk-4KINCBHL.js";
417
+ usdToMsats,
418
+ usdcToMsats,
419
+ x402NetworkByCaip2
420
+ } from "./chunk-JTMBSEZO.js";
421
+ import "./chunk-IQV4KG63.js";
422
+ import "./chunk-FPWP4S5S.js";
423
+ import "./chunk-R2DSAZBO.js";
424
+ import "./chunk-WN5R367B.js";
402
425
  import {
403
426
  privateKeyToAccount
404
427
  } from "./chunk-EVQERRCP.js";
405
428
  import "./chunk-RA24J4QM.js";
429
+ import {
430
+ chains_exports
431
+ } from "./chunk-B4WHUMZM.js";
432
+ import "./chunk-X7SEGALJ.js";
406
433
  import {
407
434
  createPublicClient,
408
435
  createWalletClient,
409
436
  http
410
- } from "./chunk-CJTE5TS3.js";
411
- import "./chunk-GZWKCIYN.js";
437
+ } from "./chunk-ESOJUXVY.js";
438
+ import "./chunk-QXMKABL7.js";
412
439
  import {
413
440
  parseEventLogs
414
- } from "./chunk-LH3QPVN6.js";
441
+ } from "./chunk-TAZWRWM4.js";
415
442
  import "./chunk-6O27TEXD.js";
416
443
  import "./chunk-65EY7CT4.js";
417
- import "./chunk-F55NNH2F.js";
444
+ import "./chunk-FOWQ7R7S.js";
418
445
  import {
419
446
  BaseError,
420
447
  InsufficientFundsError,
@@ -8682,64 +8709,6 @@ function maxSeq(msgs, fallback) {
8682
8709
  return Math.max(...msgs.map((m) => m.seq));
8683
8710
  }
8684
8711
 
8685
- // src/lib/currency.ts
8686
- function formatSats(msats) {
8687
- if (msats === 0) return "0 sats";
8688
- if (msats < 1e3) return `${msats.toLocaleString("en-US")} msats`;
8689
- if (msats % 1e3 === 0) return `${(msats / 1e3).toLocaleString("en-US")} sats`;
8690
- return `${Math.round(msats / 1e3 * 100) / 100} sats`;
8691
- }
8692
- function formatAmount(msats, rate, opts) {
8693
- const usd2 = msatsToUsd(msats, rate);
8694
- const base = `~$${formatUsd(usd2)} (${formatSats(msats)})`;
8695
- return opts?.anchor === false ? base : `${base} \u2014 ${costAnchor(usd2)}`;
8696
- }
8697
- function formatPaymentAmount(msats, fiat, opts) {
8698
- if (!fiat || fiat.amount <= 0) return formatAmountBestEffort(msats, opts);
8699
- const base = `${formatFiat(fiat.amount, fiat.currency)} (${formatSats(msats)})`;
8700
- return opts?.anchor === false ? base : `${base} \u2014 ${costAnchor(fiat.amount, fiat.currency)}`;
8701
- }
8702
- var COST_ANCHOR_BANDS = {
8703
- usd: [0.01, 0.1, 1, 10],
8704
- eur: [0.01, 0.1, 1, 10],
8705
- gbp: [0.01, 0.1, 1, 10],
8706
- jpy: [1, 10, 100, 1500]
8707
- };
8708
- function costAnchor(amount, currency = "usd") {
8709
- const bands = COST_ANCHOR_BANDS[currency] ?? COST_ANCHOR_BANDS.usd;
8710
- if (amount < bands[0]) return "fraction of a cent";
8711
- if (amount <= bands[1]) return "comparable to an API call";
8712
- if (amount <= bands[2]) return "comparable to a ChatGPT query";
8713
- if (amount <= bands[3]) return "comparable to a coffee";
8714
- return "significant purchase \u2014 review carefully";
8715
- }
8716
- function monetaryJson(msats, rate) {
8717
- const usd2 = msatsToUsd(msats, rate);
8718
- return {
8719
- msats,
8720
- usd: Math.round(usd2 * 100) / 100,
8721
- anchor: costAnchor(usd2),
8722
- display: formatAmount(msats, rate)
8723
- };
8724
- }
8725
- function parseBudget(budget, rate) {
8726
- const value = assertValidBudget(budget);
8727
- return budget.startsWith("$") ? usdToMsats(value, rate) : value;
8728
- }
8729
- function assertValidBudget(budget) {
8730
- const value = budget.startsWith("$") ? parseFloat(budget.slice(1)) : parseInt(budget, 10);
8731
- if (isNaN(value)) throw new Error(`Invalid budget: ${budget}`);
8732
- return value;
8733
- }
8734
- function formatAmountBestEffort(msats, opts) {
8735
- const m = msats ?? 0;
8736
- const cached2 = getLastKnownBtcRate();
8737
- if (cached2 === null) return `${Math.round(m / 1e3)} sats`;
8738
- const base = formatAmount(m, cached2.rate, opts);
8739
- if (Date.now() - cached2.cachedAt < FX_CACHE_TTL_MS) return base;
8740
- return `${base} (rate cached ${formatStaleness(cached2.cachedAt)})`;
8741
- }
8742
-
8743
8712
  // src/lib/next-action.ts
8744
8713
  function isTerminalJobStatus(status2) {
8745
8714
  return TERMINAL_STATUSES.has(status2);
@@ -8811,6 +8780,18 @@ var PAYMENT_RAIL_KEYS = ["cashu", "cashu_p2pk", "x402", "tempo"];
8811
8780
  function isPaymentRailKey(value) {
8812
8781
  return typeof value === "string" && PAYMENT_RAIL_KEYS.includes(value);
8813
8782
  }
8783
+ function fundingRailLabel(rail) {
8784
+ switch (rail) {
8785
+ case "cashu":
8786
+ return "ecash";
8787
+ case "lightning":
8788
+ return "Lightning";
8789
+ case "x402":
8790
+ return "x402 stablecoin";
8791
+ case "tempo":
8792
+ return "Tempo stablecoin";
8793
+ }
8794
+ }
8814
8795
  function paymentRailLabel(rail) {
8815
8796
  switch (rail) {
8816
8797
  case "cashu":
@@ -8827,80 +8808,17 @@ function probeRailLabel(rail) {
8827
8808
  }
8828
8809
  function railLabelAtSentenceStart(label) {
8829
8810
  return label === "ecash" ? "Ecash" : label;
8830
- }
8831
-
8832
- // src/lib/payment-copy.ts
8833
- function paidConfirmationDisplay(result, fiat) {
8834
- return `Paid ${formatPaidAmount(result, fiat)} via ${paymentRailLabel(result.rail)}.`;
8835
- }
8836
- function formatPaidAmount(result, fiat) {
8837
- if (result.amountUsdcMicro !== void 0) {
8838
- return `$${formatUsdcMicrounits(result.amountUsdcMicro)} USDC`;
8839
- }
8840
- return formatPaymentAmount(result.amountMsats, fiat, { anchor: false });
8841
- }
8842
-
8843
- // src/lib/agent-wallet-retry.ts
8844
- var TRANSIENT_PAYMENT_BACKOFF_MS = [250, 500, 1e3, 2e3, 4e3];
8845
- var TRANSIENT_PAYMENT_CODES = /* @__PURE__ */ new Set(["proof_pending", "mint_unreachable"]);
8846
- function defaultSleep(ms) {
8847
- return new Promise((resolve3) => setTimeout(resolve3, ms));
8848
- }
8849
- var TRANSPORT_FAILURE_CODES = /* @__PURE__ */ new Set(["timeout", "provider_unreachable"]);
8850
- async function withAgentWalletPaymentRetry(args) {
8851
- const { attempt, intendedLockPubkey, refetchInfo } = args;
8852
- const sleep = args.sleep ?? defaultSleep;
8853
- let rotationRetried = false;
8854
- let transportRetried = false;
8855
- let pendingAttempt = 0;
8856
- for (; ; ) {
8857
- try {
8858
- return await attempt();
8859
- } catch (err) {
8860
- if (!(err instanceof DvmError)) throw err;
8861
- if (args.retryTransportFailureOnce && TRANSPORT_FAILURE_CODES.has(err.code) && !transportRetried) {
8862
- transportRetried = true;
8863
- continue;
8864
- }
8865
- if (TRANSIENT_PAYMENT_CODES.has(err.code)) {
8866
- if (pendingAttempt >= TRANSIENT_PAYMENT_BACKOFF_MS.length) {
8867
- throw err;
8868
- }
8869
- await sleep(TRANSIENT_PAYMENT_BACKOFF_MS[pendingAttempt]);
8870
- pendingAttempt += 1;
8871
- continue;
8872
- }
8873
- if (err.code === "wrong_lock_pubkey") {
8874
- if (rotationRetried) {
8875
- throw new DvmError(
8876
- "payment_lock_pubkey_stale",
8877
- "DVM rejected proofs after a rotation refetch \u2014 the swap target is no longer advertised.",
8878
- "Wallet retains the locked outputs as a pending_submission for manual recovery."
8879
- );
8880
- }
8881
- let refreshed;
8882
- try {
8883
- refreshed = await refetchInfo();
8884
- } catch {
8885
- throw err;
8886
- }
8887
- const target = intendedLockPubkey.toLowerCase();
8888
- const matches = (refreshed.cashu?.lock_pubkeys ?? []).some(
8889
- (pk) => pk.toLowerCase() === target
8890
- );
8891
- if (!matches) {
8892
- throw new DvmError(
8893
- "payment_lock_pubkey_stale",
8894
- "DVM has rotated past the lock pubkey our outputs were swapped to.",
8895
- "Wallet retains the locked outputs as a pending_submission for manual recovery."
8896
- );
8897
- }
8898
- rotationRetried = true;
8899
- continue;
8900
- }
8901
- throw err;
8902
- }
8811
+ }
8812
+
8813
+ // src/lib/payment-copy.ts
8814
+ function paidConfirmationDisplay(result, fiat) {
8815
+ return `Paid ${formatPaidAmount(result, fiat)} via ${paymentRailLabel(result.rail)}.`;
8816
+ }
8817
+ function formatPaidAmount(result, fiat) {
8818
+ if (result.amountUsdcMicro !== void 0) {
8819
+ return `$${formatUsdcMicrounits(result.amountUsdcMicro)} USDC`;
8903
8820
  }
8821
+ return formatPaymentAmount(result.amountMsats, fiat, { anchor: false });
8904
8822
  }
8905
8823
 
8906
8824
  // src/lib/caller-version.ts
@@ -9068,37 +8986,847 @@ function withDecodableAcceptEncoding(input, init2) {
9068
8986
  }
9069
8987
  return { ...init2, headers };
9070
8988
  }
9071
- const record = { ...source };
9072
- if (!Object.keys(record).some((name) => name.toLowerCase() === "accept-encoding")) {
9073
- record["Accept-Encoding"] = DECODABLE_ACCEPT_ENCODING;
8989
+ const record = { ...source };
8990
+ if (!Object.keys(record).some((name) => name.toLowerCase() === "accept-encoding")) {
8991
+ record["Accept-Encoding"] = DECODABLE_ACCEPT_ENCODING;
8992
+ }
8993
+ return { ...init2, headers: record };
8994
+ }
8995
+ var nativeFetch = globalThis.fetch;
8996
+ async function readBoundedBody(response, limit) {
8997
+ if (!response.body) return "";
8998
+ const reader = response.body.getReader();
8999
+ const decoder = new TextDecoder();
9000
+ let size = 0;
9001
+ let body = "";
9002
+ try {
9003
+ for (; ; ) {
9004
+ const { done, value } = await reader.read();
9005
+ if (done) return body + decoder.decode();
9006
+ size += value.byteLength;
9007
+ if (size > limit) {
9008
+ await reader.cancel();
9009
+ return void 0;
9010
+ }
9011
+ body += decoder.decode(value, { stream: true });
9012
+ }
9013
+ } catch {
9014
+ return void 0;
9015
+ } finally {
9016
+ reader.releaseLock();
9017
+ }
9018
+ }
9019
+ var MAX_COMPATIBILITY_BODY_BYTES = 16384;
9020
+
9021
+ // src/lib/wallet-agent/recovery-submissions.ts
9022
+ var RESUME_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
9023
+ var RESUME_MAX_ATTEMPTS = 5;
9024
+ async function sweepPendingSubmissions(opts = {}) {
9025
+ const wallet = loadAgentWallet();
9026
+ if (!wallet || wallet.pending_submissions.length === 0) {
9027
+ return { outcomes: [] };
9028
+ }
9029
+ const deps = {
9030
+ httpPost: opts.httpPost ?? createDefaultHttpPost(opts.fetchImpl ?? dvmFetch),
9031
+ getWalletForMint: opts.getWalletForMint ?? getWallet,
9032
+ readMnemonic: opts.readMnemonic ?? readAgentMnemonic,
9033
+ lockPubkey: wallet.lock_pubkey
9034
+ };
9035
+ const now = opts.now ?? (() => Date.now());
9036
+ const outcomes = [];
9037
+ for (const entry of wallet.pending_submissions) {
9038
+ outcomes.push(await resolveEntry(entry, deps, now()));
9039
+ }
9040
+ if (outcomes.some(mutatesWallet)) {
9041
+ await withWalletLock(() => {
9042
+ const fresh = loadAgentWallet() ?? wallet;
9043
+ const next = outcomes.reduce(
9044
+ (acc, outcome) => applyOutcome(acc, outcome, now),
9045
+ fresh
9046
+ );
9047
+ saveAgentWallet(next);
9048
+ });
9049
+ }
9050
+ return { outcomes };
9051
+ }
9052
+ async function recoverPendingSubmission(opts) {
9053
+ if (!UUID_V4_RE.test(opts.requestId))
9054
+ throw new DvmError("invalid_request_id", "The pending-submission request id must be a UUIDv4.");
9055
+ if (!SHA256_RE.test(opts.bindingFingerprint))
9056
+ throw new DvmError(
9057
+ "invalid_submission_binding",
9058
+ "The pending-submission binding fingerprint must be lowercase SHA-256 hex."
9059
+ );
9060
+ return withWalletLock(async () => {
9061
+ const wallet = loadAgentWallet();
9062
+ if (!wallet)
9063
+ throw new DvmError("wallet_missing", "No agent wallet found.", "Run: dvm wallet init");
9064
+ const matches = wallet.pending_submissions.filter(
9065
+ (entry2) => entry2.request_id === opts.requestId
9066
+ );
9067
+ if (matches.length !== 1)
9068
+ throw new DvmError(
9069
+ "submission_not_found",
9070
+ `No unique pending submission exists for request ${opts.requestId}.`,
9071
+ "Inspect the journal with: dvm wallet submissions"
9072
+ );
9073
+ const entry = matches[0];
9074
+ const binding = entry.context && cashuSubmissionBindingFromContext(entry.context);
9075
+ const recomputed = binding ? cashuSubmissionBindingFingerprint(binding) : null;
9076
+ if (entry.context?.binding_fingerprint !== opts.bindingFingerprint || recomputed !== opts.bindingFingerprint)
9077
+ throw new DvmError(
9078
+ "submission_binding_mismatch",
9079
+ "The saved submission does not match the approved strict request binding.",
9080
+ "Do not recover by endpoint, mint, or amount. Rebuild evidence for the exact saved request."
9081
+ );
9082
+ if (entry.output_proofs.length === 0 || entry.swapping)
9083
+ throw new DvmError(
9084
+ "submission_not_ready",
9085
+ "The exact submission has no completed payment output to recover.",
9086
+ "Use read-only NUT-09/NUT-07 reconciliation for the interrupted swap."
9087
+ );
9088
+ if ((entry.attempts ?? 0) !== 0)
9089
+ throw new DvmError(
9090
+ "submission_recovery_exhausted",
9091
+ "The exact strict submission already consumed its one recovery attempt.",
9092
+ "Use read-only receipt and job lookup; do not re-submit the payment."
9093
+ );
9094
+ const now = opts.now ?? (() => Date.now());
9095
+ const attempted = {
9096
+ ...entry,
9097
+ attempts: 1,
9098
+ last_attempt_at: new Date(now()).toISOString()
9099
+ };
9100
+ saveAgentWallet({
9101
+ ...wallet,
9102
+ pending_submissions: wallet.pending_submissions.map(
9103
+ (candidate) => candidate.request_id === opts.requestId ? attempted : candidate
9104
+ )
9105
+ });
9106
+ const outcome = await shipEntry(
9107
+ attempted,
9108
+ opts.httpPost ?? createDefaultHttpPost(opts.fetchImpl ?? dvmFetch)
9109
+ );
9110
+ if (outcome.kind === "shipped" || outcome.kind === "already_accepted") {
9111
+ const current = loadAgentWallet() ?? wallet;
9112
+ saveAgentWallet(applyOutcome(current, outcome, now));
9113
+ return {
9114
+ requestId: opts.requestId,
9115
+ outcome: outcome.kind,
9116
+ jobId: outcome.kind === "shipped" ? outcome.jobId ?? null : null,
9117
+ attemptCount: 1
9118
+ };
9119
+ }
9120
+ return { requestId: opts.requestId, outcome: "pending", jobId: null, attemptCount: 1 };
9121
+ });
9122
+ }
9123
+ function isResumable(entry) {
9124
+ return resumeBody(entry) !== null;
9125
+ }
9126
+ function reclaimAtMs(entry) {
9127
+ if (entry.output_proofs.length === 0) return null;
9128
+ if (!entry.canonical_id || typeof entry.t_expire !== "number") return null;
9129
+ return entry.t_expire;
9130
+ }
9131
+ async function resolveEntry(entry, deps, nowMs) {
9132
+ if (entry.output_proofs.length === 0) {
9133
+ const inFlightWindowMs = inFlightTimeoutSeconds() * 1e3;
9134
+ if (entry.swapping) {
9135
+ return ageMs(entry, nowMs) >= inFlightWindowMs ? recoverPreparedSwap(entry, deps) : { kind: "no_swap", entry };
9136
+ }
9137
+ return ageMs(entry, nowMs) >= inFlightWindowMs ? { kind: "pruned", entry } : { kind: "no_swap", entry };
9138
+ }
9139
+ const reclaimAt = reclaimAtMs(entry);
9140
+ if (reclaimAt !== null && nowMs >= reclaimAt) {
9141
+ return reclaimEntry(entry, deps);
9142
+ }
9143
+ if (!isResumable(entry)) {
9144
+ return { kind: "unresumable", entry };
9145
+ }
9146
+ if (ageMs(entry, nowMs) > RESUME_MAX_AGE_MS) {
9147
+ return { kind: "stale", entry, reason: "older than the resume window" };
9148
+ }
9149
+ if ((entry.attempts ?? 0) >= RESUME_MAX_ATTEMPTS) {
9150
+ return { kind: "stale", entry, reason: `no response after ${RESUME_MAX_ATTEMPTS} attempts` };
9151
+ }
9152
+ return shipEntry(entry, deps.httpPost);
9153
+ }
9154
+ async function recoverPreparedSwap(entry, deps) {
9155
+ const swapping = entry.swapping;
9156
+ if (!swapping) return { kind: "pruned", entry };
9157
+ let cashuWallet;
9158
+ try {
9159
+ cashuWallet = await deps.getWalletForMint(entry.mint);
9160
+ } catch (err) {
9161
+ return { kind: "swap_recovery_pending", entry, reason: errorText(err) };
9162
+ }
9163
+ let sendData;
9164
+ let keepData;
9165
+ try {
9166
+ sendData = rehydrateOutputData(swapping.send_outputs);
9167
+ keepData = rehydrateOutputData(swapping.keep_outputs);
9168
+ } catch (err) {
9169
+ return { kind: "swap_recovery_pending", entry, reason: errorText(err) };
9170
+ }
9171
+ const allData = [...sendData, ...keepData];
9172
+ let restoreError;
9173
+ try {
9174
+ const restored = await cashuWallet.mint.restore({
9175
+ outputs: allData.map((data) => data.blindedMessage)
9176
+ });
9177
+ if (restored.outputs.length !== restored.signatures.length) {
9178
+ return {
9179
+ kind: "swap_recovery_pending",
9180
+ entry,
9181
+ reason: "mint returned mismatched NUT-09 outputs and signatures"
9182
+ };
9183
+ }
9184
+ const signaturesByOutput = new Map(
9185
+ restored.outputs.map((output, index) => [output.B_, restored.signatures[index]])
9186
+ );
9187
+ if (allData.length > 0 && allData.every((data) => signaturesByOutput.has(data.blindedMessage.B_))) {
9188
+ const restoreGroup = (data) => data.map((output) => {
9189
+ const signature = signaturesByOutput.get(output.blindedMessage.B_);
9190
+ if (!signature) throw new Error("mint omitted a restored output");
9191
+ if (signature.id !== swapping.keyset_id) {
9192
+ throw new Error("mint restored an output under an unexpected keyset");
9193
+ }
9194
+ return output.toProof(signature, cashuWallet.keyChain.getKeyset(swapping.keyset_id));
9195
+ });
9196
+ const send = restoreGroup(sendData);
9197
+ const keep = restoreGroup(keepData);
9198
+ const cashuToken = ki({ mint: entry.mint, proofs: send });
9199
+ return {
9200
+ kind: "swap_restored",
9201
+ entry,
9202
+ outputs: send.map((proof) => toAgentProof(proof, entry.mint, entry.intended_lock_pubkey)),
9203
+ keep: keep.map((proof) => toAgentProof(proof, entry.mint, deps.lockPubkey)),
9204
+ cashuToken
9205
+ };
9206
+ }
9207
+ if (restored.outputs.length > 0) {
9208
+ return {
9209
+ kind: "swap_recovery_pending",
9210
+ entry,
9211
+ reason: "mint restored only part of the interrupted swap"
9212
+ };
9213
+ }
9214
+ } catch (err) {
9215
+ restoreError = errorText(err);
9216
+ }
9217
+ try {
9218
+ const states = await cashuWallet.checkProofsStates(toCashuProofs(swapping.input_proofs));
9219
+ if (states.length === swapping.input_proofs.length && states.every((state) => state.state === la.UNSPENT)) {
9220
+ return { kind: "swap_reverted", entry };
9221
+ }
9222
+ return {
9223
+ kind: "swap_recovery_pending",
9224
+ entry,
9225
+ reason: restoreError ? `NUT-09 restore failed (${restoreError}); mint still reports the interrupted swap inputs spent or pending` : "mint still reports the interrupted swap inputs spent or pending"
9226
+ };
9227
+ } catch (err) {
9228
+ return { kind: "swap_recovery_pending", entry, reason: errorText(err) };
9229
+ }
9230
+ }
9231
+ async function reclaimEntry(entry, deps) {
9232
+ const skipped = (reason, terminal = false) => ({
9233
+ kind: "reclaim_skipped",
9234
+ entry,
9235
+ reason,
9236
+ terminal
9237
+ });
9238
+ const mnemonic = deps.readMnemonic();
9239
+ if (!mnemonic) {
9240
+ return skipped(
9241
+ "no mnemonic at ~/.dvm/wallet.mnemonic, so the refund key can't be derived \u2014 restore it with `dvm wallet recover`"
9242
+ );
9243
+ }
9244
+ let refundPrivkey;
9245
+ try {
9246
+ const refund = deriveAgentRefundSubkey(mnemonic, entry.canonical_id ?? "");
9247
+ if (entry.refund_pubkey && entry.refund_pubkey !== refund.pubkey) {
9248
+ return skipped(
9249
+ "this wallet's mnemonic does not derive the refund key the payment was locked to"
9250
+ );
9251
+ }
9252
+ refundPrivkey = refund.privkey;
9253
+ } catch (err) {
9254
+ return skipped(errorText(err));
9255
+ }
9256
+ let cashuWallet;
9257
+ try {
9258
+ cashuWallet = await deps.getWalletForMint(entry.mint);
9259
+ } catch (err) {
9260
+ return skipped(errorText(err));
9261
+ }
9262
+ let grouped;
9263
+ try {
9264
+ grouped = await cashuWallet.groupProofsByState(toCashuProofs(entry.output_proofs));
9265
+ } catch (err) {
9266
+ return skipped(errorText(err));
9267
+ }
9268
+ const spentSecrets = new Set(grouped.spent.map((p) => p.secret));
9269
+ const pendingSecrets = new Set(grouped.pending.map((p) => p.secret));
9270
+ const spent = entry.output_proofs.filter((p) => spentSecrets.has(p.secret));
9271
+ const pending4 = entry.output_proofs.filter((p) => pendingSecrets.has(p.secret));
9272
+ const unspent = entry.output_proofs.filter(
9273
+ (p) => !spentSecrets.has(p.secret) && !pendingSecrets.has(p.secret)
9274
+ );
9275
+ if (unspent.length === 0) {
9276
+ return pending4.length > 0 ? skipped("the mint still reports these proofs in flight") : { kind: "already_accepted", entry };
9277
+ }
9278
+ if (pending4.length > 0) {
9279
+ return skipped("the mint still reports some of these proofs in flight");
9280
+ }
9281
+ const totalSats = unspent.reduce((sum, p) => sum + p.amount, 0);
9282
+ const inputs = toCashuProofs(unspent);
9283
+ let outputs;
9284
+ try {
9285
+ const swapFeeSats = swapFeeForProofs(cashuWallet, inputs);
9286
+ const allowance = reclaimFeeAllowance(entry);
9287
+ if (!allowance.ok) {
9288
+ return skipped(allowance.reason, true);
9289
+ }
9290
+ if (allowance.remainingSats !== null && swapFeeSats > allowance.remainingSats) {
9291
+ return skipped(
9292
+ `the initial swap used ${allowance.initialSats} sats of this job's ${allowance.maxSats}-sat Cashu fee ceiling, leaving a ${allowance.remainingSats}-sat allowance; the mint's ${swapFeeSats}-sat recovery swap fee exceeds that remainder`,
9293
+ true
9294
+ );
9295
+ }
9296
+ const reclaimSats = totalSats - swapFeeSats;
9297
+ if (reclaimSats <= 0) {
9298
+ return skipped(
9299
+ `worth ${totalSats} sats, which does not cover the mint's ${swapFeeSats}-sat swap fee`,
9300
+ true
9301
+ );
9302
+ }
9303
+ const result = await cashuWallet.ops.send(reclaimSats, inputs).privkey(refundPrivkey).asP2PK({ pubkey: deps.lockPubkey }).run();
9304
+ outputs = result.send;
9305
+ } catch (err) {
9306
+ const diagnostic = missingDleqRecoveryDiagnostic(inputs, err);
9307
+ return skipped(diagnostic ?? errorText(err), diagnostic !== null);
9308
+ }
9309
+ return {
9310
+ kind: "reclaimed",
9311
+ entry,
9312
+ outputs: outputs.map((p) => toAgentProof(p, entry.mint, deps.lockPubkey)),
9313
+ reclaimed_sats: outputs.reduce((sum, p) => sum + A.from(p.amount).toNumber(), 0),
9314
+ spent_sats: spent.reduce((sum, p) => sum + p.amount, 0)
9315
+ };
9316
+ }
9317
+ function reclaimFeeAllowance(entry) {
9318
+ const maxSats = entry.max_cashu_fee_sats;
9319
+ const contextMaxSats = entry.context?.max_cashu_fee_sats;
9320
+ const initialSats = entry.initial_cashu_fee_sats;
9321
+ const contextInitialSats = entry.context?.initial_cashu_fee_sats;
9322
+ if (maxSats === void 0) {
9323
+ if (contextMaxSats !== void 0) {
9324
+ return {
9325
+ ok: false,
9326
+ reason: "the saved submission's Cashu fee ceiling is missing from its money journal"
9327
+ };
9328
+ }
9329
+ if (initialSats !== void 0 && !isNonNegativeSafeInteger(initialSats) || contextInitialSats !== void 0 && !isNonNegativeSafeInteger(contextInitialSats) || initialSats !== void 0 && contextInitialSats !== void 0 && initialSats !== contextInitialSats) {
9330
+ return {
9331
+ ok: false,
9332
+ reason: "the saved submission's initial Cashu fee accounting is invalid"
9333
+ };
9334
+ }
9335
+ return {
9336
+ ok: true,
9337
+ maxSats: null,
9338
+ initialSats: initialSats ?? contextInitialSats ?? 0,
9339
+ remainingSats: null
9340
+ };
9341
+ }
9342
+ if (!isNonNegativeSafeInteger(maxSats)) {
9343
+ return { ok: false, reason: "the saved submission's Cashu fee ceiling is invalid" };
9344
+ }
9345
+ if (!isNonNegativeSafeInteger(initialSats)) {
9346
+ return {
9347
+ ok: false,
9348
+ reason: "the capped saved submission is missing valid initial Cashu fee accounting"
9349
+ };
9350
+ }
9351
+ if (entry.context && (contextMaxSats !== maxSats || contextInitialSats !== initialSats)) {
9352
+ return {
9353
+ ok: false,
9354
+ reason: "the saved submission's Cashu fee accounting disagrees with its request context"
9355
+ };
9356
+ }
9357
+ if (initialSats > maxSats) {
9358
+ return {
9359
+ ok: false,
9360
+ reason: "the saved submission's initial Cashu fee exceeds its job-wide ceiling"
9361
+ };
9362
+ }
9363
+ return {
9364
+ ok: true,
9365
+ maxSats,
9366
+ initialSats,
9367
+ remainingSats: maxSats - initialSats
9368
+ };
9369
+ }
9370
+ function isNonNegativeSafeInteger(value) {
9371
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
9372
+ }
9373
+ var UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
9374
+ var SHA256_RE = /^[a-f0-9]{64}$/;
9375
+ async function shipEntry(entry, httpPost) {
9376
+ const token = { mint: entry.mint, proofs: toCashuProofs(entry.output_proofs) };
9377
+ const cashuToken = entry.cashu_token ?? ki(token);
9378
+ const headers = {
9379
+ "Content-Type": "application/json",
9380
+ "X-Cashu": cashuToken,
9381
+ "X-Cashu-Request-Id": entry.request_id
9382
+ };
9383
+ const route = entry.context?.route === "credit" ? "/v1/credit" : "/v1/job";
9384
+ let active2 = entry;
9385
+ let correctedOnce = false;
9386
+ for (; ; ) {
9387
+ const body = resumeBody(active2);
9388
+ if (!body) return { kind: "unresumable", entry };
9389
+ let response;
9390
+ try {
9391
+ response = await httpPost({
9392
+ url: `${entry.endpoint}${route}`,
9393
+ headers,
9394
+ body: JSON.stringify(body)
9395
+ });
9396
+ } catch (err) {
9397
+ return {
9398
+ kind: "still_pending",
9399
+ entry,
9400
+ reason: `network error: ${err instanceof Error ? err.message : String(err)}`
9401
+ };
9402
+ }
9403
+ if (response.status >= 200 && response.status < 300) {
9404
+ if (entry.context?.route === "credit") {
9405
+ applyResumedCreditFund(entry, response.body);
9406
+ return { kind: "shipped", entry };
9407
+ }
9408
+ const jobId = typeof response.body?.job_id === "string" ? response.body.job_id : void 0;
9409
+ if (jobId && entry.context) {
9410
+ saveJob(jobRecordFromEntry(entry, jobId, response.body, response.feedbackClaim));
9411
+ }
9412
+ await reconcileResumedJobCredit(active2, response.body, httpPost);
9413
+ return { kind: "shipped", entry, jobId };
9414
+ }
9415
+ if (response.status === 409 || response.body?.error === "replay_rejected") {
9416
+ await reconcileResumedJobCredit(active2, response.body, httpPost);
9417
+ return { kind: "already_accepted", entry };
9418
+ }
9419
+ const errCode = typeof response.body?.error === "string" ? response.body.error : null;
9420
+ if (errCode === "funding_commitment_mismatch") {
9421
+ if (!correctedOnce) {
9422
+ const correction = await correctFundAmount(active2, response.body);
9423
+ if (correction.kind === "corrected") {
9424
+ correctedOnce = true;
9425
+ active2 = correction.entry;
9426
+ continue;
9427
+ }
9428
+ if (correction.kind === "permanent") {
9429
+ return { kind: "abandoned", entry, reason: errCode };
9430
+ }
9431
+ }
9432
+ return { kind: "still_pending", entry, reason: errCode };
9433
+ }
9434
+ if (errCode === "wrong_lock_pubkey" || errCode === "not_p2pk_locked" || errCode === "payment_invalid" || errCode === "proof_not_unspent" || // Credit-route permanent refusals: the fund can never land
9435
+ // under this signed body.
9436
+ errCode === "credit_id_unavailable" || errCode === "caller_mismatch" || errCode === "credit_not_supported") {
9437
+ return { kind: "abandoned", entry, reason: errCode };
9438
+ }
9439
+ return {
9440
+ kind: "still_pending",
9441
+ entry,
9442
+ reason: errCode ?? `http ${response.status}`
9443
+ };
9444
+ }
9445
+ }
9446
+ async function correctFundAmount(entry, body) {
9447
+ const ctx = entry.context;
9448
+ if (!ctx || ctx.route === "credit") return { kind: "permanent" };
9449
+ const data = ctx.submit_body.data;
9450
+ const fund = data?.fund;
9451
+ if (!data || !fund) return { kind: "permanent" };
9452
+ const valuation = readFundValuation({
9453
+ expectedMicro: body?.expected_micro,
9454
+ message: typeof body?.message === "string" ? body.message : void 0
9455
+ });
9456
+ if (valuation.kind === "absent") return { kind: "permanent" };
9457
+ if (valuation.kind === "malformed") return { kind: "hold" };
9458
+ const expected = valuation.micro;
9459
+ if (expected === fund.amount_micro) return { kind: "hold" };
9460
+ await correctPendingFundAmount({ requestId: entry.request_id, amountMicro: expected });
9461
+ return {
9462
+ kind: "corrected",
9463
+ entry: {
9464
+ ...entry,
9465
+ context: {
9466
+ ...ctx,
9467
+ submit_body: {
9468
+ ...ctx.submit_body,
9469
+ data: { ...data, fund: { ...fund, amount_micro: expected } }
9470
+ }
9471
+ }
9472
+ }
9473
+ };
9474
+ }
9475
+ function resumeBody(entry) {
9476
+ const ctx = entry.context;
9477
+ if (!ctx) return null;
9478
+ if (ctx.route === "credit") {
9479
+ const domain2 = ctx.auth_domain;
9480
+ if (!ctx.credit_body || !ctx.signing_pubkey || !domain2) return null;
9481
+ const signer2 = findSigningIdentityByPubkey(ctx.signing_pubkey);
9482
+ if (!signer2) return null;
9483
+ return signDvmRequestData(signer2.privkey, ctx.credit_body, domain2);
9484
+ }
9485
+ if (!ctx.signing_pubkey) return ctx.submit_body;
9486
+ const domain = ctx.auth_domain;
9487
+ if (!domain) return null;
9488
+ const signer = findSigningIdentityByPubkey(ctx.signing_pubkey);
9489
+ if (!signer) return null;
9490
+ const unsigned = ctx.submit_body.data ?? {};
9491
+ return { ...ctx.submit_body, data: signDvmRequestData(signer.privkey, unsigned, domain) };
9492
+ }
9493
+ function applyResumedCreditFund(entry, body) {
9494
+ const pubkey = entry.context?.signing_pubkey;
9495
+ const credit = isCreditWire(body?.credit) ? body.credit : void 0;
9496
+ const rawReceipt = body?.funding_receipt;
9497
+ const receipt = isFundingReceipt(rawReceipt) ? rawReceipt : void 0;
9498
+ if (!pubkey || !credit) return false;
9499
+ const ctx = entry.context;
9500
+ const request2 = fundingRequest(entry);
9501
+ if (!ctx || !request2) return false;
9502
+ const mutableReplay = ctx.route === "credit" && body?.replayed === true;
9503
+ const verification = captureFundingReceipt({
9504
+ receipt,
9505
+ ...rawReceipt !== void 0 && !receipt ? { parseError: "shape_invalid" } : {},
9506
+ endpoint: entry.endpoint,
9507
+ ...ctx.builder ? { builder: ctx.builder } : {},
9508
+ expectedCreditId: credit.credit_id,
9509
+ expectedFundId: request2.fundId,
9510
+ expectedFundedMicro: typeof body?.funded_micro === "number" ? body.funded_micro : request2.amountMicro,
9511
+ ...mutableReplay ? {} : {
9512
+ expectedBalanceAfterMicro: credit.remaining_micro,
9513
+ expectedLedgerSeq: credit.ledger_seq
9514
+ },
9515
+ expectedCallerPubkey: pubkey
9516
+ });
9517
+ const sequenced = !mutableReplay && (verification === "verified" || verification === "verified_unattested");
9518
+ try {
9519
+ const stored = loadCredit(entry.endpoint, pubkey);
9520
+ recordFundResponse({
9521
+ endpoint: entry.endpoint,
9522
+ callerPubkey: pubkey,
9523
+ credit,
9524
+ targetMicro: stored?.targetMicro ?? credit.remaining_micro,
9525
+ sequenced
9526
+ });
9527
+ } catch {
9528
+ return false;
9529
+ }
9530
+ return true;
9531
+ }
9532
+ function fundingRequest(entry) {
9533
+ const ctx = entry.context;
9534
+ if (!ctx) return void 0;
9535
+ const data = ctx.route === "credit" ? ctx.credit_body : ctx.submit_body.data;
9536
+ const fund = data?.fund;
9537
+ if (!fund) return void 0;
9538
+ const fundId = ctx.route === "credit" ? fund.fund_id : entry.request_id;
9539
+ if (typeof fundId !== "string") return void 0;
9540
+ return {
9541
+ fundId,
9542
+ ...typeof fund.amount_micro === "number" ? { amountMicro: fund.amount_micro } : {}
9543
+ };
9544
+ }
9545
+ async function reconcileResumedJobCredit(entry, body, httpPost) {
9546
+ const ctx = entry.context;
9547
+ if (!ctx || ctx.route === "credit") return;
9548
+ const data = ctx.submit_body.data;
9549
+ if (!data || !data.fund && typeof data.credit_id !== "string") return;
9550
+ if (applyResumedCreditFund(entry, body)) return;
9551
+ const pubkey = ctx.signing_pubkey;
9552
+ if (!pubkey) return;
9553
+ try {
9554
+ if (loadCredit(entry.endpoint, pubkey)?.provisional !== true) return;
9555
+ } catch {
9556
+ return;
9557
+ }
9558
+ await readResumedCreditBalance(entry, httpPost).catch(() => void 0);
9559
+ }
9560
+ async function readResumedCreditBalance(entry, httpPost) {
9561
+ const pubkey = entry.context?.signing_pubkey;
9562
+ if (!pubkey) return;
9563
+ const signer = findSigningIdentityByPubkey(pubkey);
9564
+ const storedDomain = entry.context?.auth_domain;
9565
+ if (!signer || !storedDomain) return;
9566
+ const domain = creditOperationDomain(storedDomain);
9567
+ if (!domain) return;
9568
+ const response = await httpPost({
9569
+ url: `${entry.endpoint}/v1/credit`,
9570
+ headers: { "Content-Type": "application/json" },
9571
+ body: JSON.stringify(signDvmRequestData(signer.privkey, { op: "balance" }, domain))
9572
+ });
9573
+ if (response.status < 200 || response.status >= 300) return;
9574
+ const credits = (Array.isArray(response.body?.credits) ? response.body.credits : []).filter(
9575
+ isCreditWire
9576
+ );
9577
+ const primary = isCreditWire(response.body?.credit) ? response.body.credit : void 0;
9578
+ if (!primary && credits.length === 0) return;
9579
+ recordBalanceResponse({
9580
+ endpoint: entry.endpoint,
9581
+ callerPubkey: pubkey,
9582
+ credits,
9583
+ ...primary ? { primary } : {},
9584
+ sequenced: false
9585
+ });
9586
+ }
9587
+ function creditOperationDomain(domain) {
9588
+ const jobSuffix = "/v1/job";
9589
+ if (!domain.path.endsWith(jobSuffix)) return null;
9590
+ const mount = domain.path.slice(0, -jobSuffix.length);
9591
+ return {
9592
+ audience: domain.audience,
9593
+ method: "POST",
9594
+ path: `${mount}/v1/credit`,
9595
+ capability: null
9596
+ };
9597
+ }
9598
+ function isCreditWire(value) {
9599
+ if (typeof value !== "object" || value === null) return false;
9600
+ const credit = value;
9601
+ return typeof credit.credit_id === "string" && typeof credit.remaining_micro === "number";
9602
+ }
9603
+ function jobRecordFromEntry(entry, jobId, body, feedbackClaim) {
9604
+ const ctx = entry.context;
9605
+ return {
9606
+ id: jobId,
9607
+ endpoint: entry.endpoint,
9608
+ ...ctx?.dvm_id ? { dvmId: ctx.dvm_id } : {},
9609
+ ...feedbackClaim ? { feedbackClaim } : {},
9610
+ ...ctx?.capability ? { capability: ctx.capability } : {},
9611
+ status: "submitted",
9612
+ submittedAt: Date.parse(entry.created_at) || Date.now(),
9613
+ paymentMethod: "cashu",
9614
+ ...ctx?.pinned_mint ? { pinnedMint: ctx.pinned_mint } : {},
9615
+ ...ctx?.policy ? { policy: ctx.policy } : {},
9616
+ ...ctx?.strict_per_call ? { strictPerCall: true } : {},
9617
+ ...ctx?.max_cashu_fee_sats !== void 0 ? { maxCashuFeeSats: ctx.max_cashu_fee_sats } : {},
9618
+ // the per-job token an anonymous caller needs on every later read.
9619
+ ...typeof body?.job_token === "string" ? { jobToken: body.job_token } : {}
9620
+ };
9621
+ }
9622
+ function mutatesWallet(outcome) {
9623
+ if (outcome.kind === "reclaim_skipped") {
9624
+ return outcome.entry.reclaim_error !== outcome.reason || (outcome.entry.reclaim_terminal ?? false) !== outcome.terminal;
9625
+ }
9626
+ return outcome.kind === "shipped" || outcome.kind === "already_accepted" || outcome.kind === "abandoned" || outcome.kind === "pruned" || outcome.kind === "swap_restored" || outcome.kind === "swap_reverted" || outcome.kind === "still_pending" || outcome.kind === "reclaimed";
9627
+ }
9628
+ function applyOutcome(wallet, outcome, now) {
9629
+ const drop = () => ({
9630
+ ...wallet,
9631
+ pending_submissions: wallet.pending_submissions.filter(
9632
+ (s) => s.request_id !== outcome.entry.request_id
9633
+ )
9634
+ });
9635
+ if (outcome.kind === "shipped" || outcome.kind === "already_accepted") {
9636
+ const recentSpend = {
9637
+ request_id: outcome.entry.request_id,
9638
+ dvm_endpoint: outcome.entry.endpoint,
9639
+ mint: outcome.entry.mint,
9640
+ amount_sats: outcome.entry.amount_sats,
9641
+ signed_at_ms: now()
9642
+ };
9643
+ const dropped = drop();
9644
+ return {
9645
+ ...dropped,
9646
+ recent_spends: [...dropped.recent_spends, recentSpend].slice(-RECENT_SPENDS_CAP)
9647
+ };
9648
+ }
9649
+ if (outcome.kind === "abandoned" || outcome.kind === "pruned") {
9650
+ return drop();
9651
+ }
9652
+ if (outcome.kind === "swap_restored") {
9653
+ const swapping = outcome.entry.swapping;
9654
+ if (!swapping) return wallet;
9655
+ const trackedKeys = new Set(
9656
+ [...swapping.input_proofs, ...swapping.unselected_proofs].map((proof) => proofKey(proof))
9657
+ );
9658
+ const boundContext = bindCashuTokenToSubmissionContext(
9659
+ outcome.entry.context,
9660
+ outcome.cashuToken
9661
+ );
9662
+ return {
9663
+ ...wallet,
9664
+ proofs: [
9665
+ ...wallet.proofs.filter((proof) => !trackedKeys.has(proofKey(proof))),
9666
+ ...swapping.unselected_proofs.map((proof) => ({
9667
+ ...proof,
9668
+ status: "valid",
9669
+ in_flight_until_ms: void 0
9670
+ })),
9671
+ ...outcome.keep
9672
+ ],
9673
+ pending_submissions: wallet.pending_submissions.map(
9674
+ (submission) => submission.request_id === outcome.entry.request_id ? {
9675
+ ...submission,
9676
+ output_proofs: outcome.outputs,
9677
+ cashu_token: outcome.cashuToken,
9678
+ swapping: void 0,
9679
+ ...boundContext ? { context: boundContext } : {}
9680
+ } : submission
9681
+ )
9682
+ };
9683
+ }
9684
+ if (outcome.kind === "swap_reverted") {
9685
+ const swapping = outcome.entry.swapping;
9686
+ if (!swapping) return drop();
9687
+ const trackedKeys = new Set(
9688
+ [...swapping.input_proofs, ...swapping.unselected_proofs].map((proof) => proofKey(proof))
9689
+ );
9690
+ const reverted = revertInFlight(wallet, trackedKeys);
9691
+ return {
9692
+ ...reverted,
9693
+ pending_submissions: reverted.pending_submissions.filter(
9694
+ (submission) => submission.request_id !== outcome.entry.request_id
9695
+ )
9696
+ };
9697
+ }
9698
+ if (outcome.kind === "reclaimed") {
9699
+ const dropped = drop();
9700
+ const credited = { ...dropped, proofs: [...dropped.proofs, ...outcome.outputs] };
9701
+ if (outcome.spent_sats <= 0) return credited;
9702
+ const partialSpend = {
9703
+ request_id: outcome.entry.request_id,
9704
+ dvm_endpoint: outcome.entry.endpoint,
9705
+ mint: outcome.entry.mint,
9706
+ amount_sats: outcome.spent_sats,
9707
+ signed_at_ms: now()
9708
+ };
9709
+ return {
9710
+ ...credited,
9711
+ recent_spends: [...credited.recent_spends, partialSpend].slice(-RECENT_SPENDS_CAP)
9712
+ };
9713
+ }
9714
+ if (outcome.kind === "still_pending") {
9715
+ return {
9716
+ ...wallet,
9717
+ pending_submissions: wallet.pending_submissions.map(
9718
+ (s) => s.request_id === outcome.entry.request_id ? {
9719
+ ...s,
9720
+ attempts: (s.attempts ?? 0) + 1,
9721
+ last_attempt_at: new Date(now()).toISOString()
9722
+ } : s
9723
+ )
9724
+ };
9725
+ }
9726
+ if (outcome.kind === "reclaim_skipped") {
9727
+ return {
9728
+ ...wallet,
9729
+ pending_submissions: wallet.pending_submissions.map(
9730
+ (s) => s.request_id === outcome.entry.request_id ? { ...s, reclaim_error: outcome.reason, reclaim_terminal: outcome.terminal } : s
9731
+ )
9732
+ };
9074
9733
  }
9075
- return { ...init2, headers: record };
9734
+ return wallet;
9076
9735
  }
9077
- var nativeFetch = globalThis.fetch;
9078
- async function readBoundedBody(response, limit) {
9079
- if (!response.body) return "";
9080
- const reader = response.body.getReader();
9081
- const decoder = new TextDecoder();
9082
- let size = 0;
9083
- let body = "";
9084
- try {
9085
- for (; ; ) {
9086
- const { done, value } = await reader.read();
9087
- if (done) return body + decoder.decode();
9088
- size += value.byteLength;
9089
- if (size > limit) {
9090
- await reader.cancel();
9091
- return void 0;
9736
+ function ageMs(entry, nowMs) {
9737
+ const created = Date.parse(entry.created_at);
9738
+ if (Number.isNaN(created)) return Number.POSITIVE_INFINITY;
9739
+ return nowMs - created;
9740
+ }
9741
+ function errorText(err) {
9742
+ return err instanceof Error ? err.message : String(err);
9743
+ }
9744
+ function createDefaultHttpPost(fetchImpl) {
9745
+ return async function defaultHttpPost(req) {
9746
+ let res;
9747
+ try {
9748
+ res = await fetchImpl(req.url, { method: "POST", headers: req.headers, body: req.body });
9749
+ } catch (err) {
9750
+ if (err instanceof DvmError) throw err;
9751
+ throw new DvmError(
9752
+ "provider_unreachable",
9753
+ `Could not reach ${req.url}: ${err instanceof Error ? err.message : String(err)}`,
9754
+ "Retry once the DVM is reachable again."
9755
+ );
9756
+ }
9757
+ let body;
9758
+ try {
9759
+ body = await res.json();
9760
+ } catch {
9761
+ body = null;
9762
+ }
9763
+ const feedbackClaim = res.headers.get(ROUTER_FEEDBACK_CLAIM_HEADER) ?? void 0;
9764
+ return { status: res.status, body, ...feedbackClaim ? { feedbackClaim } : {} };
9765
+ };
9766
+ }
9767
+
9768
+ // src/lib/agent-wallet-retry.ts
9769
+ var TRANSIENT_PAYMENT_BACKOFF_MS = [250, 500, 1e3, 2e3, 4e3];
9770
+ var TRANSIENT_PAYMENT_CODES = /* @__PURE__ */ new Set(["proof_pending", "mint_unreachable"]);
9771
+ function defaultSleep(ms) {
9772
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
9773
+ }
9774
+ var TRANSPORT_FAILURE_CODES = /* @__PURE__ */ new Set(["timeout", "provider_unreachable"]);
9775
+ async function withAgentWalletPaymentRetry(args) {
9776
+ const { attempt, intendedLockPubkey, refetchInfo } = args;
9777
+ const sleep = args.sleep ?? defaultSleep;
9778
+ let rotationRetried = false;
9779
+ let transportRetried = false;
9780
+ let pendingAttempt = 0;
9781
+ for (; ; ) {
9782
+ try {
9783
+ return await attempt();
9784
+ } catch (err) {
9785
+ if (!(err instanceof DvmError)) throw err;
9786
+ if (args.retryTransportFailureOnce && TRANSPORT_FAILURE_CODES.has(err.code) && !transportRetried) {
9787
+ transportRetried = true;
9788
+ continue;
9092
9789
  }
9093
- body += decoder.decode(value, { stream: true });
9790
+ if (TRANSIENT_PAYMENT_CODES.has(err.code)) {
9791
+ if (pendingAttempt >= TRANSIENT_PAYMENT_BACKOFF_MS.length) {
9792
+ throw err;
9793
+ }
9794
+ await sleep(TRANSIENT_PAYMENT_BACKOFF_MS[pendingAttempt]);
9795
+ pendingAttempt += 1;
9796
+ continue;
9797
+ }
9798
+ if (err.code === "wrong_lock_pubkey") {
9799
+ if (rotationRetried) {
9800
+ throw new DvmError(
9801
+ "payment_lock_pubkey_stale",
9802
+ "DVM rejected proofs after a rotation refetch \u2014 the swap target is no longer advertised.",
9803
+ "Wallet retains the locked outputs as a pending_submission for manual recovery."
9804
+ );
9805
+ }
9806
+ let refreshed;
9807
+ try {
9808
+ refreshed = await refetchInfo();
9809
+ } catch {
9810
+ throw err;
9811
+ }
9812
+ const target = intendedLockPubkey.toLowerCase();
9813
+ const matches = (refreshed.cashu?.lock_pubkeys ?? []).some(
9814
+ (pk) => pk.toLowerCase() === target
9815
+ );
9816
+ if (!matches) {
9817
+ throw new DvmError(
9818
+ "payment_lock_pubkey_stale",
9819
+ "DVM has rotated past the lock pubkey our outputs were swapped to.",
9820
+ "Wallet retains the locked outputs as a pending_submission for manual recovery."
9821
+ );
9822
+ }
9823
+ rotationRetried = true;
9824
+ continue;
9825
+ }
9826
+ throw err;
9094
9827
  }
9095
- } catch {
9096
- return void 0;
9097
- } finally {
9098
- reader.releaseLock();
9099
9828
  }
9100
9829
  }
9101
- var MAX_COMPATIBILITY_BODY_BYTES = 16384;
9102
9830
 
9103
9831
  // src/lib/mint-pin.ts
9104
9832
  function applyMintPin(advertised, pinnedMint) {
@@ -9277,7 +10005,8 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
9277
10005
  }
9278
10006
  }
9279
10007
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
9280
- const { loadX402Wallet: loadX402Wallet2, tryX402Payment: tryX402Payment2 } = await import("./internal-INUTGTXQ.js");
10008
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RPPUCQUR.js");
10009
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-IDO4IAXG.js");
9281
10010
  const wallet = loadX402Wallet2();
9282
10011
  if (wallet) {
9283
10012
  let proof;
@@ -10458,7 +11187,7 @@ var HttpsTransport = class {
10458
11187
  captureTraceId(res);
10459
11188
  const tempoTransactionHash = await tempoTransactionHashFromResponse(res);
10460
11189
  if (!res.ok) {
10461
- const mppChallenges = res.status === 402 && res.headers.get("WWW-Authenticate") ? (await import("./dist-GKCEIY2A.js")).Challenge.fromHeadersList(res.headers) : [];
11190
+ const mppChallenges = res.status === 402 && res.headers.get("WWW-Authenticate") ? (await import("./dist-23E7OOCA.js")).Challenge.fromHeadersList(res.headers) : [];
10462
11191
  assertConfiguredTempoChallengeNetwork(mppChallenges, ["charge", "session"]);
10463
11192
  const text = await res.text();
10464
11193
  const parsed = parseJsonObject(text);
@@ -10711,7 +11440,7 @@ var HttpsTransport = class {
10711
11440
  "Check the DVM's `/v1/info` for advertised payment methods."
10712
11441
  );
10713
11442
  }
10714
- const { Challenge } = await import("./dist-GKCEIY2A.js");
11443
+ const { Challenge } = await import("./dist-23E7OOCA.js");
10715
11444
  return Challenge.fromHeadersList(res.headers);
10716
11445
  }
10717
11446
  close() {
@@ -10721,7 +11450,7 @@ async function tempoTransactionHashFromResponse(res) {
10721
11450
  const encoded = res.headers.get("Payment-Receipt");
10722
11451
  if (!encoded) return void 0;
10723
11452
  try {
10724
- const { Receipt } = await import("./dist-GKCEIY2A.js");
11453
+ const { Receipt } = await import("./dist-23E7OOCA.js");
10725
11454
  const receipt = Receipt.deserialize(encoded);
10726
11455
  if (receipt.method !== "tempo") return void 0;
10727
11456
  const extension = receipt;
@@ -10984,7 +11713,7 @@ async function paymentHeaders(payment) {
10984
11713
  if (payment?.mppCredentialRaw) {
10985
11714
  headers.Authorization = payment.mppCredentialRaw;
10986
11715
  } else if (payment?.mppCredential) {
10987
- const { Credential } = await import("./dist-GKCEIY2A.js");
11716
+ const { Credential } = await import("./dist-23E7OOCA.js");
10988
11717
  headers.Authorization = Credential.serialize(payment.mppCredential);
10989
11718
  }
10990
11719
  return headers;
@@ -11858,13 +12587,14 @@ async function confirmRollback(stored, preview, opts) {
11858
12587
  async function withStrandingChecked(removing, commit) {
11859
12588
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
11860
12589
  if (leaving.has("tempo")) {
11861
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./internal-INUTGTXQ.js");
12590
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-HS2NIFKT.js");
11862
12591
  await assertTempoWalletIdle2("disconnect");
11863
12592
  }
11864
12593
  if (!leaving.has("x402")) return commit();
11865
- const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-INUTGTXQ.js");
11866
- const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./internal-INUTGTXQ.js");
11867
- const { ensureAddress: ensureAddress2, loadX402Wallet: loadX402Wallet2 } = await import("./internal-INUTGTXQ.js");
12594
+ const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-7FXJTFBU.js");
12595
+ const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-LRS3IBQL.js");
12596
+ const { ensureAddress: ensureAddress2 } = await import("./internal-7FXJTFBU.js");
12597
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RPPUCQUR.js");
11868
12598
  return withX402ChannelLock2(async () => {
11869
12599
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
11870
12600
  if (unsettled.length > 0) {
@@ -16367,61 +17097,480 @@ function placeholderFor(prop) {
16367
17097
  }
16368
17098
  }
16369
17099
 
16370
- // src/lib/wallet-rail-copy.ts
16371
- function rpcEndpointSuffix(rail) {
16372
- const url = rail.details?.rpc_url;
16373
- return typeof url === "string" && url.length > 0 ? ` via ${url}` : "";
17100
+ // src/lib/wallet-rail-copy.ts
17101
+ function rpcEndpointSuffix(rail) {
17102
+ const url = rail.details?.rpc_url;
17103
+ return typeof url === "string" && url.length > 0 ? ` via ${url}` : "";
17104
+ }
17105
+ function rpcEndpointLine(rail) {
17106
+ const url = rail.details?.rpc_url;
17107
+ if (typeof url !== "string" || url.length === 0) return null;
17108
+ const source = rail.details?.rpc_source === "override" ? rpcOverrideEnvVar(rail.rail) : null;
17109
+ return `read from ${url} (${source ?? "bundled default"})`;
17110
+ }
17111
+ function unreachableRailDisplay(rail) {
17112
+ if (rail.error?.code === "x402_unsupported_network") {
17113
+ const network = rail.details?.network;
17114
+ return typeof network === "string" ? `x402 rail is configured for ${network}, a chain it can't settle on.` : "x402 rail is configured for a chain it can't settle on.";
17115
+ }
17116
+ return nwcRejectionDisplay(rail) ?? `${railLabelAtSentenceStart(probeRailLabel(rail.rail))} rail is configured but not reachable.`;
17117
+ }
17118
+ function nwcRejectionDisplay(rail) {
17119
+ switch (rail.error?.code) {
17120
+ case "float_unauthorized":
17121
+ return "The Lightning wallet no longer recognises this connection \u2014 it looks revoked or expired.";
17122
+ case "float_connection_restricted":
17123
+ return "The Lightning wallet recognises this connection but won't let it do what the agent needs.";
17124
+ default:
17125
+ return null;
17126
+ }
17127
+ }
17128
+ function unreachableRailHint(rail) {
17129
+ if (rail.error?.hint) return rail.error.hint;
17130
+ switch (rail.rail) {
17131
+ case "lightning":
17132
+ return "Re-run 'dvm wallet connect' with the connection string piped in.";
17133
+ case "cashu":
17134
+ return "Check mint health with 'dvm wallet mint-health'.";
17135
+ case "x402":
17136
+ return "Check DVM_X402_RPC_URL, or ensure viem is installed.";
17137
+ case "tempo":
17138
+ return "Check DVM_TEMPO_RPC_URL, or ensure viem is installed.";
17139
+ }
17140
+ }
17141
+ function tempoKeyImportRoutes(opts) {
17142
+ const force = opts.replacingConnectedKey ? " --force" : "";
17143
+ return `'dvm wallet tempo-connect --key-file <path>${force}', or DVM_TEMPO_KEY=<key> dvm wallet tempo-connect${force}`;
17144
+ }
17145
+ var TEMPO_EXIT_KEY_MISSING_HINT = `Reconnect that exact key (${tempoKeyImportRoutes({ replacingConnectedKey: false })}) before attempting an on-chain exit.`;
17146
+ function rpcOverrideEnvVar(rail) {
17147
+ switch (rail) {
17148
+ case "x402":
17149
+ return "DVM_X402_RPC_URL";
17150
+ case "tempo":
17151
+ return "DVM_TEMPO_RPC_URL";
17152
+ default:
17153
+ return null;
17154
+ }
17155
+ }
17156
+ function tempoExitRecoveryError(error, connected) {
17157
+ let hint;
17158
+ if (error.code === "tempo_wallet_mismatch") {
17159
+ hint = `Reconnect the key that opened this channel (${tempoKeyImportRoutes({ replacingConnectedKey: true })}), or use --abandon to retire this other wallet's local record without reading the chain or broadcasting.`;
17160
+ } else if (error.code === "tempo_wallet_missing") {
17161
+ hint = TEMPO_EXIT_KEY_MISSING_HINT;
17162
+ } else if (error.code === "tempo_channel_on_chain" && !connected) {
17163
+ hint = `Reconnect the key that opened this channel (${tempoKeyImportRoutes({ replacingConnectedKey: false })}) before attempting an on-chain exit.`;
17164
+ } else {
17165
+ return error;
17166
+ }
17167
+ return new DvmError(error.code, error.message, hint, error.data, error.display);
17168
+ }
17169
+
17170
+ // src/lib/funding.ts
17171
+ var SAFE_FUNDING_ADVISORY = {
17172
+ display: "Start small \u2014 fund a few days' worth and top up as confidence grows",
17173
+ description: "There's no need to fund a large amount up front. A few days of expected spend is enough to get going; top up once you've seen how your agent uses the wallet.",
17174
+ hint: "Funding lightly is the safest posture across all rails. A connected Lightning wallet lets the agent top itself up on its own \u2014 set a spending cap on the wallet (it's the one the agent can't change) and 'dvm budget set' caps here."
17175
+ };
17176
+ function detectWalletType(config, cashuMints) {
17177
+ if (!config && cashuMints.length === 0) return null;
17178
+ if (config?.nwcUri) return "nwc";
17179
+ if (cashuMints.length > 0) return "cashu";
17180
+ return null;
17181
+ }
17182
+ function getFundingGuidance(opts) {
17183
+ const fundingOptions = (opts.balanceMsats ?? 0) > 0 ? [] : opts.walletType === "nwc" ? nwcOptions() : cashuOptions(opts.cashuMints, opts.hasLightningBackend ?? false);
17184
+ return { fundingOptions, advisory: SAFE_FUNDING_ADVISORY };
17185
+ }
17186
+ function printFundingGuidance(result) {
17187
+ info(`
17188
+ ${result.advisory.display}`);
17189
+ info(` ${result.advisory.description}`);
17190
+ info(` ${result.advisory.hint}`);
17191
+ if (result.fundingOptions.length === 0) return;
17192
+ info("\nFund your wallet:");
17193
+ for (let i = 0; i < result.fundingOptions.length; i++) {
17194
+ const o = result.fundingOptions[i];
17195
+ info(` ${i + 1}. ${o.display}`);
17196
+ if (o.command) info(` ${o.command}`);
17197
+ info(` ${o.description}`);
17198
+ }
17199
+ }
17200
+ function nwcOptions() {
17201
+ return [
17202
+ {
17203
+ method: "external",
17204
+ display: "Add funds in your wallet app",
17205
+ description: "The connected Lightning wallet is the agent's float \u2014 the pot it tops itself up from. Money goes in through the wallet app itself (Alby Hub, Coinos, etc.); dvm spends from it but never fills it.",
17206
+ hint: "Receive a payment in your wallet app, then run 'dvm wallet fund <amount>' \u2014 the agent will move sats across on its own."
17207
+ }
17208
+ ];
17209
+ }
17210
+ function cashuOptions(mints, hasLightningBackend) {
17211
+ const exampleMint = mints && mints.length > 0 ? mints[0] : void 0;
17212
+ const hasMints = exampleMint !== void 0;
17213
+ const mintCommand = exampleMint ? `dvm wallet fund <sats> --mint ${exampleMint}` : "dvm wallet fund <sats> --mint <url>";
17214
+ const mintOption = {
17215
+ method: "cashu-mint",
17216
+ display: "Mint Cashu tokens via Lightning",
17217
+ command: mintCommand,
17218
+ description: hasMints ? "Pays a Lightning invoice from your Lightning wallet and mints matching P2PK-locked Cashu tokens into the agent wallet. Cashu mints are custodial \u2014 only deposit what you're willing to lose." : "After adding a mint above, pays a Lightning invoice from your Lightning wallet and mints matching P2PK-locked Cashu tokens into the agent wallet. Cashu mints are custodial \u2014 only deposit what you're willing to lose.",
17219
+ hint: hasLightningBackend ? "Requires a Lightning wallet \u2014 you have one configured." : "Requires a Lightning wallet \u2014 connect one with 'dvm wallet connect' first (pipe the connection string in, or pass --file <path>).",
17220
+ ...hasMints ? { mints } : {}
17221
+ };
17222
+ const receiveTokenOption = {
17223
+ method: "cashu-receive-token",
17224
+ display: "Receive an existing Cashu token",
17225
+ command: "dvm wallet receive-token <cashu-token>",
17226
+ description: "Claim a pre-minted Cashu token (e.g. from a friend or a faucet) into the agent wallet. The token is re-locked to your wallet's key so it's spendable.",
17227
+ hint: "Tokens are single-use; a token locked to a third party can't be claimed.",
17228
+ ...hasMints ? { mints } : {}
17229
+ };
17230
+ const options = [];
17231
+ if (!hasMints) {
17232
+ options.push({
17233
+ method: "cashu-add-mint",
17234
+ display: "Add a Cashu mint",
17235
+ command: "dvm wallet mint-add <url>",
17236
+ description: "Cashu mints hold your tokens. Add one before you can mint or receive tokens \u2014 'dvm wallet mint-list' shows recommended mints. Cashu mints are custodial \u2014 only deposit what you're willing to lose.",
17237
+ hint: "Recommended mints: see 'dvm wallet mint-list' for trusted options."
17238
+ });
17239
+ }
17240
+ if (hasLightningBackend) {
17241
+ options.push(mintOption, receiveTokenOption);
17242
+ } else {
17243
+ options.push(receiveTokenOption, mintOption);
17244
+ }
17245
+ return options;
17246
+ }
17247
+
17248
+ // src/lib/wallet-agent/mint-inventory.ts
17249
+ async function loadConfiguredMints() {
17250
+ const wallet = loadAgentWallet();
17251
+ if (!wallet) return [];
17252
+ const config = loadConfig();
17253
+ const legacy = config?.cashuMints ?? [];
17254
+ if (legacy.length === 0 || wallet.mints.length > 0) {
17255
+ return loadWalletConfiguredMints();
17256
+ }
17257
+ return withWalletLock(async () => {
17258
+ const fresh = loadAgentWallet() ?? wallet;
17259
+ if (fresh.mints.length > 0) return fresh.mints;
17260
+ const merged = dedupe(legacy);
17261
+ saveAgentWallet({ ...fresh, mints: merged });
17262
+ await updateConfig({
17263
+ reason: "cashu_mints_migration",
17264
+ patch: () => ({ unset: ["cashuMints"] })
17265
+ });
17266
+ return merged;
17267
+ });
17268
+ }
17269
+ function buildDisplayMintInventory(wallet) {
17270
+ const entries = [];
17271
+ const seen = /* @__PURE__ */ new Set();
17272
+ for (const url of wallet.mints) {
17273
+ if (seen.has(url)) continue;
17274
+ seen.add(url);
17275
+ entries.push({ url, source: "configured" });
17276
+ }
17277
+ for (const proof of wallet.proofs) {
17278
+ if (seen.has(proof.mint)) continue;
17279
+ seen.add(proof.mint);
17280
+ entries.push({ url: proof.mint, source: "proofs" });
17281
+ }
17282
+ for (const pending4 of wallet.pending_mints) {
17283
+ if (seen.has(pending4.mint)) continue;
17284
+ seen.add(pending4.mint);
17285
+ entries.push({ url: pending4.mint, source: "pending" });
17286
+ }
17287
+ if (entries.length === 0) {
17288
+ entries.push({ url: DEFAULT_AGENT_MINT_URL, source: "default" });
17289
+ }
17290
+ return entries;
17291
+ }
17292
+ function dedupe(values) {
17293
+ const seen = /* @__PURE__ */ new Set();
17294
+ const out = [];
17295
+ for (const v of values) {
17296
+ if (seen.has(v)) continue;
17297
+ seen.add(v);
17298
+ out.push(v);
17299
+ }
17300
+ return out;
17301
+ }
17302
+
17303
+ // src/lib/wallet-probe.ts
17304
+ async function probeWallets(opts = {}) {
17305
+ const timeoutMs = opts.timeoutMs ?? 5e3;
17306
+ const config = loadConfig();
17307
+ const cashuMints = await loadConfiguredMints();
17308
+ const walletType = detectWalletType(config, cashuMints);
17309
+ const rate = await fetchBtcUsdRate().catch(() => null);
17310
+ const probes = await Promise.allSettled([
17311
+ probeLightning(timeoutMs),
17312
+ probeX402(config?.x402, timeoutMs),
17313
+ probeMpp(config?.tempo, timeoutMs)
17314
+ ]);
17315
+ const rails = [];
17316
+ const cashuRow = probeCashu(cashuMints);
17317
+ if (cashuRow) rails.push(cashuRow);
17318
+ for (const result of probes) {
17319
+ if (result.status === "fulfilled" && result.value !== null) {
17320
+ rails.push(result.value);
17321
+ }
17322
+ }
17323
+ const totalLnAndCashuMsats = rails.filter((r) => r.rail === "lightning" || r.rail === "cashu").reduce((sum, r) => sum + (r.balanceMsats ?? 0), 0);
17324
+ return { walletType, rate, rails, totalLnAndCashuMsats, cashuMints };
16374
17325
  }
16375
- function rpcEndpointLine(rail) {
16376
- const url = rail.details?.rpc_url;
16377
- if (typeof url !== "string" || url.length === 0) return null;
16378
- const source = rail.details?.rpc_source === "override" ? rpcOverrideEnvVar(rail.rail) : null;
16379
- return `read from ${url} (${source ?? "bundled default"})`;
17326
+ async function probeLightning(timeoutMs) {
17327
+ let float;
17328
+ try {
17329
+ float = loadFloat();
17330
+ } catch (err) {
17331
+ const mapped = toFloatError(err);
17332
+ return {
17333
+ rail: "lightning",
17334
+ configured: true,
17335
+ reachable: false,
17336
+ error: {
17337
+ code: mapped.code,
17338
+ message: mapped.message,
17339
+ ...mapped.hint ? { hint: mapped.hint } : {},
17340
+ ...refusalFields(mapped.data)
17341
+ }
17342
+ };
17343
+ }
17344
+ if (!float) return null;
17345
+ const probe = await withTimeout(probeFloat({ float, timeoutMs }), timeoutMs, "lightning").catch(
17346
+ (err) => ({
17347
+ reachable: false,
17348
+ methods: [],
17349
+ canPay: false,
17350
+ canInvoice: false,
17351
+ canReconcile: false,
17352
+ error: {
17353
+ code: "float_wallet_offline",
17354
+ message: err instanceof Error ? err.message : String(err),
17355
+ display: "Your Lightning wallet didn't answer in time."
17356
+ }
17357
+ })
17358
+ );
17359
+ const details = {
17360
+ alias: probe.alias ?? null,
17361
+ methods: probe.methods,
17362
+ can_pay: probe.canPay,
17363
+ can_reconcile: probe.canReconcile,
17364
+ stated_budget: float.statedBudget ?? null
17365
+ };
17366
+ if (probe.walletReportedBudget) details.wallet_reported_budget = probe.walletReportedBudget;
17367
+ if (probe.reachable && probe.balanceMsats === void 0) details.balance_unknown = true;
17368
+ if (!probe.reachable) {
17369
+ return {
17370
+ rail: "lightning",
17371
+ configured: true,
17372
+ reachable: false,
17373
+ details,
17374
+ error: {
17375
+ code: probe.error?.code ?? "float_wallet_offline",
17376
+ message: probe.error?.message ?? "The Lightning wallet did not respond.",
17377
+ ...probe.error?.hint ? { hint: probe.error.hint } : {},
17378
+ ...refusalFields(probe.error?.data)
17379
+ }
17380
+ };
17381
+ }
17382
+ return {
17383
+ rail: "lightning",
17384
+ configured: true,
17385
+ reachable: true,
17386
+ ...probe.balanceMsats === void 0 ? {} : { balanceMsats: probe.balanceMsats },
17387
+ details
17388
+ };
16380
17389
  }
16381
- function unreachableRailDisplay(rail) {
16382
- if (rail.error?.code === "x402_unsupported_network") {
16383
- const network = rail.details?.network;
16384
- return typeof network === "string" ? `x402 rail is configured for ${network}, a chain it can't settle on.` : "x402 rail is configured for a chain it can't settle on.";
17390
+ function refusalFields(data) {
17391
+ const text = (key) => {
17392
+ const value = data?.[key];
17393
+ return typeof value === "string" ? value : void 0;
17394
+ };
17395
+ const method = text("method");
17396
+ const restriction = text("restriction");
17397
+ const walletMessage = text("wallet_message");
17398
+ return {
17399
+ ...method ? { method } : {},
17400
+ ...restriction ? { restriction } : {},
17401
+ ...walletMessage ? { wallet_message: walletMessage } : {}
17402
+ };
17403
+ }
17404
+ function probeCashu(cashuMints) {
17405
+ const configured = (cashuMints?.length ?? 0) > 0;
17406
+ const byMint = getBalanceByMint();
17407
+ const balanceMsats = [...byMint.values()].reduce((sum, amount) => sum + amount, 0);
17408
+ if (!configured && balanceMsats === 0) return null;
17409
+ const byMintObj = {};
17410
+ for (const url of cashuMints ?? []) {
17411
+ byMintObj[url] = byMint.get(url) ?? 0;
16385
17412
  }
16386
- return nwcRejectionDisplay(rail) ?? `${railLabelAtSentenceStart(probeRailLabel(rail.rail))} rail is configured but not reachable.`;
17413
+ for (const [url, msats] of byMint) {
17414
+ if (!(url in byMintObj)) byMintObj[url] = msats;
17415
+ }
17416
+ return {
17417
+ rail: "cashu",
17418
+ configured,
17419
+ reachable: true,
17420
+ balanceMsats,
17421
+ details: { byMint: byMintObj }
17422
+ };
16387
17423
  }
16388
- function nwcRejectionDisplay(rail) {
16389
- switch (rail.error?.code) {
16390
- case "float_unauthorized":
16391
- return "The Lightning wallet no longer recognises this connection \u2014 it looks revoked or expired.";
16392
- case "float_connection_restricted":
16393
- return "The Lightning wallet recognises this connection but won't let it do what the agent needs.";
16394
- default:
16395
- return null;
17424
+ async function probeX402(x402, timeoutMs) {
17425
+ if (!x402) return null;
17426
+ let network;
17427
+ let address;
17428
+ try {
17429
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RPPUCQUR.js");
17430
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-7FXJTFBU.js");
17431
+ const wallet = loadX402Wallet2();
17432
+ if (!wallet) {
17433
+ const storedKey = x402.privateKey;
17434
+ const missing = storedKey === void 0 || storedKey === "";
17435
+ return {
17436
+ rail: "x402",
17437
+ configured: true,
17438
+ reachable: false,
17439
+ ...x402.network ? { details: { network: x402.network } } : {},
17440
+ error: missing ? {
17441
+ code: "x402_key_missing",
17442
+ message: "x402 config is present but privateKey is missing or empty.",
17443
+ hint: "Run 'dvm wallet x402-connect' to create a wallet, or add --key-file <path> to import a key you already hold."
17444
+ } : {
17445
+ code: "x402_key_invalid",
17446
+ message: "x402 config contains a privateKey that is not a valid secp256k1 scalar.",
17447
+ hint: "Run 'dvm wallet x402-connect' to create a replacement wallet, or add --key-file <path> to import a valid key you already hold."
17448
+ }
17449
+ };
17450
+ }
17451
+ network = wallet.network;
17452
+ const w = await withTimeout(ensureAddress2(wallet), timeoutMs, "x402");
17453
+ address = w.address;
17454
+ const balance = await withTimeout(getX402Balance(w), timeoutMs, "x402");
17455
+ return {
17456
+ rail: "x402",
17457
+ configured: true,
17458
+ reachable: true,
17459
+ balanceUsdc: balance.usdc,
17460
+ details: {
17461
+ address: w.address,
17462
+ network: w.network,
17463
+ token: usdcContractByCaip2(w.network),
17464
+ ...rpcDetails(balance.rpcUrlRedacted, balance.rpcSource)
17465
+ }
17466
+ };
17467
+ } catch (err) {
17468
+ const details = { ...address ? { address } : {}, ...network ? { network } : {} };
17469
+ return {
17470
+ rail: "x402",
17471
+ configured: true,
17472
+ reachable: false,
17473
+ ...Object.keys(details).length > 0 ? { details } : {},
17474
+ error: classifyError("x402_unreachable", err)
17475
+ };
16396
17476
  }
16397
17477
  }
16398
- function unreachableRailHint(rail) {
16399
- if (rail.error?.hint) return rail.error.hint;
16400
- switch (rail.rail) {
16401
- case "lightning":
16402
- return "Re-run 'dvm wallet connect' with the connection string piped in.";
16403
- case "cashu":
16404
- return "Check mint health with 'dvm wallet mint-health'.";
16405
- case "x402":
16406
- return "Check DVM_X402_RPC_URL, or ensure viem is installed.";
16407
- case "tempo":
16408
- return "Check DVM_TEMPO_RPC_URL, or ensure viem is installed.";
17478
+ async function probeMpp(mpp, timeoutMs) {
17479
+ if (!mpp) return null;
17480
+ if (mpp.method === "tempo") {
17481
+ try {
17482
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-BA2LKR45.js");
17483
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-7FXJTFBU.js");
17484
+ const account = await connectedTempoAccount2();
17485
+ if (!account) {
17486
+ return {
17487
+ rail: "tempo",
17488
+ configured: true,
17489
+ reachable: false,
17490
+ error: {
17491
+ code: "tempo_key_missing",
17492
+ message: "Tempo config is present but apiKey is missing or not a private key.",
17493
+ hint: "Run 'dvm wallet tempo-connect' to generate a key, or add '--key-file <path>' to import one you already hold (DVM_TEMPO_KEY and piped stdin work too)."
17494
+ }
17495
+ };
17496
+ }
17497
+ try {
17498
+ const balance = await withTimeout(getTempoUsdcBalance3(account), timeoutMs, "tempo");
17499
+ return {
17500
+ rail: "tempo",
17501
+ configured: true,
17502
+ reachable: true,
17503
+ balanceUsdc: balance.usdc,
17504
+ details: {
17505
+ address: account.address,
17506
+ chain_id: balance.chainId,
17507
+ token: balance.tokenAddress,
17508
+ ...rpcDetails(balance.rpcUrlRedacted, balance.rpcSource)
17509
+ }
17510
+ };
17511
+ } catch (err) {
17512
+ return {
17513
+ rail: "tempo",
17514
+ configured: true,
17515
+ reachable: false,
17516
+ balanceUsdc: void 0,
17517
+ details: {
17518
+ address: account.address,
17519
+ chain_id: resolveTempoNetwork2(account.network ?? "mainnet").chainId,
17520
+ balance_unknown: true
17521
+ },
17522
+ error: classifyError("tempo_unreachable", err)
17523
+ };
17524
+ }
17525
+ } catch (err) {
17526
+ return {
17527
+ rail: "tempo",
17528
+ configured: true,
17529
+ reachable: false,
17530
+ error: classifyError("tempo_unavailable", err)
17531
+ };
17532
+ }
16409
17533
  }
17534
+ return {
17535
+ rail: "tempo",
17536
+ configured: true,
17537
+ reachable: false,
17538
+ error: { code: "tempo_unknown_method", message: `unknown Tempo method: ${mpp.method}` }
17539
+ };
16410
17540
  }
16411
- function tempoKeyImportRoutes(opts) {
16412
- const force = opts.replacingConnectedKey ? " --force" : "";
16413
- return `'dvm wallet tempo-connect --key-file <path>${force}', or DVM_TEMPO_KEY=<key> dvm wallet tempo-connect${force}`;
17541
+ function withTimeout(p, ms, rail) {
17542
+ return new Promise((resolve3, reject) => {
17543
+ const t = setTimeout(() => {
17544
+ reject(new Error(`${rail} probe timed out after ${ms}ms`));
17545
+ }, ms);
17546
+ p.then(
17547
+ (v) => {
17548
+ clearTimeout(t);
17549
+ resolve3(v);
17550
+ },
17551
+ (e) => {
17552
+ clearTimeout(t);
17553
+ reject(e instanceof Error ? e : new Error(String(e)));
17554
+ }
17555
+ );
17556
+ });
16414
17557
  }
16415
- var TEMPO_EXIT_KEY_MISSING_HINT = `Reconnect that exact key (${tempoKeyImportRoutes({ replacingConnectedKey: false })}) before attempting an on-chain exit.`;
16416
- function rpcOverrideEnvVar(rail) {
16417
- switch (rail) {
16418
- case "x402":
16419
- return "DVM_X402_RPC_URL";
16420
- case "tempo":
16421
- return "DVM_TEMPO_RPC_URL";
16422
- default:
16423
- return null;
17558
+ function rpcDetails(rpcUrlRedacted, rpcSource) {
17559
+ if (!rpcUrlRedacted) return {};
17560
+ return { rpc_url: rpcUrlRedacted, rpc_source: rpcSource };
17561
+ }
17562
+ function classifyError(code, err) {
17563
+ const message2 = err instanceof Error ? err.message : String(err);
17564
+ if (err instanceof DvmError) {
17565
+ return { code: err.code, message: message2, ...err.hint ? { hint: err.hint } : {} };
16424
17566
  }
17567
+ return { code, message: message2 };
17568
+ }
17569
+
17570
+ // src/lib/x402/asset.ts
17571
+ function x402WrongAssetHint(asset) {
17572
+ const wrongToken = asset.confusable ? `Another dollar on ${asset.networkLabel} \u2014 ${asset.confusable}, the legacy bridged dollar, or any other stablecoin \u2014 is a different contract and will never show up here, however much of it your wallet says you hold.` : `Another dollar on ${asset.networkLabel} is a different contract and will never show up here, however much of it your wallet says you hold.`;
17573
+ return `This rail reads only ${asset.label} (${asset.address}) on ${asset.networkLabel}. ${wrongToken} USDC on a different chain is invisible here too \u2014 this wallet reads ${asset.networkLabel} alone. If you funded the wrong one, swap it to ${asset.label} on ${asset.networkLabel}, or bridge the funds across to ${asset.networkLabel}; either way they land where this rail can spend them.`;
16425
17574
  }
16426
17575
 
16427
17576
  // src/lib/build-freshness.ts
@@ -16686,13 +17835,13 @@ function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
16686
17835
  const path = join5(dir, name);
16687
17836
  const stat = statSync5(path);
16688
17837
  if (!stat.isFile()) return null;
16689
- const ageMs = Math.max(0, nowMs - stat.mtimeMs);
17838
+ const ageMs2 = Math.max(0, nowMs - stat.mtimeMs);
16690
17839
  return {
16691
17840
  path,
16692
17841
  modifiedAt: stat.mtime.toISOString(),
16693
- ageMs,
16694
- ageDays: Math.floor(ageMs / (24 * 60 * 60 * 1e3)),
16695
- age: formatMnemonicBackupAge(ageMs)
17842
+ ageMs: ageMs2,
17843
+ ageDays: Math.floor(ageMs2 / (24 * 60 * 60 * 1e3)),
17844
+ age: formatMnemonicBackupAge(ageMs2)
16696
17845
  };
16697
17846
  }).filter((backup) => backup !== null).sort((a, b) => a.modifiedAt.localeCompare(b.modifiedAt));
16698
17847
  }
@@ -16712,8 +17861,8 @@ function describeMnemonicBackups(mnemonicFiles, nowMs = Date.now()) {
16712
17861
  }
16713
17862
  };
16714
17863
  }
16715
- function formatMnemonicBackupAge(ageMs) {
16716
- const minutes = Math.floor(ageMs / 6e4);
17864
+ function formatMnemonicBackupAge(ageMs2) {
17865
+ const minutes = Math.floor(ageMs2 / 6e4);
16717
17866
  if (minutes < 1) return "less than a minute old";
16718
17867
  if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"} old`;
16719
17868
  const hours = Math.floor(minutes / 60);
@@ -16800,16 +17949,16 @@ function describeSkippedReclaims(outcomes) {
16800
17949
  }
16801
17950
  function toView(entry, nowMs) {
16802
17951
  const createdMs = Date.parse(entry.created_at);
16803
- const ageMs = Number.isNaN(createdMs) ? Number.POSITIVE_INFINITY : nowMs - createdMs;
17952
+ const ageMs2 = Number.isNaN(createdMs) ? Number.POSITIVE_INFINITY : nowMs - createdMs;
16804
17953
  const attempts = entry.attempts ?? 0;
16805
17954
  const reclaimAt = reclaimAtMs(entry);
16806
- const state = deriveState(entry, ageMs, attempts, reclaimAt);
17955
+ const state = deriveState(entry, ageMs2, attempts, reclaimAt);
16807
17956
  return {
16808
17957
  request_id: entry.request_id,
16809
17958
  endpoint: entry.endpoint,
16810
17959
  mint: entry.mint,
16811
17960
  amount_sats: entry.amount_sats,
16812
- age_seconds: Number.isFinite(ageMs) ? Math.max(0, Math.round(ageMs / 1e3)) : null,
17961
+ age_seconds: Number.isFinite(ageMs2) ? Math.max(0, Math.round(ageMs2 / 1e3)) : null,
16813
17962
  attempts,
16814
17963
  state,
16815
17964
  at_risk: state !== "awaiting_swap",
@@ -16818,11 +17967,11 @@ function toView(entry, nowMs) {
16818
17967
  display: describe2(entry, state, reclaimAt, nowMs)
16819
17968
  };
16820
17969
  }
16821
- function deriveState(entry, ageMs, attempts, reclaimAt) {
17970
+ function deriveState(entry, ageMs2, attempts, reclaimAt) {
16822
17971
  if (entry.output_proofs.length === 0) {
16823
17972
  return entry.swapping ? "recovering_swap" : "awaiting_swap";
16824
17973
  }
16825
- const resumeOver = !isResumable(entry) || ageMs > RESUME_MAX_AGE_MS || attempts >= RESUME_MAX_ATTEMPTS;
17974
+ const resumeOver = !isResumable(entry) || ageMs2 > RESUME_MAX_AGE_MS || attempts >= RESUME_MAX_ATTEMPTS;
16826
17975
  if (resumeOver && reclaimAt !== null) {
16827
17976
  if (!entry.reclaim_error) return "reclaimable";
16828
17977
  return entry.reclaim_terminal ? "unreclaimable" : "reclaim_failed";
@@ -19038,7 +20187,7 @@ function postureSentence2(posture) {
19038
20187
  async function ensureDefaultIdentity() {
19039
20188
  return withIdentitiesLock(() => {
19040
20189
  if (identitiesFileExists()) return null;
19041
- const entry = generateIdentity();
20190
+ const entry = generateIdentity2();
19042
20191
  saveIdentities({
19043
20192
  version: IDENTITIES_VERSION,
19044
20193
  identities: { default: entry }
@@ -19057,7 +20206,7 @@ async function identityCreate(name, opts) {
19057
20206
  "Pass --force to overwrite, or pick a different name."
19058
20207
  );
19059
20208
  }
19060
- const fresh = generateIdentity();
20209
+ const fresh = generateIdentity2();
19061
20210
  file.identities[name] = fresh;
19062
20211
  saveIdentities(file);
19063
20212
  return fresh;
@@ -20972,7 +22121,7 @@ async function settleCreditAfterJob(args) {
20972
22121
  }
20973
22122
  }
20974
22123
  if (args.allowTopup !== false) {
20975
- const refill = args.refillPocket ?? (await import("./pocket-refill-K5T4LZF6.js")).refillPocketIfLow;
22124
+ const refill = args.refillPocket ?? (await import("./pocket-refill-J5OWRBXH.js")).refillPocketIfLow;
20976
22125
  await refill({ human: args.human }).catch(() => void 0);
20977
22126
  }
20978
22127
  }
@@ -25108,78 +26257,6 @@ function fmtBytes(bytes) {
25108
26257
  return `${(bytes / 1024).toFixed(1)} KB`;
25109
26258
  }
25110
26259
 
25111
- // src/lib/funding.ts
25112
- var SAFE_FUNDING_ADVISORY = {
25113
- display: "Start small \u2014 fund a few days' worth and top up as confidence grows",
25114
- description: "There's no need to fund a large amount up front. A few days of expected spend is enough to get going; top up once you've seen how your agent uses the wallet.",
25115
- hint: "Funding lightly is the safest posture across all rails. A connected Lightning wallet lets the agent top itself up on its own \u2014 set a spending cap on the wallet (it's the one the agent can't change) and 'dvm budget set' caps here."
25116
- };
25117
- function getFundingGuidance(opts) {
25118
- const fundingOptions = (opts.balanceMsats ?? 0) > 0 ? [] : opts.walletType === "nwc" ? nwcOptions() : cashuOptions(opts.cashuMints, opts.hasLightningBackend ?? false);
25119
- return { fundingOptions, advisory: SAFE_FUNDING_ADVISORY };
25120
- }
25121
- function printFundingGuidance(result) {
25122
- info(`
25123
- ${result.advisory.display}`);
25124
- info(` ${result.advisory.description}`);
25125
- info(` ${result.advisory.hint}`);
25126
- if (result.fundingOptions.length === 0) return;
25127
- info("\nFund your wallet:");
25128
- for (let i = 0; i < result.fundingOptions.length; i++) {
25129
- const o = result.fundingOptions[i];
25130
- info(` ${i + 1}. ${o.display}`);
25131
- if (o.command) info(` ${o.command}`);
25132
- info(` ${o.description}`);
25133
- }
25134
- }
25135
- function nwcOptions() {
25136
- return [
25137
- {
25138
- method: "external",
25139
- display: "Add funds in your wallet app",
25140
- description: "The connected Lightning wallet is the agent's float \u2014 the pot it tops itself up from. Money goes in through the wallet app itself (Alby Hub, Coinos, etc.); dvm spends from it but never fills it.",
25141
- hint: "Receive a payment in your wallet app, then run 'dvm wallet fund <amount>' \u2014 the agent will move sats across on its own."
25142
- }
25143
- ];
25144
- }
25145
- function cashuOptions(mints, hasLightningBackend) {
25146
- const exampleMint = mints && mints.length > 0 ? mints[0] : void 0;
25147
- const hasMints = exampleMint !== void 0;
25148
- const mintCommand = exampleMint ? `dvm wallet fund <sats> --mint ${exampleMint}` : "dvm wallet fund <sats> --mint <url>";
25149
- const mintOption = {
25150
- method: "cashu-mint",
25151
- display: "Mint Cashu tokens via Lightning",
25152
- command: mintCommand,
25153
- description: hasMints ? "Pays a Lightning invoice from your Lightning wallet and mints matching P2PK-locked Cashu tokens into the agent wallet. Cashu mints are custodial \u2014 only deposit what you're willing to lose." : "After adding a mint above, pays a Lightning invoice from your Lightning wallet and mints matching P2PK-locked Cashu tokens into the agent wallet. Cashu mints are custodial \u2014 only deposit what you're willing to lose.",
25154
- hint: hasLightningBackend ? "Requires a Lightning wallet \u2014 you have one configured." : "Requires a Lightning wallet \u2014 connect one with 'dvm wallet connect' first (pipe the connection string in, or pass --file <path>).",
25155
- ...hasMints ? { mints } : {}
25156
- };
25157
- const receiveTokenOption = {
25158
- method: "cashu-receive-token",
25159
- display: "Receive an existing Cashu token",
25160
- command: "dvm wallet receive-token <cashu-token>",
25161
- description: "Claim a pre-minted Cashu token (e.g. from a friend or a faucet) into the agent wallet. The token is re-locked to your wallet's key so it's spendable.",
25162
- hint: "Tokens are single-use; a token locked to a third party can't be claimed.",
25163
- ...hasMints ? { mints } : {}
25164
- };
25165
- const options = [];
25166
- if (!hasMints) {
25167
- options.push({
25168
- method: "cashu-add-mint",
25169
- display: "Add a Cashu mint",
25170
- command: "dvm wallet mint-add <url>",
25171
- description: "Cashu mints hold your tokens. Add one before you can mint or receive tokens \u2014 'dvm wallet mint-list' shows recommended mints. Cashu mints are custodial \u2014 only deposit what you're willing to lose.",
25172
- hint: "Recommended mints: see 'dvm wallet mint-list' for trusted options."
25173
- });
25174
- }
25175
- if (hasLightningBackend) {
25176
- options.push(mintOption, receiveTokenOption);
25177
- } else {
25178
- options.push(receiveTokenOption, mintOption);
25179
- }
25180
- return options;
25181
- }
25182
-
25183
26260
  // src/lib/onramps.ts
25184
26261
  var FUNDING_DOCS_URL = "https://dvmkit.com/docs/funding";
25185
26262
  var X402_DEFAULT_ASSET = resolveX402Asset();
@@ -27824,17 +28901,135 @@ function fundInterruptedError(err, fund) {
27824
28901
  }
27825
28902
  );
27826
28903
  }
27827
- function mintErrorName(cause) {
27828
- switch (cause) {
27829
- case "rate_limited":
27830
- return "RateLimitError";
27831
- case "mint_server_error":
27832
- return "HttpResponseError";
27833
- case "mint_unreachable":
27834
- return "NetworkError";
27835
- case "unexpected":
27836
- return "Error";
28904
+ function mintErrorName(cause) {
28905
+ switch (cause) {
28906
+ case "rate_limited":
28907
+ return "RateLimitError";
28908
+ case "mint_server_error":
28909
+ return "HttpResponseError";
28910
+ case "mint_unreachable":
28911
+ return "NetworkError";
28912
+ case "unexpected":
28913
+ return "Error";
28914
+ }
28915
+ }
28916
+
28917
+ // src/lib/wallet-agent/recovery-melt.ts
28918
+ var DEFAULT_SWEEP_QUOTE_RETRY_TIMEOUT_MS = 1e4;
28919
+ async function sweepPendingMelts(opts = {}) {
28920
+ const wallet = loadAgentWallet();
28921
+ if (!wallet || wallet.pending_melts.length === 0) {
28922
+ return { outcomes: [], settled_sats: 0, returned_sats: 0, still_pending: [], errors: [] };
28923
+ }
28924
+ const now = opts.now ?? (() => Date.now());
28925
+ const abandonAfterMs = opts.abandonAfterMs ?? meltInFlightTimeoutSeconds() * 1e3;
28926
+ const getWalletForMint = opts.getWalletForMint ?? getWallet;
28927
+ const quoteRetryTimeoutMs = opts.quoteRetryTimeoutMs ?? DEFAULT_SWEEP_QUOTE_RETRY_TIMEOUT_MS;
28928
+ const outcomes = [];
28929
+ for (const entry of wallet.pending_melts) {
28930
+ outcomes.push(
28931
+ await processEntry(wallet, entry, now(), abandonAfterMs, getWalletForMint, {
28932
+ now,
28933
+ sleep: opts.sleep,
28934
+ timeoutMs: quoteRetryTimeoutMs
28935
+ })
28936
+ );
28937
+ }
28938
+ if (outcomes.some((o) => o.kind === "settled" || o.kind === "reverted")) {
28939
+ await withWalletLock(() => {
28940
+ const fresh = loadAgentWallet() ?? wallet;
28941
+ saveAgentWallet(outcomes.reduce(applyOutcome2, fresh));
28942
+ });
28943
+ }
28944
+ return {
28945
+ outcomes,
28946
+ settled_sats: outcomes.filter((o) => o.kind === "settled").reduce((sum, o) => sum + o.entry.amount_sats, 0),
28947
+ returned_sats: outcomes.filter((o) => o.kind === "reverted").reduce((sum, o) => sum + o.returned_sats, 0),
28948
+ still_pending: outcomes.filter(
28949
+ (o) => o.kind === "still_pending"
28950
+ ).map((o) => o.entry),
28951
+ errors: outcomes.filter((o) => o.kind === "error").map((o) => ({ quote_id: o.entry.quote_id, error: o.error }))
28952
+ };
28953
+ }
28954
+ async function processEntry(wallet, entry, nowMs, abandonAfterMs, getWalletForMint, retry) {
28955
+ let cashuWallet;
28956
+ let state;
28957
+ try {
28958
+ ({ cashuWallet, state } = await retryMintQuoteOperation(
28959
+ async () => {
28960
+ const candidate = await getWalletForMint(entry.mint);
28961
+ const quote2 = await candidate.checkMeltQuoteBolt11(entry.quote_id);
28962
+ return { cashuWallet: candidate, state: quote2.state };
28963
+ },
28964
+ {
28965
+ deadlineMs: retry.now() + retry.timeoutMs,
28966
+ quoteId: entry.quote_id,
28967
+ now: retry.now,
28968
+ sleep: retry.sleep
28969
+ }
28970
+ ));
28971
+ } catch (err) {
28972
+ return { kind: "error", entry, error: errorMessage(err) };
28973
+ }
28974
+ if (state === "PAID") {
28975
+ let change;
28976
+ try {
28977
+ change = await restoreChange(cashuWallet, entry, wallet.lock_pubkey);
28978
+ } catch {
28979
+ change = [];
28980
+ }
28981
+ return { kind: "settled", entry, change };
28982
+ }
28983
+ if (state === "UNPAID") {
28984
+ const createdAtMs = Date.parse(entry.created_at);
28985
+ const ageMs2 = Number.isFinite(createdAtMs) ? nowMs - createdAtMs : Infinity;
28986
+ if (ageMs2 <= abandonAfterMs) return { kind: "still_pending", entry };
28987
+ return {
28988
+ kind: "reverted",
28989
+ entry,
28990
+ returned_sats: entry.input_proofs.reduce((sum, p) => sum + p.amount, 0)
28991
+ };
28992
+ }
28993
+ return { kind: "still_pending", entry };
28994
+ }
28995
+ async function restoreChange(cashuWallet, entry, lockPubkey) {
28996
+ if (!entry.melting || entry.melting.outputs.length === 0) return [];
28997
+ const data = rehydrateOutputData(entry.melting.outputs);
28998
+ const keyset = cashuWallet.keyChain.getKeyset(entry.melting.keyset_id);
28999
+ const restored = await cashuWallet.mint.restore({
29000
+ outputs: data.map((d) => d.blindedMessage)
29001
+ });
29002
+ if (restored.outputs.length !== restored.signatures.length) {
29003
+ throw new Error(
29004
+ `mint returned mismatched outputs (${restored.outputs.length}) and signatures (${restored.signatures.length}) \u2014 NUT-09 requires parallel arrays`
29005
+ );
29006
+ }
29007
+ const byB = new Map(data.map((d) => [d.blindedMessage.B_, d]));
29008
+ const proofs = [];
29009
+ for (let i = 0; i < restored.signatures.length; i++) {
29010
+ const owner = byB.get(restored.outputs[i].B_);
29011
+ if (!owner) continue;
29012
+ proofs.push(
29013
+ toAgentProof(owner.toProof(restored.signatures[i], keyset), entry.mint, lockPubkey)
29014
+ );
29015
+ }
29016
+ return proofs;
29017
+ }
29018
+ function applyOutcome2(wallet, outcome) {
29019
+ if (outcome.kind === "still_pending" || outcome.kind === "error") return wallet;
29020
+ const inputKeys = new Set(outcome.entry.input_proofs.map((p) => proofKey(p)));
29021
+ const next = {
29022
+ ...wallet,
29023
+ pending_melts: wallet.pending_melts.filter((m) => m.quote_id !== outcome.entry.quote_id)
29024
+ };
29025
+ if (outcome.kind === "settled") {
29026
+ next.proofs = [...next.proofs.filter((p) => !inputKeys.has(proofKey(p))), ...outcome.change];
29027
+ return next;
27837
29028
  }
29029
+ return revertInFlight(next, inputKeys);
29030
+ }
29031
+ function errorMessage(err) {
29032
+ return err instanceof Error ? err.message : String(err);
27838
29033
  }
27839
29034
 
27840
29035
  // src/lib/wallet-agent/mint-sweep.ts
@@ -28818,6 +30013,330 @@ async function writeInvoicePng(invoice, outPath) {
28818
30013
  }
28819
30014
  }
28820
30015
 
30016
+ // src/lib/wallet-agent/release.ts
30017
+ async function releaseAgentReserve(opts) {
30018
+ const cashu = opts.providerInfo.cashu;
30019
+ if (!cashu?.canonical_id) {
30020
+ throw new DvmError(
30021
+ "missing_canonical_id",
30022
+ "DVM advertises no `cashu.canonical_id` on /v1/info.",
30023
+ "Release needs canonical_id so the agent can derive the matching per-DVM refund subkey. Upgrade the builder SDK."
30024
+ );
30025
+ }
30026
+ const outputMode = opts.outputMode ?? "locked";
30027
+ const initial = loadAgentWallet();
30028
+ if (!initial) {
30029
+ throw new DvmError("wallet_missing", "No agent wallet found.", "Run `dvm wallet init` first.");
30030
+ }
30031
+ const readMnemonic = opts.readMnemonic ?? readAgentMnemonic;
30032
+ const mnemonic = readMnemonic();
30033
+ if (!mnemonic) {
30034
+ throw new DvmError(
30035
+ "mnemonic_required",
30036
+ "Release requires a BIP-39 mnemonic at ~/.dvm/wallet.mnemonic.",
30037
+ "Restore the mnemonic with `dvm wallet recover --force --file <path>` (or pipe it via stdin) \u2014 it's the only way to derive the refund subkey privkey."
30038
+ );
30039
+ }
30040
+ const refund = deriveAgentRefundSubkey(mnemonic, cashu.canonical_id);
30041
+ const marker = reservedForMarker(opts.builderHandle);
30042
+ const now = (opts.now ?? Date.now)();
30043
+ const candidates = initial.proofs.filter(
30044
+ (p) => p.reserved_for === marker && p.status === "valid" && typeof p.t_expire === "number" && p.t_expire < now
30045
+ );
30046
+ if (candidates.length === 0) {
30047
+ return { builder_handle: opts.builderHandle, output_mode: outputMode, mints: [] };
30048
+ }
30049
+ const getWalletForMint = opts.getWalletForMint ?? getWallet;
30050
+ const byMint = /* @__PURE__ */ new Map();
30051
+ for (const p of candidates) {
30052
+ const bucket = byMint.get(p.mint) ?? [];
30053
+ bucket.push(p);
30054
+ byMint.set(p.mint, bucket);
30055
+ }
30056
+ const outcomes = [];
30057
+ for (const [mintUrl, mintProofs] of byMint) {
30058
+ outcomes.push(
30059
+ await releaseAtMint(
30060
+ mintUrl,
30061
+ mintProofs,
30062
+ refund.privkey,
30063
+ initial,
30064
+ outputMode,
30065
+ getWalletForMint
30066
+ )
30067
+ );
30068
+ }
30069
+ return { builder_handle: opts.builderHandle, output_mode: outputMode, mints: outcomes };
30070
+ }
30071
+ async function releaseAtMint(mintUrl, mintProofs, refundPrivkey, initial, outputMode, getWalletForMint) {
30072
+ let cashuWallet;
30073
+ try {
30074
+ cashuWallet = await getWalletForMint(mintUrl);
30075
+ } catch (err) {
30076
+ return {
30077
+ mint: mintUrl,
30078
+ alreadySpent: [],
30079
+ pending: [],
30080
+ reclaimedInputs: [],
30081
+ reclaimedOutputs: [],
30082
+ error: err instanceof Error ? err.message : String(err)
30083
+ };
30084
+ }
30085
+ let grouped;
30086
+ try {
30087
+ grouped = await cashuWallet.groupProofsByState(toCashuProofs(mintProofs));
30088
+ } catch (err) {
30089
+ return {
30090
+ mint: mintUrl,
30091
+ alreadySpent: [],
30092
+ pending: [],
30093
+ reclaimedInputs: [],
30094
+ reclaimedOutputs: [],
30095
+ error: err instanceof Error ? err.message : String(err)
30096
+ };
30097
+ }
30098
+ const spentSecrets = new Set(grouped.spent.map((p) => p.secret));
30099
+ const pendingSecrets = new Set(grouped.pending.map((p) => p.secret));
30100
+ const alreadySpent = mintProofs.filter((p) => spentSecrets.has(p.secret));
30101
+ const pending4 = mintProofs.filter((p) => pendingSecrets.has(p.secret));
30102
+ const unspent = mintProofs.filter(
30103
+ (p) => !spentSecrets.has(p.secret) && !pendingSecrets.has(p.secret)
30104
+ );
30105
+ if (alreadySpent.length > 0) {
30106
+ await withWalletLock(() => {
30107
+ const fresh = loadAgentWallet() ?? initial;
30108
+ const spentKeys = new Set(alreadySpent.map((p) => proofIdKey(p)));
30109
+ saveAgentWallet({
30110
+ ...fresh,
30111
+ proofs: fresh.proofs.filter((p) => !spentKeys.has(proofIdKey(p)))
30112
+ });
30113
+ });
30114
+ }
30115
+ if (unspent.length === 0) {
30116
+ return {
30117
+ mint: mintUrl,
30118
+ alreadySpent,
30119
+ pending: pending4,
30120
+ reclaimedInputs: [],
30121
+ reclaimedOutputs: [],
30122
+ error: null
30123
+ };
30124
+ }
30125
+ const totalSats = unspent.reduce((sum, p) => sum + p.amount, 0);
30126
+ const inputs = toCashuProofs(unspent);
30127
+ let outputs;
30128
+ try {
30129
+ const swapFeeSats = swapFeeForProofs(cashuWallet, inputs);
30130
+ const reclaimSats = totalSats - swapFeeSats;
30131
+ if (reclaimSats <= 0) {
30132
+ throw new Error(
30133
+ `Reserve at ${mintUrl} is ${totalSats} sats, which does not cover the mint's ${swapFeeSats}-sat swap fee.`
30134
+ );
30135
+ }
30136
+ const builder = cashuWallet.ops.send(reclaimSats, inputs).privkey(refundPrivkey);
30137
+ const result = outputMode === "locked" ? await builder.asP2PK({ pubkey: initial.lock_pubkey }).run() : await builder.asRandom().run();
30138
+ outputs = result.send;
30139
+ } catch (err) {
30140
+ return {
30141
+ mint: mintUrl,
30142
+ alreadySpent,
30143
+ pending: pending4,
30144
+ reclaimedInputs: [],
30145
+ reclaimedOutputs: [],
30146
+ error: err instanceof Error ? err.message : String(err)
30147
+ };
30148
+ }
30149
+ const reclaimedOutputs = outputs.map(
30150
+ (p) => toAgentProof(p, mintUrl, outputMode === "locked" ? initial.lock_pubkey : null)
30151
+ );
30152
+ await withWalletLock(() => {
30153
+ const fresh = loadAgentWallet() ?? initial;
30154
+ const inputKeys = new Set(unspent.map((p) => proofIdKey(p)));
30155
+ saveAgentWallet({
30156
+ ...fresh,
30157
+ proofs: [...fresh.proofs.filter((p) => !inputKeys.has(proofIdKey(p))), ...reclaimedOutputs]
30158
+ });
30159
+ });
30160
+ return {
30161
+ mint: mintUrl,
30162
+ alreadySpent,
30163
+ pending: pending4,
30164
+ reclaimedInputs: unspent,
30165
+ reclaimedOutputs,
30166
+ error: null
30167
+ };
30168
+ }
30169
+ function proofIdKey(p) {
30170
+ return `${p.secret}:${p.C}`;
30171
+ }
30172
+
30173
+ // src/lib/wallet-agent/reserve.ts
30174
+ async function reserveAgentWallet(amountSats, opts) {
30175
+ if (!Number.isFinite(amountSats) || amountSats <= 0) {
30176
+ throw new DvmError(
30177
+ "invalid_amount",
30178
+ "Amount must be a positive integer number of sats.",
30179
+ "Pass a positive sats amount, e.g. `dvm wallet reserve --builder scrape.dvmkit.ai 1000`, or a USD amount, e.g. `dvm wallet reserve --builder scrape.dvmkit.ai $5`."
30180
+ );
30181
+ }
30182
+ const sats = Math.floor(amountSats);
30183
+ const cashu = opts.providerInfo.cashu;
30184
+ if (!cashu) {
30185
+ throw new DvmError(
30186
+ "missing_cashu_info",
30187
+ "DVM does not advertise a `cashu` object on /v1/info.",
30188
+ "Reserve requires the builder to expose lock_pubkeys, mints, and canonical_id. Check the builder is running an SDK that supports pre-fund."
30189
+ );
30190
+ }
30191
+ const lockPubkey = cashu.lock_pubkeys[0];
30192
+ if (!lockPubkey) {
30193
+ throw new DvmError(
30194
+ "missing_lock_pubkey",
30195
+ "DVM advertised no current lock pubkey.",
30196
+ "Ask the builder operator to deploy with DVMKIT_CASHU_LOCK_PUBKEY set."
30197
+ );
30198
+ }
30199
+ if (cashu.mints.length === 0) {
30200
+ throw new DvmError(
30201
+ "missing_dvm_mints",
30202
+ "DVM advertises no accepted Cashu mints.",
30203
+ "Ask the builder operator to set DVMKIT_CASHU_MINTS on the DVM machine."
30204
+ );
30205
+ }
30206
+ if (!cashu.canonical_id) {
30207
+ throw new DvmError(
30208
+ "missing_canonical_id",
30209
+ "DVM advertises no `cashu.canonical_id` on /v1/info.",
30210
+ "Pre-fund requires canonical_id so the agent can derive a per-DVM refund subkey. Upgrade the builder SDK to one that advertises it."
30211
+ );
30212
+ }
30213
+ if (!cashu.mints.includes(opts.mintUrl)) {
30214
+ throw new DvmError(
30215
+ "mint_not_accepted",
30216
+ `Mint ${opts.mintUrl} is not in the builder's allowlist (${cashu.mints.join(", ")}).`,
30217
+ `Re-run with --mint set to one of the builder's accepted mints, or top up at one of them first.`
30218
+ );
30219
+ }
30220
+ const locktimeSeconds = opts.locktimeSeconds ?? DEFAULT_RESERVE_LOCKTIME_SECONDS;
30221
+ if (cashu.min_locktime && locktimeSeconds < cashu.min_locktime) {
30222
+ throw new DvmError(
30223
+ "locktime_too_short",
30224
+ `Requested locktime ${locktimeSeconds}s is below the builder's minimum ${cashu.min_locktime}s.`,
30225
+ `Re-run with --locktime at or above the builder's minimum (${cashu.min_locktime}s).`
30226
+ );
30227
+ }
30228
+ const initial = loadAgentWallet();
30229
+ if (!initial) {
30230
+ throw new DvmError(
30231
+ "wallet_missing",
30232
+ "No agent wallet found.",
30233
+ "Run `dvm wallet init` first to generate a wallet."
30234
+ );
30235
+ }
30236
+ const readMnemonic = opts.readMnemonic ?? readAgentMnemonic;
30237
+ const mnemonic = readMnemonic();
30238
+ if (!mnemonic) {
30239
+ throw new DvmError(
30240
+ "mnemonic_required",
30241
+ "Reserve requires a BIP-39 mnemonic at ~/.dvm/wallet.mnemonic.",
30242
+ "The per-DVM refund subkey is derived from the mnemonic, so `dvm wallet release` post-expire requires it. Run `dvm wallet init` (fresh wallet) or `dvm wallet recover --force --file <path>` (or pipe the mnemonic via stdin) to attach the mnemonic file."
30243
+ );
30244
+ }
30245
+ const refundPubkey = deriveAgentRefundSubkeyPubkey(mnemonic, cashu.canonical_id);
30246
+ const cashuWallet = await (opts.getWalletForMint ?? getWallet)(opts.mintUrl);
30247
+ const quote2 = await cashuWallet.createLockedMintQuote(sats, initial.lock_pubkey);
30248
+ const pending4 = {
30249
+ mint: opts.mintUrl,
30250
+ quote_id: quote2.quote,
30251
+ amount_sats: sats,
30252
+ requested_at: (/* @__PURE__ */ new Date()).toISOString(),
30253
+ ...quote2.expiry === null ? {} : { expires_at: quote2.expiry }
30254
+ };
30255
+ await withWalletLock(() => {
30256
+ const fresh = loadAgentWallet() ?? initial;
30257
+ saveAgentWallet({
30258
+ ...fresh,
30259
+ pending_mints: [...fresh.pending_mints, pending4]
30260
+ });
30261
+ });
30262
+ if (opts.onInvoice) await opts.onInvoice(quote2.request, quote2);
30263
+ const finalState = await pollUntilPaidOrTimeout(cashuWallet, quote2.quote, {
30264
+ timeoutMs: opts.timeoutMs ?? fundTimeoutMs(),
30265
+ pollIntervalMs: opts.pollIntervalMs,
30266
+ now: opts.now,
30267
+ sleep: opts.sleep,
30268
+ onPoll: opts.onPoll
30269
+ });
30270
+ if (finalState === sa.ISSUED) {
30271
+ throw new DvmError(
30272
+ "reserve_already_issued",
30273
+ `Mint quote ${quote2.quote} was already collected by a concurrent run.`,
30274
+ "Inspect wallet state with `dvm wallet show` \u2014 the proofs should be persisted by the other instance."
30275
+ );
30276
+ }
30277
+ if (finalState !== sa.PAID) {
30278
+ throw new DvmError(
30279
+ "reserve_timeout",
30280
+ `Mint quote ${quote2.quote} was not paid within the reserve timeout.`,
30281
+ "Pay the invoice from a Lightning wallet, then run `dvm wallet show` to recover the pending mint, or `dvm wallet reserve` to start a new flow."
30282
+ );
30283
+ }
30284
+ const denominations = computeSmartDenominations(sats, {
30285
+ maxDenomination: maxKeysetDenomination(cashuWallet)
30286
+ });
30287
+ const nowMs = (opts.now ?? Date.now)();
30288
+ const tExpireSeconds = Math.floor(nowMs / 1e3) + locktimeSeconds;
30289
+ const tExpireMs = tExpireSeconds * 1e3;
30290
+ const preview = await prepareP2PKMint(
30291
+ cashuWallet,
30292
+ sats,
30293
+ quote2,
30294
+ initial.lock_privkey,
30295
+ lockPubkey,
30296
+ denominations,
30297
+ { locktimeUnixSec: tExpireSeconds, refundKeys: [refundPubkey] }
30298
+ );
30299
+ const minting = {
30300
+ keyset_id: preview.keysetId,
30301
+ outputs: serializeOutputData(preview.outputData)
30302
+ };
30303
+ await withWalletLock(() => {
30304
+ const fresh = loadAgentWallet() ?? initial;
30305
+ saveAgentWallet(upsertPending(fresh, { ...pending4, minting }));
30306
+ });
30307
+ const reservedFor = reservedForMarker(opts.builderHandle);
30308
+ const proofs = await cashuWallet.completeMint(preview);
30309
+ const agentProofs = proofs.map(
30310
+ (p) => toAgentProof(p, opts.mintUrl, lockPubkey, {
30311
+ reservedFor,
30312
+ tExpireMs
30313
+ })
30314
+ );
30315
+ await withWalletLock(() => {
30316
+ const post = loadAgentWallet() ?? initial;
30317
+ saveAgentWallet({
30318
+ ...post,
30319
+ proofs: [...post.proofs, ...agentProofs],
30320
+ pending_mints: post.pending_mints.filter((p) => p.quote_id !== quote2.quote)
30321
+ });
30322
+ });
30323
+ return {
30324
+ mint: opts.mintUrl,
30325
+ amount_sats: sats,
30326
+ quote_id: quote2.quote,
30327
+ denominations,
30328
+ proofs: agentProofs,
30329
+ builder_handle: opts.builderHandle,
30330
+ t_expire_ms: tExpireMs,
30331
+ refund_pubkey: refundPubkey,
30332
+ lock_pubkey: lockPubkey
30333
+ };
30334
+ }
30335
+ function upsertPending(wallet, entry) {
30336
+ const others = wallet.pending_mints.filter((p) => p.quote_id !== entry.quote_id);
30337
+ return { ...wallet, pending_mints: [...others, entry] };
30338
+ }
30339
+
28821
30340
  // src/commands/wallet-agent-reserve.ts
28822
30341
  var import_qrcode2 = __toESM(require_lib(), 1);
28823
30342
  async function walletReserve(amount, opts) {
@@ -29267,6 +30786,347 @@ function mnemonicValidationError2(result) {
29267
30786
  );
29268
30787
  }
29269
30788
 
30789
+ // src/lib/wallet-agent/cash-out.ts
30790
+ async function cashOutFromMint(opts) {
30791
+ const mintUrl = opts.mintUrl;
30792
+ const now = opts.now ?? (() => Date.now());
30793
+ const getWalletForMint = opts.getWalletForMint ?? getWallet;
30794
+ const fetchInvoice = opts.fetchInvoice ?? fetchLnurlPayInvoice;
30795
+ const initial = loadAgentWallet();
30796
+ if (!initial) {
30797
+ throw new DvmError(
30798
+ "wallet_missing",
30799
+ "No agent wallet found.",
30800
+ "Run `dvm wallet init` first to generate a lock keypair."
30801
+ );
30802
+ }
30803
+ const candidates = spendableAt(initial.proofs, mintUrl);
30804
+ if (candidates.length === 0) {
30805
+ return {
30806
+ kind: "skipped",
30807
+ mint: mintUrl,
30808
+ reason: "no_balance",
30809
+ message: `No spendable proofs at ${mintUrl}.`
30810
+ };
30811
+ }
30812
+ let cashuWallet;
30813
+ try {
30814
+ cashuWallet = await getWalletForMint(mintUrl);
30815
+ } catch (err) {
30816
+ return { kind: "failed", mint: mintUrl, message: errorMessage2(err), settlement: "reverted" };
30817
+ }
30818
+ const meltBounds = meltBoundsOf(cashuWallet);
30819
+ let target = opts.target;
30820
+ let cappedByMintMax;
30821
+ if (meltBounds.maxSats !== null) {
30822
+ const wanted = opts.target.kind === "all" ? sumSats2(candidates) : opts.target.sats;
30823
+ if (wanted > meltBounds.maxSats) {
30824
+ target = { kind: "exact", sats: meltBounds.maxSats };
30825
+ cappedByMintMax = meltBounds.maxSats;
30826
+ }
30827
+ }
30828
+ let selected = selectInputs(candidates, target);
30829
+ let inputFees;
30830
+ try {
30831
+ inputFees = await getInputFeesForProofs(mintUrl, toCashuProofs(selected));
30832
+ } catch (err) {
30833
+ return { kind: "failed", mint: mintUrl, message: errorMessage2(err), settlement: "reverted" };
30834
+ }
30835
+ let selectedTotal = sumSats2(selected);
30836
+ if (target.kind === "exact" && selectedTotal - inputFees < target.sats) {
30837
+ const widened = widenSelection(candidates, selected, target.sats, inputFees);
30838
+ if (widened) {
30839
+ selected = widened.selected;
30840
+ selectedTotal = sumSats2(selected);
30841
+ try {
30842
+ inputFees = await getInputFeesForProofs(mintUrl, toCashuProofs(selected));
30843
+ } catch (err) {
30844
+ return {
30845
+ kind: "failed",
30846
+ mint: mintUrl,
30847
+ message: errorMessage2(err),
30848
+ settlement: "reverted"
30849
+ };
30850
+ }
30851
+ }
30852
+ }
30853
+ const desired = target.kind === "all" ? selectedTotal - inputFees : Math.min(target.sats, selectedTotal - inputFees);
30854
+ if (desired <= 0) {
30855
+ return {
30856
+ kind: "skipped",
30857
+ mint: mintUrl,
30858
+ reason: "fees_exceed_balance",
30859
+ message: `The mint's per-input fee (${inputFees} sats) meets or exceeds the ${selectedTotal} sats available at ${mintUrl}.`
30860
+ };
30861
+ }
30862
+ if (meltBounds.minSats !== null && desired < meltBounds.minSats) {
30863
+ return {
30864
+ kind: "skipped",
30865
+ mint: mintUrl,
30866
+ reason: "amount_out_of_range",
30867
+ message: `${mintUrl} won't pay out less than ${meltBounds.minSats} sats in one go, and only ${desired} sats can be sent from here after fees.`
30868
+ };
30869
+ }
30870
+ if (opts.maxFeeSats !== void 0 && inputFees > opts.maxFeeSats) {
30871
+ return {
30872
+ kind: "skipped",
30873
+ mint: mintUrl,
30874
+ reason: "fee_cap_exceeded",
30875
+ message: `The per-input fee at ${mintUrl} is ${inputFees} sats on its own, over the ${opts.maxFeeSats} sat cap.`
30876
+ };
30877
+ }
30878
+ let invoice;
30879
+ let quote2;
30880
+ try {
30881
+ invoice = await fetchInvoice(opts.destination, desired * 1e3);
30882
+ quote2 = await fetchMeltQuote(mintUrl, invoice);
30883
+ } catch (err) {
30884
+ return classifyPreCommitError(mintUrl, err);
30885
+ }
30886
+ if (selectedTotal < quote2.amountSats + quote2.feeReserveSats + inputFees) {
30887
+ const widened = widenSelection(
30888
+ candidates,
30889
+ selected,
30890
+ quote2.amountSats + quote2.feeReserveSats,
30891
+ inputFees
30892
+ );
30893
+ if (widened) {
30894
+ selected = widened.selected;
30895
+ selectedTotal = sumSats2(selected);
30896
+ try {
30897
+ inputFees = await getInputFeesForProofs(mintUrl, toCashuProofs(selected));
30898
+ } catch (err) {
30899
+ return {
30900
+ kind: "failed",
30901
+ mint: mintUrl,
30902
+ message: errorMessage2(err),
30903
+ settlement: "reverted"
30904
+ };
30905
+ }
30906
+ }
30907
+ if (selectedTotal < quote2.amountSats + quote2.feeReserveSats + inputFees) {
30908
+ const target2 = selectedTotal - quote2.feeReserveSats - inputFees;
30909
+ if (target2 <= 0) {
30910
+ return {
30911
+ kind: "skipped",
30912
+ mint: mintUrl,
30913
+ reason: "fees_exceed_balance",
30914
+ message: `Fees at ${mintUrl} (${quote2.feeReserveSats} sats routing reserve + ${inputFees} sats input fee) meet or exceed the ${selectedTotal} sats available.`
30915
+ };
30916
+ }
30917
+ try {
30918
+ invoice = await fetchInvoice(opts.destination, target2 * 1e3);
30919
+ quote2 = await fetchMeltQuote(mintUrl, invoice);
30920
+ } catch (err) {
30921
+ return classifyPreCommitError(mintUrl, err);
30922
+ }
30923
+ if (selectedTotal < quote2.amountSats + quote2.feeReserveSats + inputFees) {
30924
+ return {
30925
+ kind: "skipped",
30926
+ mint: mintUrl,
30927
+ reason: "fees_exceed_balance",
30928
+ message: `${mintUrl} quoted a routing reserve (${quote2.feeReserveSats} sats) the ${selectedTotal} sats available can't cover.`
30929
+ };
30930
+ }
30931
+ }
30932
+ }
30933
+ const quoteView = {
30934
+ mint: mintUrl,
30935
+ quote_id: quote2.rawQuote.quote,
30936
+ amount_sats: quote2.amountSats,
30937
+ fee_reserve_sats: quote2.feeReserveSats,
30938
+ input_fee_sats: inputFees,
30939
+ debit_sats: selectedTotal,
30940
+ expires_at: typeof quote2.rawQuote.expiry === "number" ? quote2.rawQuote.expiry : null
30941
+ };
30942
+ const totalFees = quote2.feeReserveSats + inputFees;
30943
+ if (opts.maxFeeSats !== void 0 && totalFees > opts.maxFeeSats) {
30944
+ return {
30945
+ kind: "skipped",
30946
+ mint: mintUrl,
30947
+ reason: "fee_cap_exceeded",
30948
+ message: `Fees at ${mintUrl} would be up to ${totalFees} sats, over the ${opts.maxFeeSats} sat cap.`,
30949
+ quote: quoteView
30950
+ };
30951
+ }
30952
+ opts.onQuote?.(quoteView);
30953
+ if (opts.dryRun) {
30954
+ return {
30955
+ kind: "quoted",
30956
+ mint: mintUrl,
30957
+ quote: quoteView,
30958
+ ...cappedByMintMax !== void 0 ? { mint_max_sats: cappedByMintMax } : {}
30959
+ };
30960
+ }
30961
+ let preview;
30962
+ try {
30963
+ preview = await cashuWallet.ops.meltBolt11(quote2.rawQuote, toCashuProofs(selected)).asP2PK({ pubkey: initial.lock_pubkey }).privkey(initial.lock_privkey).prepare();
30964
+ } catch (err) {
30965
+ return {
30966
+ kind: "failed",
30967
+ mint: mintUrl,
30968
+ message: errorMessage2(err),
30969
+ settlement: "reverted",
30970
+ quote: quoteView
30971
+ };
30972
+ }
30973
+ const untilMs = now() + (opts.inFlightTimeoutSec ?? meltInFlightTimeoutSeconds()) * 1e3;
30974
+ const selectedKeys = new Set(selected.map((p) => proofKey(p)));
30975
+ const entry = {
30976
+ mint: mintUrl,
30977
+ quote_id: quote2.rawQuote.quote,
30978
+ bolt11: invoice,
30979
+ destination: opts.destination,
30980
+ amount_sats: quote2.amountSats,
30981
+ fee_reserve_sats: quote2.feeReserveSats,
30982
+ input_fee_sats: inputFees,
30983
+ input_proofs: selected,
30984
+ melting: {
30985
+ keyset_id: preview.keysetId,
30986
+ outputs: serializeOutputData(preview.outputData)
30987
+ },
30988
+ created_at: new Date(now()).toISOString(),
30989
+ ...quoteView.expires_at !== null ? { expires_at: quoteView.expires_at } : {}
30990
+ };
30991
+ const committed = await withWalletLock(() => {
30992
+ const fresh = loadAgentWallet();
30993
+ if (!fresh) return false;
30994
+ const swept = sweepStaleInFlight(fresh, now());
30995
+ const available = new Set(spendableAt(swept.wallet.proofs, mintUrl).map((p) => proofKey(p)));
30996
+ if (![...selectedKeys].every((k) => available.has(k))) {
30997
+ if (swept.reverted > 0) saveAgentWallet(swept.wallet);
30998
+ return false;
30999
+ }
31000
+ const marked = markProofsInFlight(swept.wallet, selectedKeys, untilMs);
31001
+ saveAgentWallet({ ...marked, pending_melts: [...marked.pending_melts, entry] });
31002
+ return true;
31003
+ });
31004
+ if (!committed) {
31005
+ return {
31006
+ kind: "failed",
31007
+ mint: mintUrl,
31008
+ message: `Proofs at ${mintUrl} changed underneath the melt (another dvm run may have spent them). Nothing was sent.`,
31009
+ settlement: "reverted",
31010
+ quote: quoteView
31011
+ };
31012
+ }
31013
+ let change;
31014
+ let preimage;
31015
+ try {
31016
+ const result = await cashuWallet.completeMelt(preview, initial.lock_privkey);
31017
+ change = result.change;
31018
+ preimage = result.quote.payment_preimage ?? null;
31019
+ } catch (err) {
31020
+ return resolveFailedMelt(cashuWallet, mintUrl, entry, selectedKeys, quoteView, err);
31021
+ }
31022
+ const changeProofs = change.map((p) => toAgentProof(p, mintUrl, initial.lock_pubkey));
31023
+ await withWalletLock(() => {
31024
+ const fresh = loadAgentWallet();
31025
+ if (!fresh) return;
31026
+ saveAgentWallet({
31027
+ ...fresh,
31028
+ proofs: [...fresh.proofs.filter((p) => !selectedKeys.has(proofKey(p))), ...changeProofs],
31029
+ pending_melts: fresh.pending_melts.filter((m) => m.quote_id !== entry.quote_id)
31030
+ });
31031
+ });
31032
+ return {
31033
+ kind: "sent",
31034
+ mint: mintUrl,
31035
+ quote: quoteView,
31036
+ preimage,
31037
+ change_sats: sumSats2(changeProofs),
31038
+ ...cappedByMintMax !== void 0 ? { mint_max_sats: cappedByMintMax } : {}
31039
+ };
31040
+ }
31041
+ function meltBoundsOf(wallet) {
31042
+ const reader = wallet;
31043
+ try {
31044
+ const nuts = reader.getMintInfo?.().cache?.nuts;
31045
+ if (nuts === void 0 || nuts === null) return { minSats: null, maxSats: null };
31046
+ return meltAmountBounds(nuts);
31047
+ } catch {
31048
+ return { minSats: null, maxSats: null };
31049
+ }
31050
+ }
31051
+ function spendableAt(proofs, mintUrl) {
31052
+ return proofs.filter((p) => p.mint === mintUrl && p.status === "valid" && p.reserved_for === void 0).slice().sort((a, b) => b.amount - a.amount);
31053
+ }
31054
+ async function resolveFailedMelt(cashuWallet, mintUrl, entry, selectedKeys, quoteView, err) {
31055
+ let unpaid;
31056
+ try {
31057
+ const state = await cashuWallet.checkMeltQuoteBolt11(entry.quote_id);
31058
+ unpaid = state.state === "UNPAID";
31059
+ } catch {
31060
+ unpaid = false;
31061
+ }
31062
+ if (!unpaid) {
31063
+ return {
31064
+ kind: "failed",
31065
+ mint: mintUrl,
31066
+ message: `${errorMessage2(err)} \u2014 ${entry.amount_sats} sats may still be in flight at ${mintUrl}. Run \`dvm wallet show\` to reconcile before retrying.`,
31067
+ settlement: "unresolved",
31068
+ quote: quoteView
31069
+ };
31070
+ }
31071
+ await withWalletLock(() => {
31072
+ const fresh = loadAgentWallet();
31073
+ if (!fresh) return;
31074
+ const reverted = revertInFlight(fresh, selectedKeys);
31075
+ saveAgentWallet({
31076
+ ...reverted,
31077
+ pending_melts: reverted.pending_melts.filter((m) => m.quote_id !== entry.quote_id)
31078
+ });
31079
+ });
31080
+ return {
31081
+ kind: "failed",
31082
+ mint: mintUrl,
31083
+ message: `${errorMessage2(err)} \u2014 the mint confirms the invoice is unpaid, so the ${quoteView.debit_sats} sats are back in the wallet.`,
31084
+ settlement: "reverted",
31085
+ quote: quoteView
31086
+ };
31087
+ }
31088
+ function selectInputs(candidates, target) {
31089
+ if (target.kind === "all") return [...candidates];
31090
+ const selected = [];
31091
+ let total = 0;
31092
+ for (const p of candidates) {
31093
+ selected.push(p);
31094
+ total += p.amount;
31095
+ if (total >= target.sats) return selected;
31096
+ }
31097
+ return selected;
31098
+ }
31099
+ function widenSelection(candidates, selected, needed, currentInputFees) {
31100
+ const chosen = new Set(selected.map((p) => proofKey(p)));
31101
+ const rest = candidates.filter((p) => !chosen.has(proofKey(p)));
31102
+ if (rest.length === 0) return null;
31103
+ const next = [...selected];
31104
+ let total = sumSats2(next);
31105
+ for (const p of rest) {
31106
+ if (total >= needed + currentInputFees) break;
31107
+ next.push(p);
31108
+ total += p.amount;
31109
+ }
31110
+ return next.length === selected.length ? null : { selected: next };
31111
+ }
31112
+ function classifyPreCommitError(mintUrl, err) {
31113
+ if (err instanceof DvmError && err.code === "lnurl_amount_out_of_range") {
31114
+ return {
31115
+ kind: "skipped",
31116
+ mint: mintUrl,
31117
+ reason: "amount_out_of_range",
31118
+ message: err.message
31119
+ };
31120
+ }
31121
+ return { kind: "failed", mint: mintUrl, message: errorMessage2(err), settlement: "reverted" };
31122
+ }
31123
+ function sumSats2(proofs) {
31124
+ return proofs.reduce((sum, p) => sum + p.amount, 0);
31125
+ }
31126
+ function errorMessage2(err) {
31127
+ return err instanceof Error ? err.message : String(err);
31128
+ }
31129
+
29270
31130
  // src/commands/wallet-cash-out.ts
29271
31131
  async function walletCashOut(destination, opts) {
29272
31132
  const human = opts.human ?? false;
@@ -29466,7 +31326,7 @@ function resolveMints(wallet, explicit) {
29466
31326
  return spendableAt(wallet.proofs, explicit).length > 0 ? [explicit] : [];
29467
31327
  }
29468
31328
  const candidates = /* @__PURE__ */ new Set([...effectiveMints(wallet), ...wallet.proofs.map((p) => p.mint)]);
29469
- return [...candidates].map((url) => ({ url, sats: sumSats2(spendableAt(wallet.proofs, url)) })).filter((m) => m.sats > 0).sort((a, b) => b.sats - a.sats || a.url.localeCompare(b.url)).map((m) => m.url);
31329
+ return [...candidates].map((url) => ({ url, sats: sumSats3(spendableAt(wallet.proofs, url)) })).filter((m) => m.sats > 0).sort((a, b) => b.sats - a.sats || a.url.localeCompare(b.url)).map((m) => m.url);
29470
31330
  }
29471
31331
  function buildHint(args) {
29472
31332
  if (args.unresolvedCount > 0) {
@@ -29495,7 +31355,7 @@ function parseMaxFee(raw2) {
29495
31355
  }
29496
31356
  return Math.floor(n);
29497
31357
  }
29498
- function sumSats2(proofs) {
31358
+ function sumSats3(proofs) {
29499
31359
  return proofs.reduce((sum, p) => sum + p.amount, 0);
29500
31360
  }
29501
31361
 
@@ -29741,7 +31601,7 @@ async function walletMppExit(dvm, opts) {
29741
31601
  err.display
29742
31602
  );
29743
31603
  }
29744
- throw err;
31604
+ throw err instanceof DvmError ? tempoExitRecoveryError(err, account !== null) : err;
29745
31605
  }
29746
31606
  const replayableFunding = result.status === "abandoned" && listPendingFundings({
29747
31607
  endpoint: association.endpoint,