@lucid-agents/taskmarket 1.44.0 → 1.46.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-QATTK6I6.js → api-56KWZFR4.js} +2 -2
  3. package/dist/{channels-AH2WHLMC.js → channels-YKCZU2Q7.js} +4 -4
  4. package/dist/{chunk-3HR7XRLE.js → chunk-3MITXF2F.js} +3 -3
  5. package/dist/{chunk-3NPMVKNZ.js → chunk-64NUUQBC.js} +1 -1
  6. package/dist/{chunk-YENJWEM7.js → chunk-66HELSIU.js} +3 -3
  7. package/dist/{chunk-NLHDU4CH.js → chunk-7KZOHF7R.js} +1 -1
  8. package/dist/{chunk-CH3GXKIO.js → chunk-AS3N5L25.js} +2 -2
  9. package/dist/{chunk-ZPQLJAG4.js → chunk-DPJIDICA.js} +31 -13
  10. package/dist/{chunk-LETSESYQ.js → chunk-E3J2J3PZ.js} +8 -8
  11. package/dist/{chunk-IVCJPX7J.js → chunk-HFG7TSVD.js} +4661 -3748
  12. package/dist/{chunk-XBPINLPI.js → chunk-MMODVSSS.js} +1 -1
  13. package/dist/{chunk-AZMCG2LI.js → chunk-MUFEOBRQ.js} +1 -1
  14. package/dist/{chunk-J2TAHVUS.js → chunk-O5C2CWWL.js} +5 -5
  15. package/dist/{chunk-FUHULPDT.js → chunk-Y3B7POF2.js} +631 -40
  16. package/dist/{doctor-WW54ZCQR.js → doctor-TA3AZMPJ.js} +8 -8
  17. package/dist/index.js +640 -197
  18. package/dist/{launch-FQFOZYIN.js → launch-2RINYQTU.js} +11 -11
  19. package/dist/pi-extensions/xgate.cjs +32 -1
  20. package/dist/{read-auth-B7NFDF6U.js → read-auth-FFCZKAFN.js} +3 -3
  21. package/dist/{reconcile-KHSXUVR3.js → reconcile-O6LVP2Z3.js} +4 -4
  22. package/dist/{status-IMWQR4AR.js → status-FRMTSDIG.js} +8 -8
  23. package/dist/{sync-pull-EN7CFU3J.js → sync-pull-OUXRL6A2.js} +4 -4
  24. package/dist/{task-access-grants-IBD3JFGD.js → task-access-grants-WV3HVN5V.js} +2 -2
  25. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ import {
14
14
  listWorkerSubmissions,
15
15
  submitTaskFiles,
16
16
  taskRequirementsOf
17
- } from "./chunk-LETSESYQ.js";
17
+ } from "./chunk-E3J2J3PZ.js";
18
18
  import {
19
19
  ComputeCreditError,
20
20
  applyComputeCreditSetup,
@@ -36,18 +36,21 @@ import {
36
36
  refusedPaidWrite,
37
37
  releasePendingComputePurchase,
38
38
  resolvePendingComputePurchases,
39
- x402FeePost
40
- } from "./chunk-ZPQLJAG4.js";
39
+ withPaymentProtocol,
40
+ x402FeePost,
41
+ x402PaymentProtocol
42
+ } from "./chunk-DPJIDICA.js";
41
43
  import {
42
44
  signReadAuth
43
- } from "./chunk-CH3GXKIO.js";
45
+ } from "./chunk-AS3N5L25.js";
44
46
  import {
45
47
  saveTaskAccessGrant,
46
48
  taskAccessGrantHeaders
47
- } from "./chunk-NLHDU4CH.js";
49
+ } from "./chunk-7KZOHF7R.js";
48
50
  import {
49
51
  MPP_TEMPO_DEFAULT_VALIDITY_SECONDS,
50
52
  X402PayError,
53
+ X402_PAY_PROTOCOLS,
51
54
  X402_POLICY_JSON_SCHEMA,
52
55
  addX402PolicyRule,
53
56
  getX402JournalPath,
@@ -62,7 +65,7 @@ import {
62
65
  setX402PolicyRuleEnabled,
63
66
  signSponsoredTempoTransfer,
64
67
  signTaskmarketFeePayment
65
- } from "./chunk-FUHULPDT.js";
68
+ } from "./chunk-Y3B7POF2.js";
66
69
  import {
67
70
  ALL_NETWORKS,
68
71
  ApiError,
@@ -126,7 +129,7 @@ import {
126
129
  withErrorContext,
127
130
  withIdempotentWrite,
128
131
  withTapSignature
129
- } from "./chunk-AZMCG2LI.js";
132
+ } from "./chunk-MUFEOBRQ.js";
130
133
  import {
131
134
  AGENT_AVATAR_MAX_BYTES,
132
135
  AGENT_HIRES_ROLES,
@@ -174,6 +177,9 @@ import {
174
177
  HIRE_MAX_ACCEPT_WINDOW_SECS,
175
178
  HIRE_MIN_ACCEPT_WINDOW_SECS,
176
179
  HIRE_SERVICE_ID_MAX_LENGTH,
180
+ HOOK_BIT_FEE,
181
+ HOOK_BIT_ON_CALL,
182
+ HOOK_BIT_REALLOCATE,
177
183
  HireAvailabilitySchema,
178
184
  HireKind,
179
185
  HireState,
@@ -294,6 +300,8 @@ import {
294
300
  buildAgentListingWriteMessage,
295
301
  buildDeviceRegisterMessage,
296
302
  buildForfeitMessage,
303
+ buildHookManifest,
304
+ buildHookSolidity,
297
305
  buildLegalReceiptHeaders,
298
306
  buildPitchMessage,
299
307
  buildProofMessage,
@@ -313,8 +321,10 @@ import {
313
321
  clientValidityWindowSeconds,
314
322
  compareSubmissionVersionsNewestFirst,
315
323
  composeBrief,
324
+ contractName,
316
325
  coreChains,
317
326
  dreamsToUsd,
327
+ effectiveCapabilities,
318
328
  evaluationWindowError,
319
329
  extractLiterals,
320
330
  extractTaskChecks,
@@ -331,8 +341,13 @@ import {
331
341
  hireSelectAtCapacityMessage,
332
342
  hireUnavailableAcknowledgeable,
333
343
  hireUnavailableMessage,
344
+ hookCallRoleChoices,
334
345
  hookListingSubject,
346
+ hookModes,
347
+ hookObserveChoices,
348
+ hookVetoChoices,
335
349
  humanListingChangeError,
350
+ initialHookBuilderInput,
336
351
  isCapabilitySlug,
337
352
  isInFlightApiError,
338
353
  isInitialBriefTurnMessage,
@@ -342,6 +357,7 @@ import {
342
357
  isTaskmarketChainId,
343
358
  isTerminalWalletBridgeStatus,
344
359
  listingSubmissionWriteChange,
360
+ manifestReadiness,
345
361
  marketEventPreferenceChange,
346
362
  matchesAnyGlob,
347
363
  needsYouKindForIntent,
@@ -360,6 +376,7 @@ import {
360
376
  resolveTaskTerms,
361
377
  runDataChecks,
362
378
  runPatchChecks,
379
+ selectedCallbacks,
363
380
  settlementActionExpiresAt,
364
381
  settlementActionRequiresExpiry,
365
382
  settlerModeContracts,
@@ -385,7 +402,7 @@ import {
385
402
  verifierProviderId,
386
403
  verifiersUnsupportedOnChain,
387
404
  viemChainFor
388
- } from "./chunk-IVCJPX7J.js";
405
+ } from "./chunk-HFG7TSVD.js";
389
406
  import "./chunk-S7SJMJ2I.js";
390
407
 
391
408
  // src/index.ts
@@ -482,9 +499,23 @@ function printResult(data, options) {
482
499
  })
483
500
  );
484
501
  }
502
+ var X402_FAILURE_HINTS = {
503
+ challenge_expired: "The seller's payment challenge ran out before it could be paid. Nothing was signed. Request the resource again for a fresh challenge.",
504
+ no_supported_rail: "No payment option in the 402 can be paid here. The CLI pays x402 exact and upto, and MPP tempo charge. Check --protocol and the seller's advertised methods.",
505
+ insufficient_balance: "Nothing was signed. Fund the CLI wallet (taskmarket address) with the payment token on the payment network, then request again.",
506
+ payment_header_conflict: "Nothing was signed. Remove the header the message names (set through --headers-file or --header-env); the payment credential needs it."
507
+ };
508
+ function rpcConfigurationHint(error) {
509
+ const cause = error.cause instanceof Error ? error.cause.message : void 0;
510
+ if (error.code !== "request_failed" || cause === void 0) return void 0;
511
+ if (!/^(No RPC configuration exists for|RPC environment variable )/.test(cause)) return void 0;
512
+ return `${cause}. Nothing was signed. In the x402 policy file (taskmarket x402 policy path) add "networks": { "<network>": { "rpcUrlEnv": "<ENV_VAR>" } } for the payment's network (eip155:4217 Tempo, eip155:42431 Tempo Moderato) and export that variable as an HTTPS RPC URL.`;
513
+ }
485
514
  function x402FailureFields(error) {
515
+ const hint = X402_FAILURE_HINTS[error.code] ?? rpcConfigurationHint(error);
486
516
  return {
487
517
  code: error.code,
518
+ ...hint !== void 0 ? { hint } : {},
488
519
  ...error.invocationId !== void 0 ? { invocationId: error.invocationId } : {},
489
520
  ...error.invocation !== void 0 ? {
490
521
  invocation: {
@@ -2532,6 +2563,12 @@ function numberDecoderFactory(input) {
2532
2563
  }
2533
2564
  });
2534
2565
  }
2566
+ var getI64Decoder = (config = {}) => numberDecoderFactory({
2567
+ config,
2568
+ get: (view, le) => view.getBigInt64(0, le),
2569
+ name: "i64",
2570
+ size: 8
2571
+ });
2535
2572
  var getShortU16Encoder = () => createEncoder({
2536
2573
  getSizeFromValue: (value) => {
2537
2574
  if (value <= 127) return 1;
@@ -2564,6 +2601,12 @@ var getU16Encoder = (config = {}) => numberEncoderFactory({
2564
2601
  set: (view, value, le) => view.setUint16(0, Number(value), le),
2565
2602
  size: 2
2566
2603
  });
2604
+ var getU16Decoder = (config = {}) => numberDecoderFactory({
2605
+ config,
2606
+ get: (view, le) => view.getUint16(0, le),
2607
+ name: "u16",
2608
+ size: 2
2609
+ });
2567
2610
  var getU32Encoder = (config = {}) => numberEncoderFactory({
2568
2611
  config,
2569
2612
  name: "u32",
@@ -3126,7 +3169,7 @@ function getLifetimeTokenEncoder() {
3126
3169
  noneValue: "zeroes",
3127
3170
  prefix: null
3128
3171
  }),
3129
- (token) => token ?? null
3172
+ (token2) => token2 ?? null
3130
3173
  );
3131
3174
  }
3132
3175
  function getMessageEncoder() {
@@ -3928,8 +3971,8 @@ function addRaceContender(contender) {
3928
3971
  const record = { deferreds, settled: false };
3929
3972
  Promise.resolve(contender).then(
3930
3973
  (value) => {
3931
- for (const { resolve: resolve2 } of deferreds) {
3932
- resolve2(value);
3974
+ for (const { resolve: resolve3 } of deferreds) {
3975
+ resolve3(value);
3933
3976
  }
3934
3977
  deferreds.clear();
3935
3978
  record.settled = true;
@@ -3947,11 +3990,11 @@ function addRaceContender(contender) {
3947
3990
  var wm = /* @__PURE__ */ new WeakMap();
3948
3991
  async function safeRace(contenders) {
3949
3992
  let deferred;
3950
- const result = new Promise((resolve2, reject) => {
3951
- deferred = { reject, resolve: resolve2 };
3993
+ const result = new Promise((resolve3, reject) => {
3994
+ deferred = { reject, resolve: resolve3 };
3952
3995
  for (const contender of contenders) {
3953
3996
  if (!isObject(contender)) {
3954
- Promise.resolve(contender).then(resolve2, reject);
3997
+ Promise.resolve(contender).then(resolve3, reject);
3955
3998
  continue;
3956
3999
  }
3957
4000
  let record = wm.get(contender);
@@ -3960,7 +4003,7 @@ async function safeRace(contenders) {
3960
4003
  record.deferreds.add(deferred);
3961
4004
  wm.set(contender, record);
3962
4005
  } else if (record.settled) {
3963
- Promise.resolve(contender).then(resolve2, reject);
4006
+ Promise.resolve(contender).then(resolve3, reject);
3964
4007
  } else {
3965
4008
  record.deferreds.add(deferred);
3966
4009
  }
@@ -5298,14 +5341,14 @@ function createSolanaJsonRpcIntegerOverflowError(methodName, keyPath, value) {
5298
5341
  } else {
5299
5342
  argumentLabel = `\`${keyPath[0].toString()}\``;
5300
5343
  }
5301
- const path9 = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : void 0;
5344
+ const path10 = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : void 0;
5302
5345
  const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {
5303
5346
  argumentLabel,
5304
5347
  keyPath,
5305
5348
  methodName,
5306
- optionalPathLabel: path9 ? ` at path \`${path9}\`` : "",
5349
+ optionalPathLabel: path10 ? ` at path \`${path10}\`` : "",
5307
5350
  value,
5308
- ...path9 !== void 0 ? { path: path9 } : void 0
5351
+ ...path10 !== void 0 ? { path: path10 } : void 0
5309
5352
  });
5310
5353
  safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError);
5311
5354
  return error;
@@ -5366,7 +5409,7 @@ function getRpcTransportWithRequestCoalescing(transport, getDeduplicationKey) {
5366
5409
  coalescedRequest.numConsumers++;
5367
5410
  if (signal) {
5368
5411
  const responsePromise = coalescedRequest.responsePromise;
5369
- return await new Promise((resolve2, reject) => {
5412
+ return await new Promise((resolve3, reject) => {
5370
5413
  const handleAbort = () => {
5371
5414
  signal.removeEventListener("abort", handleAbort);
5372
5415
  coalescedRequest.numConsumers -= 1;
@@ -5379,7 +5422,7 @@ function getRpcTransportWithRequestCoalescing(transport, getDeduplicationKey) {
5379
5422
  reject(signal.reason);
5380
5423
  };
5381
5424
  signal.addEventListener("abort", handleAbort);
5382
- responsePromise.then(resolve2).catch(reject).finally(() => {
5425
+ responsePromise.then(resolve3).catch(reject).finally(() => {
5383
5426
  signal.removeEventListener("abort", handleAbort);
5384
5427
  });
5385
5428
  });
@@ -7488,11 +7531,11 @@ async function tryRegisterEmail(deviceId, apiToken, warnings) {
7488
7531
  function terminalIo() {
7489
7532
  return {
7490
7533
  interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY),
7491
- ask: (question) => new Promise((resolve2) => {
7534
+ ask: (question) => new Promise((resolve3) => {
7492
7535
  const rl = createInterface2({ input: process.stdin, output: process.stderr });
7493
7536
  rl.question(question, (answer) => {
7494
7537
  rl.close();
7495
- resolve2(answer);
7538
+ resolve3(answer);
7496
7539
  });
7497
7540
  })
7498
7541
  };
@@ -7937,7 +7980,7 @@ async function approveSponsoredTaskSpend(input) {
7937
7980
  `Approval confirmed but the RPC endpoint still reports an allowance of ${allowance}; retry once the endpoint catches up`
7938
7981
  );
7939
7982
  }
7940
- await new Promise((resolve2) => setTimeout(resolve2, pollIntervalMs));
7983
+ await new Promise((resolve3) => setTimeout(resolve3, pollIntervalMs));
7941
7984
  }
7942
7985
  }
7943
7986
 
@@ -8459,7 +8502,7 @@ var taskPath = (taskId) => `/api/tasks/${encodeURIComponent(taskId)}`;
8459
8502
  var runPath = (runId) => `/api/submission-reviews/${encodeURIComponent(runId)}`;
8460
8503
  function createSubmissionReviewClient(options) {
8461
8504
  const now = options.now ?? Date.now;
8462
- const sleep4 = options.sleep ?? ((ms2) => new Promise((resolve2) => setTimeout(resolve2, ms2)));
8505
+ const sleep4 = options.sleep ?? ((ms2) => new Promise((resolve3) => setTimeout(resolve3, ms2)));
8463
8506
  let headersPromise;
8464
8507
  const headers = () => headersPromise ??= (async () => {
8465
8508
  const signer = await options.signer();
@@ -8470,10 +8513,10 @@ function createSubmissionReviewClient(options) {
8470
8513
  )
8471
8514
  };
8472
8515
  })();
8473
- async function get(path9, schema) {
8474
- return schema.parse(await options.transport.get(path9, await headers()));
8516
+ async function get(path10, schema) {
8517
+ return schema.parse(await options.transport.get(path10, await headers()));
8475
8518
  }
8476
- async function write(action, payload, chainId, path9, schema, key) {
8519
+ async function write(action, payload, chainId, path10, schema, key) {
8477
8520
  const idempotencyKey = z.string().uuid().parse(resolveIdempotencyKey(key)).toLowerCase();
8478
8521
  return withIdempotentWrite(idempotencyKey, async () => {
8479
8522
  const signer = await options.signer();
@@ -8497,7 +8540,7 @@ function createSubmissionReviewClient(options) {
8497
8540
  signature,
8498
8541
  ...["pause", "cancel", "delete"].includes(action) ? { action } : {}
8499
8542
  };
8500
- const result = await options.transport.post(path9, body, idempotencyKey);
8543
+ const result = await options.transport.post(path10, body, idempotencyKey);
8501
8544
  if (result.idempotencyKey !== idempotencyKey)
8502
8545
  throw new Error(
8503
8546
  "Review response has a different request key; recover the original request before retrying."
@@ -8710,9 +8753,9 @@ function cliSubmissionReviewClient() {
8710
8753
  };
8711
8754
  },
8712
8755
  transport: {
8713
- get: (path9, headers) => apiGet(path9, { headers }),
8714
- preview: (path9, body, headers) => apiReadPost(path9, body, { headers }),
8715
- post: (path9, body, idempotencyKey, headers) => apiPost(path9, body, { idempotencyKey, headers })
8756
+ get: (path10, headers) => apiGet(path10, { headers }),
8757
+ preview: (path10, body, headers) => apiReadPost(path10, body, { headers }),
8758
+ post: (path10, body, idempotencyKey, headers) => apiPost(path10, body, { idempotencyKey, headers })
8716
8759
  }
8717
8760
  });
8718
8761
  }
@@ -8995,13 +9038,13 @@ function retryAfterMs(res) {
8995
9038
  const wait = Number.isFinite(seconds) && seconds >= 0 ? seconds : DEFAULT_RETRY_AFTER_SECONDS;
8996
9039
  return Math.min(wait, MAX_RETRY_AFTER_SECONDS) * 1e3;
8997
9040
  }
8998
- async function x402Post(path9, body, options) {
8999
- const sleep4 = options?.sleep ?? ((ms2) => new Promise((resolve2) => setTimeout(resolve2, ms2)));
9041
+ async function x402Post(path10, body, options) {
9042
+ const sleep4 = options?.sleep ?? ((ms2) => new Promise((resolve3) => setTimeout(resolve3, ms2)));
9000
9043
  if (paymentProtocolOf(selectedNetwork().chainId) === "mpp")
9001
- return mppPost(path9, body, options);
9044
+ return mppPost(path10, body, options);
9002
9045
  const keystore = await loadKeystore();
9003
9046
  const idempotencyKey = resolveIdempotencyKey(options?.idempotencyKey);
9004
- const request = paidWriteRequest(keystore, path9, body, idempotencyKey);
9047
+ const request = paidWriteRequest(keystore, path10, body, idempotencyKey);
9005
9048
  Object.assign(request.headers, options?.headers ?? {});
9006
9049
  return withIdempotentWrite(idempotencyKey, async () => {
9007
9050
  const r1 = await fetch(request.url, {
@@ -9018,7 +9061,7 @@ async function x402Post(path9, body, options) {
9018
9061
  if (r1.ok) {
9019
9062
  return { data: await r1.json(), idempotencyKey };
9020
9063
  }
9021
- throw refusedPaidWrite(path9, r1.status, await readFailureBody(r1), idempotencyKey);
9064
+ throw refusedPaidWrite(path10, r1.status, await readFailureBody(r1), idempotencyKey);
9022
9065
  }
9023
9066
  const requirements = await r1.json();
9024
9067
  const chain = taskmarketChain(selectedNetwork().chainId);
@@ -9055,7 +9098,7 @@ async function x402Post(path9, body, options) {
9055
9098
  await sleep4(retryAfterMs(r2));
9056
9099
  continue;
9057
9100
  }
9058
- throw failedAfterPayment(path9, r2.status, read4, idempotencyKey);
9101
+ throw failedAfterPayment(path10, r2.status, read4, idempotencyKey);
9059
9102
  }
9060
9103
  });
9061
9104
  }
@@ -9132,7 +9175,7 @@ function parseRequirementFilter(value, schema, flag) {
9132
9175
  return { value: trimmed };
9133
9176
  }
9134
9177
  function tapSimulatedMessage(chainId) {
9135
- return `TAP on chain ${chainId} is simulated: a TAP check there proves only that the worker holds a key it enrolled with Taskmarket, not that the verifier knows it. Passed checks are recorded as tap-simulated, and a tap:identity:known requirement there behaves as tap:identity:verified: the simulated directory enrols only verified keys.`;
9178
+ return `TAP on chain ${chainId} is simulated: a TAP check there proves only that the worker holds a key it enrolled with Taskmarket, not that the verifier knows it. Passed checks are recorded as tap-simulated. Every simulated key is a known agent, so use tap:identity:known there: a tap:identity:verified requirement is never met.`;
9136
9179
  }
9137
9180
  async function tapSimulatedWarnings(verifiedBy, chainId) {
9138
9181
  if (chainId === void 0 || !verifiedBy?.some((id) => verifierProviderId(id) === "tap"))
@@ -9439,7 +9482,7 @@ function taskGateCandidates(task) {
9439
9482
  // src/lib/recording.ts
9440
9483
  var RECORDING_POLL_INTERVAL_MS = 3e3;
9441
9484
  var RECORDING_POLL_TIMEOUT_MS = 75e3;
9442
- var sleepFor = (ms2) => new Promise((resolve2) => setTimeout(resolve2, ms2));
9485
+ var sleepFor = (ms2) => new Promise((resolve3) => setTimeout(resolve3, ms2));
9443
9486
  async function settleRecording(data, idempotencyKey, options = {}) {
9444
9487
  if (!isRecordingPendingResponse(data)) return {};
9445
9488
  const { txHash, intentId } = data;
@@ -9453,13 +9496,13 @@ async function settleRecording(data, idempotencyKey, options = {}) {
9453
9496
  `Transaction ${txHash ?? "(unknown)"} is confirmed on chain; recording it is pending. Waiting up to ${Math.round(timeoutMs / 1e3)}s for the backend to record it...`
9454
9497
  );
9455
9498
  const headers = (await signReadAuth())?.headers ?? {};
9456
- const path9 = `/api/intents?idempotencyKey=${encodeURIComponent(idempotencyKey)}`;
9499
+ const path10 = `/api/intents?idempotencyKey=${encodeURIComponent(idempotencyKey)}`;
9457
9500
  const deadline = now() + timeoutMs;
9458
9501
  while (now() < deadline) {
9459
9502
  await sleep4(intervalMs);
9460
9503
  let intent;
9461
9504
  try {
9462
- intent = IntentStatusResponseSchema.safeParse(await apiGet(path9, { headers }));
9505
+ intent = IntentStatusResponseSchema.safeParse(await apiGet(path10, { headers }));
9463
9506
  } catch {
9464
9507
  continue;
9465
9508
  }
@@ -10088,7 +10131,7 @@ var createCmd = new Command11("create").description("Create a new task (costs th
10088
10131
  "Only workers with one of these identities may claim, pitch, bid, submit proofs or submit work (comma-separated; any one is enough): erc8004:identity:registered, erc8004:reputation:reputable"
10089
10132
  ).option(
10090
10133
  "--require-verified <verifiers>",
10091
- "Only workers one of these verifiers passes may work on the task (comma-separated; any one is enough): tap:identity:verified (verified agents) or tap:identity:known (known or verified agents). With --require-identity too, both must be met."
10134
+ "Only workers one of these verifiers passes may work on the task (comma-separated; any one is enough): tap:identity:known (any agent registered with TAP; the level to use) or tap:identity:verified (agents the verifier reviewed by hand; the verifier does not use this level yet). With --require-identity too, both must be met."
10092
10135
  ).option("--tags <tags>", "Comma-separated tags").option(
10093
10136
  "--capabilities <slugs>",
10094
10137
  "Comma-separated capability slugs the task needs, from `taskmarket capabilities` (active entries only; capped like a listing)"
@@ -10645,7 +10688,15 @@ async function runCreateTask(input, extra = {}) {
10645
10688
  stakeRequired: stake.stakeRequired,
10646
10689
  stakeBps: stake.stakeBps,
10647
10690
  tags: opts.tags ? opts.tags.split(",").map((t) => t.trim()) : [],
10648
- hookContracts: hooks,
10691
+ // The requester's own hooks only. The server attaches the payout gate after them and
10692
+ // before the sponsored hook, and the funding hash lists the hooks in that order.
10693
+ hookContracts: hooks.filter((hook) => !gateHook || hook.toLowerCase() !== gateHook),
10694
+ ...gatesTasks.length > 0 ? { payoutGate: { gatesTaskIds: gatesTasks } } : payoutGate ? {
10695
+ payoutGate: {
10696
+ ...payoutGate.gatingTaskId ? { gatingTaskId: payoutGate.gatingTaskId } : {},
10697
+ deadline: payoutGate.deadline
10698
+ }
10699
+ } : {},
10649
10700
  evaluator: opts.evaluator,
10650
10701
  evaluatorFeeBps: opts.evaluatorFeeBps ? Number(opts.evaluatorFeeBps) : void 0,
10651
10702
  evaluationWindowHours: opts.evaluationWindow ? Number(opts.evaluationWindow) : void 0,
@@ -10854,7 +10905,7 @@ var listCmd = new Command12("list").alias("search").description("List available
10854
10905
  "Only tasks that require this worker identity: erc8004:identity:registered or erc8004:reputation:reputable"
10855
10906
  ).option(
10856
10907
  "--verified-by <verifier>",
10857
- "Only tasks that require this verifier: tap:identity:verified or tap:identity:known"
10908
+ "Only tasks that require this verifier: tap:identity:known or tap:identity:verified"
10858
10909
  ).option("--limit <n>", "Maximum results to return", "20").option(
10859
10910
  "--cursor <cursor>",
10860
10911
  "Cursor from previous page (nextCursor in JSON output); pass it with the same --sort and filters"
@@ -11223,9 +11274,9 @@ function runCliChecks(spec, engineResults, target, options) {
11223
11274
  }
11224
11275
  return engineResults.map((r) => byId.get(r.id) ?? r);
11225
11276
  }
11226
- function isDirectory(path9) {
11277
+ function isDirectory(path10) {
11227
11278
  try {
11228
- return statSync(path9).isDirectory();
11279
+ return statSync(path10).isDirectory();
11229
11280
  } catch {
11230
11281
  return false;
11231
11282
  }
@@ -11292,11 +11343,11 @@ function deliverablePatch(files, patch) {
11292
11343
  return patch ?? taskCheckedPatch(files);
11293
11344
  }
11294
11345
  function runTaskChecks(spec, input) {
11295
- const read4 = (path9, encoding) => {
11346
+ const read4 = (path10, encoding) => {
11296
11347
  try {
11297
- return encoding ? readFileSync(path9, encoding) : readFileSync(path9);
11348
+ return encoding ? readFileSync(path10, encoding) : readFileSync(path10);
11298
11349
  } catch (error) {
11299
- throw new Error(`Cannot read ${path9}: ${error.message}`);
11350
+ throw new Error(`Cannot read ${path10}: ${error.message}`);
11300
11351
  }
11301
11352
  };
11302
11353
  const results = [];
@@ -11387,6 +11438,59 @@ async function confirmTaskOnSelectedNetwork(taskId, task) {
11387
11438
  return false;
11388
11439
  }
11389
11440
 
11441
+ // src/lib/worker-visibility.ts
11442
+ var APPEAL_REASON_TEXT = {
11443
+ no_evaluator: "the task has no evaluator",
11444
+ no_dispute_resolver: "the task names no dispute resolver",
11445
+ hook_can_veto_appeal: "a hook on the task can refuse an appeal",
11446
+ hook_powers_unknown: "a hook on the task has powers that are not known yet, so it may refuse an appeal"
11447
+ };
11448
+ function workerVisibilityWarnings(task) {
11449
+ const visibility = task?.workerVisibility;
11450
+ if (!visibility) return [];
11451
+ const warnings = [];
11452
+ const reducing = visibility.hooks.filter((hook) => hook.transforming === true);
11453
+ if (visibility.payoutCanBeReduced) {
11454
+ warnings.push(
11455
+ cliWarning(
11456
+ "payout_can_be_reduced",
11457
+ `A hook on this task can reduce your payout below what the evaluator or requester approves (${reducing.map((hook) => hook.name ?? hook.address).join(", ")}). ` + (visibility.appealPossible ? "You can appeal a verdict to the dispute resolver." : "You cannot appeal a reduction on this task.") + " Run `taskmarket task get` for each hook's powers.",
11458
+ {
11459
+ hooks: reducing.map((hook) => ({
11460
+ address: hook.address,
11461
+ name: hook.name,
11462
+ canReducePayout: hook.canReducePayout,
11463
+ canTakeFee: hook.canTakeFee
11464
+ })),
11465
+ appealPossible: visibility.appealPossible
11466
+ }
11467
+ )
11468
+ );
11469
+ }
11470
+ if (task?.evaluator && !visibility.appealPossible && visibility.appealUnavailableReason) {
11471
+ warnings.push(
11472
+ cliWarning(
11473
+ "appeal_unavailable",
11474
+ `You cannot appeal the evaluator's verdict: ${APPEAL_REASON_TEXT[visibility.appealUnavailableReason]}.`,
11475
+ { reason: visibility.appealUnavailableReason }
11476
+ )
11477
+ );
11478
+ }
11479
+ return warnings;
11480
+ }
11481
+ async function workerVisibilityWarningsFor(taskId, task) {
11482
+ if (task !== void 0) return workerVisibilityWarnings(task);
11483
+ try {
11484
+ return workerVisibilityWarnings(await getTask(cliTaskReadContext(), { taskId }));
11485
+ } catch {
11486
+ return [];
11487
+ }
11488
+ }
11489
+ async function workerVisibilityWarningOptions(taskId, task) {
11490
+ const warnings = await workerVisibilityWarningsFor(taskId, task);
11491
+ return warnings.length > 0 ? { warnings } : {};
11492
+ }
11493
+
11390
11494
  // src/commands/task/submit.ts
11391
11495
  function checksSummary(run2) {
11392
11496
  return { passed: run2.passed, failed: run2.failed, skipped: run2.skipped, warnings: run2.warnings };
@@ -11414,8 +11518,10 @@ var submitCmd = new Command14("submit").description("Submit work for a task").ar
11414
11518
  return;
11415
11519
  }
11416
11520
  let checks = null;
11521
+ let readTask = null;
11417
11522
  if (!opts.skipChecks) {
11418
11523
  const task = await getTask(cliTaskReadContext(), { taskId });
11524
+ readTask = task;
11419
11525
  if (!task) {
11420
11526
  printError(
11421
11527
  `Task not found: ${taskId} (or this is a private task you don't have access to)`
@@ -11474,7 +11580,7 @@ var submitCmd = new Command14("submit").description("Submit work for a task").ar
11474
11580
  const { submissionId, idempotencyKey } = await submitTaskFiles(
11475
11581
  cliTaskWriteContext(keystore),
11476
11582
  { taskId },
11477
- opts.file.map((path9) => ({ path: path9, role: opts.role })),
11583
+ opts.file.map((path10) => ({ path: path10, role: opts.role })),
11478
11584
  { idempotencyKey: submissionKey }
11479
11585
  );
11480
11586
  printResult(
@@ -11482,7 +11588,7 @@ var submitCmd = new Command14("submit").description("Submit work for a task").ar
11482
11588
  submissionId,
11483
11589
  ...opts.skipChecks ? { checks: { skipped: true } } : checks ? { checks: checksSummary(checks) } : {}
11484
11590
  },
11485
- { idempotencyKey }
11591
+ { idempotencyKey, ...await workerVisibilityWarningOptions(taskId, readTask) }
11486
11592
  );
11487
11593
  } finally {
11488
11594
  submitCmd.setOptionValue("file", []);
@@ -11926,7 +12032,7 @@ var claimCmd = new Command20("claim").description("Claim a task as a worker").ar
11926
12032
  const { claimId, idempotencyKey } = await claimTask(cliTaskWriteContext(keystore), { taskId });
11927
12033
  printResult(
11928
12034
  { claimId, ...stake > 0n ? { stake: stake.toString() } : {} },
11929
- { idempotencyKey }
12035
+ { idempotencyKey, ...await workerVisibilityWarningOptions(taskId, task) }
11930
12036
  );
11931
12037
  });
11932
12038
 
@@ -11957,7 +12063,10 @@ var pitchCmd = new Command21("pitch").description("Submit a pitch for a task (co
11957
12063
  { maxAmount: ACTION_FEE_MAX_AMOUNT, ...tap ? { tap } : {} }
11958
12064
  )
11959
12065
  );
11960
- printResult({ pitchId: result.pitchId }, { idempotencyKey });
12066
+ printResult(
12067
+ { pitchId: result.pitchId },
12068
+ { idempotencyKey, ...await workerVisibilityWarningOptions(taskId) }
12069
+ );
11961
12070
  }
11962
12071
  );
11963
12072
 
@@ -12062,21 +12171,24 @@ var bidCmd = new Command26("bid").description("Submit a bid on an auction task")
12062
12171
  }
12063
12172
  if (!await confirmUnverifiedHooks("bid", taskId, opts.acceptUnverifiedHooks)) return;
12064
12173
  if (!await confirmStakeTerms("bid", taskId, opts.yes)) return;
12065
- const path9 = `/api/tasks/${taskId}/bids`;
12174
+ const path10 = `/api/tasks/${taskId}/bids`;
12066
12175
  const body = { taskId, price: priceBaseUnits };
12067
12176
  const task = await taskRequirementsOf(taskId);
12068
12177
  const gated = (task?.identity?.length ?? 0) > 0 || taskRequiresTap(task);
12069
12178
  const { data: result, idempotencyKey } = gated ? await attestedWorkerAction(
12070
12179
  taskId,
12071
12180
  await loadKeystore(),
12072
- async (tap) => x402Post(path9, body, {
12181
+ async (tap) => x402Post(path10, body, {
12073
12182
  maxAmount: ACTION_FEE_MAX_AMOUNT,
12074
12183
  headers: (await signReadAuth())?.headers ?? {},
12075
12184
  ...tap ? { tap } : {}
12076
12185
  }),
12077
12186
  task
12078
- ) : await x402Post(path9, body, { maxAmount: ACTION_FEE_MAX_AMOUNT });
12079
- printResult({ bidId: result.bidId }, { idempotencyKey });
12187
+ ) : await x402Post(path10, body, { maxAmount: ACTION_FEE_MAX_AMOUNT });
12188
+ printResult(
12189
+ { bidId: result.bidId },
12190
+ { idempotencyKey, ...await workerVisibilityWarningOptions(taskId) }
12191
+ );
12080
12192
  }
12081
12193
  );
12082
12194
 
@@ -12095,19 +12207,19 @@ var auctionAcceptCmd = new Command27("auction-accept").description("Accept curre
12095
12207
  return;
12096
12208
  }
12097
12209
  }
12098
- const path9 = `/api/tasks/${taskId}/bids/accept`;
12210
+ const path10 = `/api/tasks/${taskId}/bids/accept`;
12099
12211
  const task = await taskRequirementsOf(taskId);
12100
12212
  const gated = (task?.identity?.length ?? 0) > 0 || taskRequiresTap(task);
12101
12213
  const { data: result, idempotencyKey } = gated ? await attestedWorkerAction(
12102
12214
  taskId,
12103
12215
  await loadKeystore(),
12104
- async (tap) => x402Post(path9, body, {
12216
+ async (tap) => x402Post(path10, body, {
12105
12217
  maxAmount: ACTION_FEE_MAX_AMOUNT,
12106
12218
  headers: (await signReadAuth())?.headers ?? {},
12107
12219
  ...tap ? { tap } : {}
12108
12220
  }),
12109
12221
  task
12110
- ) : await x402Post(path9, body, { maxAmount: ACTION_FEE_MAX_AMOUNT });
12222
+ ) : await x402Post(path10, body, { maxAmount: ACTION_FEE_MAX_AMOUNT });
12111
12223
  const { chainId } = selectedNetwork();
12112
12224
  printResult(
12113
12225
  {
@@ -12134,7 +12246,7 @@ var SubmissionPageSchema = TaskChildListSchema.pick({ cursor: true }).extend({
12134
12246
  });
12135
12247
  var submissionsCmd = new Command28("submissions").description("List submissions for a task").argument("<taskId>", "Task ID (0x-prefixed hex)").option(
12136
12248
  "--passed-check <provider>",
12137
- "Only submissions whose worker passed this check when submitting: erc8004:identity:registered, erc8004:reputation:reputable, tap:identity:verified or tap:identity:known"
12249
+ "Only submissions whose worker passed this check when submitting: erc8004:identity:registered, erc8004:reputation:reputable, tap:identity:known or tap:identity:verified"
12138
12250
  ).option("--limit <n>", "Page size (1-500); without it every submission is listed").option("--cursor <id>", "Last returned id; read the following page").option("--ids <ids>", "Only these submissions: comma-separated ids (at most 50)").action(
12139
12251
  async (taskId, opts) => {
12140
12252
  const passedCheck = parseRequirementFilter(opts.passedCheck, CHECK_FILTER, "--passed-check");
@@ -12571,7 +12683,7 @@ var updateCmd = new Command40("update").description(
12571
12683
  "Replace the identity requirement (comma-separated, any one is enough: erc8004:identity:registered, erc8004:reputation:reputable; none clears it). Refused once a worker has committed."
12572
12684
  ).option(
12573
12685
  "--require-verified <verifiers>",
12574
- "Replace the verifier requirement (comma-separated, any one is enough: tap:identity:verified, tap:identity:known; none clears it). tap:identity:known also accepts known agents; tap:identity:verified needs verified ones. Refused once a worker has committed."
12686
+ "Replace the verifier requirement (comma-separated, any one is enough: tap:identity:known, tap:identity:verified; none clears it). tap:identity:known accepts any agent registered with TAP; tap:identity:verified needs one the verifier reviewed by hand, a level it does not use yet. Refused once a worker has committed."
12575
12687
  ).action(
12576
12688
  async (taskId, opts) => {
12577
12689
  const body = { taskId };
@@ -12900,7 +13012,9 @@ var appealCmd = new Command44("appeal").description("Appeal an evaluator verdict
12900
13012
 
12901
13013
  // src/commands/task/evaluator-timeout.ts
12902
13014
  import { Command as Command45 } from "commander";
12903
- var evaluatorTimeoutCmd = new Command45("evaluator-timeout").description("Trigger evaluator timeout after the evaluation window expires (anyone)").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
13015
+ var evaluatorTimeoutCmd = new Command45("evaluator-timeout").description(
13016
+ "Trigger evaluator timeout after the evaluation window expires (anyone); also bounty and benchmark tasks with an evaluator and a live submission"
13017
+ ).argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
12904
13018
  const { data: result, idempotencyKey } = await x402Post(`/api/tasks/${taskId}/evaluator-timeout`, { taskId }, { maxAmount: ACTION_FEE_MAX_AMOUNT });
12905
13019
  printResult(
12906
13020
  { txHash: result.txHash, ...await settleRecording(result, idempotencyKey) },
@@ -13115,11 +13229,11 @@ function isCommitment(value) {
13115
13229
  }
13116
13230
 
13117
13231
  // src/commands/task/checks.ts
13118
- function readBytes(path9) {
13232
+ function readBytes(path10) {
13119
13233
  try {
13120
- return readFileSync2(path9);
13234
+ return readFileSync2(path10);
13121
13235
  } catch (error) {
13122
- return `Cannot read ${path9}: ${error.message}`;
13236
+ return `Cannot read ${path10}: ${error.message}`;
13123
13237
  }
13124
13238
  }
13125
13239
  var commitCmd = new Command54("commit").description(
@@ -13243,7 +13357,7 @@ async function confirmAtTerminal(lines, unattended) {
13243
13357
  `);
13244
13358
  const readline = createInterface3({ input: process.stdin, output: process.stderr });
13245
13359
  const answer = await new Promise(
13246
- (resolve2) => readline.question("Type yes to approve: ", resolve2)
13360
+ (resolve3) => readline.question("Type yes to approve: ", resolve3)
13247
13361
  );
13248
13362
  readline.close();
13249
13363
  return answer.trim().toLowerCase() === "yes";
@@ -13433,7 +13547,7 @@ async function runAgentCommand(options) {
13433
13547
  try {
13434
13548
  const { assertAgentCompatibility } = await import("./compatibility-636WJOEX.js");
13435
13549
  const pi = assertAgentCompatibility();
13436
- const { runAgent } = await import("./launch-FQFOZYIN.js");
13550
+ const { runAgent } = await import("./launch-2RINYQTU.js");
13437
13551
  result = await runAgent({
13438
13552
  model: options.model,
13439
13553
  pi,
@@ -13867,13 +13981,13 @@ function agentManagementCommands() {
13867
13981
  const status = new Command58("status").description(
13868
13982
  "Show the agent channels (locked, charged, refundable), purchases with an unknown outcome, the sandbox and compute credit. Reads only."
13869
13983
  ).action(async () => {
13870
- const { collectAgentStatus } = await import("./status-IMWQR4AR.js");
13984
+ const { collectAgentStatus } = await import("./status-FRMTSDIG.js");
13871
13985
  await run(() => collectAgentStatus());
13872
13986
  });
13873
13987
  const doctor = new Command58("doctor").description(
13874
13988
  "Check that the agent can start: Node and the bundled runtime, wallet and policy, channels, API, sandbox broker, host keys, xgate and RPC. Reads only."
13875
13989
  ).action(async () => {
13876
- const { runDoctor } = await import("./doctor-WW54ZCQR.js");
13990
+ const { runDoctor } = await import("./doctor-TA3AZMPJ.js");
13877
13991
  const report = await run(() => runDoctor());
13878
13992
  if (report && !report.ok) process.exitCode = 1;
13879
13993
  });
@@ -13884,7 +13998,7 @@ function agentManagementCommands() {
13884
13998
  "Reconcile the open purchases of this channel, as status lists it; also reaches retired channels"
13885
13999
  ).action(
13886
14000
  async (invocationId, options) => {
13887
- const { reconcileChannelPurchases, reconcileInvocation } = await import("./reconcile-KHSXUVR3.js");
14001
+ const { reconcileChannelPurchases, reconcileInvocation } = await import("./reconcile-O6LVP2Z3.js");
13888
14002
  const choice = { rail: options.rail, channel: options.channel };
13889
14003
  if (invocationId !== void 0) {
13890
14004
  await run(() => reconcileInvocation(invocationId, { choice }));
@@ -13916,7 +14030,7 @@ function agentManagementCommands() {
13916
14030
  `Not a USDC amount: ${options.amount} (digits, at most 6 decimals)`
13917
14031
  );
13918
14032
  }
13919
- const { openAgentChannels, requestTopUp, selectRail, withdrawalHatch } = await import("./channels-AH2WHLMC.js");
14033
+ const { openAgentChannels, requestTopUp, selectRail, withdrawalHatch } = await import("./channels-YKCZU2Q7.js");
13920
14034
  const { rails } = await openAgentChannels();
13921
14035
  const result = await requestTopUp(selectRail(rails, options.rail), amount);
13922
14036
  return {
@@ -13936,8 +14050,8 @@ function agentManagementCommands() {
13936
14050
  await run(async () => {
13937
14051
  await requireExperimental();
13938
14052
  const { AGENT_VIEW_VERSION } = await import("./budget-view-J6L7X6EY.js");
13939
- const { closeChannel, openAgentChannels, selectChannel } = await import("./channels-AH2WHLMC.js");
13940
- const { reconcileLeasedPurchase } = await import("./reconcile-KHSXUVR3.js");
14053
+ const { closeChannel, openAgentChannels, selectChannel } = await import("./channels-YKCZU2Q7.js");
14054
+ const { reconcileLeasedPurchase } = await import("./reconcile-O6LVP2Z3.js");
13941
14055
  const opened = await openAgentChannels();
13942
14056
  const { rail, retired } = selectChannel(opened, options);
13943
14057
  const result = await closeChannel(
@@ -13991,7 +14105,7 @@ function agentManagementCommands() {
13991
14105
  async (options) => {
13992
14106
  await run(async () => {
13993
14107
  await requireExperimental();
13994
- const { runPull } = await import("./sync-pull-EN7CFU3J.js");
14108
+ const { runPull } = await import("./sync-pull-OUXRL6A2.js");
13995
14109
  const { terminalPrompter } = await import("./prompter-LSICEYSQ.js");
13996
14110
  return runPull(options, {
13997
14111
  interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
@@ -14071,7 +14185,7 @@ var agentsCommand = new Command60("agents").description("Browse the worker direc
14071
14185
  "Filter by actor kind: agent, human (the web directory filtered to humans) or hosted"
14072
14186
  ).option(
14073
14187
  "--verified-by <verifier>",
14074
- "Only agents this verifier passed within the last 30 days: tap:identity:verified or tap:identity:known (also matches known agents)"
14188
+ "Only agents this verifier passed within the last 30 days: tap:identity:known (any agent registered with TAP) or tap:identity:verified (reviewed by hand; not yet used by the verifier)"
14075
14189
  ).option(
14076
14190
  "--availability <availability>",
14077
14191
  "available (open and under capacity), unavailable (paused or fully booked) or any",
@@ -15013,7 +15127,7 @@ function normalizePrivateKey(raw) {
15013
15127
  return `0x${hex3}`;
15014
15128
  }
15015
15129
  function promptHiddenInput(prompt) {
15016
- return new Promise((resolve2) => {
15130
+ return new Promise((resolve3) => {
15017
15131
  const rl = createInterface4({
15018
15132
  input: process.stdin,
15019
15133
  output: process.stderr,
@@ -15033,7 +15147,7 @@ function promptHiddenInput(prompt) {
15033
15147
  muted.muted = false;
15034
15148
  process.stderr.write("\n");
15035
15149
  rl.close();
15036
- resolve2(answer);
15150
+ resolve3(answer);
15037
15151
  });
15038
15152
  });
15039
15153
  }
@@ -15637,7 +15751,7 @@ function progress(message) {
15637
15751
  `);
15638
15752
  }
15639
15753
  function sleep(ms2) {
15640
- return new Promise((resolve2) => setTimeout(resolve2, ms2));
15754
+ return new Promise((resolve3) => setTimeout(resolve3, ms2));
15641
15755
  }
15642
15756
  function sameAddress2(a, b) {
15643
15757
  return a.toLowerCase() === b.toLowerCase();
@@ -15873,7 +15987,7 @@ async function waitForSolanaSignature(rpc, signature, { timeoutMs = CONFIRM_TIME
15873
15987
  if (status?.confirmationStatus === "confirmed" || status?.confirmationStatus === "finalized")
15874
15988
  return true;
15875
15989
  if (Date.now() >= deadline) return false;
15876
- await new Promise((resolve2) => setTimeout(resolve2, pollMs));
15990
+ await new Promise((resolve3) => setTimeout(resolve3, pollMs));
15877
15991
  }
15878
15992
  }
15879
15993
  async function relaySolanaInstructions(input) {
@@ -15943,13 +16057,13 @@ async function withdrawOnSolana(amount, opts) {
15943
16057
  var RECEIVE_POLICY_BLOCKED = "recipient_receive_policy_blocked";
15944
16058
  async function withdrawOnTempo(input) {
15945
16059
  const { keystore, chainId, withdrawalAddress, amountBaseUnits } = input;
15946
- const token = taskmarketChain(chainId).payment.token;
15947
- if (!token) throw new Error(`Chain ${chainId} has no known payment token`);
16060
+ const token2 = taskmarketChain(chainId).payment.token;
16061
+ if (!token2) throw new Error(`Chain ${chainId} has no known payment token`);
15948
16062
  const account = await createWalletAccountFromKeystore(keystore);
15949
16063
  const transaction = await signSponsoredTempoTransfer({
15950
16064
  signer: { address: account.address, sign: (args) => account.sign(args) },
15951
16065
  chainId,
15952
- token,
16066
+ token: token2,
15953
16067
  to: withdrawalAddress,
15954
16068
  amount: BigInt(amountBaseUnits),
15955
16069
  validBefore: Math.floor(Date.now() / 1e3) + clientValidityWindowSeconds(chainId, MPP_TEMPO_DEFAULT_VALIDITY_SECONDS),
@@ -16213,12 +16327,12 @@ function decodeEnvelope(raw) {
16213
16327
  var XmtpQueryManager = class {
16214
16328
  pending = /* @__PURE__ */ new Map();
16215
16329
  waitForResponse(requestId, timeoutMs) {
16216
- return new Promise((resolve2, reject) => {
16330
+ return new Promise((resolve3, reject) => {
16217
16331
  const timeout = setTimeout(() => {
16218
16332
  this.pending.delete(requestId);
16219
16333
  reject(new Error(`XMTP query timed out after ${timeoutMs}ms`));
16220
16334
  }, timeoutMs);
16221
- this.pending.set(requestId, { resolve: resolve2, reject, timeout });
16335
+ this.pending.set(requestId, { resolve: resolve3, reject, timeout });
16222
16336
  });
16223
16337
  }
16224
16338
  resolveResponse(envelope) {
@@ -16484,7 +16598,7 @@ function shouldHandleEnvelope(envelope, options) {
16484
16598
  return true;
16485
16599
  }
16486
16600
  function sleep2(ms2) {
16487
- return new Promise((resolve2) => setTimeout(resolve2, ms2));
16601
+ return new Promise((resolve3) => setTimeout(resolve3, ms2));
16488
16602
  }
16489
16603
  async function runStreamWithReconnect(options) {
16490
16604
  const maxReconnectAttempts = options.maxReconnectAttempts ?? Number.POSITIVE_INFINITY;
@@ -16638,7 +16752,7 @@ async function createDevClient(input) {
16638
16752
  live = true;
16639
16753
  options?.onLive?.();
16640
16754
  }
16641
- await new Promise((resolve2) => setTimeout(resolve2, 100));
16755
+ await new Promise((resolve3) => setTimeout(resolve3, 100));
16642
16756
  }
16643
16757
  return;
16644
16758
  }
@@ -16653,7 +16767,7 @@ async function createDevClient(input) {
16653
16767
  }
16654
16768
  continue;
16655
16769
  }
16656
- await new Promise((resolve2) => setTimeout(resolve2, 250));
16770
+ await new Promise((resolve3) => setTimeout(resolve3, 250));
16657
16771
  }
16658
16772
  },
16659
16773
  async setConsentState(_inboxId, _state) {
@@ -16784,7 +16898,7 @@ function toTransportError(error, fallbackMessage) {
16784
16898
  return new XmtpTransportError(message, category, error);
16785
16899
  }
16786
16900
  function sleep3(ms2) {
16787
- return new Promise((resolve2) => setTimeout(resolve2, ms2));
16901
+ return new Promise((resolve3) => setTimeout(resolve3, ms2));
16788
16902
  }
16789
16903
  function parseRetryAttempts() {
16790
16904
  const raw = process.env.TASKMARKET_XMTP_SEND_MAX_ATTEMPTS;
@@ -16883,7 +16997,7 @@ async function sendViaConversation(client, toInboxId, body) {
16883
16997
  );
16884
16998
  }
16885
16999
  function callAsync(operation) {
16886
- return new Promise((resolve2) => resolve2(operation()));
17000
+ return new Promise((resolve3) => resolve3(operation()));
16887
17001
  }
16888
17002
  async function sendWithSdkClient(client, toInboxId, body) {
16889
17003
  const clientObject = asObject(client);
@@ -17964,23 +18078,23 @@ async function readHistory(options) {
17964
18078
  return;
17965
18079
  }
17966
18080
  const headers = options.task ? (await signReadAuth())?.headers ?? {} : (await readAuthHeaders()).headers;
17967
- const path9 = options.task ? `/api/market-events/tasks/${encodeURIComponent(options.task)}${query3({ since, limit })}` : `/api/market-events${query3({ since, limit })}`;
17968
- printResult(await apiGet(path9, { headers }));
18081
+ const path10 = options.task ? `/api/market-events/tasks/${encodeURIComponent(options.task)}${query3({ since, limit })}` : `/api/market-events${query3({ since, limit })}`;
18082
+ printResult(await apiGet(path10, { headers }));
17969
18083
  }
17970
18084
  function warn(message) {
17971
18085
  process.stderr.write(`${JSON.stringify({ ok: true, warning: message })}
17972
18086
  `);
17973
18087
  }
17974
18088
  function abortableSleep(ms2, signal) {
17975
- return new Promise((resolve2) => {
18089
+ return new Promise((resolve3) => {
17976
18090
  if (signal?.aborted) {
17977
- resolve2();
18091
+ resolve3();
17978
18092
  return;
17979
18093
  }
17980
18094
  const done = () => {
17981
18095
  clearTimeout(timer);
17982
18096
  signal?.removeEventListener("abort", done);
17983
- resolve2();
18097
+ resolve3();
17984
18098
  };
17985
18099
  const timer = setTimeout(done, ms2);
17986
18100
  signal?.addEventListener("abort", done, { once: true });
@@ -18138,7 +18252,7 @@ async function assertTaskVisible(taskId, auth, options) {
18138
18252
  readAuth: async () => auth,
18139
18253
  transport: {
18140
18254
  ...cliTaskTransport,
18141
- get: (path9, headers) => apiGet(path9, { headers, signal })
18255
+ get: (path10, headers) => apiGet(path10, { headers, signal })
18142
18256
  }
18143
18257
  };
18144
18258
  let task;
@@ -18359,15 +18473,15 @@ var EMAIL_POLL_INTERVAL_MS = 6e4;
18359
18473
  var EMAIL_RETRY_MAX_MS = 15 * 6e4;
18360
18474
  var MAX_CURSOR_IDS = 100;
18361
18475
  function abortableSleep2(ms2, signal) {
18362
- return new Promise((resolve2) => {
18476
+ return new Promise((resolve3) => {
18363
18477
  if (signal?.aborted) {
18364
- resolve2();
18478
+ resolve3();
18365
18479
  return;
18366
18480
  }
18367
18481
  const done = () => {
18368
18482
  clearTimeout(timer);
18369
18483
  signal?.removeEventListener("abort", done);
18370
- resolve2();
18484
+ resolve3();
18371
18485
  };
18372
18486
  const timer = setTimeout(done, ms2);
18373
18487
  signal?.addEventListener("abort", done, { once: true });
@@ -18631,13 +18745,13 @@ async function storeTaskFilters(json) {
18631
18745
  printResult({ source: "market", type: "discovery.filter", ...data }, { idempotencyKey });
18632
18746
  }
18633
18747
  function sleepOrAbort(ms2, signal) {
18634
- return new Promise((resolve2) => {
18635
- const id = setTimeout(resolve2, ms2);
18748
+ return new Promise((resolve3) => {
18749
+ const id = setTimeout(resolve3, ms2);
18636
18750
  signal.addEventListener(
18637
18751
  "abort",
18638
18752
  () => {
18639
18753
  clearTimeout(id);
18640
- resolve2();
18754
+ resolve3();
18641
18755
  },
18642
18756
  { once: true }
18643
18757
  );
@@ -18851,8 +18965,8 @@ var listCommand = new Command81("list").description(
18851
18965
  const channel = parseChannel(options.channel);
18852
18966
  const headers = await walletHeaders();
18853
18967
  if (!headers) return;
18854
- const path9 = channel === "email" ? PREFERENCES_PATH : `${PREFERENCES_PATH}?channel=${channel}`;
18855
- printResult(await apiGet(path9, { headers }));
18968
+ const path10 = channel === "email" ? PREFERENCES_PATH : `${PREFERENCES_PATH}?channel=${channel}`;
18969
+ printResult(await apiGet(path10, { headers }));
18856
18970
  } catch (err) {
18857
18971
  renderFailure(err);
18858
18972
  }
@@ -19047,13 +19161,19 @@ var readCommand = new Command85("read").description("Read an email by ID (marks
19047
19161
  import { Command as Command86 } from "commander";
19048
19162
  var sendCommand = new Command86("send").description("Send an email").requiredOption("--to <address>", "Recipient email address").requiredOption("--subject <subject>", "Email subject").requiredOption("--body <text>", "Email body text").action(async (opts) => {
19049
19163
  const keystore = await loadKeystore();
19050
- const { data: result, idempotencyKey } = await apiPost("/api/emails/send", {
19051
- deviceId: keystore.deviceId,
19052
- apiToken: keystore.apiToken,
19053
- to: opts.to,
19054
- subject: opts.subject,
19055
- bodyText: opts.body
19056
- });
19164
+ const { data: result, idempotencyKey } = await x402Post(
19165
+ "/api/emails/send",
19166
+ {
19167
+ chainId: selectedNetwork().chainId,
19168
+ deviceId: keystore.deviceId,
19169
+ apiToken: keystore.apiToken,
19170
+ to: opts.to,
19171
+ subject: opts.subject,
19172
+ bodyText: opts.body
19173
+ },
19174
+ // Mail to an outside address pays the standard action fee; internal mail is never charged.
19175
+ { maxAmount: STANDARD_X402_ACTION_AMOUNT }
19176
+ );
19057
19177
  printResult({ sent: result.sent }, { idempotencyKey });
19058
19178
  });
19059
19179
 
@@ -19074,13 +19194,19 @@ var replyCommand = new Command87("reply").description("Reply to an email").argum
19074
19194
  0,
19075
19195
  EMAIL_SEND_SUBJECT_MAX_LENGTH
19076
19196
  );
19077
- const { data: result, idempotencyKey } = await apiPost("/api/emails/send", {
19078
- deviceId: keystore.deviceId,
19079
- apiToken: keystore.apiToken,
19080
- to,
19081
- subject,
19082
- bodyText: opts.body
19083
- });
19197
+ const { data: result, idempotencyKey } = await x402Post(
19198
+ "/api/emails/send",
19199
+ {
19200
+ chainId: selectedNetwork().chainId,
19201
+ deviceId: keystore.deviceId,
19202
+ apiToken: keystore.apiToken,
19203
+ to,
19204
+ subject,
19205
+ bodyText: opts.body
19206
+ },
19207
+ // Mail to an outside address pays the standard action fee; internal mail is never charged.
19208
+ { maxAmount: STANDARD_X402_ACTION_AMOUNT }
19209
+ );
19084
19210
  printResult({ sent: result.sent }, { idempotencyKey });
19085
19211
  });
19086
19212
 
@@ -19211,7 +19337,7 @@ async function readStdin(firstByteMs) {
19211
19337
  let timer;
19212
19338
  const first = await Promise.race([
19213
19339
  iterator.next(),
19214
- ...firstByteMs === void 0 ? [] : [new Promise((resolve2) => timer = setTimeout(() => resolve2(null), firstByteMs))]
19340
+ ...firstByteMs === void 0 ? [] : [new Promise((resolve3) => timer = setTimeout(() => resolve3(null), firstByteMs))]
19215
19341
  ]);
19216
19342
  clearTimeout(timer);
19217
19343
  if (first === null) {
@@ -19787,7 +19913,7 @@ async function walk(root) {
19787
19913
  const names = (await readdir(dir)).sort();
19788
19914
  for (const name of names) {
19789
19915
  const full = join2(dir, name);
19790
- const path9 = relative(root, full).split(sep).join("/");
19916
+ const path10 = relative(root, full).split(sep).join("/");
19791
19917
  const info = await lstat(full);
19792
19918
  if (info.isDirectory()) {
19793
19919
  await visit(full);
@@ -19796,7 +19922,7 @@ async function walk(root) {
19796
19922
  if (entries.length >= MAX_ENTRIES)
19797
19923
  throw new Error(`The skill directory has more than ${MAX_ENTRIES} files`);
19798
19924
  const mode = info.isSymbolicLink() ? USER_SKILL_GIT_MODES.symlink : !info.isFile() ? "other" : info.mode & 73 ? USER_SKILL_GIT_MODES.executable : USER_SKILL_GIT_MODES.file;
19799
- entries.push({ path: path9, mode, full });
19925
+ entries.push({ path: path10, mode, full });
19800
19926
  }
19801
19927
  };
19802
19928
  await visit(root);
@@ -20199,9 +20325,9 @@ async function confirmManualResolution() {
20199
20325
  if (!process.stdin.isTTY) throw new Error("Manual resolution requires an interactive TTY");
20200
20326
  const readline = createInterface5({ input: process.stdin, output: process.stderr });
20201
20327
  const answer = await new Promise(
20202
- (resolve2) => readline.question(
20328
+ (resolve3) => readline.question(
20203
20329
  "Manual resolution changes local spending accounting. Type resolve to continue: ",
20204
- resolve2
20330
+ resolve3
20205
20331
  )
20206
20332
  );
20207
20333
  readline.close();
@@ -20212,10 +20338,10 @@ var x402PaymentsCommand = new Command108("payments").description(
20212
20338
  );
20213
20339
  x402PaymentsCommand.command("list").description("List current payment records").addOption(new Option5("--state <state>", "Filter by state").choices(PAYMENT_STATES)).action(async (options) => {
20214
20340
  const payments = await listX402Payments({ state: options.state }, getX402JournalPath());
20215
- printResult({ payments });
20341
+ printResult({ payments: payments.map(withPaymentProtocol) });
20216
20342
  });
20217
20343
  x402PaymentsCommand.command("get").description("Get one payment record").argument("<paymentId>", "Payment id").action(
20218
- async (paymentId) => printResult(await getX402Payment(paymentId, getX402JournalPath()))
20344
+ async (paymentId) => printResult(withPaymentProtocol(await getX402Payment(paymentId, getX402JournalPath())))
20219
20345
  );
20220
20346
  x402PaymentsCommand.command("reconcile").description("Reconcile a payment authorization against the configured chain").argument("<paymentId>", "Payment id").action(async (paymentId) => printResult(await reconcileX402PaymentById(paymentId)));
20221
20347
  x402PaymentsCommand.command("resolve").description("Manually record an externally verified final amount").argument("<paymentId>", "Payment id").requiredOption("--settled-amount <atomicUnits>", "Final settled amount in atomic units").requiredOption("--note <text>", "Audit note describing the evidence").option("--transaction <hash>", "Settlement transaction hash").action(
@@ -20230,7 +20356,7 @@ x402PaymentsCommand.command("resolve").description("Manually record an externall
20230
20356
  },
20231
20357
  getX402JournalPath()
20232
20358
  );
20233
- printResult(payment);
20359
+ printResult(withPaymentProtocol(payment));
20234
20360
  }
20235
20361
  );
20236
20362
 
@@ -20257,7 +20383,7 @@ async function confirmUnattendedRule(rule) {
20257
20383
  );
20258
20384
  const readline = createInterface6({ input: process.stdin, output: process.stderr });
20259
20385
  const answer = await new Promise(
20260
- (resolve2) => readline.question("Type authorize to grant unattended spending: ", resolve2)
20386
+ (resolve3) => readline.question("Type authorize to grant unattended spending: ", resolve3)
20261
20387
  );
20262
20388
  readline.close();
20263
20389
  return answer.trim().toLowerCase() === "authorize";
@@ -20305,7 +20431,41 @@ function collect4(value, previous) {
20305
20431
  function confirm(lines) {
20306
20432
  return confirmAtTerminal(lines, "use --non-interactive with policy");
20307
20433
  }
20308
- var x402RequestCommand = new Command110("request").description("Request and pay for a direct x402 HTTP resource (X402 Pay)").argument("<url>", "HTTPS resource URL").addOption(new Option6("--method <method>", "HTTP method").choices(["GET", "POST"]).default("GET")).option("--json <json>", "Inline JSON POST body").option("--body-file <path>", "Read JSON POST body from a file").option("--headers-file <path>", "Read request headers from an owner-only JSON file").option(
20434
+ function amountLines(terms, charge) {
20435
+ if (!charge) {
20436
+ return [
20437
+ `${terms.scheme === "upto" ? "Maximum authorization" : "Exact charge"}: ${terms.authorizedAmount} atomic units`
20438
+ ];
20439
+ }
20440
+ const recipient = terms.chargeAmount ?? terms.authorizedAmount;
20441
+ const sponsored = terms.feeSponsored === true;
20442
+ return [
20443
+ `Recipient receives: ${recipient} atomic units`,
20444
+ sponsored ? "Network fee: paid by the seller" : `Network fee: paid by your wallet, worst case ${terms.maxFee ?? "unknown"} atomic units of the token`,
20445
+ `Maximum authorized in total: ${terms.authorizedAmount} atomic units`
20446
+ ];
20447
+ }
20448
+ function paymentConfirmationLines(terms) {
20449
+ const protocol = x402PaymentProtocol(terms);
20450
+ const charge = protocol === "mpp";
20451
+ return [
20452
+ charge ? "External MPP payment" : "External x402 payment",
20453
+ `Resource: ${terms.method} ${terms.origin}${terms.pathname}`,
20454
+ `Protocol: ${protocol}`,
20455
+ `Scheme: ${terms.scheme}`,
20456
+ `Network: ${terms.network}`,
20457
+ `Token: ${terms.asset}`,
20458
+ `Recipient: ${terms.payTo}`,
20459
+ ...amountLines(terms, charge),
20460
+ `Policy: ${terms.policyRuleId ?? "one-time interactive exception"}`
20461
+ ];
20462
+ }
20463
+ var x402RequestCommand = new Command110("request").description("Request and pay for a direct x402 HTTP resource (X402 Pay)").argument("<url>", "HTTPS resource URL").addOption(new Option6("--method <method>", "HTTP method").choices(["GET", "POST"]).default("GET")).addOption(
20464
+ new Option6(
20465
+ "--protocol <protocol>",
20466
+ "Payment protocol the 402 may be paid through: auto reads x402 and MPP, x402 or mpp restricts it"
20467
+ ).choices([...X402_PAY_PROTOCOLS]).default("auto")
20468
+ ).option("--json <json>", "Inline JSON POST body").option("--body-file <path>", "Read JSON POST body from a file").option("--headers-file <path>", "Read request headers from an owner-only JSON file").option(
20309
20469
  "--header-env <header=ENV_VAR>",
20310
20470
  "Read one request header from an environment variable (repeatable)",
20311
20471
  collect4,
@@ -20322,6 +20482,7 @@ var x402RequestCommand = new Command110("request").description("Request and pay
20322
20482
  const result = await executeX402PayRequest({
20323
20483
  rawUrl: url,
20324
20484
  method: options.method,
20485
+ protocol: options.protocol,
20325
20486
  json: options.json,
20326
20487
  bodyFile: options.bodyFile,
20327
20488
  headers,
@@ -20329,16 +20490,7 @@ var x402RequestCommand = new Command110("request").description("Request and pay
20329
20490
  nonInteractive: options.nonInteractive,
20330
20491
  policyRuleId: options.policy,
20331
20492
  invocationId: options.invocationId,
20332
- confirmPayment: (terms) => confirm([
20333
- "External x402 payment",
20334
- `Resource: ${terms.method} ${terms.origin}${terms.pathname}`,
20335
- `Scheme: ${terms.scheme}`,
20336
- `Network: ${terms.network}`,
20337
- `Asset: ${terms.asset}`,
20338
- `Recipient: ${terms.payTo}`,
20339
- `${terms.scheme === "upto" ? "Maximum authorization" : "Exact charge"}: ${terms.authorizedAmount} atomic units`,
20340
- `Policy: ${terms.policyRuleId ?? "one-time interactive exception"}`
20341
- ]),
20493
+ confirmPayment: (terms) => confirm(paymentConfirmationLines(terms)),
20342
20494
  confirmDirectApproval: (details) => confirm([
20343
20495
  "Permit2 token approval",
20344
20496
  `Network: ${details.network}`,
@@ -23521,6 +23673,28 @@ var CONFIG_DISCRIMINATOR = new Uint8Array([
23521
23673
  204,
23522
23674
  130
23523
23675
  ]);
23676
+ function getConfigDecoder() {
23677
+ return getStructDecoder([
23678
+ ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
23679
+ ["admin", getAddressDecoder()],
23680
+ ["settlers", getArrayDecoder(getAddressDecoder())],
23681
+ ["threshold", getU8Decoder()],
23682
+ ["paused", getBooleanDecoder()],
23683
+ ["feeBps", getU16Decoder()],
23684
+ ["feeRecipient", getAddressDecoder()],
23685
+ ["bump", getU8Decoder()],
23686
+ ["claimDelaySeconds", getU64Decoder()],
23687
+ ["pendingAdmin", getAddressDecoder()],
23688
+ ["clusterId", fixDecoderSize(getBytesDecoder(), 32)]
23689
+ ]);
23690
+ }
23691
+ function decodeConfig(encodedAccount) {
23692
+ return decodeAccount(encodedAccount, getConfigDecoder());
23693
+ }
23694
+ async function fetchMaybeConfig(rpc, address3, config) {
23695
+ const maybeAccount = await fetchEncodedAccount(rpc, address3, config);
23696
+ return decodeConfig(maybeAccount);
23697
+ }
23524
23698
 
23525
23699
  // ../../packages/solana-sponsored-client/dist/generated/accounts/payoutBinding.js
23526
23700
  var PAYOUT_BINDING_DISCRIMINATOR = new Uint8Array([
@@ -23540,7 +23714,9 @@ function getPayoutBindingDecoder() {
23540
23714
  ["agent", fixDecoderSize(getBytesDecoder(), 20)],
23541
23715
  ["payout", getAddressDecoder()],
23542
23716
  ["nonce", getU64Decoder()],
23543
- ["bump", getU8Decoder()]
23717
+ ["bump", getU8Decoder()],
23718
+ ["pendingPayout", getAddressDecoder()],
23719
+ ["pendingEffectiveAt", getI64Decoder()]
23544
23720
  ]);
23545
23721
  }
23546
23722
 
@@ -23769,6 +23945,7 @@ function getBindPayoutInstructionDataEncoder() {
23769
23945
  ["agent", fixEncoderSize(getBytesEncoder(), 20)],
23770
23946
  ["payout", getAddressEncoder()],
23771
23947
  ["nonce", getU64Encoder()],
23948
+ ["deadline", getU64Encoder()],
23772
23949
  ["signature", fixEncoderSize(getBytesEncoder(), 65)]
23773
23950
  ]), (value) => ({ ...value, discriminator: BIND_PAYOUT_DISCRIMINATOR }));
23774
23951
  }
@@ -23776,6 +23953,7 @@ async function getBindPayoutInstructionAsync(input, config) {
23776
23953
  const programAddress = config?.programAddress ?? SPONSORED_TASKS_PROGRAM_ADDRESS;
23777
23954
  const getAccountMeta = getAccountMetaFactory2(programAddress, "programId");
23778
23955
  const originalAccounts = {
23956
+ config: { value: input.config ?? null, isSigner: false, isWritable: false },
23779
23957
  binding: { value: input.binding ?? null, isSigner: false, isWritable: true },
23780
23958
  payer: { value: input.payer ?? null, isSigner: true, isWritable: true },
23781
23959
  systemProgram: { value: input.systemProgram ?? null, isSigner: false, isWritable: false },
@@ -23784,6 +23962,9 @@ async function getBindPayoutInstructionAsync(input, config) {
23784
23962
  };
23785
23963
  const accounts = originalAccounts;
23786
23964
  const args = { ...input };
23965
+ if (!accounts.config.value) {
23966
+ accounts.config.value = await findConfigPda({ programAddress });
23967
+ }
23787
23968
  if (!accounts.binding.value) {
23788
23969
  accounts.binding.value = await findBindingPda({
23789
23970
  taskChainId: getNonNullResolvedInstructionInput2("taskChainId", args.taskChainId),
@@ -23795,6 +23976,7 @@ async function getBindPayoutInstructionAsync(input, config) {
23795
23976
  }
23796
23977
  return Object.freeze({
23797
23978
  accounts: [
23979
+ getAccountMeta("config", accounts.config),
23798
23980
  getAccountMeta("binding", accounts.binding),
23799
23981
  getAccountMeta("payer", accounts.payer),
23800
23982
  getAccountMeta("systemProgram", accounts.systemProgram),
@@ -24061,6 +24243,18 @@ var RELEASE_DISCRIMINATOR = new Uint8Array([
24061
24243
  241
24062
24244
  ]);
24063
24245
 
24246
+ // ../../packages/solana-sponsored-client/dist/generated/instructions/releaseExpired.js
24247
+ var RELEASE_EXPIRED_DISCRIMINATOR = new Uint8Array([
24248
+ 150,
24249
+ 199,
24250
+ 225,
24251
+ 10,
24252
+ 15,
24253
+ 244,
24254
+ 46,
24255
+ 47
24256
+ ]);
24257
+
24064
24258
  // ../../packages/solana-sponsored-client/dist/generated/instructions/reserve.js
24065
24259
  var RESERVE_DISCRIMINATOR = new Uint8Array([
24066
24260
  92,
@@ -24206,16 +24400,17 @@ var SponsoredTasksEvent;
24206
24400
  SponsoredTasksEvent2[SponsoredTasksEvent2["ManagerConfigured"] = 6] = "ManagerConfigured";
24207
24401
  SponsoredTasksEvent2[SponsoredTasksEvent2["ManagerRemoved"] = 7] = "ManagerRemoved";
24208
24402
  SponsoredTasksEvent2[SponsoredTasksEvent2["PauseSet"] = 8] = "PauseSet";
24209
- SponsoredTasksEvent2[SponsoredTasksEvent2["PayoutBound"] = 9] = "PayoutBound";
24210
- SponsoredTasksEvent2[SponsoredTasksEvent2["SettlementInstalled"] = 10] = "SettlementInstalled";
24211
- SponsoredTasksEvent2[SponsoredTasksEvent2["SettlementRevoked"] = 11] = "SettlementRevoked";
24212
- SponsoredTasksEvent2[SponsoredTasksEvent2["SettlersChanged"] = 12] = "SettlersChanged";
24213
- SponsoredTasksEvent2[SponsoredTasksEvent2["SponsoredTaskClaimed"] = 13] = "SponsoredTaskClaimed";
24214
- SponsoredTasksEvent2[SponsoredTasksEvent2["TaskReleased"] = 14] = "TaskReleased";
24215
- SponsoredTasksEvent2[SponsoredTasksEvent2["TaskReserved"] = 15] = "TaskReserved";
24216
- SponsoredTasksEvent2[SponsoredTasksEvent2["VaultCreated"] = 16] = "VaultCreated";
24217
- SponsoredTasksEvent2[SponsoredTasksEvent2["VaultEmergencyExited"] = 17] = "VaultEmergencyExited";
24218
- SponsoredTasksEvent2[SponsoredTasksEvent2["VaultFunded"] = 18] = "VaultFunded";
24403
+ SponsoredTasksEvent2[SponsoredTasksEvent2["PayoutBindingPending"] = 9] = "PayoutBindingPending";
24404
+ SponsoredTasksEvent2[SponsoredTasksEvent2["PayoutBound"] = 10] = "PayoutBound";
24405
+ SponsoredTasksEvent2[SponsoredTasksEvent2["SettlementInstalled"] = 11] = "SettlementInstalled";
24406
+ SponsoredTasksEvent2[SponsoredTasksEvent2["SettlementRevoked"] = 12] = "SettlementRevoked";
24407
+ SponsoredTasksEvent2[SponsoredTasksEvent2["SettlersChanged"] = 13] = "SettlersChanged";
24408
+ SponsoredTasksEvent2[SponsoredTasksEvent2["SponsoredTaskClaimed"] = 14] = "SponsoredTaskClaimed";
24409
+ SponsoredTasksEvent2[SponsoredTasksEvent2["TaskReleased"] = 15] = "TaskReleased";
24410
+ SponsoredTasksEvent2[SponsoredTasksEvent2["TaskReserved"] = 16] = "TaskReserved";
24411
+ SponsoredTasksEvent2[SponsoredTasksEvent2["VaultCreated"] = 17] = "VaultCreated";
24412
+ SponsoredTasksEvent2[SponsoredTasksEvent2["VaultEmergencyExited"] = 18] = "VaultEmergencyExited";
24413
+ SponsoredTasksEvent2[SponsoredTasksEvent2["VaultFunded"] = 19] = "VaultFunded";
24219
24414
  })(SponsoredTasksEvent || (SponsoredTasksEvent = {}));
24220
24415
  var SponsoredTasksInstruction;
24221
24416
  (function(SponsoredTasksInstruction2) {
@@ -24230,14 +24425,15 @@ var SponsoredTasksInstruction;
24230
24425
  SponsoredTasksInstruction2[SponsoredTasksInstruction2["InitConfig"] = 8] = "InitConfig";
24231
24426
  SponsoredTasksInstruction2[SponsoredTasksInstruction2["Pause"] = 9] = "Pause";
24232
24427
  SponsoredTasksInstruction2[SponsoredTasksInstruction2["Release"] = 10] = "Release";
24233
- SponsoredTasksInstruction2[SponsoredTasksInstruction2["Reserve"] = 11] = "Reserve";
24234
- SponsoredTasksInstruction2[SponsoredTasksInstruction2["RevokeSettlement"] = 12] = "RevokeSettlement";
24235
- SponsoredTasksInstruction2[SponsoredTasksInstruction2["SetAdmin"] = 13] = "SetAdmin";
24236
- SponsoredTasksInstruction2[SponsoredTasksInstruction2["SetClaimDelay"] = 14] = "SetClaimDelay";
24237
- SponsoredTasksInstruction2[SponsoredTasksInstruction2["SetFee"] = 15] = "SetFee";
24238
- SponsoredTasksInstruction2[SponsoredTasksInstruction2["SetManagers"] = 16] = "SetManagers";
24239
- SponsoredTasksInstruction2[SponsoredTasksInstruction2["SetSettlers"] = 17] = "SetSettlers";
24240
- SponsoredTasksInstruction2[SponsoredTasksInstruction2["Settle"] = 18] = "Settle";
24428
+ SponsoredTasksInstruction2[SponsoredTasksInstruction2["ReleaseExpired"] = 11] = "ReleaseExpired";
24429
+ SponsoredTasksInstruction2[SponsoredTasksInstruction2["Reserve"] = 12] = "Reserve";
24430
+ SponsoredTasksInstruction2[SponsoredTasksInstruction2["RevokeSettlement"] = 13] = "RevokeSettlement";
24431
+ SponsoredTasksInstruction2[SponsoredTasksInstruction2["SetAdmin"] = 14] = "SetAdmin";
24432
+ SponsoredTasksInstruction2[SponsoredTasksInstruction2["SetClaimDelay"] = 15] = "SetClaimDelay";
24433
+ SponsoredTasksInstruction2[SponsoredTasksInstruction2["SetFee"] = 16] = "SetFee";
24434
+ SponsoredTasksInstruction2[SponsoredTasksInstruction2["SetManagers"] = 17] = "SetManagers";
24435
+ SponsoredTasksInstruction2[SponsoredTasksInstruction2["SetSettlers"] = 18] = "SetSettlers";
24436
+ SponsoredTasksInstruction2[SponsoredTasksInstruction2["Settle"] = 19] = "Settle";
24241
24437
  })(SponsoredTasksInstruction || (SponsoredTasksInstruction = {}));
24242
24438
 
24243
24439
  // ../../packages/solana-sponsored-client/dist/generated/errors/sponsoredTasks.js
@@ -24278,6 +24474,11 @@ var SPONSORED_TASKS_ERROR__PAYOUT_NOT_BOUND = 6033;
24278
24474
  var SPONSORED_TASKS_ERROR__CLAIM_DELAY_NOT_ELAPSED = 6034;
24279
24475
  var SPONSORED_TASKS_ERROR__NOT_PENDING_ADMIN = 6035;
24280
24476
  var SPONSORED_TASKS_ERROR__INVALID_ATTESTED_NONCE = 6036;
24477
+ var SPONSORED_TASKS_ERROR__INVALID_ADMIN = 6037;
24478
+ var SPONSORED_TASKS_ERROR__INVALID_CLUSTER_ID = 6038;
24479
+ var SPONSORED_TASKS_ERROR__PAYOUT_SIGNATURE_EXPIRED = 6039;
24480
+ var SPONSORED_TASKS_ERROR__INVALID_PAYOUT_NONCE = 6040;
24481
+ var SPONSORED_TASKS_ERROR__RESERVATION_NOT_EXPIRED = 6041;
24281
24482
  var sponsoredTasksErrorMessages;
24282
24483
  if (process.env["NODE_ENV"] !== "production") {
24283
24484
  sponsoredTasksErrorMessages = {
@@ -24287,11 +24488,14 @@ if (process.env["NODE_ENV"] !== "production") {
24287
24488
  [SPONSORED_TASKS_ERROR__DEADLINE_IN_PAST]: `Reservation deadline is in the past`,
24288
24489
  [SPONSORED_TASKS_ERROR__EPOCH_MISMATCH]: `Reservation belongs to an earlier vault epoch`,
24289
24490
  [SPONSORED_TASKS_ERROR__INSUFFICIENT_AVAILABLE]: `Reservation exceeds the vault's available balance`,
24491
+ [SPONSORED_TASKS_ERROR__INVALID_ADMIN]: `Admin must not be the zero key`,
24290
24492
  [SPONSORED_TASKS_ERROR__INVALID_ATTESTED_NONCE]: `Attested payout nonce must be the current nonce plus one and below u64::MAX`,
24291
24493
  [SPONSORED_TASKS_ERROR__INVALID_CLAIM_DELAY]: `Claim delay must be between 1 second and i64::MAX`,
24292
24494
  [SPONSORED_TASKS_ERROR__INVALID_CLAIM_PROOF]: `Award proof does not match the settlement root`,
24495
+ [SPONSORED_TASKS_ERROR__INVALID_CLUSTER_ID]: `Cluster id must not be zero`,
24293
24496
  [SPONSORED_TASKS_ERROR__INVALID_FEE_BPS]: `Fee basis points above 10000`,
24294
24497
  [SPONSORED_TASKS_ERROR__INVALID_MANAGER_CAP]: `Manager cap is below its reserved plus spent amount`,
24498
+ [SPONSORED_TASKS_ERROR__INVALID_PAYOUT_NONCE]: `Payout binding nonce must be below u64::MAX`,
24295
24499
  [SPONSORED_TASKS_ERROR__INVALID_PAYOUT_SIGNATURE]: `Payout binding signature is not from the agent`,
24296
24500
  [SPONSORED_TASKS_ERROR__INVALID_SETTLEMENT_TOTALS]: `Settlement totals do not add up or do not match the root`,
24297
24501
  [SPONSORED_TASKS_ERROR__INVALID_SETTLERS]: `Settler set is empty, too large or has duplicates`,
@@ -24308,6 +24512,8 @@ if (process.env["NODE_ENV"] !== "production") {
24308
24512
  [SPONSORED_TASKS_ERROR__OVERFLOW]: `Arithmetic overflow`,
24309
24513
  [SPONSORED_TASKS_ERROR__PAUSED]: `Program is paused`,
24310
24514
  [SPONSORED_TASKS_ERROR__PAYOUT_NOT_BOUND]: `Worker has no payout binding`,
24515
+ [SPONSORED_TASKS_ERROR__PAYOUT_SIGNATURE_EXPIRED]: `Payout binding signature has expired`,
24516
+ [SPONSORED_TASKS_ERROR__RESERVATION_NOT_EXPIRED]: `Reservation deadline has not passed`,
24311
24517
  [SPONSORED_TASKS_ERROR__RESERVATION_WRONG_STATE]: `Reservation is not in the reserved state`,
24312
24518
  [SPONSORED_TASKS_ERROR__SETTLEMENT_EXCEEDS_RESERVATION]: `Settlement awards more than the reservation holds`,
24313
24519
  [SPONSORED_TASKS_ERROR__SETTLEMENT_HAS_CLAIMS]: `Settlement already has claims against it`,
@@ -24429,6 +24635,18 @@ var PAUSE_SET_EVENT_DISCRIMINATOR = new Uint8Array([
24429
24635
  73
24430
24636
  ]);
24431
24637
 
24638
+ // ../../packages/solana-sponsored-client/dist/generated/events/payoutBindingPending.js
24639
+ var PAYOUT_BINDING_PENDING_EVENT_DISCRIMINATOR = new Uint8Array([
24640
+ 75,
24641
+ 145,
24642
+ 148,
24643
+ 254,
24644
+ 250,
24645
+ 88,
24646
+ 225,
24647
+ 107
24648
+ ]);
24649
+
24432
24650
  // ../../packages/solana-sponsored-client/dist/generated/events/payoutBound.js
24433
24651
  var PAYOUT_BOUND_EVENT_DISCRIMINATOR = new Uint8Array([
24434
24652
  36,
@@ -24726,7 +24944,7 @@ async function readVaultCreationFee(publicClient, factory) {
24726
24944
  );
24727
24945
  }
24728
24946
  if (typeof amount !== "bigint" || amount === 0n) return null;
24729
- const [token, recipient] = await Promise.all([
24947
+ const [token2, recipient] = await Promise.all([
24730
24948
  publicClient.readContract({
24731
24949
  address: factory,
24732
24950
  abi: SponsoredTaskFactoryV2ABI,
@@ -24738,7 +24956,7 @@ async function readVaultCreationFee(publicClient, factory) {
24738
24956
  functionName: "creationFeeRecipient"
24739
24957
  })
24740
24958
  ]);
24741
- return { amount, token, recipient };
24959
+ return { amount, token: token2, recipient };
24742
24960
  }
24743
24961
  function isValidAddress4(addr) {
24744
24962
  return /^0x[a-fA-F0-9]{40}$/.test(addr);
@@ -25009,14 +25227,30 @@ var sponsoredTaskFundCommand = new Command113("fund").description("Fund a Sponso
25009
25227
  import { Command as Command114 } from "commander";
25010
25228
 
25011
25229
  // src/lib/solana-payout-binding.ts
25230
+ import { concat, keccak256 } from "viem";
25012
25231
  var PROGRAM_ID_ENV = "TASKMARKET_SOLANA_SPONSORED_TASKS_PROGRAM_ID";
25013
25232
  var PAYOUT_BINDING_TYPES = {
25014
25233
  PayoutBinding: [
25015
25234
  { name: "agent", type: "address" },
25016
25235
  { name: "payout", type: "bytes32" },
25017
- { name: "nonce", type: "uint64" }
25236
+ { name: "nonce", type: "uint64" },
25237
+ { name: "deadline", type: "uint64" }
25018
25238
  ]
25019
25239
  };
25240
+ var PAYOUT_BINDING_VALIDITY_SECONDS = 3600;
25241
+ function payoutBindingDeadline(nowSeconds = Math.floor(Date.now() / 1e3)) {
25242
+ return BigInt(nowSeconds + PAYOUT_BINDING_VALIDITY_SECONDS);
25243
+ }
25244
+ async function readClusterId(rpc, programId) {
25245
+ const [configAddress] = await findConfigPda({ programAddress: programId });
25246
+ const config = await fetchMaybeConfig(rpc, configAddress);
25247
+ if (!config.exists) {
25248
+ throw new Error(
25249
+ `The Sponsored Tasks program ${programId} has no config account on this cluster`
25250
+ );
25251
+ }
25252
+ return hex(Uint8Array.from(config.data.clusterId));
25253
+ }
25020
25254
  function resolveProgramId(flag, solanaChainId, registryProgramId = (chainId) => svmChain(chainId).sponsoredTasks.programId) {
25021
25255
  const raw = flag || process.env[PROGRAM_ID_ENV] || registryProgramId(solanaChainId);
25022
25256
  if (!raw) {
@@ -25044,14 +25278,17 @@ function payoutBindingTypedData(input) {
25044
25278
  name: "Taskmarket Sponsored Tasks",
25045
25279
  version: "1",
25046
25280
  chainId: input.taskChainId,
25047
- salt: hex(getAddressEncoder().encode(input.programId))
25281
+ salt: keccak256(
25282
+ concat([hex(getAddressEncoder().encode(input.programId)), input.clusterId])
25283
+ )
25048
25284
  },
25049
25285
  types: PAYOUT_BINDING_TYPES,
25050
25286
  primaryType: "PayoutBinding",
25051
25287
  message: {
25052
25288
  agent: input.agent,
25053
25289
  payout: hex(getAddressEncoder().encode(input.payout)),
25054
- nonce: input.nonce
25290
+ nonce: input.nonce,
25291
+ deadline: input.deadline
25055
25292
  }
25056
25293
  };
25057
25294
  }
@@ -25062,16 +25299,21 @@ async function findPayoutBindingAddress(programId, taskChainId, agent) {
25062
25299
  );
25063
25300
  return pda;
25064
25301
  }
25065
- function decodePayoutBinding(data) {
25302
+ var ZERO_ADDRESS = "11111111111111111111111111111111";
25303
+ function decodePayoutBinding(data, nowSeconds = BigInt(Math.floor(Date.now() / 1e3))) {
25066
25304
  const decoder = getPayoutBindingDecoder();
25067
25305
  if (data.length < decoder.fixedSize) return null;
25068
25306
  if (!PAYOUT_BINDING_DISCRIMINATOR.every((b, i) => data[i] === b)) return null;
25069
25307
  const decoded = decoder.decode(data);
25308
+ const waiting = decoded.pendingEffectiveAt !== 0n && nowSeconds < decoded.pendingEffectiveAt;
25309
+ const pendingApplies = decoded.pendingEffectiveAt !== 0n && !waiting;
25310
+ const current = pendingApplies ? decoded.pendingPayout : decoded.payout;
25070
25311
  return {
25071
25312
  taskChainId: Number(decoded.taskChainId),
25072
25313
  agent: hex(Uint8Array.from(decoded.agent)),
25073
- payout: decoded.payout,
25074
- nonce: decoded.nonce
25314
+ payout: current === ZERO_ADDRESS && waiting ? decoded.pendingPayout : current,
25315
+ nonce: decoded.nonce,
25316
+ pending: waiting ? { payout: decoded.pendingPayout, effectiveAt: decoded.pendingEffectiveAt } : null
25075
25317
  };
25076
25318
  }
25077
25319
  async function readPayoutBinding(rpc, programId, taskChainId, agent) {
@@ -25091,8 +25333,10 @@ async function bindPayoutInstruction(input) {
25091
25333
  programAddress: input.programId,
25092
25334
  seeds: ["__event_authority"]
25093
25335
  });
25336
+ const [config] = await findConfigPda({ programAddress: input.programId });
25094
25337
  return getBindPayoutInstructionAsync(
25095
25338
  {
25339
+ config,
25096
25340
  payer: input.payer,
25097
25341
  eventAuthority,
25098
25342
  program: input.programId,
@@ -25100,6 +25344,7 @@ async function bindPayoutInstruction(input) {
25100
25344
  agent: agentBytes(input.agent),
25101
25345
  payout: input.payout,
25102
25346
  nonce: input.nonce,
25347
+ deadline: input.deadline,
25103
25348
  signature: signatureBytes(input.signature)
25104
25349
  },
25105
25350
  { programAddress: input.programId }
@@ -25719,14 +25964,14 @@ function describeSolanaAwards(awards, vaultAddress, solanaChainId, taskId) {
25719
25964
  function isRetryableClaimConflict(err) {
25720
25965
  return err instanceof ApiError && (err.status === 409 || err.status >= 500) && /retry/i.test(err.message);
25721
25966
  }
25722
- async function postClaimWithRetry(path9, body, options = {}) {
25967
+ async function postClaimWithRetry(path10, body, options = {}) {
25723
25968
  const sleep4 = options.sleep ?? ((ms2) => new Promise((r) => setTimeout(r, ms2)));
25724
25969
  const deadline = Date.now() + (options.budgetMs ?? CLAIM_RETRY_BUDGET_MS);
25725
25970
  const idempotencyKey = resolveIdempotencyKey();
25726
25971
  let delayMs = 500;
25727
25972
  for (; ; ) {
25728
25973
  try {
25729
- return await apiPost(path9, body, { idempotencyKey });
25974
+ return await apiPost(path10, body, { idempotencyKey });
25730
25975
  } catch (err) {
25731
25976
  if (!isRetryableClaimConflict(err) || Date.now() + delayMs > deadline) throw err;
25732
25977
  await sleep4(delayMs);
@@ -25966,7 +26211,16 @@ var sponsoredTaskBindPayoutCommand = new Command126("bind-payout").description(
25966
26211
  binding: await readPayoutBinding(rpc, programId, taskChainId, agent)
25967
26212
  }))
25968
26213
  );
25969
- const view = (binding) => binding ? { payout: binding.payout, nonce: binding.nonce.toString() } : null;
26214
+ const view = (binding) => binding ? {
26215
+ payout: binding.payout,
26216
+ nonce: binding.nonce.toString(),
26217
+ ...binding.pending ? {
26218
+ pending: {
26219
+ payout: binding.pending.payout,
26220
+ effectiveAt: binding.pending.effectiveAt.toString()
26221
+ }
26222
+ } : {}
26223
+ } : null;
25970
26224
  if (opts.status) {
25971
26225
  const unbound = current.some((c) => !c.binding);
25972
26226
  printResult({
@@ -25996,6 +26250,7 @@ var sponsoredTaskBindPayoutCommand = new Command126("bind-payout").description(
25996
26250
  }
25997
26251
  }
25998
26252
  let payer;
26253
+ let clusterId;
25999
26254
  const bindings = [];
26000
26255
  try {
26001
26256
  for (const { taskChainId, binding } of current) {
@@ -26004,8 +26259,18 @@ var sponsoredTaskBindPayoutCommand = new Command126("bind-payout").description(
26004
26259
  continue;
26005
26260
  }
26006
26261
  const nonce = nonceOverride ?? (binding ? binding.nonce + 1n : 1n);
26262
+ clusterId ??= await readClusterId(rpc, programId);
26263
+ const deadline = payoutBindingDeadline();
26007
26264
  const signature = await signTypedData(
26008
- payoutBindingTypedData({ taskChainId, programId, agent, payout, nonce }),
26265
+ payoutBindingTypedData({
26266
+ taskChainId,
26267
+ programId,
26268
+ clusterId,
26269
+ agent,
26270
+ payout,
26271
+ nonce,
26272
+ deadline
26273
+ }),
26009
26274
  keystore
26010
26275
  );
26011
26276
  payer ??= await createSolanaSignerFromKeystore(keystore);
@@ -26018,11 +26283,13 @@ var sponsoredTaskBindPayoutCommand = new Command126("bind-payout").description(
26018
26283
  agent,
26019
26284
  payout,
26020
26285
  nonce,
26286
+ deadline,
26021
26287
  signature
26022
26288
  });
26023
26289
  bindings.push({
26024
26290
  taskChainId,
26025
26291
  nonce: nonce.toString(),
26292
+ deadline: deadline.toString(),
26026
26293
  replaced: view(binding),
26027
26294
  signature: txSignature
26028
26295
  });
@@ -26191,9 +26458,9 @@ function evaluatorTerms(opts) {
26191
26458
  }
26192
26459
 
26193
26460
  // src/commands/project/write.ts
26194
- async function postProjectWrite(path9, body, options) {
26461
+ async function postProjectWrite(path10, body, options) {
26195
26462
  const { data: result, idempotencyKey } = await x402Post(
26196
- path9,
26463
+ path10,
26197
26464
  { chainId: selectedNetwork().chainId, ...body },
26198
26465
  { maxAmount: options.maxAmount }
26199
26466
  );
@@ -26516,10 +26783,10 @@ function proposalDecisionBody(proposalId, suggestions) {
26516
26783
  if (!parsed.success) return { error: `--suggestion: ${parsed.error.issues[0].message}` };
26517
26784
  return body;
26518
26785
  }
26519
- async function read(path9) {
26786
+ async function read(path10) {
26520
26787
  try {
26521
26788
  const headers = (await signReadAuth())?.headers ?? {};
26522
- printResult(await apiGet(withChainId(path9), { headers }));
26789
+ printResult(await apiGet(withChainId(path10), { headers }));
26523
26790
  } catch (err) {
26524
26791
  renderFailure(err);
26525
26792
  }
@@ -26673,10 +26940,10 @@ function suggestionSettingsBody(projectId, opts) {
26673
26940
  }
26674
26941
  return body;
26675
26942
  }
26676
- async function signedRead(path9) {
26943
+ async function signedRead(path10) {
26677
26944
  try {
26678
26945
  const headers = (await signReadAuth())?.headers ?? {};
26679
- printResult(await apiGet(withChainId(path9), { headers }));
26946
+ printResult(await apiGet(withChainId(path10), { headers }));
26680
26947
  } catch (err) {
26681
26948
  renderFailure(err);
26682
26949
  }
@@ -27456,22 +27723,22 @@ var UUID3 = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-
27456
27723
  var ADDRESS2 = /^0x[0-9a-fA-F]{40}$/;
27457
27724
  var FILE_MAX_BYTES = 256 * 1024;
27458
27725
  var PARAM_NAME = /^[A-Za-z][A-Za-z0-9_]{0,39}$/;
27459
- async function readJsonFile(path9, what = "template") {
27460
- if (!path9) return { error: `Pass the ${what} with --file <path> (JSON)` };
27726
+ async function readJsonFile(path10, what = "template") {
27727
+ if (!path10) return { error: `Pass the ${what} with --file <path> (JSON)` };
27461
27728
  let text;
27462
27729
  try {
27463
- const buffer = await readFile4(path9);
27730
+ const buffer = await readFile4(path10);
27464
27731
  if (buffer.length > FILE_MAX_BYTES) {
27465
- return { error: `${path9} is ${buffer.length} bytes; a ${what} is at most 64 KiB as JSON` };
27732
+ return { error: `${path10} is ${buffer.length} bytes; a ${what} is at most 64 KiB as JSON` };
27466
27733
  }
27467
27734
  text = buffer.toString("utf8");
27468
27735
  } catch (error) {
27469
- return { error: `Unable to read ${path9}: ${error.message}` };
27736
+ return { error: `Unable to read ${path10}: ${error.message}` };
27470
27737
  }
27471
27738
  try {
27472
27739
  return { document: JSON.parse(text) };
27473
27740
  } catch (error) {
27474
- return { error: `${path9} is not valid JSON: ${error.message}` };
27741
+ return { error: `${path10} is not valid JSON: ${error.message}` };
27475
27742
  }
27476
27743
  }
27477
27744
  function templateChoice(value) {
@@ -27527,8 +27794,8 @@ function updateNote(workflowId, status) {
27527
27794
  return `Update available: ${status.templateId} is at version ${status.latestVersion}, this workflow has ${status.currentVersion}. Apply it with: taskmarket workflow update-template ${workflowId}`;
27528
27795
  }
27529
27796
  var collect6 = (value, previous = []) => [...previous, value];
27530
- async function readValidTemplate(path9) {
27531
- const parsed = await readJsonFile(path9);
27797
+ async function readValidTemplate(path10) {
27798
+ const parsed = await readJsonFile(path10);
27532
27799
  if ("error" in parsed) {
27533
27800
  printError(parsed.error);
27534
27801
  return null;
@@ -27949,9 +28216,9 @@ function scheduleSettingsBody(projectId, opts) {
27949
28216
  }
27950
28217
  return body;
27951
28218
  }
27952
- async function read2(path9) {
28219
+ async function read2(path10) {
27953
28220
  try {
27954
- printResult(await apiGet(path9));
28221
+ printResult(await apiGet(path10));
27955
28222
  } catch (err) {
27956
28223
  renderFailure(err);
27957
28224
  }
@@ -28278,19 +28545,19 @@ function parseWorkflowText(text) {
28278
28545
  return { error: `The file is not valid JSON: ${error.message}` };
28279
28546
  }
28280
28547
  }
28281
- async function readDocument(path9) {
28282
- if (!path9) return { error: "Pass the workflow document with --file <path> (JSON)" };
28548
+ async function readDocument(path10) {
28549
+ if (!path10) return { error: "Pass the workflow document with --file <path> (JSON)" };
28283
28550
  let text;
28284
28551
  try {
28285
- const buffer = await readFile5(path9);
28552
+ const buffer = await readFile5(path10);
28286
28553
  if (buffer.length > FILE_MAX_BYTES2) {
28287
28554
  return {
28288
- error: `${path9} is ${buffer.length} bytes; a workflow document is at most 64 KiB as JSON`
28555
+ error: `${path10} is ${buffer.length} bytes; a workflow document is at most 64 KiB as JSON`
28289
28556
  };
28290
28557
  }
28291
28558
  text = buffer.toString("utf8");
28292
28559
  } catch (error) {
28293
- return { error: `Unable to read ${path9}: ${error.message}` };
28560
+ return { error: `Unable to read ${path10}: ${error.message}` };
28294
28561
  }
28295
28562
  return parseWorkflowText(text);
28296
28563
  }
@@ -28306,9 +28573,9 @@ function stepKey(value) {
28306
28573
  }
28307
28574
  return trimmed;
28308
28575
  }
28309
- async function read3(path9) {
28576
+ async function read3(path10) {
28310
28577
  try {
28311
- printResult(await apiGet(path9));
28578
+ printResult(await apiGet(path10));
28312
28579
  } catch (err) {
28313
28580
  renderFailure(err);
28314
28581
  }
@@ -28573,13 +28840,13 @@ var deleteCommand3 = new Command150("delete").description(
28573
28840
  { maxAmount: ACTION_FEE_MAX_AMOUNT }
28574
28841
  );
28575
28842
  });
28576
- async function ownerGet(path9) {
28843
+ async function ownerGet(path10) {
28577
28844
  const auth = await signReadAuth();
28578
- return apiGet(path9, { headers: auth?.headers ?? {} });
28845
+ return apiGet(path10, { headers: auth?.headers ?? {} });
28579
28846
  }
28580
- async function ownerRead(path9) {
28847
+ async function ownerRead(path10) {
28581
28848
  try {
28582
- printResult(await ownerGet(path9));
28849
+ printResult(await ownerGet(path10));
28583
28850
  } catch (err) {
28584
28851
  renderFailure(err);
28585
28852
  }
@@ -28787,6 +29054,8 @@ var statusCommand4 = new Command151("status").description("Check whether an emai
28787
29054
  var dropsCommand = new Command151("drops").description("Browse Task Drops and manage email subscriptions to them").addCommand(listCommand9).addCommand(showCommand7).addCommand(subscribeCommand).addCommand(statusCommand4);
28788
29055
 
28789
29056
  // src/commands/hooks.ts
29057
+ import { mkdir, readFile as readFile7, writeFile } from "fs/promises";
29058
+ import path9 from "path";
28790
29059
  import { Command as Command153 } from "commander";
28791
29060
  import { BaseError, ContractFunctionRevertedError, ContractFunctionZeroDataError } from "viem";
28792
29061
 
@@ -28912,6 +29181,84 @@ function submissionsCommandFor(kind) {
28912
29181
  });
28913
29182
  }
28914
29183
 
29184
+ // src/lib/hook-build.ts
29185
+ function token(label) {
29186
+ return label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
29187
+ }
29188
+ var vetoBits = new Map(hookVetoChoices.map((item) => [token(item.label), item.bit]));
29189
+ var observeBits = new Map([
29190
+ ...hookObserveChoices.map((item) => [token(item.label), item.bit]),
29191
+ ["other", 25]
29192
+ ]);
29193
+ var roleValues = new Map(
29194
+ hookCallRoleChoices.map((item) => [token(item.role.replace(/^ROLE_/, "")), item.value])
29195
+ );
29196
+ roleValues.set("anyone", roleValues.get("stranger") ?? 0);
29197
+ var hookVetoNames = [...vetoBits.keys()];
29198
+ var hookObserveNames = [...observeBits.keys()];
29199
+ var hookCallerRoleNames = [...roleValues.keys()];
29200
+ function resolve2(kind, names, known) {
29201
+ return names.map((raw) => {
29202
+ const value = known.get(token(raw));
29203
+ if (value === void 0) {
29204
+ throw new Error(`Unknown ${kind} "${raw}". Choose from: ${[...known.keys()].join(", ")}`);
29205
+ }
29206
+ return value;
29207
+ });
29208
+ }
29209
+ function splitNames(value) {
29210
+ if (value === void 0) return void 0;
29211
+ const list2 = Array.isArray(value) ? value : value.split(",");
29212
+ return list2.map((item) => item.trim()).filter(Boolean);
29213
+ }
29214
+ function resolveHookBuilderInput(choices) {
29215
+ const input = { ...initialHookBuilderInput };
29216
+ for (const [key, value] of Object.entries(choices.fields ?? {})) {
29217
+ if (!(key in initialHookBuilderInput)) throw new Error(`Unknown field "${key}"`);
29218
+ const kind = typeof initialHookBuilderInput[key];
29219
+ input[key] = kind === "string" && typeof value === "object" && value !== null ? JSON.stringify(value) : value;
29220
+ }
29221
+ const chosen = choices.veto !== void 0 || choices.observe !== void 0 || choices.reduce || choices.fee || (choices.onCall?.length ?? 0) > 0;
29222
+ let mask = chosen ? 0 : input.capabilities;
29223
+ for (const bit of resolve2("action to veto", choices.veto ?? [], vetoBits)) mask |= 1 << bit;
29224
+ for (const bit of resolve2("action to observe", choices.observe ?? [], observeBits)) {
29225
+ mask |= 1 << bit;
29226
+ }
29227
+ if (choices.reduce) mask |= 1 << HOOK_BIT_REALLOCATE;
29228
+ if (choices.fee) mask |= 1 << HOOK_BIT_FEE;
29229
+ if (choices.onCall && choices.onCall.length > 0) {
29230
+ mask |= 1 << HOOK_BIT_ON_CALL;
29231
+ input.callRoles = resolve2("caller role", choices.onCall, roleValues).reduce(
29232
+ (roles, value) => (roles | value) >>> 0,
29233
+ 0
29234
+ );
29235
+ }
29236
+ input.capabilities = mask >>> 0;
29237
+ if (choices.configParams !== void 0) input.configParameters = choices.configParams;
29238
+ if (choices.modes !== void 0) {
29239
+ for (const mode of choices.modes) {
29240
+ if (!hookModes.some((name) => name === mode)) {
29241
+ throw new Error(`Unknown task mode "${mode}". Choose from: ${hookModes.join(", ")}`);
29242
+ }
29243
+ }
29244
+ input.modes = choices.modes;
29245
+ }
29246
+ return input;
29247
+ }
29248
+ function buildHook(choices) {
29249
+ const input = resolveHookBuilderInput(choices);
29250
+ const readiness = manifestReadiness(input);
29251
+ return {
29252
+ ready: readiness.ready,
29253
+ problems: readiness.missing,
29254
+ capabilities: effectiveCapabilities(input),
29255
+ callbacks: selectedCallbacks(input),
29256
+ contract: contractName(input.name),
29257
+ manifest: buildHookManifest(input),
29258
+ solidity: buildHookSolidity(input)
29259
+ };
29260
+ }
29261
+
28915
29262
  // src/commands/hooks.ts
28916
29263
  function withV2Declarations(entry) {
28917
29264
  const mask = capabilitiesOf(entry);
@@ -29044,7 +29391,103 @@ var attachmentConfigCommand = new Command153("attachment-config").description(
29044
29391
  renderFailure(err);
29045
29392
  }
29046
29393
  });
29047
- var hooksCommand = new Command153("hooks").description("Browse the hook registry on the selected --network").addCommand(listCommand10).addCommand(showCommand8).addCommand(encodeConfigCommand).addCommand(attachmentConfigCommand).addCommand(submitCommandFor("hook")).addCommand(submissionsCommandFor("hook"));
29394
+ var choiceKeys = /* @__PURE__ */ new Set(["veto", "observe", "reduce", "fee", "onCall", "configParams", "modes"]);
29395
+ async function readBuildFile(file) {
29396
+ let parsed;
29397
+ try {
29398
+ parsed = JSON.parse(await readFile7(file, "utf8"));
29399
+ } catch (err) {
29400
+ throw new Error(`Cannot read ${file} as JSON: ${err.message}`);
29401
+ }
29402
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
29403
+ throw new Error(`${file} must hold a JSON object`);
29404
+ }
29405
+ const record = parsed;
29406
+ const fields = Object.fromEntries(Object.entries(record).filter(([key]) => !choiceKeys.has(key)));
29407
+ const list2 = (key) => record[key] === void 0 ? void 0 : splitNames(record[key]);
29408
+ return {
29409
+ veto: list2("veto"),
29410
+ observe: list2("observe"),
29411
+ reduce: record.reduce === true,
29412
+ fee: record.fee === true,
29413
+ onCall: list2("onCall"),
29414
+ configParams: typeof record.configParams === "string" ? record.configParams : void 0,
29415
+ modes: list2("modes"),
29416
+ fields
29417
+ };
29418
+ }
29419
+ async function hookBuildChoices(opts) {
29420
+ const choices = opts.input ? await readBuildFile(opts.input) : {};
29421
+ const fields = { ...choices.fields };
29422
+ for (const key of [
29423
+ "name",
29424
+ "description",
29425
+ "author",
29426
+ "authorUrl",
29427
+ "repository",
29428
+ "commit",
29429
+ "sourcePath"
29430
+ ]) {
29431
+ if (opts[key] !== void 0) fields[key] = opts[key];
29432
+ }
29433
+ return {
29434
+ ...choices,
29435
+ veto: splitNames(opts.veto) ?? choices.veto,
29436
+ observe: splitNames(opts.observe) ?? choices.observe,
29437
+ reduce: opts.reduce || choices.reduce,
29438
+ fee: opts.fee || choices.fee,
29439
+ onCall: splitNames(opts.onCall) ?? choices.onCall,
29440
+ configParams: opts.configParams ?? choices.configParams,
29441
+ modes: splitNames(opts.mode) ?? choices.modes,
29442
+ fields
29443
+ };
29444
+ }
29445
+ var buildCommand = new Command153("build").description(
29446
+ "Build a Task Hook V2 manifest (schema 2.0.0) and a BaseTMPHookV2 Solidity scaffold from the choices the web hook builder offers (taskmarket.dev/hooks/build). Prints one JSON envelope with 'manifest', 'solidity', 'ready' and 'problems' (what the manifest still needs before it can be submitted)"
29447
+ ).option(
29448
+ "--input <file>",
29449
+ "JSON file with the choices below as keys (veto, observe, reduce, fee, onCall, configParams, modes) and any other web builder field, such as deploymentChainId or hookAddress; flags override it"
29450
+ ).option(
29451
+ "--veto <actions>",
29452
+ `Actions the hook can refuse, comma-separated: ${hookVetoNames.join(", ")}`
29453
+ ).option(
29454
+ "--observe <actions>",
29455
+ `Actions the hook observes after they run, comma-separated: ${hookObserveNames.join(", ")}`
29456
+ ).option(
29457
+ "--reduce",
29458
+ "The hook can reduce or reallocate awards (switches Accept on, forbids an Appeal veto)"
29459
+ ).option("--fee", "The hook can take a hook fee (switches Accept on, forbids an Appeal veto)").option(
29460
+ "--on-call <roles>",
29461
+ `Accept direct calls (onCall) from these roles, comma-separated: ${hookCallerRoleNames.join(", ")}`
29462
+ ).option(
29463
+ "--config-params <abi>",
29464
+ "The hook's own configuration as ABI parameters, such as 'address recipient, uint64 limit'; needs the create veto"
29465
+ ).option(
29466
+ "--mode <modes>",
29467
+ "Task modes the hook serves, comma-separated: bounty, claim, pitch, benchmark, auction (default bounty)"
29468
+ ).option("--name <name>", "Project name").option("--description <text>", "What the hook does").option("--author <name>", "Author name").option("--author-url <url>", "Author HTTPS URL").option("--repository <url>", "Source repository HTTPS URL").option("--commit <sha>", "Source commit SHA").option("--source-path <path>", "Source contract path, such as src/MyHook.sol").option(
29469
+ "--out-dir <dir>",
29470
+ "Also write <slug>.manifest.json and <Contract>.sol to this directory (the envelope still prints)"
29471
+ ).action(async (opts) => {
29472
+ try {
29473
+ const result = buildHook(await hookBuildChoices(opts));
29474
+ let files;
29475
+ if (opts.outDir) {
29476
+ await mkdir(opts.outDir, { recursive: true });
29477
+ files = {
29478
+ manifest: path9.resolve(opts.outDir, `${result.manifest.identity.slug}.manifest.json`),
29479
+ solidity: path9.resolve(opts.outDir, `${result.contract}.sol`)
29480
+ };
29481
+ await writeFile(files.manifest, `${JSON.stringify(result.manifest, null, 2)}
29482
+ `);
29483
+ await writeFile(files.solidity, result.solidity);
29484
+ }
29485
+ printResult(files ? { ...result, files } : result);
29486
+ } catch (err) {
29487
+ renderFailure(err);
29488
+ }
29489
+ });
29490
+ var hooksCommand = new Command153("hooks").description("Browse the hook registry on the selected --network").addCommand(listCommand10).addCommand(showCommand8).addCommand(encodeConfigCommand).addCommand(attachmentConfigCommand).addCommand(buildCommand).addCommand(submitCommandFor("hook")).addCommand(submissionsCommandFor("hook"));
29048
29491
 
29049
29492
  // src/commands/catalog/index.ts
29050
29493
  import { Command as Command154 } from "commander";