@dvmkit/dvm-cli 0.19.1 → 0.19.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.
@@ -2744,27 +2744,61 @@ function parseUpfrontRailPayment(value) {
2744
2744
  ...Number.isSafeInteger(raw.usdMicro) && raw.usdMicro >= 0 ? { usdMicro: raw.usdMicro } : {}
2745
2745
  };
2746
2746
  }
2747
- function parseUpfrontPayment(value) {
2748
- if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
2747
+ var UPFRONT_RAILS = {
2748
+ cashu: true,
2749
+ x402: true,
2750
+ tempo: true,
2751
+ lightning: true,
2752
+ stripe: true
2753
+ };
2754
+ function isUpfrontRail(value) {
2755
+ return typeof value === "string" && Object.hasOwn(UPFRONT_RAILS, value);
2756
+ }
2757
+ function checkUpfrontPayment(value) {
2758
+ if (!value || typeof value !== "object" || Array.isArray(value)) return { reason: "upfront_payment is not an object" };
2749
2759
  const raw = value;
2750
- if (!Number.isSafeInteger(raw.amount_msats) || Number(raw.amount_msats) < 0) return void 0;
2760
+ if (!Number.isSafeInteger(raw.amount_msats) || Number(raw.amount_msats) < 0)
2761
+ return { reason: "amount_msats is not a non-negative integer" };
2751
2762
  for (const key of ["amount_micro", "native_amount"]) {
2752
- if (raw[key] !== void 0 && (!Number.isSafeInteger(raw[key]) || Number(raw[key]) < 0)) return void 0;
2753
- }
2754
- if (raw.amount_micro === void 0 !== (raw.currency === void 0) || raw.currency !== void 0 && (typeof raw.currency !== "string" || !/^[a-z]{3}$/.test(raw.currency))) return void 0;
2755
- if (raw.credit_id === void 0 !== (raw.draw_id === void 0)) return void 0;
2763
+ if (raw[key] !== void 0 && (!Number.isSafeInteger(raw[key]) || Number(raw[key]) < 0))
2764
+ return { reason: `${key} is not a non-negative integer` };
2765
+ }
2766
+ if (raw.amount_micro === void 0 !== (raw.currency === void 0))
2767
+ return { reason: "amount_micro and currency must be set together" };
2768
+ if (raw.currency !== void 0 && (typeof raw.currency !== "string" || !/^[a-z]{3}$/.test(raw.currency)))
2769
+ return { reason: "currency is not a lowercase three-letter code" };
2770
+ if (raw.credit_id === void 0 !== (raw.draw_id === void 0))
2771
+ return { reason: "credit_id and draw_id must be set together" };
2756
2772
  for (const key of ["credit_id", "draw_id", "native_asset"]) {
2757
- if (raw[key] !== void 0 && (typeof raw[key] !== "string" || raw[key].trim().length === 0)) return void 0;
2773
+ if (raw[key] !== void 0 && (typeof raw[key] !== "string" || raw[key].trim().length === 0))
2774
+ return { reason: `${key} is not a non-empty string` };
2758
2775
  }
2759
- if (raw.rail !== void 0 && !["cashu", "x402", "tempo", "lightning"].includes(String(raw.rail))) return void 0;
2760
- return {
2776
+ if (raw.rail !== void 0 && !isUpfrontRail(raw.rail))
2777
+ return { reason: `rail ${JSON.stringify(String(raw.rail)).slice(0, 40)} is not a known funding rail` };
2778
+ return { payment: {
2761
2779
  amount_msats: raw.amount_msats,
2762
2780
  ...raw.amount_micro !== void 0 ? { amount_micro: raw.amount_micro, currency: raw.currency } : {},
2763
2781
  ...raw.rail !== void 0 ? { rail: raw.rail } : {},
2764
2782
  ...raw.native_amount !== void 0 ? { native_amount: raw.native_amount } : {},
2765
2783
  ...raw.native_asset !== void 0 ? { native_asset: raw.native_asset } : {},
2766
2784
  ...raw.credit_id !== void 0 ? { credit_id: raw.credit_id, draw_id: raw.draw_id } : {}
2767
- };
2785
+ } };
2786
+ }
2787
+ function parseUpfrontPayment(value) {
2788
+ const checked = checkUpfrontPayment(value);
2789
+ return "payment" in checked ? checked.payment : void 0;
2790
+ }
2791
+ function upfrontPaymentFault(value) {
2792
+ if (value === void 0 || value === null) return void 0;
2793
+ const checked = checkUpfrontPayment(value);
2794
+ return "reason" in checked ? checked.reason : void 0;
2795
+ }
2796
+ function upfrontReceiptFields(value) {
2797
+ const fault = upfrontPaymentFault(value);
2798
+ return { upfrontPayment: parseUpfrontPayment(value), ...fault ? { upfrontPaymentFault: fault } : {} };
2799
+ }
2800
+ function receiptUpfrontFault(receipt) {
2801
+ return receipt.upfrontPaymentFault;
2768
2802
  }
2769
2803
 
2770
2804
  // src/lib/job-budget.ts
@@ -2832,28 +2866,51 @@ function saveSubmittedJob(job) {
2832
2866
  throw new Error("Submitted job conflicts with an existing local job.");
2833
2867
  }, true, job);
2834
2868
  }
