@lucid-agents/taskmarket 1.48.0 → 1.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/agent-compatibility.json +1 -1
  2. package/dist/{api-2PFUP432.js → api-SXHSD3WO.js} +2 -2
  3. package/dist/{channels-Z6VN7FXP.js → channels-4YOMV7R7.js} +4 -4
  4. package/dist/{chunk-AB3BDUMS.js → chunk-6VZBAHQC.js} +3 -3
  5. package/dist/{chunk-GPKAJ7QH.js → chunk-C7557KRB.js} +1 -1
  6. package/dist/{chunk-KTT6PSHQ.js → chunk-CGUFHUIV.js} +1 -1
  7. package/dist/{chunk-JXBWKGXC.js → chunk-EJ7KUYME.js} +141 -25
  8. package/dist/{chunk-UJ3FRWUU.js → chunk-EVCG557X.js} +1 -1
  9. package/dist/{chunk-SV6LNVI5.js → chunk-EYHXTVYK.js} +2 -2
  10. package/dist/{chunk-QRNIBDYX.js → chunk-FGW2NNPQ.js} +3 -3
  11. package/dist/{chunk-DKBI3SE3.js → chunk-M5WTLXDY.js} +1 -1
  12. package/dist/{chunk-WPJRL4F7.js → chunk-MY5CD4PT.js} +8 -8
  13. package/dist/{chunk-YAUYTYQI.js → chunk-PZI3QQO4.js} +5 -5
  14. package/dist/{chunk-VYYJ7FUB.js → chunk-V5S4LCIE.js} +318 -88
  15. package/dist/{chunk-VENFZBAZ.js → chunk-YBSZTSJE.js} +1 -1
  16. package/dist/{doctor-6ASEDCCF.js → doctor-FACAMASV.js} +9 -8
  17. package/dist/index.js +993 -1917
  18. package/dist/{launch-JVXJSXJF.js → launch-K5666QYB.js} +11 -11
  19. package/dist/pi-extensions/xgate.cjs +204 -121
  20. package/dist/{read-auth-OQ3VVA4V.js → read-auth-EFE6NQFG.js} +3 -3
  21. package/dist/{reconcile-TJ2VXC6R.js → reconcile-Q4MJXXR3.js} +4 -4
  22. package/dist/{status-LU7AKAKJ.js → status-YKFKGTMQ.js} +9 -8
  23. package/dist/{sync-pull-52G7XZZT.js → sync-pull-AN2M344W.js} +4 -4
  24. package/dist/{task-access-grants-HUYBGG5E.js → task-access-grants-MN5WXHHQ.js} +2 -2
  25. package/package.json +7 -10
@@ -1,4 +1,7 @@
1
1
  import { createRequire as __tmCreateRequire } from 'node:module'; import { fileURLToPath as __tmFileURLToPath } from 'node:url'; import { dirname as __tmDirname } from 'node:path'; const require = __tmCreateRequire(import.meta.url); const __tmFilename = __tmFileURLToPath(import.meta.url); const __tmDirnameValue = __tmDirname(__tmFilename);
2
+ import {
3
+ signReadAuth
4
+ } from "./chunk-EYHXTVYK.js";
2
5
  import {
3
6
  MPP_TEMPO_CHARGE_SCHEME,
4
7
  X402PayError,
@@ -17,7 +20,7 @@ import {
17
20
  readMppTempoChallenge,
18
21
  reconcileX402Payment,
19
22
  withX402FileLock
20
- } from "./chunk-GPKAJ7QH.js";
23
+ } from "./chunk-C7557KRB.js";
21
24
  import {
22
25
  ApiError,
23
26
  apiGet,
@@ -38,34 +41,177 @@ import {
38
41
  withChainId,
39
42
  withIdempotentWrite,
40
43
  withTapSignature
41
- } from "./chunk-UJ3FRWUU.js";
44
+ } from "./chunk-EVCG557X.js";
42
45
  import {
43
46
  ComputeCreditBuyOutputSchema,
44
47
  ComputeCreditPricingSchema,
45
48
  ComputeCreditStatusOutputSchema,
49
+ IntentStatusResponseSchema,
46
50
  apiErrorEnvelopeOf,
47
51
  getTaskmarketHome
48
- } from "./chunk-JXBWKGXC.js";
52
+ } from "./chunk-EJ7KUYME.js";
49
53
 
50
54
  // src/lib/x402-fee.ts
