@vapi-network/cli 0.16.0 → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -10119,7 +10119,7 @@ var init_call = __esm({
10119
10119
  });
10120
10120
 
10121
10121
  // src/cli.ts
10122
- import { join as join34 } from "node:path";
10122
+ import { join as join35 } from "node:path";
10123
10123
 
10124
10124
  // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/external.js
10125
10125
  var external_exports = {};
@@ -47432,6 +47432,10 @@ var DEFAULT_SPEND_CAPS = {
47432
47432
  };
47433
47433
  var DEFAULT_MAX_PER_TASK_USD = 100;
47434
47434
  var DEFAULT_AUTO_RELEASE_BELOW_USD = 25;
47435
+ var walletTaskPolicySchema = external_exports.object({
47436
+ maxPerTaskUsd: external_exports.number().min(0).optional(),
47437
+ approveAboveUsd: external_exports.number().min(0).optional()
47438
+ });
47435
47439
  var DEFAULT_CEILING_ATOMIC = 5000000n;
47436
47440
  var atomicString = external_exports.string().regex(/^\d+$/, "Expected non-negative atomic units.");
47437
47441
  var spendCapsSchema = external_exports.object({
@@ -71449,10 +71453,21 @@ function readSecretBackend(home = getVapiPaths().directory) {
71449
71453
  }
71450
71454
  async function chooseSecretBackend(options) {
71451
71455
  const env = options.env ?? process.env;
71452
- const osWorks = options.os.platform !== "linux" || await osStoreWorks(options.os);
71456
+ const osWorks = await osStoreUsable(options.os);
71453
71457
  const path = secretBackendPath(options.home);
71454
71458
  return await withVaultLock(path, async () => {
71455
- if (await fileExists(path)) return readSecretBackend(options.home);
71459
+ if (await fileExists(path)) {
71460
+ const pinned = readSecretBackend(options.home);
71461
+ if (pinned === "os" && !hasOsStore(options.os.platform)) {
71462
+ throw new KeystoreError(
71463
+ [
71464
+ `This vAPI home is set to use the OS secret store, which ${options.os.platform} does not have.`,
71465
+ `If vapi setup never finished here, delete ${path}, set ${FILE_SECRET_STORE_PASSWORD_ENV} (at least ${FILE_SECRET_STORE_MIN_PASSWORD} characters) and run vapi setup again.`
71466
+ ].join(" ")
71467
+ );
71468
+ }
71469
+ return pinned;
71470
+ }
71456
71471
  if (await fileExists(join6(options.home, "vault.json"))) return "os";
71457
71472
  let backend;
71458
71473
  if (osWorks) {
@@ -71482,6 +71497,13 @@ async function fileExists(path) {
71482
71497
  throw error61;
71483
71498
  }
71484
71499
  }
71500
+ function hasOsStore(platform2) {
71501
+ return platform2 === "darwin" || platform2 === "win32" || platform2 === "linux";
71502
+ }
71503
+ async function osStoreUsable(store) {
71504
+ if (store.platform === "linux") return await osStoreWorks(store);
71505
+ return hasOsStore(store.platform);
71506
+ }
71485
71507
  async function osStoreWorks(store) {
71486
71508
  if (!store.available) return false;
71487
71509
  try {
@@ -72776,6 +72798,8 @@ var walletEntrySchema = external_exports.object({
72776
72798
  ceilingAtomic: external_exports.string().regex(/^\d+$/).nullable().optional(),
72777
72799
  ceilingSweepAttemptedAt: external_exports.iso.datetime().optional(),
72778
72800
  ceilingSweepPending: ceilingSweepPendingSchema.optional(),
72801
+ // Task limits for an account without an agent profile; absent means the defaults.
72802
+ taskPolicy: walletTaskPolicySchema.optional(),
72779
72803
  routerRefill: routerRefillSchema.optional(),
72780
72804
  routerPendingPurchase: routerPendingPurchaseSchema.optional(),
72781
72805
  link: agentLinkSchema.optional()
@@ -73124,6 +73148,30 @@ var WalletStore = class _WalletStore {
73124
73148
  return structuredClone(entry);
73125
73149
  });
73126
73150
  }
73151
+ /**
73152
+ * Stores task limits for an account without an agent profile, from the latest registry value
73153
+ * while holding its write lock. Returning undefined removes them, so the defaults apply.
73154
+ */
73155
+ async updateTaskPolicy(name, update) {
73156
+ const walletName = assertWalletName(name);
73157
+ return await withRegistryLock(this.registryPath, async () => {
73158
+ const registry2 = await this.readRegistry();
73159
+ const entry = ownWalletEntry(registry2.wallets, walletName);
73160
+ if (!entry) {
73161
+ throw new KeystoreError(unknownWalletMessage(walletName, Object.keys(registry2.wallets)));
73162
+ }
73163
+ const next = update(entry.taskPolicy === void 0 ? void 0 : { ...entry.taskPolicy });
73164
+ const parsed = next === void 0 ? void 0 : walletTaskPolicySchema.parse(next);
73165
+ if (JSON.stringify(parsed) !== JSON.stringify(entry.taskPolicy)) {
73166
+ if (parsed === void 0) delete entry.taskPolicy;
73167
+ else entry.taskPolicy = parsed;
73168
+ await this.writeRegistry(registry2);
73169
+ } else {
73170
+ this.registry = registry2;
73171
+ }
73172
+ return structuredClone(entry);
73173
+ });
73174
+ }
73127
73175
  /** Reads the configured ceiling and the per-day-cap floor for one wallet. */
73128
73176
  ceilingCaps(name) {
73129
73177
  const entry = this.resolve({ name }).entry;
@@ -74531,6 +74579,14 @@ function secretsAllowed(env, streams) {
74531
74579
  import { randomBytes as randomBytes10 } from "node:crypto";
74532
74580
  import { mkdir as mkdir11, readFile as readFile13, readdir as readdir4, rename as rename8, unlink as unlink8, writeFile as writeFile5 } from "node:fs/promises";
74533
74581
  import { join as join11 } from "node:path";
74582
+ var DEFAULT_APPROVE_ABOVE_USD = 0.5;
74583
+ function accountTaskLimitsUnderProfile(current) {
74584
+ const kept = {
74585
+ ...current?.maxPerTaskUsd !== void 0 && current.maxPerTaskUsd < DEFAULT_MAX_PER_TASK_USD ? { maxPerTaskUsd: current.maxPerTaskUsd } : {},
74586
+ ...current?.approveAboveUsd !== void 0 && current.approveAboveUsd < DEFAULT_APPROVE_ABOVE_USD ? { approveAboveUsd: current.approveAboveUsd } : {}
74587
+ };
74588
+ return Object.keys(kept).length === 0 ? void 0 : kept;
74589
+ }
74534
74590
  var DEFAULT_AGENT_TOOLS = ["call.search", "call.inspect", "call.pay"];
74535
74591
  var AGENT_GRANTS = ["read", "delegate", "allocate"];
74536
74592
  var agentProfileShape = {
@@ -74540,7 +74596,7 @@ var agentProfileShape = {
74540
74596
  model: external_exports.string().min(1),
74541
74597
  instructions: external_exports.string().max(2e4),
74542
74598
  verifiedOnly: external_exports.boolean().default(true),
74543
- approveAboveUsd: external_exports.number().min(0).default(0.5),
74599
+ approveAboveUsd: external_exports.number().min(0).default(DEFAULT_APPROVE_ABOVE_USD),
74544
74600
  maxPerTaskUsd: external_exports.number().min(0).default(DEFAULT_MAX_PER_TASK_USD),
74545
74601
  autoReleaseBelowUsd: external_exports.number().min(0).default(DEFAULT_AUTO_RELEASE_BELOW_USD),
74546
74602
  maxSteps: external_exports.number().int().min(1).max(50).default(12),
@@ -78321,6 +78377,7 @@ async function provisionSwarm(opts, home, swarm, accounts) {
78321
78377
  }
78322
78378
  if (member !== void 0) {
78323
78379
  if (!await profileExists(home, member.account)) {
78380
+ const stricter = (await opts.store.updateTaskPolicy(member.account, accountTaskLimitsUnderProfile)).taskPolicy;
78324
78381
  await writeAgentProfile(home, {
78325
78382
  version: 1,
78326
78383
  name: member.account,
@@ -78330,7 +78387,8 @@ async function provisionSwarm(opts, home, swarm, accounts) {
78330
78387
  tools: [...DEFAULT_AGENT_TOOLS],
78331
78388
  grants: roleGrants(member.role),
78332
78389
  verifiedOnly: true,
78333
- approveAboveUsd: 0.5,
78390
+ approveAboveUsd: stricter?.approveAboveUsd ?? 0.5,
78391
+ ...stricter?.maxPerTaskUsd === void 0 ? {} : { maxPerTaskUsd: stricter.maxPerTaskUsd },
78334
78392
  maxSteps: 12,
78335
78393
  paused: false,
78336
78394
  createdAt: (opts.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
@@ -78666,7 +78724,7 @@ function createRunBudget(args) {
78666
78724
  import { mkdir as mkdir15, writeFile as writeFile7 } from "node:fs/promises";
78667
78725
  import { arch, platform, release } from "node:os";
78668
78726
  import { join as join14 } from "node:path";
78669
- var VAPI_CLIENT_VERSION = "0.16.0";
78727
+ var VAPI_CLIENT_VERSION = "0.16.2";
78670
78728
  async function createSupportReport(options) {
78671
78729
  const message = options.message.trim();
78672
78730
  if (!message) throw new Error("Support report message must not be empty.");
@@ -82209,9 +82267,11 @@ var taskV2OperationSchema = external_exports.object({
82209
82267
  step: taskV2StepSchema,
82210
82268
  expectedActor: address2,
82211
82269
  transactionHash: hash4.nullable(),
82212
- plan: taskV2PlanSchema
82270
+ // The API returns the plan only while the step is prepared and re-validated; once the
82271
+ // transaction is submitted or confirmed, and while a recovery scan runs, it sends null.
82272
+ plan: taskV2PlanSchema.nullable()
82213
82273
  }).refine(
82214
- (v) => v.plan.operationId === v.id && v.plan.step === v.step && v.plan.from === v.expectedActor,
82274
+ (v) => v.plan === null || v.plan.operationId === v.id && v.plan.step === v.step && v.plan.from === v.expectedActor,
82215
82275
  "Operation plan binding mismatch"
82216
82276
  ).refine(
82217
82277
  (v) => !["submitted", "confirmed"].includes(v.state) || v.transactionHash !== null,
@@ -83109,934 +83169,383 @@ function taskFundingIntentNonce(intent, expected) {
83109
83169
  return message.nonce.toLowerCase();
83110
83170
  }
83111
83171
 
83112
- // ../core/src/tasks/dispute-fee.ts
83113
- import { createHash as createHash3 } from "node:crypto";
83114
- function disputeFeeBaseUnits(amount4) {
83115
- if (amount4 < 0n) throw new Error("Dispute amount must be nonnegative.");
83116
- const fee = amount4 * 1000n / 10000n;
83117
- return fee < 20000000n ? 20000000n : fee > 500000000n ? 500000000n : fee;
83118
- }
83119
- function taskFeeReservationKey(milestoneId2, action) {
83120
- const bytes = createHash3("sha256").update(JSON.stringify([milestoneId2, action])).digest().subarray(0, 16);
83121
- bytes[6] = bytes[6] & 15 | 80;
83122
- bytes[8] = bytes[8] & 63 | 128;
83123
- const hex5 = bytes.toString("hex");
83124
- return `${hex5.slice(0, 8)}-${hex5.slice(8, 12)}-${hex5.slice(12, 16)}-${hex5.slice(16, 20)}-${hex5.slice(20)}`;
83125
- }
83126
-
83127
- // ../core/src/tasks/money.ts
83128
- function formatBaseUnitsUsd(baseUnits2) {
83129
- const [whole, fraction = ""] = formatUsdc(parseBaseUnits(baseUnits2)).split(".");
83130
- return `${whole}.${fraction.padEnd(2, "0")}`;
83131
- }
83132
- function parseUsdToBaseUnits(text) {
83133
- if (!/^\d+(?:\.\d{1,6})?$/u.test(text)) {
83134
- throw new Error(
83135
- "Task USD amount must be a non-negative decimal with at most six decimal places."
83136
- );
83137
- }
83138
- const [whole = "0", fraction = ""] = text.split(".");
83139
- return BigInt(whole) * 1000000n + BigInt(fraction.padEnd(6, "0"));
83140
- }
83141
- function parseFeeBp(deploymentOrReadiness) {
83142
- if (typeof deploymentOrReadiness !== "object" || deploymentOrReadiness === null || !("feeBp" in deploymentOrReadiness)) {
83143
- return null;
83144
- }
83145
- const feeBp = deploymentOrReadiness.feeBp;
83146
- if (feeBp === void 0 || feeBp === null) return null;
83147
- validateFeeBp(feeBp);
83148
- return feeBp;
83149
- }
83150
- function taskMoney(grossBaseUnits, feeBp) {
83151
- const atomic = parseBaseUnits(grossBaseUnits);
83152
- const gross = amount3(atomic);
83153
- if (feeBp === null) {
83154
- return { gross, fee: null, net: null, feeBp, line: `$${gross.usd} gross \xB7 fee unavailable` };
83155
- }
83156
- validateFeeBp(feeBp);
83157
- const feeAtomic = atomic * BigInt(feeBp) / 10000n;
83158
- const fee = amount3(feeAtomic);
83159
- const net = amount3(atomic - feeAtomic);
83160
- return {
83161
- gross,
83162
- fee,
83163
- net,
83164
- feeBp,
83165
- line: `$${gross.usd} gross \xB7 $${fee.usd} fee \xB7 $${net.usd} net`
83166
- };
83167
- }
83168
- function amount3(atomic) {
83169
- return { usd: formatBaseUnitsUsd(atomic), baseUnits: atomic.toString() };
83170
- }
83171
- function validateFeeBp(value) {
83172
- if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 1e4) {
83173
- throw new Error("Task fee basis points must be an integer from 0 to 10000.");
83174
- }
83175
- }
83176
- function parseBaseUnits(value) {
83177
- if (typeof value === "string" && !/^\d+$/u.test(value) || typeof value !== "bigint" && typeof value !== "string") {
83178
- throw new Error("Task base units must be a non-negative integer.");
83179
- }
83180
- const atomic = BigInt(value);
83181
- if (atomic < 0n) throw new Error("Task base units must be a non-negative integer.");
83182
- return atomic;
83183
- }
83184
- function taskPolicyAtomic(value) {
83185
- if (!Number.isFinite(value) || value < 0)
83186
- throw new Error("Task policy USD amounts must be finite and non-negative.");
83187
- const [mantissa = "0", exponent = "0"] = value.toString().split("e");
83188
- const [whole = "0", fraction = ""] = mantissa.split(".");
83189
- const digits = BigInt(whole + fraction);
83190
- const scale = 6 + Number(exponent) - fraction.length;
83191
- return scale >= 0 ? digits * 10n ** BigInt(scale) : digits / 10n ** BigInt(-scale);
83192
- }
83172
+ // ../core/src/tasks/operation-support.ts
83173
+ import { readFile as readFile18, stat as stat15 } from "node:fs/promises";
83174
+ import { basename as basename2, extname, join as join16 } from "node:path";
83193
83175
 
83194
- // ../core/src/tasks/plan-guard.ts
83195
- var TASKS_CHAIN_ABI = [
83176
+ // ../core/src/tasks/v2-abi.generated.ts
83177
+ var escrowFactoryV2Abi = [
83196
83178
  {
83197
- type: "function",
83198
- name: "createEscrow",
83199
- stateMutability: "nonpayable",
83179
+ type: "constructor",
83200
83180
  inputs: [
83201
- { name: "buyer", type: "address" },
83202
- { name: "token", type: "address" },
83203
- { name: "amount", type: "uint256" },
83204
- { name: "workDuration", type: "uint64" },
83205
- { name: "acceptanceWindow", type: "uint64" },
83206
- { name: "termsHash", type: "bytes32" },
83207
- { name: "salt", type: "bytes32" }
83181
+ { name: "initialOwner", type: "address", internalType: "address" },
83182
+ { name: "feeRouter", type: "address", internalType: "address" },
83183
+ { name: "disputeResolver", type: "address", internalType: "address" },
83184
+ { name: "outcomeRegistry", type: "address", internalType: "address" },
83185
+ { name: "usdc", type: "address", internalType: "address" },
83186
+ { name: "initialFeeBp", type: "uint16", internalType: "uint16" },
83187
+ { name: "maxFeeBp_", type: "uint16", internalType: "uint16" },
83188
+ { name: "maxEscrowAmount_", type: "uint256", internalType: "uint256" },
83189
+ { name: "cancelGrace", type: "uint64", internalType: "uint64" },
83190
+ { name: "lateWindow", type: "uint64", internalType: "uint64" },
83191
+ { name: "minWorkTime", type: "uint64", internalType: "uint64" }
83208
83192
  ],
83209
- outputs: [{ name: "escrow", type: "address" }]
83193
+ stateMutability: "nonpayable"
83210
83194
  },
83211
83195
  {
83212
83196
  type: "function",
83213
- name: "fundWithAuthorization",
83214
- stateMutability: "nonpayable",
83197
+ name: "bountyImplementation",
83198
+ inputs: [],
83199
+ outputs: [{ name: "", type: "address", internalType: "address" }],
83200
+ stateMutability: "view"
83201
+ },
83202
+ {
83203
+ type: "function",
83204
+ name: "createAndFundWithAuthorization",
83215
83205
  inputs: [
83216
- { name: "validAfter", type: "uint256" },
83217
- { name: "validBefore", type: "uint256" },
83218
- { name: "nonce", type: "bytes32" },
83219
- { name: "signature", type: "bytes" }
83206
+ {
83207
+ name: "terms_",
83208
+ type: "tuple",
83209
+ internalType: "struct IEscrowV2.Terms",
83210
+ components: [
83211
+ { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
83212
+ { name: "poster", type: "address", internalType: "address" },
83213
+ { name: "worker", type: "address", internalType: "address" },
83214
+ { name: "termsHash", type: "bytes32", internalType: "bytes32" },
83215
+ { name: "offerTtl", type: "uint64", internalType: "uint64" },
83216
+ { name: "reviewWindow", type: "uint64", internalType: "uint64" },
83217
+ { name: "choiceWindow", type: "uint64", internalType: "uint64" },
83218
+ { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
83219
+ { name: "objectionWindow", type: "uint64", internalType: "uint64" },
83220
+ { name: "workerBondBp", type: "uint16", internalType: "uint16" },
83221
+ { name: "feeBp", type: "uint16", internalType: "uint16" },
83222
+ { name: "winners", type: "uint8", internalType: "uint8" },
83223
+ { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
83224
+ ]
83225
+ },
83226
+ {
83227
+ name: "milestones",
83228
+ type: "tuple[]",
83229
+ internalType: "struct IEscrowV2.Milestone[]",
83230
+ components: [
83231
+ { name: "amount", type: "uint96", internalType: "uint96" },
83232
+ { name: "deadline", type: "uint64", internalType: "uint64" },
83233
+ { name: "status", type: "uint8", internalType: "uint8" },
83234
+ { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
83235
+ ]
83236
+ },
83237
+ { name: "salt", type: "bytes32", internalType: "bytes32" },
83238
+ { name: "from", type: "address", internalType: "address" },
83239
+ { name: "validAfter", type: "uint256", internalType: "uint256" },
83240
+ { name: "validBefore", type: "uint256", internalType: "uint256" },
83241
+ { name: "nonce", type: "bytes32", internalType: "bytes32" },
83242
+ { name: "signature", type: "bytes", internalType: "bytes" }
83220
83243
  ],
83221
- outputs: []
83244
+ outputs: [{ name: "escrow", type: "address", internalType: "address" }],
83245
+ stateMutability: "nonpayable"
83222
83246
  },
83223
83247
  {
83224
83248
  type: "function",
83225
- name: "approve",
83226
- stateMutability: "nonpayable",
83249
+ name: "createEscrow",
83227
83250
  inputs: [
83228
- { name: "spender", type: "address" },
83229
- { name: "amount", type: "uint256" }
83251
+ {
83252
+ name: "terms_",
83253
+ type: "tuple",
83254
+ internalType: "struct IEscrowV2.Terms",
83255
+ components: [
83256
+ { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
83257
+ { name: "poster", type: "address", internalType: "address" },
83258
+ { name: "worker", type: "address", internalType: "address" },
83259
+ { name: "termsHash", type: "bytes32", internalType: "bytes32" },
83260
+ { name: "offerTtl", type: "uint64", internalType: "uint64" },
83261
+ { name: "reviewWindow", type: "uint64", internalType: "uint64" },
83262
+ { name: "choiceWindow", type: "uint64", internalType: "uint64" },
83263
+ { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
83264
+ { name: "objectionWindow", type: "uint64", internalType: "uint64" },
83265
+ { name: "workerBondBp", type: "uint16", internalType: "uint16" },
83266
+ { name: "feeBp", type: "uint16", internalType: "uint16" },
83267
+ { name: "winners", type: "uint8", internalType: "uint8" },
83268
+ { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
83269
+ ]
83270
+ },
83271
+ {
83272
+ name: "milestones",
83273
+ type: "tuple[]",
83274
+ internalType: "struct IEscrowV2.Milestone[]",
83275
+ components: [
83276
+ { name: "amount", type: "uint96", internalType: "uint96" },
83277
+ { name: "deadline", type: "uint64", internalType: "uint64" },
83278
+ { name: "status", type: "uint8", internalType: "uint8" },
83279
+ { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
83280
+ ]
83281
+ },
83282
+ { name: "salt", type: "bytes32", internalType: "bytes32" }
83230
83283
  ],
83231
- outputs: [{ name: "ok", type: "bool" }]
83284
+ outputs: [{ name: "escrow", type: "address", internalType: "address" }],
83285
+ stateMutability: "nonpayable"
83232
83286
  },
83233
83287
  {
83234
83288
  type: "function",
83235
- name: "depositFunds",
83236
- stateMutability: "nonpayable",
83289
+ name: "feeBp",
83237
83290
  inputs: [],
83238
- outputs: []
83291
+ outputs: [{ name: "", type: "uint16", internalType: "uint16" }],
83292
+ stateMutability: "view"
83239
83293
  },
83240
83294
  {
83241
83295
  type: "function",
83242
- name: "submitDelivery",
83243
- stateMutability: "nonpayable",
83244
- inputs: [{ name: "manifestHash", type: "bytes32" }],
83245
- outputs: []
83296
+ name: "implementation",
83297
+ inputs: [],
83298
+ outputs: [{ name: "", type: "address", internalType: "address" }],
83299
+ stateMutability: "view"
83246
83300
  },
83247
83301
  {
83248
83302
  type: "function",
83249
- name: "releaseFunds",
83250
- stateMutability: "nonpayable",
83303
+ name: "isEscrow",
83304
+ inputs: [{ name: "escrow", type: "address", internalType: "address" }],
83305
+ outputs: [{ name: "registered", type: "bool", internalType: "bool" }],
83306
+ stateMutability: "view"
83307
+ },
83308
+ {
83309
+ type: "function",
83310
+ name: "maxEscrowAmount",
83251
83311
  inputs: [],
83252
- outputs: []
83312
+ outputs: [{ name: "", type: "uint256", internalType: "uint256" }],
83313
+ stateMutability: "view"
83253
83314
  },
83254
- { type: "function", name: "refundBuyer", stateMutability: "nonpayable", inputs: [], outputs: [] },
83255
83315
  {
83256
83316
  type: "function",
83257
- name: "raiseDispute",
83258
- stateMutability: "nonpayable",
83259
- inputs: [{ name: "evidenceHash", type: "bytes32" }],
83260
- outputs: []
83317
+ name: "maxFeeBp",
83318
+ inputs: [],
83319
+ outputs: [{ name: "", type: "uint16", internalType: "uint16" }],
83320
+ stateMutability: "view"
83261
83321
  },
83262
83322
  {
83263
83323
  type: "function",
83264
- name: "submitCounterEvidence",
83265
- stateMutability: "nonpayable",
83266
- inputs: [{ name: "evidenceHash", type: "bytes32" }],
83267
- outputs: []
83324
+ name: "owner",
83325
+ inputs: [],
83326
+ outputs: [{ name: "", type: "address", internalType: "address" }],
83327
+ stateMutability: "view"
83268
83328
  },
83329
+ { type: "function", name: "pause", inputs: [], outputs: [], stateMutability: "nonpayable" },
83269
83330
  {
83270
83331
  type: "function",
83271
- name: "resolveUnmatchedDispute",
83272
- stateMutability: "nonpayable",
83332
+ name: "paused",
83273
83333
  inputs: [],
83274
- outputs: []
83334
+ outputs: [{ name: "", type: "bool", internalType: "bool" }],
83335
+ stateMutability: "view"
83275
83336
  },
83276
83337
  {
83277
83338
  type: "function",
83278
- name: "timeoutRefund",
83279
- stateMutability: "nonpayable",
83339
+ name: "paymentToken",
83280
83340
  inputs: [],
83281
- outputs: []
83341
+ outputs: [{ name: "", type: "address", internalType: "address" }],
83342
+ stateMutability: "view"
83282
83343
  },
83283
- { type: "function", name: "finalize", stateMutability: "nonpayable", inputs: [], outputs: [] },
83284
83344
  {
83285
83345
  type: "function",
83286
- name: "disputeFee",
83287
- stateMutability: "view",
83346
+ name: "predictBountyEscrow",
83347
+ inputs: [
83348
+ {
83349
+ name: "terms_",
83350
+ type: "tuple",
83351
+ internalType: "struct IEscrowV2.Terms",
83352
+ components: [
83353
+ { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
83354
+ { name: "poster", type: "address", internalType: "address" },
83355
+ { name: "worker", type: "address", internalType: "address" },
83356
+ { name: "termsHash", type: "bytes32", internalType: "bytes32" },
83357
+ { name: "offerTtl", type: "uint64", internalType: "uint64" },
83358
+ { name: "reviewWindow", type: "uint64", internalType: "uint64" },
83359
+ { name: "choiceWindow", type: "uint64", internalType: "uint64" },
83360
+ { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
83361
+ { name: "objectionWindow", type: "uint64", internalType: "uint64" },
83362
+ { name: "workerBondBp", type: "uint16", internalType: "uint16" },
83363
+ { name: "feeBp", type: "uint16", internalType: "uint16" },
83364
+ { name: "winners", type: "uint8", internalType: "uint8" },
83365
+ { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
83366
+ ]
83367
+ },
83368
+ {
83369
+ name: "milestones",
83370
+ type: "tuple[]",
83371
+ internalType: "struct IEscrowV2.Milestone[]",
83372
+ components: [
83373
+ { name: "amount", type: "uint96", internalType: "uint96" },
83374
+ { name: "deadline", type: "uint64", internalType: "uint64" },
83375
+ { name: "status", type: "uint8", internalType: "uint8" },
83376
+ { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
83377
+ ]
83378
+ },
83379
+ { name: "salt", type: "bytes32", internalType: "bytes32" }
83380
+ ],
83381
+ outputs: [{ name: "", type: "address", internalType: "address" }],
83382
+ stateMutability: "view"
83383
+ },
83384
+ {
83385
+ type: "function",
83386
+ name: "predictEscrow",
83387
+ inputs: [
83388
+ {
83389
+ name: "terms_",
83390
+ type: "tuple",
83391
+ internalType: "struct IEscrowV2.Terms",
83392
+ components: [
83393
+ { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
83394
+ { name: "poster", type: "address", internalType: "address" },
83395
+ { name: "worker", type: "address", internalType: "address" },
83396
+ { name: "termsHash", type: "bytes32", internalType: "bytes32" },
83397
+ { name: "offerTtl", type: "uint64", internalType: "uint64" },
83398
+ { name: "reviewWindow", type: "uint64", internalType: "uint64" },
83399
+ { name: "choiceWindow", type: "uint64", internalType: "uint64" },
83400
+ { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
83401
+ { name: "objectionWindow", type: "uint64", internalType: "uint64" },
83402
+ { name: "workerBondBp", type: "uint16", internalType: "uint16" },
83403
+ { name: "feeBp", type: "uint16", internalType: "uint16" },
83404
+ { name: "winners", type: "uint8", internalType: "uint8" },
83405
+ { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
83406
+ ]
83407
+ },
83408
+ {
83409
+ name: "milestones",
83410
+ type: "tuple[]",
83411
+ internalType: "struct IEscrowV2.Milestone[]",
83412
+ components: [
83413
+ { name: "amount", type: "uint96", internalType: "uint96" },
83414
+ { name: "deadline", type: "uint64", internalType: "uint64" },
83415
+ { name: "status", type: "uint8", internalType: "uint8" },
83416
+ { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
83417
+ ]
83418
+ },
83419
+ { name: "salt", type: "bytes32", internalType: "bytes32" }
83420
+ ],
83421
+ outputs: [{ name: "", type: "address", internalType: "address" }],
83422
+ stateMutability: "view"
83423
+ },
83424
+ {
83425
+ type: "function",
83426
+ name: "renounceOwnership",
83288
83427
  inputs: [],
83289
- outputs: [{ name: "fee", type: "uint256" }]
83428
+ outputs: [],
83429
+ stateMutability: "nonpayable"
83290
83430
  },
83291
83431
  {
83292
83432
  type: "function",
83293
- name: "allowance",
83294
- stateMutability: "view",
83433
+ name: "setFeeBp",
83434
+ inputs: [{ name: "newFeeBp", type: "uint16", internalType: "uint16" }],
83435
+ outputs: [],
83436
+ stateMutability: "nonpayable"
83437
+ },
83438
+ {
83439
+ type: "function",
83440
+ name: "setMaxEscrowAmount",
83441
+ inputs: [{ name: "newAmount", type: "uint256", internalType: "uint256" }],
83442
+ outputs: [],
83443
+ stateMutability: "nonpayable"
83444
+ },
83445
+ {
83446
+ type: "function",
83447
+ name: "transferOwnership",
83448
+ inputs: [{ name: "newOwner", type: "address", internalType: "address" }],
83449
+ outputs: [],
83450
+ stateMutability: "nonpayable"
83451
+ },
83452
+ { type: "function", name: "unpause", inputs: [], outputs: [], stateMutability: "nonpayable" },
83453
+ {
83454
+ type: "event",
83455
+ name: "EscrowCreated",
83295
83456
  inputs: [
83296
- { name: "owner", type: "address" },
83297
- { name: "spender", type: "address" }
83457
+ { name: "escrow", type: "address", indexed: true, internalType: "address" },
83458
+ { name: "poster", type: "address", indexed: true, internalType: "address" },
83459
+ { name: "termsHash", type: "bytes32", indexed: true, internalType: "bytes32" },
83460
+ { name: "salt", type: "bytes32", indexed: false, internalType: "bytes32" },
83461
+ { name: "feeBp", type: "uint16", indexed: false, internalType: "uint16" }
83298
83462
  ],
83299
- outputs: [{ name: "amount", type: "uint256" }]
83300
- }
83301
- ];
83302
- var TASKS_READ_ABI = parseAbi([
83303
- "function paymentToken() view returns (address)",
83304
- "function isEscrow(address escrow) view returns (bool)",
83305
- "function name() view returns (string)",
83306
- "function version() view returns (string)",
83307
- "function buyer() view returns (address)",
83308
- "function seller() view returns (address)",
83309
- "function token() view returns (address)",
83310
- "function amount() view returns (uint256)",
83311
- "function termsHash() view returns (bytes32)",
83312
- "function state() view returns (uint8)",
83313
- "function offerDeadline() view returns (uint64)",
83314
- "function workDeadline() view returns (uint64)",
83315
- "function reviewDeadline() view returns (uint64)",
83316
- "function disputedAt() view returns (uint64)",
83317
- "function counterEvidenceDeadline() view returns (uint64)",
83318
- "function resolution() view returns (uint8)",
83319
- "function disputeFee() view returns (uint256)",
83320
- "function predictEscrow(address seller, bytes32 salt) view returns (address)"
83321
- ]);
83322
- function verifyPlan(operation, expectation) {
83323
- const fail2 = (message) => {
83324
- throw new TasksChainError(`Unsafe transaction plan: ${message}`, false);
83325
- };
83326
- const plan = operation.plan;
83327
- if (!plan) throw new TasksChainError("Unsafe transaction plan: missing plan", false);
83328
- if (plan.operationId !== operation.id || plan.step !== operation.step) fail2("operation mismatch");
83329
- if (!expectation.steps.includes(plan.step)) fail2("unexpected step");
83330
- if (!operation.expectedActor || getAddress(operation.expectedActor) !== getAddress(expectation.signer) || getAddress(plan.from) !== getAddress(expectation.signer))
83331
- fail2("unexpected signer");
83332
- if (plan.chainId !== expectation.deployment.chainId || plan.network !== expectation.deployment.network || plan.network !== `eip155:${plan.chainId}` || plan.value !== "0")
83333
- fail2("unexpected network or value");
83334
- if (expectation.milestone.network !== plan.network || expectation.milestone.asset.toLowerCase() !== `${plan.network}/erc20:${expectation.deployment.usdc}`.toLowerCase())
83335
- fail2("milestone asset mismatch");
83336
- const target = plan.step === "create-escrow" ? expectation.deployment.escrowContract : plan.step === "approve-usdc" ? expectation.deployment.usdc : expectation.milestone.escrowContract;
83337
- if (getAddress(plan.to) !== getAddress(target)) fail2("unexpected target");
83338
- const decoded = (() => {
83339
- try {
83340
- return decodeFunctionData({ abi: TASKS_CHAIN_ABI, data: plan.data });
83341
- } catch {
83342
- return fail2("invalid calldata");
83343
- }
83344
- })();
83345
- const expectedName = {
83346
- "create-escrow": "createEscrow",
83347
- "fund-with-authorization": "fundWithAuthorization",
83348
- "approve-usdc": "approve",
83349
- "deposit-funds": "depositFunds",
83350
- "submit-delivery": "submitDelivery",
83351
- "release-funds": "releaseFunds",
83352
- "refund-buyer": "refundBuyer",
83353
- "raise-dispute": "raiseDispute",
83354
- "submit-counter-evidence": "submitCounterEvidence",
83355
- "resolve-unmatched-dispute": "resolveUnmatchedDispute",
83356
- "timeout-refund": "timeoutRefund",
83357
- finalize: "finalize"
83358
- };
83359
- if (decoded.functionName !== expectedName[plan.step]) fail2("unexpected selector");
83360
- const args = [...decoded.args ?? []];
83361
- const eq = (a, b) => typeof a === "string" && typeof b === "string" ? a.toLowerCase() === b.toLowerCase() : a === b;
83362
- const requireArgs = (values) => {
83363
- if (args.length !== values.length || args.some((v, i2) => !eq(v, values[i2])))
83364
- fail2("unexpected arguments");
83365
- };
83366
- if (plan.step === "create-escrow") {
83367
- if (!expectation.seller || getAddress(expectation.signer) !== getAddress(expectation.seller))
83368
- fail2("createEscrow requires the locally bound seller");
83369
- const workDuration = expectation.workDurationSeconds ?? expectation.milestone.terms.workDurationSeconds ?? getTrustedTasksDurations(expectation.deployment.chainId).workDurationSeconds;
83370
- if (workDuration === void 0) fail2("missing trusted work duration");
83371
- requireArgs([
83372
- expectation.buyer,
83373
- expectation.deployment.usdc,
83374
- BigInt(expectation.milestone.amountBaseUnits),
83375
- BigInt(workDuration),
83376
- BigInt(
83377
- expectation.reviewWindowSeconds ?? expectation.milestone.terms.acceptanceWindowSeconds
83378
- ),
83379
- expectation.milestone.termsHash,
83380
- keccak256(stringToHex(expectation.milestone.id))
83381
- ]);
83382
- } else if (plan.step === "fund-with-authorization") {
83383
- const a = expectation.authorization;
83384
- if (!a)
83385
- throw new TasksChainError("Unsafe transaction plan: missing local authorization", false);
83386
- requireArgs([BigInt(a.validAfter), BigInt(a.validBefore), a.nonce, a.signature]);
83387
- } else if (plan.step === "approve-usdc") {
83388
- if (expectation.approveAmount === void 0) fail2("missing verified approval amount");
83389
- requireArgs([expectation.milestone.escrowContract, expectation.approveAmount]);
83390
- } else if (plan.step === "submit-delivery") {
83391
- if (!expectation.manifestHash) fail2("missing manifest hash");
83392
- requireArgs([expectation.manifestHash]);
83393
- } else if (plan.step === "raise-dispute" || plan.step === "submit-counter-evidence") {
83394
- if (!expectation.evidenceHash) fail2("missing evidence hash");
83395
- requireArgs([expectation.evidenceHash]);
83396
- } else requireArgs([]);
83397
- }
83398
-
83399
- // ../core/src/tasks/chain-verification.ts
83400
- var TasksPartiesNotBoundError = class extends TasksValidationError {
83401
- constructor() {
83402
- super(
83403
- "The task parties are not bound on this machine. Sign the scope with `vapi task sign` on this machine first; an explicit --counterparty only confirms an existing binding."
83404
- );
83405
- this.name = "TasksPartiesNotBoundError";
83406
- }
83407
- };
83408
- async function verifyDeployment(ready, rpc, overrides) {
83409
- const factory = getTrustedTasksFactory(ready.chainId, overrides);
83410
- if (!factory)
83411
- throw new TasksChainError(
83412
- `No trusted Tasks escrow factory is configured for chain ${ready.chainId}. Set VAPI_TASKS_ESCROW_FACTORY_${ready.chainId}.`,
83413
- false,
83414
- { authorizationExposed: false }
83415
- );
83416
- if (!isAddressEqual(factory, ready.escrowContract))
83417
- throw new TasksValidationError(
83418
- "The Tasks readiness factory does not match the trusted factory."
83419
- );
83420
- if (await rpc.getChainId() !== ready.chainId)
83421
- throw new TasksValidationError("The RPC chain ID does not match the task deployment.");
83422
- const token = await rpc.readContract({
83423
- address: factory,
83424
- abi: TASKS_READ_ABI,
83425
- functionName: "paymentToken"
83426
- });
83427
- if (!isAddressEqual(token, ready.usdc))
83428
- throw new TasksValidationError(
83429
- "The Tasks readiness token does not match the trusted factory payment token."
83430
- );
83431
- const [name, version5] = await Promise.all([
83432
- rpc.readContract({ address: token, abi: TASKS_READ_ABI, functionName: "name" }),
83433
- rpc.readContract({ address: token, abi: TASKS_READ_ABI, functionName: "version" })
83434
- ]);
83435
- const domain2 = { name, version: version5, chainId: ready.chainId, verifyingContract: getAddress(token) };
83436
- if (ready.eip3009Domain && (ready.eip3009Domain.name !== name || ready.eip3009Domain.version !== version5 || ready.eip3009Domain.chainId !== ready.chainId || !isAddressEqual(ready.eip3009Domain.verifyingContract, token)))
83437
- throw new TasksValidationError(
83438
- "The funding authorization domain does not match the onchain token domain."
83439
- );
83440
- return {
83441
- ...ready,
83442
- escrowContract: getAddress(factory),
83443
- usdc: getAddress(token),
83444
- eip3009Domain: domain2
83445
- };
83446
- }
83447
- async function verifyScope(client, signer, selected, ready, verb, steps, options = {}) {
83448
- const { scopes } = await client.getScopes(selected.workOrderId);
83449
- const matches = scopes.filter(
83450
- (scope2) => scope2.state === "accepted" && scope2.milestoneId === selected.id
83451
- );
83452
- if (matches.length !== 1)
83453
- throw new TasksValidationError("The task milestone requires one accepted signed scope.");
83454
- const scope = matches[0];
83455
- const payload = scope.signingPayload;
83456
- const frozen = freezeScopeTerms(scope.structuredTerms, scope.brief);
83457
- if (scope.workOrderId !== selected.workOrderId || payload.workOrderId !== selected.workOrderId || payload.trancheOrdinal !== selected.ordinal || scope.trancheOrdinal !== selected.ordinal || payload.scopeVersion !== scope.version || frozen.termsHash !== scope.termsHash || frozen.termsHash !== payload.termsHash || frozen.termsHash !== selected.termsHash)
83458
- throw new TasksValidationError(
83459
- "The accepted task scope does not match its locally verified terms hash and milestone."
83460
- );
83461
- if (!scope.counterpartyAddress || !scope.counterpartySignature || isAddressEqual(scope.proposerAddress, scope.counterpartyAddress) || !(isAddressEqual(signer, scope.proposerAddress) || isAddressEqual(signer, scope.counterpartyAddress)))
83462
- throw new TasksValidationError(
83463
- "The local signer is not one of the two accepted scope parties."
83464
- );
83465
- const message = canonicalJson(payload);
83466
- const signatures = await Promise.all([
83467
- verifyMessage({
83468
- address: scope.proposerAddress,
83469
- message,
83470
- signature: scope.proposerSignature
83471
- }),
83472
- verifyMessage({
83473
- address: scope.counterpartyAddress,
83474
- message,
83475
- signature: scope.counterpartySignature
83476
- })
83477
- ]);
83478
- if (signatures.some((valid) => !valid))
83479
- throw new TasksValidationError("Both accepted task scope signatures must verify.");
83480
- const terms = frozen.structured;
83481
- if (terms.budget.network !== ready.network || terms.budget.asset.toLowerCase() !== `${ready.network}/erc20:${ready.usdc}`.toLowerCase() || !isAddressEqual(terms.escrow.contract, ready.escrowContract) || selected.network !== terms.budget.network || selected.asset.toLowerCase() !== terms.budget.asset.toLowerCase() || selected.amountBaseUnits !== terms.budget.amountBaseUnits)
83482
- throw new TasksValidationError(
83483
- "The signed task scope asset, factory or amount does not match the deployment and milestone."
83484
- );
83485
- const identity = {
83486
- orderId: selected.workOrderId,
83487
- trancheOrdinal: selected.ordinal,
83488
- scopeVersion: scope.version,
83489
- termsHash: frozen.termsHash,
83490
- self: getAddress(signer)
83491
- };
83492
- const binding = await options.bindings?.get(identity);
83493
- if (!binding) throw new TasksPartiesNotBoundError();
83494
- if (options.counterparty && !isAddressEqual(binding.counterparty, options.counterparty))
83495
- throw new TasksValidationError(
83496
- "The confirmed counterparty differs from the locally bound parties."
83497
- );
83498
- if (!isAddressEqual(binding.self, signer) || binding.orderId !== identity.orderId || binding.trancheOrdinal !== identity.trancheOrdinal || binding.scopeVersion !== identity.scopeVersion || binding.termsHash.toLowerCase() !== identity.termsHash.toLowerCase() || ![scope.proposerAddress, scope.counterpartyAddress].every(
83499
- (address10) => isAddressEqual(address10, binding.self) || isAddressEqual(address10, binding.counterparty)
83500
- ))
83501
- throw new TasksValidationError(
83502
- "The accepted scope parties do not match the locally bound parties."
83503
- );
83504
- const buyer = getAddress(binding.role === "client" ? binding.self : binding.counterparty);
83505
- const seller = getAddress(binding.role === "provider" ? binding.self : binding.counterparty);
83506
- if (verb === "createEscrow" && !isAddressEqual(signer, seller))
83507
- throw new TasksValidationError("Task createEscrow requires the locally bound seller's wallet.");
83508
- const workDurationSeconds = terms.workDurationSeconds ?? getTrustedTasksDurations(ready.chainId, options.trustedDurations).workDurationSeconds;
83509
- if (workDurationSeconds === void 0)
83510
- throw new TasksValidationError(
83511
- "The signed task scope has no work duration and no trusted default is configured."
83512
- );
83513
- return {
83514
- signer,
83515
- buyer,
83516
- seller,
83517
- parties: [buyer, seller],
83518
- workDurationSeconds,
83519
- ...verb === "fund" ? { approveAmount: BigInt(terms.budget.amountBaseUnits) } : {},
83520
- reviewWindowSeconds: terms.acceptanceWindowSeconds,
83521
- nowSeconds: BigInt(Math.floor((options.now ?? (() => /* @__PURE__ */ new Date()))().getTime() / 1e3)),
83522
- verb,
83523
- deployment: ready,
83524
- milestone: {
83525
- ...selected,
83526
- terms,
83527
- termsHash: frozen.termsHash,
83528
- amountBaseUnits: terms.budget.amountBaseUnits
83529
- },
83530
- steps
83531
- };
83532
- }
83533
- async function verifyClone(rpc, expected, checkState) {
83534
- if (expected.verb === "createEscrow") return;
83535
- const clone2 = expected.milestone.escrowContract;
83536
- const registered = await rpc.readContract({
83537
- address: expected.deployment.escrowContract,
83538
- abi: TASKS_READ_ABI,
83539
- functionName: "isEscrow",
83540
- args: [clone2]
83541
- });
83542
- if (!registered)
83543
- throw new TasksValidationError(
83544
- "The task escrow clone is not registered by the trusted factory."
83545
- );
83546
- const predicted = await rpc.readContract({
83547
- address: expected.deployment.escrowContract,
83548
- abi: TASKS_READ_ABI,
83549
- functionName: "predictEscrow",
83550
- args: [expected.seller, keccak256(stringToHex(expected.milestone.id))]
83551
- });
83552
- if (!isAddressEqual(predicted, clone2))
83553
- throw new TasksValidationError(
83554
- "The escrow clone does not match the signed milestone salt and bound seller."
83555
- );
83556
- const read = (functionName) => rpc.readContract({ address: clone2, abi: TASKS_READ_ABI, functionName });
83557
- const [
83558
- buyer,
83559
- seller,
83560
- token,
83561
- amount4,
83562
- termsHash,
83563
- state,
83564
- resolution,
83565
- offerDeadline,
83566
- workDeadline,
83567
- reviewDeadline,
83568
- disputedAt,
83569
- counterEvidenceDeadline,
83570
- slot0,
83571
- slot6,
83572
- slot7
83573
- ] = await Promise.all([
83574
- read("buyer"),
83575
- read("seller"),
83576
- read("token"),
83577
- read("amount"),
83578
- read("termsHash"),
83579
- read("state"),
83580
- read("resolution"),
83581
- read("offerDeadline"),
83582
- read("workDeadline"),
83583
- read("reviewDeadline"),
83584
- read("disputedAt"),
83585
- read("counterEvidenceDeadline"),
83586
- rpc.getStorageAt({ address: clone2, slot: "0x0" }),
83587
- rpc.getStorageAt({ address: clone2, slot: "0x6" }),
83588
- rpc.getStorageAt({ address: clone2, slot: "0x7" })
83589
- ]);
83590
- if (isAddressEqual(buyer, seller) || !isAddressEqual(buyer, expected.buyer) || !isAddressEqual(seller, expected.seller) || !isAddressEqual(token, expected.deployment.usdc) || amount4 !== BigInt(expected.milestone.amountBaseUnits) || termsHash.toLowerCase() !== expected.milestone.termsHash.toLowerCase())
83591
- throw new TasksValidationError(
83592
- "The onchain escrow parties, token, amount or terms hash do not match the signed scope."
83593
- );
83594
- const s0 = storageWord(slot0);
83595
- const s6 = storageWord(slot6);
83596
- const s7 = storageWord(slot7);
83597
- if (field(s0, 0, 1) !== BigInt(state) || field(s0, 1, 1) !== BigInt(resolution) || !isAddressEqual(storageAddress(s0, 2), buyer) || field(s6, 0, 8) !== offerDeadline || field(s6, 8, 8) !== workDeadline || field(s6, 16, 8) !== reviewDeadline || field(s6, 24, 8) !== disputedAt || field(s7, 0, 8) !== counterEvidenceDeadline)
83598
- throw new TasksValidationError("unsupported escrow layout");
83599
- if (field(s7, 8, 8) !== BigInt(expected.workDurationSeconds) || field(s7, 16, 8) !== BigInt(expected.reviewWindowSeconds))
83600
- throw new TasksValidationError(
83601
- "The onchain escrow durations do not match the signed terms and trusted defaults."
83602
- );
83603
- const actor = expected.verb === "fund" || expected.verb === "release" ? buyer : expected.verb === "deliver" || expected.verb === "refund" ? seller : expected.signer;
83604
- if (!isAddressEqual(actor, expected.signer))
83605
- throw new TasksValidationError(
83606
- `Task ${expected.verb} requires the onchain escrow party's local wallet.`
83607
- );
83608
- const states = {
83609
- fund: [1],
83610
- deliver: [2],
83611
- release: [3],
83612
- refund: [2, 3],
83613
- dispute: [2, 3],
83614
- "counter-evidence": [4],
83615
- "resolve-unmatched": [4]
83616
- };
83617
- if (checkState && !states[expected.verb]?.includes(state))
83618
- throw new TasksValidationError(
83619
- `The onchain escrow state is not eligible for task ${expected.verb}.`
83620
- );
83621
- if (["dispute", "counter-evidence"].includes(expected.verb)) {
83622
- const fee = disputeFeeBaseUnits(amount4);
83623
- if (await read("disputeFee") !== fee)
83624
- throw new TasksValidationError(
83625
- "The onchain dispute fee does not match the verified amount fee rule."
83626
- );
83627
- expected.disputeFee = fee;
83628
- expected.approveAmount = fee;
83629
- }
83630
- if (checkState && ["counter-evidence", "resolve-unmatched"].includes(expected.verb)) {
83631
- const slot8 = storageWord(await rpc.getStorageAt({ address: clone2, slot: "0x8" }));
83632
- const opener = storageAddress(slot8, 0);
83633
- const submitted = field(slot8, 20, 1);
83634
- if (!isAddressEqual(opener, buyer) && !isAddressEqual(opener, seller) || submitted > 1n || field(slot8, 21, 11) !== 0n)
83635
- throw new TasksValidationError("unsupported escrow layout");
83636
- const now = expected.nowSeconds;
83637
- if (now === void 0)
83638
- throw new TasksValidationError("A trusted clock is required for dispute eligibility.");
83639
- if (submitted === 1n)
83640
- throw new TasksValidationError(
83641
- "Counter-evidence has already been submitted for this dispute."
83642
- );
83643
- if (expected.verb === "counter-evidence") {
83644
- if (isAddressEqual(opener, expected.signer))
83645
- throw new TasksValidationError("Only the non-opener party can submit counter-evidence.");
83646
- if (now >= counterEvidenceDeadline)
83647
- throw new TasksValidationError("The counter-evidence deadline has passed.");
83648
- } else if (now <= counterEvidenceDeadline)
83649
- throw new TasksValidationError(
83650
- "The counter-evidence deadline has not passed; unmatched resolution is unavailable."
83651
- );
83652
- }
83653
- expected.offerDeadline = offerDeadline;
83654
- }
83655
- function storageWord(value) {
83656
- if (!value || !/^0x[0-9a-fA-F]{64}$/.test(value))
83657
- throw new TasksValidationError("unsupported escrow layout");
83658
- return BigInt(value);
83659
- }
83660
- function field(word, offset, bytes) {
83661
- return word >> BigInt(offset * 8) & (1n << BigInt(bytes * 8)) - 1n;
83662
- }
83663
- function storageAddress(word, offset) {
83664
- return getAddress(`0x${field(word, offset, 20).toString(16).padStart(40, "0")}`);
83665
- }
83666
-
83667
- // ../core/src/tasks/v2-abi.generated.ts
83668
- var escrowFactoryV2Abi = [
83669
- {
83670
- type: "constructor",
83671
- inputs: [
83672
- { name: "initialOwner", type: "address", internalType: "address" },
83673
- { name: "feeRouter", type: "address", internalType: "address" },
83674
- { name: "disputeResolver", type: "address", internalType: "address" },
83675
- { name: "outcomeRegistry", type: "address", internalType: "address" },
83676
- { name: "usdc", type: "address", internalType: "address" },
83677
- { name: "initialFeeBp", type: "uint16", internalType: "uint16" },
83678
- { name: "maxFeeBp_", type: "uint16", internalType: "uint16" },
83679
- { name: "maxEscrowAmount_", type: "uint256", internalType: "uint256" },
83680
- { name: "cancelGrace", type: "uint64", internalType: "uint64" },
83681
- { name: "lateWindow", type: "uint64", internalType: "uint64" },
83682
- { name: "minWorkTime", type: "uint64", internalType: "uint64" }
83683
- ],
83684
- stateMutability: "nonpayable"
83685
- },
83686
- {
83687
- type: "function",
83688
- name: "bountyImplementation",
83689
- inputs: [],
83690
- outputs: [{ name: "", type: "address", internalType: "address" }],
83691
- stateMutability: "view"
83692
- },
83693
- {
83694
- type: "function",
83695
- name: "createAndFundWithAuthorization",
83696
- inputs: [
83697
- {
83698
- name: "terms_",
83699
- type: "tuple",
83700
- internalType: "struct IEscrowV2.Terms",
83701
- components: [
83702
- { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
83703
- { name: "poster", type: "address", internalType: "address" },
83704
- { name: "worker", type: "address", internalType: "address" },
83705
- { name: "termsHash", type: "bytes32", internalType: "bytes32" },
83706
- { name: "offerTtl", type: "uint64", internalType: "uint64" },
83707
- { name: "reviewWindow", type: "uint64", internalType: "uint64" },
83708
- { name: "choiceWindow", type: "uint64", internalType: "uint64" },
83709
- { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
83710
- { name: "objectionWindow", type: "uint64", internalType: "uint64" },
83711
- { name: "workerBondBp", type: "uint16", internalType: "uint16" },
83712
- { name: "feeBp", type: "uint16", internalType: "uint16" },
83713
- { name: "winners", type: "uint8", internalType: "uint8" },
83714
- { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
83715
- ]
83716
- },
83717
- {
83718
- name: "milestones",
83719
- type: "tuple[]",
83720
- internalType: "struct IEscrowV2.Milestone[]",
83721
- components: [
83722
- { name: "amount", type: "uint96", internalType: "uint96" },
83723
- { name: "deadline", type: "uint64", internalType: "uint64" },
83724
- { name: "status", type: "uint8", internalType: "uint8" },
83725
- { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
83726
- ]
83727
- },
83728
- { name: "salt", type: "bytes32", internalType: "bytes32" },
83729
- { name: "from", type: "address", internalType: "address" },
83730
- { name: "validAfter", type: "uint256", internalType: "uint256" },
83731
- { name: "validBefore", type: "uint256", internalType: "uint256" },
83732
- { name: "nonce", type: "bytes32", internalType: "bytes32" },
83733
- { name: "signature", type: "bytes", internalType: "bytes" }
83734
- ],
83735
- outputs: [{ name: "escrow", type: "address", internalType: "address" }],
83736
- stateMutability: "nonpayable"
83737
- },
83738
- {
83739
- type: "function",
83740
- name: "createEscrow",
83741
- inputs: [
83742
- {
83743
- name: "terms_",
83744
- type: "tuple",
83745
- internalType: "struct IEscrowV2.Terms",
83746
- components: [
83747
- { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
83748
- { name: "poster", type: "address", internalType: "address" },
83749
- { name: "worker", type: "address", internalType: "address" },
83750
- { name: "termsHash", type: "bytes32", internalType: "bytes32" },
83751
- { name: "offerTtl", type: "uint64", internalType: "uint64" },
83752
- { name: "reviewWindow", type: "uint64", internalType: "uint64" },
83753
- { name: "choiceWindow", type: "uint64", internalType: "uint64" },
83754
- { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
83755
- { name: "objectionWindow", type: "uint64", internalType: "uint64" },
83756
- { name: "workerBondBp", type: "uint16", internalType: "uint16" },
83757
- { name: "feeBp", type: "uint16", internalType: "uint16" },
83758
- { name: "winners", type: "uint8", internalType: "uint8" },
83759
- { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
83760
- ]
83761
- },
83762
- {
83763
- name: "milestones",
83764
- type: "tuple[]",
83765
- internalType: "struct IEscrowV2.Milestone[]",
83766
- components: [
83767
- { name: "amount", type: "uint96", internalType: "uint96" },
83768
- { name: "deadline", type: "uint64", internalType: "uint64" },
83769
- { name: "status", type: "uint8", internalType: "uint8" },
83770
- { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
83771
- ]
83772
- },
83773
- { name: "salt", type: "bytes32", internalType: "bytes32" }
83774
- ],
83775
- outputs: [{ name: "escrow", type: "address", internalType: "address" }],
83776
- stateMutability: "nonpayable"
83777
- },
83778
- {
83779
- type: "function",
83780
- name: "feeBp",
83781
- inputs: [],
83782
- outputs: [{ name: "", type: "uint16", internalType: "uint16" }],
83783
- stateMutability: "view"
83784
- },
83785
- {
83786
- type: "function",
83787
- name: "implementation",
83788
- inputs: [],
83789
- outputs: [{ name: "", type: "address", internalType: "address" }],
83790
- stateMutability: "view"
83791
- },
83792
- {
83793
- type: "function",
83794
- name: "isEscrow",
83795
- inputs: [{ name: "escrow", type: "address", internalType: "address" }],
83796
- outputs: [{ name: "registered", type: "bool", internalType: "bool" }],
83797
- stateMutability: "view"
83798
- },
83799
- {
83800
- type: "function",
83801
- name: "maxEscrowAmount",
83802
- inputs: [],
83803
- outputs: [{ name: "", type: "uint256", internalType: "uint256" }],
83804
- stateMutability: "view"
83805
- },
83806
- {
83807
- type: "function",
83808
- name: "maxFeeBp",
83809
- inputs: [],
83810
- outputs: [{ name: "", type: "uint16", internalType: "uint16" }],
83811
- stateMutability: "view"
83812
- },
83813
- {
83814
- type: "function",
83815
- name: "owner",
83816
- inputs: [],
83817
- outputs: [{ name: "", type: "address", internalType: "address" }],
83818
- stateMutability: "view"
83819
- },
83820
- { type: "function", name: "pause", inputs: [], outputs: [], stateMutability: "nonpayable" },
83821
- {
83822
- type: "function",
83823
- name: "paused",
83824
- inputs: [],
83825
- outputs: [{ name: "", type: "bool", internalType: "bool" }],
83826
- stateMutability: "view"
83827
- },
83828
- {
83829
- type: "function",
83830
- name: "paymentToken",
83831
- inputs: [],
83832
- outputs: [{ name: "", type: "address", internalType: "address" }],
83833
- stateMutability: "view"
83834
- },
83835
- {
83836
- type: "function",
83837
- name: "predictBountyEscrow",
83838
- inputs: [
83839
- {
83840
- name: "terms_",
83841
- type: "tuple",
83842
- internalType: "struct IEscrowV2.Terms",
83843
- components: [
83844
- { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
83845
- { name: "poster", type: "address", internalType: "address" },
83846
- { name: "worker", type: "address", internalType: "address" },
83847
- { name: "termsHash", type: "bytes32", internalType: "bytes32" },
83848
- { name: "offerTtl", type: "uint64", internalType: "uint64" },
83849
- { name: "reviewWindow", type: "uint64", internalType: "uint64" },
83850
- { name: "choiceWindow", type: "uint64", internalType: "uint64" },
83851
- { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
83852
- { name: "objectionWindow", type: "uint64", internalType: "uint64" },
83853
- { name: "workerBondBp", type: "uint16", internalType: "uint16" },
83854
- { name: "feeBp", type: "uint16", internalType: "uint16" },
83855
- { name: "winners", type: "uint8", internalType: "uint8" },
83856
- { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
83857
- ]
83858
- },
83859
- {
83860
- name: "milestones",
83861
- type: "tuple[]",
83862
- internalType: "struct IEscrowV2.Milestone[]",
83863
- components: [
83864
- { name: "amount", type: "uint96", internalType: "uint96" },
83865
- { name: "deadline", type: "uint64", internalType: "uint64" },
83866
- { name: "status", type: "uint8", internalType: "uint8" },
83867
- { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
83868
- ]
83869
- },
83870
- { name: "salt", type: "bytes32", internalType: "bytes32" }
83871
- ],
83872
- outputs: [{ name: "", type: "address", internalType: "address" }],
83873
- stateMutability: "view"
83874
- },
83875
- {
83876
- type: "function",
83877
- name: "predictEscrow",
83878
- inputs: [
83879
- {
83880
- name: "terms_",
83881
- type: "tuple",
83882
- internalType: "struct IEscrowV2.Terms",
83883
- components: [
83884
- { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
83885
- { name: "poster", type: "address", internalType: "address" },
83886
- { name: "worker", type: "address", internalType: "address" },
83887
- { name: "termsHash", type: "bytes32", internalType: "bytes32" },
83888
- { name: "offerTtl", type: "uint64", internalType: "uint64" },
83889
- { name: "reviewWindow", type: "uint64", internalType: "uint64" },
83890
- { name: "choiceWindow", type: "uint64", internalType: "uint64" },
83891
- { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
83892
- { name: "objectionWindow", type: "uint64", internalType: "uint64" },
83893
- { name: "workerBondBp", type: "uint16", internalType: "uint16" },
83894
- { name: "feeBp", type: "uint16", internalType: "uint16" },
83895
- { name: "winners", type: "uint8", internalType: "uint8" },
83896
- { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
83897
- ]
83898
- },
83899
- {
83900
- name: "milestones",
83901
- type: "tuple[]",
83902
- internalType: "struct IEscrowV2.Milestone[]",
83903
- components: [
83904
- { name: "amount", type: "uint96", internalType: "uint96" },
83905
- { name: "deadline", type: "uint64", internalType: "uint64" },
83906
- { name: "status", type: "uint8", internalType: "uint8" },
83907
- { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
83908
- ]
83909
- },
83910
- { name: "salt", type: "bytes32", internalType: "bytes32" }
83911
- ],
83912
- outputs: [{ name: "", type: "address", internalType: "address" }],
83913
- stateMutability: "view"
83914
- },
83915
- {
83916
- type: "function",
83917
- name: "renounceOwnership",
83918
- inputs: [],
83919
- outputs: [],
83920
- stateMutability: "nonpayable"
83921
- },
83922
- {
83923
- type: "function",
83924
- name: "setFeeBp",
83925
- inputs: [{ name: "newFeeBp", type: "uint16", internalType: "uint16" }],
83926
- outputs: [],
83927
- stateMutability: "nonpayable"
83928
- },
83929
- {
83930
- type: "function",
83931
- name: "setMaxEscrowAmount",
83932
- inputs: [{ name: "newAmount", type: "uint256", internalType: "uint256" }],
83933
- outputs: [],
83934
- stateMutability: "nonpayable"
83935
- },
83936
- {
83937
- type: "function",
83938
- name: "transferOwnership",
83939
- inputs: [{ name: "newOwner", type: "address", internalType: "address" }],
83940
- outputs: [],
83941
- stateMutability: "nonpayable"
83942
- },
83943
- { type: "function", name: "unpause", inputs: [], outputs: [], stateMutability: "nonpayable" },
83944
- {
83945
- type: "event",
83946
- name: "EscrowCreated",
83947
- inputs: [
83948
- { name: "escrow", type: "address", indexed: true, internalType: "address" },
83949
- { name: "poster", type: "address", indexed: true, internalType: "address" },
83950
- { name: "termsHash", type: "bytes32", indexed: true, internalType: "bytes32" },
83951
- { name: "salt", type: "bytes32", indexed: false, internalType: "bytes32" },
83952
- { name: "feeBp", type: "uint16", indexed: false, internalType: "uint16" }
83953
- ],
83954
- anonymous: false
83955
- },
83956
- {
83957
- type: "event",
83958
- name: "FeeBpSet",
83959
- inputs: [
83960
- { name: "previousFeeBp", type: "uint16", indexed: false, internalType: "uint16" },
83961
- { name: "newFeeBp", type: "uint16", indexed: false, internalType: "uint16" }
83962
- ],
83963
- anonymous: false
83964
- },
83965
- {
83966
- type: "event",
83967
- name: "MaxEscrowAmountSet",
83968
- inputs: [
83969
- { name: "previousAmount", type: "uint256", indexed: false, internalType: "uint256" },
83970
- { name: "newAmount", type: "uint256", indexed: false, internalType: "uint256" }
83971
- ],
83972
- anonymous: false
83973
- },
83974
- {
83975
- type: "event",
83976
- name: "OwnershipTransferred",
83977
- inputs: [
83978
- { name: "previousOwner", type: "address", indexed: true, internalType: "address" },
83979
- { name: "newOwner", type: "address", indexed: true, internalType: "address" }
83980
- ],
83981
- anonymous: false
83982
- },
83983
- {
83984
- type: "event",
83985
- name: "PauseSet",
83986
- inputs: [{ name: "paused", type: "bool", indexed: false, internalType: "bool" }],
83987
- anonymous: false
83988
- },
83989
- {
83990
- type: "error",
83991
- name: "EscrowAlreadyExists",
83992
- inputs: [{ name: "escrow", type: "address", internalType: "address" }]
83993
- },
83994
- {
83995
- type: "error",
83996
- name: "EscrowAmountAboveCap",
83997
- inputs: [
83998
- { name: "amount", type: "uint256", internalType: "uint256" },
83999
- { name: "cap", type: "uint256", internalType: "uint256" }
84000
- ]
84001
- },
84002
- { type: "error", name: "FactoryPaused", inputs: [] },
84003
- { type: "error", name: "FailedDeployment", inputs: [] },
84004
- {
84005
- type: "error",
84006
- name: "InsufficientBalance",
84007
- inputs: [
84008
- { name: "balance", type: "uint256", internalType: "uint256" },
84009
- { name: "needed", type: "uint256", internalType: "uint256" }
84010
- ]
84011
- },
84012
- { type: "error", name: "InvalidAddress", inputs: [] },
84013
- { type: "error", name: "InvalidFee", inputs: [] },
84014
- { type: "error", name: "InvalidToken", inputs: [] },
84015
- {
84016
- type: "error",
84017
- name: "OwnableInvalidOwner",
84018
- inputs: [{ name: "owner", type: "address", internalType: "address" }]
84019
- },
84020
- {
84021
- type: "error",
84022
- name: "OwnableUnauthorizedAccount",
84023
- inputs: [{ name: "account", type: "address", internalType: "address" }]
84024
- },
84025
- {
84026
- type: "error",
84027
- name: "ShapeMismatch",
84028
- inputs: [
84029
- { name: "expected", type: "uint8", internalType: "enum IEscrowV2.Shape" },
84030
- { name: "supplied", type: "uint8", internalType: "enum IEscrowV2.Shape" }
84031
- ]
84032
- },
84033
- {
84034
- type: "error",
84035
- name: "TermsFeeMismatch",
84036
- inputs: [
84037
- { name: "expected", type: "uint16", internalType: "uint16" },
84038
- { name: "supplied", type: "uint16", internalType: "uint16" }
84039
- ]
83463
+ anonymous: false
83464
+ },
83465
+ {
83466
+ type: "event",
83467
+ name: "FeeBpSet",
83468
+ inputs: [
83469
+ { name: "previousFeeBp", type: "uint16", indexed: false, internalType: "uint16" },
83470
+ { name: "newFeeBp", type: "uint16", indexed: false, internalType: "uint16" }
83471
+ ],
83472
+ anonymous: false
83473
+ },
83474
+ {
83475
+ type: "event",
83476
+ name: "MaxEscrowAmountSet",
83477
+ inputs: [
83478
+ { name: "previousAmount", type: "uint256", indexed: false, internalType: "uint256" },
83479
+ { name: "newAmount", type: "uint256", indexed: false, internalType: "uint256" }
83480
+ ],
83481
+ anonymous: false
83482
+ },
83483
+ {
83484
+ type: "event",
83485
+ name: "OwnershipTransferred",
83486
+ inputs: [
83487
+ { name: "previousOwner", type: "address", indexed: true, internalType: "address" },
83488
+ { name: "newOwner", type: "address", indexed: true, internalType: "address" }
83489
+ ],
83490
+ anonymous: false
83491
+ },
83492
+ {
83493
+ type: "event",
83494
+ name: "PauseSet",
83495
+ inputs: [{ name: "paused", type: "bool", indexed: false, internalType: "bool" }],
83496
+ anonymous: false
83497
+ },
83498
+ {
83499
+ type: "error",
83500
+ name: "EscrowAlreadyExists",
83501
+ inputs: [{ name: "escrow", type: "address", internalType: "address" }]
83502
+ },
83503
+ {
83504
+ type: "error",
83505
+ name: "EscrowAmountAboveCap",
83506
+ inputs: [
83507
+ { name: "amount", type: "uint256", internalType: "uint256" },
83508
+ { name: "cap", type: "uint256", internalType: "uint256" }
83509
+ ]
83510
+ },
83511
+ { type: "error", name: "FactoryPaused", inputs: [] },
83512
+ { type: "error", name: "FailedDeployment", inputs: [] },
83513
+ {
83514
+ type: "error",
83515
+ name: "InsufficientBalance",
83516
+ inputs: [
83517
+ { name: "balance", type: "uint256", internalType: "uint256" },
83518
+ { name: "needed", type: "uint256", internalType: "uint256" }
83519
+ ]
83520
+ },
83521
+ { type: "error", name: "InvalidAddress", inputs: [] },
83522
+ { type: "error", name: "InvalidFee", inputs: [] },
83523
+ { type: "error", name: "InvalidToken", inputs: [] },
83524
+ {
83525
+ type: "error",
83526
+ name: "OwnableInvalidOwner",
83527
+ inputs: [{ name: "owner", type: "address", internalType: "address" }]
83528
+ },
83529
+ {
83530
+ type: "error",
83531
+ name: "OwnableUnauthorizedAccount",
83532
+ inputs: [{ name: "account", type: "address", internalType: "address" }]
83533
+ },
83534
+ {
83535
+ type: "error",
83536
+ name: "ShapeMismatch",
83537
+ inputs: [
83538
+ { name: "expected", type: "uint8", internalType: "enum IEscrowV2.Shape" },
83539
+ { name: "supplied", type: "uint8", internalType: "enum IEscrowV2.Shape" }
83540
+ ]
83541
+ },
83542
+ {
83543
+ type: "error",
83544
+ name: "TermsFeeMismatch",
83545
+ inputs: [
83546
+ { name: "expected", type: "uint16", internalType: "uint16" },
83547
+ { name: "supplied", type: "uint16", internalType: "uint16" }
83548
+ ]
84040
83549
  }
84041
83550
  ];
84042
83551
  var escrowV2Abi = [
@@ -86657,10 +86166,6 @@ var TASK_V2_CASE_STATE = {
86657
86166
  Snapshotting: 6
86658
86167
  };
86659
86168
 
86660
- // ../core/src/tasks/operation-support.ts
86661
- import { readFile as readFile18, stat as stat15 } from "node:fs/promises";
86662
- import { basename as basename2, extname } from "node:path";
86663
-
86664
86169
  // ../core/src/tasks/v2-events.ts
86665
86170
  var TASK_V2_NO_VERDICT_SUMMARY = "Disputed: status quo final after round 2 without a verdict; no dispute winner.";
86666
86171
  var TASK_V2_REVIEWER_GUIDANCE = "mayVote reports jury membership only. Do not touch your stake until you have revealed; even a cancelled unstake can cost the vote.";
@@ -86695,6 +86200,73 @@ function taskV2OutcomeLines(value) {
86695
86200
  return [...new Set(Object.values(source).flatMap(taskV2OutcomeLines))];
86696
86201
  }
86697
86202
 
86203
+ // ../core/src/tasks/money.ts
86204
+ function formatBaseUnitsUsd(baseUnits2) {
86205
+ const [whole, fraction = ""] = formatUsdc(parseBaseUnits(baseUnits2)).split(".");
86206
+ return `${whole}.${fraction.padEnd(2, "0")}`;
86207
+ }
86208
+ function parseUsdToBaseUnits(text) {
86209
+ if (!/^\d+(?:\.\d{1,6})?$/u.test(text)) {
86210
+ throw new Error(
86211
+ "Task USD amount must be a non-negative decimal with at most six decimal places."
86212
+ );
86213
+ }
86214
+ const [whole = "0", fraction = ""] = text.split(".");
86215
+ return BigInt(whole) * 1000000n + BigInt(fraction.padEnd(6, "0"));
86216
+ }
86217
+ function parseFeeBp(deploymentOrReadiness) {
86218
+ if (typeof deploymentOrReadiness !== "object" || deploymentOrReadiness === null || !("feeBp" in deploymentOrReadiness)) {
86219
+ return null;
86220
+ }
86221
+ const feeBp = deploymentOrReadiness.feeBp;
86222
+ if (feeBp === void 0 || feeBp === null) return null;
86223
+ validateFeeBp(feeBp);
86224
+ return feeBp;
86225
+ }
86226
+ function taskMoney(grossBaseUnits, feeBp) {
86227
+ const atomic = parseBaseUnits(grossBaseUnits);
86228
+ const gross = amount3(atomic);
86229
+ if (feeBp === null) {
86230
+ return { gross, fee: null, net: null, feeBp, line: `$${gross.usd} gross \xB7 fee unavailable` };
86231
+ }
86232
+ validateFeeBp(feeBp);
86233
+ const feeAtomic = atomic * BigInt(feeBp) / 10000n;
86234
+ const fee = amount3(feeAtomic);
86235
+ const net = amount3(atomic - feeAtomic);
86236
+ return {
86237
+ gross,
86238
+ fee,
86239
+ net,
86240
+ feeBp,
86241
+ line: `$${gross.usd} gross \xB7 $${fee.usd} fee \xB7 $${net.usd} net`
86242
+ };
86243
+ }
86244
+ function amount3(atomic) {
86245
+ return { usd: formatBaseUnitsUsd(atomic), baseUnits: atomic.toString() };
86246
+ }
86247
+ function validateFeeBp(value) {
86248
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 1e4) {
86249
+ throw new Error("Task fee basis points must be an integer from 0 to 10000.");
86250
+ }
86251
+ }
86252
+ function parseBaseUnits(value) {
86253
+ if (typeof value === "string" && !/^\d+$/u.test(value) || typeof value !== "bigint" && typeof value !== "string") {
86254
+ throw new Error("Task base units must be a non-negative integer.");
86255
+ }
86256
+ const atomic = BigInt(value);
86257
+ if (atomic < 0n) throw new Error("Task base units must be a non-negative integer.");
86258
+ return atomic;
86259
+ }
86260
+ function taskPolicyAtomic(value) {
86261
+ if (!Number.isFinite(value) || value < 0)
86262
+ throw new Error("Task policy USD amounts must be finite and non-negative.");
86263
+ const [mantissa = "0", exponent = "0"] = value.toString().split("e");
86264
+ const [whole = "0", fraction = ""] = mantissa.split(".");
86265
+ const digits = BigInt(whole + fraction);
86266
+ const scale = 6 + Number(exponent) - fraction.length;
86267
+ return scale >= 0 ? digits * 10n ** BigInt(scale) : digits / 10n ** BigInt(-scale);
86268
+ }
86269
+
86698
86270
  // ../core/src/tasks/operation-support.ts
86699
86271
  var TaskOperationError = class extends Error {
86700
86272
  constructor(code, message, manifestHash, details) {
@@ -86971,121 +86543,667 @@ function nextTaskEvents(page, cursor2) {
86971
86543
  "invalid_response",
86972
86544
  "The task event cursor regressed or is malformed."
86973
86545
  );
86974
- for (const event of page.events)
86975
- if (!Number.isSafeInteger(event.sequence) || event.sequence < 0)
86976
- throw new TaskOperationError("invalid_response", "A task event sequence is malformed.");
86977
- const seen = /* @__PURE__ */ new Set();
86978
- const events = [...page.events].sort((a, b) => a.sequence - b.sequence).filter((event) => {
86979
- if (event.sequence <= cursor2 || seen.has(event.sequence)) return false;
86980
- seen.add(event.sequence);
86981
- return true;
86546
+ for (const event of page.events)
86547
+ if (!Number.isSafeInteger(event.sequence) || event.sequence < 0)
86548
+ throw new TaskOperationError("invalid_response", "A task event sequence is malformed.");
86549
+ const seen = /* @__PURE__ */ new Set();
86550
+ const events = [...page.events].sort((a, b) => a.sequence - b.sequence).filter((event) => {
86551
+ if (event.sequence <= cursor2 || seen.has(event.sequence)) return false;
86552
+ seen.add(event.sequence);
86553
+ return true;
86554
+ });
86555
+ return {
86556
+ events,
86557
+ nextCursor: Math.max(cursor2, page.nextAfter, ...page.events.map((e3) => e3.sequence))
86558
+ };
86559
+ }
86560
+ async function accountTaskPolicy(directory, wallet, warn) {
86561
+ let raw;
86562
+ try {
86563
+ raw = await readFile18(join16(directory, "wallets.json"), "utf8");
86564
+ } catch {
86565
+ return void 0;
86566
+ }
86567
+ try {
86568
+ const wallets = JSON.parse(raw).wallets;
86569
+ const stored = wallets && Object.hasOwn(wallets, wallet) ? wallets[wallet]?.taskPolicy : void 0;
86570
+ return stored === void 0 ? void 0 : walletTaskPolicySchema.parse(stored);
86571
+ } catch {
86572
+ warn?.(`The task limits stored for account ${wallet} are unreadable; using the defaults.`);
86573
+ return void 0;
86574
+ }
86575
+ }
86576
+ async function taskPolicyForWallet(args) {
86577
+ let invalid = false;
86578
+ const profiles = await listAgentProfiles(args.directory, {
86579
+ schema: args.schema,
86580
+ ...args.warn ? { warn: args.warn } : {},
86581
+ onInvalid: () => {
86582
+ invalid = true;
86583
+ }
86584
+ });
86585
+ if (invalid) throw new TaskInputError("An invalid agent profile prevents task policy selection.");
86586
+ const matches = profiles.filter((profile2) => profile2.wallet === args.wallet);
86587
+ if (matches.length > 1)
86588
+ throw new TaskInputError(
86589
+ `More than one agent profile uses wallet ${args.wallet}; task policy is ambiguous.`
86590
+ );
86591
+ const profile = matches[0];
86592
+ if (profile)
86593
+ return {
86594
+ maxPerTaskUsd: profile.maxPerTaskUsd,
86595
+ approveAboveUsd: profile.approveAboveUsd,
86596
+ autoReleaseBelowUsd: profile.autoReleaseBelowUsd,
86597
+ source: "agent-profile"
86598
+ };
86599
+ const account = await accountTaskPolicy(args.directory, args.wallet, args.warn);
86600
+ const stored = account?.maxPerTaskUsd !== void 0 || account?.approveAboveUsd !== void 0;
86601
+ return {
86602
+ maxPerTaskUsd: account?.maxPerTaskUsd ?? DEFAULT_MAX_PER_TASK_USD,
86603
+ approveAboveUsd: account?.approveAboveUsd ?? agentProfileSchema.shape.approveAboveUsd.parse(void 0),
86604
+ autoReleaseBelowUsd: DEFAULT_AUTO_RELEASE_BELOW_USD,
86605
+ source: stored ? "account" : "defaults"
86606
+ };
86607
+ }
86608
+ async function taskMoneySnapshot(client, orderId, escrowId, options = { signInHint: "" }) {
86609
+ const order = await taskRequest(
86610
+ "task money",
86611
+ "getOrder",
86612
+ () => client.getOrder(orderId),
86613
+ options
86614
+ ), workOrder = order.workOrder;
86615
+ if (workOrder.id !== orderId || workOrder.version !== "work-order-view-v1")
86616
+ throw new TaskOperationError(
86617
+ "invalid_response",
86618
+ "A private task order matching the requested ID is required."
86619
+ );
86620
+ const matches = escrowId ? workOrder.milestones.filter((m) => m.id === escrowId) : workOrder.milestones;
86621
+ if (matches.length !== 1)
86622
+ throw new TaskOperationError("invalid_response", "Select one task milestone by escrow ID.");
86623
+ const milestone = matches[0];
86624
+ if (milestone.workOrderId !== orderId)
86625
+ throw new TaskOperationError("invalid_response", "The milestone belongs to a different task.");
86626
+ let readiness;
86627
+ try {
86628
+ readiness = { ok: true, value: await client.deployment() };
86629
+ } catch (error61) {
86630
+ readiness = { ok: false, error: error61 };
86631
+ }
86632
+ return {
86633
+ order,
86634
+ escrowId: milestone.id,
86635
+ money: taskMoney(milestone.amountBaseUnits, readiness.ok ? parseFeeBp(readiness.value) : null),
86636
+ readiness
86637
+ };
86638
+ }
86639
+ function cachedMoneyClient(client, snapshot) {
86640
+ return new Proxy(client, {
86641
+ get(target, property) {
86642
+ if (property === "getOrder")
86643
+ return async (id2) => {
86644
+ if (id2 !== snapshot.order.workOrder.id)
86645
+ throw new Error("The cached task order does not match the requested ID.");
86646
+ return snapshot.order;
86647
+ };
86648
+ if (property === "deployment")
86649
+ return async () => {
86650
+ if (snapshot.readiness.ok) return snapshot.readiness.value;
86651
+ throw snapshot.readiness.error;
86652
+ };
86653
+ const value = Reflect.get(target, property, target);
86654
+ return typeof value === "function" ? value.bind(target) : value;
86655
+ }
86656
+ });
86657
+ }
86658
+ function fundingRefusalReason(error61) {
86659
+ if (error61 instanceof Error && error61.name === "SpendCapExceededError") {
86660
+ const fromCause = fundingRefusalReason(error61.cause);
86661
+ if (fromCause) return fromCause;
86662
+ return "cap" in error61 && error61.cap === "per_day" ? "policy.perDay" : void 0;
86663
+ }
86664
+ if (!(error61 instanceof SpendCapError || error61 instanceof Error && error61.name === "SpendCapError"))
86665
+ return void 0;
86666
+ const code = "code" in error61 ? error61.code : void 0;
86667
+ return code === "per_task_cap_exceeded" ? "policy.perTask" : code === "per_day_cap_exceeded" ? "policy.perDay" : void 0;
86668
+ }
86669
+ function taskEventLine(event) {
86670
+ const label2 = event.type === "task.judging" ? `deadline passed, ${event.payload.submissionCount} submissions, pick winners` : event.type === "task.claimed" ? "first submission received" : event.type === "task.checkin" ? `check-in: ${event.payload.status ?? "received"}` : event.type === "task.stalled" ? "task stalled" : event.type === "task.milestone" ? "milestone updated" : event.type === "task.released" ? "escrow released" : event.type;
86671
+ return `${event.sequence}: ${[label2, ...taskV2OutcomeLines(event.payload)].join(" \xB7 ")}`;
86672
+ }
86673
+ function requireTaskMethod(client, name) {
86674
+ const method = client[name];
86675
+ if (typeof method !== "function")
86676
+ throw new TaskOperationError(
86677
+ "not_supported",
86678
+ `Task method ${name} is not supported by this SDK adapter.`
86679
+ );
86680
+ return method.bind(client);
86681
+ }
86682
+
86683
+ // ../core/src/tasks/availability.ts
86684
+ var TASK_V2_NEW_WORK_ACTIONS = [
86685
+ "fund",
86686
+ "approve-bond",
86687
+ "award",
86688
+ "award-consent"
86689
+ ];
86690
+ var NETWORK_NAMES = {
86691
+ 8453: "Base",
86692
+ 84532: "Base Sepolia",
86693
+ 5042002: "Arc testnet"
86694
+ };
86695
+ function taskNetworkName(chainId) {
86696
+ return NETWORK_NAMES[chainId] ?? `chain ${chainId}`;
86697
+ }
86698
+ function tasksUnavailableError(chainId, untouched = "Nothing was signed and no money moved.", code = "tasks_unavailable") {
86699
+ return new TaskOperationError(
86700
+ code,
86701
+ `vAPI reports Tasks as unavailable on ${taskNetworkName(chainId)} right now. ${untouched} Try again later.`
86702
+ );
86703
+ }
86704
+ async function readTasksReadiness(client) {
86705
+ try {
86706
+ return await client.deployment();
86707
+ } catch {
86708
+ return void 0;
86709
+ }
86710
+ }
86711
+ function requireTasksAvailable(action, readiness, untouched) {
86712
+ if (!TASK_V2_NEW_WORK_ACTIONS.includes(action)) return;
86713
+ if (!readiness)
86714
+ throw new TaskOperationError(
86715
+ "tasks_unavailable",
86716
+ `vAPI's Tasks status could not be read. ${untouched ?? "Nothing was signed and no money moved."} Try again later.`
86717
+ );
86718
+ if (!readiness.configured) throw tasksUnavailableError(readiness.chainId, untouched);
86719
+ }
86720
+
86721
+ // ../core/src/tasks/dispute-fee.ts
86722
+ import { createHash as createHash3 } from "node:crypto";
86723
+ function disputeFeeBaseUnits(amount4) {
86724
+ if (amount4 < 0n) throw new Error("Dispute amount must be nonnegative.");
86725
+ const fee = amount4 * 1000n / 10000n;
86726
+ return fee < 20000000n ? 20000000n : fee > 500000000n ? 500000000n : fee;
86727
+ }
86728
+ function taskFeeReservationKey(milestoneId2, action) {
86729
+ const bytes = createHash3("sha256").update(JSON.stringify([milestoneId2, action])).digest().subarray(0, 16);
86730
+ bytes[6] = bytes[6] & 15 | 80;
86731
+ bytes[8] = bytes[8] & 63 | 128;
86732
+ const hex5 = bytes.toString("hex");
86733
+ return `${hex5.slice(0, 8)}-${hex5.slice(8, 12)}-${hex5.slice(12, 16)}-${hex5.slice(16, 20)}-${hex5.slice(20)}`;
86734
+ }
86735
+
86736
+ // ../core/src/tasks/plan-guard.ts
86737
+ var TASKS_CHAIN_ABI = [
86738
+ {
86739
+ type: "function",
86740
+ name: "createEscrow",
86741
+ stateMutability: "nonpayable",
86742
+ inputs: [
86743
+ { name: "buyer", type: "address" },
86744
+ { name: "token", type: "address" },
86745
+ { name: "amount", type: "uint256" },
86746
+ { name: "workDuration", type: "uint64" },
86747
+ { name: "acceptanceWindow", type: "uint64" },
86748
+ { name: "termsHash", type: "bytes32" },
86749
+ { name: "salt", type: "bytes32" }
86750
+ ],
86751
+ outputs: [{ name: "escrow", type: "address" }]
86752
+ },
86753
+ {
86754
+ type: "function",
86755
+ name: "fundWithAuthorization",
86756
+ stateMutability: "nonpayable",
86757
+ inputs: [
86758
+ { name: "validAfter", type: "uint256" },
86759
+ { name: "validBefore", type: "uint256" },
86760
+ { name: "nonce", type: "bytes32" },
86761
+ { name: "signature", type: "bytes" }
86762
+ ],
86763
+ outputs: []
86764
+ },
86765
+ {
86766
+ type: "function",
86767
+ name: "approve",
86768
+ stateMutability: "nonpayable",
86769
+ inputs: [
86770
+ { name: "spender", type: "address" },
86771
+ { name: "amount", type: "uint256" }
86772
+ ],
86773
+ outputs: [{ name: "ok", type: "bool" }]
86774
+ },
86775
+ {
86776
+ type: "function",
86777
+ name: "depositFunds",
86778
+ stateMutability: "nonpayable",
86779
+ inputs: [],
86780
+ outputs: []
86781
+ },
86782
+ {
86783
+ type: "function",
86784
+ name: "submitDelivery",
86785
+ stateMutability: "nonpayable",
86786
+ inputs: [{ name: "manifestHash", type: "bytes32" }],
86787
+ outputs: []
86788
+ },
86789
+ {
86790
+ type: "function",
86791
+ name: "releaseFunds",
86792
+ stateMutability: "nonpayable",
86793
+ inputs: [],
86794
+ outputs: []
86795
+ },
86796
+ { type: "function", name: "refundBuyer", stateMutability: "nonpayable", inputs: [], outputs: [] },
86797
+ {
86798
+ type: "function",
86799
+ name: "raiseDispute",
86800
+ stateMutability: "nonpayable",
86801
+ inputs: [{ name: "evidenceHash", type: "bytes32" }],
86802
+ outputs: []
86803
+ },
86804
+ {
86805
+ type: "function",
86806
+ name: "submitCounterEvidence",
86807
+ stateMutability: "nonpayable",
86808
+ inputs: [{ name: "evidenceHash", type: "bytes32" }],
86809
+ outputs: []
86810
+ },
86811
+ {
86812
+ type: "function",
86813
+ name: "resolveUnmatchedDispute",
86814
+ stateMutability: "nonpayable",
86815
+ inputs: [],
86816
+ outputs: []
86817
+ },
86818
+ {
86819
+ type: "function",
86820
+ name: "timeoutRefund",
86821
+ stateMutability: "nonpayable",
86822
+ inputs: [],
86823
+ outputs: []
86824
+ },
86825
+ { type: "function", name: "finalize", stateMutability: "nonpayable", inputs: [], outputs: [] },
86826
+ {
86827
+ type: "function",
86828
+ name: "disputeFee",
86829
+ stateMutability: "view",
86830
+ inputs: [],
86831
+ outputs: [{ name: "fee", type: "uint256" }]
86832
+ },
86833
+ {
86834
+ type: "function",
86835
+ name: "allowance",
86836
+ stateMutability: "view",
86837
+ inputs: [
86838
+ { name: "owner", type: "address" },
86839
+ { name: "spender", type: "address" }
86840
+ ],
86841
+ outputs: [{ name: "amount", type: "uint256" }]
86842
+ }
86843
+ ];
86844
+ var TASKS_READ_ABI = parseAbi([
86845
+ "function paymentToken() view returns (address)",
86846
+ "function isEscrow(address escrow) view returns (bool)",
86847
+ "function name() view returns (string)",
86848
+ "function version() view returns (string)",
86849
+ "function buyer() view returns (address)",
86850
+ "function seller() view returns (address)",
86851
+ "function token() view returns (address)",
86852
+ "function amount() view returns (uint256)",
86853
+ "function termsHash() view returns (bytes32)",
86854
+ "function state() view returns (uint8)",
86855
+ "function offerDeadline() view returns (uint64)",
86856
+ "function workDeadline() view returns (uint64)",
86857
+ "function reviewDeadline() view returns (uint64)",
86858
+ "function disputedAt() view returns (uint64)",
86859
+ "function counterEvidenceDeadline() view returns (uint64)",
86860
+ "function resolution() view returns (uint8)",
86861
+ "function disputeFee() view returns (uint256)",
86862
+ "function predictEscrow(address seller, bytes32 salt) view returns (address)"
86863
+ ]);
86864
+ function verifyPlan(operation, expectation) {
86865
+ const fail2 = (message) => {
86866
+ throw new TasksChainError(`Unsafe transaction plan: ${message}`, false);
86867
+ };
86868
+ const plan = operation.plan;
86869
+ if (!plan) throw new TasksChainError("Unsafe transaction plan: missing plan", false);
86870
+ if (plan.operationId !== operation.id || plan.step !== operation.step) fail2("operation mismatch");
86871
+ if (!expectation.steps.includes(plan.step)) fail2("unexpected step");
86872
+ if (!operation.expectedActor || getAddress(operation.expectedActor) !== getAddress(expectation.signer) || getAddress(plan.from) !== getAddress(expectation.signer))
86873
+ fail2("unexpected signer");
86874
+ if (plan.chainId !== expectation.deployment.chainId || plan.network !== expectation.deployment.network || plan.network !== `eip155:${plan.chainId}` || plan.value !== "0")
86875
+ fail2("unexpected network or value");
86876
+ if (expectation.milestone.network !== plan.network || expectation.milestone.asset.toLowerCase() !== `${plan.network}/erc20:${expectation.deployment.usdc}`.toLowerCase())
86877
+ fail2("milestone asset mismatch");
86878
+ const target = plan.step === "create-escrow" ? expectation.deployment.escrowContract : plan.step === "approve-usdc" ? expectation.deployment.usdc : expectation.milestone.escrowContract;
86879
+ if (getAddress(plan.to) !== getAddress(target)) fail2("unexpected target");
86880
+ const decoded = (() => {
86881
+ try {
86882
+ return decodeFunctionData({ abi: TASKS_CHAIN_ABI, data: plan.data });
86883
+ } catch {
86884
+ return fail2("invalid calldata");
86885
+ }
86886
+ })();
86887
+ const expectedName = {
86888
+ "create-escrow": "createEscrow",
86889
+ "fund-with-authorization": "fundWithAuthorization",
86890
+ "approve-usdc": "approve",
86891
+ "deposit-funds": "depositFunds",
86892
+ "submit-delivery": "submitDelivery",
86893
+ "release-funds": "releaseFunds",
86894
+ "refund-buyer": "refundBuyer",
86895
+ "raise-dispute": "raiseDispute",
86896
+ "submit-counter-evidence": "submitCounterEvidence",
86897
+ "resolve-unmatched-dispute": "resolveUnmatchedDispute",
86898
+ "timeout-refund": "timeoutRefund",
86899
+ finalize: "finalize"
86900
+ };
86901
+ if (decoded.functionName !== expectedName[plan.step]) fail2("unexpected selector");
86902
+ const args = [...decoded.args ?? []];
86903
+ const eq = (a, b) => typeof a === "string" && typeof b === "string" ? a.toLowerCase() === b.toLowerCase() : a === b;
86904
+ const requireArgs = (values) => {
86905
+ if (args.length !== values.length || args.some((v, i2) => !eq(v, values[i2])))
86906
+ fail2("unexpected arguments");
86907
+ };
86908
+ if (plan.step === "create-escrow") {
86909
+ if (!expectation.seller || getAddress(expectation.signer) !== getAddress(expectation.seller))
86910
+ fail2("createEscrow requires the locally bound seller");
86911
+ const workDuration = expectation.workDurationSeconds ?? expectation.milestone.terms.workDurationSeconds ?? getTrustedTasksDurations(expectation.deployment.chainId).workDurationSeconds;
86912
+ if (workDuration === void 0) fail2("missing trusted work duration");
86913
+ requireArgs([
86914
+ expectation.buyer,
86915
+ expectation.deployment.usdc,
86916
+ BigInt(expectation.milestone.amountBaseUnits),
86917
+ BigInt(workDuration),
86918
+ BigInt(
86919
+ expectation.reviewWindowSeconds ?? expectation.milestone.terms.acceptanceWindowSeconds
86920
+ ),
86921
+ expectation.milestone.termsHash,
86922
+ keccak256(stringToHex(expectation.milestone.id))
86923
+ ]);
86924
+ } else if (plan.step === "fund-with-authorization") {
86925
+ const a = expectation.authorization;
86926
+ if (!a)
86927
+ throw new TasksChainError("Unsafe transaction plan: missing local authorization", false);
86928
+ requireArgs([BigInt(a.validAfter), BigInt(a.validBefore), a.nonce, a.signature]);
86929
+ } else if (plan.step === "approve-usdc") {
86930
+ if (expectation.approveAmount === void 0) fail2("missing verified approval amount");
86931
+ requireArgs([expectation.milestone.escrowContract, expectation.approveAmount]);
86932
+ } else if (plan.step === "submit-delivery") {
86933
+ if (!expectation.manifestHash) fail2("missing manifest hash");
86934
+ requireArgs([expectation.manifestHash]);
86935
+ } else if (plan.step === "raise-dispute" || plan.step === "submit-counter-evidence") {
86936
+ if (!expectation.evidenceHash) fail2("missing evidence hash");
86937
+ requireArgs([expectation.evidenceHash]);
86938
+ } else requireArgs([]);
86939
+ }
86940
+
86941
+ // ../core/src/tasks/chain-verification.ts
86942
+ var TasksPartiesNotBoundError = class extends TasksValidationError {
86943
+ constructor() {
86944
+ super(
86945
+ "The task parties are not bound on this machine. Sign the scope with `vapi task sign` on this machine first; an explicit --counterparty only confirms an existing binding."
86946
+ );
86947
+ this.name = "TasksPartiesNotBoundError";
86948
+ }
86949
+ };
86950
+ async function verifyDeployment(ready, rpc, overrides) {
86951
+ const factory = getTrustedTasksFactory(ready.chainId, overrides);
86952
+ if (!factory)
86953
+ throw new TasksChainError(
86954
+ `No trusted Tasks escrow factory is configured for chain ${ready.chainId}. Set VAPI_TASKS_ESCROW_FACTORY_${ready.chainId}.`,
86955
+ false,
86956
+ { authorizationExposed: false }
86957
+ );
86958
+ if (!isAddressEqual(factory, ready.escrowContract))
86959
+ throw new TasksValidationError(
86960
+ "The Tasks readiness factory does not match the trusted factory."
86961
+ );
86962
+ if (await rpc.getChainId() !== ready.chainId)
86963
+ throw new TasksValidationError("The RPC chain ID does not match the task deployment.");
86964
+ const token = await rpc.readContract({
86965
+ address: factory,
86966
+ abi: TASKS_READ_ABI,
86967
+ functionName: "paymentToken"
86982
86968
  });
86969
+ if (!isAddressEqual(token, ready.usdc))
86970
+ throw new TasksValidationError(
86971
+ "The Tasks readiness token does not match the trusted factory payment token."
86972
+ );
86973
+ const [name, version5] = await Promise.all([
86974
+ rpc.readContract({ address: token, abi: TASKS_READ_ABI, functionName: "name" }),
86975
+ rpc.readContract({ address: token, abi: TASKS_READ_ABI, functionName: "version" })
86976
+ ]);
86977
+ const domain2 = { name, version: version5, chainId: ready.chainId, verifyingContract: getAddress(token) };
86978
+ if (ready.eip3009Domain && (ready.eip3009Domain.name !== name || ready.eip3009Domain.version !== version5 || ready.eip3009Domain.chainId !== ready.chainId || !isAddressEqual(ready.eip3009Domain.verifyingContract, token)))
86979
+ throw new TasksValidationError(
86980
+ "The funding authorization domain does not match the onchain token domain."
86981
+ );
86983
86982
  return {
86984
- events,
86985
- nextCursor: Math.max(cursor2, page.nextAfter, ...page.events.map((e3) => e3.sequence))
86983
+ ...ready,
86984
+ escrowContract: getAddress(factory),
86985
+ usdc: getAddress(token),
86986
+ eip3009Domain: domain2
86986
86987
  };
86987
86988
  }
86988
- async function taskPolicyForWallet(args) {
86989
- let invalid = false;
86990
- const profiles = await listAgentProfiles(args.directory, {
86991
- schema: args.schema,
86992
- ...args.warn ? { warn: args.warn } : {},
86993
- onInvalid: () => {
86994
- invalid = true;
86995
- }
86996
- });
86997
- if (invalid) throw new TaskInputError("An invalid agent profile prevents task policy selection.");
86998
- const matches = profiles.filter((profile2) => profile2.wallet === args.wallet);
86999
- if (matches.length > 1)
87000
- throw new TaskInputError(
87001
- `More than one agent profile uses wallet ${args.wallet}; task policy is ambiguous.`
86989
+ async function verifyScope(client, signer, selected, ready, verb, steps, options = {}) {
86990
+ const { scopes } = await client.getScopes(selected.workOrderId);
86991
+ const matches = scopes.filter(
86992
+ (scope2) => scope2.state === "accepted" && scope2.milestoneId === selected.id
86993
+ );
86994
+ if (matches.length !== 1)
86995
+ throw new TasksValidationError("The task milestone requires one accepted signed scope.");
86996
+ const scope = matches[0];
86997
+ const payload = scope.signingPayload;
86998
+ const frozen = freezeScopeTerms(scope.structuredTerms, scope.brief);
86999
+ if (scope.workOrderId !== selected.workOrderId || payload.workOrderId !== selected.workOrderId || payload.trancheOrdinal !== selected.ordinal || scope.trancheOrdinal !== selected.ordinal || payload.scopeVersion !== scope.version || frozen.termsHash !== scope.termsHash || frozen.termsHash !== payload.termsHash || frozen.termsHash !== selected.termsHash)
87000
+ throw new TasksValidationError(
87001
+ "The accepted task scope does not match its locally verified terms hash and milestone."
87002
87002
  );
87003
- const profile = matches[0];
87004
- return profile ? {
87005
- maxPerTaskUsd: profile.maxPerTaskUsd,
87006
- approveAboveUsd: profile.approveAboveUsd,
87007
- autoReleaseBelowUsd: profile.autoReleaseBelowUsd,
87008
- source: "agent-profile"
87009
- } : {
87010
- maxPerTaskUsd: DEFAULT_MAX_PER_TASK_USD,
87011
- approveAboveUsd: agentProfileSchema.shape.approveAboveUsd.parse(void 0),
87012
- autoReleaseBelowUsd: DEFAULT_AUTO_RELEASE_BELOW_USD,
87013
- source: "defaults"
87003
+ if (!scope.counterpartyAddress || !scope.counterpartySignature || isAddressEqual(scope.proposerAddress, scope.counterpartyAddress) || !(isAddressEqual(signer, scope.proposerAddress) || isAddressEqual(signer, scope.counterpartyAddress)))
87004
+ throw new TasksValidationError(
87005
+ "The local signer is not one of the two accepted scope parties."
87006
+ );
87007
+ const message = canonicalJson(payload);
87008
+ const signatures = await Promise.all([
87009
+ verifyMessage({
87010
+ address: scope.proposerAddress,
87011
+ message,
87012
+ signature: scope.proposerSignature
87013
+ }),
87014
+ verifyMessage({
87015
+ address: scope.counterpartyAddress,
87016
+ message,
87017
+ signature: scope.counterpartySignature
87018
+ })
87019
+ ]);
87020
+ if (signatures.some((valid) => !valid))
87021
+ throw new TasksValidationError("Both accepted task scope signatures must verify.");
87022
+ const terms = frozen.structured;
87023
+ if (terms.budget.network !== ready.network || terms.budget.asset.toLowerCase() !== `${ready.network}/erc20:${ready.usdc}`.toLowerCase() || !isAddressEqual(terms.escrow.contract, ready.escrowContract) || selected.network !== terms.budget.network || selected.asset.toLowerCase() !== terms.budget.asset.toLowerCase() || selected.amountBaseUnits !== terms.budget.amountBaseUnits)
87024
+ throw new TasksValidationError(
87025
+ "The signed task scope asset, factory or amount does not match the deployment and milestone."
87026
+ );
87027
+ const identity = {
87028
+ orderId: selected.workOrderId,
87029
+ trancheOrdinal: selected.ordinal,
87030
+ scopeVersion: scope.version,
87031
+ termsHash: frozen.termsHash,
87032
+ self: getAddress(signer)
87014
87033
  };
87015
- }
87016
- async function taskMoneySnapshot(client, orderId, escrowId, options = { signInHint: "" }) {
87017
- const order = await taskRequest(
87018
- "task money",
87019
- "getOrder",
87020
- () => client.getOrder(orderId),
87021
- options
87022
- ), workOrder = order.workOrder;
87023
- if (workOrder.id !== orderId || workOrder.version !== "work-order-view-v1")
87024
- throw new TaskOperationError(
87025
- "invalid_response",
87026
- "A private task order matching the requested ID is required."
87034
+ const binding = await options.bindings?.get(identity);
87035
+ if (!binding) throw new TasksPartiesNotBoundError();
87036
+ if (options.counterparty && !isAddressEqual(binding.counterparty, options.counterparty))
87037
+ throw new TasksValidationError(
87038
+ "The confirmed counterparty differs from the locally bound parties."
87039
+ );
87040
+ if (!isAddressEqual(binding.self, signer) || binding.orderId !== identity.orderId || binding.trancheOrdinal !== identity.trancheOrdinal || binding.scopeVersion !== identity.scopeVersion || binding.termsHash.toLowerCase() !== identity.termsHash.toLowerCase() || ![scope.proposerAddress, scope.counterpartyAddress].every(
87041
+ (address10) => isAddressEqual(address10, binding.self) || isAddressEqual(address10, binding.counterparty)
87042
+ ))
87043
+ throw new TasksValidationError(
87044
+ "The accepted scope parties do not match the locally bound parties."
87045
+ );
87046
+ const buyer = getAddress(binding.role === "client" ? binding.self : binding.counterparty);
87047
+ const seller = getAddress(binding.role === "provider" ? binding.self : binding.counterparty);
87048
+ if (verb === "createEscrow" && !isAddressEqual(signer, seller))
87049
+ throw new TasksValidationError("Task createEscrow requires the locally bound seller's wallet.");
87050
+ const workDurationSeconds = terms.workDurationSeconds ?? getTrustedTasksDurations(ready.chainId, options.trustedDurations).workDurationSeconds;
87051
+ if (workDurationSeconds === void 0)
87052
+ throw new TasksValidationError(
87053
+ "The signed task scope has no work duration and no trusted default is configured."
87027
87054
  );
87028
- const matches = escrowId ? workOrder.milestones.filter((m) => m.id === escrowId) : workOrder.milestones;
87029
- if (matches.length !== 1)
87030
- throw new TaskOperationError("invalid_response", "Select one task milestone by escrow ID.");
87031
- const milestone = matches[0];
87032
- if (milestone.workOrderId !== orderId)
87033
- throw new TaskOperationError("invalid_response", "The milestone belongs to a different task.");
87034
- let readiness;
87035
- try {
87036
- readiness = { ok: true, value: await client.deployment() };
87037
- } catch (error61) {
87038
- readiness = { ok: false, error: error61 };
87039
- }
87040
87055
  return {
87041
- order,
87042
- escrowId: milestone.id,
87043
- money: taskMoney(milestone.amountBaseUnits, readiness.ok ? parseFeeBp(readiness.value) : null),
87044
- readiness
87056
+ signer,
87057
+ buyer,
87058
+ seller,
87059
+ parties: [buyer, seller],
87060
+ workDurationSeconds,
87061
+ ...verb === "fund" ? { approveAmount: BigInt(terms.budget.amountBaseUnits) } : {},
87062
+ reviewWindowSeconds: terms.acceptanceWindowSeconds,
87063
+ nowSeconds: BigInt(Math.floor((options.now ?? (() => /* @__PURE__ */ new Date()))().getTime() / 1e3)),
87064
+ verb,
87065
+ deployment: ready,
87066
+ milestone: {
87067
+ ...selected,
87068
+ terms,
87069
+ termsHash: frozen.termsHash,
87070
+ amountBaseUnits: terms.budget.amountBaseUnits
87071
+ },
87072
+ steps
87045
87073
  };
87046
87074
  }
87047
- function cachedMoneyClient(client, snapshot) {
87048
- return new Proxy(client, {
87049
- get(target, property) {
87050
- if (property === "getOrder")
87051
- return async (id2) => {
87052
- if (id2 !== snapshot.order.workOrder.id)
87053
- throw new Error("The cached task order does not match the requested ID.");
87054
- return snapshot.order;
87055
- };
87056
- if (property === "deployment")
87057
- return async () => {
87058
- if (snapshot.readiness.ok) return snapshot.readiness.value;
87059
- throw snapshot.readiness.error;
87060
- };
87061
- const value = Reflect.get(target, property, target);
87062
- return typeof value === "function" ? value.bind(target) : value;
87063
- }
87075
+ async function verifyClone(rpc, expected, checkState) {
87076
+ if (expected.verb === "createEscrow") return;
87077
+ const clone2 = expected.milestone.escrowContract;
87078
+ const registered = await rpc.readContract({
87079
+ address: expected.deployment.escrowContract,
87080
+ abi: TASKS_READ_ABI,
87081
+ functionName: "isEscrow",
87082
+ args: [clone2]
87064
87083
  });
87065
- }
87066
- function fundingRefusalReason(error61) {
87067
- if (error61 instanceof Error && error61.name === "SpendCapExceededError") {
87068
- const fromCause = fundingRefusalReason(error61.cause);
87069
- if (fromCause) return fromCause;
87070
- return "cap" in error61 && error61.cap === "per_day" ? "policy.perDay" : void 0;
87084
+ if (!registered)
87085
+ throw new TasksValidationError(
87086
+ "The task escrow clone is not registered by the trusted factory."
87087
+ );
87088
+ const predicted = await rpc.readContract({
87089
+ address: expected.deployment.escrowContract,
87090
+ abi: TASKS_READ_ABI,
87091
+ functionName: "predictEscrow",
87092
+ args: [expected.seller, keccak256(stringToHex(expected.milestone.id))]
87093
+ });
87094
+ if (!isAddressEqual(predicted, clone2))
87095
+ throw new TasksValidationError(
87096
+ "The escrow clone does not match the signed milestone salt and bound seller."
87097
+ );
87098
+ const read = (functionName) => rpc.readContract({ address: clone2, abi: TASKS_READ_ABI, functionName });
87099
+ const [
87100
+ buyer,
87101
+ seller,
87102
+ token,
87103
+ amount4,
87104
+ termsHash,
87105
+ state,
87106
+ resolution,
87107
+ offerDeadline,
87108
+ workDeadline,
87109
+ reviewDeadline,
87110
+ disputedAt,
87111
+ counterEvidenceDeadline,
87112
+ slot0,
87113
+ slot6,
87114
+ slot7
87115
+ ] = await Promise.all([
87116
+ read("buyer"),
87117
+ read("seller"),
87118
+ read("token"),
87119
+ read("amount"),
87120
+ read("termsHash"),
87121
+ read("state"),
87122
+ read("resolution"),
87123
+ read("offerDeadline"),
87124
+ read("workDeadline"),
87125
+ read("reviewDeadline"),
87126
+ read("disputedAt"),
87127
+ read("counterEvidenceDeadline"),
87128
+ rpc.getStorageAt({ address: clone2, slot: "0x0" }),
87129
+ rpc.getStorageAt({ address: clone2, slot: "0x6" }),
87130
+ rpc.getStorageAt({ address: clone2, slot: "0x7" })
87131
+ ]);
87132
+ if (isAddressEqual(buyer, seller) || !isAddressEqual(buyer, expected.buyer) || !isAddressEqual(seller, expected.seller) || !isAddressEqual(token, expected.deployment.usdc) || amount4 !== BigInt(expected.milestone.amountBaseUnits) || termsHash.toLowerCase() !== expected.milestone.termsHash.toLowerCase())
87133
+ throw new TasksValidationError(
87134
+ "The onchain escrow parties, token, amount or terms hash do not match the signed scope."
87135
+ );
87136
+ const s0 = storageWord(slot0);
87137
+ const s6 = storageWord(slot6);
87138
+ const s7 = storageWord(slot7);
87139
+ if (field(s0, 0, 1) !== BigInt(state) || field(s0, 1, 1) !== BigInt(resolution) || !isAddressEqual(storageAddress(s0, 2), buyer) || field(s6, 0, 8) !== offerDeadline || field(s6, 8, 8) !== workDeadline || field(s6, 16, 8) !== reviewDeadline || field(s6, 24, 8) !== disputedAt || field(s7, 0, 8) !== counterEvidenceDeadline)
87140
+ throw new TasksValidationError("unsupported escrow layout");
87141
+ if (field(s7, 8, 8) !== BigInt(expected.workDurationSeconds) || field(s7, 16, 8) !== BigInt(expected.reviewWindowSeconds))
87142
+ throw new TasksValidationError(
87143
+ "The onchain escrow durations do not match the signed terms and trusted defaults."
87144
+ );
87145
+ const actor = expected.verb === "fund" || expected.verb === "release" ? buyer : expected.verb === "deliver" || expected.verb === "refund" ? seller : expected.signer;
87146
+ if (!isAddressEqual(actor, expected.signer))
87147
+ throw new TasksValidationError(
87148
+ `Task ${expected.verb} requires the onchain escrow party's local wallet.`
87149
+ );
87150
+ const states = {
87151
+ fund: [1],
87152
+ deliver: [2],
87153
+ release: [3],
87154
+ refund: [2, 3],
87155
+ dispute: [2, 3],
87156
+ "counter-evidence": [4],
87157
+ "resolve-unmatched": [4]
87158
+ };
87159
+ if (checkState && !states[expected.verb]?.includes(state))
87160
+ throw new TasksValidationError(
87161
+ `The onchain escrow state is not eligible for task ${expected.verb}.`
87162
+ );
87163
+ if (["dispute", "counter-evidence"].includes(expected.verb)) {
87164
+ const fee = disputeFeeBaseUnits(amount4);
87165
+ if (await read("disputeFee") !== fee)
87166
+ throw new TasksValidationError(
87167
+ "The onchain dispute fee does not match the verified amount fee rule."
87168
+ );
87169
+ expected.disputeFee = fee;
87170
+ expected.approveAmount = fee;
87071
87171
  }
87072
- if (!(error61 instanceof SpendCapError || error61 instanceof Error && error61.name === "SpendCapError"))
87073
- return void 0;
87074
- const code = "code" in error61 ? error61.code : void 0;
87075
- return code === "per_task_cap_exceeded" ? "policy.perTask" : code === "per_day_cap_exceeded" ? "policy.perDay" : void 0;
87172
+ if (checkState && ["counter-evidence", "resolve-unmatched"].includes(expected.verb)) {
87173
+ const slot8 = storageWord(await rpc.getStorageAt({ address: clone2, slot: "0x8" }));
87174
+ const opener = storageAddress(slot8, 0);
87175
+ const submitted = field(slot8, 20, 1);
87176
+ if (!isAddressEqual(opener, buyer) && !isAddressEqual(opener, seller) || submitted > 1n || field(slot8, 21, 11) !== 0n)
87177
+ throw new TasksValidationError("unsupported escrow layout");
87178
+ const now = expected.nowSeconds;
87179
+ if (now === void 0)
87180
+ throw new TasksValidationError("A trusted clock is required for dispute eligibility.");
87181
+ if (submitted === 1n)
87182
+ throw new TasksValidationError(
87183
+ "Counter-evidence has already been submitted for this dispute."
87184
+ );
87185
+ if (expected.verb === "counter-evidence") {
87186
+ if (isAddressEqual(opener, expected.signer))
87187
+ throw new TasksValidationError("Only the non-opener party can submit counter-evidence.");
87188
+ if (now >= counterEvidenceDeadline)
87189
+ throw new TasksValidationError("The counter-evidence deadline has passed.");
87190
+ } else if (now <= counterEvidenceDeadline)
87191
+ throw new TasksValidationError(
87192
+ "The counter-evidence deadline has not passed; unmatched resolution is unavailable."
87193
+ );
87194
+ }
87195
+ expected.offerDeadline = offerDeadline;
87076
87196
  }
87077
- function taskEventLine(event) {
87078
- const label2 = event.type === "task.judging" ? `deadline passed, ${event.payload.submissionCount} submissions, pick winners` : event.type === "task.claimed" ? "first submission received" : event.type === "task.checkin" ? `check-in: ${event.payload.status ?? "received"}` : event.type === "task.stalled" ? "task stalled" : event.type === "task.milestone" ? "milestone updated" : event.type === "task.released" ? "escrow released" : event.type;
87079
- return `${event.sequence}: ${[label2, ...taskV2OutcomeLines(event.payload)].join(" \xB7 ")}`;
87197
+ function storageWord(value) {
87198
+ if (!value || !/^0x[0-9a-fA-F]{64}$/.test(value))
87199
+ throw new TasksValidationError("unsupported escrow layout");
87200
+ return BigInt(value);
87080
87201
  }
87081
- function requireTaskMethod(client, name) {
87082
- const method = client[name];
87083
- if (typeof method !== "function")
87084
- throw new TaskOperationError(
87085
- "not_supported",
87086
- `Task method ${name} is not supported by this SDK adapter.`
87087
- );
87088
- return method.bind(client);
87202
+ function field(word, offset, bytes) {
87203
+ return word >> BigInt(offset * 8) & (1n << BigInt(bytes * 8)) - 1n;
87204
+ }
87205
+ function storageAddress(word, offset) {
87206
+ return getAddress(`0x${field(word, offset, 20).toString(16).padStart(40, "0")}`);
87089
87207
  }
87090
87208
 
87091
87209
  // ../core/src/tasks/v2-trust.ts
@@ -87178,12 +87296,65 @@ function getTrustedTasksV2Deployment(chainId, options = {}) {
87178
87296
  return normalized2;
87179
87297
  }
87180
87298
 
87299
+ // ../core/src/tasks/v2-limits.ts
87300
+ var feeBpSchema = external_exports.union([external_exports.number(), external_exports.bigint()]).transform(Number).pipe(external_exports.number().int().min(0).max(2e3));
87301
+ var capSchema = external_exports.bigint().positive();
87302
+ async function readTaskV2Limits(input2) {
87303
+ const read = async () => {
87304
+ const pin = getTrustedTasksV2Deployment(input2.chainId, {
87305
+ ...input2.trustedV2Deployments ? { overrides: input2.trustedV2Deployments } : {},
87306
+ ...input2.env ? { env: input2.env } : {},
87307
+ // Display and pre-check only; the signing path prints the override notice.
87308
+ notice: input2.onV2UntrustedOverride ?? (() => {
87309
+ })
87310
+ });
87311
+ const rpc = input2.rpcFor(input2.chainId);
87312
+ if (await rpc.getChainId() !== input2.chainId) throw new Error("RPC chain mismatch");
87313
+ const pool = input2.shape === "pool";
87314
+ const address10 = pool ? pin.bountyPoolFactoryV1 : pin.escrowFactoryV2;
87315
+ const abi2 = pool ? bountyPoolFactoryV1Abi : escrowFactoryV2Abi;
87316
+ const [feeBp, cap] = await Promise.all([
87317
+ rpc.readContract({ address: address10, abi: abi2, functionName: "feeBp" }),
87318
+ rpc.readContract({
87319
+ address: address10,
87320
+ abi: abi2,
87321
+ functionName: pool ? "maxPoolBudget" : "maxEscrowAmount"
87322
+ })
87323
+ ]);
87324
+ return {
87325
+ chainId: input2.chainId,
87326
+ shape: input2.shape,
87327
+ feeBp: feeBpSchema.parse(feeBp),
87328
+ maxBaseUnits: capSchema.parse(cap)
87329
+ };
87330
+ };
87331
+ let timer;
87332
+ try {
87333
+ return await Promise.race([
87334
+ read(),
87335
+ new Promise((resolve3) => {
87336
+ timer = setTimeout(() => resolve3(void 0), input2.timeoutMs ?? 5e3);
87337
+ })
87338
+ ]);
87339
+ } catch {
87340
+ return void 0;
87341
+ } finally {
87342
+ if (timer) clearTimeout(timer);
87343
+ }
87344
+ }
87345
+ function assertWithinTaskV2Limit(totalBaseUnits, limits, untouched = "Nothing was signed and no money moved.") {
87346
+ if (totalBaseUnits <= limits.maxBaseUnits) return;
87347
+ throw new TaskInputError(
87348
+ `The total of $${formatBaseUnitsUsd(totalBaseUnits)} USDC is above the live limit of $${formatBaseUnitsUsd(limits.maxBaseUnits)} USDC per ${limits.shape} on ${taskNetworkName(limits.chainId)}. ${untouched}`
87349
+ );
87350
+ }
87351
+
87181
87352
  // ../core/src/tasks/v2-plan-guard.ts
87182
87353
  var address5 = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u).transform((v) => getAddress(v));
87183
87354
  var hash5 = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/u).transform((v) => v.toLowerCase());
87184
87355
  var uint2 = external_exports.union([external_exports.bigint(), external_exports.number().int().nonnegative(), external_exports.string().regex(/^\d+$/u)]).transform(BigInt);
87185
87356
  var small = (max) => external_exports.union([external_exports.number(), external_exports.bigint()]).transform(Number).pipe(external_exports.number().int().min(0).max(max));
87186
- var feeBpSchema = small(2e3);
87357
+ var feeBpSchema2 = small(2e3);
87187
87358
  var escrowTermsSchema = external_exports.object({
87188
87359
  shape: small(1),
87189
87360
  poster: address5,
@@ -87195,7 +87366,7 @@ var escrowTermsSchema = external_exports.object({
87195
87366
  bountyDeadline: uint2,
87196
87367
  objectionWindow: uint2,
87197
87368
  workerBondBp: small(2e3),
87198
- feeBp: feeBpSchema,
87369
+ feeBp: feeBpSchema2,
87199
87370
  winners: small(255),
87200
87371
  rewardPerWinner: uint2
87201
87372
  });
@@ -87459,7 +87630,7 @@ function verifyActor(action, signer, poster, worker, verifier) {
87459
87630
  );
87460
87631
  }
87461
87632
  async function creationPolicy(rpc, pin, pool) {
87462
- const feeBp = feeBpSchema.parse(
87633
+ const feeBp = feeBpSchema2.parse(
87463
87634
  await v2Read(
87464
87635
  rpc,
87465
87636
  pool ? pin.bountyPoolFactoryV1 : pin.escrowFactoryV2,
@@ -87478,10 +87649,13 @@ async function verifyFundingDeadlines(rpc, contract, deadlines, timestamp) {
87478
87649
  `Every milestone deadline must leave at least MIN_WORK_TIME (${minimum} seconds) from the trusted chain clock before creation or funding so the task can be awarded.`
87479
87650
  );
87480
87651
  }
87481
- async function verifyV2Target(options, current, view, action, knownTarget) {
87652
+ async function verifyV2Target(options, current, view, action, knownTarget, fundingMined = false) {
87482
87653
  const operation = taskV2OperationResponseSchema.safeParse(current);
87483
87654
  const intent = taskV2IntentSchema.safeParse(current);
87484
- const chainId = operation.success ? operation.data.operation.plan.chainId : intent.success ? intent.data.typedData.domain.chainId : external_exports.object({ chainId: external_exports.number().int().positive() }).parse(current).chainId;
87655
+ const plan = operation.success ? operation.data.operation.plan : null;
87656
+ if (operation.success && !plan)
87657
+ return v2GuardFailure("The hosted operation carries no plan to verify.");
87658
+ const chainId = plan ? plan.chainId : intent.success ? intent.data.typedData.domain.chainId : external_exports.object({ chainId: external_exports.number().int().positive() }).parse(current).chainId;
87485
87659
  const binding = await options.pending.v2Target?.(view.workOrder.id);
87486
87660
  if (action.action === "bump-consent-nonce" && !binding)
87487
87661
  return v2GuardFailure("Revocation requires a locally accepted consent target binding.");
@@ -87513,11 +87687,8 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
87513
87687
  let candidate = knownTarget ?? external_exports.object({ escrow: address5 }).safeParse(order.v2State).data?.escrow ?? (intent.success ? external_exports.object({ escrow: address5 }).safeParse(intent.data).data?.escrow : void 0);
87514
87688
  let creationArgs;
87515
87689
  let fresh;
87516
- if (action.action === "fund" && operation.success && same(operation.data.operation.plan.to, factory)) {
87517
- const decoded = decodeFunctionData({
87518
- abi: factoryAbi,
87519
- data: operation.data.operation.plan.data
87520
- });
87690
+ if (action.action === "fund" && plan && same(plan.to, factory)) {
87691
+ const decoded = decodeFunctionData({ abi: factoryAbi, data: plan.data });
87521
87692
  const names = pool ? ["createPool"] : ["createEscrow", "createAndFundWithAuthorization"];
87522
87693
  if (!names.includes(decoded.functionName))
87523
87694
  return v2GuardFailure("Unexpected V2 factory funding selector.");
@@ -87527,7 +87698,7 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
87527
87698
  verifyAcceptedCreation(options, view, pin, creationArgs, pool, chainId, fresh);
87528
87699
  candidate = await predict(creationArgs);
87529
87700
  }
87530
- if (action.action === "fund" && operation.success && operation.data.operation.plan.step === "v2-approve-usdc" && (!candidate || !await isRegistered(candidate))) {
87701
+ if (action.action === "fund" && plan?.step === "v2-approve-usdc" && (!candidate || !await isRegistered(candidate))) {
87531
87702
  fresh = await creationPolicy(rpc, pin, pool);
87532
87703
  creationArgs = acceptedCreationArgs(options, view, pin, chainId, fresh);
87533
87704
  verifyAcceptedCreation(options, view, pin, creationArgs, pool, chainId, fresh);
@@ -87543,7 +87714,7 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
87543
87714
  "The V2 target cannot be independently verified from this response. A registered target or verifiable funding creation terms are required."
87544
87715
  );
87545
87716
  if (!await isRegistered(candidate)) {
87546
- if (action.action !== "fund" || !operation.success || !creationArgs || !fresh)
87717
+ if (action.action !== "fund" || !plan || !creationArgs || !fresh)
87547
87718
  return v2GuardFailure("The V2 target is not registered by the locally pinned factory.");
87548
87719
  const expectedCreation = acceptedCreationArgs(options, view, pin, chainId, fresh);
87549
87720
  if (canon(creationArgs) !== canon(expectedCreation))
@@ -87595,7 +87766,7 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
87595
87766
  poster = address5.parse(await read("poster"));
87596
87767
  verifier = address5.parse(await read("verifier"));
87597
87768
  total = uint2.parse(await read("budget"));
87598
- feeBp = feeBpSchema.parse(await read("feeBp"));
87769
+ feeBp = feeBpSchema2.parse(await read("feeBp"));
87599
87770
  termsHash = hash5.parse(await read("termsHash"));
87600
87771
  creationArgs = [
87601
87772
  poster,
@@ -87659,7 +87830,7 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
87659
87830
  "The V2 target differs from the pinned factory's prediction for the requested order."
87660
87831
  );
87661
87832
  verifyBinding(candidate, termsHash);
87662
- if (action.action === "fund" && !pool && !bounty)
87833
+ if (action.action === "fund" && !pool && !bounty && !fundingMined)
87663
87834
  await verifyFundingDeadlines(
87664
87835
  rpc,
87665
87836
  candidate,
@@ -87763,6 +87934,7 @@ function acceptedV2WorkerBond(target, view) {
87763
87934
  }
87764
87935
  async function verifyV2Plan(target, op, action, pays, fundingAuthorization) {
87765
87936
  const plan = op.plan;
87937
+ if (!plan) return v2GuardFailure("The hosted operation carries no plan to verify.");
87766
87938
  if (plan.value !== "0" || plan.chainId !== target.chainId)
87767
87939
  return v2GuardFailure("V2 plan value or chain mismatch.");
87768
87940
  const authorizationArgs = fundingAuthorization ? [
@@ -88029,7 +88201,8 @@ function isTaskV2SecretAction(action) {
88029
88201
  return action.action === "commit-vote" || action.action === "reveal-vote";
88030
88202
  }
88031
88203
  function publicTaskV2Operation(op, secret = false) {
88032
- const reveal = secret || op.step === "v2-reveal-vote" || op.plan.step === "v2-reveal-vote" || op.plan.data.toLowerCase().startsWith(REVEAL_SELECTOR);
88204
+ const plan = op.plan;
88205
+ const reveal = secret || op.step === "v2-reveal-vote" || plan?.step === "v2-reveal-vote" || plan?.data.toLowerCase().startsWith(REVEAL_SELECTOR) === true;
88033
88206
  return {
88034
88207
  id: op.id,
88035
88208
  kind: op.kind,
@@ -88037,16 +88210,17 @@ function publicTaskV2Operation(op, secret = false) {
88037
88210
  step: op.step,
88038
88211
  expectedActor: op.expectedActor,
88039
88212
  transactionHash: op.transactionHash,
88040
- plan: {
88041
- version: op.plan.version,
88042
- operationId: op.plan.operationId,
88043
- step: op.plan.step,
88044
- chainId: op.plan.chainId,
88045
- network: op.plan.network,
88046
- from: op.plan.from,
88047
- to: op.plan.to,
88048
- data: reveal ? TASK_V2_REDACTED_CALLDATA : op.plan.data,
88049
- value: op.plan.value
88213
+ // Null once the transaction is submitted or confirmed: the API no longer returns the plan.
88214
+ plan: plan && {
88215
+ version: plan.version,
88216
+ operationId: plan.operationId,
88217
+ step: plan.step,
88218
+ chainId: plan.chainId,
88219
+ network: plan.network,
88220
+ from: plan.from,
88221
+ to: plan.to,
88222
+ data: reveal ? TASK_V2_REDACTED_CALLDATA : plan.data,
88223
+ value: plan.value
88050
88224
  }
88051
88225
  };
88052
88226
  }
@@ -88067,7 +88241,7 @@ var shownOperationSchema = external_exports.object({
88067
88241
  to: external_exports.string(),
88068
88242
  data: external_exports.string(),
88069
88243
  value: external_exports.literal("0")
88070
- })
88244
+ }).nullable()
88071
88245
  });
88072
88246
  function publicTaskV2OperationOf(value, secret = false) {
88073
88247
  const parsed = shownOperationSchema.safeParse(value);
@@ -88287,6 +88461,9 @@ function bufferedV2Gas(estimate) {
88287
88461
  var fail = (message) => {
88288
88462
  throw new TaskOperationError("invalid_response", message);
88289
88463
  };
88464
+ var balanceAbi = parseAbi(["function balanceOf(address account) view returns (uint256)"]);
88465
+ var PAID_NOW_ACTIONS = ["fund", "raise-dispute", "counter-evidence"];
88466
+ var RESERVING_ACTIONS = [...PAID_NOW_ACTIONS, "approve-bond"];
88290
88467
  async function taskUsesV2(context, id2) {
88291
88468
  if (!context.client.prepareV2) return false;
88292
88469
  const { workOrder } = await context.client.getOrder(id2);
@@ -88314,6 +88491,7 @@ async function executeTaskV2(context, input2) {
88314
88491
  }
88315
88492
  const saved = journal.preparedV2;
88316
88493
  if (saved) return saved;
88494
+ requireTasksAvailable(action.action, await readTasksReadiness(context.client));
88317
88495
  const result = await (input2.consent ? context.client.signV2(input2.id, input2.consent, journal) : context.client.prepareV2(input2.id, input2.write, journal));
88318
88496
  await context.pending?.bindPreparedV2?.(input2.id, verb, result);
88319
88497
  return result;
@@ -88347,17 +88525,76 @@ function createTaskV2Executor(options) {
88347
88525
  journal = { idempotencyKey: input2.preparationKey ?? randomUUID4(), inputs: action };
88348
88526
  await pending.putPreparation(input2.id, verb, journal);
88349
88527
  }
88350
- let current = taskV2PreparedSchema.parse(
88351
- input2.prepared ?? journal.preparedV2 ?? await (input2.consent ? sign2(input2.id, input2.consent, journal) : prepare(input2.id, input2.write, journal))
88352
- );
88353
88528
  if (!pending.bindPreparedV2) fail("Durable V2 preparation storage is unavailable.");
88354
- await pending.bindPreparedV2(input2.id, verb, current);
88529
+ const supplied = input2.prepared ?? journal.preparedV2;
88530
+ let current = supplied === void 0 ? void 0 : taskV2PreparedSchema.parse(supplied);
88531
+ if (current) await pending.bindPreparedV2(input2.id, verb, current);
88532
+ const finalStep = action.action === "approve-bond" ? "v2-approve-usdc" : `v2-${action.action}`;
88533
+ const allowedSteps = action.action === "fund" ? ["v2-create-escrow", "v2-create-pool", "v2-approve-usdc", "v2-fund"] : action.action === "raise-dispute" || action.action === "counter-evidence" ? ["v2-approve-usdc", finalStep] : [finalStep];
88534
+ const reservedForTask = (excludeReservationId) => taskReservedAtomic({
88535
+ ledgerPath: input2.ledgerPath,
88536
+ wallet: input2.wallet,
88537
+ taskKey: input2.id,
88538
+ now: now(),
88539
+ ...excludeReservationId === void 0 ? {} : { excludeReservationId }
88540
+ });
88541
+ const savedOperation = journal.operationId;
88542
+ const savedTransaction = savedOperation !== void 0 && (await Promise.all(allowedSteps.map((step2) => pending.get(savedOperation, step2)))).some(
88543
+ (entry) => entry !== void 0
88544
+ );
88545
+ const signedBefore = journal.signed === true;
88546
+ const started = savedTransaction || RESERVING_ACTIONS.includes(action.action) && (signedBefore || await reservedForTask() !== await reservedForTask(journal.idempotencyKey));
88547
+ const savedFinal = savedOperation === void 0 ? void 0 : await pending.get(savedOperation, finalStep);
88548
+ const mined = savedFinal && isAddressEqual(savedFinal.signer, account.address) && (await Promise.resolve().then(
88549
+ () => rpcFor(savedFinal.chainId).getTransactionReceipt({ hash: savedFinal.txHash })
88550
+ ).catch(() => void 0))?.status === "success" ? savedFinal : void 0;
88551
+ if (current && !started && action.action === "fund" && "kind" in current && current.kind === "eip712") {
88552
+ const end = external_exports.object({ validBefore: uint3 }).safeParse(taskV2IntentSchema.parse(current).typedData.message);
88553
+ if (end.success && BigInt(end.data.validBefore) * 1000n <= BigInt(now().getTime())) {
88554
+ await pending.completePreparation(input2.id, verb);
88555
+ journal = { idempotencyKey: randomUUID4(), inputs: action };
88556
+ await pending.putPreparation(input2.id, verb, journal);
88557
+ current = void 0;
88558
+ }
88559
+ }
88560
+ const readiness = await readTasksReadiness(client);
88561
+ if (!started)
88562
+ requireTasksAvailable(
88563
+ action.action,
88564
+ readiness,
88565
+ input2.consent && journal.preparedV2 ? `This run signed nothing and moved no money. A consent this wallet signed earlier for this task may still be valid until it expires; vapi task bump-consent-nonce ${input2.id} --new-nonce <n> revokes it.` : void 0
88566
+ );
88567
+ if (!current) {
88568
+ current = taskV2PreparedSchema.parse(
88569
+ await (input2.consent ? sign2(input2.id, input2.consent, journal) : prepare(input2.id, input2.write, journal))
88570
+ );
88571
+ await pending.bindPreparedV2(input2.id, verb, current);
88572
+ }
88355
88573
  const view = await client.getOrder(input2.id);
88356
88574
  if (view.workOrder.id !== input2.id) fail("The money view belongs to another task.");
88357
88575
  const terms = view.workOrder.terms;
88358
88576
  const state = stateSchema.safeParse(view.workOrder.v2State);
88359
- const deployment = await client.deployment();
88360
- const target = await verifyV2Target(options, current, view, action);
88577
+ const resumed = taskV2OperationResponseSchema.safeParse(current);
88578
+ let resumedChainId;
88579
+ if (resumed.success && !resumed.data.operation.plan) {
88580
+ resumedChainId = (await pending.v2Target?.(input2.id))?.chainId ?? readiness?.chainId;
88581
+ if (resumedChainId === void 0)
88582
+ fail("The hosted operation carries no plan and its chain cannot be read.");
88583
+ }
88584
+ const target = await verifyV2Target(
88585
+ options,
88586
+ resumedChainId === void 0 ? current : { chainId: resumedChainId },
88587
+ view,
88588
+ action,
88589
+ void 0,
88590
+ mined !== void 0
88591
+ );
88592
+ if (mined && mined.chainId !== target.chainId)
88593
+ fail("The saved transaction is for another chain than the verified task.");
88594
+ if (readiness && target.chainId !== readiness.chainId)
88595
+ fail(
88596
+ `The prepared step is for ${taskNetworkName(target.chainId)}, but vAPI serves Tasks on ${taskNetworkName(readiness.chainId)}. ${started ? "No new step was signed." : "Nothing was signed."}`
88597
+ );
88361
88598
  if (state.success && (BigInt(state.data.totalBaseUnits) !== target.total || state.data.feeBp !== target.feeBp))
88362
88599
  v2GuardFailure("Hosted money snapshot differs from the verified V2 target.");
88363
88600
  let gross = 0n, pays = 0n;
@@ -88401,8 +88638,7 @@ function createTaskV2Executor(options) {
88401
88638
  else gross = total ?? 0n;
88402
88639
  feeBp = 0;
88403
88640
  } else if (action.action === "raise-dispute" || action.action === "counter-evidence") {
88404
- if (!state.success || !deployment.configured)
88405
- fail("Hosted dispute binding is unavailable.");
88641
+ if (!state.success) fail("Hosted dispute binding is unavailable.");
88406
88642
  pays = gross = await target.rpc.readContract({
88407
88643
  address: target.escrow,
88408
88644
  abi: escrowV2Abi,
@@ -88460,6 +88696,44 @@ function createTaskV2Executor(options) {
88460
88696
  }
88461
88697
  };
88462
88698
  await input2.onMoney?.(money2);
88699
+ if (action.action === "fund" && !started) {
88700
+ const cap = await v2Read(
88701
+ target.rpc,
88702
+ target.factory,
88703
+ target.pool ? bountyPoolFactoryV1Abi : escrowFactoryV2Abi,
88704
+ target.pool ? "maxPoolBudget" : "maxEscrowAmount"
88705
+ ).catch(() => void 0);
88706
+ if (typeof cap === "bigint" && cap > 0n)
88707
+ assertWithinTaskV2Limit(gross, {
88708
+ chainId: target.chainId,
88709
+ shape: target.pool ? "pool" : target.bounty ? "bounty" : "task",
88710
+ feeBp: target.feeBp,
88711
+ maxBaseUnits: cap
88712
+ });
88713
+ }
88714
+ if (pays > 0n && PAID_NOW_ACTIONS.includes(action.action) && !started) {
88715
+ const balance = await target.rpc.readContract({
88716
+ address: target.pin.usdc,
88717
+ abi: balanceAbi,
88718
+ functionName: "balanceOf",
88719
+ args: [account.address]
88720
+ }).catch(() => void 0);
88721
+ if (typeof balance === "bigint" && balance < pays)
88722
+ throw new TaskOperationError(
88723
+ "insufficient_usdc",
88724
+ `This step pays $${formatBaseUnitsUsd(pays)} USDC, but the wallet holds $${formatBaseUnitsUsd(balance)} on ${taskNetworkName(target.chainId)}. Nothing was signed and no money moved.`,
88725
+ void 0,
88726
+ progress
88727
+ );
88728
+ const gas = await Promise.resolve().then(() => target.rpc.getBalance({ address: account.address })).catch(() => void 0);
88729
+ if (gas === 0n)
88730
+ throw new TaskOperationError(
88731
+ "insufficient_gas",
88732
+ `The wallet holds no ETH on ${taskNetworkName(target.chainId)} to pay for the transaction. Nothing was signed and no money moved.`,
88733
+ void 0,
88734
+ progress
88735
+ );
88736
+ }
88463
88737
  const reservationKey = journal.idempotencyKey;
88464
88738
  const remaining2 = pays > 0n ? await escrowFundingDayRemainingAtomic({
88465
88739
  caps: input2.caps,
@@ -88475,11 +88749,11 @@ function createTaskV2Executor(options) {
88475
88749
  now: now(),
88476
88750
  excludeReservationId: reservationKey
88477
88751
  }) : 0n;
88478
- if (pays + alreadyReserved > taskPolicyAtomic(input2.policy.maxPerTaskUsd))
88752
+ if (!mined && pays + alreadyReserved > taskPolicyAtomic(input2.policy.maxPerTaskUsd))
88479
88753
  return { ok: false, reason: "policy.perTask", money: money2, ...progress };
88480
- if (pays > remaining2)
88754
+ if (!mined && pays > remaining2)
88481
88755
  return { ok: false, reason: "policy.perDay", money: money2, ...progress };
88482
- if (pays > taskPolicyAtomic(input2.policy.approveAboveUsd)) {
88756
+ if (!mined && pays > taskPolicyAtomic(input2.policy.approveAboveUsd)) {
88483
88757
  if (input2.approval && "ask" in input2.approval) {
88484
88758
  if (!await input2.approval.ask({
88485
88759
  money: taskMoney(pays, 0),
@@ -88515,13 +88789,24 @@ function createTaskV2Executor(options) {
88515
88789
  };
88516
88790
  let fundingAuthorization;
88517
88791
  try {
88792
+ if (mined && "kind" in current)
88793
+ current = taskV2OperationResponseSchema.parse(
88794
+ await operationCall(savedOperation, "recover", { step: finalStep }, key2())
88795
+ );
88518
88796
  if ("kind" in current && current.kind === "eip712") {
88519
88797
  const intent = taskV2IntentSchema.parse(current);
88520
88798
  const typed = intent.typedData;
88799
+ if (started && !savedTransaction && !signedBefore)
88800
+ requireTasksAvailable(
88801
+ action.action,
88802
+ readiness,
88803
+ "No new signature was made. An authorization signed earlier stays valid until it expires."
88804
+ );
88521
88805
  await verifyV2TypedData(target, intent, action, account.address, pays);
88522
88806
  await bindTarget();
88523
88807
  await beforeSign();
88524
88808
  const signature = await account.signTypedData(typed);
88809
+ await pending.markPreparationSigned?.(input2.id, verb);
88525
88810
  if (action.action === "fund")
88526
88811
  fundingAuthorization = { message: typed.message, signature };
88527
88812
  const response = await confirmSignature(input2.id, intent.operationId, signature, key2());
@@ -88547,8 +88832,6 @@ function createTaskV2Executor(options) {
88547
88832
  }
88548
88833
  let result = taskV2OperationResponseSchema.parse(current);
88549
88834
  const operationId = result.operation.id;
88550
- const finalStep = action.action === "approve-bond" ? "v2-approve-usdc" : `v2-${action.action}`;
88551
- const allowedSteps = action.action === "fund" ? ["v2-create-escrow", "v2-create-pool", "v2-approve-usdc", "v2-fund"] : action.action === "raise-dispute" || action.action === "counter-evidence" ? ["v2-approve-usdc", finalStep] : [finalStep];
88552
88835
  const validate7 = (value) => {
88553
88836
  if (value.orderId !== input2.id || value.operation.id !== operationId || !isAddressEqual(value.operation.expectedActor, account.address) || !allowedSteps.includes(value.operation.step))
88554
88837
  fail("Hosted operation does not match the requested task, wallet or action.");
@@ -88567,10 +88850,17 @@ function createTaskV2Executor(options) {
88567
88850
  fail("Hosted sequence moved backwards.");
88568
88851
  return { parsed, complete: !("scanComplete" in response) || response.scanComplete };
88569
88852
  };
88853
+ let waiting;
88570
88854
  for (let poll2 = 0; poll2 < 256; poll2++) {
88571
88855
  validate7(result);
88572
88856
  progress = { ...progress, operation: publicTaskV2Operation(result.operation, secret) };
88573
88857
  const op = result.operation;
88858
+ if (op.state !== "prepared" || waiting?.step !== op.step) waiting = void 0;
88859
+ if (op.state === "prepared" && op.plan) {
88860
+ const shown = canonicalJson(op.plan);
88861
+ if (waiting && waiting.plan !== shown) fail("Recovery changed the prepared plan.");
88862
+ waiting = { step: op.step, plan: shown };
88863
+ }
88574
88864
  if (op.state === "confirmed") {
88575
88865
  if (op.step !== finalStep)
88576
88866
  fail("An approval alone cannot complete the requested action.");
@@ -88600,14 +88890,26 @@ function createTaskV2Executor(options) {
88600
88890
  result = recovered.parsed;
88601
88891
  continue;
88602
88892
  }
88603
- if (canonicalJson(recovered.parsed.operation.plan) !== canonicalJson(op.plan))
88893
+ if (mined) {
88894
+ if (op.step !== finalStep)
88895
+ fail(
88896
+ "vAPI asks for an earlier step although the last step of this operation is mined. Nothing was signed."
88897
+ );
88898
+ result = (await call2("transaction", op.step, mined.txHash)).parsed;
88899
+ if (result.operation.state === "prepared") await sleep(1e3);
88900
+ continue;
88901
+ }
88902
+ const plan = recovered.parsed.operation.plan;
88903
+ if (!plan) return fail("The hosted operation is prepared but carries no plan to sign.");
88904
+ if (waiting && waiting.plan !== canonicalJson(plan))
88604
88905
  fail("Recovery changed the prepared plan.");
88605
- const plan = op.plan;
88606
- if (!deployment.configured || plan.chainId !== deployment.chainId)
88607
- fail("Hosted plan deployment mismatch.");
88906
+ waiting = void 0;
88907
+ const step2 = { ...op, plan };
88908
+ if (plan.chainId !== target.chainId)
88909
+ fail("The hosted plan names another chain than the verified task.");
88608
88910
  const refreshed = await verifyV2Target(
88609
88911
  options,
88610
- { orderId: input2.id, operation: op },
88912
+ { orderId: input2.id, operation: step2 },
88611
88913
  view,
88612
88914
  action,
88613
88915
  target.escrow
@@ -88615,7 +88917,7 @@ function createTaskV2Executor(options) {
88615
88917
  if (!isAddressEqual(refreshed.escrow, target.escrow))
88616
88918
  v2GuardFailure("The continuation changed the verified V2 target.");
88617
88919
  try {
88618
- await verifyV2Plan(refreshed, op, action, pays, fundingAuthorization);
88920
+ await verifyV2Plan(refreshed, step2, action, pays, fundingAuthorization);
88619
88921
  } catch (error61) {
88620
88922
  if (error61 instanceof TaskOperationError) throw error61;
88621
88923
  v2GuardFailure("Unknown V2 selector or malformed ABI arguments.");
@@ -88624,7 +88926,6 @@ function createTaskV2Executor(options) {
88624
88926
  if (await rpc.getChainId() !== plan.chainId) fail("Transaction chain mismatch.");
88625
88927
  await input2.beforeSigning?.();
88626
88928
  await bindTarget();
88627
- await beforeSign();
88628
88929
  const saved = await pending.withStepLock(
88629
88930
  op.id,
88630
88931
  op.step,
@@ -88639,8 +88940,15 @@ function createTaskV2Executor(options) {
88639
88940
  account.address
88640
88941
  ))
88641
88942
  fail("Saved transaction differs from the hosted plan.");
88943
+ await beforeSign();
88642
88944
  return existing;
88643
88945
  }
88946
+ if (started)
88947
+ requireTasksAvailable(
88948
+ action.action,
88949
+ readiness,
88950
+ "This step was not signed. Anything this operation signed earlier stands."
88951
+ );
88644
88952
  const nonce = Math.max(
88645
88953
  await rpc.getTransactionCount({ address: account.address, blockTag: "pending" }),
88646
88954
  await pending.nextNonce(plan.chainId, account.address)
@@ -88655,6 +88963,7 @@ function createTaskV2Executor(options) {
88655
88963
  nonce
88656
88964
  });
88657
88965
  if (request.gas === void 0) fail("The V2 transaction has no gas estimate.");
88966
+ await beforeSign();
88658
88967
  const raw = await account.signTransaction({
88659
88968
  ...request,
88660
88969
  gas: bufferedV2Gas(request.gas)
@@ -88759,7 +89068,7 @@ import { randomBytes as nodeRandomBytes } from "node:crypto";
88759
89068
 
88760
89069
  // ../core/src/tasks/ballots.ts
88761
89070
  import { readdir as readdir7, readFile as readFile19 } from "node:fs/promises";
88762
- import { join as join16 } from "node:path";
89071
+ import { join as join17 } from "node:path";
88763
89072
  var address6 = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u).transform((v) => v.toLowerCase());
88764
89073
  var hash6 = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/u).transform((v) => v.toLowerCase());
88765
89074
  var TASK_V2_VOTE_OUTCOMES = ["worker", "poster", "split"];
@@ -88779,7 +89088,7 @@ var taskV2BallotSchema = external_exports.strictObject({
88779
89088
  createdAt: external_exports.iso.datetime()
88780
89089
  });
88781
89090
  function taskV2BallotDirectory(home, key2) {
88782
- return join16(
89091
+ return join17(
88783
89092
  home,
88784
89093
  "tasks",
88785
89094
  "ballots",
@@ -88789,7 +89098,7 @@ function taskV2BallotDirectory(home, key2) {
88789
89098
  );
88790
89099
  }
88791
89100
  function taskV2BallotPath(home, key2) {
88792
- return join16(taskV2BallotDirectory(home, key2), `${hash6.parse(key2.commitment)}.json`);
89101
+ return join17(taskV2BallotDirectory(home, key2), `${hash6.parse(key2.commitment)}.json`);
88793
89102
  }
88794
89103
  async function writeTaskV2Ballot(home, ballot) {
88795
89104
  const parsed = taskV2BallotSchema.parse(ballot);
@@ -88825,7 +89134,7 @@ async function listTaskV2Ballots(home, key2) {
88825
89134
  }
88826
89135
  const ballots = [];
88827
89136
  for (const name of names.filter((n) => /^0x[0-9a-f]{64}\.json$/u.test(n)).sort()) {
88828
- const ballot = await readBallotFile(join16(directory, name));
89137
+ const ballot = await readBallotFile(join17(directory, name));
88829
89138
  if (ballot && `${ballot.commitment}.json` === name) ballots.push(ballot);
88830
89139
  }
88831
89140
  return ballots.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
@@ -88892,13 +89201,16 @@ function createTaskV2Jury(options) {
88892
89201
  };
88893
89202
  async function voteCase(id2, i2) {
88894
89203
  taskV2IndexSchema.parse(i2);
88895
- const deployment = await client.deployment();
88896
- if (!deployment.configured)
88897
- throw new TaskOperationError("v2_resolver_unavailable", "Hosted Tasks V2 is not configured.");
89204
+ const chainId = (await readTasksReadiness(client))?.chainId ?? (await options.pending.v2Target?.(id2))?.chainId;
89205
+ if (chainId === void 0)
89206
+ throw new TaskOperationError(
89207
+ "v2_resolver_unavailable",
89208
+ "vAPI's Tasks status could not be read, so the chain of this dispute is unknown. Nothing was signed. Try again later."
89209
+ );
88898
89210
  const view = await client.getOrder(id2);
88899
89211
  if (view.workOrder.id !== id2)
88900
89212
  throw new TaskOperationError("invalid_response", "The order view belongs to another task.");
88901
- const target = await verifyV2Target(options, { chainId: deployment.chainId }, view, {
89213
+ const target = await verifyV2Target(options, { chainId }, view, {
88902
89214
  action: "open-jury",
88903
89215
  i: i2
88904
89216
  });
@@ -89309,7 +89621,9 @@ function createTasksChain(options) {
89309
89621
  });
89310
89622
  async function deployment() {
89311
89623
  const value = await client.deployment();
89312
- if (!value.configured || value.network !== `eip155:${value.chainId}`)
89624
+ if (!value.configured)
89625
+ throw new TasksValidationError(tasksUnavailableError(value.chainId).message);
89626
+ if (value.network !== `eip155:${value.chainId}`)
89313
89627
  throw new TasksValidationError("The Tasks chain deployment is unavailable.");
89314
89628
  if (!getTrustedTasksFactory(value.chainId, options.trustedFactories))
89315
89629
  throw new TasksChainError(
@@ -90264,7 +90578,7 @@ function createTasksRpcFor(config2, options = {}) {
90264
90578
 
90265
90579
  // ../core/src/tasks/pending-transactions.ts
90266
90580
  import { readFile as readFile20 } from "node:fs/promises";
90267
- import { join as join17 } from "node:path";
90581
+ import { join as join18 } from "node:path";
90268
90582
  var hex4 = external_exports.string().regex(/^0x(?:[0-9a-fA-F]{2})+$/).transform((v) => v);
90269
90583
  var hash8 = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/).transform((v) => v);
90270
90584
  var step = external_exports.union([
@@ -90329,7 +90643,8 @@ var stateSchema2 = external_exports.object({
90329
90643
  idempotencyKey: external_exports.uuid(),
90330
90644
  inputs: external_exports.unknown(),
90331
90645
  operationId: external_exports.uuid().optional(),
90332
- preparedV2: taskV2PreparedSchema.optional()
90646
+ preparedV2: taskV2PreparedSchema.optional(),
90647
+ signed: external_exports.boolean().optional()
90333
90648
  }).strict()
90334
90649
  ).default({})
90335
90650
  }).strict();
@@ -90353,7 +90668,7 @@ function validCheckpointStep(storedStep, response) {
90353
90668
  }[response.operation.kind];
90354
90669
  }
90355
90670
  function createPendingTransactions(home) {
90356
- const path = join17(home, "tasks", "pending.json");
90671
+ const path = join18(home, "tasks", "pending.json");
90357
90672
  const lockPath = `${path}.lock`;
90358
90673
  const read = async () => {
90359
90674
  try {
@@ -90440,7 +90755,7 @@ function createPendingTransactions(home) {
90440
90755
  },
90441
90756
  withStepLock(operationId, step2, fn) {
90442
90757
  return withFileLock(
90443
- join17(
90758
+ join18(
90444
90759
  home,
90445
90760
  "tasks",
90446
90761
  `step-${encodeURIComponent(operationId)}-${encodeURIComponent(step2)}.lock`
@@ -90452,13 +90767,13 @@ function createPendingTransactions(home) {
90452
90767
  external_exports.number().int().positive().parse(chainId);
90453
90768
  address8.parse(signer);
90454
90769
  return withFileLock(
90455
- join17(home, "tasks", `signer-${chainId}-${signer.toLowerCase()}.lock`),
90770
+ join18(home, "tasks", `signer-${chainId}-${signer.toLowerCase()}.lock`),
90456
90771
  fn
90457
90772
  );
90458
90773
  },
90459
90774
  withFundingLock(milestoneId2, fn) {
90460
90775
  milestoneKey(milestoneId2);
90461
- return withFileLock(join17(home, "tasks", `fund-${milestoneId2}.lock`), fn);
90776
+ return withFileLock(join18(home, "tasks", `fund-${milestoneId2}.lock`), fn);
90462
90777
  },
90463
90778
  async nextNonce(chainId, signer) {
90464
90779
  external_exports.number().int().positive().parse(chainId);
@@ -90519,7 +90834,8 @@ function createPendingTransactions(home) {
90519
90834
  idempotencyKey: external_exports.uuid(),
90520
90835
  inputs: external_exports.unknown(),
90521
90836
  operationId: external_exports.uuid().optional(),
90522
- preparedV2: taskV2PreparedSchema.optional()
90837
+ preparedV2: taskV2PreparedSchema.optional(),
90838
+ signed: external_exports.boolean().optional()
90523
90839
  }).strict().parse(preparation);
90524
90840
  const existing = state.preparations[key2];
90525
90841
  if (existing && (existing.idempotencyKey !== parsed.idempotencyKey || canonicalJson(existing.inputs) !== canonicalJson(parsed.inputs)))
@@ -90561,6 +90877,14 @@ function createPendingTransactions(home) {
90561
90877
  }
90562
90878
  });
90563
90879
  },
90880
+ async markPreparationSigned(milestoneId2, verb) {
90881
+ await locked(async (state) => {
90882
+ const existing = state.preparations[preparationKey(milestoneId2, verb)];
90883
+ if (!existing || existing.signed) return;
90884
+ existing.signed = true;
90885
+ await save(state);
90886
+ });
90887
+ },
90564
90888
  async completePreparation(milestoneId2, verb) {
90565
90889
  await locked(async (state) => {
90566
90890
  const key2 = preparationKey(milestoneId2, verb);
@@ -90700,7 +91024,7 @@ function validateAmount(amountUsd) {
90700
91024
  // ../core/src/tasks/funding-attempts.ts
90701
91025
  import { createHash as createHash5 } from "node:crypto";
90702
91026
  import { readFile as readFile21, unlink as unlink13 } from "node:fs/promises";
90703
- import { dirname as dirname10, join as join18 } from "node:path";
91027
+ import { dirname as dirname10, join as join19 } from "node:path";
90704
91028
  var coordinates = external_exports.object({
90705
91029
  network: external_exports.string().regex(/^eip155:[1-9][0-9]*$/u),
90706
91030
  asset: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u),
@@ -90728,7 +91052,7 @@ var attemptSchema = external_exports.object({
90728
91052
  );
90729
91053
  async function withFundingAttempt(input2, operation) {
90730
91054
  const key2 = createHash5("sha256").update(`${input2.taskId}:${input2.milestoneId}`).digest("hex");
90731
- const path = join18(dirname10(input2.ledgerPath), "tasks", `funding-${key2}.json`);
91055
+ const path = join19(dirname10(input2.ledgerPath), "tasks", `funding-${key2}.json`);
90732
91056
  return withFileLock(
90733
91057
  `${path}.lock`,
90734
91058
  async () => {
@@ -91492,7 +91816,14 @@ async function postTask(context, input2) {
91492
91816
  "The Tasks deployment is unavailable, so the market network cannot be selected."
91493
91817
  );
91494
91818
  }
91495
- const feeBp = parseFeeBp(deployment);
91819
+ if (input2.fund)
91820
+ requireTasksAvailable("fund", deployment, "Nothing was posted or signed and no money moved.");
91821
+ const declared = input2.order;
91822
+ const shape = declared.shape ?? (input2.intake === "submissions" ? "bounty" : "task");
91823
+ const total = input2.amount * BigInt(shape === "bounty" ? declared.bounty?.winners ?? input2.maxAwards ?? 1 : 1);
91824
+ const limits = typeof deployment.chainId === "number" ? await context.limitsV2?.(deployment.chainId, shape).catch(() => void 0) : void 0;
91825
+ if (limits) assertWithinTaskV2Limit(total, limits, "Nothing was posted and no money moved.");
91826
+ const feeBp = limits?.feeBp ?? parseFeeBp(deployment);
91496
91827
  const feeUnavailable = feeBp === null;
91497
91828
  if (feeUnavailable) input2.onFeeUnavailable?.();
91498
91829
  const money2 = taskMoney(input2.amount, feeBp);
@@ -91571,7 +91902,11 @@ async function proposeTask(context, input2) {
91571
91902
  context
91572
91903
  );
91573
91904
  if (!deployment.configured)
91574
- throw new TaskOperationError("not_available", "Task escrow deployment is unavailable.");
91905
+ throw tasksUnavailableError(
91906
+ deployment.chainId,
91907
+ "No proposal was signed or sent.",
91908
+ "not_available"
91909
+ );
91575
91910
  const account = await input2.unlock();
91576
91911
  const terms = {
91577
91912
  title: workOrder.title,
@@ -91652,7 +91987,11 @@ async function submitTask(context, input2) {
91652
91987
  context
91653
91988
  );
91654
91989
  if (!deployment.configured)
91655
- throw new TaskOperationError("not_available", "Task escrow deployment is unavailable.");
91990
+ throw tasksUnavailableError(
91991
+ deployment.chainId,
91992
+ "No entry was signed or sent.",
91993
+ "not_available"
91994
+ );
91656
91995
  if (task.amount === null) {
91657
91996
  throw new TaskInputError("Task amount is unavailable.");
91658
91997
  }
@@ -92152,6 +92491,9 @@ async function resolveUnmatchedTaskOperation(context, input2) {
92152
92491
  }
92153
92492
 
92154
92493
  // ../core/src/tasks/post-options.ts
92494
+ var TASK_POST_DEADLINE_LEAD_MS = 3 * 36e5;
92495
+ var TASK_POST_DEADLINE_MARGIN_MS = 6e4;
92496
+ var TASK_DEADLINE_TOO_SOON = "must be at least 3 hours from now when vAPI receives the post, so the task can still be funded and awarded. Use 181m or more.";
92155
92497
  function positive(text, name) {
92156
92498
  if (text === void 0) throw new TaskInputError(`${name} is required.`);
92157
92499
  try {
@@ -92249,17 +92591,16 @@ function prepareTaskPost(input2, now) {
92249
92591
  "An open pool requires --open-check allowlist|invite (configure participants separately)."
92250
92592
  );
92251
92593
  } else {
92252
- if (!input2.milestones?.length && duration3 < 36e5)
92253
- throw new TaskInputError(
92254
- "Task deadlines must leave at least one hour for work before award."
92255
- );
92594
+ const lead = input2.shape === void 0 && input2.intake === "submissions" && !input2.milestones && !input2.proofSpec && !input2.checkin ? TASK_LIMITS.postDeadlineMinMs : TASK_POST_DEADLINE_LEAD_MS + TASK_POST_DEADLINE_MARGIN_MS;
92595
+ if (!input2.milestones?.length && duration3 < lead)
92596
+ throw new TaskInputError(`Task deadlines ${TASK_DEADLINE_TOO_SOON}`);
92256
92597
  const sum = input2.milestones?.reduce((total, item) => total + BigInt(item.amountBaseUnits), 0n);
92257
92598
  amount4 = input2.amountUsd === void 0 && sum !== void 0 ? sum : positive(input2.amountUsd, "--amount");
92258
92599
  if (sum !== void 0 && sum !== amount4)
92259
92600
  throw new TaskInputError("Milestone amounts must sum to --amount.");
92260
- if (input2.milestones?.some((item) => Date.parse(item.deadlineAt) - now.getTime() < 36e5))
92601
+ if (input2.milestones?.some((item) => Date.parse(item.deadlineAt) - now.getTime() < lead))
92261
92602
  throw new TaskInputError(
92262
- "Milestone deadlines must leave at least one hour for work; creation and funding also check the verified MIN_WORK_TIME against the chain clock."
92603
+ `Milestone deadlines ${TASK_DEADLINE_TOO_SOON} Creation and funding also check the contract's MIN_WORK_TIME against the chain clock.`
92263
92604
  );
92264
92605
  }
92265
92606
  if (input2.amountUsd !== void 0 && positive(input2.amountUsd, "--amount") !== amount4)
@@ -93470,7 +93811,7 @@ function csvCell(value) {
93470
93811
  // ../core/src/swarm-capital.ts
93471
93812
  import { createHash as createHash6, randomBytes as randomBytes16 } from "node:crypto";
93472
93813
  import { readFile as readFile24, unlink as unlink14 } from "node:fs/promises";
93473
- import { join as join20 } from "node:path";
93814
+ import { join as join21 } from "node:path";
93474
93815
 
93475
93816
  // ../core/src/payment-warning.ts
93476
93817
  var PAYMENT_WARNING_CODES = [
@@ -93487,7 +93828,7 @@ var PAYMENT_WARNING_CODES = [
93487
93828
 
93488
93829
  // ../core/src/swarm-workers.ts
93489
93830
  import { readFile as readFile23, readdir as readdir8 } from "node:fs/promises";
93490
- import { join as join19 } from "node:path";
93831
+ import { join as join20 } from "node:path";
93491
93832
  var runSchema = external_exports.object({
93492
93833
  v: external_exports.literal(1),
93493
93834
  runId: external_exports.string(),
@@ -93517,7 +93858,7 @@ var sidecarSchema = external_exports.object({
93517
93858
  state: external_exports.string().optional()
93518
93859
  });
93519
93860
  async function assertSwarmWorkersStopped(home, swarm) {
93520
- const directory = join19(home, "runs");
93861
+ const directory = join20(home, "runs");
93521
93862
  let files;
93522
93863
  try {
93523
93864
  files = await readdir8(directory);
@@ -93533,7 +93874,7 @@ async function assertSwarmWorkersStopped(home, swarm) {
93533
93874
  for (const file2 of files.sort()) {
93534
93875
  const match = /^(run_[0-9a-f]{24})\.json$/u.exec(file2);
93535
93876
  if (match === null) continue;
93536
- const value = await readWorkerFile(join19(directory, file2));
93877
+ const value = await readWorkerFile(join20(directory, file2));
93537
93878
  if (value === void 0) continue;
93538
93879
  const parsed = runSchema.safeParse(value);
93539
93880
  if (!parsed.success || parsed.data.runId !== match[1]) {
@@ -93555,7 +93896,7 @@ async function assertSwarmWorkersStopped(home, swarm) {
93555
93896
  for (const file2 of files) {
93556
93897
  const match = /^(run_[0-9a-f]{24})\.railway\.json$/u.exec(file2);
93557
93898
  if (match === null) continue;
93558
- const value = await readWorkerFile(join19(directory, file2));
93899
+ const value = await readWorkerFile(join20(directory, file2));
93559
93900
  if (value === void 0) continue;
93560
93901
  const parsed = sidecarSchema.safeParse(value);
93561
93902
  if (!parsed.success) {
@@ -94552,13 +94893,13 @@ function runRecordMovementId(value) {
94552
94893
  return parsed.data;
94553
94894
  }
94554
94895
  function treasuryRequestRecordPath(home, movementId) {
94555
- return join20(home, "runs", "requests", `${movementId}.json`);
94896
+ return join21(home, "runs", "requests", `${movementId}.json`);
94556
94897
  }
94557
94898
  function delegationRecordPath(home, movementId) {
94558
- return join20(home, "runs", "delegations", `${movementId}.json`);
94899
+ return join21(home, "runs", "delegations", `${movementId}.json`);
94559
94900
  }
94560
94901
  function legacyFundingProgressPath(home, name) {
94561
- return join20(home, "swarms", `.${name}.funding`);
94902
+ return join21(home, "swarms", `.${name}.funding`);
94562
94903
  }
94563
94904
  async function readLegacyFundingProgress(home, name) {
94564
94905
  try {
@@ -95208,7 +95549,7 @@ async function removeMemberLocked(home, swarm, account) {
95208
95549
  }
95209
95550
 
95210
95551
  // ../core/src/status.ts
95211
- import { join as join21 } from "node:path";
95552
+ import { join as join22 } from "node:path";
95212
95553
  var STATUS_TIMEOUT_MS = 2e3;
95213
95554
  async function buildStatus(deps) {
95214
95555
  const timers = deps.timers ?? { setTimeout, clearTimeout };
@@ -95264,7 +95605,7 @@ function formatUsdAmount(value) {
95264
95605
  }
95265
95606
  async function readVaultStatus(deps) {
95266
95607
  const store = deps.secrets.description.replace(/^the /u, "");
95267
- const path = join21(deps.home, "vault.json");
95608
+ const path = join22(deps.home, "vault.json");
95268
95609
  let file2;
95269
95610
  try {
95270
95611
  file2 = await readVaultFileUnlocked(path);
@@ -95754,7 +96095,7 @@ function output2(io, json2, value, human) {
95754
96095
  }
95755
96096
 
95756
96097
  // src/wallet-session.ts
95757
- import { join as join22 } from "node:path";
96098
+ import { join as join23 } from "node:path";
95758
96099
 
95759
96100
  // src/args.ts
95760
96101
  var UsageError = class extends Error {
@@ -96003,7 +96344,7 @@ async function confirmWalletName(name, prompt, refusal, dependencies) {
96003
96344
  if (typed.trim() !== name) throw new KeystoreError(refusal);
96004
96345
  }
96005
96346
  async function deviceVaultKey(store, dependencies) {
96006
- const path = join22(store.home, "vault.json");
96347
+ const path = join23(store.home, "vault.json");
96007
96348
  const metadata = await readVaultFileUnlocked(path);
96008
96349
  const secrets = getSecretStore(dependencies);
96009
96350
  const key2 = metadata.protected ? await unlockProtectedVault({
@@ -98691,7 +99032,7 @@ function exactPriceFact(value) {
98691
99032
 
98692
99033
  // ../mcp/src/agent/runtime.ts
98693
99034
  import { mkdir as mkdir17, readFile as readFile25, readdir as readdir9, rm as rm2 } from "node:fs/promises";
98694
- import { join as join23 } from "node:path";
99035
+ import { join as join24 } from "node:path";
98695
99036
 
98696
99037
  // ../mcp/src/agent/run.ts
98697
99038
  var loopSearchResultSchema = external_exports.array(
@@ -100030,19 +100371,19 @@ var runRecordSchema = external_exports.strictObject({
100030
100371
  }
100031
100372
  );
100032
100373
  function runsDirectory(home) {
100033
- return join23(home, "runs");
100374
+ return join24(home, "runs");
100034
100375
  }
100035
100376
  function runRecordPath(home, runId) {
100036
100377
  assertRunId(runId);
100037
- return join23(runsDirectory(home), `${runId}.json`);
100378
+ return join24(runsDirectory(home), `${runId}.json`);
100038
100379
  }
100039
100380
  function runLogPath(home, runId) {
100040
100381
  assertRunId(runId);
100041
- return join23(runsDirectory(home), `${runId}.log`);
100382
+ return join24(runsDirectory(home), `${runId}.log`);
100042
100383
  }
100043
100384
  function runResultPath(home, runId) {
100044
100385
  assertRunId(runId);
100045
- return join23(runsDirectory(home), `${runId}.result.json`);
100386
+ return join24(runsDirectory(home), `${runId}.result.json`);
100046
100387
  }
100047
100388
  async function writeRunRecord(home, record3) {
100048
100389
  const path = runRecordPath(home, record3.runId);
@@ -100073,7 +100414,7 @@ async function listRunRecords(home, filter = {}) {
100073
100414
  if (match === null) continue;
100074
100415
  try {
100075
100416
  const record3 = runRecordSchema.parse(
100076
- JSON.parse(await readFile25(join23(runsDirectory(home), file2), "utf8"))
100417
+ JSON.parse(await readFile25(join24(runsDirectory(home), file2), "utf8"))
100077
100418
  );
100078
100419
  if (record3.runId !== match[1]) continue;
100079
100420
  if (filter.swarm !== void 0 && record3.member.swarm !== filter.swarm) continue;
@@ -100452,7 +100793,7 @@ async function stopRun(args) {
100452
100793
  }
100453
100794
  }
100454
100795
  function memberRunLockPath(home, account) {
100455
- return join23(runsDirectory(home), `.member-${account}.lock`);
100796
+ return join24(runsDirectory(home), `.member-${account}.lock`);
100456
100797
  }
100457
100798
  async function withMemberRunLock(home, account, operation) {
100458
100799
  if (!WALLET_NAME_PATTERN.test(account))
@@ -101871,6 +102212,11 @@ function createTasksTools(options) {
101871
102212
  const client = typeof injected === "function" ? injected(clientOptions) : injected ?? createHostedTasksClient(clientOptions);
101872
102213
  return {
101873
102214
  client,
102215
+ limitsV2: (async (chainId, shape) => readTaskV2Limits({
102216
+ chainId,
102217
+ shape,
102218
+ rpcFor: options.rpcFor ?? createTasksRpcFor(await loadConfig(getVapiPaths(home).config), { fetch: guardedFetch2 })
102219
+ })),
101874
102220
  chain: options.chain ?? (selected === void 0 ? missingTasksChain : lazyTasksChain(async () => {
101875
102221
  const { account } = await options.session.payment(selected.name);
101876
102222
  const config2 = await loadConfig(getVapiPaths(home).config);
@@ -104932,7 +105278,7 @@ function assertKeyMatchesAddress(bundle) {
104932
105278
  }
104933
105279
 
104934
105280
  // src/vault.ts
104935
- import { join as join28 } from "node:path";
105281
+ import { join as join29 } from "node:path";
104936
105282
 
104937
105283
  // src/balance-reader.ts
104938
105284
  function baseUsdcBalanceReader(config2, dependencies) {
@@ -104956,10 +105302,10 @@ function baseUsdcBalanceReader(config2, dependencies) {
104956
105302
  }
104957
105303
 
104958
105304
  // src/cloud-backup.ts
104959
- import { join as join26 } from "node:path";
105305
+ import { join as join27 } from "node:path";
104960
105306
 
104961
105307
  // ../core/src/cloud-backup.ts
104962
- import { join as join25 } from "node:path";
105308
+ import { join as join26 } from "node:path";
104963
105309
 
104964
105310
  // ../core/src/backup.ts
104965
105311
  import {
@@ -104986,7 +105332,7 @@ import {
104986
105332
  readdir as readdir10,
104987
105333
  rm as rm3
104988
105334
  } from "node:fs/promises";
104989
- import { dirname as dirname12, join as join24 } from "node:path";
105335
+ import { dirname as dirname12, join as join25 } from "node:path";
104990
105336
  var ERROR_MESSAGES = {
104991
105337
  backup_too_large: "Backup envelope exceeds 65,536 bytes.",
104992
105338
  backup_open_failed: "Unable to open backup.",
@@ -105464,7 +105810,7 @@ async function exportBackupSource(options) {
105464
105810
  var BackupSnapshotChangedError = class extends Error {
105465
105811
  };
105466
105812
  async function exportBackupSourceAttempt(options, networks) {
105467
- const path = join24(options.store.home, "vault.json");
105813
+ const path = join25(options.store.home, "vault.json");
105468
105814
  const { phrase, file: file2, accounts } = await withVaultLock(path, async () => {
105469
105815
  const [phrase2, vault, file3] = await Promise.all([
105470
105816
  exportVaultPhrase({ path, key: options.vaultKey }),
@@ -105600,16 +105946,16 @@ async function restoreBackupPlaintext(options) {
105600
105946
  } catch {
105601
105947
  throw new BackupError("backup_invalid_input");
105602
105948
  }
105603
- const vaultPath2 = join24(options.home, "vault.json");
105604
- const registryPath = join24(options.home, "wallets.json");
105949
+ const vaultPath2 = join25(options.home, "vault.json");
105950
+ const registryPath = join25(options.home, "wallets.json");
105605
105951
  let stagingHome;
105606
105952
  let beforePublishError;
105607
105953
  let afterPublishError;
105608
105954
  try {
105609
105955
  await mkdir18(options.home, { recursive: true, mode: 448 });
105610
- stagingHome = await mkdtemp(join24(options.home, ".backup-restore-"));
105611
- const stagedVaultPath = join24(stagingHome, "vault.json");
105612
- const stagedRegistryPath = join24(stagingHome, "wallets.json");
105956
+ stagingHome = await mkdtemp(join25(options.home, ".backup-restore-"));
105957
+ const stagedVaultPath = join25(stagingHome, "vault.json");
105958
+ const stagedRegistryPath = join25(stagingHome, "wallets.json");
105613
105959
  await createVault({
105614
105960
  path: stagedVaultPath,
105615
105961
  key: options.vaultKey,
@@ -105668,7 +106014,7 @@ async function restoreBackupPlaintext(options) {
105668
106014
  protected: plaintext.protected,
105669
106015
  networks: [...plaintext.registry.networks]
105670
106016
  };
105671
- const markerPath = join24(options.home, RESTORE_MARKER_FILE);
106017
+ const markerPath = join25(options.home, RESTORE_MARKER_FILE);
105672
106018
  const fingerprint = restoreFingerprint(
105673
106019
  plaintext,
105674
106020
  stagedV2?.restoreDevice ?? options.device,
@@ -105879,13 +106225,13 @@ async function stageV2Restore(options) {
105879
106225
  }
105880
106226
  const agents = [];
105881
106227
  for (const profile of validAgents) {
105882
- const stagedPath = join24(options.stagingHome, "agents", `${profile.name}.json`);
106228
+ const stagedPath = join25(options.stagingHome, "agents", `${profile.name}.json`);
105883
106229
  if (await stageRestoreBytes(stagedPath, prettyJson(profile))) {
105884
106230
  agents.push({
105885
106231
  kind: "agent",
105886
106232
  name: profile.name,
105887
106233
  stagedPath,
105888
- targetPath: join24(options.home, "agents", `${profile.name}.json`)
106234
+ targetPath: join25(options.home, "agents", `${profile.name}.json`)
105889
106235
  });
105890
106236
  } else {
105891
106237
  skipped2.push({ kind: "agent", name: profile.name, reason: "write_failed" });
@@ -105905,13 +106251,13 @@ async function stageV2Restore(options) {
105905
106251
  if (restoreDevice !== void 0) {
105906
106252
  for (const value of validSwarms) {
105907
106253
  const swarm = swarmFileSchema.parse({ ...value, device: restoreDevice });
105908
- const stagedPath = join24(options.stagingHome, "swarms", `${swarm.name}.json`);
106254
+ const stagedPath = join25(options.stagingHome, "swarms", `${swarm.name}.json`);
105909
106255
  if (await stageRestoreBytes(stagedPath, prettyJson(swarm))) {
105910
106256
  swarms.push({
105911
106257
  kind: "swarm",
105912
106258
  name: swarm.name,
105913
106259
  stagedPath,
105914
- targetPath: join24(options.home, "swarms", `${swarm.name}.json`)
106260
+ targetPath: join25(options.home, "swarms", `${swarm.name}.json`)
105915
106261
  });
105916
106262
  } else {
105917
106263
  skipped2.push({ kind: "swarm", name: swarm.name, reason: "write_failed" });
@@ -105921,13 +106267,13 @@ async function stageV2Restore(options) {
105921
106267
  const movements = [];
105922
106268
  for (const movement of validMovements) {
105923
106269
  const restored = reconcileRestoredMovement(movement, assumedReceiptKeys);
105924
- const stagedPath = join24(options.stagingHome, "movements", `${restored.id}.json`);
106270
+ const stagedPath = join25(options.stagingHome, "movements", `${restored.id}.json`);
105925
106271
  if (await stageRestoreBytes(stagedPath, serializeMovement(restored))) {
105926
106272
  movements.push({
105927
106273
  kind: "movement",
105928
106274
  name: restored.id,
105929
106275
  stagedPath,
105930
- targetPath: join24(options.home, "movements", `${restored.id}.json`),
106276
+ targetPath: join25(options.home, "movements", `${restored.id}.json`),
105931
106277
  movement: restored
105932
106278
  });
105933
106279
  } else {
@@ -106086,7 +106432,7 @@ async function reconcilePublishedMovements(staged, home, requireDurableSafety =
106086
106432
  const unjournaledKeys = new Set([...signedKeys].filter((key2) => !journaledKeys.has(key2)));
106087
106433
  let files;
106088
106434
  try {
106089
- files = await readdir10(join24(home, "movements"));
106435
+ files = await readdir10(join25(home, "movements"));
106090
106436
  } catch (error61) {
106091
106437
  if (isMissingFile4(error61)) return;
106092
106438
  if (requireDurableSafety && unjournaledKeys.size > 0) throw error61;
@@ -106995,7 +107341,7 @@ async function uploadBackupLocked(options, signal) {
106995
107341
  try {
106996
107342
  let vaultFile;
106997
107343
  try {
106998
- vaultFile = await readVaultFileUnlocked(join25(options.store.home, "vault.json"));
107344
+ vaultFile = await readVaultFileUnlocked(join26(options.store.home, "vault.json"));
106999
107345
  } catch (error61) {
107000
107346
  if (error61 instanceof VaultError && error61.code === "not_found") {
107001
107347
  return { status: "skipped", reason: "no_vault" };
@@ -107004,7 +107350,7 @@ async function uploadBackupLocked(options, signal) {
107004
107350
  }
107005
107351
  try {
107006
107352
  vaultKey = vaultFile.protected ? await unlockProtectedVault({
107007
- path: join25(options.store.home, "vault.json"),
107353
+ path: join26(options.store.home, "vault.json"),
107008
107354
  secrets: options.secrets,
107009
107355
  env: options.env,
107010
107356
  ...options.now === void 0 ? {} : { now: options.now }
@@ -108525,7 +108871,7 @@ async function cloudBackupCommand(argv, json2, io, dependencies) {
108525
108871
  }
108526
108872
  async function enrollCloudBackup(json2, io, dependencies) {
108527
108873
  const paths = getVapiPaths();
108528
- if (!await fileExists3(join26(paths.directory, "vault.json"))) {
108874
+ if (!await fileExists3(join27(paths.directory, "vault.json"))) {
108529
108875
  throw new Error("No vault on this device. Run vapi setup first.");
108530
108876
  }
108531
108877
  const context = await cloudContext(io, dependencies);
@@ -108637,7 +108983,7 @@ async function restoreFromOwnerCommand(argv, json2, io, dependencies) {
108637
108983
  }
108638
108984
  const expectedOwner = ownerValue?.toLowerCase();
108639
108985
  const paths = getVapiPaths();
108640
- if (await fileExists3(join26(paths.directory, "vault.json")) && !await fileExists3(join26(paths.directory, ".backup-restore.json"))) {
108986
+ if (await fileExists3(join27(paths.directory, "vault.json")) && !await fileExists3(join27(paths.directory, ".backup-restore.json"))) {
108641
108987
  throw new Error(
108642
108988
  `A vault already exists in ${paths.directory}. Move it aside before restoring.`
108643
108989
  );
@@ -109028,7 +109374,7 @@ function writeSkippedWarnings(io, skipped2) {
109028
109374
 
109029
109375
  // src/setup.ts
109030
109376
  import { rm as rm4 } from "node:fs/promises";
109031
- import { join as join27 } from "node:path";
109377
+ import { join as join28 } from "node:path";
109032
109378
 
109033
109379
  // src/identity.ts
109034
109380
  async function fetchWalletIdentity(options) {
@@ -109808,7 +110154,7 @@ async function readProcessStdin() {
109808
110154
  }
109809
110155
 
109810
110156
  // src/version.ts
109811
- var CLI_VERSION = "0.16.0";
110157
+ var CLI_VERSION = "0.16.2";
109812
110158
 
109813
110159
  // src/status.ts
109814
110160
  async function statusCommand(argv, json2, io, dependencies) {
@@ -110023,7 +110369,7 @@ async function setupCommand(argv, json2, io, dependencies) {
110023
110369
  steps.push("config");
110024
110370
  }
110025
110371
  const config2 = await readConfig(paths.config, humanIo);
110026
- if (!await fileExists3(join27(paths.directory, "vault.json"))) {
110372
+ if (!await fileExists3(join28(paths.directory, "vault.json"))) {
110027
110373
  const os = dependencies.secretBackendProbe ?? (dependencies.secretStore === void 0 ? osSecretStore() : void 0);
110028
110374
  if (os !== void 0) {
110029
110375
  await chooseSecretBackend({ home: paths.directory, os, env: getEnvironment(dependencies) });
@@ -110035,7 +110381,7 @@ async function setupCommand(argv, json2, io, dependencies) {
110035
110381
  let changedAccount = false;
110036
110382
  let changedLink = false;
110037
110383
  let scannedAddresses;
110038
- if (!await fileExists3(join27(paths.directory, "vault.json"))) {
110384
+ if (!await fileExists3(join28(paths.directory, "vault.json"))) {
110039
110385
  const choice = await vaultChoice(dependencies);
110040
110386
  if (choice === "restore") {
110041
110387
  if (!isInteractive(dependencies)) {
@@ -110123,7 +110469,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
110123
110469
  let scannedAddresses = 0;
110124
110470
  try {
110125
110471
  const restored = await restoreVault({
110126
- path: join27(paths.directory, "vault.json"),
110472
+ path: join28(paths.directory, "vault.json"),
110127
110473
  key: key2,
110128
110474
  phrase: validatedPhrase,
110129
110475
  probe: async (address10) => await readBalance3(address10) > 0n,
@@ -110134,7 +110480,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
110134
110480
  ...dependencies.now === void 0 ? {} : { now: dependencies.now }
110135
110481
  });
110136
110482
  names = restored.accounts().map((account) => account.name);
110137
- await rm4(join27(paths.directory, "wallets.json"), { force: true });
110483
+ await rm4(join28(paths.directory, "wallets.json"), { force: true });
110138
110484
  } finally {
110139
110485
  key2.fill(0);
110140
110486
  }
@@ -110217,7 +110563,7 @@ async function restoreCommand(argv, json2, io, dependencies) {
110217
110563
  }
110218
110564
  const accountCount = parseRestoreAccountCount(parsed.one("--accounts"));
110219
110565
  const paths = getVapiPaths();
110220
- const path = join28(paths.directory, "vault.json");
110566
+ const path = join29(paths.directory, "vault.json");
110221
110567
  if (await fileExists3(path)) {
110222
110568
  throw new Error(
110223
110569
  `A vault already exists in ${paths.directory}. Move it aside before restoring.`
@@ -110374,7 +110720,7 @@ function requireNoArguments2(argv) {
110374
110720
  parseArguments(argv, { valueOptions: /* @__PURE__ */ new Set(), maximumPositionals: 0 });
110375
110721
  }
110376
110722
  function vaultPath() {
110377
- return join28(getVapiPaths().directory, "vault.json");
110723
+ return join29(getVapiPaths().directory, "vault.json");
110378
110724
  }
110379
110725
  function quietIo(io) {
110380
110726
  return { stdout: () => void 0, stderr: io.stderr };
@@ -110468,7 +110814,7 @@ async function backupCommand(argv, json2, io, dependencies) {
110468
110814
  const target = await targetWallet(parsed, dependencies);
110469
110815
  const vaultAccount = await target.store.hasVaultAccount(target.name);
110470
110816
  if (vaultAccount) {
110471
- const vault = await readVaultFileUnlocked(join28(target.store.home, "vault.json"));
110817
+ const vault = await readVaultFileUnlocked(join29(target.store.home, "vault.json"));
110472
110818
  if (vault.accounts.some((account) => account.name === target.name && account.kind === "imported")) {
110473
110819
  throw new KeystoreError(
110474
110820
  `Account ${target.name} was imported and is not recoverable from the vault phrase. Back it up with vapi export-key --account ${target.name}.`
@@ -110545,7 +110891,7 @@ async function importCommand(argv, json2, io, dependencies) {
110545
110891
  const existed = store.has(name);
110546
110892
  if (existed && !parsed.has("--replace")) {
110547
110893
  const address10 = await store.readAddress(name);
110548
- const location = await store.hasVaultAccount(name) ? join28(store.home, "vault.json") : store.pathFor(name);
110894
+ const location = await store.hasVaultAccount(name) ? join29(store.home, "vault.json") : store.pathFor(name);
110549
110895
  throw new Error(
110550
110896
  [
110551
110897
  `Wallet ${name} already exists at ${location}.`,
@@ -110581,7 +110927,7 @@ async function importCommand(argv, json2, io, dependencies) {
110581
110927
  const result = {
110582
110928
  address: account.address,
110583
110929
  ...account.solana ? { solanaAddress: account.solana.address } : {},
110584
- vault: join28(paths.directory, "vault.json"),
110930
+ vault: join29(paths.directory, "vault.json"),
110585
110931
  ...previousKeystore ? { previousKeystore } : {},
110586
110932
  message: "Wallet imported. Its encrypted key stays on this machine."
110587
110933
  };
@@ -110782,7 +111128,8 @@ async function retireStoredPassphrase(target, dependencies, io) {
110782
111128
 
110783
111129
  // src/accounts.ts
110784
111130
  import { readFile as readFile28, stat as stat18 } from "node:fs/promises";
110785
- import { join as join29 } from "node:path";
111131
+ import { join as join30 } from "node:path";
111132
+ import { createInterface as createInterface3 } from "node:readline/promises";
110786
111133
 
110787
111134
  // src/dashboard.ts
110788
111135
  import { resolve as resolve2 } from "node:path";
@@ -111177,10 +111524,10 @@ async function accountsRenameCommand(argv, json2, io, dependencies) {
111177
111524
  {
111178
111525
  previous: from16,
111179
111526
  ...address10 === void 0 ? {} : { address: address10 },
111180
- vault: join29(store.home, "vault.json"),
111527
+ vault: join30(store.home, "vault.json"),
111181
111528
  message: `Wallet ${from16} is now ${renamed.name}.`
111182
111529
  },
111183
- [`Wallet ${from16} is now ${renamed.name}.`, `Vault: ${join29(store.home, "vault.json")}`].join(
111530
+ [`Wallet ${from16} is now ${renamed.name}.`, `Vault: ${join30(store.home, "vault.json")}`].join(
111184
111531
  "\n"
111185
111532
  )
111186
111533
  );
@@ -111289,33 +111636,44 @@ async function accountsRestoreCommand(argv, json2, io, dependencies) {
111289
111636
  { name: restored.name, ...address10 === void 0 ? {} : { address: address10 } },
111290
111637
  {
111291
111638
  ...address10 === void 0 ? {} : { address: address10 },
111292
- vault: join29(store.home, "vault.json"),
111639
+ vault: join30(store.home, "vault.json"),
111293
111640
  spendCaps: restored.entry.spendCaps,
111294
111641
  message: `Wallet ${restored.name} restored to the device vault.`
111295
111642
  },
111296
111643
  [
111297
111644
  `Wallet ${restored.name} restored to the device vault.`,
111298
- `Vault: ${join29(store.home, "vault.json")}`
111645
+ `Vault: ${join30(store.home, "vault.json")}`
111299
111646
  ].join("\n")
111300
111647
  );
111301
111648
  }
111302
111649
  async function accountsCapsCommand(argv, json2, io, dependencies) {
111303
111650
  const parsed = parseArguments(argv, {
111304
- valueOptions: /* @__PURE__ */ new Set(["--per-call", "--per-day", "--ceiling"]),
111651
+ valueOptions: /* @__PURE__ */ new Set([
111652
+ "--per-call",
111653
+ "--per-day",
111654
+ "--ceiling",
111655
+ "--max-per-task",
111656
+ "--approve-above"
111657
+ ]),
111658
+ booleanOptions: /* @__PURE__ */ new Set(["--yes"]),
111305
111659
  maximumPositionals: 1
111306
111660
  });
111307
- const name = requiredPositional(
111308
- parsed.positionals[0],
111309
- "<name>",
111310
- "Usage: vapi accounts caps <name> [--per-call <usd>] [--per-day <usd>] [--ceiling <usd|off>] [--json]"
111311
- );
111661
+ const name = requiredPositional(parsed.positionals[0], "<name>", CAPS_USAGE);
111312
111662
  const perCall = parsed.one("--per-call");
111313
111663
  const perDay = parsed.one("--per-day");
111314
111664
  const ceiling = parsed.one("--ceiling");
111665
+ const maxPerTask = parsed.one("--max-per-task");
111666
+ const approveAbove = parsed.one("--approve-above");
111315
111667
  const store = await openWalletStore(dependencies);
111316
111668
  const account = store.resolve({ name, env: {} });
111317
111669
  const address10 = await store.readAddress(account.name);
111318
- if (perCall === void 0 && perDay === void 0 && ceiling === void 0) {
111670
+ let taskPolicy = await taskPolicyForWallet({
111671
+ directory: store.home,
111672
+ wallet: account.name,
111673
+ schema: registeredAgentProfileSchema,
111674
+ warn: io.stderr
111675
+ });
111676
+ if (perCall === void 0 && perDay === void 0 && ceiling === void 0 && maxPerTask === void 0 && approveAbove === void 0) {
111319
111677
  const caps2 = capsOutput(account.entry.spendCaps, store.ceilingCaps(account.name));
111320
111678
  outputForWallet2(
111321
111679
  io,
@@ -111324,13 +111682,15 @@ async function accountsCapsCommand(argv, json2, io, dependencies) {
111324
111682
  {
111325
111683
  ...address10 === void 0 ? {} : { address: address10 },
111326
111684
  spendCaps: account.entry.spendCaps,
111327
- ...caps2
111685
+ ...caps2,
111686
+ taskLimits: taskLimitsJson(taskPolicy)
111328
111687
  },
111329
111688
  [
111330
111689
  walletHeader2({ name: account.name, ...address10 === void 0 ? {} : { address: address10 } }),
111331
111690
  `Spend caps: ${formatCaps(account.entry.spendCaps)}`,
111332
111691
  `Ceiling: ${caps2.ceilingUsd === "off" ? "off" : `${caps2.ceilingUsd} USDC`}`,
111333
- "Change them with --per-call <usd>, --per-day <usd>, or --ceiling <usd|off>."
111692
+ `Task limits: ${formatTaskLimits(taskPolicy)}`,
111693
+ "Change them with --per-call <usd>, --per-day <usd>, --ceiling <usd|off>, --max-per-task <usd>, or --approve-above <usd>."
111334
111694
  ].join("\n")
111335
111695
  );
111336
111696
  return;
@@ -111343,17 +111703,72 @@ async function accountsCapsCommand(argv, json2, io, dependencies) {
111343
111703
  throw new UsageError("The per-call cap cannot be larger than the per-day cap.");
111344
111704
  }
111345
111705
  const ceilingAtomic = ceiling === void 0 ? void 0 : ceiling === "off" ? null : BigInt(capAtomic(ceiling, "--ceiling"));
111706
+ const taskLimits = maxPerTask === void 0 && approveAbove === void 0 ? void 0 : {
111707
+ maxPerTaskUsd: maxPerTask === void 0 ? taskPolicy.maxPerTaskUsd : taskLimitUsd(maxPerTask, "--max-per-task"),
111708
+ approveAboveUsd: approveAbove === void 0 ? taskPolicy.approveAboveUsd : taskLimitUsd(approveAbove, "--approve-above")
111709
+ };
111710
+ const profile = taskLimits === void 0 || taskPolicy.source !== "agent-profile" ? void 0 : (await listAgentProfiles(store.home, {
111711
+ schema: registeredAgentProfileSchema,
111712
+ warn: () => {
111713
+ }
111714
+ })).find((candidate) => candidate.wallet === account.name);
111715
+ if (taskLimits !== void 0 && taskPolicy.source === "agent-profile" && !profile)
111716
+ throw new Error(`The agent profile of ${account.name} is unreadable.`);
111717
+ if (taskLimits !== void 0 && (taskLimits.maxPerTaskUsd > taskPolicy.maxPerTaskUsd || taskLimits.approveAboveUsd > taskPolicy.approveAboveUsd)) {
111718
+ const command = `vapi accounts caps ${account.name}${maxPerTask === void 0 ? "" : ` --max-per-task ${maxPerTask}`}${approveAbove === void 0 ? "" : ` --approve-above ${approveAbove}`}`;
111719
+ const marker = activeAgentMarker(getEnvironment(dependencies));
111720
+ if (marker !== void 0 || !isStdinInteractive(dependencies))
111721
+ throw new UsageError(
111722
+ `Raising a task limit is a decision for a person. Nothing was changed. ${marker === void 0 ? "Standard input is not a terminal." : `${marker} is set, so this is an agent session.`} Run it yourself in a terminal: ${command}`
111723
+ );
111724
+ if (maxPerTask !== void 0 && taskLimits.maxPerTaskUsd > taskPolicy.maxPerTaskUsd) {
111725
+ const liveUsd = await liveTaskLimitUsd(dependencies);
111726
+ if (liveUsd !== void 0 && taskLimits.maxPerTaskUsd > liveUsd)
111727
+ io.stderr(
111728
+ `Note: one task on Base holds at most ${liveUsd} USDC today, so a per-task limit above that changes nothing until the contract's limit is raised.`
111729
+ );
111730
+ }
111731
+ if (!parsed.has("--yes")) {
111732
+ const question = `Raise the task limits of ${account.name} from ${formatTaskLimits(taskPolicy, false)} to ${formatTaskLimits(taskLimits, false)}? Type yes to confirm: `;
111733
+ if (json2 || !isInteractive(dependencies))
111734
+ throw new UsageError(
111735
+ `Raising a task limit needs your confirmation. Nothing was changed. Run it again with --yes: ${command} --yes`
111736
+ );
111737
+ if ((await visibleLine(question, dependencies)).trim().toLowerCase() !== "yes")
111738
+ throw new UsageError("Not confirmed. Nothing was changed.");
111739
+ }
111740
+ }
111346
111741
  let entry = account.entry;
111347
111742
  if (perCall !== void 0 || perDay !== void 0) {
111348
111743
  entry = await store.setSpendCaps(account.name, spendCaps);
111349
111744
  }
111350
111745
  if (ceilingAtomic !== void 0) entry = await store.setCeiling(account.name, ceilingAtomic);
111746
+ if (taskLimits !== void 0) {
111747
+ if (profile) {
111748
+ await writeAgentProfile(
111749
+ store.home,
111750
+ { ...profile, ...taskLimits },
111751
+ { schema: registeredAgentProfileSchema }
111752
+ );
111753
+ taskPolicy = { ...taskPolicy, ...taskLimits };
111754
+ } else {
111755
+ entry = await store.updateTaskPolicy(account.name, (current) => ({
111756
+ ...current,
111757
+ ...maxPerTask === void 0 ? {} : { maxPerTaskUsd: taskLimits.maxPerTaskUsd },
111758
+ ...approveAbove === void 0 ? {} : { approveAboveUsd: taskLimits.approveAboveUsd }
111759
+ }));
111760
+ taskPolicy = { ...taskPolicy, ...taskLimits, source: "account" };
111761
+ }
111762
+ }
111763
+ const taskLimitsChanged = taskLimits !== void 0;
111351
111764
  const caps = capsOutput(entry.spendCaps, store.ceilingCaps(account.name));
111352
111765
  await recordAudit(dependencies, "wallet.caps", {
111353
111766
  wallet: account.name,
111354
- detail: `${formatCaps(entry.spendCaps)}, ceiling ${caps.ceilingUsd === "off" ? "off" : `${caps.ceilingUsd} USDC`}`
111767
+ detail: `${formatCaps(entry.spendCaps)}, ceiling ${caps.ceilingUsd === "off" ? "off" : `${caps.ceilingUsd} USDC`}${taskLimitsChanged ? `, task limits ${formatTaskLimits(taskPolicy, false)}` : ""}`
111355
111768
  });
111356
- const message = perCall !== void 0 || perDay !== void 0 ? `Spend caps updated for ${account.name}.` : `Ceiling updated for ${account.name}.`;
111769
+ const message = perCall !== void 0 || perDay !== void 0 ? `Spend caps updated for ${account.name}.` : ceilingAtomic !== void 0 ? `Ceiling updated for ${account.name}.` : `Task limits updated for ${account.name}.`;
111770
+ const perDayUsd = Number(formatUsdc(BigInt(entry.spendCaps.perDayAtomic)));
111771
+ const perDayHint = taskLimitsChanged && taskPolicy.maxPerTaskUsd > perDayUsd ? `The per-day cap of ${formatUsdc(BigInt(entry.spendCaps.perDayAtomic))} USD still applies to task funding. Raise it with: vapi accounts caps ${account.name} --per-day <usd>` : void 0;
111357
111772
  outputForWallet2(
111358
111773
  io,
111359
111774
  json2,
@@ -111362,15 +111777,67 @@ async function accountsCapsCommand(argv, json2, io, dependencies) {
111362
111777
  ...address10 === void 0 ? {} : { address: address10 },
111363
111778
  spendCaps: entry.spendCaps,
111364
111779
  ...caps,
111365
- message
111780
+ taskLimits: taskLimitsJson(taskPolicy),
111781
+ message,
111782
+ ...perDayHint === void 0 ? {} : { hint: perDayHint }
111366
111783
  },
111367
111784
  [
111368
111785
  message,
111369
111786
  `Spend caps: ${formatCaps(entry.spendCaps)}`,
111370
- `Ceiling: ${caps.ceilingUsd === "off" ? "off" : `${caps.ceilingUsd} USDC`}`
111787
+ `Ceiling: ${caps.ceilingUsd === "off" ? "off" : `${caps.ceilingUsd} USDC`}`,
111788
+ `Task limits: ${formatTaskLimits(taskPolicy)}`,
111789
+ ...perDayHint === void 0 ? [] : [perDayHint]
111371
111790
  ].join("\n")
111372
111791
  );
111373
111792
  }
111793
+ var CAPS_USAGE = "Usage: vapi accounts caps <name> [--per-call <usd>] [--per-day <usd>] [--ceiling <usd|off>] [--max-per-task <usd>] [--approve-above <usd>] [--yes] [--json]";
111794
+ function taskLimitsJson(policy) {
111795
+ return {
111796
+ maxPerTaskUsd: policy.maxPerTaskUsd,
111797
+ approveAboveUsd: policy.approveAboveUsd,
111798
+ source: policy.source
111799
+ };
111800
+ }
111801
+ function formatTaskLimits(policy, withSource = true) {
111802
+ const source = policy.source === "agent-profile" ? "agent profile" : policy.source === "account" ? "set for this account" : "defaults";
111803
+ return `${policy.maxPerTaskUsd} USD per task, approval above ${policy.approveAboveUsd} USD${withSource && policy.source ? ` (${source})` : ""}`;
111804
+ }
111805
+ async function visibleLine(prompt, dependencies) {
111806
+ const line = getPrompts(dependencies).line;
111807
+ if (line) return await line(prompt);
111808
+ const reader = createInterface3({ input: process.stdin, output: process.stderr });
111809
+ try {
111810
+ return await reader.question(prompt);
111811
+ } finally {
111812
+ reader.close();
111813
+ }
111814
+ }
111815
+ var MAX_TASK_LIMIT_USD = 1e6;
111816
+ function taskLimitUsd(value, option) {
111817
+ const usd3 = Number(formatUsdc(BigInt(capAtomic(value, option))));
111818
+ if (!Number.isFinite(usd3) || usd3 > MAX_TASK_LIMIT_USD)
111819
+ throw new UsageError(`${option} must be at most ${MAX_TASK_LIMIT_USD} USD.`);
111820
+ return usd3;
111821
+ }
111822
+ async function liveTaskLimitUsd(dependencies) {
111823
+ try {
111824
+ const env = getEnvironment(dependencies);
111825
+ const rpcFor = dependencies.tasks?.rpcFor ?? createTasksRpcFor(await accountsConfig(dependencies), {
111826
+ env,
111827
+ ...dependencies.fetchImpl === void 0 ? {} : { fetch: dependencies.fetchImpl }
111828
+ });
111829
+ const limits = await readTaskV2Limits({
111830
+ chainId: 8453,
111831
+ shape: "task",
111832
+ rpcFor,
111833
+ env,
111834
+ timeoutMs: 2e3
111835
+ });
111836
+ return limits === void 0 ? void 0 : Number(formatUsdc(limits.maxBaseUnits));
111837
+ } catch {
111838
+ return void 0;
111839
+ }
111840
+ }
111374
111841
  var DISTRIBUTE_USAGE = "Usage: vapi accounts distribute <amount> --from <account> [--to <a,b,c>] [--network base|arc] [--json]\n vapi accounts distribute --resume <id> [--replace-expired-restored] [--bind-legacy-addresses] [--json]\n vapi accounts distribute --cancel <id> [--replace-expired-restored] [--json]";
111375
111842
  async function accountsDistributeCommand(argv, json2, io, dependencies) {
111376
111843
  const parsed = parseArguments(argv, {
@@ -111626,19 +112093,19 @@ function formatNetworkAccounts(accounts) {
111626
112093
 
111627
112094
  // src/agent.ts
111628
112095
  import { readFile as readFile30, stat as stat19 } from "node:fs/promises";
111629
- import { join as join32 } from "node:path";
111630
- import { createInterface as createInterface3 } from "node:readline/promises";
112096
+ import { join as join33 } from "node:path";
112097
+ import { createInterface as createInterface4 } from "node:readline/promises";
111631
112098
 
111632
112099
  // src/headless.ts
111633
112100
  import { rmSync } from "node:fs";
111634
112101
  import { chmod as chmod7, mkdtemp as mkdtemp2, rm as rm5, writeFile as writeFile9 } from "node:fs/promises";
111635
112102
  import { tmpdir as osTmpdir } from "node:os";
111636
- import { join as join30 } from "node:path";
112103
+ import { join as join31 } from "node:path";
111637
112104
  var BUNDLE_VARIABLE_PATTERN = /^[A-Z_][A-Z0-9_]*$/u;
111638
112105
  var REMOTE_BLOCKED_GRANTS2 = /* @__PURE__ */ new Set(["delegate", "allocate"]);
111639
112106
  var agentProfileOptions = { schema: registeredAgentProfileSchema };
111640
112107
  async function createHeadlessHome(bundle, options = {}) {
111641
- const home = await mkdtemp2(join30(options.tmpdir ?? osTmpdir(), "vapi-headless-"));
112108
+ const home = await mkdtemp2(join31(options.tmpdir ?? osTmpdir(), "vapi-headless-"));
111642
112109
  const cleanup = async () => {
111643
112110
  await rm5(home, { recursive: true, force: true });
111644
112111
  };
@@ -111850,7 +112317,7 @@ import {
111850
112317
  writeFile as nodeWriteFile
111851
112318
  } from "node:fs/promises";
111852
112319
  import { tmpdir as osTmpdir2 } from "node:os";
111853
- import { basename as basename4, dirname as dirname14, join as join31 } from "node:path";
112320
+ import { basename as basename4, dirname as dirname14, join as join32 } from "node:path";
111854
112321
  var RAILWAY_CLI = {
111855
112322
  binary: "railway",
111856
112323
  create: (options) => [
@@ -112041,7 +112508,7 @@ async function assertRemoteSafeMember(args) {
112041
112508
  }
112042
112509
  function railwaySidecarPath(home, runId) {
112043
112510
  if (!isRunId(runId)) throw new RuntimeError("invalid_run_id", `Invalid run id: ${runId}.`);
112044
- return join31(runsDirectory(home), `${runId}.railway.json`);
112511
+ return join32(runsDirectory(home), `${runId}.railway.json`);
112045
112512
  }
112046
112513
  function createRailwayRuntime(options) {
112047
112514
  const { home } = options;
@@ -112402,10 +112869,10 @@ ${destroyedInstruction}
112402
112869
  let createError;
112403
112870
  let cleanupError;
112404
112871
  try {
112405
- directory = await fs.mkdtemp(join31(options.tmpdir ?? osTmpdir2(), "vapi-railway-"));
112872
+ directory = await fs.mkdtemp(join32(options.tmpdir ?? osTmpdir2(), "vapi-railway-"));
112406
112873
  assertNotInterrupted();
112407
112874
  await assertMode(fs, directory, 448, "env-file directory");
112408
- envFile = join31(directory, "member.env");
112875
+ envFile = join32(directory, "member.env");
112409
112876
  await fs.writeFile(envFile, `${RAILWAY_CLI.bundleVariable}=${bundle}
112410
112877
  `, {
112411
112878
  encoding: "utf8",
@@ -112766,7 +113233,7 @@ Destroy it yourself with: railway sandbox destroy ${id2}`
112766
113233
  return { runId, sandboxId: id2, destroyed: true };
112767
113234
  };
112768
113235
  if (account !== void 0) return await withMemberRunLock(home, account, destroy);
112769
- return await withFileLock(join31(runsDirectory(home), `.sidecar-${runId}.lock`), destroy, {
113236
+ return await withFileLock(join32(runsDirectory(home), `.sidecar-${runId}.lock`), destroy, {
112770
113237
  timeoutMs: 5e3,
112771
113238
  lockedMessage: `Run ${runId} is changing sidecar state.`
112772
113239
  });
@@ -112988,7 +113455,7 @@ async function writeSidecar(home, runId, sidecar) {
112988
113455
  function writeSidecarSync(path, sidecar) {
112989
113456
  const directory = dirname14(path);
112990
113457
  mkdirSync(directory, { recursive: true, mode: 448 });
112991
- const temporary = join31(
113458
+ const temporary = join32(
112992
113459
  directory,
112993
113460
  `.${basename4(path)}.${process.pid}.${randomBytes17(6).toString("hex")}.tmp`
112994
113461
  );
@@ -113086,7 +113553,7 @@ async function assertMode(fs, path, mode, what) {
113086
113553
  }
113087
113554
  }
113088
113555
  async function deviceVaultKey2(home, secrets, now) {
113089
- const path = join31(home, "vault.json");
113556
+ const path = join32(home, "vault.json");
113090
113557
  const metadata = await readVaultFileUnlocked(path);
113091
113558
  const key2 = metadata.protected ? await unlockProtectedVault({
113092
113559
  path,
@@ -113457,24 +113924,42 @@ async function createCommand(argv, json2, io, dependencies) {
113457
113924
  const callBudget = usdOption(parsed.one("--call-budget") ?? "1", "--call-budget", true);
113458
113925
  const maxPerCall = usdOption(parsed.one("--max-per-call") ?? "0.05", "--max-per-call");
113459
113926
  const routerBudget = usdOption(parsed.one("--router-budget") ?? "1", "--router-budget", true);
113460
- const approveAbove = usdOption(parsed.one("--approve-above") ?? "0.5", "--approve-above");
113927
+ const initialStore = await openWalletStore(dependencies);
113928
+ const owned = initialStore.entry(name);
113929
+ const stricter = accountTaskLimitsUnderProfile(owned?.taskPolicy);
113930
+ const defaultMaxPerTask = stricter?.maxPerTaskUsd ?? DEFAULT_MAX_PER_TASK_USD;
113931
+ const approveAbove = usdOption(
113932
+ parsed.one("--approve-above") ?? String(stricter?.approveAboveUsd ?? 0.5),
113933
+ "--approve-above"
113934
+ );
113461
113935
  const maxSteps = boundedInteger(parsed.one("--max-steps") ?? "12", "--max-steps", 1, 50);
113462
113936
  const interactive = !json2 && (dependencies.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY));
113463
113937
  const promptForTaskPolicy = interactive && !parsed.has("--yes");
113464
113938
  const maxPerTask = usdOption(
113465
- parsed.one("--max-per-task") ?? ((promptForTaskPolicy ? await visibleLine(`Max per task in USD [${DEFAULT_MAX_PER_TASK_USD}]: `, dependencies) : "") || String(DEFAULT_MAX_PER_TASK_USD)),
113939
+ parsed.one("--max-per-task") ?? ((promptForTaskPolicy ? await visibleLine2(`Max per task in USD [${defaultMaxPerTask}]: `, dependencies) : "") || String(defaultMaxPerTask)),
113466
113940
  "--max-per-task"
113467
113941
  );
113468
113942
  const autoReleaseBelow = usdOption(
113469
- parsed.one("--auto-release-below") ?? ((promptForTaskPolicy ? await visibleLine(
113943
+ parsed.one("--auto-release-below") ?? ((promptForTaskPolicy ? await visibleLine2(
113470
113944
  `Auto-release below in USD [${DEFAULT_AUTO_RELEASE_BELOW_USD}]: `,
113471
113945
  dependencies
113472
113946
  ) : "") || String(DEFAULT_AUTO_RELEASE_BELOW_USD)),
113473
113947
  "--auto-release-below"
113474
113948
  );
113949
+ if (owned !== void 0) {
113950
+ const raised = [
113951
+ ...maxPerTask.number > (owned.taskPolicy?.maxPerTaskUsd ?? DEFAULT_MAX_PER_TASK_USD) ? [`--max-per-task ${maxPerTask.text}`] : [],
113952
+ ...approveAbove.number > (owned.taskPolicy?.approveAboveUsd ?? 0.5) ? [`--approve-above ${approveAbove.text}`] : [],
113953
+ ...BigInt(callBudget.atomic) > BigInt(owned.spendCaps.perDayAtomic) ? [`--call-budget ${callBudget.text}`] : []
113954
+ ];
113955
+ const marker = activeAgentMarker(getEnvironment(dependencies));
113956
+ if (raised.length > 0 && (marker !== void 0 || !isStdinInteractive(dependencies)))
113957
+ throw new UsageError(
113958
+ `Account ${name} already exists, and ${raised.join(", ")} would raise what it has now: ${owned.taskPolicy?.maxPerTaskUsd ?? DEFAULT_MAX_PER_TASK_USD} USD per task, approval above ${owned.taskPolicy?.approveAboveUsd ?? 0.5} USD, ${formatUsdc(BigInt(owned.spendCaps.perDayAtomic))} USD per day. Raising a limit is a decision for a person. Nothing was changed. ${marker === void 0 ? "Standard input is not a terminal." : `${marker} is set, so this is an agent session.`} Run the command yourself in a terminal, or leave these values at or below the account's.`
113959
+ );
113960
+ }
113475
113961
  const commandIo = json2 ? { stdout: () => void 0, stderr: io.stderr } : io;
113476
- const initialStore = await openWalletStore(dependencies);
113477
- if (!initialStore.has(name)) {
113962
+ if (owned === void 0) {
113478
113963
  await walletCreateCommand([name, "--label", name], json2, commandIo, dependencies);
113479
113964
  }
113480
113965
  await walletCapsCommand(
@@ -113499,6 +113984,20 @@ async function createCommand(argv, json2, io, dependencies) {
113499
113984
  paused: false,
113500
113985
  createdAt: (dependencies.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
113501
113986
  };
113987
+ let clearedAccountTaskLimits = false;
113988
+ const keptAccountTaskLimits = (await initialStore.updateTaskPolicy(name, (current) => {
113989
+ const kept = accountTaskLimitsUnderProfile(current);
113990
+ clearedAccountTaskLimits = JSON.stringify(kept) !== JSON.stringify(current);
113991
+ return kept;
113992
+ })).taskPolicy;
113993
+ if (keptAccountTaskLimits)
113994
+ io.stderr(
113995
+ `Account ${name} keeps the task limits its owner set below the defaults. When the agent profile is removed it returns to ${keptAccountTaskLimits.maxPerTaskUsd ?? DEFAULT_MAX_PER_TASK_USD} USD per task and approval above ${keptAccountTaskLimits.approveAboveUsd ?? 0.5} USD. The agent profile holds the limits now: ${profile.maxPerTaskUsd} USD per task, approval above ${profile.approveAboveUsd} USD.`
113996
+ );
113997
+ else if (clearedAccountTaskLimits)
113998
+ io.stderr(
113999
+ `The task limits set for account ${name} with vapi accounts caps were cleared. The agent profile holds them now: ${profile.maxPerTaskUsd} USD per task, approval above ${profile.approveAboveUsd} USD.`
114000
+ );
113502
114001
  const writeProfile = dependencies.agent?.writeAgentProfile ?? writeAgentProfile;
113503
114002
  await writeProfile(paths.directory, profile, agentProfileOptions2);
113504
114003
  await runLoginFlow(["--account", name, "--label", name], json2, commandIo, dependencies, {
@@ -113526,6 +114025,7 @@ async function createCommand(argv, json2, io, dependencies) {
113526
114025
  perDayAtomic: callBudget.atomic
113527
114026
  },
113528
114027
  routerAllowanceUsd: routerBudget.number,
114028
+ ...clearedAccountTaskLimits ? { clearedAccountTaskLimits: true } : {},
113529
114029
  fundingHint
113530
114030
  })
113531
114031
  );
@@ -113778,7 +114278,7 @@ async function buildAgentRunDeps(input2) {
113778
114278
  };
113779
114279
  const approve2 = async ({ ref, priceUsd, reason }) => {
113780
114280
  if (approvals === "decline" || !tty) return false;
113781
- const answer = await visibleLine(
114281
+ const answer = await visibleLine2(
113782
114282
  `Pay ${usd(priceUsd)} to ${ref}? ${reason} [y/N] `,
113783
114283
  dependencies
113784
114284
  );
@@ -114051,10 +114551,10 @@ function searchQuery(argumentsJson) {
114051
114551
  return void 0;
114052
114552
  }
114053
114553
  }
114054
- async function visibleLine(prompt, dependencies) {
114554
+ async function visibleLine2(prompt, dependencies) {
114055
114555
  if (dependencies.prompts?.line)
114056
114556
  return (await dependencies.prompts.line(prompt)).trim().toLowerCase();
114057
- const reader = createInterface3({ input: process.stdin, output: process.stderr });
114557
+ const reader = createInterface4({ input: process.stdin, output: process.stderr });
114058
114558
  try {
114059
114559
  return (await reader.question(prompt)).trim().toLowerCase();
114060
114560
  } finally {
@@ -114066,7 +114566,7 @@ function explicitWallet(name) {
114066
114566
  }
114067
114567
  async function profileFileExists(directory, name) {
114068
114568
  try {
114069
- await stat19(join32(directory, `${name}.json`));
114569
+ await stat19(join33(directory, `${name}.json`));
114070
114570
  return true;
114071
114571
  } catch (error61) {
114072
114572
  if (isMissingFile(error61)) return false;
@@ -114783,7 +115283,7 @@ import { constants as constants3, homedir as homedir4 } from "node:os";
114783
115283
  import { constants as constants2 } from "node:fs";
114784
115284
  import { access, mkdir as mkdir20, readFile as readFile31, realpath, unlink as unlink15, writeFile as writeFile10 } from "node:fs/promises";
114785
115285
  import { homedir as homedir3 } from "node:os";
114786
- import { basename as basename5, dirname as dirname15, join as join33, posix, win32 as win322 } from "node:path";
115286
+ import { basename as basename5, dirname as dirname15, join as join34, posix, win32 as win322 } from "node:path";
114787
115287
 
114788
115288
  // src/toml-config.ts
114789
115289
  function removeTomlTables(contents, isTarget) {
@@ -114863,7 +115363,7 @@ var VAPI_CODEX_PROFILE = "vapi";
114863
115363
  var VAPI_CODEX_DEFAULT_MODEL = "venice/openai-gpt-61-sol";
114864
115364
  var VAPI_ROUTER_KEY_ENV = "VAPI_ROUTER_KEY";
114865
115365
  function codexConfigPath(env, home) {
114866
- return join33(env.CODEX_HOME || join33(home, ".codex"), "config.toml");
115366
+ return join34(env.CODEX_HOME || join34(home, ".codex"), "config.toml");
114867
115367
  }
114868
115368
  function hasVapiCodexProfile(contents) {
114869
115369
  const roots = new Set(
@@ -114979,7 +115479,7 @@ async function codeCommand(argv, json2, io, dependencies) {
114979
115479
  const env = getEnvironment(dependencies);
114980
115480
  const home = dependencies.code?.homedir ?? homedir3();
114981
115481
  const config2 = codexConfigPath(env, home);
114982
- const rcPaths = [join33(home, ".zshrc"), join33(home, ".bashrc")];
115482
+ const rcPaths = [join34(home, ".zshrc"), join34(home, ".bashrc")];
114983
115483
  if (command === "uninstall") {
114984
115484
  const removed = [];
114985
115485
  const previous = await readOptional(config2);
@@ -117225,7 +117725,8 @@ async function taskV2Command(verb, id2, parsed, json2, io, dependencies) {
117225
117725
  const policy = await taskPolicyForWallet({
117226
117726
  directory: getVapiPaths().directory,
117227
117727
  wallet: target.name,
117228
- schema: registeredAgentProfileSchema
117728
+ schema: registeredAgentProfileSchema,
117729
+ warn: io.stderr
117229
117730
  });
117230
117731
  try {
117231
117732
  const result = await executeTaskV2(context, {
@@ -117327,7 +117828,8 @@ async function taskJuryCommand(verb, id2, parsed, json2, io, dependencies) {
117327
117828
  policy: await taskPolicyForWallet({
117328
117829
  directory: getVapiPaths().directory,
117329
117830
  wallet: target.name,
117330
- schema: registeredAgentProfileSchema
117831
+ schema: registeredAgentProfileSchema,
117832
+ warn: io.stderr
117331
117833
  }),
117332
117834
  caps: await spendCapsForWallet(target.store, target.name),
117333
117835
  wallet: target.name,
@@ -117426,12 +117928,13 @@ var TASK_HELP = `Usage:
117426
117928
  vapi task watch <id> [--until <state>] [--auto-release] [--timeout 7d] [--interval 5s] [--counterparty <0x\u2026>] [--account <name>] [--json]
117427
117929
  vapi task status <id> [--operation <uuid> --step <v2-step> --recover|--abandon] [--account <name>] [--json]
117428
117930
 
117429
- Durations: 5s, 10m, 48h, 7d, or an ISO-8601 timestamp. Task milestone deadlines require at least one hour; bounty and pool posting and proposal terms require at least 10 minutes.
117931
+ Durations: 5s, 10m, 48h, 7d, or an ISO-8601 timestamp. A task deadline and every task milestone deadline must be at least 3 hours ahead when vAPI receives the post (one hour of work time, one to award, one to fund); use 181m or more. Bounty and pool posting and proposal terms require at least 10 minutes.
117430
117932
  V1 dispute accepts a precomputed evidence hash. V2 dispute accepts --index with --evidence text. Milestone action indices are zero-based; declared milestone indices remain one-based.
117431
117933
  Jury: ${TASK_V2_JURY_RULES} ${TASK_V2_REVIEWER_GUIDANCE} Jury open repeats while the case is Snapshotting.
117432
117934
  Vote --commit seals the salt in a local ballot under VAPI_HOME before vAPI sees the commitment; --reveal reads that ballot back by the onchain commitment, so reveal from the machine that committed. --to-worker is USDC base units and only for split.
117433
117935
  Watch requires an interval of at least 1s and a positive timeout. Auto-release uses the acting wallet's agent profile, or defaults, and releases only amounts strictly below the threshold.
117434
- Posting without --fund moves no money. --fund applies task and daily caps before signing. Task reads require tasks:read and writes require tasks:write; write access includes reads.
117936
+ Posting without --fund moves no money. --fund applies task and daily caps before signing. Fund, post --fund, approve-bond, sign --action award-consent and award --worker need vAPI to report Tasks as available and stop before signing when it does not; a rerun of an operation that already signed something is resumed instead. Show or raise task limits with vapi accounts caps <name> [--max-per-task <usd>] [--approve-above <usd>].
117937
+ Base mainnet runs V2 only: the worker runs sign --action award-consent, then the poster runs award --worker <addr>. propose sends an offer the poster can read. award <proposalId> and sign without --action are V1 only. Task reads require tasks:read and writes require tasks:write; write access includes reads.
117435
117938
  The thread cursor is the previous page's nextBeforeSeq; --after reads older messages using beforeSeq.
117436
117939
  Every command accepts --json. Watch and a partially completed sign may write more than one JSON value. Human diagnostics go to stderr.
117437
117940
 
@@ -117614,6 +118117,10 @@ async function taskContext(parsed, io, dependencies, publicOnly = false) {
117614
118117
  const injected = dependencies.tasks?.client;
117615
118118
  const client = typeof injected === "function" ? injected(options) : injected ?? createHostedTasksClient(options);
117616
118119
  const pending = createPendingTransactions(getVapiPaths().directory);
118120
+ const readRpcFor = dependencies.tasks?.rpcFor ?? createTasksRpcFor(config2, {
118121
+ env,
118122
+ ...dependencies.fetchImpl === void 0 ? {} : { fetch: dependencies.fetchImpl }
118123
+ });
117617
118124
  const chain2 = dependencies.tasks?.chain ?? (publicOnly || target === void 0 ? missingTasksChain : lazyTasksChain2(
117618
118125
  async () => {
117619
118126
  const { account } = await unlockTarget(target, dependencies);
@@ -117640,6 +118147,7 @@ async function taskContext(parsed, io, dependencies, publicOnly = false) {
117640
118147
  ));
117641
118148
  return {
117642
118149
  client,
118150
+ limitsV2: (chainId, shape) => readTaskV2Limits({ chainId, shape, rpcFor: readRpcFor, env }),
117643
118151
  baseUrl,
117644
118152
  ...target === void 0 ? {} : { target },
117645
118153
  ...token === void 0 ? {} : { token },
@@ -117853,7 +118361,8 @@ async function taskCommandInner(argv, json2, io, dependencies) {
117853
118361
  budget: parsed.one("--budget"),
117854
118362
  gate: enumOption(parsed.one("--gate"), ["open", "proven"], "--gate"),
117855
118363
  verifier: enumOption(parsed.one("--verifier"), ["poster", "vapi"], "--verifier"),
117856
- openCheck: enumOption(parsed.one("--open-check"), ["allowlist", "invite"], "--open-check")
118364
+ openCheck: enumOption(parsed.one("--open-check"), ["allowlist", "invite"], "--open-check"),
118365
+ intake: enumOption(parsed.one("--intake"), ["proposals", "submissions"], "--intake")
117857
118366
  },
117858
118367
  now
117859
118368
  );
@@ -117886,7 +118395,9 @@ async function taskCommandInner(argv, json2, io, dependencies) {
117886
118395
  ...intake === void 0 ? {} : { intake },
117887
118396
  ...maxAwards === void 0 ? {} : { maxAwards },
117888
118397
  ...parsed.one("--webhook") === void 0 ? {} : { webhook: parsed.one("--webhook") },
117889
- onFeeUnavailable: () => io.stderr("The deployed fee is unavailable.")
118398
+ onFeeUnavailable: () => io.stderr(
118399
+ "The fee could not be read from the Tasks contract or from vAPI. Funding shows it before anything is signed."
118400
+ )
117890
118401
  });
117891
118402
  if (parsed.has("--fund")) {
117892
118403
  if (outcome.funding?.error) {
@@ -118753,7 +119264,7 @@ Usage:
118753
119264
  vapi accounts use <name> [--json]
118754
119265
  vapi accounts remove <name> [--force] [--json]
118755
119266
  vapi accounts restore <name> [--json]
118756
- vapi accounts caps <name> [--per-call <usd>] [--per-day <usd>] [--ceiling <usd|off>] [--json]
119267
+ vapi accounts caps <name> [--per-call <usd>] [--per-day <usd>] [--ceiling <usd|off>] [--max-per-task <usd>] [--approve-above <usd>] [--yes] [--json]
118757
119268
  vapi accounts distribute <amount> --from <account> [--to <a,b,c>] [--network base|arc] [--json]
118758
119269
  vapi accounts distribute --resume <id> [--replace-expired-restored] [--bind-legacy-addresses] [--json]
118759
119270
  vapi accounts distribute --cancel <id> [--replace-expired-restored] [--json]
@@ -119069,7 +119580,7 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
119069
119580
  break;
119070
119581
  case "unlock":
119071
119582
  io.stderr("vapi unlock is now vapi vault unlock; the old name works for one release.");
119072
- if (await fileExists3(join34(getVapiPaths().directory, "vault.json"))) {
119583
+ if (await fileExists3(join35(getVapiPaths().directory, "vault.json"))) {
119073
119584
  parseArguments(args.slice(1), {
119074
119585
  valueOptions: /* @__PURE__ */ new Set([WALLET_OPTION]),
119075
119586
  maximumPositionals: 0
@@ -119269,7 +119780,7 @@ async function initCommand(argv, json2, io, dependencies) {
119269
119780
  address: account.address,
119270
119781
  accounts,
119271
119782
  config: paths.config,
119272
- vault: join34(paths.directory, "vault.json"),
119783
+ vault: join35(paths.directory, "vault.json"),
119273
119784
  ...configRewrites.length > 0 ? { configRewrites } : {},
119274
119785
  custody: "self",
119275
119786
  warning: CUSTODY_NOTICE,
@@ -119408,7 +119919,7 @@ async function walletCreateCommand(argv, json2, io, dependencies) {
119408
119919
  const result = {
119409
119920
  address: account.address,
119410
119921
  ...account.solana ? { solanaAddress: account.solana.address } : {},
119411
- vault: join34(paths.directory, "vault.json"),
119922
+ vault: join35(paths.directory, "vault.json"),
119412
119923
  ...label2 === void 0 ? {} : { label: label2 },
119413
119924
  spendCaps: created.entry.spendCaps,
119414
119925
  isDefault,
@@ -119448,7 +119959,7 @@ function formatCaps2(caps) {
119448
119959
  function walletListResult(store, wallets, unlocked) {
119449
119960
  return {
119450
119961
  default: store.defaultName ?? null,
119451
- vault: join34(store.home, "vault.json"),
119962
+ vault: join35(store.home, "vault.json"),
119452
119963
  wallets: wallets.map((wallet) => ({
119453
119964
  name: wallet.name,
119454
119965
  ...wallet.address === void 0 ? {} : { address: wallet.address },