2835
- function recordUpfrontCreditPayment(jobId, value, paidOnRail = false) {
2869
+ function markUpfrontCreditConflict(job, reason, recoverable = false) {
2870
+ const wasRecoverable = job.upfrontCreditConflictRecoverable === true;
2871
+ if (job.upfrontCreditConflict && !(wasRecoverable && !recoverable)) {
2872
+ job.upfrontCreditConflictReason ??= reason;
2873
+ return;
2874
+ }
2875
+ job.upfrontCreditConflict = true;
2876
+ job.upfrontCreditConflictReason = reason;
2877
+ if (recoverable) job.upfrontCreditConflictRecoverable = true;
2878
+ else delete job.upfrontCreditConflictRecoverable;
2879
+ }
2880
+ function recordUpfrontCreditPayment(jobId, value, paidOnRail = false, fault) {
2836
2881
  const payment = parseUpfrontPayment(value);
2882
+ const unusable = fault ?? upfrontPaymentFault(value);
2837
2883
  mutateJobs((jobs) => {
2838
2884
  const job = jobs.find((entry) => entry.id === jobId);
2839
- if (!job || !payment) return;
2885
+ if (!job) return;
2886
+ if (!payment) {
2887
+ if (unusable && !paidOnRail && job.paymentMethod === "credit" && !job.upfrontCreditBooked) {
2888
+ markUpfrontCreditConflict(job, `the provider's upfront_payment was unusable: ${unusable}`, true);
2889
+ }
2890
+ return;
2891
+ }
2840
2892
  if (paidOnRail || job.paymentMethod && job.paymentMethod !== "credit") {
2841
2893
  job.upfrontPayment ??= payment;
2842
2894
  return;
2843
2895
  }
2844
2896
  if (!payment.credit_id || !payment.draw_id) {
2845
- if (job.paymentMethod === "credit") job.upfrontCreditConflict = true;
2897
+ if (job.paymentMethod === "credit") markUpfrontCreditConflict(job, "the accepted debit names no credit draw");
2846
2898
  return;
2847
2899
  }
2848
2900
  const binding = job.creditBinding;
2849
2901
  if (!binding || "unbound" in binding || binding.creditId !== payment.credit_id || binding.drawId !== payment.draw_id) {
2850
- job.upfrontCreditConflict = true;
2902
+ markUpfrontCreditConflict(job, "the accepted debit does not match this job's credit draw");
2851
2903
  return;
2852
2904
  }
2853
2905
  if (job.upfrontPayment && JSON.stringify(job.upfrontPayment) !== JSON.stringify(payment)) {
2854
- job.upfrontCreditConflict = true;
2906
+ markUpfrontCreditConflict(job, "the provider reported a different accepted debit than the one recorded");
2855
2907
  return;
2856
2908
  }
2909
+ if (job.upfrontCreditConflictRecoverable) {
2910
+ delete job.upfrontCreditConflict;
2911
+ delete job.upfrontCreditConflictReason;
2912
+ delete job.upfrontCreditConflictRecoverable;
2913
+ }
2857
2914
  job.upfrontPayment = payment;
2858
2915
  job.paymentMethod = "credit";
2859
2916
  if (job.upfrontCreditBooked) return;
@@ -9599,6 +9656,8 @@ export {
9599
9656
  upfrontRailPayment,
9600
9657
  parseUpfrontRailPayment,
9601
9658
  parseUpfrontPayment,
9659
+ upfrontReceiptFields,
9660
+ receiptUpfrontFault,
9602
9661
  budgetVerdict,
9603
9662
  dollarBoundUsdMicro,
9604
9663
  askUsdMicro,
package/dist/dvm.js CHANGED
@@ -153,6 +153,7 @@ import {
153
153
  receiptPieceContext,
154
154
  receiptSettlement,
155
155
  receiptTrustFields,
156
+ receiptUpfrontFault,
156
157
  reclaimIntentIds,
157
158
  reconcileInFlightPaymentRequest,
158
159
  reconcilePaymentRequestHistory,
@@ -207,6 +208,7 @@ import {
207
208
  updateJob,
208
209
  updateObservedJob,
209
210
  upfrontRailPayment,
211
+ upfrontReceiptFields,
210
212
  usdMicro,
211
213
  walletHistory,
212
214
  walletInvoiceFundingAdvice,
@@ -216,7 +218,7 @@ import {
216
218
  withJobTokenRedaction,
217
219
  withRequestResultRecovery,
218
220
  withoutPendingMint
219
- } from "./chunk-NCX4JVLU.js";
221
+ } from "./chunk-5ZY5IKS2.js";
220
222
  import {
221
223
  connectedTempoAccount,
222
224
  generateTempoKey,
@@ -9012,19 +9014,180 @@ function formatPaidAmount(result, fiat) {
9012
9014
  return formatPaymentAmount(result.amountMsats, fiat, { anchor: false });
9013
9015
  }
9014
9016
 
9017
+ // src/lib/request-intent-store.ts
9018
+ var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
9019
+ import {
9020
+ closeSync,
9021
+ existsSync,
9022
+ fsyncSync,
9023
+ mkdirSync,
9024
+ openSync,
9025
+ readFileSync,
9026
+ renameSync,
9027
+ writeFileSync
9028
+ } from "fs";
9029
+ import { join } from "path";
9030
+ function saveRequestIntent(intent) {
9031
+ assertRequestId(intent.requestId);
9032
+ assertNoPaymentOrAuthSecrets(intent.body);
9033
+ ensureConfigSubdir(REQUEST_INTENTS_DIR);
9034
+ const dir = intentDirectory(intent.requestId);
9035
+ try {
9036
+ mkdirSync(dir, { mode: 448 });
9037
+ } catch (error) {
9038
+ if (error.code === "EEXIST") return false;
9039
+ throw error;
9040
+ }
9041
+ fsyncDirectory(REQUEST_INTENTS_DIR);
9042
+ const temp = join(dir, `intent.${String(process.pid)}.tmp`);
9043
+ const target = join(dir, "intent.json");
9044
+ const fd = openSync(temp, "wx", 384);
9045
+ try {
9046
+ writeFileSync(fd, JSON.stringify(intent, null, 2) + "\n");
9047
+ fsyncSync(fd);
9048
+ } finally {
9049
+ closeSync(fd);
9050
+ }
9051
+ renameSync(temp, target);
9052
+ fsyncDirectory(dir);
9053
+ return true;
9054
+ }
9055
+ function loadRequestIntent(requestId) {
9056
+ assertRequestId(requestId);
9057
+ const dir = intentDirectory(requestId);
9058
+ if (!existsSync(dir)) return null;
9059
+ const path = join(dir, "intent.json");
9060
+ try {
9061
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
9062
+ if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
9063
+ throw new Error("invalid shape");
9064
+ return parsed;
9065
+ } catch (error) {
9066
+ throw new DvmError(
9067
+ "request_intent_unreadable",
9068
+ `The saved request intent for ${requestId} is incomplete or unreadable.`,
9069
+ "Do not submit a replacement request. The provider may already have accepted and charged the original; restore this intent from backup before using request-result.",
9070
+ { request_id: requestId, cause: error instanceof Error ? error.message : String(error) }
9071
+ );
9072
+ }
9073
+ }
9074
+ function recordRequestRailPayment(requestId, payment) {
9075
+ assertRequestId(requestId);
9076
+ if (!parseUpfrontRailPayment(payment)) throw new DvmError("invalid_upfront_payment", "Invalid upfront rail price.");
9077
+ const dir = intentDirectory(requestId);
9078
+ const target = join(dir, "intent.json");
9079
+ const release = import_proper_lockfile2.default.lockSync(target, { realpath: false });
9080
+ try {
9081
+ const intent = loadRequestIntent(requestId);
9082
+ if (!intent) throw new DvmError("request_not_found", "No saved request intent exists for this rail payment.");
9083
+ if (intent.railPayment && JSON.stringify(intent.railPayment) !== JSON.stringify(payment))
9084
+ throw new DvmError("upfront_payment_conflict", "This request already records a different upfront rail price.");
9085
+ const temp = join(dir, `rail.${String(process.pid)}.tmp`);
9086
+ const fd = openSync(temp, "w", 384);
9087
+ try {
9088
+ writeFileSync(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
9089
+ fsyncSync(fd);
9090
+ } finally {
9091
+ closeSync(fd);
9092
+ }
9093
+ renameSync(temp, target);
9094
+ fsyncDirectory(dir);
9095
+ } finally {
9096
+ release();
9097
+ }
9098
+ }
9099
+ function assertNoPaymentOrAuthSecrets(body) {
9100
+ if (!containsForbiddenSecret(body)) return;
9101
+ throw new DvmError(
9102
+ "request_intent_contains_secret",
9103
+ "Request recovery cannot persist a payment credential, bearer token, or request auth signature.",
9104
+ "No payment was attempted. Remove the secret-bearing input or omit --request-id."
9105
+ );
9106
+ }
9107
+ function containsForbiddenSecret(value) {
9108
+ if (typeof value === "string") return /^Bearer\s/i.test(value);
9109
+ if (!value || typeof value !== "object") return false;
9110
+ if (Array.isArray(value)) return value.some(containsForbiddenSecret);
9111
+ const record2 = value;
9112
+ if (["pubkey", "timestamp", "nonce", "signature"].every((key) => Object.hasOwn(record2, key))) {
9113
+ return true;
9114
+ }
9115
+ const forbidden = /* @__PURE__ */ new Set([
9116
+ "authorization",
9117
+ "bearer_token",
9118
+ "access_token",
9119
+ "cashu_token",
9120
+ "x402_payment",
9121
+ "tempo_credential"
9122
+ ]);
9123
+ return Object.entries(record2).some(
9124
+ ([key, child]) => forbidden.has(key.toLowerCase()) || containsForbiddenSecret(child)
9125
+ );
9126
+ }
9127
+ function assertRequestId(requestId) {
9128
+ if (isPublicRequestId(requestId)) return;
9129
+ throw new DvmError(
9130
+ "invalid_request_id",
9131
+ "Invalid request id.",
9132
+ "Use 1\u2013128 characters: letters, digits, dot, underscore, colon, or hyphen."
9133
+ );
9134
+ }
9135
+ function intentDirectory(requestId) {
9136
+ return join(REQUEST_INTENTS_DIR, requestId);
9137
+ }
9138
+ function fsyncDirectory(path) {
9139
+ if (process.platform === "win32") return;
9140
+ let fd;
9141
+ try {
9142
+ fd = openSync(path, "r");
9143
+ fsyncSync(fd);
9144
+ } finally {
9145
+ if (fd !== void 0) closeSync(fd);
9146
+ }
9147
+ }
9148
+ function isRequestIntent(value) {
9149
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
9150
+ const candidate = value;
9151
+ return candidate.v === 2 && isPublicRequestId(candidate.requestId) && typeof candidate.endpoint === "string" && typeof candidate.capability === "string" && typeof candidate.callerPubkey === "string" && isSignedRequestAudience(candidate.authAudience) && typeof candidate.createdAt === "number" && typeof candidate.body === "object" && candidate.body !== null && !Array.isArray(candidate.body) && typeof candidate.policy === "object" && candidate.policy !== null;
9152
+ }
9153
+ function isSignedRequestAudience(value) {
9154
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
9155
+ const candidate = value;
9156
+ return typeof candidate.dvm_id === "string" && typeof candidate.builder_pubkey === "string";
9157
+ }
9158
+
9159
+ // src/lib/upfront-credit-error.ts
9160
+ function unknownUpfrontCreditError(job, message2) {
9161
+ const reason = job.upfrontCreditConflictReason;
9162
+ const requestId = job.requestId;
9163
+ let recovery;
9164
+ if (requestId && loadRequestIntent(requestId))
9165
+ recovery = `Run \`dvm request-result ${shellQuoteArg(requestId)}\` to recover the accepted upfront amount; it reads only and sends no payment.`;
9166
+ else if (requestId)
9167
+ recovery = `Request ${requestId} has no stored intent on this machine, so \`dvm request-result\` cannot recover it. Restore the caller state that submitted it.`;
9168
+ else
9169
+ recovery = "This job has no stored request id, so `dvm request-result` cannot recover it. Restore the caller state that submitted it.";
9170
+ return new DvmError(
9171
+ "upfront_credit_unknown",
9172
+ `${message2}${reason ? ` Cause: ${reason}.` : ""}`,
9173
+ `${recovery} Do not edit the local job store.`,
9174
+ { ...reason ? { reason } : {}, ...requestId ? { request_id: requestId } : {} }
9175
+ );
9176
+ }
9177
+
9015
9178
  // src/lib/credit-payment.ts
9016
9179
  import { randomUUID } from "crypto";
9017
9180
 
9018
9181
  // src/lib/caller-version.ts
9019
- import { existsSync, readFileSync } from "fs";
9020
- import { dirname, join } from "path";
9182
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
9183
+ import { dirname, join as join2 } from "path";
9021
9184
  import { fileURLToPath } from "url";
9022
9185
  var CALLER_VERSION = readCallerVersion();
9023
9186
  function readCallerVersion() {
9024
9187
  let dir = dirname(fileURLToPath(import.meta.url));
9025
9188
  for (; ; ) {
9026
- const manifestPath = join(dir, "package.json");
9027
- if (existsSync(manifestPath)) {
9189
+ const manifestPath = join2(dir, "package.json");
9190
+ if (existsSync2(manifestPath)) {
9028
9191
  const manifest = readManifest(manifestPath);
9029
9192
  if (manifest.name === "@dvmkit/dvm-cli") return manifest.version;
9030
9193
  }
@@ -9036,7 +9199,7 @@ function readCallerVersion() {
9036
9199
  }
9037
9200
  }
9038
9201
  function readManifest(path) {
9039
- return JSON.parse(readFileSync(path, "utf8"));
9202
+ return JSON.parse(readFileSync2(path, "utf8"));
9040
9203
  }
9041
9204
 
9042
9205
  // src/lib/client-compatibility.ts
@@ -9213,9 +9376,9 @@ async function readBoundedBody(response, limit) {
9213
9376
  var MAX_COMPATIBILITY_BODY_BYTES = 16384;
9214
9377
 
9215
9378
  // src/lib/credit-suggestion-cooldown.ts
9216
- import { existsSync as existsSync2, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync } from "fs";
9217
- import { join as join2 } from "path";
9218
- var CREDIT_SUGGESTIONS_FILE = join2(CONFIG_DIR, "credit-suggestions.json");
9379
+ import { existsSync as existsSync3, readFileSync as readFileSync3, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
9380
+ import { join as join3 } from "path";
9381
+ var CREDIT_SUGGESTIONS_FILE = join3(CONFIG_DIR, "credit-suggestions.json");
9219
9382
  var CREDIT_SUGGESTION_COOLDOWN_MS = 7 * 24 * 60 * 60 * 1e3;
9220
9383
  function creditSuggestionDue(endpoint, now = Date.now()) {
9221
9384
  const shownAt = loadState()[normalizeCreditEndpoint(endpoint)];
@@ -9232,9 +9395,9 @@ function recordCreditSuggestionShown(endpoint, now = Date.now()) {
9232
9395
  }
9233
9396
  }
9234
9397
  function loadState() {
9235
- if (!existsSync2(CREDIT_SUGGESTIONS_FILE)) return {};
9398
+ if (!existsSync3(CREDIT_SUGGESTIONS_FILE)) return {};
9236
9399
  try {
9237
- const parsed = JSON.parse(readFileSync2(CREDIT_SUGGESTIONS_FILE, "utf-8"));
9400
+ const parsed = JSON.parse(readFileSync3(CREDIT_SUGGESTIONS_FILE, "utf-8"));
9238
9401
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
9239
9402
  return Object.fromEntries(
9240
9403
  Object.entries(parsed).filter((entry) => typeof entry[1] === "string")
@@ -9246,9 +9409,9 @@ function loadState() {
9246
9409
  function saveState(state) {
9247
9410
  ensureConfigDir();
9248
9411
  const tmp = `${CREDIT_SUGGESTIONS_FILE}.${process.pid}.tmp`;
9249
- writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
9412
+ writeFileSync2(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
9250
9413
  try {
9251
- renameSync(tmp, CREDIT_SUGGESTIONS_FILE);
9414
+ renameSync2(tmp, CREDIT_SUGGESTIONS_FILE);
9252
9415
  } catch (err) {
9253
9416
  try {
9254
9417
  unlinkSync(tmp);
@@ -9898,7 +10061,7 @@ async function tryCreditPayment(args) {
9898
10061
  throw new DvmError("upfront_rail_unknown", "Recover the original upfront rail charge before another balance payment.");
9899
10062
  const ask = request2.credit;
9900
10063
  if (job && hasUnknownUpfrontCredit(job))
9901
- throw new DvmError("upfront_credit_unknown", "The original upfront credit debit must be recovered before another balance payment.");
10064
+ throw unknownUpfrontCreditError(job, "The original upfront credit debit must be recovered before another balance payment.");
9902
10065
  if (!job?.creditBinding || !ask || !Number.isSafeInteger(requestSeq) || requestSeq < 0 || !Number.isSafeInteger(ask.amount_micro) || ask.amount_micro <= 0 || !/^[a-z]{3}$/.test(ask.currency)) return false;
9903
10066
  const signer = findSigningIdentityByPubkey(job.creditBinding.callerPubkey);
9904
10067
  if (!signer) return false;
@@ -11404,148 +11567,6 @@ function parseTempoNetwork(value, source) {
11404
11567
  );
11405
11568
  }
11406
11569
 
11407
- // src/lib/request-intent-store.ts
11408
- var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
11409
- import {
11410
- closeSync,
11411
- existsSync as existsSync3,
11412
- fsyncSync,
11413
- mkdirSync,
11414
- openSync,
11415
- readFileSync as readFileSync3,
11416
- renameSync as renameSync2,
11417
- writeFileSync as writeFileSync2
11418
- } from "fs";
11419
- import { join as join3 } from "path";
11420
- function saveRequestIntent(intent) {
11421
- assertRequestId(intent.requestId);
11422
- assertNoPaymentOrAuthSecrets(intent.body);
11423
- ensureConfigSubdir(REQUEST_INTENTS_DIR);
11424
- const dir = intentDirectory(intent.requestId);
11425
- try {
11426
- mkdirSync(dir, { mode: 448 });
11427
- } catch (error) {
11428
- if (error.code === "EEXIST") return false;
11429
- throw error;
11430
- }
11431
- fsyncDirectory(REQUEST_INTENTS_DIR);
11432
- const temp = join3(dir, `intent.${String(process.pid)}.tmp`);
11433
- const target = join3(dir, "intent.json");
11434
- const fd = openSync(temp, "wx", 384);
11435
- try {
11436
- writeFileSync2(fd, JSON.stringify(intent, null, 2) + "\n");
11437
- fsyncSync(fd);
11438
- } finally {
11439
- closeSync(fd);
11440
- }
11441
- renameSync2(temp, target);
11442
- fsyncDirectory(dir);
11443
- return true;
11444
- }
11445
- function loadRequestIntent(requestId) {
11446
- assertRequestId(requestId);
11447
- const dir = intentDirectory(requestId);
11448
- if (!existsSync3(dir)) return null;
11449
- const path = join3(dir, "intent.json");
11450
- try {
11451
- const parsed = JSON.parse(readFileSync3(path, "utf8"));
11452
- if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
11453
- throw new Error("invalid shape");
11454
- return parsed;
11455
- } catch (error) {
11456
- throw new DvmError(
11457
- "request_intent_unreadable",
11458
- `The saved request intent for ${requestId} is incomplete or unreadable.`,
11459
- "Do not submit a replacement request. The provider may already have accepted and charged the original; restore this intent from backup before using request-result.",
11460
- { request_id: requestId, cause: error instanceof Error ? error.message : String(error) }
11461
- );
11462
- }
11463
- }
11464
- function recordRequestRailPayment(requestId, payment) {
11465
- assertRequestId(requestId);
11466
- if (!parseUpfrontRailPayment(payment)) throw new DvmError("invalid_upfront_payment", "Invalid upfront rail price.");
11467
- const dir = intentDirectory(requestId);
11468
- const target = join3(dir, "intent.json");
11469
- const release = import_proper_lockfile2.default.lockSync(target, { realpath: false });
11470
- try {
11471
- const intent = loadRequestIntent(requestId);
11472
- if (!intent) throw new DvmError("request_not_found", "No saved request intent exists for this rail payment.");
11473
- if (intent.railPayment && JSON.stringify(intent.railPayment) !== JSON.stringify(payment))
11474
- throw new DvmError("upfront_payment_conflict", "This request already records a different upfront rail price.");
11475
- const temp = join3(dir, `rail.${String(process.pid)}.tmp`);
11476
- const fd = openSync(temp, "w", 384);
11477
- try {
11478
- writeFileSync2(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
11479
- fsyncSync(fd);
11480
- } finally {
11481
- closeSync(fd);
11482
- }
11483
- renameSync2(temp, target);
11484
- fsyncDirectory(dir);
11485
- } finally {
11486
- release();
11487
- }
11488
- }
11489
- function assertNoPaymentOrAuthSecrets(body) {
11490
- if (!containsForbiddenSecret(body)) return;
11491
- throw new DvmError(
11492
- "request_intent_contains_secret",
11493
- "Request recovery cannot persist a payment credential, bearer token, or request auth signature.",
11494
- "No payment was attempted. Remove the secret-bearing input or omit --request-id."
11495
- );
11496
- }
11497
- function containsForbiddenSecret(value) {
11498
- if (typeof value === "string") return /^Bearer\s/i.test(value);
11499
- if (!value || typeof value !== "object") return false;
11500
- if (Array.isArray(value)) return value.some(containsForbiddenSecret);
11501
- const record2 = value;
11502
- if (["pubkey", "timestamp", "nonce", "signature"].every((key) => Object.hasOwn(record2, key))) {
11503
- return true;
11504
- }
11505
- const forbidden = /* @__PURE__ */ new Set([
11506
- "authorization",
11507
- "bearer_token",
11508
- "access_token",
11509
- "cashu_token",
11510
- "x402_payment",
11511
- "tempo_credential"
11512
- ]);
11513
- return Object.entries(record2).some(
11514
- ([key, child]) => forbidden.has(key.toLowerCase()) || containsForbiddenSecret(child)
11515
- );
11516
- }
11517
- function assertRequestId(requestId) {
11518
- if (isPublicRequestId(requestId)) return;
11519
- throw new DvmError(
11520
- "invalid_request_id",
11521
- "Invalid request id.",
11522
- "Use 1\u2013128 characters: letters, digits, dot, underscore, colon, or hyphen."
11523
- );
11524
- }
11525
- function intentDirectory(requestId) {
11526
- return join3(REQUEST_INTENTS_DIR, requestId);
11527
- }
11528
- function fsyncDirectory(path) {
11529
- if (process.platform === "win32") return;
11530
- let fd;
11531
- try {
11532
- fd = openSync(path, "r");
11533
- fsyncSync(fd);
11534
- } finally {
11535
- if (fd !== void 0) closeSync(fd);
11536
- }
11537
- }
11538
- function isRequestIntent(value) {
11539
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
11540
- const candidate = value;
11541
- return candidate.v === 2 && isPublicRequestId(candidate.requestId) && typeof candidate.endpoint === "string" && typeof candidate.capability === "string" && typeof candidate.callerPubkey === "string" && isSignedRequestAudience(candidate.authAudience) && typeof candidate.createdAt === "number" && typeof candidate.body === "object" && candidate.body !== null && !Array.isArray(candidate.body) && typeof candidate.policy === "object" && candidate.policy !== null;
11542
- }
11543
- function isSignedRequestAudience(value) {
11544
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
11545
- const candidate = value;
11546
- return typeof candidate.dvm_id === "string" && typeof candidate.builder_pubkey === "string";
11547
- }
11548
-
11549
11570
  // src/lib/payment-responder.ts
11550
11571
  async function handlePaymentRequest(jobId, request2, policy, transport, provider, opts) {
11551
11572
  const seq = opts?.requestSeq;
@@ -11715,11 +11736,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11715
11736
  "Recover the original job price before authorizing more payments."
11716
11737
  );
11717
11738
  if (job && hasUnknownUpfrontCredit(job))
11718
- throw new DvmError(
11719
- "upfront_credit_unknown",
11720
- "The original upfront credit debit is unknown or conflicting.",
11721
- "Recover the accepted upfront amount with 'dvm request-result' before authorizing more payments."
11722
- );
11739
+ throw unknownUpfrontCreditError(job, "The original upfront credit debit is unknown or conflicting.");
11723
11740
  const pinnedMint = job?.pinnedMint;
11724
11741
  const strictPerCall = job?.strictPerCall === true;
11725
11742
  const maxCashuFeeSats = job?.maxCashuFeeSats;
@@ -12397,7 +12414,7 @@ function refundNextAction(jobId, claims) {
12397
12414
  reason: claim.reason,
12398
12415
  claimed: false,
12399
12416
  cashu_token: claim.cashu_token,
12400
- hint: `The provider sent a ${noun} but the auto-claim into your wallet failed (the mint may be unreachable). Claim it manually with 'dvm wallet receive-token <cashu_token>' \u2014 the token is in this action's 'cashu_token' field, don't lose it. Or retry the auto-claim with 'dvm messages ${guidanceJobArg(jobId)} --no-stream' (re-running plain 'dvm messages' won't retry \u2014 its cursor has already advanced past this message).`
12417
+ hint: `The provider sent a ${noun} but the auto-claim into your wallet failed (the mint may be unreachable). Pipe this action's 'cashu_token' field into 'dvm wallet receive-token' via stdin; do not put the token in command arguments. Or retry the auto-claim with 'dvm messages ${guidanceJobArg(jobId)} --no-stream' (re-running plain 'dvm messages' won't retry \u2014 its cursor has already advanced past this message).`
12401
12418
  }, ["amount_msats", "reason", "cashu_token"]);
12402
12419
  }
12403
12420
  return providerFields({
@@ -12431,7 +12448,7 @@ function refundSummaryHuman(claim) {
12431
12448
  if (claim.claimed) {
12432
12449
  return `Claimed ${noun} of ${formatAmountBestEffort(claim.amount_msats)} into your wallet.`;
12433
12450
  }
12434
- return `${cap(noun)} of ${formatAmountBestEffort(claim.amount_msats)} could not be auto-claimed (the mint may be down). Recover with: dvm wallet receive-token ${claim.cashu_token}`;
12451
+ return `${cap(noun)} of ${formatAmountBestEffort(claim.amount_msats)} could not be auto-claimed (the mint may be down). Pipe the cashu_token field from JSON messages output into dvm wallet receive-token via stdin; do not put the token in command arguments. Use dvm messages <job-id> --no-stream to retry the auto-claim or recover the token.`;
12435
12452
  }
12436
12453
  function cap(s) {
12437
12454
  return s.charAt(0).toUpperCase() + s.slice(1);
@@ -13270,7 +13287,7 @@ var HttpsTransport = class {
13270
13287
  ...tempoTransactionHash ? { transactionHash: tempoTransactionHash } : {},
13271
13288
  ...feedbackClaim ? { feedbackClaim } : {},
13272
13289
  ...parseFundingResponse(data),
13273
- upfrontPayment: parseUpfrontPayment(data.upfront_payment)
13290
+ ...upfrontReceiptFields(data.upfront_payment)
13274
13291
  };
13275
13292
  }
13276
13293
  return {
@@ -13286,7 +13303,7 @@ var HttpsTransport = class {
13286
13303
  ...feedbackClaim ? { feedbackClaim } : {},
13287
13304
  ...parseSignedReceipt(data.receipt),
13288
13305
  ...parseFundingResponse(data),
13289
- upfrontPayment: parseUpfrontPayment(data.upfront_payment)
13306
+ ...upfrontReceiptFields(data.upfront_payment)
13290
13307
  };
13291
13308
  }
13292
13309
  async requestResult(provider, requestId, signedJob) {
@@ -13797,7 +13814,7 @@ function parseRequestResultResponse(value, requestId, httpStatus) {
13797
13814
  ...typeof data.job_token === "string" ? { jobToken: data.job_token } : {},
13798
13815
  ...receipt ? { receipt } : {},
13799
13816
  ...parseFundingResponse(data),
13800
- upfrontPayment: parseUpfrontPayment(data.upfront_payment)
13817
+ ...upfrontReceiptFields(data.upfront_payment)
13801
13818
  };
13802
13819
  }
13803
13820
  function malformedRequestResult(requestId, reason) {
@@ -14715,7 +14732,7 @@ async function settleCreditAfterJob(args) {
14715
14732
  }
14716
14733
  }
14717
14734
  if (args.allowTopup !== false) {
14718
- const refill = args.refillPocket ?? (await import("./pocket-refill-U4VK5WGO.js")).refillPocketIfLow;
14735
+ const refill = args.refillPocket ?? (await import("./pocket-refill-ETV6QWO6.js")).refillPocketIfLow;
14719
14736
  await refill({ human: args.human }).catch(() => void 0);
14720
14737
  }
14721
14738
  }
@@ -22020,9 +22037,9 @@ function cashuOptions(mints, hasLightningBackend) {
22020
22037
  const receiveTokenOption = {
22021
22038
  method: "cashu-receive-token",
22022
22039
  display: "Receive an existing Cashu token",
22023
- command: "dvm wallet receive-token <cashu-token>",
22040
+ command: "dvm wallet receive-token",
22024
22041
  description: "Claim a pre-minted Cashu token (e.g. from a friend or a faucet) into the agent wallet. The token is re-locked to your wallet's key so it's spendable.",
22025
- hint: "Tokens are single-use; a token locked to a third party can't be claimed.",
22042
+ hint: "Pipe the token into stdin or redirect a token file; do not pass it as a command argument. Tokens are single-use; a token locked to a third party can't be claimed.",
22026
22043
  ...hasMints ? { mints } : {}
22027
22044
  };
22028
22045
  const options = [];
@@ -28550,7 +28567,7 @@ async function requestWithWarnings(opts, stage) {
28550
28567
  ...receiptTrustFields(providerInfo),
28551
28568
  ...localCorrelationJobFields(localCorrelationId)
28552
28569
  });
28553
- recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment);
28570
+ recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment, false, receiptUpfrontFault(receipt));
28554
28571
  if (noStream && !isTerminalJobStatus(receipt.status)) {
28555
28572
  transport.close();
28556
28573
  const nextAction = pollNextAction(receipt.jobId);
@@ -30863,7 +30880,12 @@ async function readStdin() {
30863
30880
  async function requestResult(requestId, opts = {}) {
30864
30881
  return withOutputWarnings(() => requestResultWithWarnings(requestId, opts), opts.human);
30865
30882
  }
30866
- async function requestResultWithWarnings(requestId, opts) {
30883
+ function resolveRequestId(arg) {
30884
+ if (isPublicRequestId(arg) && loadRequestIntent(arg)) return arg;
30885
+ return loadJob(arg)?.requestId ?? arg;
30886
+ }
30887
+ async function requestResultWithWarnings(argument, opts) {
30888
+ const requestId = resolveRequestId(argument);
30867
30889
  if (!isPublicRequestId(requestId)) {
30868
30890
  throw new DvmError(
30869
30891
  "invalid_request_id",
@@ -30982,7 +31004,7 @@ async function requestResultWithWarnings(requestId, opts) {
30982
31004
  const free = existing?.upfrontRailPayment === "free" || accepted?.amount_msats === 0 && !method;
30983
31005
  recordUpfrontRailPayment(receipt.jobId, localPayment ?? (free ? "free" : accepted && method ? { method, amountMsats: accepted.amount_msats } : void 0));
30984
31006
  }
30985
- recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment, originalData?.fund !== void 0);
31007
+ recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment, originalData?.fund !== void 0, receiptUpfrontFault(receipt));
30986
31008
  if (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled") {
30987
31009
  markJobTerminal(receipt.jobId, receipt.status, completionSnapshot(receipt), restored);
30988
31010
  } else {
@@ -35043,6 +35065,25 @@ function describeFloatOutcome(outcome) {
35043
35065
  }
35044
35066
  }
35045
35067
  async function walletReceiveToken(token, opts) {
35068
+ const stdinHint = "Pipe the Cashu token into `dvm wallet receive-token` or redirect a token file into stdin. Do not put the token in command arguments.";
35069
+ if (token === void 0 || token === "-") {
35070
+ if (process.stdin.isTTY) {
35071
+ throw new DvmError("no_input", "No Cashu token provided.", stdinHint);
35072
+ }
35073
+ try {
35074
+ token = (await drainStdin()).trim();
35075
+ } catch (err) {
35076
+ if (err instanceof StdinTimeoutError) {
35077
+ throw new DvmError("no_input", "No Cashu token provided (stdin timed out).", stdinHint);
35078
+ }
35079
+ throw err;
35080
+ }
35081
+ } else {
35082
+ info("WARNING: passing a Cashu token on the command line exposes it in shell history and process listings, where anyone who reads it can spend it first. Pipe it into `dvm wallet receive-token` instead.");
35083
+ }
35084
+ if (!token) {
35085
+ throw new DvmError("no_input", "No Cashu token provided.", stdinHint);
35086
+ }
35046
35087
  const result = await receiveToAgentWallet(token);
35047
35088
  if (opts.human) {
35048
35089
  info("");
@@ -40619,7 +40660,7 @@ function buildProgram() {
40619
40660
  ).option("--human", "Human-readable output instead of JSON").option("--timeout <sec>", "Override default timeout").action((opts) => {
40620
40661
  return catchErrors(() => request(opts), opts.human);
40621
40662
  });
40622
- program2.command("request-result <request-id>").description("Read the exact accepted job for a caller-generated request id without mutation").option("--human", "Human-readable output instead of JSON").action((requestId, opts) => {
40663
+ program2.command("request-result <request-id>").description("Read the exact accepted job for a caller-generated request id (or a local job id) without mutation").option("--human", "Human-readable output instead of JSON").action((requestId, opts) => {
40623
40664
  return catchErrors(() => requestResult(requestId, opts), opts.human);
40624
40665
  });
40625
40666
  program2.command("request-resume <request-id>").description("Explicitly finish a durably accepted request without sending payment").option("--human", "Human-readable output instead of JSON").option("--timeout <sec>", "Override default timeout").action((requestId, opts) => {
@@ -40945,7 +40986,7 @@ Docs:
40945
40986
  ).option("--all", "Empty the wallet (or the --mint mint) \u2014 fees come out of the balance").option("--mint <url>", "Cash out from this mint only (default: every mint, richest first)").option("--max-fee <sats>", "Refuse a mint whose routing reserve + input fee exceeds this").option("--dry-run", "Quote the melt and report the fee without paying anything").option("--human", "Human-readable output instead of JSON").action((destination, opts) => {
40946
40987
  return catchErrors(() => walletCashOut(destination, opts), opts.human);
40947
40988
  });
40948
- wallet.command("receive-token <token>").description("Claim an external Cashu token into the agent wallet as spendable balance").option("--human", "Human-readable output instead of JSON").action((token, opts) => {
40989
+ wallet.command("receive-token [token]").description("Claim an external Cashu token into the agent wallet. Omit token or use - to read stdin (recommended); positional tokens expose funds in shell history and process listings").option("--human", "Human-readable output instead of JSON").action((token, opts) => {
40949
40990
  return catchErrors(() => walletReceiveToken(token, opts), opts.human);
40950
40991
  });
40951
40992
  wallet.command("set-default-rail [rail]").description("Set the preferred rail for `dvm request` upfront payments (cashu, tempo, x402)").option("--clear", "Clear the persisted default rail").option("--human", "Human-readable output instead of JSON").action((rail, opts) => {
@@ -13,7 +13,7 @@ import {
13
13
  recordFloatSpend,
14
14
  resolveFundMint,
15
15
  sweepPendingMints
16
- } from "./chunk-NCX4JVLU.js";
16
+ } from "./chunk-5ZY5IKS2.js";
17
17
  import "./chunk-MM646MFM.js";
18
18
  import "./chunk-NKD4NEUF.js";
19
19
  import {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dvmkit/dvm-cli",
3
- "version": "0.19.1",
3
+ "version": "0.19.2",
4
4
  "description": "Command-line client and agent skill for Digital Vending Machines: pay-per-use HTTPS services AI agents can find, pay, and call with no account or API key",
5
5
  "author": "DVM Technologies Ltd",
6
6
  "keywords": [
@@ -48,7 +48,7 @@ These command forms and safeguards are promised:
48
48
 
49
49
  | Command or action | Prerequisites and effect |
50
50
  | --- | --- |
51
- | `dvm request-result <request-id>` | Requires the saved request intent and original signing identity. Reads the original accepted job without submitting a replacement or sending payment credentials. Missing state or not found leaves the payment outcome unknown, except `request_not_submitted`: the CLI recorded refusing that request ID before sending it, so no job or payment exists and retrying the same approved request is safe. A saved intent always takes precedence over that record. |
51
+ | `dvm request-result <request-id>` | Also accepts a local job ID and reads the request ID stored on that job (a request ID with a saved intent wins). Requires the saved request intent and original signing identity. Reads the original accepted job without submitting a replacement or sending payment credentials. Missing state or not found leaves the payment outcome unknown, except `request_not_submitted`: the CLI recorded refusing that request ID before sending it, so no job or payment exists and retrying the same approved request is safe. A saved intent always takes precedence over that record. |
52
52
  | `dvm request-resume <request-id>` | First tries `request-result`; only a not-found result allows the dedicated resume route to finish a durably accepted request. Uses the original intent and signer without payment credentials, then reads the canonical result. |
53
53
  | `next_action.type: "resubmit"` | Has string `command` and `hint`, and `requires_user_approval: true`. `command` is a shell-ready `dvm request …` preserving the original request and safety options with the stated adjustments. Run it only after the user approves and the prior outcome permits resubmission. There is no separate `request-resubmit` command. |
54
54
  | `dvm wallet recover-submission <request-id> --binding-fingerprint <sha256>` | Requires the exact journal UUID and original binding fingerprint. Under the wallet lock it permits one recovery attempt using the same payment, records that attempt before I/O, and leaves unrelated submissions untouched. An unknown outcome consumes that attempt; verification or lookup must follow. |
@@ -16,6 +16,8 @@ For a trusted local connection, pass credentials through the CLI's documented fi
16
16
 
17
17
  ## Fund within authorization
18
18
 
19
+ To claim an existing Cashu token, run `dvm wallet receive-token < token.txt` with a token file supplied through a trusted channel, or pipe a trusted tool's token output into `dvm wallet receive-token`. Omitting the argument or using `-` reads and trims stdin. The positional form remains supported but warns on stderr because it exposes spendable funds in shell history and process listings. Never place the token literal in a command, chat, or logs.
20
+
19
21
  Check the required amount and existing balance before topping up. Wallet funding and job payments both count toward spending caps; leave enough authorized headroom for both. Quote shell amounts containing a dollar sign, for example `dvm wallet fund '$5'`, so the shell does not substitute them.
20
22
 
21
23
  For autonomous funding, follow the output until it reports the observed result. When a human pays a Cashu Lightning invoice, run `dvm wallet fund '<amount>' --no-float --no-wait`, then run the returned `next_step` (`dvm wallet show`) after payment to collect it. An existing unpaid-quote warning names an earlier invoice: avoid asking the human to pay both for the same top-up. Collect before the returned `collect_before` time: a mint can refuse to issue for a paid invoice once its quote has expired. `dvm wallet show` keeps an unpaid invoice past its expiry and keeps checking it for a late payment for 24 hours (`sweep.kept_past_expiry`); it removes one only when the mint no longer honors it (`sweep.expired`). An invoice whose mint named no expiry stays pending until it is paid or you run `dvm wallet forget-quote <quote-id> --yes`. Forget a quote only when you are sure its invoice will not be paid: a payment made afterwards cannot be collected.