51
- import { randomUUID as randomUUID3 } from "crypto";
55
+ import { randomUUID as randomUUID4 } from "crypto";
56
+
57
+ // src/lib/paid-write-bodies.ts
58
+ import { createHash, randomUUID } from "crypto";
59
+ import { promises as fs } from "fs";
60
+ import path from "path";
61
+ var PROOF_FIELDS = ["nonce", "expiresAt", "signature"];
62
+ var SAVED_PATHS = /* @__PURE__ */ new Set([
63
+ "/api/catalog/submissions",
64
+ "/api/hooks/submissions"
65
+ ]);
66
+ var SECRET_FIELD = /^(?:secret|password|passphrase|mnemonic|seed|seedPhrase|credentials?|bearer)$|(?:token|secret|password|passphrase|privateKey|apiKey|mnemonic|credentials?)$/i;
67
+ function isSecretField(name) {
68
+ if (/^token$/i.test(name)) return false;
69
+ const words = name.replace(/[-_]/g, "");
70
+ return SECRET_FIELD.test(name) || SECRET_FIELD.test(words);
71
+ }
72
+ function holdsSecret(value) {
73
+ if (Array.isArray(value)) return value.some(holdsSecret);
74
+ if (value !== null && typeof value === "object") {
75
+ return Object.entries(value).some(
76
+ ([key, entry]) => isSecretField(key) || holdsSecret(entry)
77
+ );
78
+ }
79
+ return false;
80
+ }
81
+ var PROOF_EXPIRY_MARGIN_SECONDS = 30;
82
+ var RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
83
+ function directory() {
84
+ return path.join(getTaskmarketHome(), "paid-writes");
85
+ }
86
+ function recordPath(idempotencyKey) {
87
+ return path.join(
88
+ directory(),
89
+ `${createHash("sha256").update(idempotencyKey).digest("hex")}.json`
90
+ );
91
+ }
92
+ function canonical(value) {
93
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
94
+ if (value !== null && typeof value === "object") {
95
+ const entries = Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
96
+ return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonical(entry)}`).join(",")}}`;
97
+ }
98
+ return JSON.stringify(value) ?? "null";
99
+ }
100
+ function withoutProof(body) {
101
+ const rest = { ...body };
102
+ for (const field of PROOF_FIELDS) delete rest[field];
103
+ return rest;
104
+ }
105
+ function reusable(stored, fresh, nowMs) {
106
+ let parsed;
107
+ try {
108
+ parsed = JSON.parse(stored);
109
+ } catch {
110
+ return false;
111
+ }
112
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return false;
113
+ const record = parsed;
114
+ const freshSent = JSON.parse(JSON.stringify(fresh));
115
+ if (canonical(withoutProof(record)) !== canonical(withoutProof(freshSent))) return false;
116
+ const expiresAt = record["expiresAt"];
117
+ return typeof expiresAt === "number" && expiresAt - PROOF_EXPIRY_MARGIN_SECONDS <= Math.floor(nowMs / 1e3) ? "expired" : "valid";
118
+ }
119
+ async function load(idempotencyKey) {
120
+ let raw;
121
+ try {
122
+ raw = await fs.readFile(recordPath(idempotencyKey), "utf8");
123
+ } catch (error) {
124
+ if (error.code === "ENOENT") return null;
125
+ throw error;
126
+ }
127
+ try {
128
+ const record = JSON.parse(raw);
129
+ return record.version === 1 && record.idempotencyKey === idempotencyKey && typeof record.body === "string" ? record : null;
130
+ } catch {
131
+ return null;
132
+ }
133
+ }
134
+ async function save(record) {
135
+ await fs.mkdir(directory(), { recursive: true, mode: 448 });
136
+ await fs.chmod(directory(), 448);
137
+ const target = recordPath(record.idempotencyKey);
138
+ const temporary = `${target}.${randomUUID()}.tmp`;
139
+ try {
140
+ await fs.writeFile(temporary, JSON.stringify(record), { mode: 384 });
141
+ await fs.chmod(temporary, 384);
142
+ await fs.rename(temporary, target);
143
+ } catch (error) {
144
+ await fs.rm(temporary, { force: true });
145
+ throw error;
146
+ }
147
+ }
148
+ async function prune(nowMs) {
149
+ let names;
150
+ try {
151
+ names = await fs.readdir(directory());
152
+ } catch {
153
+ return;
154
+ }
155
+ await Promise.all(
156
+ names.map(async (name) => {
157
+ const file = path.join(directory(), name);
158
+ try {
159
+ if (nowMs - (await fs.stat(file)).mtimeMs > RETENTION_MS)
160
+ await fs.rm(file, { force: true });
161
+ } catch {
162
+ }
163
+ })
164
+ );
165
+ }
166
+ async function fixedPaidWriteBody(requestPath, body, idempotencyKey, options = {}) {
167
+ const nowMs = options.nowMs ?? Date.now();
168
+ const stored = await load(idempotencyKey).catch(() => null);
169
+ const state = stored && stored.path === requestPath ? reusable(stored.body, body, nowMs) : false;
170
+ if (state === "valid") return stored.body;
171
+ if (state === "expired" && await options.keyCompleted?.().catch(() => false)) {
172
+ return stored.body;
173
+ }
174
+ const fresh = JSON.stringify(body);
175
+ if (!SAVED_PATHS.has(requestPath) || holdsSecret(body)) return fresh;
176
+ try {
177
+ await save({
178
+ version: 1,
179
+ idempotencyKey,
180
+ path: requestPath,
181
+ body: fresh,
182
+ savedAt: new Date(nowMs).toISOString()
183
+ });
184
+ await prune(nowMs);
185
+ } catch {
186
+ }
187
+ return fresh;
188
+ }
189
+ async function forgetPaidWriteBody(idempotencyKey) {
190
+ await fs.rm(recordPath(idempotencyKey), { force: true }).catch(() => void 0);
191
+ }
52
192
 
