@dvmkit/dvm-cli 0.15.1 → 0.15.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.
package/dist/dvm.js
CHANGED
|
@@ -32,6 +32,7 @@ import {
|
|
|
32
32
|
captureTransportReceipt,
|
|
33
33
|
clearAskPaymentBlocks,
|
|
34
34
|
clearPaymentRequestInFlight,
|
|
35
|
+
clearReclaimIntent,
|
|
35
36
|
commitAgentSpend,
|
|
36
37
|
completedCreditHistory,
|
|
37
38
|
completedDrainMatches,
|
|
@@ -55,6 +56,7 @@ import {
|
|
|
55
56
|
extractBuilderHandle,
|
|
56
57
|
fetchMissingJobReceipt,
|
|
57
58
|
fetchTrustAnchor,
|
|
59
|
+
finalizeLandedReclaims,
|
|
58
60
|
finishBookedSubmission,
|
|
59
61
|
floatBudgetJson,
|
|
60
62
|
floatPaymentDisplay,
|
|
@@ -91,6 +93,7 @@ import {
|
|
|
91
93
|
loadJob,
|
|
92
94
|
loadLedger,
|
|
93
95
|
loadMessages,
|
|
96
|
+
loadReclaimIntent,
|
|
94
97
|
loadSubmissionEvidence,
|
|
95
98
|
markJobTerminal,
|
|
96
99
|
markPaymentRequestAnswered,
|
|
@@ -136,12 +139,14 @@ import {
|
|
|
136
139
|
receiptPieceContext,
|
|
137
140
|
receiptSettlement,
|
|
138
141
|
receiptTrustFields,
|
|
142
|
+
reclaimIntentIds,
|
|
139
143
|
reconcileInFlightPaymentRequest,
|
|
140
144
|
reconcilePaymentRequestHistory,
|
|
141
145
|
recordCallerMessageHash,
|
|
142
146
|
recordFloatSpend,
|
|
143
147
|
recordIdentityFailure,
|
|
144
148
|
recordLocalJobCollision,
|
|
149
|
+
recordReclaimIntent,
|
|
145
150
|
recordSpend,
|
|
146
151
|
recordSpendOnce,
|
|
147
152
|
recordSubmissionEvidence,
|
|
@@ -189,7 +194,7 @@ import {
|
|
|
189
194
|
withIdentityRecovery,
|
|
190
195
|
withJobTokenRedaction,
|
|
191
196
|
withRequestResultRecovery
|
|
192
|
-
} from "./chunk-
|
|
197
|
+
} from "./chunk-ECJO73RZ.js";
|
|
193
198
|
import {
|
|
194
199
|
connectedTempoAccount,
|
|
195
200
|
generateTempoKey,
|
|
@@ -432,6 +437,7 @@ import {
|
|
|
432
437
|
resolveTempoAsset,
|
|
433
438
|
resolveTempoNetwork,
|
|
434
439
|
resolveX402ChannelRpc,
|
|
440
|
+
restoreProofsFromOutputs,
|
|
435
441
|
retryMintQuoteOperation,
|
|
436
442
|
sa,
|
|
437
443
|
saveAgentWallet,
|
|
@@ -444,6 +450,7 @@ import {
|
|
|
444
450
|
signedRequestDomain,
|
|
445
451
|
sn,
|
|
446
452
|
swapFeeForProofs,
|
|
453
|
+
te,
|
|
447
454
|
tempoChannelControlledBy,
|
|
448
455
|
tempoCredentialAmountMicro,
|
|
449
456
|
tempoSessionChallenge,
|
|
@@ -9891,10 +9898,20 @@ function requestRecoveryPath(route, requestId) {
|
|
|
9891
9898
|
// src/lib/wallet-agent/recovery-submissions.ts
|
|
9892
9899
|
var RESUME_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
|
|
9893
9900
|
var RESUME_MAX_ATTEMPTS = 5;
|
|
9901
|
+
var RECLAIM_IN_FLIGHT_MS = 2 * 6e4;
|
|
9902
|
+
var RECLAIM_UNSAVED_REASON = "the reclaim swap may have gone through at the mint but its result is not saved to the wallet yet; run `dvm wallet show` to recover it";
|
|
9894
9903
|
async function sweepPendingSubmissions(opts = {}) {
|
|
9904
|
+
const writeFailures = [];
|
|
9905
|
+
const result = (outcomes2) => writeFailures.length > 0 ? { outcomes: outcomes2, writeFailures } : { outcomes: outcomes2 };
|
|
9906
|
+
const failed = (requestId, stage, error) => writeFailures.push({ requestId, stage, message: errorText(error) });
|
|
9907
|
+
try {
|
|
9908
|
+
finalizeLandedReclaims();
|
|
9909
|
+
} catch (error) {
|
|
9910
|
+
failed("", "verdict_journal", error);
|
|
9911
|
+
}
|
|
9895
9912
|
const wallet = loadAgentWallet();
|
|
9896
9913
|
if (!wallet || wallet.pending_submissions.length === 0) {
|
|
9897
|
-
return
|
|
9914
|
+
return result([]);
|
|
9898
9915
|
}
|
|
9899
9916
|
const deps = {
|
|
9900
9917
|
httpPost: opts.httpPost ?? createDefaultHttpPost(opts.fetchImpl ?? dvmFetch),
|
|
@@ -9910,31 +9927,79 @@ async function sweepPendingSubmissions(opts = {}) {
|
|
|
9910
9927
|
const now = opts.now ?? (() => Date.now());
|
|
9911
9928
|
const { entries, unreadable } = await reconcileEvidenceMarkers(wallet);
|
|
9912
9929
|
const outcomes = [];
|
|
9930
|
+
const handled = /* @__PURE__ */ new Set();
|
|
9913
9931
|
for (const entry of entries) {
|
|
9914
|
-
|
|
9932
|
+
const outcome = await resolveEntry(entry, deps, now(), unreadable.has(entry.request_id));
|
|
9933
|
+
if (outcome.kind !== "reclaimed") {
|
|
9934
|
+
outcomes.push(outcome);
|
|
9935
|
+
continue;
|
|
9936
|
+
}
|
|
9937
|
+
const unsaved = await commitReclaim(outcome, wallet, now, failed);
|
|
9938
|
+
const reported = unsaved ?? outcome;
|
|
9939
|
+
handled.add(reported);
|
|
9940
|
+
outcomes.push(reported);
|
|
9915
9941
|
}
|
|
9916
|
-
|
|
9942
|
+
const rest = outcomes.filter((outcome) => !handled.has(outcome) && mutatesWallet(outcome));
|
|
9943
|
+
if (rest.length > 0) {
|
|
9917
9944
|
try {
|
|
9918
|
-
recordSubmissionVerdicts(
|
|
9919
|
-
} catch {
|
|
9945
|
+
recordSubmissionVerdicts(rest.flatMap(verdictFor));
|
|
9946
|
+
} catch (error) {
|
|
9947
|
+
for (const outcome of rest) failed(outcome.entry.request_id, "verdict_journal", error);
|
|
9920
9948
|
}
|
|
9949
|
+
try {
|
|
9950
|
+
await withWalletLock(() => {
|
|
9951
|
+
const fresh = loadAgentWallet() ?? wallet;
|
|
9952
|
+
const next = rest.reduce((acc, outcome) => applyOutcome(acc, outcome, now), fresh);
|
|
9953
|
+
saveAgentWallet(next);
|
|
9954
|
+
});
|
|
9955
|
+
await applySubmissionVerdicts().catch((error) => failed("", "verdict_apply", error));
|
|
9956
|
+
} catch (error) {
|
|
9957
|
+
for (const outcome of rest) failed(outcome.entry.request_id, "wallet_save", error);
|
|
9958
|
+
}
|
|
9959
|
+
}
|
|
9960
|
+
return result(outcomes);
|
|
9961
|
+
}
|
|
9962
|
+
async function commitReclaim(outcome, wallet, now, failed) {
|
|
9963
|
+
const requestId = outcome.entry.request_id;
|
|
9964
|
+
let alreadySaved = false;
|
|
9965
|
+
try {
|
|
9921
9966
|
await withWalletLock(() => {
|
|
9922
9967
|
const fresh = loadAgentWallet() ?? wallet;
|
|
9923
|
-
|
|
9924
|
-
|
|
9925
|
-
|
|
9926
|
-
|
|
9927
|
-
saveAgentWallet(
|
|
9968
|
+
if (!fresh.pending_submissions.some((s) => s.request_id === requestId)) {
|
|
9969
|
+
alreadySaved = true;
|
|
9970
|
+
return;
|
|
9971
|
+
}
|
|
9972
|
+
saveAgentWallet(applyOutcome(fresh, outcome, now));
|
|
9928
9973
|
});
|
|
9929
|
-
|
|
9974
|
+
} catch (error) {
|
|
9975
|
+
failed(requestId, "wallet_save", error);
|
|
9976
|
+
return { kind: "reclaim_skipped", entry: outcome.entry, reason: RECLAIM_UNSAVED_REASON, terminal: false };
|
|
9930
9977
|
}
|
|
9931
|
-
|
|
9978
|
+
if (alreadySaved) {
|
|
9979
|
+
return {
|
|
9980
|
+
kind: "reclaim_skipped",
|
|
9981
|
+
entry: outcome.entry,
|
|
9982
|
+
reason: "another sweep already saved this reclaim",
|
|
9983
|
+
terminal: false
|
|
9984
|
+
};
|
|
9985
|
+
}
|
|
9986
|
+
try {
|
|
9987
|
+
finalizeLandedReclaims();
|
|
9988
|
+
} catch (error) {
|
|
9989
|
+
failed(requestId, "verdict_journal", error);
|
|
9990
|
+
return null;
|
|
9991
|
+
}
|
|
9992
|
+
await applySubmissionVerdicts().catch((error) => failed(requestId, "verdict_apply", error));
|
|
9993
|
+
return null;
|
|
9932
9994
|
}
|
|
9933
9995
|
function verdictFor(outcome) {
|
|
9934
9996
|
const reserve = outcome.entry.output_proofs.some((proof) => proof.reserved_for !== void 0) ? { reserve: true } : {};
|
|
9935
9997
|
if (outcome.kind === "already_accepted") return [{ requestId: outcome.entry.request_id, verdict: "spent", ...reserve }];
|
|
9936
9998
|
if (outcome.kind !== "reclaimed") return [];
|
|
9937
|
-
return [outcome.
|
|
9999
|
+
return [reclaimVerdict(outcome.entry, outcome.spent_sats)];
|
|
10000
|
+
}
|
|
10001
|
+
function reclaimVerdict(entry, spentSats) {
|
|
10002
|
+
return spentSats > 0 ? { requestId: entry.request_id, verdict: "partly_spent", spentSats, amountSats: entry.amount_sats } : { requestId: entry.request_id, verdict: "reclaimed" };
|
|
9938
10003
|
}
|
|
9939
10004
|
async function recoverPendingSubmission(opts) {
|
|
9940
10005
|
if (!UUID_V4_RE.test(opts.requestId))
|
|
@@ -10205,6 +10270,11 @@ async function reclaimEntry(entry, deps) {
|
|
|
10205
10270
|
} catch (err) {
|
|
10206
10271
|
return skipped(errorText(err));
|
|
10207
10272
|
}
|
|
10273
|
+
const intent = loadReclaimIntent(entry.request_id);
|
|
10274
|
+
if (intent) {
|
|
10275
|
+
const recovered = await recoverReclaimIntent(entry, intent, cashuWallet, deps.lockPubkey);
|
|
10276
|
+
if (recovered) return recovered;
|
|
10277
|
+
}
|
|
10208
10278
|
let grouped;
|
|
10209
10279
|
try {
|
|
10210
10280
|
grouped = await cashuWallet.groupProofsByState(toCashuProofs(entry.output_proofs));
|
|
@@ -10225,8 +10295,9 @@ async function reclaimEntry(entry, deps) {
|
|
|
10225
10295
|
return skipped("the mint still reports some of these proofs in flight");
|
|
10226
10296
|
}
|
|
10227
10297
|
const totalSats = unspent.reduce((sum, p) => sum + p.amount, 0);
|
|
10298
|
+
const spentSats = spent.reduce((sum, p) => sum + p.amount, 0);
|
|
10228
10299
|
const inputs = toCashuProofs(unspent);
|
|
10229
|
-
let
|
|
10300
|
+
let preview;
|
|
10230
10301
|
try {
|
|
10231
10302
|
const swapFeeSats = swapFeeForProofs(cashuWallet, inputs);
|
|
10232
10303
|
const allowance = reclaimFeeAllowance(entry);
|
|
@@ -10246,20 +10317,88 @@ async function reclaimEntry(entry, deps) {
|
|
|
10246
10317
|
true
|
|
10247
10318
|
);
|
|
10248
10319
|
}
|
|
10249
|
-
|
|
10250
|
-
outputs = result.send;
|
|
10320
|
+
preview = await cashuWallet.ops.send(reclaimSats, inputs).privkey(refundPrivkey).asP2PK({ pubkey: deps.lockPubkey }).prepare();
|
|
10251
10321
|
} catch (err) {
|
|
10252
10322
|
const diagnostic = missingDleqRecoveryDiagnostic(inputs, err);
|
|
10253
10323
|
return skipped(diagnostic ?? errorText(err), diagnostic !== null);
|
|
10254
10324
|
}
|
|
10325
|
+
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
10326
|
+
try {
|
|
10327
|
+
recordReclaimIntent({
|
|
10328
|
+
requestId: entry.request_id,
|
|
10329
|
+
mint: entry.mint,
|
|
10330
|
+
keysetId: preview.keysetId,
|
|
10331
|
+
lockPubkey: deps.lockPubkey,
|
|
10332
|
+
outputs: serializeOutputData(preview.sendOutputs ?? []),
|
|
10333
|
+
inputSecrets: unspent.map((p) => p.secret),
|
|
10334
|
+
spentSats,
|
|
10335
|
+
verdict: reclaimVerdict(entry, spentSats),
|
|
10336
|
+
createdAt
|
|
10337
|
+
});
|
|
10338
|
+
} catch (err) {
|
|
10339
|
+
return skipped(`could not record the reclaim before sending it to the mint, so nothing was swapped: ${errorText(err)}`);
|
|
10340
|
+
}
|
|
10341
|
+
let outputs;
|
|
10342
|
+
try {
|
|
10343
|
+
outputs = (await cashuWallet.completeSwap(preview, refundPrivkey)).send;
|
|
10344
|
+
} catch (err) {
|
|
10345
|
+
const diagnostic = missingDleqRecoveryDiagnostic(inputs, err);
|
|
10346
|
+
if (err instanceof te || diagnostic !== null) discardReclaimIntent(entry.request_id, createdAt);
|
|
10347
|
+
return skipped(diagnostic ?? errorText(err), diagnostic !== null);
|
|
10348
|
+
}
|
|
10349
|
+
return reclaimedOutcome(entry, outputs, deps.lockPubkey, spentSats);
|
|
10350
|
+
}
|
|
10351
|
+
function reclaimedOutcome(entry, outputs, lockPubkey, spentSats) {
|
|
10255
10352
|
return {
|
|
10256
10353
|
kind: "reclaimed",
|
|
10257
10354
|
entry,
|
|
10258
|
-
outputs: outputs.map((p) => toAgentProof(p, entry.mint,
|
|
10355
|
+
outputs: outputs.map((p) => toAgentProof(p, entry.mint, lockPubkey)),
|
|
10259
10356
|
reclaimed_sats: outputs.reduce((sum, p) => sum + A.from(p.amount).toNumber(), 0),
|
|
10260
|
-
spent_sats:
|
|
10357
|
+
spent_sats: spentSats
|
|
10261
10358
|
};
|
|
10262
10359
|
}
|
|
10360
|
+
function discardReclaimIntent(requestId, createdAt) {
|
|
10361
|
+
try {
|
|
10362
|
+
clearReclaimIntent(requestId, createdAt);
|
|
10363
|
+
} catch {
|
|
10364
|
+
}
|
|
10365
|
+
}
|
|
10366
|
+
async function recoverReclaimIntent(entry, intent, cashuWallet, lockPubkey) {
|
|
10367
|
+
const skipped = (reason) => ({
|
|
10368
|
+
kind: "reclaim_skipped",
|
|
10369
|
+
entry,
|
|
10370
|
+
reason,
|
|
10371
|
+
terminal: false
|
|
10372
|
+
});
|
|
10373
|
+
let restored = [];
|
|
10374
|
+
let restoreError;
|
|
10375
|
+
try {
|
|
10376
|
+
restored = await restoreProofsFromOutputs(cashuWallet, intent.keysetId, intent.outputs);
|
|
10377
|
+
} catch (err) {
|
|
10378
|
+
restoreError = errorText(err);
|
|
10379
|
+
}
|
|
10380
|
+
if (restored.length > 0) {
|
|
10381
|
+
return restored.length === intent.outputs.length ? reclaimedOutcome(entry, restored, lockPubkey, intent.spentSats) : skipped("the mint restored only part of the reclaim swap's outputs");
|
|
10382
|
+
}
|
|
10383
|
+
const secrets = new Set(intent.inputSecrets);
|
|
10384
|
+
try {
|
|
10385
|
+
const states = await cashuWallet.groupProofsByState(
|
|
10386
|
+
toCashuProofs(entry.output_proofs.filter((proof) => secrets.has(proof.secret)))
|
|
10387
|
+
);
|
|
10388
|
+
if (states.pending.length === 0 && (states.spent.length === 0 || restoreError === void 0)) {
|
|
10389
|
+
if (states.spent.length === 0 && Date.now() - Date.parse(intent.createdAt) < RECLAIM_IN_FLIGHT_MS) {
|
|
10390
|
+
return skipped("another reclaim of this payment may still be in flight; the next sweep checks again");
|
|
10391
|
+
}
|
|
10392
|
+
clearReclaimIntent(entry.request_id, intent.createdAt);
|
|
10393
|
+
return null;
|
|
10394
|
+
}
|
|
10395
|
+
} catch (err) {
|
|
10396
|
+
return skipped(errorText(err));
|
|
10397
|
+
}
|
|
10398
|
+
return skipped(
|
|
10399
|
+
`the reclaim swap spent these proofs at the mint but its outputs cannot be restored yet${restoreError ? ` (${restoreError})` : ""}; the next sweep tries again`
|
|
10400
|
+
);
|
|
10401
|
+
}
|
|
10263
10402
|
function reclaimFeeAllowance(entry) {
|
|
10264
10403
|
const maxSats = entry.max_cashu_fee_sats;
|
|
10265
10404
|
const contextMaxSats = entry.context?.max_cashu_fee_sats;
|
|
@@ -13409,7 +13548,7 @@ function parseStructuredError(body) {
|
|
|
13409
13548
|
if (err && typeof err === "object" && !Array.isArray(err)) {
|
|
13410
13549
|
const e = err;
|
|
13411
13550
|
if (typeof e.code !== "string") return null;
|
|
13412
|
-
return buildStructuredError(e.code, e);
|
|
13551
|
+
return buildStructuredError(e.code, e, parsed);
|
|
13413
13552
|
}
|
|
13414
13553
|
if (typeof err !== "string") return null;
|
|
13415
13554
|
if (err === "invalid_input" || err === "invalid_quote_data") {
|
|
@@ -13425,7 +13564,7 @@ function jobCredentialError(status2, body) {
|
|
|
13425
13564
|
if (status2 !== 401) return null;
|
|
13426
13565
|
return parseStructuredError(body);
|
|
13427
13566
|
}
|
|
13428
|
-
function buildStructuredError(code, fields) {
|
|
13567
|
+
function buildStructuredError(code, fields, envelope = fields) {
|
|
13429
13568
|
const display = typeof fields.display === "string" ? fields.display : void 0;
|
|
13430
13569
|
const providerMessage = typeof fields.message === "string" ? fields.message : void 0;
|
|
13431
13570
|
const message2 = providerMessage ?? display ?? "The provider returned an error without explanatory prose.";
|
|
@@ -13433,10 +13572,10 @@ function buildStructuredError(code, fields) {
|
|
|
13433
13572
|
const data = {};
|
|
13434
13573
|
if (display !== void 0) data.display = display;
|
|
13435
13574
|
if (typeof fields.retryable === "boolean") data.retryable = fields.retryable;
|
|
13436
|
-
if (fields.status === "unknown") data.status =
|
|
13575
|
+
if (fields.status === "unknown" || envelope.status === "unknown") data.status = "unknown";
|
|
13437
13576
|
if (typeof fields.request_id === "string") data.request_id = fields.request_id;
|
|
13438
13577
|
if (fields.server_acceptance === "absent") data.server_acceptance = fields.server_acceptance;
|
|
13439
|
-
if (fields.payment_state === "unknown") data.payment_state =
|
|
13578
|
+
if (fields.payment_state === "unknown" || envelope.payment_state === "unknown") data.payment_state = "unknown";
|
|
13440
13579
|
const detectedSources = providerProseSources(fields, data);
|
|
13441
13580
|
const proseSources = display !== void 0 && providerMessage === void 0 ? { ...detectedSources, message: "provider" } : detectedSources;
|
|
13442
13581
|
return new DvmError(
|
|
@@ -13502,7 +13641,7 @@ function isReceipt402(code) {
|
|
|
13502
13641
|
function buildPaymentError(errorBody) {
|
|
13503
13642
|
if (typeof errorBody.error === "string") return buildStructuredError(errorBody.error, errorBody);
|
|
13504
13643
|
const nested = errorBody.error && typeof errorBody.error === "object" && !Array.isArray(errorBody.error) ? errorBody.error : void 0;
|
|
13505
|
-
if (typeof nested?.code === "string") return buildStructuredError(nested.code, nested);
|
|
13644
|
+
if (typeof nested?.code === "string") return buildStructuredError(nested.code, nested, errorBody);
|
|
13506
13645
|
const error = buildStructuredError("payment_insufficient", errorBody);
|
|
13507
13646
|
error.data = { ...error.data, code_source: "inferred" };
|
|
13508
13647
|
return error;
|
|
@@ -13932,6 +14071,55 @@ function round2(n) {
|
|
|
13932
14071
|
return Math.round(n * 100) / 100;
|
|
13933
14072
|
}
|
|
13934
14073
|
|
|
14074
|
+
// src/lib/terminal-completion.ts
|
|
14075
|
+
async function readTerminalCompletion(args) {
|
|
14076
|
+
const { jobId, status: status2, saved, transport, ref, jobToken } = args;
|
|
14077
|
+
let completion = completionSnapshot(status2);
|
|
14078
|
+
if (!isTerminalJobStatus(status2.status) || status2.content_available === false) return completion;
|
|
14079
|
+
if (completion.hasArtifacts === void 0) {
|
|
14080
|
+
delete completion.artifactCount;
|
|
14081
|
+
delete completion.payloadIn;
|
|
14082
|
+
try {
|
|
14083
|
+
const messages2 = await transport.getMessages(jobId, 0, ref, {
|
|
14084
|
+
jobToken,
|
|
14085
|
+
timeoutMs: args.timeoutMs ?? 5e3
|
|
14086
|
+
});
|
|
14087
|
+
const derived = messages2.length === 0 && saved?.hasArtifacts !== void 0 ? saved : completionFromMessages(messages2);
|
|
14088
|
+
completion = { ...derived, ...completion };
|
|
14089
|
+
} catch {
|
|
14090
|
+
completion = { ...saved, ...completion };
|
|
14091
|
+
}
|
|
14092
|
+
}
|
|
14093
|
+
return completionForStatus(status2.status, completion);
|
|
14094
|
+
}
|
|
14095
|
+
function completionForStatus(status2, input) {
|
|
14096
|
+
const completion = { ...input };
|
|
14097
|
+
if (status2 !== "completed") {
|
|
14098
|
+
if (completion.hasArtifacts === true) completion.payloadIn = "messages";
|
|
14099
|
+
else delete completion.payloadIn;
|
|
14100
|
+
}
|
|
14101
|
+
return completion;
|
|
14102
|
+
}
|
|
14103
|
+
function terminalCompletionOutput(jobId, status2, input, options = {}) {
|
|
14104
|
+
if (!isTerminalJobStatus(status2)) return { fields: {} };
|
|
14105
|
+
const completion = completionForStatus(status2, input);
|
|
14106
|
+
const fields = buildCompletionHintFields(jobId, completion);
|
|
14107
|
+
if (options.contentAvailable === false) {
|
|
14108
|
+
delete fields.next_step_hint;
|
|
14109
|
+
if (fields.payload_in === "messages") delete fields.payload_in;
|
|
14110
|
+
return { fields };
|
|
14111
|
+
}
|
|
14112
|
+
let hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount, options.human);
|
|
14113
|
+
if (completion.hasArtifacts === void 0 && status2 !== "completed") {
|
|
14114
|
+
const job = options.human ? shellQuoteArg(jobId) : guidanceJobArg(jobId);
|
|
14115
|
+
hint = `Any output from finished pieces can be read with 'dvm messages ${job} --no-stream'.`;
|
|
14116
|
+
}
|
|
14117
|
+
if (hint) fields.next_step_hint = hint;
|
|
14118
|
+
const count = typeof completion.artifactCount === "number" && Number.isSafeInteger(completion.artifactCount) && completion.artifactCount >= 0 ? completion.artifactCount : void 0;
|
|
14119
|
+
const display = completion.hasArtifacts === true && hint ? `The job holds ${count === void 0 ? "artifacts" : `${count} artifact${count === 1 ? "" : "s"}`}. ${hint}` : hint;
|
|
14120
|
+
return { fields, hint, display };
|
|
14121
|
+
}
|
|
14122
|
+
|
|
13935
14123
|
// src/lib/dvm-identifier.ts
|
|
13936
14124
|
var TAG_NAME_RE = CAPABILITY_NAME_RE;
|
|
13937
14125
|
var HANDLE_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
|
|
@@ -14180,7 +14368,7 @@ async function settleCreditAfterJob(args) {
|
|
|
14180
14368
|
}
|
|
14181
14369
|
}
|
|
14182
14370
|
if (args.allowTopup !== false) {
|
|
14183
|
-
const refill = args.refillPocket ?? (await import("./pocket-refill-
|
|
14371
|
+
const refill = args.refillPocket ?? (await import("./pocket-refill-XZTMPTP6.js")).refillPocketIfLow;
|
|
14184
14372
|
await refill({ human: args.human }).catch(() => void 0);
|
|
14185
14373
|
}
|
|
14186
14374
|
}
|
|
@@ -14598,7 +14786,10 @@ async function cancelWithAccess(jobId, opts, access) {
|
|
|
14598
14786
|
if (!access.endpointOverridden) markJobTerminal(
|
|
14599
14787
|
jobId,
|
|
14600
14788
|
"cancelled",
|
|
14601
|
-
|
|
14789
|
+
{
|
|
14790
|
+
...stored?.status === "cancelled" ? stored.completion : {},
|
|
14791
|
+
...opts.reason !== void 0 ? { message: opts.reason } : {}
|
|
14792
|
+
},
|
|
14602
14793
|
{ callerCancelled: true }
|
|
14603
14794
|
);
|
|
14604
14795
|
const { settlement, status: status2 } = await readEnding({
|
|
@@ -14612,10 +14803,28 @@ async function cancelWithAccess(jobId, opts, access) {
|
|
|
14612
14803
|
if (!access.endpointOverridden) clearAskPaymentBlocks(jobId);
|
|
14613
14804
|
}
|
|
14614
14805
|
});
|
|
14806
|
+
const saved = stored?.status === "cancelled" ? stored.completion : void 0;
|
|
14807
|
+
const completion = await readTerminalCompletion({
|
|
14808
|
+
jobId,
|
|
14809
|
+
status: status2 ?? { status: "cancelled" },
|
|
14810
|
+
saved,
|
|
14811
|
+
transport,
|
|
14812
|
+
ref,
|
|
14813
|
+
jobToken
|
|
14814
|
+
});
|
|
14815
|
+
if (!access.endpointOverridden) markJobTerminal(jobId, "cancelled", {
|
|
14816
|
+
...status2?.content_available === false && saved ? saved : completion,
|
|
14817
|
+
...opts.reason !== void 0 ? { message: opts.reason } : {}
|
|
14818
|
+
});
|
|
14819
|
+
const artifacts = terminalCompletionOutput(jobId, "cancelled", completion, {
|
|
14820
|
+
human: opts.human,
|
|
14821
|
+
contentAvailable: status2?.content_available
|
|
14822
|
+
});
|
|
14615
14823
|
transport.close();
|
|
14616
14824
|
const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
|
|
14617
14825
|
const receiptPending = !settlement && status2 !== void 0 && isTerminalJobStatus(status2.status) && !status2.receipt && !status2.receiptParseError && !access.endpointOverridden && expectsReceipt(jobId, stored);
|
|
14618
|
-
const
|
|
14826
|
+
const endingDisplay = settlement ? cancelledDisplay(settlement) : receiptPending ? `Stopped. Its receipt is not available yet; \`dvm status ${guidanceJobArg(jobId)}\` shows what was charged once it is.` : void 0;
|
|
14827
|
+
const display = [endingDisplay, artifacts.display].filter(Boolean).join(" ") || void 0;
|
|
14619
14828
|
const hint = settlementCurrencyHint(settlement, ref.endpoint);
|
|
14620
14829
|
if (opts.human) {
|
|
14621
14830
|
info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""} cancelled.`);
|
|
@@ -14629,6 +14838,7 @@ async function cancelWithAccess(jobId, opts, access) {
|
|
|
14629
14838
|
...opts.reason ? { reason: opts.reason } : {},
|
|
14630
14839
|
...settlement ? { settlement } : {},
|
|
14631
14840
|
...display ? { display } : {},
|
|
14841
|
+
...artifacts.fields,
|
|
14632
14842
|
...hint ? { hint } : {},
|
|
14633
14843
|
next_action: null
|
|
14634
14844
|
});
|
|
@@ -14666,16 +14876,19 @@ async function declineWithAccess(jobId, opts, access) {
|
|
|
14666
14876
|
markJobTerminal(
|
|
14667
14877
|
jobId,
|
|
14668
14878
|
status2.status,
|
|
14669
|
-
|
|
14879
|
+
{
|
|
14880
|
+
...stored?.status === status2.status ? stored.completion : {},
|
|
14881
|
+
...opts.reason !== void 0 ? { message: opts.reason } : {}
|
|
14882
|
+
},
|
|
14670
14883
|
{ callerCancelled: true, callerDeclined: true }
|
|
14671
14884
|
);
|
|
14672
14885
|
clearAskPaymentBlocks(jobId);
|
|
14673
14886
|
}
|
|
14674
14887
|
}
|
|
14675
14888
|
});
|
|
14676
|
-
transport.close();
|
|
14677
14889
|
const observed = ending.status?.status;
|
|
14678
14890
|
if (observed !== void 0 && !isTerminalJobStatus(observed)) {
|
|
14891
|
+
transport.close();
|
|
14679
14892
|
throw new DvmError(
|
|
14680
14893
|
"decline_unsupported",
|
|
14681
14894
|
`The provider accepted the decline, but the job is still ${observed}.`,
|
|
@@ -14683,9 +14896,30 @@ async function declineWithAccess(jobId, opts, access) {
|
|
|
14683
14896
|
{ jobId, status: observed }
|
|
14684
14897
|
);
|
|
14685
14898
|
}
|
|
14899
|
+
const completion = ending.status ? await readTerminalCompletion({
|
|
14900
|
+
jobId,
|
|
14901
|
+
status: ending.status,
|
|
14902
|
+
transport,
|
|
14903
|
+
ref,
|
|
14904
|
+
jobToken,
|
|
14905
|
+
saved: stored && stored.status === observed ? stored.completion : void 0
|
|
14906
|
+
}) : {};
|
|
14907
|
+
if (observed && isTerminalJobStatus(observed) && !access.endpointOverridden) {
|
|
14908
|
+
const saved = stored?.status === observed ? stored.completion : void 0;
|
|
14909
|
+
markJobTerminal(jobId, observed, {
|
|
14910
|
+
...ending.status?.content_available === false && saved ? saved : completion,
|
|
14911
|
+
...opts.reason !== void 0 ? { message: opts.reason } : {}
|
|
14912
|
+
});
|
|
14913
|
+
}
|
|
14914
|
+
const artifacts = terminalCompletionOutput(jobId, observed ?? "unknown", completion, {
|
|
14915
|
+
human: opts.human,
|
|
14916
|
+
contentAvailable: ending.status?.content_available
|
|
14917
|
+
});
|
|
14918
|
+
transport.close();
|
|
14686
14919
|
const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
|
|
14687
14920
|
const { settlement } = ending;
|
|
14688
|
-
const
|
|
14921
|
+
const endingDisplay = observed === void 0 ? `Decline sent, but the job's status could not be read. Check it with \`dvm status ${job}\`.` : settlement ? `Declined; the job has ended. ${settlement.display}` : `Declined; the job has ended. Its receipt is not available yet; \`dvm status ${job}\` shows the final charge once it is.`;
|
|
14922
|
+
const display = [endingDisplay, artifacts.display].filter(Boolean).join(" ");
|
|
14689
14923
|
const hint = settlementCurrencyHint(settlement, ref.endpoint);
|
|
14690
14924
|
if (opts.human) {
|
|
14691
14925
|
info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""}: ${display}`);
|
|
@@ -14700,6 +14934,7 @@ async function declineWithAccess(jobId, opts, access) {
|
|
|
14700
14934
|
...opts.reason !== void 0 ? { reason: opts.reason } : {},
|
|
14701
14935
|
...settlement ? { settlement } : {},
|
|
14702
14936
|
display,
|
|
14937
|
+
...artifacts.fields,
|
|
14703
14938
|
...hint ? { hint } : {},
|
|
14704
14939
|
next_action: observed === void 0 ? pollNextAction(jobId, display) : null
|
|
14705
14940
|
});
|
|
@@ -15456,8 +15691,9 @@ async function creditOp(transport, endpoint, body, payment) {
|
|
|
15456
15691
|
function advisoryBtcRate() {
|
|
15457
15692
|
return tryResolveBtcUsdRate().then((resolved) => resolved?.rate).catch(() => void 0);
|
|
15458
15693
|
}
|
|
15459
|
-
function implicitCreditJson(credit) {
|
|
15694
|
+
function implicitCreditJson(credit, postureOff) {
|
|
15460
15695
|
const active2 = credit.status === "active";
|
|
15696
|
+
const blocked = active2 && postureOff;
|
|
15461
15697
|
const amount = formatFiat(Math.max(credit.remainingMicro, 0) / 1e6, credit.currency);
|
|
15462
15698
|
const label = dvmLabelFromEndpoint(credit.endpoint);
|
|
15463
15699
|
return {
|
|
@@ -15471,7 +15707,8 @@ function implicitCreditJson(credit) {
|
|
|
15471
15707
|
expiry_ms: credit.expiryMs,
|
|
15472
15708
|
status: credit.status,
|
|
15473
15709
|
tracked: true,
|
|
15474
|
-
drawable: active2,
|
|
15710
|
+
drawable: active2 && !postureOff,
|
|
15711
|
+
...blocked ? { draw_blocked_reason: "posture_off" } : {},
|
|
15475
15712
|
drainable: false,
|
|
15476
15713
|
released_by_job_id: credit.releasedByJobId,
|
|
15477
15714
|
released_at_ms: credit.releasedAt,
|
|
@@ -15486,7 +15723,7 @@ function implicitCreditJson(credit) {
|
|
|
15486
15723
|
job_id: credit.discrepancy.jobId
|
|
15487
15724
|
}
|
|
15488
15725
|
} : {},
|
|
15489
|
-
display: active2 ? `${amount} released by an unsuccessful per-call job at ${label}; the next eligible request spends it automatically before prepaid credit.` : `${amount} released per-call balance at ${label} is lost; implicit credits have no drain path after expiry or server retirement.`,
|
|
15726
|
+
display: blocked ? `${amount} released per-call balance is held at ${label}, but spending it is switched off by credit posture; no drain path is available.` : active2 ? `${amount} released by an unsuccessful per-call job at ${label}; the next eligible request spends it automatically before prepaid credit.` : `${amount} released per-call balance at ${label} is lost; implicit credits have no drain path after expiry or server retirement.`,
|
|
15490
15727
|
hint: active2 ? `Use it promptly. ${new Date(credit.expiryMs).toISOString()} is the latest possible expiry inferred from the receipt; the server may retire it earlier. No funding menu or new payment is needed.` : "No reclaim action is available. A provider must offer prepaid credit for unused value to have a drain path."
|
|
15491
15728
|
};
|
|
15492
15729
|
}
|
|
@@ -15498,6 +15735,7 @@ function currencyTotal(totals, currency) {
|
|
|
15498
15735
|
trackedCount: 0,
|
|
15499
15736
|
siblingCount: 0,
|
|
15500
15737
|
drawableMicro: 0,
|
|
15738
|
+
postureBlockedMicro: 0,
|
|
15501
15739
|
siblingSpendableMicro: 0
|
|
15502
15740
|
};
|
|
15503
15741
|
totals.set(currency, created);
|
|
@@ -15512,8 +15750,9 @@ function creditCurrencyTotalsJson(total, source) {
|
|
|
15512
15750
|
tracked_count: total.trackedCount,
|
|
15513
15751
|
sibling_count: total.siblingCount,
|
|
15514
15752
|
drawable_micro: total.drawableMicro,
|
|
15753
|
+
...total.postureBlockedMicro > 0 ? { posture_blocked_micro: total.postureBlockedMicro } : {},
|
|
15515
15754
|
sibling_spendable_micro: total.siblingSpendableMicro,
|
|
15516
|
-
spendable_micro: total.drawableMicro + total.siblingSpendableMicro,
|
|
15755
|
+
spendable_micro: total.drawableMicro + total.postureBlockedMicro + total.siblingSpendableMicro,
|
|
15517
15756
|
display: creditCurrencyTotalDisplay(total, source)
|
|
15518
15757
|
};
|
|
15519
15758
|
}
|
|
@@ -15525,10 +15764,14 @@ function creditCurrencyTotalDisplay(total, source) {
|
|
|
15525
15764
|
const drawable = formatFiat(total.drawableMicro / 1e6, total.currency);
|
|
15526
15765
|
const sibling = formatFiat(total.siblingSpendableMicro / 1e6, total.currency);
|
|
15527
15766
|
const spendable = formatFiat(
|
|
15528
|
-
(total.drawableMicro + total.siblingSpendableMicro) / 1e6,
|
|
15767
|
+
(total.drawableMicro + total.postureBlockedMicro + total.siblingSpendableMicro) / 1e6,
|
|
15529
15768
|
total.currency
|
|
15530
15769
|
);
|
|
15531
15770
|
const certainty = source === "local" ? "believed" : "server-confirmed";
|
|
15771
|
+
if (total.postureBlockedMicro > 0) {
|
|
15772
|
+
const blocked = formatFiat(total.postureBlockedMicro / 1e6, total.currency);
|
|
15773
|
+
return `${spendable} ${certainty} spendable: ${drawable} drawable from tracked credits, ${blocked} held but spending switched off by credit posture, and ${sibling} held on sibling credits that draws do not use.`;
|
|
15774
|
+
}
|
|
15532
15775
|
return total.siblingSpendableMicro > 0 ? `${spendable} ${certainty} spendable: ${drawable} drawable from tracked credits, and ${sibling} held on sibling credits that draws do not use.` : `${drawable} ${certainty} spendable, all drawable from tracked credits; no sibling spendable balance is recorded in ${total.currency.toUpperCase()}.`;
|
|
15533
15776
|
}
|
|
15534
15777
|
function headroomReader() {
|
|
@@ -15708,9 +15951,11 @@ async function balanceAt(transport, endpoint, signer, headroomOf, advisoryRate,
|
|
|
15708
15951
|
}
|
|
15709
15952
|
const providerInfo = await transport.describe({ endpoint }).catch(() => void 0);
|
|
15710
15953
|
const identity = providerDvmIdentity(providerInfo);
|
|
15954
|
+
const postureOff = effectiveCreditPosture(loadConfig()?.credit, endpoint, identity).posture === "off";
|
|
15711
15955
|
if (!providerInfo)
|
|
15712
15956
|
throw new DvmError("provider_unavailable", "Could not read provider metadata.");
|
|
15713
|
-
const
|
|
15957
|
+
const localImplicitCredits = loadImplicitCredits(endpoint, signer.pubkey, identity);
|
|
15958
|
+
const implicitCredits = localImplicitCredits.filter(
|
|
15714
15959
|
(credit) => !creditId || credit.creditId === creditId
|
|
15715
15960
|
);
|
|
15716
15961
|
const signCredit = (body) => signDvmRequestData(
|
|
@@ -15747,7 +15992,7 @@ async function balanceAt(transport, endpoint, signer, headroomOf, advisoryRate,
|
|
|
15747
15992
|
}
|
|
15748
15993
|
} catch (err) {
|
|
15749
15994
|
if (err instanceof DvmError && err.code === "credit_not_supported") {
|
|
15750
|
-
const rows = implicitCredits.map(implicitCreditJson);
|
|
15995
|
+
const rows = implicitCredits.map((credit) => implicitCreditJson(credit, postureOff));
|
|
15751
15996
|
return {
|
|
15752
15997
|
rows: rows.length > 0 ? rows : [
|
|
15753
15998
|
{
|
|
@@ -15804,16 +16049,18 @@ async function balanceAt(transport, endpoint, signer, headroomOf, advisoryRate,
|
|
|
15804
16049
|
...btcRate !== void 0 ? { btcRate } : {}
|
|
15805
16050
|
});
|
|
15806
16051
|
const liveIds = new Set(credits.map((credit) => credit.credit_id));
|
|
16052
|
+
const implicitById = new Map(localImplicitCredits.map((credit) => [credit.creditId, credit]));
|
|
15807
16053
|
return {
|
|
15808
16054
|
rows: [
|
|
15809
16055
|
...credits.map(
|
|
15810
|
-
(credit) => wireCreditJson(
|
|
16056
|
+
(credit) => credit.credit_id.startsWith("imp:") ? wireImplicitCreditJson(endpoint, credit, implicitById.get(credit.credit_id), postureOff) : wireCreditJson(
|
|
15811
16057
|
endpoint,
|
|
15812
16058
|
credit,
|
|
15813
|
-
credit.credit_id === currentStored?.creditId && currentStored.selectionCleared !== true
|
|
16059
|
+
credit.credit_id === currentStored?.creditId && currentStored.selectionCleared !== true,
|
|
16060
|
+
postureOff
|
|
15814
16061
|
)
|
|
15815
16062
|
),
|
|
15816
|
-
...implicitCredits.filter((credit) => !liveIds.has(credit.creditId)).map(implicitCreditJson)
|
|
16063
|
+
...implicitCredits.filter((credit) => !liveIds.has(credit.creditId)).map((credit) => implicitCreditJson(credit, postureOff))
|
|
15817
16064
|
],
|
|
15818
16065
|
// Emitted even when `credits` is empty: the server just stated its menu, so
|
|
15819
16066
|
// this read answers "what could I open here" without a second round trip.
|
|
@@ -15829,7 +16076,25 @@ function advisoryBtcRateOnce() {
|
|
|
15829
16076
|
let pending4;
|
|
15830
16077
|
return () => pending4 ??= advisoryBtcRate();
|
|
15831
16078
|
}
|
|
15832
|
-
function
|
|
16079
|
+
function wireImplicitCreditJson(endpoint, credit, local, postureOff) {
|
|
16080
|
+
const label = dvmLabelFromEndpoint(endpoint);
|
|
16081
|
+
const amount = formatFiat(Math.max(credit.remaining_micro, 0) / 1e6, credit.currency);
|
|
16082
|
+
const unavailable = credit.status === "unbacked" ? "backing finalized before collection" : credit.reconciliation_pending ? "backing reconciliation pending" : credit.expired ? "expired" : !local ? "no receipt-backed release is tracked for this caller at this DVM" : local.status !== "active" || local.expiryMs <= Date.now() ? "the local release is lost" : local.remainingMicro <= 0 || credit.remaining_micro <= 0 ? "no released value is available for draws" : void 0;
|
|
16083
|
+
const blocked = unavailable === void 0 && postureOff;
|
|
16084
|
+
return {
|
|
16085
|
+
endpoint,
|
|
16086
|
+
dvm: label,
|
|
16087
|
+
...credit,
|
|
16088
|
+
kind: "implicit",
|
|
16089
|
+
tracked: local !== void 0,
|
|
16090
|
+
drawable: unavailable === void 0 && !postureOff,
|
|
16091
|
+
...blocked ? { draw_blocked_reason: "posture_off" } : {},
|
|
16092
|
+
drainable: false,
|
|
16093
|
+
...local ? { released_by_job_id: local.releasedByJobId, released_at_ms: local.releasedAt } : {},
|
|
16094
|
+
display: blocked ? `${amount} released per-call balance is held at ${label}, but spending it is switched off by credit posture; no drain path is available.` : unavailable !== void 0 ? `${amount} released per-call balance at ${label} (${unavailable}; not drawable). No drain path is available.` : `${amount} released by an unsuccessful per-call job at ${label}; the next eligible request spends it automatically before prepaid credit.`
|
|
16095
|
+
};
|
|
16096
|
+
}
|
|
16097
|
+
function wireCreditJson(endpoint, credit, tracked, postureOff) {
|
|
15833
16098
|
const label = dvmLabelFromEndpoint(endpoint);
|
|
15834
16099
|
const unbacked = credit.status === "unbacked";
|
|
15835
16100
|
const amount = formatFiat(
|
|
@@ -15838,14 +16103,18 @@ function wireCreditJson(endpoint, credit, tracked) {
|
|
|
15838
16103
|
);
|
|
15839
16104
|
const state = unbacked ? "closed \u2014 backing finalized before collection" : credit.reconciliation_pending ? "backing reconciliation pending" : credit.expired ? "expired \u2014 balance reclaimable" : "spendable";
|
|
15840
16105
|
const command = creditDrainCommand(endpoint, credit.credit_id);
|
|
16106
|
+
const active2 = !credit.expired && !unbacked && !credit.reconciliation_pending;
|
|
16107
|
+
const eligible = tracked && active2;
|
|
16108
|
+
const blocked = postureOff && eligible;
|
|
15841
16109
|
return {
|
|
15842
16110
|
endpoint,
|
|
15843
16111
|
dvm: label,
|
|
15844
16112
|
...credit,
|
|
15845
16113
|
tracked,
|
|
15846
|
-
drawable:
|
|
16114
|
+
drawable: eligible && !postureOff,
|
|
16115
|
+
...blocked ? { draw_blocked_reason: "posture_off" } : {},
|
|
15847
16116
|
...!tracked && credit.drainable ? { drain_command: command } : {},
|
|
15848
|
-
display: tracked ? unbacked ? `${amount} of former credit at ${label} (${state}; no action is available).` : credit.reconciliation_pending ? `${amount} of credit at ${label} (${state}, tracked locally but not drawable).` : credit.expired ? `${amount} of credit at ${label} (${state}, tracked locally but not drawable).` : `${amount} of credit at ${label} (${state}, tracked for draws).` : `${amount} on sibling credit ${credit.credit_id} at ${label} (${state}, not used for draws).`,
|
|
16117
|
+
display: blocked ? `${amount} of credit is held at ${label}, but spending it is switched off by credit posture${credit.drainable ? "; balance remains reclaimable" : ""}.` : tracked ? unbacked ? `${amount} of former credit at ${label} (${state}; no action is available).` : credit.reconciliation_pending ? `${amount} of credit at ${label} (${state}, tracked locally but not drawable).` : credit.expired ? `${amount} of credit at ${label} (${state}, tracked locally but not drawable).` : `${amount} of credit at ${label} (${state}, tracked for draws).` : `${amount} on sibling credit ${credit.credit_id} at ${label} (${state}, not used for draws).`,
|
|
15849
16118
|
...!tracked && credit.drainable ? { hint: `Reclaim it with this command: ${command}` } : {}
|
|
15850
16119
|
};
|
|
15851
16120
|
}
|
|
@@ -15860,7 +16129,9 @@ function wireCreditCurrencyTotals(rows) {
|
|
|
15860
16129
|
else total.siblingCount += 1;
|
|
15861
16130
|
if (row.expired === true) continue;
|
|
15862
16131
|
if (row.drawable === true) total.drawableMicro += Math.max(row.remaining_micro, 0);
|
|
15863
|
-
else if (
|
|
16132
|
+
else if (row.draw_blocked_reason === "posture_off") {
|
|
16133
|
+
total.postureBlockedMicro += Math.max(row.remaining_micro, 0);
|
|
16134
|
+
} else if (!row.tracked && row.drainable === true) {
|
|
15864
16135
|
total.siblingSpendableMicro += Math.max(row.remaining_micro, 0);
|
|
15865
16136
|
}
|
|
15866
16137
|
}
|
|
@@ -20315,16 +20586,17 @@ function creditList(opts) {
|
|
|
20315
20586
|
const creditConfig = loadConfig()?.credit;
|
|
20316
20587
|
const headroomOf = headroomReader();
|
|
20317
20588
|
const identityOf = (endpoint) => offlineDvmIdentity(creditConfig, endpoint, headroomOf);
|
|
20318
|
-
const postureOf = (
|
|
20589
|
+
const postureOf = (row) => effectiveCreditPosture(creditConfig, row.endpoint, dvmLocationIdentity(row) ?? identityOf(row.endpoint));
|
|
20590
|
+
const postureOff = (row) => postureOf(row).posture === "off";
|
|
20319
20591
|
const fundingRailOf = (endpoint) => effectiveFundingRail(creditConfig, endpoint, identityOf(endpoint));
|
|
20320
20592
|
const globalPosture = isCreditPosture(creditConfig?.posture) ? { posture: creditConfig.posture, source: "global" } : { posture: DEFAULT_CREDIT_POSTURE, source: "default" };
|
|
20321
20593
|
const globalRail = effectiveFundingRail(creditConfig);
|
|
20322
20594
|
const siblingCredits = credits.flatMap((credit) => credit.siblingCredits ?? []);
|
|
20323
|
-
const totals = localCreditCurrencyTotals(credits, implicitCredits);
|
|
20595
|
+
const totals = localCreditCurrencyTotals(credits, implicitCredits, postureOff);
|
|
20324
20596
|
if (opts.human) {
|
|
20325
20597
|
info(humanPostureLine(globalPosture));
|
|
20326
20598
|
for (const [endpoint, per] of postureOverrides(creditConfig)) {
|
|
20327
|
-
info(` At ${dvmLabelFromEndpoint(endpoint)}: ${per} (overrides the global setting)
|
|
20599
|
+
info(` At ${dvmLabelFromEndpoint(endpoint)}: ${per} (overrides the global setting).${per === "off" ? " Spending held credit is also switched off." : ""}`);
|
|
20328
20600
|
}
|
|
20329
20601
|
info(humanFundingRailLine(globalRail));
|
|
20330
20602
|
for (const [endpoint, rail] of fundingRailOverrides(creditConfig)) {
|
|
@@ -20338,13 +20610,13 @@ function creditList(opts) {
|
|
|
20338
20610
|
return;
|
|
20339
20611
|
}
|
|
20340
20612
|
for (const c of credits) {
|
|
20341
|
-
info(` ${humanCreditRow(c)}`);
|
|
20613
|
+
info(` ${humanCreditRow(c, postureOff(c))}`);
|
|
20342
20614
|
for (const sibling of c.siblingCredits ?? []) {
|
|
20343
20615
|
info(` ${humanSiblingCreditRow(c, sibling)}`);
|
|
20344
20616
|
}
|
|
20345
20617
|
info(` ${headroomDisplay(headroomOf.of(headroomInputsFor(c, identityOf(c.endpoint))))}`);
|
|
20346
20618
|
}
|
|
20347
|
-
for (const row of humanImplicitCreditRows(implicitCredits)) info(` ${row}`);
|
|
20619
|
+
for (const row of humanImplicitCreditRows(implicitCredits, postureOff)) info(` ${row}`);
|
|
20348
20620
|
for (const snapshot of snapshots) {
|
|
20349
20621
|
const machine = cachedDvmJson(snapshot, credits, headroomOf, identityOf(snapshot.endpoint));
|
|
20350
20622
|
info(` ${String(machine.display)}`);
|
|
@@ -20378,19 +20650,19 @@ function creditList(opts) {
|
|
|
20378
20650
|
hint: `Pin it with 'dvm credit rail <${CREDIT_FUND_RAILS.join("|")}>' or return to the amount rule with 'dvm credit rail --clear'; add --dvm <dvm> to scope either operation.`
|
|
20379
20651
|
},
|
|
20380
20652
|
credits: credits.map((c) => ({
|
|
20381
|
-
...storedCreditJson(c, headroomOf.of(headroomInputsFor(c, identityOf(c.endpoint)))),
|
|
20382
|
-
...postureFields(postureOf(c
|
|
20653
|
+
...storedCreditJson(c, headroomOf.of(headroomInputsFor(c, identityOf(c.endpoint))), postureOff(c)),
|
|
20654
|
+
...postureFields(postureOf(c)),
|
|
20383
20655
|
...fundingRailFields(fundingRailOf(c.endpoint))
|
|
20384
20656
|
})),
|
|
20385
20657
|
count: credits.length,
|
|
20386
|
-
implicit_credits: implicitCredits.map(implicitCreditJson),
|
|
20658
|
+
implicit_credits: implicitCredits.map((c) => implicitCreditJson(c, postureOff(c))),
|
|
20387
20659
|
implicit_count: implicitCredits.length,
|
|
20388
20660
|
credit_count: credits.length + siblingCredits.length + implicitCredits.length,
|
|
20389
20661
|
sibling_count: siblingCredits.length,
|
|
20390
20662
|
totals_by_currency: totals.map((total) => creditCurrencyTotalsJson(total, "local")),
|
|
20391
20663
|
dvms: snapshots.map((snapshot) => ({
|
|
20392
20664
|
...cachedDvmJson(snapshot, credits, headroomOf, identityOf(snapshot.endpoint)),
|
|
20393
|
-
...postureFields(postureOf(snapshot
|
|
20665
|
+
...postureFields(postureOf(snapshot)),
|
|
20394
20666
|
...fundingRailFields(fundingRailOf(snapshot.endpoint))
|
|
20395
20667
|
})),
|
|
20396
20668
|
dvm_count: snapshots.length,
|
|
@@ -20437,14 +20709,15 @@ function postureSentence(posture) {
|
|
|
20437
20709
|
case "auto":
|
|
20438
20710
|
return "credit is bought within the trust-tier caps without asking, and every purchase reports its amount, route and reason.";
|
|
20439
20711
|
case "off":
|
|
20440
|
-
return "no multi-job credit is opened
|
|
20712
|
+
return "no multi-job credit is opened or refilled, and spending held credit is switched off; every job pays per-call.";
|
|
20441
20713
|
case "suggest":
|
|
20442
20714
|
return "nothing is ever bought automatically; where a credit would have helped, the job output says so and names how to fund it.";
|
|
20443
20715
|
}
|
|
20444
20716
|
}
|
|
20445
20717
|
function humanPostureLine(effective) {
|
|
20446
20718
|
const provenance = effective.source === "global" ? "set in config" : "the default";
|
|
20447
|
-
|
|
20719
|
+
const subject = effective.posture === "off" ? "Credit purchases and spending" : "Automatic credit purchases";
|
|
20720
|
+
return `${subject}: ${effective.posture} (${provenance}) \u2014 ${postureSentence(effective.posture)}`;
|
|
20448
20721
|
}
|
|
20449
20722
|
function postureAdoptionSentence(posture) {
|
|
20450
20723
|
switch (posture) {
|
|
@@ -20483,8 +20756,9 @@ function fundingRailFields(effective) {
|
|
|
20483
20756
|
funding_rail_source: effective.source
|
|
20484
20757
|
};
|
|
20485
20758
|
}
|
|
20486
|
-
function storedCreditJson(c, headroom) {
|
|
20759
|
+
function storedCreditJson(c, headroom, postureOff) {
|
|
20487
20760
|
const channelId = storedCreditChannelId(c);
|
|
20761
|
+
const eligible = c.selectionCleared !== true && c.status === "active" && !c.reconciliationPending;
|
|
20488
20762
|
return {
|
|
20489
20763
|
endpoint: c.endpoint,
|
|
20490
20764
|
dvm: dvmLabelFromEndpoint(c.endpoint),
|
|
@@ -20498,7 +20772,8 @@ function storedCreditJson(c, headroom) {
|
|
|
20498
20772
|
...channelId ? { channel_id: channelId } : {},
|
|
20499
20773
|
...c.reconciliationPending ? { reconciliation_pending: true } : {},
|
|
20500
20774
|
tracked: c.selectionCleared !== true,
|
|
20501
|
-
drawable:
|
|
20775
|
+
drawable: eligible && !postureOff,
|
|
20776
|
+
...eligible && postureOff ? { draw_blocked_reason: "posture_off" } : {},
|
|
20502
20777
|
...c.siblingCredits ? { sibling_credits: c.siblingCredits.map((sibling) => siblingCreditJson(c, sibling)) } : {},
|
|
20503
20778
|
...c.provisional ? { provisional: true } : {},
|
|
20504
20779
|
...c.pendingDrains?.length ? { pending_drains: c.pendingDrains.map(pendingDrainJson) } : {},
|
|
@@ -20514,7 +20789,7 @@ function storedCreditJson(c, headroom) {
|
|
|
20514
20789
|
}
|
|
20515
20790
|
} : {},
|
|
20516
20791
|
headroom: headroomJson(headroom),
|
|
20517
|
-
display: humanCreditRow(c)
|
|
20792
|
+
display: humanCreditRow(c, postureOff)
|
|
20518
20793
|
};
|
|
20519
20794
|
}
|
|
20520
20795
|
function storedCreditChannelId(credit) {
|
|
@@ -20548,13 +20823,14 @@ function siblingCreditJson(record2, sibling) {
|
|
|
20548
20823
|
...sibling.drainable ? { hint: `Reclaim it with this command: ${command}` } : {}
|
|
20549
20824
|
};
|
|
20550
20825
|
}
|
|
20551
|
-
function localCreditCurrencyTotals(credits, implicitCredits
|
|
20826
|
+
function localCreditCurrencyTotals(credits, implicitCredits, postureOff) {
|
|
20552
20827
|
const totals = /* @__PURE__ */ new Map();
|
|
20553
20828
|
for (const credit of credits) {
|
|
20554
20829
|
const tracked = currencyTotal(totals, credit.currency);
|
|
20555
20830
|
tracked.trackedCount += 1;
|
|
20556
20831
|
if (credit.status === "active" && !credit.reconciliationPending) {
|
|
20557
|
-
tracked.
|
|
20832
|
+
if (postureOff(credit)) tracked.postureBlockedMicro += Math.max(credit.remainingMicro, 0);
|
|
20833
|
+
else tracked.drawableMicro += Math.max(credit.remainingMicro, 0);
|
|
20558
20834
|
}
|
|
20559
20835
|
for (const sibling of credit.siblingCredits ?? []) {
|
|
20560
20836
|
const siblingTotal = currencyTotal(totals, sibling.currency);
|
|
@@ -20567,7 +20843,10 @@ function localCreditCurrencyTotals(credits, implicitCredits = []) {
|
|
|
20567
20843
|
for (const credit of implicitCredits) {
|
|
20568
20844
|
const total = currencyTotal(totals, credit.currency);
|
|
20569
20845
|
total.trackedCount += 1;
|
|
20570
|
-
if (credit.status === "active")
|
|
20846
|
+
if (credit.status === "active") {
|
|
20847
|
+
if (postureOff(credit)) total.postureBlockedMicro += Math.max(credit.remainingMicro, 0);
|
|
20848
|
+
else total.drawableMicro += Math.max(credit.remainingMicro, 0);
|
|
20849
|
+
}
|
|
20571
20850
|
}
|
|
20572
20851
|
return sortedCurrencyTotals(totals);
|
|
20573
20852
|
}
|
|
@@ -20734,7 +21013,7 @@ function pendingFundingsDisplay(pending4) {
|
|
|
20734
21013
|
function drainReceiptCount(c) {
|
|
20735
21014
|
return (c.drainEvidence ?? []).reduce((sum, e) => sum + e.receipts.length, 0);
|
|
20736
21015
|
}
|
|
20737
|
-
function humanCreditRow(c) {
|
|
21016
|
+
function humanCreditRow(c, postureOff) {
|
|
20738
21017
|
const label = dvmLabelFromEndpoint(c.endpoint).padEnd(12);
|
|
20739
21018
|
const amount = formatFiat(
|
|
20740
21019
|
Math.max(c.status === "unbacked" ? c.balanceMicro : c.remainingMicro, 0) / 1e6,
|
|
@@ -20744,6 +21023,7 @@ function humanCreditRow(c) {
|
|
|
20744
21023
|
const stranded = others.filter((d) => d.creditId !== void 0).length;
|
|
20745
21024
|
const unattributed = others.length - stranded;
|
|
20746
21025
|
const flags = [
|
|
21026
|
+
postureOff && c.status === "active" && !c.reconciliationPending ? "held but spending switched off by credit posture; balance remains reclaimable" : void 0,
|
|
20747
21027
|
c.status !== "active" ? c.status : void 0,
|
|
20748
21028
|
c.reconciliationPending ? "backing reconciliation pending" : void 0,
|
|
20749
21029
|
c.provisional ? "syncing" : void 0,
|
|
@@ -20756,10 +21036,10 @@ function humanCreditRow(c) {
|
|
|
20756
21036
|
const expiry = c.expiryMs > 0 ? ` \xB7 expires ${new Date(c.expiryMs).toISOString().slice(0, 10)}` : "";
|
|
20757
21037
|
return `${label} ${amount}${expiry}${flags ? ` \xB7 ${flags}` : ""}`;
|
|
20758
21038
|
}
|
|
20759
|
-
function humanImplicitCreditRows(credits) {
|
|
21039
|
+
function humanImplicitCreditRows(credits, postureOff) {
|
|
20760
21040
|
const groups = /* @__PURE__ */ new Map();
|
|
20761
21041
|
for (const credit of credits) {
|
|
20762
|
-
const key = `${credit.endpoint}\0${credit.currency}\0${credit.status}`;
|
|
21042
|
+
const key = `${credit.endpoint}\0${credit.currency}\0${credit.status}\0${postureOff(credit)}`;
|
|
20763
21043
|
const group = groups.get(key) ?? [];
|
|
20764
21044
|
group.push(credit);
|
|
20765
21045
|
groups.set(key, group);
|
|
@@ -20775,6 +21055,9 @@ function humanImplicitCreditRows(credits) {
|
|
|
20775
21055
|
if (first.status === "lost") {
|
|
20776
21056
|
return `${label} ${amount} across ${count} \xB7 lost; no drain path is available`;
|
|
20777
21057
|
}
|
|
21058
|
+
if (postureOff(first)) {
|
|
21059
|
+
return `${label} ${amount} across ${count} \xB7 held but spending switched off by credit posture; no drain path is available`;
|
|
21060
|
+
}
|
|
20778
21061
|
const expiry = Math.min(...group.map((credit) => credit.expiryMs));
|
|
20779
21062
|
return `${label} ${amount} across ${count} \xB7 next request uses the earliest expiry first \xB7 expires by ${new Date(expiry).toISOString().slice(0, 10)}`;
|
|
20780
21063
|
});
|
|
@@ -21760,18 +22043,85 @@ function findPackageRoot(start) {
|
|
|
21760
22043
|
}
|
|
21761
22044
|
|
|
21762
22045
|
// src/lib/caller-state.ts
|
|
21763
|
-
import { existsSync as
|
|
21764
|
-
import { basename, join as
|
|
22046
|
+
import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
|
|
22047
|
+
import { basename, join as join5 } from "path";
|
|
22048
|
+
|
|
22049
|
+
// src/lib/request-refusal-store.ts
|
|
22050
|
+
import {
|
|
22051
|
+
closeSync as closeSync2,
|
|
22052
|
+
existsSync as existsSync4,
|
|
22053
|
+
fsyncSync as fsyncSync2,
|
|
22054
|
+
openSync as openSync2,
|
|
22055
|
+
readFileSync as readFileSync4,
|
|
22056
|
+
renameSync as renameSync2,
|
|
22057
|
+
rmSync,
|
|
22058
|
+
writeFileSync as writeFileSync2
|
|
22059
|
+
} from "fs";
|
|
22060
|
+
import { join as join4 } from "path";
|
|
22061
|
+
var REQUEST_REFUSALS_DIR = join4(CONFIG_DIR, "request-refusals");
|
|
22062
|
+
var SAFE_TOKEN = /^[a-z0-9_.:-]{1,64}$/;
|
|
22063
|
+
function requestIntentMayExist(requestId) {
|
|
22064
|
+
return existsSync4(join4(REQUEST_INTENTS_DIR, requestId));
|
|
22065
|
+
}
|
|
22066
|
+
function recordRequestRefusal(requestId, refusal) {
|
|
22067
|
+
if (!isPublicRequestId(requestId) || requestIntentMayExist(requestId)) return false;
|
|
22068
|
+
const record2 = {
|
|
22069
|
+
v: 1,
|
|
22070
|
+
requestId,
|
|
22071
|
+
code: SAFE_TOKEN.test(refusal.code) ? refusal.code : "refused",
|
|
22072
|
+
...typeof refusal.reason === "string" && SAFE_TOKEN.test(refusal.reason) ? { reason: refusal.reason } : {},
|
|
22073
|
+
refusedAt: Date.now()
|
|
22074
|
+
};
|
|
22075
|
+
try {
|
|
22076
|
+
ensureConfigSubdir(REQUEST_REFUSALS_DIR);
|
|
22077
|
+
const target = refusalPath(requestId);
|
|
22078
|
+
const temp = `${target}.${String(process.pid)}.tmp`;
|
|
22079
|
+
const fd = openSync2(temp, "w", 384);
|
|
22080
|
+
try {
|
|
22081
|
+
writeFileSync2(fd, JSON.stringify(record2, null, 2) + "\n");
|
|
22082
|
+
fsyncSync2(fd);
|
|
22083
|
+
} finally {
|
|
22084
|
+
closeSync2(fd);
|
|
22085
|
+
}
|
|
22086
|
+
renameSync2(temp, target);
|
|
22087
|
+
} catch {
|
|
22088
|
+
}
|
|
22089
|
+
return true;
|
|
22090
|
+
}
|
|
22091
|
+
function clearRequestRefusal(requestId) {
|
|
22092
|
+
if (!isPublicRequestId(requestId)) return;
|
|
22093
|
+
try {
|
|
22094
|
+
rmSync(refusalPath(requestId), { force: true });
|
|
22095
|
+
} catch {
|
|
22096
|
+
}
|
|
22097
|
+
}
|
|
22098
|
+
function loadRequestRefusal(requestId) {
|
|
22099
|
+
if (!isPublicRequestId(requestId)) return null;
|
|
22100
|
+
try {
|
|
22101
|
+
const parsed = JSON.parse(readFileSync4(refusalPath(requestId), "utf8"));
|
|
22102
|
+
if (parsed.v !== 1 || parsed.requestId !== requestId || typeof parsed.code !== "string" || typeof parsed.refusedAt !== "number" || parsed.reason !== void 0 && typeof parsed.reason !== "string") {
|
|
22103
|
+
return null;
|
|
22104
|
+
}
|
|
22105
|
+
return parsed;
|
|
22106
|
+
} catch {
|
|
22107
|
+
return null;
|
|
22108
|
+
}
|
|
22109
|
+
}
|
|
22110
|
+
function refusalPath(requestId) {
|
|
22111
|
+
return join4(REQUEST_REFUSALS_DIR, `${requestId}.json`);
|
|
22112
|
+
}
|
|
22113
|
+
|
|
22114
|
+
// src/lib/caller-state.ts
|
|
21765
22115
|
function detectSetupState() {
|
|
21766
22116
|
return {
|
|
21767
22117
|
existingState: {
|
|
21768
|
-
jobs:
|
|
21769
|
-
messages:
|
|
22118
|
+
jobs: existsSync5(JOBS_FILE),
|
|
22119
|
+
messages: existsSync5(MESSAGES_DIR)
|
|
21770
22120
|
},
|
|
21771
22121
|
missing: {
|
|
21772
|
-
config: !
|
|
21773
|
-
identity: !
|
|
21774
|
-
wallet: !
|
|
22122
|
+
config: !existsSync5(CONFIG_FILE),
|
|
22123
|
+
identity: !existsSync5(IDENTITIES_FILE),
|
|
22124
|
+
wallet: !existsSync5(WALLET_FILE)
|
|
21775
22125
|
}
|
|
21776
22126
|
};
|
|
21777
22127
|
}
|
|
@@ -21866,6 +22216,13 @@ var FILE_SPECS = [
|
|
|
21866
22216
|
secret: false,
|
|
21867
22217
|
directory: true
|
|
21868
22218
|
},
|
|
22219
|
+
{
|
|
22220
|
+
name: "request_refusals",
|
|
22221
|
+
path: REQUEST_REFUSALS_DIR,
|
|
22222
|
+
json: false,
|
|
22223
|
+
secret: false,
|
|
22224
|
+
directory: true
|
|
22225
|
+
},
|
|
21869
22226
|
{ name: "messages", path: MESSAGES_DIR, json: false, secret: false, directory: true },
|
|
21870
22227
|
// Evidence of paid calls accepted without a settled job identity. Each file
|
|
21871
22228
|
// is 0600 because a record can hold an anonymous job's access token, so
|
|
@@ -21894,17 +22251,17 @@ function findQuarantinedCreditStores() {
|
|
|
21894
22251
|
} catch {
|
|
21895
22252
|
return [];
|
|
21896
22253
|
}
|
|
21897
|
-
return entries.filter((name) => name.startsWith(prefix)).sort((a, b) => a < b ? 1 : a > b ? -1 : 0).map((name) => ({ path:
|
|
22254
|
+
return entries.filter((name) => name.startsWith(prefix)).sort((a, b) => a < b ? 1 : a > b ? -1 : 0).map((name) => ({ path: join5(CONFIG_DIR, name), name }));
|
|
21898
22255
|
}
|
|
21899
22256
|
function checkOne(spec) {
|
|
21900
|
-
const exists =
|
|
22257
|
+
const exists = existsSync5(spec.path);
|
|
21901
22258
|
if (!exists) {
|
|
21902
22259
|
return { name: spec.name, path: spec.path, exists: false };
|
|
21903
22260
|
}
|
|
21904
22261
|
const row = { name: spec.name, path: spec.path, exists: true };
|
|
21905
22262
|
if (spec.json) {
|
|
21906
22263
|
try {
|
|
21907
|
-
JSON.parse(
|
|
22264
|
+
JSON.parse(readFileSync5(spec.path, "utf-8"));
|
|
21908
22265
|
row.parseable = true;
|
|
21909
22266
|
} catch (err) {
|
|
21910
22267
|
row.parseable = false;
|
|
@@ -21933,7 +22290,7 @@ function checkSecretDirectory(dir, row) {
|
|
|
21933
22290
|
try {
|
|
21934
22291
|
const offenders = [];
|
|
21935
22292
|
for (const name of readdirSync2(dir)) {
|
|
21936
|
-
const path =
|
|
22293
|
+
const path = join5(dir, name);
|
|
21937
22294
|
const stat2 = statSync2(path);
|
|
21938
22295
|
if (!stat2.isFile()) continue;
|
|
21939
22296
|
const mode = stat2.mode & 511;
|
|
@@ -21954,9 +22311,9 @@ function octalMode(mode) {
|
|
|
21954
22311
|
return "0" + mode.toString(8).padStart(3, "0");
|
|
21955
22312
|
}
|
|
21956
22313
|
function readBtcRateCacheAge(now = Date.now()) {
|
|
21957
|
-
if (!
|
|
22314
|
+
if (!existsSync5(BTC_RATE_FILE)) return null;
|
|
21958
22315
|
try {
|
|
21959
|
-
const data = JSON.parse(
|
|
22316
|
+
const data = JSON.parse(readFileSync5(BTC_RATE_FILE, "utf-8"));
|
|
21960
22317
|
if (typeof data.timestamp !== "number") return null;
|
|
21961
22318
|
return { ageMs: now - data.timestamp };
|
|
21962
22319
|
} catch {
|
|
@@ -21966,7 +22323,7 @@ function readBtcRateCacheAge(now = Date.now()) {
|
|
|
21966
22323
|
|
|
21967
22324
|
// src/lib/mnemonic-backups.ts
|
|
21968
22325
|
import { readdirSync as readdirSync3, statSync as statSync3 } from "fs";
|
|
21969
|
-
import { basename as basename2, dirname as dirname3, join as
|
|
22326
|
+
import { basename as basename2, dirname as dirname3, join as join6 } from "path";
|
|
21970
22327
|
function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
|
|
21971
22328
|
const dir = dirname3(mnemonicFile);
|
|
21972
22329
|
const prefix = `${basename2(mnemonicFile)}.`;
|
|
@@ -21978,7 +22335,7 @@ function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
|
|
|
21978
22335
|
throw err;
|
|
21979
22336
|
}
|
|
21980
22337
|
return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
|
|
21981
|
-
const path =
|
|
22338
|
+
const path = join6(dir, name);
|
|
21982
22339
|
const stat2 = statSync3(path);
|
|
21983
22340
|
if (!stat2.isFile()) return null;
|
|
21984
22341
|
const ageMs2 = Math.max(0, nowMs - stat2.mtimeMs);
|
|
@@ -22018,8 +22375,8 @@ function formatMnemonicBackupAge(ageMs2) {
|
|
|
22018
22375
|
}
|
|
22019
22376
|
|
|
22020
22377
|
// src/lib/wallet-agent/submissions-view.ts
|
|
22021
|
-
function describePendingSubmissions(wallet, nowMs = Date.now()) {
|
|
22022
|
-
const entries = wallet.pending_submissions.map((entry) => toView(entry, nowMs));
|
|
22378
|
+
function describePendingSubmissions(wallet, nowMs = Date.now(), reclaimUnsaved = reclaimIntentIds()) {
|
|
22379
|
+
const entries = wallet.pending_submissions.map((entry) => toView(entry, nowMs, reclaimUnsaved.has(entry.request_id)));
|
|
22023
22380
|
return {
|
|
22024
22381
|
entries,
|
|
22025
22382
|
at_risk_sats: entries.filter((e) => e.at_risk).reduce((sum, e) => sum + e.amount_sats, 0),
|
|
@@ -22162,12 +22519,12 @@ function describeSubmissionEvidence(records) {
|
|
|
22162
22519
|
};
|
|
22163
22520
|
});
|
|
22164
22521
|
}
|
|
22165
|
-
function toView(entry, nowMs) {
|
|
22522
|
+
function toView(entry, nowMs, reclaimUnsaved) {
|
|
22166
22523
|
const createdMs = Date.parse(entry.created_at);
|
|
22167
22524
|
const ageMs2 = Number.isNaN(createdMs) ? Number.POSITIVE_INFINITY : nowMs - createdMs;
|
|
22168
22525
|
const attempts = entry.attempts ?? 0;
|
|
22169
22526
|
const reclaimAt = reclaimAtMs(entry);
|
|
22170
|
-
const state = deriveState(entry, ageMs2, attempts, reclaimAt);
|
|
22527
|
+
const state = reclaimUnsaved ? "reclaim_failed" : deriveState(entry, ageMs2, attempts, reclaimAt);
|
|
22171
22528
|
return {
|
|
22172
22529
|
request_id: entry.request_id,
|
|
22173
22530
|
endpoint: entry.endpoint,
|
|
@@ -22178,10 +22535,15 @@ function toView(entry, nowMs) {
|
|
|
22178
22535
|
state,
|
|
22179
22536
|
at_risk: state !== "awaiting_swap",
|
|
22180
22537
|
reclaim_at: reclaimAt === null ? null : new Date(reclaimAt).toISOString(),
|
|
22181
|
-
reclaim_error: state === "reclaim_failed" || state === "unreclaimable" ? entry.reclaim_error ?? null : null,
|
|
22538
|
+
reclaim_error: reclaimUnsaved ? RECLAIM_UNSAVED_REASON : state === "reclaim_failed" || state === "unreclaimable" ? entry.reclaim_error ?? null : null,
|
|
22182
22539
|
...entry.accepted_unresolved ? { accepted_unresolved: entry.accepted_unresolved } : {},
|
|
22183
22540
|
...publicRequestIdOf(entry) ? { public_request_id: publicRequestIdOf(entry) } : {},
|
|
22184
|
-
display: describe4(
|
|
22541
|
+
display: describe4(
|
|
22542
|
+
reclaimUnsaved ? { ...entry, reclaim_error: RECLAIM_UNSAVED_REASON } : entry,
|
|
22543
|
+
state,
|
|
22544
|
+
reclaimAt,
|
|
22545
|
+
nowMs
|
|
22546
|
+
)
|
|
22185
22547
|
};
|
|
22186
22548
|
}
|
|
22187
22549
|
function locateAdvice(entry, publicRequestId = publicRequestIdOf(entry)) {
|
|
@@ -23869,11 +24231,11 @@ async function favRm(name, opts) {
|
|
|
23869
24231
|
}
|
|
23870
24232
|
|
|
23871
24233
|
// src/lib/byte-source.ts
|
|
23872
|
-
import { readFileSync as
|
|
24234
|
+
import { readFileSync as readFileSync6 } from "fs";
|
|
23873
24235
|
import { resolve as resolve2 } from "path";
|
|
23874
24236
|
var STDIN_TIMEOUT_MS2 = 1e4;
|
|
23875
24237
|
function readFileText(path) {
|
|
23876
|
-
return
|
|
24238
|
+
return readFileSync6(resolve2(path), "utf-8");
|
|
23877
24239
|
}
|
|
23878
24240
|
var StdinTimeoutError = class extends Error {
|
|
23879
24241
|
constructor(timeoutMs) {
|
|
@@ -24037,7 +24399,7 @@ function callerPlatformResponseError(code, remote, fallbackMessage) {
|
|
|
24037
24399
|
}
|
|
24038
24400
|
|
|
24039
24401
|
// src/lib/feedback-nudges.ts
|
|
24040
|
-
import { existsSync as
|
|
24402
|
+
import { existsSync as existsSync6, readFileSync as readFileSync7, renameSync as renameSync3, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
|
|
24041
24403
|
|
|
24042
24404
|
// src/lib/feedback-notice.ts
|
|
24043
24405
|
function buildFeedbackNudge(args) {
|
|
@@ -24089,10 +24451,10 @@ function effectiveFeedbackPosture(config2) {
|
|
|
24089
24451
|
return { posture: DEFAULT_FEEDBACK_POSTURE, source: "default" };
|
|
24090
24452
|
}
|
|
24091
24453
|
function loadFeedbackNudgeState() {
|
|
24092
|
-
if (!
|
|
24454
|
+
if (!existsSync6(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
|
|
24093
24455
|
try {
|
|
24094
24456
|
const parsed = JSON.parse(
|
|
24095
|
-
|
|
24457
|
+
readFileSync7(FEEDBACK_NUDGES_FILE, "utf-8")
|
|
24096
24458
|
);
|
|
24097
24459
|
return {
|
|
24098
24460
|
...typeof parsed.introShownAt === "string" ? { introShownAt: parsed.introShownAt } : {},
|
|
@@ -24181,9 +24543,9 @@ function coercePerDvm(perDvm) {
|
|
|
24181
24543
|
function saveState(state) {
|
|
24182
24544
|
ensureConfigDir();
|
|
24183
24545
|
const tmp = `${FEEDBACK_NUDGES_FILE}.${process.pid}.tmp`;
|
|
24184
|
-
|
|
24546
|
+
writeFileSync3(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
|
|
24185
24547
|
try {
|
|
24186
|
-
|
|
24548
|
+
renameSync3(tmp, FEEDBACK_NUDGES_FILE);
|
|
24187
24549
|
} catch (err) {
|
|
24188
24550
|
try {
|
|
24189
24551
|
unlinkSync(tmp);
|
|
@@ -24195,9 +24557,9 @@ function saveState(state) {
|
|
|
24195
24557
|
var nudgedThisInvocation = false;
|
|
24196
24558
|
|
|
24197
24559
|
// src/lib/platform.ts
|
|
24198
|
-
import { existsSync as
|
|
24560
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "fs";
|
|
24199
24561
|
import { homedir as homedir2 } from "os";
|
|
24200
|
-
import { join as
|
|
24562
|
+
import { join as join7 } from "path";
|
|
24201
24563
|
function getPlatformUrl() {
|
|
24202
24564
|
return process.env.DVMKIT_PLATFORM_URL ?? "https://api.dvmkit.dev";
|
|
24203
24565
|
}
|
|
@@ -24766,16 +25128,16 @@ function finalizeProgressLine() {
|
|
|
24766
25128
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
24767
25129
|
import {
|
|
24768
25130
|
chmodSync,
|
|
24769
|
-
closeSync as
|
|
25131
|
+
closeSync as closeSync3,
|
|
24770
25132
|
mkdtempSync,
|
|
24771
|
-
openSync as
|
|
25133
|
+
openSync as openSync3,
|
|
24772
25134
|
readdirSync as readdirSync4,
|
|
24773
25135
|
rmdirSync,
|
|
24774
25136
|
unlinkSync as unlinkSync2,
|
|
24775
|
-
writeFileSync as
|
|
25137
|
+
writeFileSync as writeFileSync5
|
|
24776
25138
|
} from "fs";
|
|
24777
25139
|
import { tmpdir } from "os";
|
|
24778
|
-
import { join as
|
|
25140
|
+
import { join as join8 } from "path";
|
|
24779
25141
|
|
|
24780
25142
|
// src/lib/mime-ext.ts
|
|
24781
25143
|
var MIME_TO_EXT = {
|
|
@@ -24831,11 +25193,11 @@ var ArtifactSaveSession = class {
|
|
|
24831
25193
|
let created = false;
|
|
24832
25194
|
try {
|
|
24833
25195
|
const directory = this.ensureDirectory();
|
|
24834
|
-
path =
|
|
24835
|
-
fd =
|
|
25196
|
+
path = join8(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
|
|
25197
|
+
fd = openSync3(path, "wx", FILE_MODE);
|
|
24836
25198
|
created = true;
|
|
24837
|
-
|
|
24838
|
-
|
|
25199
|
+
writeFileSync5(fd, buf);
|
|
25200
|
+
closeSync3(fd);
|
|
24839
25201
|
fd = void 0;
|
|
24840
25202
|
chmodSync(path, FILE_MODE);
|
|
24841
25203
|
this.successfulWrites += 1;
|
|
@@ -24843,7 +25205,7 @@ var ArtifactSaveSession = class {
|
|
|
24843
25205
|
} catch (err) {
|
|
24844
25206
|
if (fd !== void 0) {
|
|
24845
25207
|
try {
|
|
24846
|
-
|
|
25208
|
+
closeSync3(fd);
|
|
24847
25209
|
} catch {
|
|
24848
25210
|
}
|
|
24849
25211
|
}
|
|
@@ -24860,7 +25222,7 @@ var ArtifactSaveSession = class {
|
|
|
24860
25222
|
}
|
|
24861
25223
|
ensureDirectory() {
|
|
24862
25224
|
if (this.directory) return this.directory;
|
|
24863
|
-
const directory = mkdtempSync(
|
|
25225
|
+
const directory = mkdtempSync(join8(tmpdir(), "dvm-artifacts-"));
|
|
24864
25226
|
try {
|
|
24865
25227
|
chmodSync(directory, DIRECTORY_MODE);
|
|
24866
25228
|
} catch (err) {
|
|
@@ -25020,6 +25382,19 @@ function printNextActionHuman(action, options = {}) {
|
|
|
25020
25382
|
if (line) info(line);
|
|
25021
25383
|
}
|
|
25022
25384
|
|
|
25385
|
+
// src/lib/read-next-action.ts
|
|
25386
|
+
function readNextAction(jobId, messages2, options = {}) {
|
|
25387
|
+
const answered = options.ignoreLocalState ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(jobId);
|
|
25388
|
+
const pending4 = messages2.filter((message2) => !answered.has(message2.seq));
|
|
25389
|
+
const action = computeNextAction(jobId, pending4, void 0, options.ignoreLocalState ? void 0 : options.context);
|
|
25390
|
+
if (action?.type !== "pay" || options.ignoreLocalState) return action;
|
|
25391
|
+
const request2 = pendingPaymentRequest(pending4);
|
|
25392
|
+
const held = loadJob(jobId);
|
|
25393
|
+
if (request2 && held && (held.inFlightPaymentRequestSeqs?.includes(request2.seq) || held.unconfirmedPaymentSubmissions?.[request2.seq] || held.askPaymentBlocks?.[request2.seq]))
|
|
25394
|
+
return { ...action, hint: paymentInFlightHint(jobId, held, request2.seq) };
|
|
25395
|
+
return action;
|
|
25396
|
+
}
|
|
25397
|
+
|
|
25023
25398
|
// src/lib/wait-for-job.ts
|
|
25024
25399
|
async function waitForJob(opts, durationMs, now = Date.now) {
|
|
25025
25400
|
const deadline = now() + durationMs;
|
|
@@ -25181,13 +25556,7 @@ async function messagesWithAccess(jobId, opts, access) {
|
|
|
25181
25556
|
const { stored, ref, jobToken } = access;
|
|
25182
25557
|
const json3 = (data) => providerJobJson(data, !!stored);
|
|
25183
25558
|
function actionFromMessages(batch) {
|
|
25184
|
-
|
|
25185
|
-
const action = computeNextAction(jobId, batch.filter((message2) => !answered.has(message2.seq)), void 0, access.endpointOverridden ? void 0 : stored ?? void 0);
|
|
25186
|
-
const request2 = batch.findLast((message2) => message2.type === "payment-request");
|
|
25187
|
-
const current = access.endpointOverridden ? null : loadJob(jobId);
|
|
25188
|
-
if (action?.type === "pay" && request2 && current && (current.inFlightPaymentRequestSeqs?.includes(request2.seq) || current.unconfirmedPaymentSubmissions?.[request2.seq] || current.askPaymentBlocks?.[request2.seq]))
|
|
25189
|
-
return { ...action, hint: paymentInFlightHint(jobId, current, request2.seq) };
|
|
25190
|
-
return action;
|
|
25559
|
+
return readNextAction(jobId, batch, { ignoreLocalState: access.endpointOverridden, context: stored ?? void 0 });
|
|
25191
25560
|
}
|
|
25192
25561
|
async function resolveNextAction2(action, messages2, observedStatus) {
|
|
25193
25562
|
if (action?.type === "refund") return action;
|
|
@@ -26663,8 +27032,9 @@ async function refetchAnchor(endpointOrAlias) {
|
|
|
26663
27032
|
function deliveredFromMessages(jobId, receipt) {
|
|
26664
27033
|
const messages2 = loadMessages(jobId);
|
|
26665
27034
|
if (messages2.length === 0) return void 0;
|
|
26666
|
-
|
|
26667
|
-
|
|
27035
|
+
const job = loadJob(jobId);
|
|
27036
|
+
if (!messages2.some((m) => isCompleteMessage(m) || isCancelMessage(m) || m.type === "decline" && job?.callerDeclined === true && isTerminalJobStatus(job.status))) return void 0;
|
|
27037
|
+
const completion = job?.completion;
|
|
26668
27038
|
if (completion?.hasArtifacts === void 0) return void 0;
|
|
26669
27039
|
const artifacts = messages2.filter(isArtifactMessage);
|
|
26670
27040
|
if (artifacts.length !== (completion.artifactCount ?? 0)) return void 0;
|
|
@@ -27125,9 +27495,23 @@ function resolveBudget(current, minimumMsats) {
|
|
|
27125
27495
|
|
|
27126
27496
|
// src/commands/request.ts
|
|
27127
27497
|
async function request(opts) {
|
|
27128
|
-
|
|
27498
|
+
const stage = { intentReached: false };
|
|
27499
|
+
return withOutputWarnings(async () => {
|
|
27500
|
+
try {
|
|
27501
|
+
await requestWithWarnings(opts, stage);
|
|
27502
|
+
} catch (error) {
|
|
27503
|
+
throw stage.intentReached ? error : markRefusedBeforeSend(opts.requestId, error);
|
|
27504
|
+
}
|
|
27505
|
+
});
|
|
27129
27506
|
}
|
|
27130
|
-
|
|
27507
|
+
function markRefusedBeforeSend(requestId, error) {
|
|
27508
|
+
if (!requestId || !(error instanceof DvmError)) return error;
|
|
27509
|
+
const reason = error.data?.reason;
|
|
27510
|
+
if (!recordRequestRefusal(requestId, { code: error.code, reason })) return error;
|
|
27511
|
+
error.data = { ...error.data, submitted: false };
|
|
27512
|
+
return error;
|
|
27513
|
+
}
|
|
27514
|
+
async function requestWithWarnings(opts, stage) {
|
|
27131
27515
|
const artifactSession = opts.human ? createArtifactSaveSession() : void 0;
|
|
27132
27516
|
const timeout = opts.timeout ? Number(opts.timeout) * 1e3 : 3e4;
|
|
27133
27517
|
const requestedMaxCashuFeeSats = parseMaxCashuFeeSats(opts.maxCashuFeeSats);
|
|
@@ -27380,7 +27764,7 @@ async function requestWithWarnings(opts) {
|
|
|
27380
27764
|
throw new DvmError(
|
|
27381
27765
|
"credit_only_unavailable",
|
|
27382
27766
|
`Prepaid credit ${opts.creditOnly} is not drawable under the current caller state.`,
|
|
27383
|
-
"Reconcile that exact credit with 'dvm credit balance <dvm> --credit-id <id>'; this request did not fall back to a wallet payment.",
|
|
27767
|
+
probePlan.mode === "none" && probePlan.drawSkipped?.reason === "posture_off" ? buildCreditDrawSkipped({ dvm: identity.dvmId ?? endpoint, endpoint, skip: probePlan.drawSkipped }).hint : "Reconcile that exact credit with 'dvm credit balance <dvm> --credit-id <id>'; this request did not fall back to a wallet payment.",
|
|
27384
27768
|
{
|
|
27385
27769
|
credit_id: opts.creditOnly,
|
|
27386
27770
|
...probePlan.mode === "none" && probePlan.drawSkipped ? { reason: probePlan.drawSkipped.reason } : {}
|
|
@@ -27419,6 +27803,7 @@ async function requestWithWarnings(opts) {
|
|
|
27419
27803
|
}
|
|
27420
27804
|
let envelope = { ...envelopeBase, data };
|
|
27421
27805
|
let jobRequestId = opts.requestId ?? drawRequestId;
|
|
27806
|
+
stage.intentReached = true;
|
|
27422
27807
|
if (jobRequestId) {
|
|
27423
27808
|
persistRequestIntent({
|
|
27424
27809
|
requestId: jobRequestId,
|
|
@@ -28750,6 +29135,7 @@ function persistRequestIntent(args) {
|
|
|
28750
29135
|
{ request_id: requestId, status: "unknown" }
|
|
28751
29136
|
);
|
|
28752
29137
|
}
|
|
29138
|
+
clearRequestRefusal(requestId);
|
|
28753
29139
|
}
|
|
28754
29140
|
function submitCanCarryGeneratedRequestId(args) {
|
|
28755
29141
|
return args.opts.requestId === void 0 && args.opts.creditOnly === void 0 && args.providerInfo.requestRecovery === true && args.providerInfo.auth?.includes(SIGNED_REQUEST_AUTH_ID) === true && args.signing !== void 0;
|
|
@@ -28801,7 +29187,21 @@ function requestIdOutputFields(requestId) {
|
|
|
28801
29187
|
function normalizedLocalCorrelationId(opts) {
|
|
28802
29188
|
return opts.localCorrelationId === void 0 ? void 0 : normalizeLocalCorrelationId(opts.localCorrelationId);
|
|
28803
29189
|
}
|
|
29190
|
+
var PREACCEPT_REFUSAL_CODES = /* @__PURE__ */ new Set([
|
|
29191
|
+
"invalid_input",
|
|
29192
|
+
"budget_exceeded",
|
|
29193
|
+
"cashu_fee_cap_exceeded",
|
|
29194
|
+
"insufficient_balance",
|
|
29195
|
+
"no_eligible_mint",
|
|
29196
|
+
"mint_not_allowed",
|
|
29197
|
+
"mint_pin_unsatisfiable",
|
|
29198
|
+
"rail_unsatisfiable",
|
|
29199
|
+
"tempo_network_mismatch"
|
|
29200
|
+
]);
|
|
28804
29201
|
function requestOutcomeUnknown(requestId, cause) {
|
|
29202
|
+
if (cause instanceof DvmError && PREACCEPT_REFUSAL_CODES.has(cause.code) && !postPaymentErrors.has(cause) && cause.data?.spend_committed !== true && cause.data?.status !== "unknown" && cause.data?.payment_state !== "unknown") {
|
|
29203
|
+
return cause;
|
|
29204
|
+
}
|
|
28805
29205
|
if (cause instanceof DvmError && typeof cause.data?.job_id === "string" && loadJob(cause.data.job_id)?.requestId === requestId) {
|
|
28806
29206
|
return cause;
|
|
28807
29207
|
}
|
|
@@ -29876,11 +30276,9 @@ async function requestResult(requestId, opts = {}) {
|
|
|
29876
30276
|
}
|
|
29877
30277
|
const intent = loadRequestIntent(requestId);
|
|
29878
30278
|
if (!intent) {
|
|
29879
|
-
throw
|
|
29880
|
-
|
|
29881
|
-
|
|
29882
|
-
"The outcome is unknown. Do not submit or pay for a replacement; restore the original caller state and retry.",
|
|
29883
|
-
{ request_id: requestId, status: "unknown" }
|
|
30279
|
+
throw requestNotFound(
|
|
30280
|
+
requestId,
|
|
30281
|
+
"The outcome is unknown. Do not submit or pay for a replacement; restore the original caller state and retry."
|
|
29884
30282
|
);
|
|
29885
30283
|
}
|
|
29886
30284
|
const signer = findSigningIdentityByPubkey(intent.callerPubkey);
|
|
@@ -30030,6 +30428,30 @@ async function requestResult(requestId, opts = {}) {
|
|
|
30030
30428
|
}
|
|
30031
30429
|
});
|
|
30032
30430
|
}
|
|
30431
|
+
function requestNotFound(requestId, unknownHint) {
|
|
30432
|
+
const refusal = loadRequestRefusal(requestId);
|
|
30433
|
+
if (!refusal) {
|
|
30434
|
+
return new DvmError(
|
|
30435
|
+
"request_not_found",
|
|
30436
|
+
`No local intent exists for request ${requestId}.`,
|
|
30437
|
+
unknownHint,
|
|
30438
|
+
{ request_id: requestId, status: "unknown" }
|
|
30439
|
+
);
|
|
30440
|
+
}
|
|
30441
|
+
return new DvmError(
|
|
30442
|
+
"request_not_submitted",
|
|
30443
|
+
`Request ${requestId} was refused locally before it was sent.`,
|
|
30444
|
+
"No job or payment was sent for this request id. Retrying the same approved request is safe.",
|
|
30445
|
+
{
|
|
30446
|
+
request_id: requestId,
|
|
30447
|
+
status: "not_submitted",
|
|
30448
|
+
submitted: false,
|
|
30449
|
+
refusal_code: refusal.code,
|
|
30450
|
+
...refusal.reason ? { refusal_reason: refusal.reason } : {},
|
|
30451
|
+
refused_at: new Date(refusal.refusedAt).toISOString()
|
|
30452
|
+
}
|
|
30453
|
+
);
|
|
30454
|
+
}
|
|
30033
30455
|
function signedIntentEnvelope(intent, privkey, route) {
|
|
30034
30456
|
const body = intent.body;
|
|
30035
30457
|
const data = body.data;
|
|
@@ -30091,11 +30513,9 @@ async function resumeRequest(requestId, opts) {
|
|
|
30091
30513
|
}
|
|
30092
30514
|
const intent = loadRequestIntent(requestId);
|
|
30093
30515
|
if (!intent) {
|
|
30094
|
-
throw
|
|
30095
|
-
|
|
30096
|
-
|
|
30097
|
-
"The outcome is unknown. Restore the original caller state; never submit or pay for a replacement.",
|
|
30098
|
-
{ request_id: requestId, status: "unknown" }
|
|
30516
|
+
throw requestNotFound(
|
|
30517
|
+
requestId,
|
|
30518
|
+
"The outcome is unknown. Restore the original caller state; never submit or pay for a replacement."
|
|
30099
30519
|
);
|
|
30100
30520
|
}
|
|
30101
30521
|
const signer = findSigningIdentityByPubkey(intent.callerPubkey);
|
|
@@ -30432,14 +30852,16 @@ async function status(jobId, opts) {
|
|
|
30432
30852
|
}
|
|
30433
30853
|
async function statusWithAccess(jobId, opts, access) {
|
|
30434
30854
|
const { stored, ref, jobToken } = access;
|
|
30435
|
-
if (stored && !access.overridden && isTerminalJobStatus(stored.status) && stored.completion && !opts.messages) {
|
|
30855
|
+
if (stored && !access.overridden && isTerminalJobStatus(stored.status) && (stored.completion || stored.status !== "completed") && !opts.messages) {
|
|
30436
30856
|
let receipt2 = replayStoredReceipt(stored);
|
|
30437
30857
|
let terminalStatus = stored.status;
|
|
30438
|
-
let completion2 = stored.completion;
|
|
30858
|
+
let completion2 = stored.completion ?? {};
|
|
30859
|
+
let content;
|
|
30439
30860
|
const transport2 = createDvmTransport();
|
|
30440
30861
|
if (stored.receiptsSupported && receipt2.status === "absent") {
|
|
30441
30862
|
const fetched = await fetchMissingJobReceipt(jobId, transport2, ref);
|
|
30442
30863
|
if (fetched.status && isTerminalJobStatus(fetched.status)) {
|
|
30864
|
+
content = fetched;
|
|
30443
30865
|
const saved = stored.status === fetched.status ? completion2 : void 0;
|
|
30444
30866
|
terminalStatus = fetched.status;
|
|
30445
30867
|
completion2 = fetched.content_available === false && saved ? saved : { ...saved, ...completionSnapshot(fetched) };
|
|
@@ -30452,10 +30874,21 @@ async function statusWithAccess(jobId, opts, access) {
|
|
|
30452
30874
|
receipt2 = captureTransportReceipt(jobId, fetched);
|
|
30453
30875
|
}
|
|
30454
30876
|
}
|
|
30877
|
+
if (terminalStatus !== "completed" && completion2.hasArtifacts === void 0 && content?.content_available !== false) {
|
|
30878
|
+
completion2 = await readTerminalCompletion({
|
|
30879
|
+
jobId,
|
|
30880
|
+
status: { ...completion2, ...content, status: terminalStatus },
|
|
30881
|
+
transport: transport2,
|
|
30882
|
+
ref,
|
|
30883
|
+
jobToken
|
|
30884
|
+
});
|
|
30885
|
+
markJobTerminal(jobId, terminalStatus, completion2);
|
|
30886
|
+
}
|
|
30455
30887
|
await settleCreditAfterRead({ job: stored, capture: receipt2, transport: transport2, human: opts.human });
|
|
30456
30888
|
transport2.close();
|
|
30457
30889
|
renderStatus(jobId, stored, terminalStatus, completion2, "local", null, opts, {
|
|
30458
|
-
receipt: receipt2
|
|
30890
|
+
receipt: receipt2,
|
|
30891
|
+
content
|
|
30459
30892
|
});
|
|
30460
30893
|
return;
|
|
30461
30894
|
}
|
|
@@ -30479,9 +30912,9 @@ async function statusWithAccess(jobId, opts, access) {
|
|
|
30479
30912
|
timeoutMs: timeout,
|
|
30480
30913
|
jobToken,
|
|
30481
30914
|
context: access.endpointOverridden ? void 0 : stored ?? void 0,
|
|
30482
|
-
|
|
30915
|
+
ignoreLocalState: access.endpointOverridden
|
|
30483
30916
|
});
|
|
30484
|
-
|
|
30917
|
+
let completion = completionSnapshot(result);
|
|
30485
30918
|
const reasonUnavailable = completion.message === void 0 || result.content_available === false && completion.message === "";
|
|
30486
30919
|
if (reasonUnavailable && (result.status === "failed" || result.status === "cancelled")) {
|
|
30487
30920
|
const savedReason = !access.endpointOverridden && stored?.status === result.status ? stored.completion?.message : void 0;
|
|
@@ -30489,6 +30922,17 @@ async function statusWithAccess(jobId, opts, access) {
|
|
|
30489
30922
|
const reason = savedReason ?? (terminal?.type === "cancel" || terminal?.type === "decline" ? terminal.content.reason : void 0);
|
|
30490
30923
|
if (reason !== void 0) completion.message = reason;
|
|
30491
30924
|
}
|
|
30925
|
+
if (isTerminalJobStatus(result.status)) {
|
|
30926
|
+
completion = await readTerminalCompletion({
|
|
30927
|
+
jobId,
|
|
30928
|
+
status: { ...result, ...completion },
|
|
30929
|
+
transport,
|
|
30930
|
+
ref,
|
|
30931
|
+
jobToken,
|
|
30932
|
+
timeoutMs: timeout,
|
|
30933
|
+
saved: !access.endpointOverridden && stored?.status === result.status ? stored.completion : void 0
|
|
30934
|
+
});
|
|
30935
|
+
}
|
|
30492
30936
|
let receipt;
|
|
30493
30937
|
let currency;
|
|
30494
30938
|
if (isTerminalJobStatus(result.status)) {
|
|
@@ -30544,7 +30988,10 @@ function transientReceiptCapture(jobId, response, endpoint, currency) {
|
|
|
30544
30988
|
}
|
|
30545
30989
|
function renderStatus(jobId, stored, jobStatus, completion, source, nextAction, opts, fetched) {
|
|
30546
30990
|
const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
|
|
30547
|
-
const
|
|
30991
|
+
const artifacts = terminalCompletionOutput(jobId, jobStatus, completion, {
|
|
30992
|
+
human: opts.human,
|
|
30993
|
+
contentAvailable: fetched?.content?.content_available
|
|
30994
|
+
});
|
|
30548
30995
|
const msgs = fetched?.msgs ?? [];
|
|
30549
30996
|
const receipt = fetched?.receipt;
|
|
30550
30997
|
const content = jobContentFields(jobId, fetched?.content, opts.human);
|
|
@@ -30566,7 +31013,7 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
|
|
|
30566
31013
|
info(`Status: ${jobStatus}${identifier ? ` [${identifier}]` : ""}`);
|
|
30567
31014
|
if (completion.message) info(` ${completion.message}`);
|
|
30568
31015
|
}
|
|
30569
|
-
if (
|
|
31016
|
+
if (artifacts.hint) info(`\u{1F4CE} ${artifacts.hint}`);
|
|
30570
31017
|
info(String(content.content_hint));
|
|
30571
31018
|
if (msgs.length > 0) {
|
|
30572
31019
|
info(`
|
|
@@ -30596,7 +31043,8 @@ ${msgs.length} new message(s):`);
|
|
|
30596
31043
|
],
|
|
30597
31044
|
...content,
|
|
30598
31045
|
...completion.summary ? { summary: completion.summary } : {},
|
|
30599
|
-
...
|
|
31046
|
+
...artifacts.fields,
|
|
31047
|
+
...artifacts.display ? { display: artifacts.display } : {},
|
|
30600
31048
|
...completion.message ? { message: completion.message } : {},
|
|
30601
31049
|
// terminal responses only. On a still-running job "absent" would
|
|
30602
31050
|
// read as "this DVM doesn't issue receipts" rather than "not yet".
|
|
@@ -30620,20 +31068,13 @@ ${msgs.length} new message(s):`);
|
|
|
30620
31068
|
async function resolveNextAction(jobId, status2, fetched, transport, ref, opts) {
|
|
30621
31069
|
if (isTerminalJobStatus(status2)) return null;
|
|
30622
31070
|
if (status2 === "awaiting-input") {
|
|
30623
|
-
const fromBatch =
|
|
30624
|
-
if (fromBatch) return
|
|
31071
|
+
const fromBatch = readNextAction(jobId, fetched, opts);
|
|
31072
|
+
if (fromBatch) return fromBatch;
|
|
30625
31073
|
const history = await transport.getMessages(jobId, 0, ref, opts);
|
|
30626
|
-
return
|
|
31074
|
+
return readNextAction(jobId, history, opts) ?? pollNextAction(jobId);
|
|
30627
31075
|
}
|
|
30628
31076
|
return pollNextAction(jobId);
|
|
30629
31077
|
}
|
|
30630
|
-
function withHeldPaymentHint(jobId, action, messages2, held) {
|
|
30631
|
-
if (action?.type !== "pay" || !held) return action;
|
|
30632
|
-
const ask = pendingPaymentRequest(messages2);
|
|
30633
|
-
if (!ask || !(held.inFlightPaymentRequestSeqs?.includes(ask.seq) || held.unconfirmedPaymentSubmissions?.[ask.seq] || held.askPaymentBlocks?.[ask.seq]))
|
|
30634
|
-
return action;
|
|
30635
|
-
return { ...action, hint: paymentInFlightHint(jobId, held, ask.seq) };
|
|
30636
|
-
}
|
|
30637
31078
|
|
|
30638
31079
|
// src/commands/upload.ts
|
|
30639
31080
|
import { statSync as statSync4 } from "fs";
|
|
@@ -32698,7 +33139,7 @@ function mnemonicValidationError(result) {
|
|
|
32698
33139
|
var import_qrcode = __toESM(require_lib(), 1);
|
|
32699
33140
|
import { randomBytes as randomBytes3 } from "crypto";
|
|
32700
33141
|
import { tmpdir as tmpdir2 } from "os";
|
|
32701
|
-
import { join as
|
|
33142
|
+
import { join as join9 } from "path";
|
|
32702
33143
|
async function renderQrTerminal(payload) {
|
|
32703
33144
|
return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
|
|
32704
33145
|
}
|
|
@@ -32711,7 +33152,7 @@ async function renderQrPng(payload, outPath) {
|
|
|
32711
33152
|
});
|
|
32712
33153
|
}
|
|
32713
33154
|
function defaultQrImagePath(prefix = "dvm-wallet-fund") {
|
|
32714
|
-
return
|
|
33155
|
+
return join9(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
|
|
32715
33156
|
}
|
|
32716
33157
|
|
|
32717
33158
|
// src/lib/funding-handoff.ts
|
|
@@ -37169,14 +37610,14 @@ function hexToBytes2(hex2) {
|
|
|
37169
37610
|
var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
|
|
37170
37611
|
import {
|
|
37171
37612
|
chmodSync as chmodSync2,
|
|
37172
|
-
existsSync as
|
|
37613
|
+
existsSync as existsSync8,
|
|
37173
37614
|
readdirSync as readdirSync5,
|
|
37174
|
-
readFileSync as
|
|
37175
|
-
renameSync as
|
|
37615
|
+
readFileSync as readFileSync9,
|
|
37616
|
+
renameSync as renameSync4,
|
|
37176
37617
|
unlinkSync as unlinkSync3,
|
|
37177
|
-
writeFileSync as
|
|
37618
|
+
writeFileSync as writeFileSync6
|
|
37178
37619
|
} from "fs";
|
|
37179
|
-
import { join as
|
|
37620
|
+
import { join as join10 } from "path";
|
|
37180
37621
|
var pairingIdPattern = /^[0-9a-f]{64}$/;
|
|
37181
37622
|
var stateSchema = external_exports.object({
|
|
37182
37623
|
version: external_exports.literal(1),
|
|
@@ -37198,12 +37639,12 @@ var stateSchema = external_exports.object({
|
|
|
37198
37639
|
function createWalletPairingState(state) {
|
|
37199
37640
|
ensurePairingsDirectory();
|
|
37200
37641
|
const path = pairingPath(state.pairing_id);
|
|
37201
|
-
|
|
37642
|
+
writeFileSync6(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
|
|
37202
37643
|
chmodSync2(path, 384);
|
|
37203
37644
|
}
|
|
37204
37645
|
function loadWalletPairingState(pairingId) {
|
|
37205
37646
|
const path = pairingPath(pairingId);
|
|
37206
|
-
if (!
|
|
37647
|
+
if (!existsSync8(path)) {
|
|
37207
37648
|
throw new DvmError(
|
|
37208
37649
|
"wallet_pairing_not_found",
|
|
37209
37650
|
"No local state exists for that wallet pairing.",
|
|
@@ -37211,7 +37652,7 @@ function loadWalletPairingState(pairingId) {
|
|
|
37211
37652
|
);
|
|
37212
37653
|
}
|
|
37213
37654
|
try {
|
|
37214
|
-
return stateSchema.parse(JSON.parse(
|
|
37655
|
+
return stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
|
|
37215
37656
|
} catch {
|
|
37216
37657
|
throw new DvmError(
|
|
37217
37658
|
"wallet_pairing_state_invalid",
|
|
@@ -37225,9 +37666,9 @@ function saveWalletPairingState(state) {
|
|
|
37225
37666
|
ensurePairingsDirectory();
|
|
37226
37667
|
const path = pairingPath(state.pairing_id);
|
|
37227
37668
|
const tmp = `${path}.tmp`;
|
|
37228
|
-
|
|
37669
|
+
writeFileSync6(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
|
|
37229
37670
|
try {
|
|
37230
|
-
|
|
37671
|
+
renameSync4(tmp, path);
|
|
37231
37672
|
chmodSync2(path, 384);
|
|
37232
37673
|
} catch (err) {
|
|
37233
37674
|
try {
|
|
@@ -37246,13 +37687,13 @@ function deleteWalletPairingState(pairingId) {
|
|
|
37246
37687
|
}
|
|
37247
37688
|
}
|
|
37248
37689
|
function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() / 1e3)) {
|
|
37249
|
-
if (!
|
|
37690
|
+
if (!existsSync8(PAIRINGS_DIR)) return 0;
|
|
37250
37691
|
let removed = 0;
|
|
37251
37692
|
for (const name of readdirSync5(PAIRINGS_DIR)) {
|
|
37252
37693
|
if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
|
|
37253
|
-
const path =
|
|
37694
|
+
const path = join10(PAIRINGS_DIR, name);
|
|
37254
37695
|
try {
|
|
37255
|
-
const state = stateSchema.parse(JSON.parse(
|
|
37696
|
+
const state = stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
|
|
37256
37697
|
if (state.manifest.expires_at <= nowSeconds) {
|
|
37257
37698
|
unlinkSync3(path);
|
|
37258
37699
|
removed += 1;
|
|
@@ -37264,7 +37705,7 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
|
|
|
37264
37705
|
}
|
|
37265
37706
|
async function withWalletPairingLock(pairingId, fn) {
|
|
37266
37707
|
const path = pairingPath(pairingId);
|
|
37267
|
-
if (!
|
|
37708
|
+
if (!existsSync8(path)) return fn();
|
|
37268
37709
|
let release;
|
|
37269
37710
|
try {
|
|
37270
37711
|
release = await import_proper_lockfile3.default.lock(path, {
|
|
@@ -37294,7 +37735,7 @@ function pairingPath(pairingId) {
|
|
|
37294
37735
|
"Wallet pairing id must be 64 lowercase hexadecimal characters."
|
|
37295
37736
|
);
|
|
37296
37737
|
}
|
|
37297
|
-
return
|
|
37738
|
+
return join10(PAIRINGS_DIR, `${pairingId}.json`);
|
|
37298
37739
|
}
|
|
37299
37740
|
function ensurePairingsDirectory() {
|
|
37300
37741
|
ensureConfigSubdir(PAIRINGS_DIR);
|
|
@@ -37933,9 +38374,11 @@ async function forgetSubmission(requestId, opts) {
|
|
|
37933
38374
|
"List them with: dvm wallet submissions"
|
|
37934
38375
|
);
|
|
37935
38376
|
}
|
|
38377
|
+
refuseIfReclaimUnsaved(view, opts);
|
|
37936
38378
|
refuseIfSelfHealing(view, opts);
|
|
37937
38379
|
await confirmForget(view, opts);
|
|
37938
38380
|
await abandonPendingSubmission({ requestId });
|
|
38381
|
+
clearReclaimIntent(requestId);
|
|
37939
38382
|
const abandoned = view.at_risk ? view.amount_sats : 0;
|
|
37940
38383
|
const heldFor = heldCashuSubmissionAsks(/* @__PURE__ */ new Set([requestId]));
|
|
37941
38384
|
const warning = heldFor.length === 0 ? void 0 : `This token is the unconfirmed payment for an open charge on ${heldFor.map((ask) => `job ${ask.jobId}`).join(", ")}. That charge stays held, but if the provider asks for it again it can become payable again, and the provider can still redeem the forgotten token.`;
|
|
@@ -37956,6 +38399,14 @@ async function forgetSubmission(requestId, opts) {
|
|
|
37956
38399
|
...warning ? { warning, held_for: heldFor.map((ask) => ({ job_id: ask.jobId, request_seq: ask.requestSeq })) } : {}
|
|
37957
38400
|
});
|
|
37958
38401
|
}
|
|
38402
|
+
function refuseIfReclaimUnsaved(view, opts) {
|
|
38403
|
+
if (opts.force || !reclaimIntentIds().has(view.request_id)) return;
|
|
38404
|
+
throw new DvmError(
|
|
38405
|
+
"reclaim_unsaved",
|
|
38406
|
+
`Request ${view.request_id}: the reclaim swap for ${view.amount_sats} sats may already have gone through at the mint, and the new proofs have not been saved to the wallet yet.`,
|
|
38407
|
+
`Run \`dvm wallet show\` to recover them. Forgetting this entry first can lose them; if the recovery keeps failing and you accept that, add --force: dvm wallet submissions --forget ${view.request_id} --yes --force`
|
|
38408
|
+
);
|
|
38409
|
+
}
|
|
37959
38410
|
function refuseIfSelfHealing(view, opts) {
|
|
37960
38411
|
if (opts.force) return;
|
|
37961
38412
|
if (view.state !== "reclaimable" && view.state !== "reclaim_failed") return;
|