53
193
  // src/lib/paid-write.ts
54
- function paidWriteRequest(keystore, path3, body, idempotencyKey) {
194
+ async function paidWriteRequest(keystore, path4, body, idempotencyKey) {
195
+ const sent = await fixedPaidWriteBody(path4, body, idempotencyKey, {
196
+ keyCompleted: () => keyNamesCompletedWrite(idempotencyKey)
197
+ });
55
198
  return {
56
- url: `${apiUrl()}${path3}`,
199
+ url: `${apiUrl()}${path4}`,
57
200
  headers: {
58
201
  "Content-Type": "application/json",
59
- ...legalReceiptHeadersForKeystore(keystore, path3, "POST"),
202
+ ...legalReceiptHeadersForKeystore(keystore, path4, "POST"),
60
203
  ...idempotencyHeaders(idempotencyKey)
61
204
  },
62
- body: JSON.stringify(body)
205
+ body: sent
63
206
  };
64
207
  }
65
- function refusedPaidWrite(path3, status, read, idempotencyKey) {
208
+ function withSelectedChain(path4, body) {
209
+ return /^\/api\/tasks\/[^/]+\//.test(path4) ? { chainId: selectedNetwork().chainId, ...body } : body;
210
+ }
211
+ function refusedPaidWrite(path4, status, read, idempotencyKey) {
66
212
  return new ApiError(
67
213
  status,
68
- `POST ${path3} failed (${status}): ${read.text}`,
214
+ `POST ${path4} failed (${status}): ${read.text}`,
69
215
  idempotencyKey,
70
216
  apiErrorEnvelopeOf(read.body) ?? void 0
71
217
  );
@@ -79,30 +225,66 @@ var REFUSED_BEFORE_SETTLEMENT = /* @__PURE__ */ new Set([
79
225
  "chain_conflict",
80
226
  "invalid_input"
81
227
  ]);
82
- function failedAfterPayment(path3, status, read, idempotencyKey) {
228
+ function failedAfterPayment(path4, status, read, idempotencyKey) {
83
229
  const envelope = apiErrorEnvelopeOf(read.body) ?? void 0;
84
- const prefix = envelope !== void 0 && REFUSED_BEFORE_SETTLEMENT.has(envelope.reason) ? `POST ${path3} was refused before payment; no payment was taken` : `POST ${path3} failed after payment`;
230
+ const prefix = envelope !== void 0 && REFUSED_BEFORE_SETTLEMENT.has(envelope.reason) ? `POST ${path4} was refused before payment; no payment was taken` : `POST ${path4} failed after payment`;
85
231
  return new ApiError(status, failureMessage(prefix, status, read), idempotencyKey, envelope);
86
232
  }
233
+ async function keyNamesCompletedWrite(idempotencyKey) {
234
+ const headers = (await signReadAuth())?.headers ?? {};
235
+ const intent = IntentStatusResponseSchema.safeParse(
236
+ await apiGet(`/api/intents?idempotencyKey=${encodeURIComponent(idempotencyKey)}`, { headers })
237
+ );
238
+ return intent.success && intent.data.status === "completed" && intent.data.result !== void 0;
239
+ }
240
+ function replayedFields(outcome) {
241
+ return outcome.replayed ? { replayed: true, intentId: outcome.replayed.intentId } : {};
242
+ }
243
+ async function filledWriteOutcome(status, read, idempotencyKey) {
244
+ const envelope = apiErrorEnvelopeOf(read.body);
245
+ if (status !== 409 || envelope?.reason !== "idempotency_key_reused" || envelope.intentStatus !== "completed" || // The backend compared this request's route and body hash with the completed intent's.
246
+ envelope.sameRequest !== true) {
247
+ return void 0;
248
+ }
249
+ let intent;
250
+ try {
251
+ const headers = (await signReadAuth())?.headers ?? {};
252
+ intent = IntentStatusResponseSchema.safeParse(
253
+ await apiGet(`/api/intents?idempotencyKey=${encodeURIComponent(idempotencyKey)}`, {
254
+ headers
255
+ })
256
+ );
257
+ } catch {
258
+ return void 0;
259
+ }
260
+ if (!intent.success || intent.data.status !== "completed" || intent.data.result === void 0 || intent.data.intentId !== envelope.intentId || intent.data.operation !== envelope.operation) {
261
+ return void 0;
262
+ }
263
+ return {
264
+ data: intent.data.result,
265
+ idempotencyKey,
266
+ replayed: { intentId: intent.data.intentId, operation: intent.data.operation }
267
+ };
268
+ }
87
269
 
88
270
  // src/lib/mpp.ts
89
271
  var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
90
- function inFlight(path3, read, key) {
272
+ function inFlight(path4, read, key) {
91
273
  const envelope = apiErrorEnvelopeOf(read.body) ?? void 0;
92
274
  const txHash = read.body?.taskmarket?.txHash;
93
275
  return new ApiError(
94
276
  409,
95
- `POST ${path3}: the payment transfer${typeof txHash === "string" ? ` ${txHash}` : ""} was submitted but its outcome is not known yet. Do not pay again; re-run with TASKMARKET_IDEMPOTENCY_KEY=${key} to check this write.`,
277
+ `POST ${path4}: the payment transfer${typeof txHash === "string" ? ` ${txHash}` : ""} was submitted but its outcome is not known yet. Do not pay again; re-run with TASKMARKET_IDEMPOTENCY_KEY=${key} to check this write.`,
96
278
  key,
97
279
  envelope
98
280
  );
99
281
  }
100
- async function mppPost(path3, body, options = {}) {
282
+ async function mppPost(path4, body, options = {}) {
101
283
  const keystore = await loadKeystore();
102
284
  const fetchImpl = options.fetchImpl ?? globalThis.fetch;
103
285
  const idempotencyKey = resolveIdempotencyKey(options.idempotencyKey);
104
286
  const chainId = options.chainId ?? selectedNetwork().chainId;
105
- const request = paidWriteRequest(keystore, path3, { chainId, ...body }, idempotencyKey);
287
+ const request = await paidWriteRequest(keystore, path4, { chainId, ...body }, idempotencyKey);
106
288
  Object.assign(request.headers, options.headers ?? {});
107
289
  const send = (headers) => fetchImpl(request.url, {
108
290
  method: "POST",
@@ -123,8 +305,18 @@ async function mppPost(path3, body, options = {}) {
123
305
  return withIdempotentWrite(idempotencyKey, async () => {
124
306
  const r1 = await send({});
125
307
  if (r1.status !== 402) {
126
- if (r1.ok) return { data: await r1.json(), idempotencyKey };
127
- throw refusedPaidWrite(path3, r1.status, await readFailureBody(r1), idempotencyKey);
308
+ if (r1.ok) {
309
+ const data = await r1.json();
310
+ await forgetPaidWriteBody(idempotencyKey);
311
+ return { data, idempotencyKey };
312
+ }
313
+ const read = await readFailureBody(r1);
314
+ const filled = await filledWriteOutcome(r1.status, read, idempotencyKey);
315
+ if (filled) {
316
+ await forgetPaidWriteBody(idempotencyKey);
317
+ return filled;
318
+ }
319
+ throw refusedPaidWrite(path4, r1.status, read, idempotencyKey);
128
320
  }
129
321
  const challenge = readMppTempoChallenge(r1.headers);
130
322
  if (!challenge) throw new Error("No payment methods accepted by server");
@@ -150,31 +342,40 @@ async function mppPost(path3, body, options = {}) {
150
342
  if (canRetry) continue;
151
343
  throw error;
152
344
  }
153
- if (r2.ok) return { data: await r2.json(), idempotencyKey };
345
+ if (r2.ok) {
346
+ const data = await r2.json();
347
+ await forgetPaidWriteBody(idempotencyKey);
348
+ return { data, idempotencyKey };
349
+ }
154
350
  const read = await readFailureBody(r2);
155
351
  if (RETRYABLE_STATUSES.has(r2.status) && canRetry) continue;
156
352
  const reason = apiErrorEnvelopeOf(read.body)?.reason;
157
353
  if (r2.status === 409 && reason === "intent_in_flight")
158
- throw inFlight(path3, read, idempotencyKey);
354
+ throw inFlight(path4, read, idempotencyKey);
159
355
  if (r2.status === 402) {
160
- throw refusedPaidWrite(path3, r2.status, read, idempotencyKey);
356
+ throw refusedPaidWrite(path4, r2.status, read, idempotencyKey);
357
+ }
358
+ const filledByKey = await filledWriteOutcome(r2.status, read, idempotencyKey);
359
+ if (filledByKey) {
360
+ await forgetPaidWriteBody(idempotencyKey);
361
+ return filledByKey;
161
362
  }
162
- throw failedAfterPayment(path3, r2.status, read, idempotencyKey);
363
+ throw failedAfterPayment(path4, r2.status, read, idempotencyKey);
163
364
  }
164
365
  });
165
366
  }
166
367
 
167
368
  // src/lib/x402-pay-client.ts
168
- import { randomUUID as randomUUID2 } from "crypto";
369
+ import { randomUUID as randomUUID3 } from "crypto";
169
370
 
170
371
  // src/lib/x402-http.ts
171
- import { createHash, randomUUID } from "crypto";
172
- import { promises as fs } from "fs";
173
- import path from "path";
372
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
373
+ import { promises as fs2 } from "fs";
374
+ import path2 from "path";
174
375
  async function loadExternalHeaders(input) {
175
376
  const result = {};
176
377
  if (input.headersFile) {
177
- const handle = await fs.open(input.headersFile, "r");
378
+ const handle = await fs2.open(input.headersFile, "r");
178
379
  let raw;
179
380
  try {
180
381
  const stat = await handle.stat();
@@ -223,7 +424,7 @@ function requestBodyTooLarge(maxBytes) {
223
424
  });
224
425
  }
225
426
  async function readBoundedBodyFile(bodyFile, maxBytes) {
226
- const handle = await fs.open(bodyFile, "r");
427
+ const handle = await fs2.open(bodyFile, "r");
227
428
  try {
228
429
  const stat = await handle.stat();
229
430
  if (stat.isFile() && stat.size > maxBytes) throw requestBodyTooLarge(maxBytes);
@@ -271,26 +472,26 @@ async function readX402RequestBody(input) {
271
472
  return Buffer.from(raw, "utf8");
272
473
  }
273
474
  async function writeExclusiveAtomic(outputPath, bytes) {
274
- const directory = path.dirname(outputPath);
275
- await fs.mkdir(directory, { recursive: true });
276
- const temporaryPath = path.join(directory, `.${path.basename(outputPath)}-${randomUUID()}.tmp`);
475
+ const directory2 = path2.dirname(outputPath);
476
+ await fs2.mkdir(directory2, { recursive: true });
477
+ const temporaryPath = path2.join(directory2, `.${path2.basename(outputPath)}-${randomUUID2()}.tmp`);
277
478
  try {
278
- await fs.writeFile(temporaryPath, bytes, { flag: "wx", mode: 384 });
279
- await fs.link(temporaryPath, outputPath);
280
- await fs.unlink(temporaryPath);
479
+ await fs2.writeFile(temporaryPath, bytes, { flag: "wx", mode: 384 });
480
+ await fs2.link(temporaryPath, outputPath);
481
+ await fs2.unlink(temporaryPath);
281
482
  } catch (error) {
282
483
  if (error.code === "EEXIST") {
283
484
  throw new Error(`Output file already exists: ${outputPath}`);
284
485
  }
285
486
  throw error;
286
487
  } finally {
287
- await fs.rm(temporaryPath, { force: true }).catch(() => void 0);
488
+ await fs2.rm(temporaryPath, { force: true }).catch(() => void 0);
288
489
  }
289
490
  }
290
491
  async function externalResponseData(response, options = {}) {
291
492
  const bytes = response instanceof Response ? new Uint8Array(await response.arrayBuffer()) : response.body;
292
493
  const contentType = response instanceof Response ? response.headers.get("content-type") ?? "application/octet-stream" : response.contentType;
293
- const sha256 = createHash("sha256").update(bytes).digest("hex");
494
+ const sha256 = createHash2("sha256").update(bytes).digest("hex");
294
495
  if (options.outputPath) {
295
496
  await writeExclusiveAtomic(options.outputPath, bytes);
296
497
  return {
@@ -298,7 +499,7 @@ async function externalResponseData(response, options = {}) {
298
499
  contentType,
299
500
  bytes: bytes.length,
300
501
  sha256,
301
- outputPath: path.resolve(options.outputPath)
502
+ outputPath: path2.resolve(options.outputPath)
302
503
  };
303
504
  }
304
505
  const inlineLimit = options.inlineLimitBytes ?? 1048576;
@@ -380,7 +581,7 @@ async function executeX402PayRequest(options) {
380
581
  const result = await payer.request(
381
582
  {
382
583
  apiVersion: 1,
383
- invocationId: options.invocationId ?? randomUUID2(),
584
+ invocationId: options.invocationId ?? randomUUID3(),
384
585
  url: options.rawUrl,
385
586
  method,
386
587
  headers: options.headers,
@@ -461,11 +662,11 @@ function prePaymentFailure(error) {
461
662
  }
462
663
  return error;
463
664
  }
464
- async function x402FeePost(path3, body, options = {}) {
665
+ async function x402FeePost(path4, body, options = {}) {
465
666
  if (paymentProtocolOf(selectedNetwork().chainId) === "mpp") {
466
667
  if (options.allocationId !== void 0)
467
668
  throw new Error("x402 allocations cannot pay for writes on a Tempo network");
468
- return mppPost(path3, body, {
669
+ return mppPost(path4, body, {
469
670
  idempotencyKey: options.idempotencyKey,
470
671
  expect: options.expect,
471
672
  account: options.account,
@@ -475,7 +676,12 @@ async function x402FeePost(path3, body, options = {}) {
475
676
  }
476
677
  const keystore = await loadKeystore();
477
678
  const idempotencyKey = resolveIdempotencyKey(options.idempotencyKey);
478
- const request = paidWriteRequest(keystore, path3, body, idempotencyKey);
679
+ const request = await paidWriteRequest(
680
+ keystore,
681
+ path4,
682
+ withSelectedChain(path4, body),
683
+ idempotencyKey
684
+ );
479
685
  return withIdempotentWrite(idempotencyKey, async () => {
480
686
  const payer = createCliX402Payer({
481
687
  firstParty: true,
@@ -490,7 +696,7 @@ async function x402FeePost(path3, body, options = {}) {
490
696
  apiVersion: 1,
491
697
  // A fresh invocation per run: the backend recognises a repeated write by its idempotency
492
698
  // key, so a re-run must reach it rather than be answered from the local journal.
493
- invocationId: options.invocationId ?? randomUUID3(),
699
+ invocationId: options.invocationId ?? randomUUID4(),
494
700
  url: request.url,
495
701
  method: "POST",
496
702
  headers: request.headers,
@@ -506,8 +712,17 @@ async function x402FeePost(path3, body, options = {}) {
506
712
  if (isSuccess(error.response.status)) {
507
713
  return { data: successData(error.response), idempotencyKey };
508
714
  }
715
+ const filledByKey = await filledWriteOutcome(
716
+ error.response.status,
717
+ bodyOf(error.response),
718
+ idempotencyKey
719
+ );
720
+ if (filledByKey) {
721
+ await forgetPaidWriteBody(idempotencyKey);
722
+ return filledByKey;
723
+ }
509
724
  throw failedAfterPayment(
510
- path3,
725
+ path4,
511
726
  error.response.status,
512
727
  bodyOf(error.response),
513
728
  idempotencyKey
@@ -517,19 +732,27 @@ async function x402FeePost(path3, body, options = {}) {
517
732
  }
518
733
  const { response } = result;
519
734
  if (isSuccess(response.status)) {
520
- return { data: successData(response), idempotencyKey };
735
+ const data = successData(response);
736
+ await forgetPaidWriteBody(idempotencyKey);
737
+ return { data, idempotencyKey };
738
+ }
739
+ const read = bodyOf(response);
740
+ const filled = await filledWriteOutcome(response.status, read, idempotencyKey);
741
+ if (filled) {
742
+ await forgetPaidWriteBody(idempotencyKey);
743
+ return filled;
521
744
  }
522
745
  if (result.payment !== void 0) {
523
- throw failedAfterPayment(path3, response.status, bodyOf(response), idempotencyKey);
746
+ throw failedAfterPayment(path4, response.status, read, idempotencyKey);
524
747
  }
525
- throw refusedPaidWrite(path3, response.status, bodyOf(response), idempotencyKey);
748
+ throw refusedPaidWrite(path4, response.status, read, idempotencyKey);
526
749
  });
527
750
  }
528
751
 
529
752
  // src/lib/compute-credits.ts
530
- import { randomUUID as randomUUID4 } from "crypto";
531
- import { promises as fs2 } from "fs";
532
- import path2 from "path";
753
+ import { randomUUID as randomUUID5 } from "crypto";
754
+ import { promises as fs3 } from "fs";
755
+ import path3 from "path";
533
756
  var COMPUTE_CREDIT_PATH = "/api/compute/credits";
534
757
  var COMPUTE_CREDIT_STATUS_PATH = "/api/compute/credits/status";
535
758
  var COMPUTE_PRICING_PATH = "/api/compute/pricing";
@@ -546,20 +769,20 @@ var ComputeCreditError = class extends Error {
546
769
  }
547
770
  };
548
771
  function getComputeCreditConfigPath() {
549
- return path2.join(getTaskmarketHome(), "compute-credits.json");
772
+ return path3.join(getTaskmarketHome(), "compute-credits.json");
550
773
  }
551
774
  function pendingDirectory() {
552
- return path2.join(getTaskmarketHome(), "compute-credit-purchases");
775
+ return path3.join(getTaskmarketHome(), "compute-credit-purchases");
553
776
  }
554
777
  function pendingPath(idempotencyKey) {
555
- return path2.join(pendingDirectory(), `${idempotencyKey}.json`);
778
+ return path3.join(pendingDirectory(), `${idempotencyKey}.json`);
556
779
  }
557
780
  async function withComputeCreditLock(fn) {
558
781
  const timeoutMessage = `compute credit lock: waited ${COMPUTE_CREDIT_LOCK_WAIT_MS} ms`;
559
782
  let entered = false;
560
783
  try {
561
784
  return await withX402FileLock(
562
- path2.join(getTaskmarketHome(), "compute-credits.lock"),
785
+ path3.join(getTaskmarketHome(), "compute-credits.lock"),
563
786
  () => {
564
787
  entered = true;
565
788
  return fn();
@@ -575,16 +798,18 @@ async function withComputeCreditLock(fn) {
575
798
  }
576
799
  }
577
800
  async function writePrivateJson(file, value) {
578
- await fs2.mkdir(path2.dirname(file), { recursive: true, mode: 448 });
579
- const temporary = `${file}.${process.pid}.${randomUUID4()}.tmp`;
580
- await fs2.writeFile(temporary, `${JSON.stringify(value, null, 2)}
801
+ await fs3.mkdir(path3.dirname(file), { recursive: true, mode: 448 });
802
+ await fs3.chmod(path3.dirname(file), 448);
803
+ const temporary = `${file}.${process.pid}.${randomUUID5()}.tmp`;
804
+ await fs3.writeFile(temporary, `${JSON.stringify(value, null, 2)}
581
805
  `, { mode: 384 });
582
- await fs2.rename(temporary, file);
806
+ await fs3.chmod(temporary, 384);
807
+ await fs3.rename(temporary, file);
583
808
  }
584
809
  async function loadComputeCreditConfig() {
585
810
  let text;
586
811
  try {
587
- text = await fs2.readFile(getComputeCreditConfigPath(), "utf8");
812
+ text = await fs3.readFile(getComputeCreditConfigPath(), "utf8");
588
813
  } catch (error) {
589
814
  if (error.code === "ENOENT") return void 0;
590
815
  throw error;
@@ -601,7 +826,7 @@ async function loadComputeCreditConfig() {
601
826
  async function listPendingComputePurchases() {
602
827
  let names;
603
828
  try {
604
- names = await fs2.readdir(pendingDirectory());
829
+ names = await fs3.readdir(pendingDirectory());
605
830
  } catch (error) {
606
831
  if (error.code === "ENOENT") return [];
607
832
  throw error;
@@ -610,7 +835,7 @@ async function listPendingComputePurchases() {
610
835
  for (const name of names.filter((entry) => entry.endsWith(".json")).sort()) {
611
836
  let text;
612
837
  try {
613
- text = await fs2.readFile(path2.join(pendingDirectory(), name), "utf8");
838
+ text = await fs3.readFile(path3.join(pendingDirectory(), name), "utf8");
614
839
  } catch (error) {
615
840
  if (error.code === "ENOENT") continue;
616
841
  throw error;
@@ -620,7 +845,7 @@ async function listPendingComputePurchases() {
620
845
  return records.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
621
846
  }
622
847
  async function forgetPending(idempotencyKey) {
623
- await fs2.rm(pendingPath(idempotencyKey), { force: true });
848
+ await fs3.rm(pendingPath(idempotencyKey), { force: true });
624
849
  }
625
850
  function usdToAtomic(value) {
626
851
  const match = /^(\d{1,9})(?:\.(\d{1,6}))?$/.exec(value.trim());
@@ -728,7 +953,7 @@ async function applyComputeCreditSetup(plan, approvalNote, now = /* @__PURE__ */
728
953
  async function applySetupLocked(plan, approvalNote, now) {
729
954
  const replaces = (await loadComputeCreditConfig())?.allocationId;
730
955
  const store = allocations();
731
- const allocationId = `compute-credits-${randomUUID4()}`;
956
+ const allocationId = `compute-credits-${randomUUID5()}`;
732
957
  await store.open(
733
958
  {
734
959
  id: allocationId,
@@ -857,31 +1082,29 @@ async function purchaseLocked(input, seams) {
857
1082
  assertDenomination(pricing, input.amountUsd);
858
1083
  const { payTo } = railOf(pricing);
859
1084
  const keystore = await loadKeystore();
1085
+ const request = {
1086
+ chainId: selectedNetwork().chainId,
1087
+ deviceId: keystore.deviceId,
1088
+ apiToken: keystore.apiToken,
1089
+ amountUsd: input.amountUsd
1090
+ };
860
1091
  const pending = {
861
- idempotencyKey: randomUUID4(),
862
- invocationId: randomUUID4(),
1092
+ idempotencyKey: randomUUID5(),
1093
+ invocationId: randomUUID5(),
863
1094
  amountUsd: input.amountUsd,
864
1095
  auto: Boolean(input.auto),
865
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1096
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1097
+ request
866
1098
  };
867
1099
  await writePrivateJson(pendingPath(pending.idempotencyKey), pending);
868
1100
  try {
869
- const outcome = await x402FeePost(
870
- COMPUTE_CREDIT_PATH,
871
- {
872
- chainId: selectedNetwork().chainId,
873
- deviceId: keystore.deviceId,
874
- apiToken: keystore.apiToken,
875
- amountUsd: input.amountUsd
876
- },
877
- {
878
- idempotencyKey: pending.idempotencyKey,
879
- invocationId: pending.invocationId,
880
- allocationId,
881
- expect: { amount: usdAtomic(input.amountUsd), payTo },
882
- ...seams
883
- }
884
- );
1101
+ const outcome = await x402FeePost(COMPUTE_CREDIT_PATH, request, {
1102
+ idempotencyKey: pending.idempotencyKey,
1103
+ invocationId: pending.invocationId,
1104
+ allocationId,
1105
+ expect: { amount: usdAtomic(input.amountUsd), payTo },
1106
+ ...seams
1107
+ });
885
1108
  const parsed = ComputeCreditBuyOutputSchema.safeParse(outcome.data);
886
1109
  if (!parsed.success) {
887
1110
  throw new ComputeCreditError("invalid_response", "The purchase response is malformed");
@@ -903,13 +1126,21 @@ function apiErrorCode(error) {
903
1126
  error.message
904
1127
  )?.[1];
905
1128
  }
1129
+ async function legacyPurchaseRequest(record) {
1130
+ const keystore = await loadKeystore();
1131
+ return {
1132
+ chainId: selectedNetwork().chainId,
1133
+ deviceId: keystore.deviceId,
1134
+ apiToken: keystore.apiToken,
1135
+ amountUsd: record.amountUsd
1136
+ };
1137
+ }
906
1138
  async function resolvePendingComputePurchases(seams = {}) {
907
1139
  return withComputeCreditLock(() => resolvePendingLocked(seams));
908
1140
  }
909
1141
  async function resolvePendingLocked(seams) {
910
1142
  const records = await listPendingComputePurchases();
911
1143
  if (records.length === 0) return [];
912
- const keystore = await loadKeystore();
913
1144
  const payer = createCliX402Payer({ firstParty: true, ...seams });
914
1145
  const outcomes = [];
915
1146
  for (const record of records) {
@@ -930,12 +1161,7 @@ async function resolvePendingLocked(seams) {
930
1161
  try {
931
1162
  const replay = await apiPost(
932
1163
  COMPUTE_CREDIT_PATH,
933
- {
934
- chainId: selectedNetwork().chainId,
935
- deviceId: keystore.deviceId,
936
- apiToken: keystore.apiToken,
937
- amountUsd: record.amountUsd
938
- },
1164
+ record.request ?? await legacyPurchaseRequest(record),
939
1165
  { idempotencyKey: key }
940
1166
  );
941
1167
  const parsed = ComputeCreditBuyOutputSchema.safeParse(replay.data);
@@ -1124,9 +1350,13 @@ async function onComputeBalanceObserved(observation, seams = {}) {
1124
1350
  }
1125
1351
 
1126
1352
  export {
1353
+ forgetPaidWriteBody,
1127
1354
  paidWriteRequest,
1355
+ withSelectedChain,
1128
1356
  refusedPaidWrite,
1129
1357
  failedAfterPayment,
1358
+ replayedFields,
1359
+ filledWriteOutcome,
1130
1360
  mppPost,
1131
1361
  loadExternalHeaders,
1132
1362
  x402PaymentProtocol,
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tmCreateRequire } from 'node:module'; import { fileURLToPath as __tmFileURLToPath } from 'node:url'; import { dirname as __tmDirname } from 'node:path'; const require = __tmCreateRequire(import.meta.url); const __tmFilename = __tmFileURLToPath(import.meta.url); const __tmDirnameValue = __tmDirname(__tmFilename);
2
2
  import {
3
3
  getTaskmarketHome
4
- } from "./chunk-JXBWKGXC.js";
4
+ } from "./chunk-EJ7KUYME.js";
5
5
  import {
6
6
  AgentLaunchError
7
7
  } from "./chunk-YM4S6IE4.js";