vapi-network 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
@@ -10131,7 +10131,7 @@ __export(src_exports4, {
10131
10131
  });
10132
10132
 
10133
10133
  // ../cli/src/cli.ts
10134
- import { join as join35 } from "node:path";
10134
+ import { join as join36 } from "node:path";
10135
10135
 
10136
10136
  // ../core/src/index.ts
10137
10137
  var src_exports = {};
@@ -10242,6 +10242,7 @@ __export(src_exports, {
10242
10242
  X402_SOLANA_MAINNET_CAIP2: () => X402_SOLANA_MAINNET_CAIP2,
10243
10243
  __setAtomicFileTestHooks: () => __setAtomicFileTestHooks,
10244
10244
  __setReceiptTestHooks: () => __setReceiptTestHooks,
10245
+ accountTaskLimitsUnderProfile: () => accountTaskLimitsUnderProfile,
10245
10246
  activeAgentMarker: () => activeAgentMarker,
10246
10247
  addAccount: () => addAccount,
10247
10248
  addSwarmMember: () => addSwarmMember,
@@ -10498,6 +10499,7 @@ __export(src_exports, {
10498
10499
  walletEntrySchema: () => walletEntrySchema,
10499
10500
  walletNameSchema: () => walletNameSchema,
10500
10501
  walletRegistrySchema: () => walletRegistrySchema,
10502
+ walletTaskPolicySchema: () => walletTaskPolicySchema,
10501
10503
  windowsSecretFileName: () => windowsSecretFileName,
10502
10504
  withAccountMovementLock: () => withAccountMovementLock,
10503
10505
  withFileLock: () => withFileLock,
@@ -47839,6 +47841,10 @@ var DEFAULT_SPEND_CAPS = {
47839
47841
  };
47840
47842
  var DEFAULT_MAX_PER_TASK_USD = 100;
47841
47843
  var DEFAULT_AUTO_RELEASE_BELOW_USD = 25;
47844
+ var walletTaskPolicySchema = external_exports.object({
47845
+ maxPerTaskUsd: external_exports.number().min(0).optional(),
47846
+ approveAboveUsd: external_exports.number().min(0).optional()
47847
+ });
47842
47848
  var DEFAULT_CEILING_ATOMIC = 5000000n;
47843
47849
  var atomicString = external_exports.string().regex(/^\d+$/, "Expected non-negative atomic units.");
47844
47850
  var spendCapsSchema = external_exports.object({
@@ -72023,10 +72029,21 @@ function readSecretBackend(home = getVapiPaths().directory) {
72023
72029
  }
72024
72030
  async function chooseSecretBackend(options) {
72025
72031
  const env = options.env ?? process.env;
72026
- const osWorks = options.os.platform !== "linux" || await osStoreWorks(options.os);
72032
+ const osWorks = await osStoreUsable(options.os);
72027
72033
  const path = secretBackendPath(options.home);
72028
72034
  return await withVaultLock(path, async () => {
72029
- if (await fileExists(path)) return readSecretBackend(options.home);
72035
+ if (await fileExists(path)) {
72036
+ const pinned = readSecretBackend(options.home);
72037
+ if (pinned === "os" && !hasOsStore(options.os.platform)) {
72038
+ throw new KeystoreError(
72039
+ [
72040
+ `This vAPI home is set to use the OS secret store, which ${options.os.platform} does not have.`,
72041
+ `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.`
72042
+ ].join(" ")
72043
+ );
72044
+ }
72045
+ return pinned;
72046
+ }
72030
72047
  if (await fileExists(join6(options.home, "vault.json"))) return "os";
72031
72048
  let backend;
72032
72049
  if (osWorks) {
@@ -72056,6 +72073,13 @@ async function fileExists(path) {
72056
72073
  throw error61;
72057
72074
  }
72058
72075
  }
72076
+ function hasOsStore(platform2) {
72077
+ return platform2 === "darwin" || platform2 === "win32" || platform2 === "linux";
72078
+ }
72079
+ async function osStoreUsable(store) {
72080
+ if (store.platform === "linux") return await osStoreWorks(store);
72081
+ return hasOsStore(store.platform);
72082
+ }
72059
72083
  async function osStoreWorks(store) {
72060
72084
  if (!store.available) return false;
72061
72085
  try {
@@ -73353,6 +73377,8 @@ var walletEntrySchema = external_exports.object({
73353
73377
  ceilingAtomic: external_exports.string().regex(/^\d+$/).nullable().optional(),
73354
73378
  ceilingSweepAttemptedAt: external_exports.iso.datetime().optional(),
73355
73379
  ceilingSweepPending: ceilingSweepPendingSchema.optional(),
73380
+ // Task limits for an account without an agent profile; absent means the defaults.
73381
+ taskPolicy: walletTaskPolicySchema.optional(),
73356
73382
  routerRefill: routerRefillSchema.optional(),
73357
73383
  routerPendingPurchase: routerPendingPurchaseSchema.optional(),
73358
73384
  link: agentLinkSchema.optional()
@@ -73701,6 +73727,30 @@ var WalletStore = class _WalletStore {
73701
73727
  return structuredClone(entry);
73702
73728
  });
73703
73729
  }
73730
+ /**
73731
+ * Stores task limits for an account without an agent profile, from the latest registry value
73732
+ * while holding its write lock. Returning undefined removes them, so the defaults apply.
73733
+ */
73734
+ async updateTaskPolicy(name, update) {
73735
+ const walletName = assertWalletName(name);
73736
+ return await withRegistryLock(this.registryPath, async () => {
73737
+ const registry2 = await this.readRegistry();
73738
+ const entry = ownWalletEntry(registry2.wallets, walletName);
73739
+ if (!entry) {
73740
+ throw new KeystoreError(unknownWalletMessage(walletName, Object.keys(registry2.wallets)));
73741
+ }
73742
+ const next = update(entry.taskPolicy === void 0 ? void 0 : { ...entry.taskPolicy });
73743
+ const parsed = next === void 0 ? void 0 : walletTaskPolicySchema.parse(next);
73744
+ if (JSON.stringify(parsed) !== JSON.stringify(entry.taskPolicy)) {
73745
+ if (parsed === void 0) delete entry.taskPolicy;
73746
+ else entry.taskPolicy = parsed;
73747
+ await this.writeRegistry(registry2);
73748
+ } else {
73749
+ this.registry = registry2;
73750
+ }
73751
+ return structuredClone(entry);
73752
+ });
73753
+ }
73704
73754
  /** Reads the configured ceiling and the per-day-cap floor for one wallet. */
73705
73755
  ceilingCaps(name) {
73706
73756
  const entry = this.resolve({ name }).entry;
@@ -75108,6 +75158,14 @@ function secretsAllowed(env, streams) {
75108
75158
  import { randomBytes as randomBytes10 } from "node:crypto";
75109
75159
  import { mkdir as mkdir11, readFile as readFile13, readdir as readdir4, rename as rename8, unlink as unlink8, writeFile as writeFile5 } from "node:fs/promises";
75110
75160
  import { join as join11 } from "node:path";
75161
+ var DEFAULT_APPROVE_ABOVE_USD = 0.5;
75162
+ function accountTaskLimitsUnderProfile(current) {
75163
+ const kept = {
75164
+ ...current?.maxPerTaskUsd !== void 0 && current.maxPerTaskUsd < DEFAULT_MAX_PER_TASK_USD ? { maxPerTaskUsd: current.maxPerTaskUsd } : {},
75165
+ ...current?.approveAboveUsd !== void 0 && current.approveAboveUsd < DEFAULT_APPROVE_ABOVE_USD ? { approveAboveUsd: current.approveAboveUsd } : {}
75166
+ };
75167
+ return Object.keys(kept).length === 0 ? void 0 : kept;
75168
+ }
75111
75169
  var DEFAULT_AGENT_TOOLS = ["call.search", "call.inspect", "call.pay"];
75112
75170
  var AGENT_GRANTS = ["read", "delegate", "allocate"];
75113
75171
  var agentProfileShape = {
@@ -75117,7 +75175,7 @@ var agentProfileShape = {
75117
75175
  model: external_exports.string().min(1),
75118
75176
  instructions: external_exports.string().max(2e4),
75119
75177
  verifiedOnly: external_exports.boolean().default(true),
75120
- approveAboveUsd: external_exports.number().min(0).default(0.5),
75178
+ approveAboveUsd: external_exports.number().min(0).default(DEFAULT_APPROVE_ABOVE_USD),
75121
75179
  maxPerTaskUsd: external_exports.number().min(0).default(DEFAULT_MAX_PER_TASK_USD),
75122
75180
  autoReleaseBelowUsd: external_exports.number().min(0).default(DEFAULT_AUTO_RELEASE_BELOW_USD),
75123
75181
  maxSteps: external_exports.number().int().min(1).max(50).default(12),
@@ -78898,6 +78956,7 @@ async function provisionSwarm(opts, home, swarm, accounts) {
78898
78956
  }
78899
78957
  if (member !== void 0) {
78900
78958
  if (!await profileExists(home, member.account)) {
78959
+ const stricter = (await opts.store.updateTaskPolicy(member.account, accountTaskLimitsUnderProfile)).taskPolicy;
78901
78960
  await writeAgentProfile(home, {
78902
78961
  version: 1,
78903
78962
  name: member.account,
@@ -78907,7 +78966,8 @@ async function provisionSwarm(opts, home, swarm, accounts) {
78907
78966
  tools: [...DEFAULT_AGENT_TOOLS],
78908
78967
  grants: roleGrants(member.role),
78909
78968
  verifiedOnly: true,
78910
- approveAboveUsd: 0.5,
78969
+ approveAboveUsd: stricter?.approveAboveUsd ?? 0.5,
78970
+ ...stricter?.maxPerTaskUsd === void 0 ? {} : { maxPerTaskUsd: stricter.maxPerTaskUsd },
78911
78971
  maxSteps: 12,
78912
78972
  paused: false,
78913
78973
  createdAt: (opts.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
@@ -79243,7 +79303,7 @@ function createRunBudget(args) {
79243
79303
  import { mkdir as mkdir15, writeFile as writeFile7 } from "node:fs/promises";
79244
79304
  import { arch, platform, release } from "node:os";
79245
79305
  import { join as join14 } from "node:path";
79246
- var VAPI_CLIENT_VERSION = "0.16.0";
79306
+ var VAPI_CLIENT_VERSION = "0.16.2";
79247
79307
  async function createSupportReport(options) {
79248
79308
  const message = options.message.trim();
79249
79309
  if (!message) throw new Error("Support report message must not be empty.");
@@ -81444,10 +81504,13 @@ __export(tasks_exports, {
81444
81504
  TASKS_CLIENT_VERBS: () => TASKS_CLIENT_VERBS,
81445
81505
  TASKS_V2_EVENT_ABIS: () => TASKS_V2_EVENT_ABIS,
81446
81506
  TASK_LIMITS: () => TASK_LIMITS,
81507
+ TASK_POST_DEADLINE_LEAD_MS: () => TASK_POST_DEADLINE_LEAD_MS,
81508
+ TASK_POST_DEADLINE_MARGIN_MS: () => TASK_POST_DEADLINE_MARGIN_MS,
81447
81509
  TASK_V2_CASE_STATES: () => TASK_V2_CASE_STATES,
81448
81510
  TASK_V2_GAS_BUFFER_PERCENT: () => TASK_V2_GAS_BUFFER_PERCENT,
81449
81511
  TASK_V2_JURY_RULES: () => TASK_V2_JURY_RULES,
81450
81512
  TASK_V2_JURY_STEPS: () => TASK_V2_JURY_STEPS,
81513
+ TASK_V2_NEW_WORK_ACTIONS: () => TASK_V2_NEW_WORK_ACTIONS,
81451
81514
  TASK_V2_NO_VERDICT_SUMMARY: () => TASK_V2_NO_VERDICT_SUMMARY,
81452
81515
  TASK_V2_REDACTED: () => TASK_V2_REDACTED,
81453
81516
  TASK_V2_REDACTED_CALLDATA: () => TASK_V2_REDACTED_CALLDATA,
@@ -81466,6 +81529,7 @@ __export(tasks_exports, {
81466
81529
  TasksScopeCreationError: () => TasksScopeCreationError,
81467
81530
  V2_RESOLVER_ACTIONS: () => V2_RESOLVER_ACTIONS,
81468
81531
  acceptedV2WorkerBond: () => acceptedV2WorkerBond,
81532
+ assertWithinTaskV2Limit: () => assertWithinTaskV2Limit,
81469
81533
  autoReleaseDecision: () => autoReleaseDecision,
81470
81534
  awardTask: () => awardTask,
81471
81535
  boardNumbersSchema: () => boardNumbersSchema,
@@ -81556,7 +81620,9 @@ __export(tasks_exports, {
81556
81620
  publicTaskV2Recovery: () => publicTaskV2Recovery,
81557
81621
  readTaskFile: () => readTaskFile,
81558
81622
  readTaskV2Ballot: () => readTaskV2Ballot,
81623
+ readTaskV2Limits: () => readTaskV2Limits,
81559
81624
  readTaskV2ReviewerStatus: () => readTaskV2ReviewerStatus,
81625
+ readTasksReadiness: () => readTasksReadiness,
81560
81626
  recoverTaskV2: () => recoverTaskV2,
81561
81627
  redactTaskV2Ballots: () => redactTaskV2Ballots,
81562
81628
  refundTask: () => refundTask,
@@ -81564,6 +81630,7 @@ __export(tasks_exports, {
81564
81630
  releaseTask: () => releaseTask,
81565
81631
  releaseTaskOperation: () => releaseTaskOperation,
81566
81632
  requireTaskMethod: () => requireTaskMethod,
81633
+ requireTasksAvailable: () => requireTasksAvailable,
81567
81634
  resolveTaskBearer: () => resolveTaskBearer,
81568
81635
  resolveUnmatchedTask: () => resolveUnmatchedTask,
81569
81636
  resolveUnmatchedTaskOperation: () => resolveUnmatchedTaskOperation,
@@ -81587,6 +81654,7 @@ __export(tasks_exports, {
81587
81654
  taskLifecycleSchema: () => taskLifecycleSchema,
81588
81655
  taskMoney: () => taskMoney,
81589
81656
  taskMoneySnapshot: () => taskMoneySnapshot,
81657
+ taskNetworkName: () => taskNetworkName,
81590
81658
  taskPolicyAtomic: () => taskPolicyAtomic,
81591
81659
  taskPolicyForWallet: () => taskPolicyForWallet,
81592
81660
  taskPostResponseSchema: () => taskPostResponseSchema,
@@ -81625,6 +81693,7 @@ __export(tasks_exports, {
81625
81693
  taskV2VoteHostedError: () => taskV2VoteHostedError,
81626
81694
  taskV2VoteInputSchema: () => taskV2VoteInputSchema,
81627
81695
  taskViewFields: () => taskViewFields,
81696
+ tasksUnavailableError: () => tasksUnavailableError,
81628
81697
  threadTask: () => threadTask,
81629
81698
  validTaskBrief: () => validTaskBrief,
81630
81699
  verifiedV2Resolver: () => verifiedV2Resolver,
@@ -82982,9 +83051,11 @@ var taskV2OperationSchema = external_exports.object({
82982
83051
  step: taskV2StepSchema,
82983
83052
  expectedActor: address2,
82984
83053
  transactionHash: hash4.nullable(),
82985
- plan: taskV2PlanSchema
83054
+ // The API returns the plan only while the step is prepared and re-validated; once the
83055
+ // transaction is submitted or confirmed, and while a recovery scan runs, it sends null.
83056
+ plan: taskV2PlanSchema.nullable()
82986
83057
  }).refine(
82987
- (v) => v.plan.operationId === v.id && v.plan.step === v.step && v.plan.from === v.expectedActor,
83058
+ (v) => v.plan === null || v.plan.operationId === v.id && v.plan.step === v.step && v.plan.from === v.expectedActor,
82988
83059
  "Operation plan binding mismatch"
82989
83060
  ).refine(
82990
83061
  (v) => !["submitted", "confirmed"].includes(v.state) || v.transactionHash !== null,
@@ -83882,934 +83953,383 @@ function taskFundingIntentNonce(intent, expected) {
83882
83953
  return message.nonce.toLowerCase();
83883
83954
  }
83884
83955
 
83885
- // ../core/src/tasks/dispute-fee.ts
83886
- import { createHash as createHash3 } from "node:crypto";
83887
- function disputeFeeBaseUnits(amount4) {
83888
- if (amount4 < 0n) throw new Error("Dispute amount must be nonnegative.");
83889
- const fee = amount4 * 1000n / 10000n;
83890
- return fee < 20000000n ? 20000000n : fee > 500000000n ? 500000000n : fee;
83891
- }
83892
- function taskFeeReservationKey(milestoneId2, action) {
83893
- const bytes = createHash3("sha256").update(JSON.stringify([milestoneId2, action])).digest().subarray(0, 16);
83894
- bytes[6] = bytes[6] & 15 | 80;
83895
- bytes[8] = bytes[8] & 63 | 128;
83896
- const hex5 = bytes.toString("hex");
83897
- return `${hex5.slice(0, 8)}-${hex5.slice(8, 12)}-${hex5.slice(12, 16)}-${hex5.slice(16, 20)}-${hex5.slice(20)}`;
83898
- }
83899
-
83900
- // ../core/src/tasks/money.ts
83901
- function formatBaseUnitsUsd(baseUnits2) {
83902
- const [whole, fraction = ""] = formatUsdc(parseBaseUnits(baseUnits2)).split(".");
83903
- return `${whole}.${fraction.padEnd(2, "0")}`;
83904
- }
83905
- function parseUsdToBaseUnits(text) {
83906
- if (!/^\d+(?:\.\d{1,6})?$/u.test(text)) {
83907
- throw new Error(
83908
- "Task USD amount must be a non-negative decimal with at most six decimal places."
83909
- );
83910
- }
83911
- const [whole = "0", fraction = ""] = text.split(".");
83912
- return BigInt(whole) * 1000000n + BigInt(fraction.padEnd(6, "0"));
83913
- }
83914
- function parseFeeBp(deploymentOrReadiness) {
83915
- if (typeof deploymentOrReadiness !== "object" || deploymentOrReadiness === null || !("feeBp" in deploymentOrReadiness)) {
83916
- return null;
83917
- }
83918
- const feeBp = deploymentOrReadiness.feeBp;
83919
- if (feeBp === void 0 || feeBp === null) return null;
83920
- validateFeeBp(feeBp);
83921
- return feeBp;
83922
- }
83923
- function taskMoney(grossBaseUnits, feeBp) {
83924
- const atomic = parseBaseUnits(grossBaseUnits);
83925
- const gross = amount3(atomic);
83926
- if (feeBp === null) {
83927
- return { gross, fee: null, net: null, feeBp, line: `$${gross.usd} gross \xB7 fee unavailable` };
83928
- }
83929
- validateFeeBp(feeBp);
83930
- const feeAtomic = atomic * BigInt(feeBp) / 10000n;
83931
- const fee = amount3(feeAtomic);
83932
- const net = amount3(atomic - feeAtomic);
83933
- return {
83934
- gross,
83935
- fee,
83936
- net,
83937
- feeBp,
83938
- line: `$${gross.usd} gross \xB7 $${fee.usd} fee \xB7 $${net.usd} net`
83939
- };
83940
- }
83941
- function amount3(atomic) {
83942
- return { usd: formatBaseUnitsUsd(atomic), baseUnits: atomic.toString() };
83943
- }
83944
- function validateFeeBp(value) {
83945
- if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 1e4) {
83946
- throw new Error("Task fee basis points must be an integer from 0 to 10000.");
83947
- }
83948
- }
83949
- function parseBaseUnits(value) {
83950
- if (typeof value === "string" && !/^\d+$/u.test(value) || typeof value !== "bigint" && typeof value !== "string") {
83951
- throw new Error("Task base units must be a non-negative integer.");
83952
- }
83953
- const atomic = BigInt(value);
83954
- if (atomic < 0n) throw new Error("Task base units must be a non-negative integer.");
83955
- return atomic;
83956
- }
83957
- function taskPolicyAtomic(value) {
83958
- if (!Number.isFinite(value) || value < 0)
83959
- throw new Error("Task policy USD amounts must be finite and non-negative.");
83960
- const [mantissa = "0", exponent = "0"] = value.toString().split("e");
83961
- const [whole = "0", fraction = ""] = mantissa.split(".");
83962
- const digits = BigInt(whole + fraction);
83963
- const scale = 6 + Number(exponent) - fraction.length;
83964
- return scale >= 0 ? digits * 10n ** BigInt(scale) : digits / 10n ** BigInt(-scale);
83965
- }
83956
+ // ../core/src/tasks/operation-support.ts
83957
+ import { readFile as readFile18, stat as stat15 } from "node:fs/promises";
83958
+ import { basename as basename2, extname, join as join16 } from "node:path";
83966
83959
 
83967
- // ../core/src/tasks/plan-guard.ts
83968
- var TASKS_CHAIN_ABI = [
83960
+ // ../core/src/tasks/v2-abi.generated.ts
83961
+ var escrowFactoryV2Abi = [
83969
83962
  {
83970
- type: "function",
83971
- name: "createEscrow",
83972
- stateMutability: "nonpayable",
83963
+ type: "constructor",
83973
83964
  inputs: [
83974
- { name: "buyer", type: "address" },
83975
- { name: "token", type: "address" },
83976
- { name: "amount", type: "uint256" },
83977
- { name: "workDuration", type: "uint64" },
83978
- { name: "acceptanceWindow", type: "uint64" },
83979
- { name: "termsHash", type: "bytes32" },
83980
- { name: "salt", type: "bytes32" }
83965
+ { name: "initialOwner", type: "address", internalType: "address" },
83966
+ { name: "feeRouter", type: "address", internalType: "address" },
83967
+ { name: "disputeResolver", type: "address", internalType: "address" },
83968
+ { name: "outcomeRegistry", type: "address", internalType: "address" },
83969
+ { name: "usdc", type: "address", internalType: "address" },
83970
+ { name: "initialFeeBp", type: "uint16", internalType: "uint16" },
83971
+ { name: "maxFeeBp_", type: "uint16", internalType: "uint16" },
83972
+ { name: "maxEscrowAmount_", type: "uint256", internalType: "uint256" },
83973
+ { name: "cancelGrace", type: "uint64", internalType: "uint64" },
83974
+ { name: "lateWindow", type: "uint64", internalType: "uint64" },
83975
+ { name: "minWorkTime", type: "uint64", internalType: "uint64" }
83981
83976
  ],
83982
- outputs: [{ name: "escrow", type: "address" }]
83977
+ stateMutability: "nonpayable"
83983
83978
  },
83984
83979
  {
83985
83980
  type: "function",
83986
- name: "fundWithAuthorization",
83987
- stateMutability: "nonpayable",
83981
+ name: "bountyImplementation",
83982
+ inputs: [],
83983
+ outputs: [{ name: "", type: "address", internalType: "address" }],
83984
+ stateMutability: "view"
83985
+ },
83986
+ {
83987
+ type: "function",
83988
+ name: "createAndFundWithAuthorization",
83988
83989
  inputs: [
83989
- { name: "validAfter", type: "uint256" },
83990
- { name: "validBefore", type: "uint256" },
83991
- { name: "nonce", type: "bytes32" },
83992
- { name: "signature", type: "bytes" }
83990
+ {
83991
+ name: "terms_",
83992
+ type: "tuple",
83993
+ internalType: "struct IEscrowV2.Terms",
83994
+ components: [
83995
+ { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
83996
+ { name: "poster", type: "address", internalType: "address" },
83997
+ { name: "worker", type: "address", internalType: "address" },
83998
+ { name: "termsHash", type: "bytes32", internalType: "bytes32" },
83999
+ { name: "offerTtl", type: "uint64", internalType: "uint64" },
84000
+ { name: "reviewWindow", type: "uint64", internalType: "uint64" },
84001
+ { name: "choiceWindow", type: "uint64", internalType: "uint64" },
84002
+ { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
84003
+ { name: "objectionWindow", type: "uint64", internalType: "uint64" },
84004
+ { name: "workerBondBp", type: "uint16", internalType: "uint16" },
84005
+ { name: "feeBp", type: "uint16", internalType: "uint16" },
84006
+ { name: "winners", type: "uint8", internalType: "uint8" },
84007
+ { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
84008
+ ]
84009
+ },
84010
+ {
84011
+ name: "milestones",
84012
+ type: "tuple[]",
84013
+ internalType: "struct IEscrowV2.Milestone[]",
84014
+ components: [
84015
+ { name: "amount", type: "uint96", internalType: "uint96" },
84016
+ { name: "deadline", type: "uint64", internalType: "uint64" },
84017
+ { name: "status", type: "uint8", internalType: "uint8" },
84018
+ { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
84019
+ ]
84020
+ },
84021
+ { name: "salt", type: "bytes32", internalType: "bytes32" },
84022
+ { name: "from", type: "address", internalType: "address" },
84023
+ { name: "validAfter", type: "uint256", internalType: "uint256" },
84024
+ { name: "validBefore", type: "uint256", internalType: "uint256" },
84025
+ { name: "nonce", type: "bytes32", internalType: "bytes32" },
84026
+ { name: "signature", type: "bytes", internalType: "bytes" }
83993
84027
  ],
83994
- outputs: []
84028
+ outputs: [{ name: "escrow", type: "address", internalType: "address" }],
84029
+ stateMutability: "nonpayable"
83995
84030
  },
83996
84031
  {
83997
84032
  type: "function",
83998
- name: "approve",
83999
- stateMutability: "nonpayable",
84033
+ name: "createEscrow",
84000
84034
  inputs: [
84001
- { name: "spender", type: "address" },
84002
- { name: "amount", type: "uint256" }
84035
+ {
84036
+ name: "terms_",
84037
+ type: "tuple",
84038
+ internalType: "struct IEscrowV2.Terms",
84039
+ components: [
84040
+ { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
84041
+ { name: "poster", type: "address", internalType: "address" },
84042
+ { name: "worker", type: "address", internalType: "address" },
84043
+ { name: "termsHash", type: "bytes32", internalType: "bytes32" },
84044
+ { name: "offerTtl", type: "uint64", internalType: "uint64" },
84045
+ { name: "reviewWindow", type: "uint64", internalType: "uint64" },
84046
+ { name: "choiceWindow", type: "uint64", internalType: "uint64" },
84047
+ { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
84048
+ { name: "objectionWindow", type: "uint64", internalType: "uint64" },
84049
+ { name: "workerBondBp", type: "uint16", internalType: "uint16" },
84050
+ { name: "feeBp", type: "uint16", internalType: "uint16" },
84051
+ { name: "winners", type: "uint8", internalType: "uint8" },
84052
+ { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
84053
+ ]
84054
+ },
84055
+ {
84056
+ name: "milestones",
84057
+ type: "tuple[]",
84058
+ internalType: "struct IEscrowV2.Milestone[]",
84059
+ components: [
84060
+ { name: "amount", type: "uint96", internalType: "uint96" },
84061
+ { name: "deadline", type: "uint64", internalType: "uint64" },
84062
+ { name: "status", type: "uint8", internalType: "uint8" },
84063
+ { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
84064
+ ]
84065
+ },
84066
+ { name: "salt", type: "bytes32", internalType: "bytes32" }
84003
84067
  ],
84004
- outputs: [{ name: "ok", type: "bool" }]
84068
+ outputs: [{ name: "escrow", type: "address", internalType: "address" }],
84069
+ stateMutability: "nonpayable"
84005
84070
  },
84006
84071
  {
84007
84072
  type: "function",
84008
- name: "depositFunds",
84009
- stateMutability: "nonpayable",
84073
+ name: "feeBp",
84010
84074
  inputs: [],
84011
- outputs: []
84075
+ outputs: [{ name: "", type: "uint16", internalType: "uint16" }],
84076
+ stateMutability: "view"
84012
84077
  },
84013
84078
  {
84014
84079
  type: "function",
84015
- name: "submitDelivery",
84016
- stateMutability: "nonpayable",
84017
- inputs: [{ name: "manifestHash", type: "bytes32" }],
84018
- outputs: []
84080
+ name: "implementation",
84081
+ inputs: [],
84082
+ outputs: [{ name: "", type: "address", internalType: "address" }],
84083
+ stateMutability: "view"
84019
84084
  },
84020
84085
  {
84021
84086
  type: "function",
84022
- name: "releaseFunds",
84023
- stateMutability: "nonpayable",
84087
+ name: "isEscrow",
84088
+ inputs: [{ name: "escrow", type: "address", internalType: "address" }],
84089
+ outputs: [{ name: "registered", type: "bool", internalType: "bool" }],
84090
+ stateMutability: "view"
84091
+ },
84092
+ {
84093
+ type: "function",
84094
+ name: "maxEscrowAmount",
84024
84095
  inputs: [],
84025
- outputs: []
84096
+ outputs: [{ name: "", type: "uint256", internalType: "uint256" }],
84097
+ stateMutability: "view"
84026
84098
  },
84027
- { type: "function", name: "refundBuyer", stateMutability: "nonpayable", inputs: [], outputs: [] },
84028
84099
  {
84029
84100
  type: "function",
84030
- name: "raiseDispute",
84031
- stateMutability: "nonpayable",
84032
- inputs: [{ name: "evidenceHash", type: "bytes32" }],
84033
- outputs: []
84101
+ name: "maxFeeBp",
84102
+ inputs: [],
84103
+ outputs: [{ name: "", type: "uint16", internalType: "uint16" }],
84104
+ stateMutability: "view"
84034
84105
  },
84035
84106
  {
84036
84107
  type: "function",
84037
- name: "submitCounterEvidence",
84038
- stateMutability: "nonpayable",
84039
- inputs: [{ name: "evidenceHash", type: "bytes32" }],
84040
- outputs: []
84108
+ name: "owner",
84109
+ inputs: [],
84110
+ outputs: [{ name: "", type: "address", internalType: "address" }],
84111
+ stateMutability: "view"
84041
84112
  },
84113
+ { type: "function", name: "pause", inputs: [], outputs: [], stateMutability: "nonpayable" },
84042
84114
  {
84043
84115
  type: "function",
84044
- name: "resolveUnmatchedDispute",
84045
- stateMutability: "nonpayable",
84116
+ name: "paused",
84046
84117
  inputs: [],
84047
- outputs: []
84118
+ outputs: [{ name: "", type: "bool", internalType: "bool" }],
84119
+ stateMutability: "view"
84048
84120
  },
84049
84121
  {
84050
84122
  type: "function",
84051
- name: "timeoutRefund",
84052
- stateMutability: "nonpayable",
84123
+ name: "paymentToken",
84053
84124
  inputs: [],
84054
- outputs: []
84125
+ outputs: [{ name: "", type: "address", internalType: "address" }],
84126
+ stateMutability: "view"
84055
84127
  },
84056
- { type: "function", name: "finalize", stateMutability: "nonpayable", inputs: [], outputs: [] },
84057
84128
  {
84058
84129
  type: "function",
84059
- name: "disputeFee",
84060
- stateMutability: "view",
84130
+ name: "predictBountyEscrow",
84131
+ inputs: [
84132
+ {
84133
+ name: "terms_",
84134
+ type: "tuple",
84135
+ internalType: "struct IEscrowV2.Terms",
84136
+ components: [
84137
+ { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
84138
+ { name: "poster", type: "address", internalType: "address" },
84139
+ { name: "worker", type: "address", internalType: "address" },
84140
+ { name: "termsHash", type: "bytes32", internalType: "bytes32" },
84141
+ { name: "offerTtl", type: "uint64", internalType: "uint64" },
84142
+ { name: "reviewWindow", type: "uint64", internalType: "uint64" },
84143
+ { name: "choiceWindow", type: "uint64", internalType: "uint64" },
84144
+ { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
84145
+ { name: "objectionWindow", type: "uint64", internalType: "uint64" },
84146
+ { name: "workerBondBp", type: "uint16", internalType: "uint16" },
84147
+ { name: "feeBp", type: "uint16", internalType: "uint16" },
84148
+ { name: "winners", type: "uint8", internalType: "uint8" },
84149
+ { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
84150
+ ]
84151
+ },
84152
+ {
84153
+ name: "milestones",
84154
+ type: "tuple[]",
84155
+ internalType: "struct IEscrowV2.Milestone[]",
84156
+ components: [
84157
+ { name: "amount", type: "uint96", internalType: "uint96" },
84158
+ { name: "deadline", type: "uint64", internalType: "uint64" },
84159
+ { name: "status", type: "uint8", internalType: "uint8" },
84160
+ { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
84161
+ ]
84162
+ },
84163
+ { name: "salt", type: "bytes32", internalType: "bytes32" }
84164
+ ],
84165
+ outputs: [{ name: "", type: "address", internalType: "address" }],
84166
+ stateMutability: "view"
84167
+ },
84168
+ {
84169
+ type: "function",
84170
+ name: "predictEscrow",
84171
+ inputs: [
84172
+ {
84173
+ name: "terms_",
84174
+ type: "tuple",
84175
+ internalType: "struct IEscrowV2.Terms",
84176
+ components: [
84177
+ { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
84178
+ { name: "poster", type: "address", internalType: "address" },
84179
+ { name: "worker", type: "address", internalType: "address" },
84180
+ { name: "termsHash", type: "bytes32", internalType: "bytes32" },
84181
+ { name: "offerTtl", type: "uint64", internalType: "uint64" },
84182
+ { name: "reviewWindow", type: "uint64", internalType: "uint64" },
84183
+ { name: "choiceWindow", type: "uint64", internalType: "uint64" },
84184
+ { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
84185
+ { name: "objectionWindow", type: "uint64", internalType: "uint64" },
84186
+ { name: "workerBondBp", type: "uint16", internalType: "uint16" },
84187
+ { name: "feeBp", type: "uint16", internalType: "uint16" },
84188
+ { name: "winners", type: "uint8", internalType: "uint8" },
84189
+ { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
84190
+ ]
84191
+ },
84192
+ {
84193
+ name: "milestones",
84194
+ type: "tuple[]",
84195
+ internalType: "struct IEscrowV2.Milestone[]",
84196
+ components: [
84197
+ { name: "amount", type: "uint96", internalType: "uint96" },
84198
+ { name: "deadline", type: "uint64", internalType: "uint64" },
84199
+ { name: "status", type: "uint8", internalType: "uint8" },
84200
+ { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
84201
+ ]
84202
+ },
84203
+ { name: "salt", type: "bytes32", internalType: "bytes32" }
84204
+ ],
84205
+ outputs: [{ name: "", type: "address", internalType: "address" }],
84206
+ stateMutability: "view"
84207
+ },
84208
+ {
84209
+ type: "function",
84210
+ name: "renounceOwnership",
84061
84211
  inputs: [],
84062
- outputs: [{ name: "fee", type: "uint256" }]
84212
+ outputs: [],
84213
+ stateMutability: "nonpayable"
84063
84214
  },
84064
84215
  {
84065
84216
  type: "function",
84066
- name: "allowance",
84067
- stateMutability: "view",
84217
+ name: "setFeeBp",
84218
+ inputs: [{ name: "newFeeBp", type: "uint16", internalType: "uint16" }],
84219
+ outputs: [],
84220
+ stateMutability: "nonpayable"
84221
+ },
84222
+ {
84223
+ type: "function",
84224
+ name: "setMaxEscrowAmount",
84225
+ inputs: [{ name: "newAmount", type: "uint256", internalType: "uint256" }],
84226
+ outputs: [],
84227
+ stateMutability: "nonpayable"
84228
+ },
84229
+ {
84230
+ type: "function",
84231
+ name: "transferOwnership",
84232
+ inputs: [{ name: "newOwner", type: "address", internalType: "address" }],
84233
+ outputs: [],
84234
+ stateMutability: "nonpayable"
84235
+ },
84236
+ { type: "function", name: "unpause", inputs: [], outputs: [], stateMutability: "nonpayable" },
84237
+ {
84238
+ type: "event",
84239
+ name: "EscrowCreated",
84068
84240
  inputs: [
84069
- { name: "owner", type: "address" },
84070
- { name: "spender", type: "address" }
84241
+ { name: "escrow", type: "address", indexed: true, internalType: "address" },
84242
+ { name: "poster", type: "address", indexed: true, internalType: "address" },
84243
+ { name: "termsHash", type: "bytes32", indexed: true, internalType: "bytes32" },
84244
+ { name: "salt", type: "bytes32", indexed: false, internalType: "bytes32" },
84245
+ { name: "feeBp", type: "uint16", indexed: false, internalType: "uint16" }
84071
84246
  ],
84072
- outputs: [{ name: "amount", type: "uint256" }]
84073
- }
84074
- ];
84075
- var TASKS_READ_ABI = parseAbi([
84076
- "function paymentToken() view returns (address)",
84077
- "function isEscrow(address escrow) view returns (bool)",
84078
- "function name() view returns (string)",
84079
- "function version() view returns (string)",
84080
- "function buyer() view returns (address)",
84081
- "function seller() view returns (address)",
84082
- "function token() view returns (address)",
84083
- "function amount() view returns (uint256)",
84084
- "function termsHash() view returns (bytes32)",
84085
- "function state() view returns (uint8)",
84086
- "function offerDeadline() view returns (uint64)",
84087
- "function workDeadline() view returns (uint64)",
84088
- "function reviewDeadline() view returns (uint64)",
84089
- "function disputedAt() view returns (uint64)",
84090
- "function counterEvidenceDeadline() view returns (uint64)",
84091
- "function resolution() view returns (uint8)",
84092
- "function disputeFee() view returns (uint256)",
84093
- "function predictEscrow(address seller, bytes32 salt) view returns (address)"
84094
- ]);
84095
- function verifyPlan(operation, expectation) {
84096
- const fail2 = (message) => {
84097
- throw new TasksChainError(`Unsafe transaction plan: ${message}`, false);
84098
- };
84099
- const plan = operation.plan;
84100
- if (!plan) throw new TasksChainError("Unsafe transaction plan: missing plan", false);
84101
- if (plan.operationId !== operation.id || plan.step !== operation.step) fail2("operation mismatch");
84102
- if (!expectation.steps.includes(plan.step)) fail2("unexpected step");
84103
- if (!operation.expectedActor || getAddress(operation.expectedActor) !== getAddress(expectation.signer) || getAddress(plan.from) !== getAddress(expectation.signer))
84104
- fail2("unexpected signer");
84105
- if (plan.chainId !== expectation.deployment.chainId || plan.network !== expectation.deployment.network || plan.network !== `eip155:${plan.chainId}` || plan.value !== "0")
84106
- fail2("unexpected network or value");
84107
- if (expectation.milestone.network !== plan.network || expectation.milestone.asset.toLowerCase() !== `${plan.network}/erc20:${expectation.deployment.usdc}`.toLowerCase())
84108
- fail2("milestone asset mismatch");
84109
- const target = plan.step === "create-escrow" ? expectation.deployment.escrowContract : plan.step === "approve-usdc" ? expectation.deployment.usdc : expectation.milestone.escrowContract;
84110
- if (getAddress(plan.to) !== getAddress(target)) fail2("unexpected target");
84111
- const decoded = (() => {
84112
- try {
84113
- return decodeFunctionData({ abi: TASKS_CHAIN_ABI, data: plan.data });
84114
- } catch {
84115
- return fail2("invalid calldata");
84116
- }
84117
- })();
84118
- const expectedName = {
84119
- "create-escrow": "createEscrow",
84120
- "fund-with-authorization": "fundWithAuthorization",
84121
- "approve-usdc": "approve",
84122
- "deposit-funds": "depositFunds",
84123
- "submit-delivery": "submitDelivery",
84124
- "release-funds": "releaseFunds",
84125
- "refund-buyer": "refundBuyer",
84126
- "raise-dispute": "raiseDispute",
84127
- "submit-counter-evidence": "submitCounterEvidence",
84128
- "resolve-unmatched-dispute": "resolveUnmatchedDispute",
84129
- "timeout-refund": "timeoutRefund",
84130
- finalize: "finalize"
84131
- };
84132
- if (decoded.functionName !== expectedName[plan.step]) fail2("unexpected selector");
84133
- const args = [...decoded.args ?? []];
84134
- const eq = (a, b) => typeof a === "string" && typeof b === "string" ? a.toLowerCase() === b.toLowerCase() : a === b;
84135
- const requireArgs = (values) => {
84136
- if (args.length !== values.length || args.some((v, i2) => !eq(v, values[i2])))
84137
- fail2("unexpected arguments");
84138
- };
84139
- if (plan.step === "create-escrow") {
84140
- if (!expectation.seller || getAddress(expectation.signer) !== getAddress(expectation.seller))
84141
- fail2("createEscrow requires the locally bound seller");
84142
- const workDuration = expectation.workDurationSeconds ?? expectation.milestone.terms.workDurationSeconds ?? getTrustedTasksDurations(expectation.deployment.chainId).workDurationSeconds;
84143
- if (workDuration === void 0) fail2("missing trusted work duration");
84144
- requireArgs([
84145
- expectation.buyer,
84146
- expectation.deployment.usdc,
84147
- BigInt(expectation.milestone.amountBaseUnits),
84148
- BigInt(workDuration),
84149
- BigInt(
84150
- expectation.reviewWindowSeconds ?? expectation.milestone.terms.acceptanceWindowSeconds
84151
- ),
84152
- expectation.milestone.termsHash,
84153
- keccak256(stringToHex(expectation.milestone.id))
84154
- ]);
84155
- } else if (plan.step === "fund-with-authorization") {
84156
- const a = expectation.authorization;
84157
- if (!a)
84158
- throw new TasksChainError("Unsafe transaction plan: missing local authorization", false);
84159
- requireArgs([BigInt(a.validAfter), BigInt(a.validBefore), a.nonce, a.signature]);
84160
- } else if (plan.step === "approve-usdc") {
84161
- if (expectation.approveAmount === void 0) fail2("missing verified approval amount");
84162
- requireArgs([expectation.milestone.escrowContract, expectation.approveAmount]);
84163
- } else if (plan.step === "submit-delivery") {
84164
- if (!expectation.manifestHash) fail2("missing manifest hash");
84165
- requireArgs([expectation.manifestHash]);
84166
- } else if (plan.step === "raise-dispute" || plan.step === "submit-counter-evidence") {
84167
- if (!expectation.evidenceHash) fail2("missing evidence hash");
84168
- requireArgs([expectation.evidenceHash]);
84169
- } else requireArgs([]);
84170
- }
84171
-
84172
- // ../core/src/tasks/chain-verification.ts
84173
- var TasksPartiesNotBoundError = class extends TasksValidationError {
84174
- constructor() {
84175
- super(
84176
- "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."
84177
- );
84178
- this.name = "TasksPartiesNotBoundError";
84179
- }
84180
- };
84181
- async function verifyDeployment(ready, rpc, overrides) {
84182
- const factory = getTrustedTasksFactory(ready.chainId, overrides);
84183
- if (!factory)
84184
- throw new TasksChainError(
84185
- `No trusted Tasks escrow factory is configured for chain ${ready.chainId}. Set VAPI_TASKS_ESCROW_FACTORY_${ready.chainId}.`,
84186
- false,
84187
- { authorizationExposed: false }
84188
- );
84189
- if (!isAddressEqual(factory, ready.escrowContract))
84190
- throw new TasksValidationError(
84191
- "The Tasks readiness factory does not match the trusted factory."
84192
- );
84193
- if (await rpc.getChainId() !== ready.chainId)
84194
- throw new TasksValidationError("The RPC chain ID does not match the task deployment.");
84195
- const token = await rpc.readContract({
84196
- address: factory,
84197
- abi: TASKS_READ_ABI,
84198
- functionName: "paymentToken"
84199
- });
84200
- if (!isAddressEqual(token, ready.usdc))
84201
- throw new TasksValidationError(
84202
- "The Tasks readiness token does not match the trusted factory payment token."
84203
- );
84204
- const [name, version5] = await Promise.all([
84205
- rpc.readContract({ address: token, abi: TASKS_READ_ABI, functionName: "name" }),
84206
- rpc.readContract({ address: token, abi: TASKS_READ_ABI, functionName: "version" })
84207
- ]);
84208
- const domain2 = { name, version: version5, chainId: ready.chainId, verifyingContract: getAddress(token) };
84209
- if (ready.eip3009Domain && (ready.eip3009Domain.name !== name || ready.eip3009Domain.version !== version5 || ready.eip3009Domain.chainId !== ready.chainId || !isAddressEqual(ready.eip3009Domain.verifyingContract, token)))
84210
- throw new TasksValidationError(
84211
- "The funding authorization domain does not match the onchain token domain."
84212
- );
84213
- return {
84214
- ...ready,
84215
- escrowContract: getAddress(factory),
84216
- usdc: getAddress(token),
84217
- eip3009Domain: domain2
84218
- };
84219
- }
84220
- async function verifyScope(client, signer, selected, ready, verb, steps, options = {}) {
84221
- const { scopes } = await client.getScopes(selected.workOrderId);
84222
- const matches = scopes.filter(
84223
- (scope2) => scope2.state === "accepted" && scope2.milestoneId === selected.id
84224
- );
84225
- if (matches.length !== 1)
84226
- throw new TasksValidationError("The task milestone requires one accepted signed scope.");
84227
- const scope = matches[0];
84228
- const payload = scope.signingPayload;
84229
- const frozen = freezeScopeTerms(scope.structuredTerms, scope.brief);
84230
- 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)
84231
- throw new TasksValidationError(
84232
- "The accepted task scope does not match its locally verified terms hash and milestone."
84233
- );
84234
- if (!scope.counterpartyAddress || !scope.counterpartySignature || isAddressEqual(scope.proposerAddress, scope.counterpartyAddress) || !(isAddressEqual(signer, scope.proposerAddress) || isAddressEqual(signer, scope.counterpartyAddress)))
84235
- throw new TasksValidationError(
84236
- "The local signer is not one of the two accepted scope parties."
84237
- );
84238
- const message = canonicalJson(payload);
84239
- const signatures = await Promise.all([
84240
- verifyMessage({
84241
- address: scope.proposerAddress,
84242
- message,
84243
- signature: scope.proposerSignature
84244
- }),
84245
- verifyMessage({
84246
- address: scope.counterpartyAddress,
84247
- message,
84248
- signature: scope.counterpartySignature
84249
- })
84250
- ]);
84251
- if (signatures.some((valid) => !valid))
84252
- throw new TasksValidationError("Both accepted task scope signatures must verify.");
84253
- const terms = frozen.structured;
84254
- 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)
84255
- throw new TasksValidationError(
84256
- "The signed task scope asset, factory or amount does not match the deployment and milestone."
84257
- );
84258
- const identity = {
84259
- orderId: selected.workOrderId,
84260
- trancheOrdinal: selected.ordinal,
84261
- scopeVersion: scope.version,
84262
- termsHash: frozen.termsHash,
84263
- self: getAddress(signer)
84264
- };
84265
- const binding = await options.bindings?.get(identity);
84266
- if (!binding) throw new TasksPartiesNotBoundError();
84267
- if (options.counterparty && !isAddressEqual(binding.counterparty, options.counterparty))
84268
- throw new TasksValidationError(
84269
- "The confirmed counterparty differs from the locally bound parties."
84270
- );
84271
- 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(
84272
- (address10) => isAddressEqual(address10, binding.self) || isAddressEqual(address10, binding.counterparty)
84273
- ))
84274
- throw new TasksValidationError(
84275
- "The accepted scope parties do not match the locally bound parties."
84276
- );
84277
- const buyer = getAddress(binding.role === "client" ? binding.self : binding.counterparty);
84278
- const seller = getAddress(binding.role === "provider" ? binding.self : binding.counterparty);
84279
- if (verb === "createEscrow" && !isAddressEqual(signer, seller))
84280
- throw new TasksValidationError("Task createEscrow requires the locally bound seller's wallet.");
84281
- const workDurationSeconds = terms.workDurationSeconds ?? getTrustedTasksDurations(ready.chainId, options.trustedDurations).workDurationSeconds;
84282
- if (workDurationSeconds === void 0)
84283
- throw new TasksValidationError(
84284
- "The signed task scope has no work duration and no trusted default is configured."
84285
- );
84286
- return {
84287
- signer,
84288
- buyer,
84289
- seller,
84290
- parties: [buyer, seller],
84291
- workDurationSeconds,
84292
- ...verb === "fund" ? { approveAmount: BigInt(terms.budget.amountBaseUnits) } : {},
84293
- reviewWindowSeconds: terms.acceptanceWindowSeconds,
84294
- nowSeconds: BigInt(Math.floor((options.now ?? (() => /* @__PURE__ */ new Date()))().getTime() / 1e3)),
84295
- verb,
84296
- deployment: ready,
84297
- milestone: {
84298
- ...selected,
84299
- terms,
84300
- termsHash: frozen.termsHash,
84301
- amountBaseUnits: terms.budget.amountBaseUnits
84302
- },
84303
- steps
84304
- };
84305
- }
84306
- async function verifyClone(rpc, expected, checkState) {
84307
- if (expected.verb === "createEscrow") return;
84308
- const clone2 = expected.milestone.escrowContract;
84309
- const registered = await rpc.readContract({
84310
- address: expected.deployment.escrowContract,
84311
- abi: TASKS_READ_ABI,
84312
- functionName: "isEscrow",
84313
- args: [clone2]
84314
- });
84315
- if (!registered)
84316
- throw new TasksValidationError(
84317
- "The task escrow clone is not registered by the trusted factory."
84318
- );
84319
- const predicted = await rpc.readContract({
84320
- address: expected.deployment.escrowContract,
84321
- abi: TASKS_READ_ABI,
84322
- functionName: "predictEscrow",
84323
- args: [expected.seller, keccak256(stringToHex(expected.milestone.id))]
84324
- });
84325
- if (!isAddressEqual(predicted, clone2))
84326
- throw new TasksValidationError(
84327
- "The escrow clone does not match the signed milestone salt and bound seller."
84328
- );
84329
- const read = (functionName) => rpc.readContract({ address: clone2, abi: TASKS_READ_ABI, functionName });
84330
- const [
84331
- buyer,
84332
- seller,
84333
- token,
84334
- amount4,
84335
- termsHash,
84336
- state,
84337
- resolution,
84338
- offerDeadline,
84339
- workDeadline,
84340
- reviewDeadline,
84341
- disputedAt,
84342
- counterEvidenceDeadline,
84343
- slot0,
84344
- slot6,
84345
- slot7
84346
- ] = await Promise.all([
84347
- read("buyer"),
84348
- read("seller"),
84349
- read("token"),
84350
- read("amount"),
84351
- read("termsHash"),
84352
- read("state"),
84353
- read("resolution"),
84354
- read("offerDeadline"),
84355
- read("workDeadline"),
84356
- read("reviewDeadline"),
84357
- read("disputedAt"),
84358
- read("counterEvidenceDeadline"),
84359
- rpc.getStorageAt({ address: clone2, slot: "0x0" }),
84360
- rpc.getStorageAt({ address: clone2, slot: "0x6" }),
84361
- rpc.getStorageAt({ address: clone2, slot: "0x7" })
84362
- ]);
84363
- 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())
84364
- throw new TasksValidationError(
84365
- "The onchain escrow parties, token, amount or terms hash do not match the signed scope."
84366
- );
84367
- const s0 = storageWord(slot0);
84368
- const s6 = storageWord(slot6);
84369
- const s7 = storageWord(slot7);
84370
- 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)
84371
- throw new TasksValidationError("unsupported escrow layout");
84372
- if (field(s7, 8, 8) !== BigInt(expected.workDurationSeconds) || field(s7, 16, 8) !== BigInt(expected.reviewWindowSeconds))
84373
- throw new TasksValidationError(
84374
- "The onchain escrow durations do not match the signed terms and trusted defaults."
84375
- );
84376
- const actor = expected.verb === "fund" || expected.verb === "release" ? buyer : expected.verb === "deliver" || expected.verb === "refund" ? seller : expected.signer;
84377
- if (!isAddressEqual(actor, expected.signer))
84378
- throw new TasksValidationError(
84379
- `Task ${expected.verb} requires the onchain escrow party's local wallet.`
84380
- );
84381
- const states = {
84382
- fund: [1],
84383
- deliver: [2],
84384
- release: [3],
84385
- refund: [2, 3],
84386
- dispute: [2, 3],
84387
- "counter-evidence": [4],
84388
- "resolve-unmatched": [4]
84389
- };
84390
- if (checkState && !states[expected.verb]?.includes(state))
84391
- throw new TasksValidationError(
84392
- `The onchain escrow state is not eligible for task ${expected.verb}.`
84393
- );
84394
- if (["dispute", "counter-evidence"].includes(expected.verb)) {
84395
- const fee = disputeFeeBaseUnits(amount4);
84396
- if (await read("disputeFee") !== fee)
84397
- throw new TasksValidationError(
84398
- "The onchain dispute fee does not match the verified amount fee rule."
84399
- );
84400
- expected.disputeFee = fee;
84401
- expected.approveAmount = fee;
84402
- }
84403
- if (checkState && ["counter-evidence", "resolve-unmatched"].includes(expected.verb)) {
84404
- const slot8 = storageWord(await rpc.getStorageAt({ address: clone2, slot: "0x8" }));
84405
- const opener = storageAddress(slot8, 0);
84406
- const submitted = field(slot8, 20, 1);
84407
- if (!isAddressEqual(opener, buyer) && !isAddressEqual(opener, seller) || submitted > 1n || field(slot8, 21, 11) !== 0n)
84408
- throw new TasksValidationError("unsupported escrow layout");
84409
- const now = expected.nowSeconds;
84410
- if (now === void 0)
84411
- throw new TasksValidationError("A trusted clock is required for dispute eligibility.");
84412
- if (submitted === 1n)
84413
- throw new TasksValidationError(
84414
- "Counter-evidence has already been submitted for this dispute."
84415
- );
84416
- if (expected.verb === "counter-evidence") {
84417
- if (isAddressEqual(opener, expected.signer))
84418
- throw new TasksValidationError("Only the non-opener party can submit counter-evidence.");
84419
- if (now >= counterEvidenceDeadline)
84420
- throw new TasksValidationError("The counter-evidence deadline has passed.");
84421
- } else if (now <= counterEvidenceDeadline)
84422
- throw new TasksValidationError(
84423
- "The counter-evidence deadline has not passed; unmatched resolution is unavailable."
84424
- );
84425
- }
84426
- expected.offerDeadline = offerDeadline;
84427
- }
84428
- function storageWord(value) {
84429
- if (!value || !/^0x[0-9a-fA-F]{64}$/.test(value))
84430
- throw new TasksValidationError("unsupported escrow layout");
84431
- return BigInt(value);
84432
- }
84433
- function field(word, offset, bytes) {
84434
- return word >> BigInt(offset * 8) & (1n << BigInt(bytes * 8)) - 1n;
84435
- }
84436
- function storageAddress(word, offset) {
84437
- return getAddress(`0x${field(word, offset, 20).toString(16).padStart(40, "0")}`);
84438
- }
84439
-
84440
- // ../core/src/tasks/v2-abi.generated.ts
84441
- var escrowFactoryV2Abi = [
84442
- {
84443
- type: "constructor",
84444
- inputs: [
84445
- { name: "initialOwner", type: "address", internalType: "address" },
84446
- { name: "feeRouter", type: "address", internalType: "address" },
84447
- { name: "disputeResolver", type: "address", internalType: "address" },
84448
- { name: "outcomeRegistry", type: "address", internalType: "address" },
84449
- { name: "usdc", type: "address", internalType: "address" },
84450
- { name: "initialFeeBp", type: "uint16", internalType: "uint16" },
84451
- { name: "maxFeeBp_", type: "uint16", internalType: "uint16" },
84452
- { name: "maxEscrowAmount_", type: "uint256", internalType: "uint256" },
84453
- { name: "cancelGrace", type: "uint64", internalType: "uint64" },
84454
- { name: "lateWindow", type: "uint64", internalType: "uint64" },
84455
- { name: "minWorkTime", type: "uint64", internalType: "uint64" }
84456
- ],
84457
- stateMutability: "nonpayable"
84458
- },
84459
- {
84460
- type: "function",
84461
- name: "bountyImplementation",
84462
- inputs: [],
84463
- outputs: [{ name: "", type: "address", internalType: "address" }],
84464
- stateMutability: "view"
84465
- },
84466
- {
84467
- type: "function",
84468
- name: "createAndFundWithAuthorization",
84469
- inputs: [
84470
- {
84471
- name: "terms_",
84472
- type: "tuple",
84473
- internalType: "struct IEscrowV2.Terms",
84474
- components: [
84475
- { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
84476
- { name: "poster", type: "address", internalType: "address" },
84477
- { name: "worker", type: "address", internalType: "address" },
84478
- { name: "termsHash", type: "bytes32", internalType: "bytes32" },
84479
- { name: "offerTtl", type: "uint64", internalType: "uint64" },
84480
- { name: "reviewWindow", type: "uint64", internalType: "uint64" },
84481
- { name: "choiceWindow", type: "uint64", internalType: "uint64" },
84482
- { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
84483
- { name: "objectionWindow", type: "uint64", internalType: "uint64" },
84484
- { name: "workerBondBp", type: "uint16", internalType: "uint16" },
84485
- { name: "feeBp", type: "uint16", internalType: "uint16" },
84486
- { name: "winners", type: "uint8", internalType: "uint8" },
84487
- { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
84488
- ]
84489
- },
84490
- {
84491
- name: "milestones",
84492
- type: "tuple[]",
84493
- internalType: "struct IEscrowV2.Milestone[]",
84494
- components: [
84495
- { name: "amount", type: "uint96", internalType: "uint96" },
84496
- { name: "deadline", type: "uint64", internalType: "uint64" },
84497
- { name: "status", type: "uint8", internalType: "uint8" },
84498
- { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
84499
- ]
84500
- },
84501
- { name: "salt", type: "bytes32", internalType: "bytes32" },
84502
- { name: "from", type: "address", internalType: "address" },
84503
- { name: "validAfter", type: "uint256", internalType: "uint256" },
84504
- { name: "validBefore", type: "uint256", internalType: "uint256" },
84505
- { name: "nonce", type: "bytes32", internalType: "bytes32" },
84506
- { name: "signature", type: "bytes", internalType: "bytes" }
84507
- ],
84508
- outputs: [{ name: "escrow", type: "address", internalType: "address" }],
84509
- stateMutability: "nonpayable"
84510
- },
84511
- {
84512
- type: "function",
84513
- name: "createEscrow",
84514
- inputs: [
84515
- {
84516
- name: "terms_",
84517
- type: "tuple",
84518
- internalType: "struct IEscrowV2.Terms",
84519
- components: [
84520
- { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
84521
- { name: "poster", type: "address", internalType: "address" },
84522
- { name: "worker", type: "address", internalType: "address" },
84523
- { name: "termsHash", type: "bytes32", internalType: "bytes32" },
84524
- { name: "offerTtl", type: "uint64", internalType: "uint64" },
84525
- { name: "reviewWindow", type: "uint64", internalType: "uint64" },
84526
- { name: "choiceWindow", type: "uint64", internalType: "uint64" },
84527
- { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
84528
- { name: "objectionWindow", type: "uint64", internalType: "uint64" },
84529
- { name: "workerBondBp", type: "uint16", internalType: "uint16" },
84530
- { name: "feeBp", type: "uint16", internalType: "uint16" },
84531
- { name: "winners", type: "uint8", internalType: "uint8" },
84532
- { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
84533
- ]
84534
- },
84535
- {
84536
- name: "milestones",
84537
- type: "tuple[]",
84538
- internalType: "struct IEscrowV2.Milestone[]",
84539
- components: [
84540
- { name: "amount", type: "uint96", internalType: "uint96" },
84541
- { name: "deadline", type: "uint64", internalType: "uint64" },
84542
- { name: "status", type: "uint8", internalType: "uint8" },
84543
- { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
84544
- ]
84545
- },
84546
- { name: "salt", type: "bytes32", internalType: "bytes32" }
84547
- ],
84548
- outputs: [{ name: "escrow", type: "address", internalType: "address" }],
84549
- stateMutability: "nonpayable"
84550
- },
84551
- {
84552
- type: "function",
84553
- name: "feeBp",
84554
- inputs: [],
84555
- outputs: [{ name: "", type: "uint16", internalType: "uint16" }],
84556
- stateMutability: "view"
84557
- },
84558
- {
84559
- type: "function",
84560
- name: "implementation",
84561
- inputs: [],
84562
- outputs: [{ name: "", type: "address", internalType: "address" }],
84563
- stateMutability: "view"
84564
- },
84565
- {
84566
- type: "function",
84567
- name: "isEscrow",
84568
- inputs: [{ name: "escrow", type: "address", internalType: "address" }],
84569
- outputs: [{ name: "registered", type: "bool", internalType: "bool" }],
84570
- stateMutability: "view"
84571
- },
84572
- {
84573
- type: "function",
84574
- name: "maxEscrowAmount",
84575
- inputs: [],
84576
- outputs: [{ name: "", type: "uint256", internalType: "uint256" }],
84577
- stateMutability: "view"
84578
- },
84579
- {
84580
- type: "function",
84581
- name: "maxFeeBp",
84582
- inputs: [],
84583
- outputs: [{ name: "", type: "uint16", internalType: "uint16" }],
84584
- stateMutability: "view"
84585
- },
84586
- {
84587
- type: "function",
84588
- name: "owner",
84589
- inputs: [],
84590
- outputs: [{ name: "", type: "address", internalType: "address" }],
84591
- stateMutability: "view"
84592
- },
84593
- { type: "function", name: "pause", inputs: [], outputs: [], stateMutability: "nonpayable" },
84594
- {
84595
- type: "function",
84596
- name: "paused",
84597
- inputs: [],
84598
- outputs: [{ name: "", type: "bool", internalType: "bool" }],
84599
- stateMutability: "view"
84600
- },
84601
- {
84602
- type: "function",
84603
- name: "paymentToken",
84604
- inputs: [],
84605
- outputs: [{ name: "", type: "address", internalType: "address" }],
84606
- stateMutability: "view"
84607
- },
84608
- {
84609
- type: "function",
84610
- name: "predictBountyEscrow",
84611
- inputs: [
84612
- {
84613
- name: "terms_",
84614
- type: "tuple",
84615
- internalType: "struct IEscrowV2.Terms",
84616
- components: [
84617
- { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
84618
- { name: "poster", type: "address", internalType: "address" },
84619
- { name: "worker", type: "address", internalType: "address" },
84620
- { name: "termsHash", type: "bytes32", internalType: "bytes32" },
84621
- { name: "offerTtl", type: "uint64", internalType: "uint64" },
84622
- { name: "reviewWindow", type: "uint64", internalType: "uint64" },
84623
- { name: "choiceWindow", type: "uint64", internalType: "uint64" },
84624
- { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
84625
- { name: "objectionWindow", type: "uint64", internalType: "uint64" },
84626
- { name: "workerBondBp", type: "uint16", internalType: "uint16" },
84627
- { name: "feeBp", type: "uint16", internalType: "uint16" },
84628
- { name: "winners", type: "uint8", internalType: "uint8" },
84629
- { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
84630
- ]
84631
- },
84632
- {
84633
- name: "milestones",
84634
- type: "tuple[]",
84635
- internalType: "struct IEscrowV2.Milestone[]",
84636
- components: [
84637
- { name: "amount", type: "uint96", internalType: "uint96" },
84638
- { name: "deadline", type: "uint64", internalType: "uint64" },
84639
- { name: "status", type: "uint8", internalType: "uint8" },
84640
- { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
84641
- ]
84642
- },
84643
- { name: "salt", type: "bytes32", internalType: "bytes32" }
84644
- ],
84645
- outputs: [{ name: "", type: "address", internalType: "address" }],
84646
- stateMutability: "view"
84647
- },
84648
- {
84649
- type: "function",
84650
- name: "predictEscrow",
84651
- inputs: [
84652
- {
84653
- name: "terms_",
84654
- type: "tuple",
84655
- internalType: "struct IEscrowV2.Terms",
84656
- components: [
84657
- { name: "shape", type: "uint8", internalType: "enum IEscrowV2.Shape" },
84658
- { name: "poster", type: "address", internalType: "address" },
84659
- { name: "worker", type: "address", internalType: "address" },
84660
- { name: "termsHash", type: "bytes32", internalType: "bytes32" },
84661
- { name: "offerTtl", type: "uint64", internalType: "uint64" },
84662
- { name: "reviewWindow", type: "uint64", internalType: "uint64" },
84663
- { name: "choiceWindow", type: "uint64", internalType: "uint64" },
84664
- { name: "bountyDeadline", type: "uint64", internalType: "uint64" },
84665
- { name: "objectionWindow", type: "uint64", internalType: "uint64" },
84666
- { name: "workerBondBp", type: "uint16", internalType: "uint16" },
84667
- { name: "feeBp", type: "uint16", internalType: "uint16" },
84668
- { name: "winners", type: "uint8", internalType: "uint8" },
84669
- { name: "rewardPerWinner", type: "uint96", internalType: "uint96" }
84670
- ]
84671
- },
84672
- {
84673
- name: "milestones",
84674
- type: "tuple[]",
84675
- internalType: "struct IEscrowV2.Milestone[]",
84676
- components: [
84677
- { name: "amount", type: "uint96", internalType: "uint96" },
84678
- { name: "deadline", type: "uint64", internalType: "uint64" },
84679
- { name: "status", type: "uint8", internalType: "uint8" },
84680
- { name: "deliveryHash", type: "bytes32", internalType: "bytes32" }
84681
- ]
84682
- },
84683
- { name: "salt", type: "bytes32", internalType: "bytes32" }
84684
- ],
84685
- outputs: [{ name: "", type: "address", internalType: "address" }],
84686
- stateMutability: "view"
84687
- },
84688
- {
84689
- type: "function",
84690
- name: "renounceOwnership",
84691
- inputs: [],
84692
- outputs: [],
84693
- stateMutability: "nonpayable"
84694
- },
84695
- {
84696
- type: "function",
84697
- name: "setFeeBp",
84698
- inputs: [{ name: "newFeeBp", type: "uint16", internalType: "uint16" }],
84699
- outputs: [],
84700
- stateMutability: "nonpayable"
84701
- },
84702
- {
84703
- type: "function",
84704
- name: "setMaxEscrowAmount",
84705
- inputs: [{ name: "newAmount", type: "uint256", internalType: "uint256" }],
84706
- outputs: [],
84707
- stateMutability: "nonpayable"
84708
- },
84709
- {
84710
- type: "function",
84711
- name: "transferOwnership",
84712
- inputs: [{ name: "newOwner", type: "address", internalType: "address" }],
84713
- outputs: [],
84714
- stateMutability: "nonpayable"
84715
- },
84716
- { type: "function", name: "unpause", inputs: [], outputs: [], stateMutability: "nonpayable" },
84717
- {
84718
- type: "event",
84719
- name: "EscrowCreated",
84720
- inputs: [
84721
- { name: "escrow", type: "address", indexed: true, internalType: "address" },
84722
- { name: "poster", type: "address", indexed: true, internalType: "address" },
84723
- { name: "termsHash", type: "bytes32", indexed: true, internalType: "bytes32" },
84724
- { name: "salt", type: "bytes32", indexed: false, internalType: "bytes32" },
84725
- { name: "feeBp", type: "uint16", indexed: false, internalType: "uint16" }
84726
- ],
84727
- anonymous: false
84728
- },
84729
- {
84730
- type: "event",
84731
- name: "FeeBpSet",
84732
- inputs: [
84733
- { name: "previousFeeBp", type: "uint16", indexed: false, internalType: "uint16" },
84734
- { name: "newFeeBp", type: "uint16", indexed: false, internalType: "uint16" }
84735
- ],
84736
- anonymous: false
84737
- },
84738
- {
84739
- type: "event",
84740
- name: "MaxEscrowAmountSet",
84741
- inputs: [
84742
- { name: "previousAmount", type: "uint256", indexed: false, internalType: "uint256" },
84743
- { name: "newAmount", type: "uint256", indexed: false, internalType: "uint256" }
84744
- ],
84745
- anonymous: false
84746
- },
84747
- {
84748
- type: "event",
84749
- name: "OwnershipTransferred",
84750
- inputs: [
84751
- { name: "previousOwner", type: "address", indexed: true, internalType: "address" },
84752
- { name: "newOwner", type: "address", indexed: true, internalType: "address" }
84753
- ],
84754
- anonymous: false
84755
- },
84756
- {
84757
- type: "event",
84758
- name: "PauseSet",
84759
- inputs: [{ name: "paused", type: "bool", indexed: false, internalType: "bool" }],
84760
- anonymous: false
84761
- },
84762
- {
84763
- type: "error",
84764
- name: "EscrowAlreadyExists",
84765
- inputs: [{ name: "escrow", type: "address", internalType: "address" }]
84766
- },
84767
- {
84768
- type: "error",
84769
- name: "EscrowAmountAboveCap",
84770
- inputs: [
84771
- { name: "amount", type: "uint256", internalType: "uint256" },
84772
- { name: "cap", type: "uint256", internalType: "uint256" }
84773
- ]
84774
- },
84775
- { type: "error", name: "FactoryPaused", inputs: [] },
84776
- { type: "error", name: "FailedDeployment", inputs: [] },
84777
- {
84778
- type: "error",
84779
- name: "InsufficientBalance",
84780
- inputs: [
84781
- { name: "balance", type: "uint256", internalType: "uint256" },
84782
- { name: "needed", type: "uint256", internalType: "uint256" }
84783
- ]
84784
- },
84785
- { type: "error", name: "InvalidAddress", inputs: [] },
84786
- { type: "error", name: "InvalidFee", inputs: [] },
84787
- { type: "error", name: "InvalidToken", inputs: [] },
84788
- {
84789
- type: "error",
84790
- name: "OwnableInvalidOwner",
84791
- inputs: [{ name: "owner", type: "address", internalType: "address" }]
84792
- },
84793
- {
84794
- type: "error",
84795
- name: "OwnableUnauthorizedAccount",
84796
- inputs: [{ name: "account", type: "address", internalType: "address" }]
84797
- },
84798
- {
84799
- type: "error",
84800
- name: "ShapeMismatch",
84801
- inputs: [
84802
- { name: "expected", type: "uint8", internalType: "enum IEscrowV2.Shape" },
84803
- { name: "supplied", type: "uint8", internalType: "enum IEscrowV2.Shape" }
84804
- ]
84805
- },
84806
- {
84807
- type: "error",
84808
- name: "TermsFeeMismatch",
84809
- inputs: [
84810
- { name: "expected", type: "uint16", internalType: "uint16" },
84811
- { name: "supplied", type: "uint16", internalType: "uint16" }
84812
- ]
84247
+ anonymous: false
84248
+ },
84249
+ {
84250
+ type: "event",
84251
+ name: "FeeBpSet",
84252
+ inputs: [
84253
+ { name: "previousFeeBp", type: "uint16", indexed: false, internalType: "uint16" },
84254
+ { name: "newFeeBp", type: "uint16", indexed: false, internalType: "uint16" }
84255
+ ],
84256
+ anonymous: false
84257
+ },
84258
+ {
84259
+ type: "event",
84260
+ name: "MaxEscrowAmountSet",
84261
+ inputs: [
84262
+ { name: "previousAmount", type: "uint256", indexed: false, internalType: "uint256" },
84263
+ { name: "newAmount", type: "uint256", indexed: false, internalType: "uint256" }
84264
+ ],
84265
+ anonymous: false
84266
+ },
84267
+ {
84268
+ type: "event",
84269
+ name: "OwnershipTransferred",
84270
+ inputs: [
84271
+ { name: "previousOwner", type: "address", indexed: true, internalType: "address" },
84272
+ { name: "newOwner", type: "address", indexed: true, internalType: "address" }
84273
+ ],
84274
+ anonymous: false
84275
+ },
84276
+ {
84277
+ type: "event",
84278
+ name: "PauseSet",
84279
+ inputs: [{ name: "paused", type: "bool", indexed: false, internalType: "bool" }],
84280
+ anonymous: false
84281
+ },
84282
+ {
84283
+ type: "error",
84284
+ name: "EscrowAlreadyExists",
84285
+ inputs: [{ name: "escrow", type: "address", internalType: "address" }]
84286
+ },
84287
+ {
84288
+ type: "error",
84289
+ name: "EscrowAmountAboveCap",
84290
+ inputs: [
84291
+ { name: "amount", type: "uint256", internalType: "uint256" },
84292
+ { name: "cap", type: "uint256", internalType: "uint256" }
84293
+ ]
84294
+ },
84295
+ { type: "error", name: "FactoryPaused", inputs: [] },
84296
+ { type: "error", name: "FailedDeployment", inputs: [] },
84297
+ {
84298
+ type: "error",
84299
+ name: "InsufficientBalance",
84300
+ inputs: [
84301
+ { name: "balance", type: "uint256", internalType: "uint256" },
84302
+ { name: "needed", type: "uint256", internalType: "uint256" }
84303
+ ]
84304
+ },
84305
+ { type: "error", name: "InvalidAddress", inputs: [] },
84306
+ { type: "error", name: "InvalidFee", inputs: [] },
84307
+ { type: "error", name: "InvalidToken", inputs: [] },
84308
+ {
84309
+ type: "error",
84310
+ name: "OwnableInvalidOwner",
84311
+ inputs: [{ name: "owner", type: "address", internalType: "address" }]
84312
+ },
84313
+ {
84314
+ type: "error",
84315
+ name: "OwnableUnauthorizedAccount",
84316
+ inputs: [{ name: "account", type: "address", internalType: "address" }]
84317
+ },
84318
+ {
84319
+ type: "error",
84320
+ name: "ShapeMismatch",
84321
+ inputs: [
84322
+ { name: "expected", type: "uint8", internalType: "enum IEscrowV2.Shape" },
84323
+ { name: "supplied", type: "uint8", internalType: "enum IEscrowV2.Shape" }
84324
+ ]
84325
+ },
84326
+ {
84327
+ type: "error",
84328
+ name: "TermsFeeMismatch",
84329
+ inputs: [
84330
+ { name: "expected", type: "uint16", internalType: "uint16" },
84331
+ { name: "supplied", type: "uint16", internalType: "uint16" }
84332
+ ]
84813
84333
  }
84814
84334
  ];
84815
84335
  var escrowV2Abi = [
@@ -87643,10 +87163,6 @@ var TASK_V2_CASE_STATE = {
87643
87163
  Snapshotting: 6
87644
87164
  };
87645
87165
 
87646
- // ../core/src/tasks/operation-support.ts
87647
- import { readFile as readFile18, stat as stat15 } from "node:fs/promises";
87648
- import { basename as basename2, extname } from "node:path";
87649
-
87650
87166
  // ../core/src/tasks/v2-events.ts
87651
87167
  var TASKS_V2_EVENT_ABIS = {
87652
87168
  EscrowFactoryV2: escrowFactoryV2Abi,
@@ -87696,6 +87212,73 @@ function taskV2OutcomeLines(value) {
87696
87212
  return [...new Set(Object.values(source).flatMap(taskV2OutcomeLines))];
87697
87213
  }
87698
87214
 
87215
+ // ../core/src/tasks/money.ts
87216
+ function formatBaseUnitsUsd(baseUnits2) {
87217
+ const [whole, fraction = ""] = formatUsdc(parseBaseUnits(baseUnits2)).split(".");
87218
+ return `${whole}.${fraction.padEnd(2, "0")}`;
87219
+ }
87220
+ function parseUsdToBaseUnits(text) {
87221
+ if (!/^\d+(?:\.\d{1,6})?$/u.test(text)) {
87222
+ throw new Error(
87223
+ "Task USD amount must be a non-negative decimal with at most six decimal places."
87224
+ );
87225
+ }
87226
+ const [whole = "0", fraction = ""] = text.split(".");
87227
+ return BigInt(whole) * 1000000n + BigInt(fraction.padEnd(6, "0"));
87228
+ }
87229
+ function parseFeeBp(deploymentOrReadiness) {
87230
+ if (typeof deploymentOrReadiness !== "object" || deploymentOrReadiness === null || !("feeBp" in deploymentOrReadiness)) {
87231
+ return null;
87232
+ }
87233
+ const feeBp = deploymentOrReadiness.feeBp;
87234
+ if (feeBp === void 0 || feeBp === null) return null;
87235
+ validateFeeBp(feeBp);
87236
+ return feeBp;
87237
+ }
87238
+ function taskMoney(grossBaseUnits, feeBp) {
87239
+ const atomic = parseBaseUnits(grossBaseUnits);
87240
+ const gross = amount3(atomic);
87241
+ if (feeBp === null) {
87242
+ return { gross, fee: null, net: null, feeBp, line: `$${gross.usd} gross \xB7 fee unavailable` };
87243
+ }
87244
+ validateFeeBp(feeBp);
87245
+ const feeAtomic = atomic * BigInt(feeBp) / 10000n;
87246
+ const fee = amount3(feeAtomic);
87247
+ const net = amount3(atomic - feeAtomic);
87248
+ return {
87249
+ gross,
87250
+ fee,
87251
+ net,
87252
+ feeBp,
87253
+ line: `$${gross.usd} gross \xB7 $${fee.usd} fee \xB7 $${net.usd} net`
87254
+ };
87255
+ }
87256
+ function amount3(atomic) {
87257
+ return { usd: formatBaseUnitsUsd(atomic), baseUnits: atomic.toString() };
87258
+ }
87259
+ function validateFeeBp(value) {
87260
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 1e4) {
87261
+ throw new Error("Task fee basis points must be an integer from 0 to 10000.");
87262
+ }
87263
+ }
87264
+ function parseBaseUnits(value) {
87265
+ if (typeof value === "string" && !/^\d+$/u.test(value) || typeof value !== "bigint" && typeof value !== "string") {
87266
+ throw new Error("Task base units must be a non-negative integer.");
87267
+ }
87268
+ const atomic = BigInt(value);
87269
+ if (atomic < 0n) throw new Error("Task base units must be a non-negative integer.");
87270
+ return atomic;
87271
+ }
87272
+ function taskPolicyAtomic(value) {
87273
+ if (!Number.isFinite(value) || value < 0)
87274
+ throw new Error("Task policy USD amounts must be finite and non-negative.");
87275
+ const [mantissa = "0", exponent = "0"] = value.toString().split("e");
87276
+ const [whole = "0", fraction = ""] = mantissa.split(".");
87277
+ const digits = BigInt(whole + fraction);
87278
+ const scale = 6 + Number(exponent) - fraction.length;
87279
+ return scale >= 0 ? digits * 10n ** BigInt(scale) : digits / 10n ** BigInt(-scale);
87280
+ }
87281
+
87699
87282
  // ../core/src/tasks/operation-support.ts
87700
87283
  var TaskOperationError = class extends Error {
87701
87284
  constructor(code, message, manifestHash, details) {
@@ -87972,121 +87555,667 @@ function nextTaskEvents(page, cursor2) {
87972
87555
  "invalid_response",
87973
87556
  "The task event cursor regressed or is malformed."
87974
87557
  );
87975
- for (const event of page.events)
87976
- if (!Number.isSafeInteger(event.sequence) || event.sequence < 0)
87977
- throw new TaskOperationError("invalid_response", "A task event sequence is malformed.");
87978
- const seen = /* @__PURE__ */ new Set();
87979
- const events = [...page.events].sort((a, b) => a.sequence - b.sequence).filter((event) => {
87980
- if (event.sequence <= cursor2 || seen.has(event.sequence)) return false;
87981
- seen.add(event.sequence);
87982
- return true;
87558
+ for (const event of page.events)
87559
+ if (!Number.isSafeInteger(event.sequence) || event.sequence < 0)
87560
+ throw new TaskOperationError("invalid_response", "A task event sequence is malformed.");
87561
+ const seen = /* @__PURE__ */ new Set();
87562
+ const events = [...page.events].sort((a, b) => a.sequence - b.sequence).filter((event) => {
87563
+ if (event.sequence <= cursor2 || seen.has(event.sequence)) return false;
87564
+ seen.add(event.sequence);
87565
+ return true;
87566
+ });
87567
+ return {
87568
+ events,
87569
+ nextCursor: Math.max(cursor2, page.nextAfter, ...page.events.map((e3) => e3.sequence))
87570
+ };
87571
+ }
87572
+ async function accountTaskPolicy(directory, wallet, warn) {
87573
+ let raw;
87574
+ try {
87575
+ raw = await readFile18(join16(directory, "wallets.json"), "utf8");
87576
+ } catch {
87577
+ return void 0;
87578
+ }
87579
+ try {
87580
+ const wallets = JSON.parse(raw).wallets;
87581
+ const stored = wallets && Object.hasOwn(wallets, wallet) ? wallets[wallet]?.taskPolicy : void 0;
87582
+ return stored === void 0 ? void 0 : walletTaskPolicySchema.parse(stored);
87583
+ } catch {
87584
+ warn?.(`The task limits stored for account ${wallet} are unreadable; using the defaults.`);
87585
+ return void 0;
87586
+ }
87587
+ }
87588
+ async function taskPolicyForWallet(args) {
87589
+ let invalid = false;
87590
+ const profiles = await listAgentProfiles(args.directory, {
87591
+ schema: args.schema,
87592
+ ...args.warn ? { warn: args.warn } : {},
87593
+ onInvalid: () => {
87594
+ invalid = true;
87595
+ }
87596
+ });
87597
+ if (invalid) throw new TaskInputError("An invalid agent profile prevents task policy selection.");
87598
+ const matches = profiles.filter((profile2) => profile2.wallet === args.wallet);
87599
+ if (matches.length > 1)
87600
+ throw new TaskInputError(
87601
+ `More than one agent profile uses wallet ${args.wallet}; task policy is ambiguous.`
87602
+ );
87603
+ const profile = matches[0];
87604
+ if (profile)
87605
+ return {
87606
+ maxPerTaskUsd: profile.maxPerTaskUsd,
87607
+ approveAboveUsd: profile.approveAboveUsd,
87608
+ autoReleaseBelowUsd: profile.autoReleaseBelowUsd,
87609
+ source: "agent-profile"
87610
+ };
87611
+ const account = await accountTaskPolicy(args.directory, args.wallet, args.warn);
87612
+ const stored = account?.maxPerTaskUsd !== void 0 || account?.approveAboveUsd !== void 0;
87613
+ return {
87614
+ maxPerTaskUsd: account?.maxPerTaskUsd ?? DEFAULT_MAX_PER_TASK_USD,
87615
+ approveAboveUsd: account?.approveAboveUsd ?? agentProfileSchema.shape.approveAboveUsd.parse(void 0),
87616
+ autoReleaseBelowUsd: DEFAULT_AUTO_RELEASE_BELOW_USD,
87617
+ source: stored ? "account" : "defaults"
87618
+ };
87619
+ }
87620
+ async function taskMoneySnapshot(client, orderId, escrowId, options = { signInHint: "" }) {
87621
+ const order = await taskRequest(
87622
+ "task money",
87623
+ "getOrder",
87624
+ () => client.getOrder(orderId),
87625
+ options
87626
+ ), workOrder = order.workOrder;
87627
+ if (workOrder.id !== orderId || workOrder.version !== "work-order-view-v1")
87628
+ throw new TaskOperationError(
87629
+ "invalid_response",
87630
+ "A private task order matching the requested ID is required."
87631
+ );
87632
+ const matches = escrowId ? workOrder.milestones.filter((m) => m.id === escrowId) : workOrder.milestones;
87633
+ if (matches.length !== 1)
87634
+ throw new TaskOperationError("invalid_response", "Select one task milestone by escrow ID.");
87635
+ const milestone = matches[0];
87636
+ if (milestone.workOrderId !== orderId)
87637
+ throw new TaskOperationError("invalid_response", "The milestone belongs to a different task.");
87638
+ let readiness;
87639
+ try {
87640
+ readiness = { ok: true, value: await client.deployment() };
87641
+ } catch (error61) {
87642
+ readiness = { ok: false, error: error61 };
87643
+ }
87644
+ return {
87645
+ order,
87646
+ escrowId: milestone.id,
87647
+ money: taskMoney(milestone.amountBaseUnits, readiness.ok ? parseFeeBp(readiness.value) : null),
87648
+ readiness
87649
+ };
87650
+ }
87651
+ function cachedMoneyClient(client, snapshot) {
87652
+ return new Proxy(client, {
87653
+ get(target, property) {
87654
+ if (property === "getOrder")
87655
+ return async (id2) => {
87656
+ if (id2 !== snapshot.order.workOrder.id)
87657
+ throw new Error("The cached task order does not match the requested ID.");
87658
+ return snapshot.order;
87659
+ };
87660
+ if (property === "deployment")
87661
+ return async () => {
87662
+ if (snapshot.readiness.ok) return snapshot.readiness.value;
87663
+ throw snapshot.readiness.error;
87664
+ };
87665
+ const value = Reflect.get(target, property, target);
87666
+ return typeof value === "function" ? value.bind(target) : value;
87667
+ }
87668
+ });
87669
+ }
87670
+ function fundingRefusalReason(error61) {
87671
+ if (error61 instanceof Error && error61.name === "SpendCapExceededError") {
87672
+ const fromCause = fundingRefusalReason(error61.cause);
87673
+ if (fromCause) return fromCause;
87674
+ return "cap" in error61 && error61.cap === "per_day" ? "policy.perDay" : void 0;
87675
+ }
87676
+ if (!(error61 instanceof SpendCapError || error61 instanceof Error && error61.name === "SpendCapError"))
87677
+ return void 0;
87678
+ const code = "code" in error61 ? error61.code : void 0;
87679
+ return code === "per_task_cap_exceeded" ? "policy.perTask" : code === "per_day_cap_exceeded" ? "policy.perDay" : void 0;
87680
+ }
87681
+ function taskEventLine(event) {
87682
+ 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;
87683
+ return `${event.sequence}: ${[label2, ...taskV2OutcomeLines(event.payload)].join(" \xB7 ")}`;
87684
+ }
87685
+ function requireTaskMethod(client, name) {
87686
+ const method = client[name];
87687
+ if (typeof method !== "function")
87688
+ throw new TaskOperationError(
87689
+ "not_supported",
87690
+ `Task method ${name} is not supported by this SDK adapter.`
87691
+ );
87692
+ return method.bind(client);
87693
+ }
87694
+
87695
+ // ../core/src/tasks/availability.ts
87696
+ var TASK_V2_NEW_WORK_ACTIONS = [
87697
+ "fund",
87698
+ "approve-bond",
87699
+ "award",
87700
+ "award-consent"
87701
+ ];
87702
+ var NETWORK_NAMES = {
87703
+ 8453: "Base",
87704
+ 84532: "Base Sepolia",
87705
+ 5042002: "Arc testnet"
87706
+ };
87707
+ function taskNetworkName(chainId) {
87708
+ return NETWORK_NAMES[chainId] ?? `chain ${chainId}`;
87709
+ }
87710
+ function tasksUnavailableError(chainId, untouched = "Nothing was signed and no money moved.", code = "tasks_unavailable") {
87711
+ return new TaskOperationError(
87712
+ code,
87713
+ `vAPI reports Tasks as unavailable on ${taskNetworkName(chainId)} right now. ${untouched} Try again later.`
87714
+ );
87715
+ }
87716
+ async function readTasksReadiness(client) {
87717
+ try {
87718
+ return await client.deployment();
87719
+ } catch {
87720
+ return void 0;
87721
+ }
87722
+ }
87723
+ function requireTasksAvailable(action, readiness, untouched) {
87724
+ if (!TASK_V2_NEW_WORK_ACTIONS.includes(action)) return;
87725
+ if (!readiness)
87726
+ throw new TaskOperationError(
87727
+ "tasks_unavailable",
87728
+ `vAPI's Tasks status could not be read. ${untouched ?? "Nothing was signed and no money moved."} Try again later.`
87729
+ );
87730
+ if (!readiness.configured) throw tasksUnavailableError(readiness.chainId, untouched);
87731
+ }
87732
+
87733
+ // ../core/src/tasks/dispute-fee.ts
87734
+ import { createHash as createHash3 } from "node:crypto";
87735
+ function disputeFeeBaseUnits(amount4) {
87736
+ if (amount4 < 0n) throw new Error("Dispute amount must be nonnegative.");
87737
+ const fee = amount4 * 1000n / 10000n;
87738
+ return fee < 20000000n ? 20000000n : fee > 500000000n ? 500000000n : fee;
87739
+ }
87740
+ function taskFeeReservationKey(milestoneId2, action) {
87741
+ const bytes = createHash3("sha256").update(JSON.stringify([milestoneId2, action])).digest().subarray(0, 16);
87742
+ bytes[6] = bytes[6] & 15 | 80;
87743
+ bytes[8] = bytes[8] & 63 | 128;
87744
+ const hex5 = bytes.toString("hex");
87745
+ return `${hex5.slice(0, 8)}-${hex5.slice(8, 12)}-${hex5.slice(12, 16)}-${hex5.slice(16, 20)}-${hex5.slice(20)}`;
87746
+ }
87747
+
87748
+ // ../core/src/tasks/plan-guard.ts
87749
+ var TASKS_CHAIN_ABI = [
87750
+ {
87751
+ type: "function",
87752
+ name: "createEscrow",
87753
+ stateMutability: "nonpayable",
87754
+ inputs: [
87755
+ { name: "buyer", type: "address" },
87756
+ { name: "token", type: "address" },
87757
+ { name: "amount", type: "uint256" },
87758
+ { name: "workDuration", type: "uint64" },
87759
+ { name: "acceptanceWindow", type: "uint64" },
87760
+ { name: "termsHash", type: "bytes32" },
87761
+ { name: "salt", type: "bytes32" }
87762
+ ],
87763
+ outputs: [{ name: "escrow", type: "address" }]
87764
+ },
87765
+ {
87766
+ type: "function",
87767
+ name: "fundWithAuthorization",
87768
+ stateMutability: "nonpayable",
87769
+ inputs: [
87770
+ { name: "validAfter", type: "uint256" },
87771
+ { name: "validBefore", type: "uint256" },
87772
+ { name: "nonce", type: "bytes32" },
87773
+ { name: "signature", type: "bytes" }
87774
+ ],
87775
+ outputs: []
87776
+ },
87777
+ {
87778
+ type: "function",
87779
+ name: "approve",
87780
+ stateMutability: "nonpayable",
87781
+ inputs: [
87782
+ { name: "spender", type: "address" },
87783
+ { name: "amount", type: "uint256" }
87784
+ ],
87785
+ outputs: [{ name: "ok", type: "bool" }]
87786
+ },
87787
+ {
87788
+ type: "function",
87789
+ name: "depositFunds",
87790
+ stateMutability: "nonpayable",
87791
+ inputs: [],
87792
+ outputs: []
87793
+ },
87794
+ {
87795
+ type: "function",
87796
+ name: "submitDelivery",
87797
+ stateMutability: "nonpayable",
87798
+ inputs: [{ name: "manifestHash", type: "bytes32" }],
87799
+ outputs: []
87800
+ },
87801
+ {
87802
+ type: "function",
87803
+ name: "releaseFunds",
87804
+ stateMutability: "nonpayable",
87805
+ inputs: [],
87806
+ outputs: []
87807
+ },
87808
+ { type: "function", name: "refundBuyer", stateMutability: "nonpayable", inputs: [], outputs: [] },
87809
+ {
87810
+ type: "function",
87811
+ name: "raiseDispute",
87812
+ stateMutability: "nonpayable",
87813
+ inputs: [{ name: "evidenceHash", type: "bytes32" }],
87814
+ outputs: []
87815
+ },
87816
+ {
87817
+ type: "function",
87818
+ name: "submitCounterEvidence",
87819
+ stateMutability: "nonpayable",
87820
+ inputs: [{ name: "evidenceHash", type: "bytes32" }],
87821
+ outputs: []
87822
+ },
87823
+ {
87824
+ type: "function",
87825
+ name: "resolveUnmatchedDispute",
87826
+ stateMutability: "nonpayable",
87827
+ inputs: [],
87828
+ outputs: []
87829
+ },
87830
+ {
87831
+ type: "function",
87832
+ name: "timeoutRefund",
87833
+ stateMutability: "nonpayable",
87834
+ inputs: [],
87835
+ outputs: []
87836
+ },
87837
+ { type: "function", name: "finalize", stateMutability: "nonpayable", inputs: [], outputs: [] },
87838
+ {
87839
+ type: "function",
87840
+ name: "disputeFee",
87841
+ stateMutability: "view",
87842
+ inputs: [],
87843
+ outputs: [{ name: "fee", type: "uint256" }]
87844
+ },
87845
+ {
87846
+ type: "function",
87847
+ name: "allowance",
87848
+ stateMutability: "view",
87849
+ inputs: [
87850
+ { name: "owner", type: "address" },
87851
+ { name: "spender", type: "address" }
87852
+ ],
87853
+ outputs: [{ name: "amount", type: "uint256" }]
87854
+ }
87855
+ ];
87856
+ var TASKS_READ_ABI = parseAbi([
87857
+ "function paymentToken() view returns (address)",
87858
+ "function isEscrow(address escrow) view returns (bool)",
87859
+ "function name() view returns (string)",
87860
+ "function version() view returns (string)",
87861
+ "function buyer() view returns (address)",
87862
+ "function seller() view returns (address)",
87863
+ "function token() view returns (address)",
87864
+ "function amount() view returns (uint256)",
87865
+ "function termsHash() view returns (bytes32)",
87866
+ "function state() view returns (uint8)",
87867
+ "function offerDeadline() view returns (uint64)",
87868
+ "function workDeadline() view returns (uint64)",
87869
+ "function reviewDeadline() view returns (uint64)",
87870
+ "function disputedAt() view returns (uint64)",
87871
+ "function counterEvidenceDeadline() view returns (uint64)",
87872
+ "function resolution() view returns (uint8)",
87873
+ "function disputeFee() view returns (uint256)",
87874
+ "function predictEscrow(address seller, bytes32 salt) view returns (address)"
87875
+ ]);
87876
+ function verifyPlan(operation, expectation) {
87877
+ const fail2 = (message) => {
87878
+ throw new TasksChainError(`Unsafe transaction plan: ${message}`, false);
87879
+ };
87880
+ const plan = operation.plan;
87881
+ if (!plan) throw new TasksChainError("Unsafe transaction plan: missing plan", false);
87882
+ if (plan.operationId !== operation.id || plan.step !== operation.step) fail2("operation mismatch");
87883
+ if (!expectation.steps.includes(plan.step)) fail2("unexpected step");
87884
+ if (!operation.expectedActor || getAddress(operation.expectedActor) !== getAddress(expectation.signer) || getAddress(plan.from) !== getAddress(expectation.signer))
87885
+ fail2("unexpected signer");
87886
+ if (plan.chainId !== expectation.deployment.chainId || plan.network !== expectation.deployment.network || plan.network !== `eip155:${plan.chainId}` || plan.value !== "0")
87887
+ fail2("unexpected network or value");
87888
+ if (expectation.milestone.network !== plan.network || expectation.milestone.asset.toLowerCase() !== `${plan.network}/erc20:${expectation.deployment.usdc}`.toLowerCase())
87889
+ fail2("milestone asset mismatch");
87890
+ const target = plan.step === "create-escrow" ? expectation.deployment.escrowContract : plan.step === "approve-usdc" ? expectation.deployment.usdc : expectation.milestone.escrowContract;
87891
+ if (getAddress(plan.to) !== getAddress(target)) fail2("unexpected target");
87892
+ const decoded = (() => {
87893
+ try {
87894
+ return decodeFunctionData({ abi: TASKS_CHAIN_ABI, data: plan.data });
87895
+ } catch {
87896
+ return fail2("invalid calldata");
87897
+ }
87898
+ })();
87899
+ const expectedName = {
87900
+ "create-escrow": "createEscrow",
87901
+ "fund-with-authorization": "fundWithAuthorization",
87902
+ "approve-usdc": "approve",
87903
+ "deposit-funds": "depositFunds",
87904
+ "submit-delivery": "submitDelivery",
87905
+ "release-funds": "releaseFunds",
87906
+ "refund-buyer": "refundBuyer",
87907
+ "raise-dispute": "raiseDispute",
87908
+ "submit-counter-evidence": "submitCounterEvidence",
87909
+ "resolve-unmatched-dispute": "resolveUnmatchedDispute",
87910
+ "timeout-refund": "timeoutRefund",
87911
+ finalize: "finalize"
87912
+ };
87913
+ if (decoded.functionName !== expectedName[plan.step]) fail2("unexpected selector");
87914
+ const args = [...decoded.args ?? []];
87915
+ const eq = (a, b) => typeof a === "string" && typeof b === "string" ? a.toLowerCase() === b.toLowerCase() : a === b;
87916
+ const requireArgs = (values) => {
87917
+ if (args.length !== values.length || args.some((v, i2) => !eq(v, values[i2])))
87918
+ fail2("unexpected arguments");
87919
+ };
87920
+ if (plan.step === "create-escrow") {
87921
+ if (!expectation.seller || getAddress(expectation.signer) !== getAddress(expectation.seller))
87922
+ fail2("createEscrow requires the locally bound seller");
87923
+ const workDuration = expectation.workDurationSeconds ?? expectation.milestone.terms.workDurationSeconds ?? getTrustedTasksDurations(expectation.deployment.chainId).workDurationSeconds;
87924
+ if (workDuration === void 0) fail2("missing trusted work duration");
87925
+ requireArgs([
87926
+ expectation.buyer,
87927
+ expectation.deployment.usdc,
87928
+ BigInt(expectation.milestone.amountBaseUnits),
87929
+ BigInt(workDuration),
87930
+ BigInt(
87931
+ expectation.reviewWindowSeconds ?? expectation.milestone.terms.acceptanceWindowSeconds
87932
+ ),
87933
+ expectation.milestone.termsHash,
87934
+ keccak256(stringToHex(expectation.milestone.id))
87935
+ ]);
87936
+ } else if (plan.step === "fund-with-authorization") {
87937
+ const a = expectation.authorization;
87938
+ if (!a)
87939
+ throw new TasksChainError("Unsafe transaction plan: missing local authorization", false);
87940
+ requireArgs([BigInt(a.validAfter), BigInt(a.validBefore), a.nonce, a.signature]);
87941
+ } else if (plan.step === "approve-usdc") {
87942
+ if (expectation.approveAmount === void 0) fail2("missing verified approval amount");
87943
+ requireArgs([expectation.milestone.escrowContract, expectation.approveAmount]);
87944
+ } else if (plan.step === "submit-delivery") {
87945
+ if (!expectation.manifestHash) fail2("missing manifest hash");
87946
+ requireArgs([expectation.manifestHash]);
87947
+ } else if (plan.step === "raise-dispute" || plan.step === "submit-counter-evidence") {
87948
+ if (!expectation.evidenceHash) fail2("missing evidence hash");
87949
+ requireArgs([expectation.evidenceHash]);
87950
+ } else requireArgs([]);
87951
+ }
87952
+
87953
+ // ../core/src/tasks/chain-verification.ts
87954
+ var TasksPartiesNotBoundError = class extends TasksValidationError {
87955
+ constructor() {
87956
+ super(
87957
+ "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."
87958
+ );
87959
+ this.name = "TasksPartiesNotBoundError";
87960
+ }
87961
+ };
87962
+ async function verifyDeployment(ready, rpc, overrides) {
87963
+ const factory = getTrustedTasksFactory(ready.chainId, overrides);
87964
+ if (!factory)
87965
+ throw new TasksChainError(
87966
+ `No trusted Tasks escrow factory is configured for chain ${ready.chainId}. Set VAPI_TASKS_ESCROW_FACTORY_${ready.chainId}.`,
87967
+ false,
87968
+ { authorizationExposed: false }
87969
+ );
87970
+ if (!isAddressEqual(factory, ready.escrowContract))
87971
+ throw new TasksValidationError(
87972
+ "The Tasks readiness factory does not match the trusted factory."
87973
+ );
87974
+ if (await rpc.getChainId() !== ready.chainId)
87975
+ throw new TasksValidationError("The RPC chain ID does not match the task deployment.");
87976
+ const token = await rpc.readContract({
87977
+ address: factory,
87978
+ abi: TASKS_READ_ABI,
87979
+ functionName: "paymentToken"
87983
87980
  });
87981
+ if (!isAddressEqual(token, ready.usdc))
87982
+ throw new TasksValidationError(
87983
+ "The Tasks readiness token does not match the trusted factory payment token."
87984
+ );
87985
+ const [name, version5] = await Promise.all([
87986
+ rpc.readContract({ address: token, abi: TASKS_READ_ABI, functionName: "name" }),
87987
+ rpc.readContract({ address: token, abi: TASKS_READ_ABI, functionName: "version" })
87988
+ ]);
87989
+ const domain2 = { name, version: version5, chainId: ready.chainId, verifyingContract: getAddress(token) };
87990
+ if (ready.eip3009Domain && (ready.eip3009Domain.name !== name || ready.eip3009Domain.version !== version5 || ready.eip3009Domain.chainId !== ready.chainId || !isAddressEqual(ready.eip3009Domain.verifyingContract, token)))
87991
+ throw new TasksValidationError(
87992
+ "The funding authorization domain does not match the onchain token domain."
87993
+ );
87984
87994
  return {
87985
- events,
87986
- nextCursor: Math.max(cursor2, page.nextAfter, ...page.events.map((e3) => e3.sequence))
87995
+ ...ready,
87996
+ escrowContract: getAddress(factory),
87997
+ usdc: getAddress(token),
87998
+ eip3009Domain: domain2
87987
87999
  };
87988
88000
  }
87989
- async function taskPolicyForWallet(args) {
87990
- let invalid = false;
87991
- const profiles = await listAgentProfiles(args.directory, {
87992
- schema: args.schema,
87993
- ...args.warn ? { warn: args.warn } : {},
87994
- onInvalid: () => {
87995
- invalid = true;
87996
- }
87997
- });
87998
- if (invalid) throw new TaskInputError("An invalid agent profile prevents task policy selection.");
87999
- const matches = profiles.filter((profile2) => profile2.wallet === args.wallet);
88000
- if (matches.length > 1)
88001
- throw new TaskInputError(
88002
- `More than one agent profile uses wallet ${args.wallet}; task policy is ambiguous.`
88001
+ async function verifyScope(client, signer, selected, ready, verb, steps, options = {}) {
88002
+ const { scopes } = await client.getScopes(selected.workOrderId);
88003
+ const matches = scopes.filter(
88004
+ (scope2) => scope2.state === "accepted" && scope2.milestoneId === selected.id
88005
+ );
88006
+ if (matches.length !== 1)
88007
+ throw new TasksValidationError("The task milestone requires one accepted signed scope.");
88008
+ const scope = matches[0];
88009
+ const payload = scope.signingPayload;
88010
+ const frozen = freezeScopeTerms(scope.structuredTerms, scope.brief);
88011
+ 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)
88012
+ throw new TasksValidationError(
88013
+ "The accepted task scope does not match its locally verified terms hash and milestone."
88003
88014
  );
88004
- const profile = matches[0];
88005
- return profile ? {
88006
- maxPerTaskUsd: profile.maxPerTaskUsd,
88007
- approveAboveUsd: profile.approveAboveUsd,
88008
- autoReleaseBelowUsd: profile.autoReleaseBelowUsd,
88009
- source: "agent-profile"
88010
- } : {
88011
- maxPerTaskUsd: DEFAULT_MAX_PER_TASK_USD,
88012
- approveAboveUsd: agentProfileSchema.shape.approveAboveUsd.parse(void 0),
88013
- autoReleaseBelowUsd: DEFAULT_AUTO_RELEASE_BELOW_USD,
88014
- source: "defaults"
88015
+ if (!scope.counterpartyAddress || !scope.counterpartySignature || isAddressEqual(scope.proposerAddress, scope.counterpartyAddress) || !(isAddressEqual(signer, scope.proposerAddress) || isAddressEqual(signer, scope.counterpartyAddress)))
88016
+ throw new TasksValidationError(
88017
+ "The local signer is not one of the two accepted scope parties."
88018
+ );
88019
+ const message = canonicalJson(payload);
88020
+ const signatures = await Promise.all([
88021
+ verifyMessage({
88022
+ address: scope.proposerAddress,
88023
+ message,
88024
+ signature: scope.proposerSignature
88025
+ }),
88026
+ verifyMessage({
88027
+ address: scope.counterpartyAddress,
88028
+ message,
88029
+ signature: scope.counterpartySignature
88030
+ })
88031
+ ]);
88032
+ if (signatures.some((valid) => !valid))
88033
+ throw new TasksValidationError("Both accepted task scope signatures must verify.");
88034
+ const terms = frozen.structured;
88035
+ 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)
88036
+ throw new TasksValidationError(
88037
+ "The signed task scope asset, factory or amount does not match the deployment and milestone."
88038
+ );
88039
+ const identity = {
88040
+ orderId: selected.workOrderId,
88041
+ trancheOrdinal: selected.ordinal,
88042
+ scopeVersion: scope.version,
88043
+ termsHash: frozen.termsHash,
88044
+ self: getAddress(signer)
88015
88045
  };
88016
- }
88017
- async function taskMoneySnapshot(client, orderId, escrowId, options = { signInHint: "" }) {
88018
- const order = await taskRequest(
88019
- "task money",
88020
- "getOrder",
88021
- () => client.getOrder(orderId),
88022
- options
88023
- ), workOrder = order.workOrder;
88024
- if (workOrder.id !== orderId || workOrder.version !== "work-order-view-v1")
88025
- throw new TaskOperationError(
88026
- "invalid_response",
88027
- "A private task order matching the requested ID is required."
88046
+ const binding = await options.bindings?.get(identity);
88047
+ if (!binding) throw new TasksPartiesNotBoundError();
88048
+ if (options.counterparty && !isAddressEqual(binding.counterparty, options.counterparty))
88049
+ throw new TasksValidationError(
88050
+ "The confirmed counterparty differs from the locally bound parties."
88051
+ );
88052
+ 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(
88053
+ (address10) => isAddressEqual(address10, binding.self) || isAddressEqual(address10, binding.counterparty)
88054
+ ))
88055
+ throw new TasksValidationError(
88056
+ "The accepted scope parties do not match the locally bound parties."
88057
+ );
88058
+ const buyer = getAddress(binding.role === "client" ? binding.self : binding.counterparty);
88059
+ const seller = getAddress(binding.role === "provider" ? binding.self : binding.counterparty);
88060
+ if (verb === "createEscrow" && !isAddressEqual(signer, seller))
88061
+ throw new TasksValidationError("Task createEscrow requires the locally bound seller's wallet.");
88062
+ const workDurationSeconds = terms.workDurationSeconds ?? getTrustedTasksDurations(ready.chainId, options.trustedDurations).workDurationSeconds;
88063
+ if (workDurationSeconds === void 0)
88064
+ throw new TasksValidationError(
88065
+ "The signed task scope has no work duration and no trusted default is configured."
88028
88066
  );
88029
- const matches = escrowId ? workOrder.milestones.filter((m) => m.id === escrowId) : workOrder.milestones;
88030
- if (matches.length !== 1)
88031
- throw new TaskOperationError("invalid_response", "Select one task milestone by escrow ID.");
88032
- const milestone = matches[0];
88033
- if (milestone.workOrderId !== orderId)
88034
- throw new TaskOperationError("invalid_response", "The milestone belongs to a different task.");
88035
- let readiness;
88036
- try {
88037
- readiness = { ok: true, value: await client.deployment() };
88038
- } catch (error61) {
88039
- readiness = { ok: false, error: error61 };
88040
- }
88041
88067
  return {
88042
- order,
88043
- escrowId: milestone.id,
88044
- money: taskMoney(milestone.amountBaseUnits, readiness.ok ? parseFeeBp(readiness.value) : null),
88045
- readiness
88068
+ signer,
88069
+ buyer,
88070
+ seller,
88071
+ parties: [buyer, seller],
88072
+ workDurationSeconds,
88073
+ ...verb === "fund" ? { approveAmount: BigInt(terms.budget.amountBaseUnits) } : {},
88074
+ reviewWindowSeconds: terms.acceptanceWindowSeconds,
88075
+ nowSeconds: BigInt(Math.floor((options.now ?? (() => /* @__PURE__ */ new Date()))().getTime() / 1e3)),
88076
+ verb,
88077
+ deployment: ready,
88078
+ milestone: {
88079
+ ...selected,
88080
+ terms,
88081
+ termsHash: frozen.termsHash,
88082
+ amountBaseUnits: terms.budget.amountBaseUnits
88083
+ },
88084
+ steps
88046
88085
  };
88047
88086
  }
88048
- function cachedMoneyClient(client, snapshot) {
88049
- return new Proxy(client, {
88050
- get(target, property) {
88051
- if (property === "getOrder")
88052
- return async (id2) => {
88053
- if (id2 !== snapshot.order.workOrder.id)
88054
- throw new Error("The cached task order does not match the requested ID.");
88055
- return snapshot.order;
88056
- };
88057
- if (property === "deployment")
88058
- return async () => {
88059
- if (snapshot.readiness.ok) return snapshot.readiness.value;
88060
- throw snapshot.readiness.error;
88061
- };
88062
- const value = Reflect.get(target, property, target);
88063
- return typeof value === "function" ? value.bind(target) : value;
88064
- }
88087
+ async function verifyClone(rpc, expected, checkState) {
88088
+ if (expected.verb === "createEscrow") return;
88089
+ const clone2 = expected.milestone.escrowContract;
88090
+ const registered = await rpc.readContract({
88091
+ address: expected.deployment.escrowContract,
88092
+ abi: TASKS_READ_ABI,
88093
+ functionName: "isEscrow",
88094
+ args: [clone2]
88065
88095
  });
88066
- }
88067
- function fundingRefusalReason(error61) {
88068
- if (error61 instanceof Error && error61.name === "SpendCapExceededError") {
88069
- const fromCause = fundingRefusalReason(error61.cause);
88070
- if (fromCause) return fromCause;
88071
- return "cap" in error61 && error61.cap === "per_day" ? "policy.perDay" : void 0;
88096
+ if (!registered)
88097
+ throw new TasksValidationError(
88098
+ "The task escrow clone is not registered by the trusted factory."
88099
+ );
88100
+ const predicted = await rpc.readContract({
88101
+ address: expected.deployment.escrowContract,
88102
+ abi: TASKS_READ_ABI,
88103
+ functionName: "predictEscrow",
88104
+ args: [expected.seller, keccak256(stringToHex(expected.milestone.id))]
88105
+ });
88106
+ if (!isAddressEqual(predicted, clone2))
88107
+ throw new TasksValidationError(
88108
+ "The escrow clone does not match the signed milestone salt and bound seller."
88109
+ );
88110
+ const read = (functionName) => rpc.readContract({ address: clone2, abi: TASKS_READ_ABI, functionName });
88111
+ const [
88112
+ buyer,
88113
+ seller,
88114
+ token,
88115
+ amount4,
88116
+ termsHash,
88117
+ state,
88118
+ resolution,
88119
+ offerDeadline,
88120
+ workDeadline,
88121
+ reviewDeadline,
88122
+ disputedAt,
88123
+ counterEvidenceDeadline,
88124
+ slot0,
88125
+ slot6,
88126
+ slot7
88127
+ ] = await Promise.all([
88128
+ read("buyer"),
88129
+ read("seller"),
88130
+ read("token"),
88131
+ read("amount"),
88132
+ read("termsHash"),
88133
+ read("state"),
88134
+ read("resolution"),
88135
+ read("offerDeadline"),
88136
+ read("workDeadline"),
88137
+ read("reviewDeadline"),
88138
+ read("disputedAt"),
88139
+ read("counterEvidenceDeadline"),
88140
+ rpc.getStorageAt({ address: clone2, slot: "0x0" }),
88141
+ rpc.getStorageAt({ address: clone2, slot: "0x6" }),
88142
+ rpc.getStorageAt({ address: clone2, slot: "0x7" })
88143
+ ]);
88144
+ 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())
88145
+ throw new TasksValidationError(
88146
+ "The onchain escrow parties, token, amount or terms hash do not match the signed scope."
88147
+ );
88148
+ const s0 = storageWord(slot0);
88149
+ const s6 = storageWord(slot6);
88150
+ const s7 = storageWord(slot7);
88151
+ 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)
88152
+ throw new TasksValidationError("unsupported escrow layout");
88153
+ if (field(s7, 8, 8) !== BigInt(expected.workDurationSeconds) || field(s7, 16, 8) !== BigInt(expected.reviewWindowSeconds))
88154
+ throw new TasksValidationError(
88155
+ "The onchain escrow durations do not match the signed terms and trusted defaults."
88156
+ );
88157
+ const actor = expected.verb === "fund" || expected.verb === "release" ? buyer : expected.verb === "deliver" || expected.verb === "refund" ? seller : expected.signer;
88158
+ if (!isAddressEqual(actor, expected.signer))
88159
+ throw new TasksValidationError(
88160
+ `Task ${expected.verb} requires the onchain escrow party's local wallet.`
88161
+ );
88162
+ const states = {
88163
+ fund: [1],
88164
+ deliver: [2],
88165
+ release: [3],
88166
+ refund: [2, 3],
88167
+ dispute: [2, 3],
88168
+ "counter-evidence": [4],
88169
+ "resolve-unmatched": [4]
88170
+ };
88171
+ if (checkState && !states[expected.verb]?.includes(state))
88172
+ throw new TasksValidationError(
88173
+ `The onchain escrow state is not eligible for task ${expected.verb}.`
88174
+ );
88175
+ if (["dispute", "counter-evidence"].includes(expected.verb)) {
88176
+ const fee = disputeFeeBaseUnits(amount4);
88177
+ if (await read("disputeFee") !== fee)
88178
+ throw new TasksValidationError(
88179
+ "The onchain dispute fee does not match the verified amount fee rule."
88180
+ );
88181
+ expected.disputeFee = fee;
88182
+ expected.approveAmount = fee;
88072
88183
  }
88073
- if (!(error61 instanceof SpendCapError || error61 instanceof Error && error61.name === "SpendCapError"))
88074
- return void 0;
88075
- const code = "code" in error61 ? error61.code : void 0;
88076
- return code === "per_task_cap_exceeded" ? "policy.perTask" : code === "per_day_cap_exceeded" ? "policy.perDay" : void 0;
88184
+ if (checkState && ["counter-evidence", "resolve-unmatched"].includes(expected.verb)) {
88185
+ const slot8 = storageWord(await rpc.getStorageAt({ address: clone2, slot: "0x8" }));
88186
+ const opener = storageAddress(slot8, 0);
88187
+ const submitted = field(slot8, 20, 1);
88188
+ if (!isAddressEqual(opener, buyer) && !isAddressEqual(opener, seller) || submitted > 1n || field(slot8, 21, 11) !== 0n)
88189
+ throw new TasksValidationError("unsupported escrow layout");
88190
+ const now = expected.nowSeconds;
88191
+ if (now === void 0)
88192
+ throw new TasksValidationError("A trusted clock is required for dispute eligibility.");
88193
+ if (submitted === 1n)
88194
+ throw new TasksValidationError(
88195
+ "Counter-evidence has already been submitted for this dispute."
88196
+ );
88197
+ if (expected.verb === "counter-evidence") {
88198
+ if (isAddressEqual(opener, expected.signer))
88199
+ throw new TasksValidationError("Only the non-opener party can submit counter-evidence.");
88200
+ if (now >= counterEvidenceDeadline)
88201
+ throw new TasksValidationError("The counter-evidence deadline has passed.");
88202
+ } else if (now <= counterEvidenceDeadline)
88203
+ throw new TasksValidationError(
88204
+ "The counter-evidence deadline has not passed; unmatched resolution is unavailable."
88205
+ );
88206
+ }
88207
+ expected.offerDeadline = offerDeadline;
88077
88208
  }
88078
- function taskEventLine(event) {
88079
- 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;
88080
- return `${event.sequence}: ${[label2, ...taskV2OutcomeLines(event.payload)].join(" \xB7 ")}`;
88209
+ function storageWord(value) {
88210
+ if (!value || !/^0x[0-9a-fA-F]{64}$/.test(value))
88211
+ throw new TasksValidationError("unsupported escrow layout");
88212
+ return BigInt(value);
88081
88213
  }
88082
- function requireTaskMethod(client, name) {
88083
- const method = client[name];
88084
- if (typeof method !== "function")
88085
- throw new TaskOperationError(
88086
- "not_supported",
88087
- `Task method ${name} is not supported by this SDK adapter.`
88088
- );
88089
- return method.bind(client);
88214
+ function field(word, offset, bytes) {
88215
+ return word >> BigInt(offset * 8) & (1n << BigInt(bytes * 8)) - 1n;
88216
+ }
88217
+ function storageAddress(word, offset) {
88218
+ return getAddress(`0x${field(word, offset, 20).toString(16).padStart(40, "0")}`);
88090
88219
  }
88091
88220
 
88092
88221
  // ../core/src/tasks/v2-trust.ts
@@ -88179,12 +88308,65 @@ function getTrustedTasksV2Deployment(chainId, options = {}) {
88179
88308
  return normalized2;
88180
88309
  }
88181
88310
 
88311
+ // ../core/src/tasks/v2-limits.ts
88312
+ var feeBpSchema = external_exports.union([external_exports.number(), external_exports.bigint()]).transform(Number).pipe(external_exports.number().int().min(0).max(2e3));
88313
+ var capSchema = external_exports.bigint().positive();
88314
+ async function readTaskV2Limits(input2) {
88315
+ const read = async () => {
88316
+ const pin = getTrustedTasksV2Deployment(input2.chainId, {
88317
+ ...input2.trustedV2Deployments ? { overrides: input2.trustedV2Deployments } : {},
88318
+ ...input2.env ? { env: input2.env } : {},
88319
+ // Display and pre-check only; the signing path prints the override notice.
88320
+ notice: input2.onV2UntrustedOverride ?? (() => {
88321
+ })
88322
+ });
88323
+ const rpc = input2.rpcFor(input2.chainId);
88324
+ if (await rpc.getChainId() !== input2.chainId) throw new Error("RPC chain mismatch");
88325
+ const pool = input2.shape === "pool";
88326
+ const address10 = pool ? pin.bountyPoolFactoryV1 : pin.escrowFactoryV2;
88327
+ const abi2 = pool ? bountyPoolFactoryV1Abi : escrowFactoryV2Abi;
88328
+ const [feeBp, cap] = await Promise.all([
88329
+ rpc.readContract({ address: address10, abi: abi2, functionName: "feeBp" }),
88330
+ rpc.readContract({
88331
+ address: address10,
88332
+ abi: abi2,
88333
+ functionName: pool ? "maxPoolBudget" : "maxEscrowAmount"
88334
+ })
88335
+ ]);
88336
+ return {
88337
+ chainId: input2.chainId,
88338
+ shape: input2.shape,
88339
+ feeBp: feeBpSchema.parse(feeBp),
88340
+ maxBaseUnits: capSchema.parse(cap)
88341
+ };
88342
+ };
88343
+ let timer;
88344
+ try {
88345
+ return await Promise.race([
88346
+ read(),
88347
+ new Promise((resolve4) => {
88348
+ timer = setTimeout(() => resolve4(void 0), input2.timeoutMs ?? 5e3);
88349
+ })
88350
+ ]);
88351
+ } catch {
88352
+ return void 0;
88353
+ } finally {
88354
+ if (timer) clearTimeout(timer);
88355
+ }
88356
+ }
88357
+ function assertWithinTaskV2Limit(totalBaseUnits, limits, untouched = "Nothing was signed and no money moved.") {
88358
+ if (totalBaseUnits <= limits.maxBaseUnits) return;
88359
+ throw new TaskInputError(
88360
+ `The total of $${formatBaseUnitsUsd(totalBaseUnits)} USDC is above the live limit of $${formatBaseUnitsUsd(limits.maxBaseUnits)} USDC per ${limits.shape} on ${taskNetworkName(limits.chainId)}. ${untouched}`
88361
+ );
88362
+ }
88363
+
88182
88364
  // ../core/src/tasks/v2-plan-guard.ts
88183
88365
  var address5 = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u).transform((v) => getAddress(v));
88184
88366
  var hash5 = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/u).transform((v) => v.toLowerCase());
88185
88367
  var uint2 = external_exports.union([external_exports.bigint(), external_exports.number().int().nonnegative(), external_exports.string().regex(/^\d+$/u)]).transform(BigInt);
88186
88368
  var small = (max) => external_exports.union([external_exports.number(), external_exports.bigint()]).transform(Number).pipe(external_exports.number().int().min(0).max(max));
88187
- var feeBpSchema = small(2e3);
88369
+ var feeBpSchema2 = small(2e3);
88188
88370
  var escrowTermsSchema = external_exports.object({
88189
88371
  shape: small(1),
88190
88372
  poster: address5,
@@ -88196,7 +88378,7 @@ var escrowTermsSchema = external_exports.object({
88196
88378
  bountyDeadline: uint2,
88197
88379
  objectionWindow: uint2,
88198
88380
  workerBondBp: small(2e3),
88199
- feeBp: feeBpSchema,
88381
+ feeBp: feeBpSchema2,
88200
88382
  winners: small(255),
88201
88383
  rewardPerWinner: uint2
88202
88384
  });
@@ -88460,7 +88642,7 @@ function verifyActor(action, signer, poster, worker, verifier) {
88460
88642
  );
88461
88643
  }
88462
88644
  async function creationPolicy(rpc, pin, pool) {
88463
- const feeBp = feeBpSchema.parse(
88645
+ const feeBp = feeBpSchema2.parse(
88464
88646
  await v2Read(
88465
88647
  rpc,
88466
88648
  pool ? pin.bountyPoolFactoryV1 : pin.escrowFactoryV2,
@@ -88479,10 +88661,13 @@ async function verifyFundingDeadlines(rpc, contract, deadlines, timestamp) {
88479
88661
  `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.`
88480
88662
  );
88481
88663
  }
88482
- async function verifyV2Target(options, current, view, action, knownTarget) {
88664
+ async function verifyV2Target(options, current, view, action, knownTarget, fundingMined = false) {
88483
88665
  const operation = taskV2OperationResponseSchema.safeParse(current);
88484
88666
  const intent = taskV2IntentSchema.safeParse(current);
88485
- 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;
88667
+ const plan = operation.success ? operation.data.operation.plan : null;
88668
+ if (operation.success && !plan)
88669
+ return v2GuardFailure("The hosted operation carries no plan to verify.");
88670
+ const chainId = plan ? plan.chainId : intent.success ? intent.data.typedData.domain.chainId : external_exports.object({ chainId: external_exports.number().int().positive() }).parse(current).chainId;
88486
88671
  const binding = await options.pending.v2Target?.(view.workOrder.id);
88487
88672
  if (action.action === "bump-consent-nonce" && !binding)
88488
88673
  return v2GuardFailure("Revocation requires a locally accepted consent target binding.");
@@ -88514,11 +88699,8 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
88514
88699
  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);
88515
88700
  let creationArgs;
88516
88701
  let fresh;
88517
- if (action.action === "fund" && operation.success && same(operation.data.operation.plan.to, factory)) {
88518
- const decoded = decodeFunctionData({
88519
- abi: factoryAbi,
88520
- data: operation.data.operation.plan.data
88521
- });
88702
+ if (action.action === "fund" && plan && same(plan.to, factory)) {
88703
+ const decoded = decodeFunctionData({ abi: factoryAbi, data: plan.data });
88522
88704
  const names = pool ? ["createPool"] : ["createEscrow", "createAndFundWithAuthorization"];
88523
88705
  if (!names.includes(decoded.functionName))
88524
88706
  return v2GuardFailure("Unexpected V2 factory funding selector.");
@@ -88528,7 +88710,7 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
88528
88710
  verifyAcceptedCreation(options, view, pin, creationArgs, pool, chainId, fresh);
88529
88711
  candidate = await predict(creationArgs);
88530
88712
  }
88531
- if (action.action === "fund" && operation.success && operation.data.operation.plan.step === "v2-approve-usdc" && (!candidate || !await isRegistered(candidate))) {
88713
+ if (action.action === "fund" && plan?.step === "v2-approve-usdc" && (!candidate || !await isRegistered(candidate))) {
88532
88714
  fresh = await creationPolicy(rpc, pin, pool);
88533
88715
  creationArgs = acceptedCreationArgs(options, view, pin, chainId, fresh);
88534
88716
  verifyAcceptedCreation(options, view, pin, creationArgs, pool, chainId, fresh);
@@ -88544,7 +88726,7 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
88544
88726
  "The V2 target cannot be independently verified from this response. A registered target or verifiable funding creation terms are required."
88545
88727
  );
88546
88728
  if (!await isRegistered(candidate)) {
88547
- if (action.action !== "fund" || !operation.success || !creationArgs || !fresh)
88729
+ if (action.action !== "fund" || !plan || !creationArgs || !fresh)
88548
88730
  return v2GuardFailure("The V2 target is not registered by the locally pinned factory.");
88549
88731
  const expectedCreation = acceptedCreationArgs(options, view, pin, chainId, fresh);
88550
88732
  if (canon(creationArgs) !== canon(expectedCreation))
@@ -88596,7 +88778,7 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
88596
88778
  poster = address5.parse(await read("poster"));
88597
88779
  verifier = address5.parse(await read("verifier"));
88598
88780
  total = uint2.parse(await read("budget"));
88599
- feeBp = feeBpSchema.parse(await read("feeBp"));
88781
+ feeBp = feeBpSchema2.parse(await read("feeBp"));
88600
88782
  termsHash = hash5.parse(await read("termsHash"));
88601
88783
  creationArgs = [
88602
88784
  poster,
@@ -88660,7 +88842,7 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
88660
88842
  "The V2 target differs from the pinned factory's prediction for the requested order."
88661
88843
  );
88662
88844
  verifyBinding(candidate, termsHash);
88663
- if (action.action === "fund" && !pool && !bounty)
88845
+ if (action.action === "fund" && !pool && !bounty && !fundingMined)
88664
88846
  await verifyFundingDeadlines(
88665
88847
  rpc,
88666
88848
  candidate,
@@ -88764,6 +88946,7 @@ function acceptedV2WorkerBond(target, view) {
88764
88946
  }
88765
88947
  async function verifyV2Plan(target, op, action, pays, fundingAuthorization) {
88766
88948
  const plan = op.plan;
88949
+ if (!plan) return v2GuardFailure("The hosted operation carries no plan to verify.");
88767
88950
  if (plan.value !== "0" || plan.chainId !== target.chainId)
88768
88951
  return v2GuardFailure("V2 plan value or chain mismatch.");
88769
88952
  const authorizationArgs = fundingAuthorization ? [
@@ -89030,7 +89213,8 @@ function isTaskV2SecretAction(action) {
89030
89213
  return action.action === "commit-vote" || action.action === "reveal-vote";
89031
89214
  }
89032
89215
  function publicTaskV2Operation(op, secret = false) {
89033
- const reveal = secret || op.step === "v2-reveal-vote" || op.plan.step === "v2-reveal-vote" || op.plan.data.toLowerCase().startsWith(REVEAL_SELECTOR);
89216
+ const plan = op.plan;
89217
+ const reveal = secret || op.step === "v2-reveal-vote" || plan?.step === "v2-reveal-vote" || plan?.data.toLowerCase().startsWith(REVEAL_SELECTOR) === true;
89034
89218
  return {
89035
89219
  id: op.id,
89036
89220
  kind: op.kind,
@@ -89038,16 +89222,17 @@ function publicTaskV2Operation(op, secret = false) {
89038
89222
  step: op.step,
89039
89223
  expectedActor: op.expectedActor,
89040
89224
  transactionHash: op.transactionHash,
89041
- plan: {
89042
- version: op.plan.version,
89043
- operationId: op.plan.operationId,
89044
- step: op.plan.step,
89045
- chainId: op.plan.chainId,
89046
- network: op.plan.network,
89047
- from: op.plan.from,
89048
- to: op.plan.to,
89049
- data: reveal ? TASK_V2_REDACTED_CALLDATA : op.plan.data,
89050
- value: op.plan.value
89225
+ // Null once the transaction is submitted or confirmed: the API no longer returns the plan.
89226
+ plan: plan && {
89227
+ version: plan.version,
89228
+ operationId: plan.operationId,
89229
+ step: plan.step,
89230
+ chainId: plan.chainId,
89231
+ network: plan.network,
89232
+ from: plan.from,
89233
+ to: plan.to,
89234
+ data: reveal ? TASK_V2_REDACTED_CALLDATA : plan.data,
89235
+ value: plan.value
89051
89236
  }
89052
89237
  };
89053
89238
  }
@@ -89068,7 +89253,7 @@ var shownOperationSchema = external_exports.object({
89068
89253
  to: external_exports.string(),
89069
89254
  data: external_exports.string(),
89070
89255
  value: external_exports.literal("0")
89071
- })
89256
+ }).nullable()
89072
89257
  });
89073
89258
  function publicTaskV2OperationOf(value, secret = false) {
89074
89259
  const parsed = shownOperationSchema.safeParse(value);
@@ -89288,6 +89473,9 @@ function bufferedV2Gas(estimate) {
89288
89473
  var fail = (message) => {
89289
89474
  throw new TaskOperationError("invalid_response", message);
89290
89475
  };
89476
+ var balanceAbi = parseAbi(["function balanceOf(address account) view returns (uint256)"]);
89477
+ var PAID_NOW_ACTIONS = ["fund", "raise-dispute", "counter-evidence"];
89478
+ var RESERVING_ACTIONS = [...PAID_NOW_ACTIONS, "approve-bond"];
89291
89479
  async function taskUsesV2(context, id2) {
89292
89480
  if (!context.client.prepareV2) return false;
89293
89481
  const { workOrder } = await context.client.getOrder(id2);
@@ -89315,6 +89503,7 @@ async function executeTaskV2(context, input2) {
89315
89503
  }
89316
89504
  const saved = journal.preparedV2;
89317
89505
  if (saved) return saved;
89506
+ requireTasksAvailable(action.action, await readTasksReadiness(context.client));
89318
89507
  const result = await (input2.consent ? context.client.signV2(input2.id, input2.consent, journal) : context.client.prepareV2(input2.id, input2.write, journal));
89319
89508
  await context.pending?.bindPreparedV2?.(input2.id, verb, result);
89320
89509
  return result;
@@ -89348,17 +89537,76 @@ function createTaskV2Executor(options) {
89348
89537
  journal = { idempotencyKey: input2.preparationKey ?? randomUUID4(), inputs: action };
89349
89538
  await pending.putPreparation(input2.id, verb, journal);
89350
89539
  }
89351
- let current = taskV2PreparedSchema.parse(
89352
- input2.prepared ?? journal.preparedV2 ?? await (input2.consent ? sign2(input2.id, input2.consent, journal) : prepare(input2.id, input2.write, journal))
89353
- );
89354
89540
  if (!pending.bindPreparedV2) fail("Durable V2 preparation storage is unavailable.");
89355
- await pending.bindPreparedV2(input2.id, verb, current);
89541
+ const supplied = input2.prepared ?? journal.preparedV2;
89542
+ let current = supplied === void 0 ? void 0 : taskV2PreparedSchema.parse(supplied);
89543
+ if (current) await pending.bindPreparedV2(input2.id, verb, current);
89544
+ const finalStep = action.action === "approve-bond" ? "v2-approve-usdc" : `v2-${action.action}`;
89545
+ 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];
89546
+ const reservedForTask = (excludeReservationId) => taskReservedAtomic({
89547
+ ledgerPath: input2.ledgerPath,
89548
+ wallet: input2.wallet,
89549
+ taskKey: input2.id,
89550
+ now: now(),
89551
+ ...excludeReservationId === void 0 ? {} : { excludeReservationId }
89552
+ });
89553
+ const savedOperation = journal.operationId;
89554
+ const savedTransaction = savedOperation !== void 0 && (await Promise.all(allowedSteps.map((step2) => pending.get(savedOperation, step2)))).some(
89555
+ (entry) => entry !== void 0
89556
+ );
89557
+ const signedBefore = journal.signed === true;
89558
+ const started = savedTransaction || RESERVING_ACTIONS.includes(action.action) && (signedBefore || await reservedForTask() !== await reservedForTask(journal.idempotencyKey));
89559
+ const savedFinal = savedOperation === void 0 ? void 0 : await pending.get(savedOperation, finalStep);
89560
+ const mined = savedFinal && isAddressEqual(savedFinal.signer, account.address) && (await Promise.resolve().then(
89561
+ () => rpcFor(savedFinal.chainId).getTransactionReceipt({ hash: savedFinal.txHash })
89562
+ ).catch(() => void 0))?.status === "success" ? savedFinal : void 0;
89563
+ if (current && !started && action.action === "fund" && "kind" in current && current.kind === "eip712") {
89564
+ const end = external_exports.object({ validBefore: uint3 }).safeParse(taskV2IntentSchema.parse(current).typedData.message);
89565
+ if (end.success && BigInt(end.data.validBefore) * 1000n <= BigInt(now().getTime())) {
89566
+ await pending.completePreparation(input2.id, verb);
89567
+ journal = { idempotencyKey: randomUUID4(), inputs: action };
89568
+ await pending.putPreparation(input2.id, verb, journal);
89569
+ current = void 0;
89570
+ }
89571
+ }
89572
+ const readiness = await readTasksReadiness(client);
89573
+ if (!started)
89574
+ requireTasksAvailable(
89575
+ action.action,
89576
+ readiness,
89577
+ 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
89578
+ );
89579
+ if (!current) {
89580
+ current = taskV2PreparedSchema.parse(
89581
+ await (input2.consent ? sign2(input2.id, input2.consent, journal) : prepare(input2.id, input2.write, journal))
89582
+ );
89583
+ await pending.bindPreparedV2(input2.id, verb, current);
89584
+ }
89356
89585
  const view = await client.getOrder(input2.id);
89357
89586
  if (view.workOrder.id !== input2.id) fail("The money view belongs to another task.");
89358
89587
  const terms = view.workOrder.terms;
89359
89588
  const state = stateSchema.safeParse(view.workOrder.v2State);
89360
- const deployment = await client.deployment();
89361
- const target = await verifyV2Target(options, current, view, action);
89589
+ const resumed = taskV2OperationResponseSchema.safeParse(current);
89590
+ let resumedChainId;
89591
+ if (resumed.success && !resumed.data.operation.plan) {
89592
+ resumedChainId = (await pending.v2Target?.(input2.id))?.chainId ?? readiness?.chainId;
89593
+ if (resumedChainId === void 0)
89594
+ fail("The hosted operation carries no plan and its chain cannot be read.");
89595
+ }
89596
+ const target = await verifyV2Target(
89597
+ options,
89598
+ resumedChainId === void 0 ? current : { chainId: resumedChainId },
89599
+ view,
89600
+ action,
89601
+ void 0,
89602
+ mined !== void 0
89603
+ );
89604
+ if (mined && mined.chainId !== target.chainId)
89605
+ fail("The saved transaction is for another chain than the verified task.");
89606
+ if (readiness && target.chainId !== readiness.chainId)
89607
+ fail(
89608
+ `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."}`
89609
+ );
89362
89610
  if (state.success && (BigInt(state.data.totalBaseUnits) !== target.total || state.data.feeBp !== target.feeBp))
89363
89611
  v2GuardFailure("Hosted money snapshot differs from the verified V2 target.");
89364
89612
  let gross = 0n, pays = 0n;
@@ -89402,8 +89650,7 @@ function createTaskV2Executor(options) {
89402
89650
  else gross = total ?? 0n;
89403
89651
  feeBp = 0;
89404
89652
  } else if (action.action === "raise-dispute" || action.action === "counter-evidence") {
89405
- if (!state.success || !deployment.configured)
89406
- fail("Hosted dispute binding is unavailable.");
89653
+ if (!state.success) fail("Hosted dispute binding is unavailable.");
89407
89654
  pays = gross = await target.rpc.readContract({
89408
89655
  address: target.escrow,
89409
89656
  abi: escrowV2Abi,
@@ -89461,6 +89708,44 @@ function createTaskV2Executor(options) {
89461
89708
  }
89462
89709
  };
89463
89710
  await input2.onMoney?.(money2);
89711
+ if (action.action === "fund" && !started) {
89712
+ const cap = await v2Read(
89713
+ target.rpc,
89714
+ target.factory,
89715
+ target.pool ? bountyPoolFactoryV1Abi : escrowFactoryV2Abi,
89716
+ target.pool ? "maxPoolBudget" : "maxEscrowAmount"
89717
+ ).catch(() => void 0);
89718
+ if (typeof cap === "bigint" && cap > 0n)
89719
+ assertWithinTaskV2Limit(gross, {
89720
+ chainId: target.chainId,
89721
+ shape: target.pool ? "pool" : target.bounty ? "bounty" : "task",
89722
+ feeBp: target.feeBp,
89723
+ maxBaseUnits: cap
89724
+ });
89725
+ }
89726
+ if (pays > 0n && PAID_NOW_ACTIONS.includes(action.action) && !started) {
89727
+ const balance = await target.rpc.readContract({
89728
+ address: target.pin.usdc,
89729
+ abi: balanceAbi,
89730
+ functionName: "balanceOf",
89731
+ args: [account.address]
89732
+ }).catch(() => void 0);
89733
+ if (typeof balance === "bigint" && balance < pays)
89734
+ throw new TaskOperationError(
89735
+ "insufficient_usdc",
89736
+ `This step pays $${formatBaseUnitsUsd(pays)} USDC, but the wallet holds $${formatBaseUnitsUsd(balance)} on ${taskNetworkName(target.chainId)}. Nothing was signed and no money moved.`,
89737
+ void 0,
89738
+ progress
89739
+ );
89740
+ const gas = await Promise.resolve().then(() => target.rpc.getBalance({ address: account.address })).catch(() => void 0);
89741
+ if (gas === 0n)
89742
+ throw new TaskOperationError(
89743
+ "insufficient_gas",
89744
+ `The wallet holds no ETH on ${taskNetworkName(target.chainId)} to pay for the transaction. Nothing was signed and no money moved.`,
89745
+ void 0,
89746
+ progress
89747
+ );
89748
+ }
89464
89749
  const reservationKey = journal.idempotencyKey;
89465
89750
  const remaining2 = pays > 0n ? await escrowFundingDayRemainingAtomic({
89466
89751
  caps: input2.caps,
@@ -89476,11 +89761,11 @@ function createTaskV2Executor(options) {
89476
89761
  now: now(),
89477
89762
  excludeReservationId: reservationKey
89478
89763
  }) : 0n;
89479
- if (pays + alreadyReserved > taskPolicyAtomic(input2.policy.maxPerTaskUsd))
89764
+ if (!mined && pays + alreadyReserved > taskPolicyAtomic(input2.policy.maxPerTaskUsd))
89480
89765
  return { ok: false, reason: "policy.perTask", money: money2, ...progress };
89481
- if (pays > remaining2)
89766
+ if (!mined && pays > remaining2)
89482
89767
  return { ok: false, reason: "policy.perDay", money: money2, ...progress };
89483
- if (pays > taskPolicyAtomic(input2.policy.approveAboveUsd)) {
89768
+ if (!mined && pays > taskPolicyAtomic(input2.policy.approveAboveUsd)) {
89484
89769
  if (input2.approval && "ask" in input2.approval) {
89485
89770
  if (!await input2.approval.ask({
89486
89771
  money: taskMoney(pays, 0),
@@ -89516,13 +89801,24 @@ function createTaskV2Executor(options) {
89516
89801
  };
89517
89802
  let fundingAuthorization;
89518
89803
  try {
89804
+ if (mined && "kind" in current)
89805
+ current = taskV2OperationResponseSchema.parse(
89806
+ await operationCall(savedOperation, "recover", { step: finalStep }, key2())
89807
+ );
89519
89808
  if ("kind" in current && current.kind === "eip712") {
89520
89809
  const intent = taskV2IntentSchema.parse(current);
89521
89810
  const typed = intent.typedData;
89811
+ if (started && !savedTransaction && !signedBefore)
89812
+ requireTasksAvailable(
89813
+ action.action,
89814
+ readiness,
89815
+ "No new signature was made. An authorization signed earlier stays valid until it expires."
89816
+ );
89522
89817
  await verifyV2TypedData(target, intent, action, account.address, pays);
89523
89818
  await bindTarget();
89524
89819
  await beforeSign();
89525
89820
  const signature = await account.signTypedData(typed);
89821
+ await pending.markPreparationSigned?.(input2.id, verb);
89526
89822
  if (action.action === "fund")
89527
89823
  fundingAuthorization = { message: typed.message, signature };
89528
89824
  const response = await confirmSignature(input2.id, intent.operationId, signature, key2());
@@ -89548,8 +89844,6 @@ function createTaskV2Executor(options) {
89548
89844
  }
89549
89845
  let result = taskV2OperationResponseSchema.parse(current);
89550
89846
  const operationId = result.operation.id;
89551
- const finalStep = action.action === "approve-bond" ? "v2-approve-usdc" : `v2-${action.action}`;
89552
- 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];
89553
89847
  const validate7 = (value) => {
89554
89848
  if (value.orderId !== input2.id || value.operation.id !== operationId || !isAddressEqual(value.operation.expectedActor, account.address) || !allowedSteps.includes(value.operation.step))
89555
89849
  fail("Hosted operation does not match the requested task, wallet or action.");
@@ -89568,10 +89862,17 @@ function createTaskV2Executor(options) {
89568
89862
  fail("Hosted sequence moved backwards.");
89569
89863
  return { parsed, complete: !("scanComplete" in response) || response.scanComplete };
89570
89864
  };
89865
+ let waiting;
89571
89866
  for (let poll2 = 0; poll2 < 256; poll2++) {
89572
89867
  validate7(result);
89573
89868
  progress = { ...progress, operation: publicTaskV2Operation(result.operation, secret) };
89574
89869
  const op = result.operation;
89870
+ if (op.state !== "prepared" || waiting?.step !== op.step) waiting = void 0;
89871
+ if (op.state === "prepared" && op.plan) {
89872
+ const shown = canonicalJson(op.plan);
89873
+ if (waiting && waiting.plan !== shown) fail("Recovery changed the prepared plan.");
89874
+ waiting = { step: op.step, plan: shown };
89875
+ }
89575
89876
  if (op.state === "confirmed") {
89576
89877
  if (op.step !== finalStep)
89577
89878
  fail("An approval alone cannot complete the requested action.");
@@ -89601,14 +89902,26 @@ function createTaskV2Executor(options) {
89601
89902
  result = recovered.parsed;
89602
89903
  continue;
89603
89904
  }
89604
- if (canonicalJson(recovered.parsed.operation.plan) !== canonicalJson(op.plan))
89905
+ if (mined) {
89906
+ if (op.step !== finalStep)
89907
+ fail(
89908
+ "vAPI asks for an earlier step although the last step of this operation is mined. Nothing was signed."
89909
+ );
89910
+ result = (await call2("transaction", op.step, mined.txHash)).parsed;
89911
+ if (result.operation.state === "prepared") await sleep(1e3);
89912
+ continue;
89913
+ }
89914
+ const plan = recovered.parsed.operation.plan;
89915
+ if (!plan) return fail("The hosted operation is prepared but carries no plan to sign.");
89916
+ if (waiting && waiting.plan !== canonicalJson(plan))
89605
89917
  fail("Recovery changed the prepared plan.");
89606
- const plan = op.plan;
89607
- if (!deployment.configured || plan.chainId !== deployment.chainId)
89608
- fail("Hosted plan deployment mismatch.");
89918
+ waiting = void 0;
89919
+ const step2 = { ...op, plan };
89920
+ if (plan.chainId !== target.chainId)
89921
+ fail("The hosted plan names another chain than the verified task.");
89609
89922
  const refreshed = await verifyV2Target(
89610
89923
  options,
89611
- { orderId: input2.id, operation: op },
89924
+ { orderId: input2.id, operation: step2 },
89612
89925
  view,
89613
89926
  action,
89614
89927
  target.escrow
@@ -89616,7 +89929,7 @@ function createTaskV2Executor(options) {
89616
89929
  if (!isAddressEqual(refreshed.escrow, target.escrow))
89617
89930
  v2GuardFailure("The continuation changed the verified V2 target.");
89618
89931
  try {
89619
- await verifyV2Plan(refreshed, op, action, pays, fundingAuthorization);
89932
+ await verifyV2Plan(refreshed, step2, action, pays, fundingAuthorization);
89620
89933
  } catch (error61) {
89621
89934
  if (error61 instanceof TaskOperationError) throw error61;
89622
89935
  v2GuardFailure("Unknown V2 selector or malformed ABI arguments.");
@@ -89625,7 +89938,6 @@ function createTaskV2Executor(options) {
89625
89938
  if (await rpc.getChainId() !== plan.chainId) fail("Transaction chain mismatch.");
89626
89939
  await input2.beforeSigning?.();
89627
89940
  await bindTarget();
89628
- await beforeSign();
89629
89941
  const saved = await pending.withStepLock(
89630
89942
  op.id,
89631
89943
  op.step,
@@ -89640,8 +89952,15 @@ function createTaskV2Executor(options) {
89640
89952
  account.address
89641
89953
  ))
89642
89954
  fail("Saved transaction differs from the hosted plan.");
89955
+ await beforeSign();
89643
89956
  return existing;
89644
89957
  }
89958
+ if (started)
89959
+ requireTasksAvailable(
89960
+ action.action,
89961
+ readiness,
89962
+ "This step was not signed. Anything this operation signed earlier stands."
89963
+ );
89645
89964
  const nonce = Math.max(
89646
89965
  await rpc.getTransactionCount({ address: account.address, blockTag: "pending" }),
89647
89966
  await pending.nextNonce(plan.chainId, account.address)
@@ -89656,6 +89975,7 @@ function createTaskV2Executor(options) {
89656
89975
  nonce
89657
89976
  });
89658
89977
  if (request.gas === void 0) fail("The V2 transaction has no gas estimate.");
89978
+ await beforeSign();
89659
89979
  const raw = await account.signTransaction({
89660
89980
  ...request,
89661
89981
  gas: bufferedV2Gas(request.gas)
@@ -89760,7 +90080,7 @@ import { randomBytes as nodeRandomBytes } from "node:crypto";
89760
90080
 
89761
90081
  // ../core/src/tasks/ballots.ts
89762
90082
  import { readdir as readdir7, readFile as readFile19 } from "node:fs/promises";
89763
- import { join as join16 } from "node:path";
90083
+ import { join as join17 } from "node:path";
89764
90084
  var address6 = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u).transform((v) => v.toLowerCase());
89765
90085
  var hash6 = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/u).transform((v) => v.toLowerCase());
89766
90086
  var TASK_V2_VOTE_OUTCOMES = ["worker", "poster", "split"];
@@ -89780,7 +90100,7 @@ var taskV2BallotSchema = external_exports.strictObject({
89780
90100
  createdAt: external_exports.iso.datetime()
89781
90101
  });
89782
90102
  function taskV2BallotDirectory(home, key2) {
89783
- return join16(
90103
+ return join17(
89784
90104
  home,
89785
90105
  "tasks",
89786
90106
  "ballots",
@@ -89790,7 +90110,7 @@ function taskV2BallotDirectory(home, key2) {
89790
90110
  );
89791
90111
  }
89792
90112
  function taskV2BallotPath(home, key2) {
89793
- return join16(taskV2BallotDirectory(home, key2), `${hash6.parse(key2.commitment)}.json`);
90113
+ return join17(taskV2BallotDirectory(home, key2), `${hash6.parse(key2.commitment)}.json`);
89794
90114
  }
89795
90115
  async function writeTaskV2Ballot(home, ballot) {
89796
90116
  const parsed = taskV2BallotSchema.parse(ballot);
@@ -89826,7 +90146,7 @@ async function listTaskV2Ballots(home, key2) {
89826
90146
  }
89827
90147
  const ballots = [];
89828
90148
  for (const name of names.filter((n) => /^0x[0-9a-f]{64}\.json$/u.test(n)).sort()) {
89829
- const ballot = await readBallotFile(join16(directory, name));
90149
+ const ballot = await readBallotFile(join17(directory, name));
89830
90150
  if (ballot && `${ballot.commitment}.json` === name) ballots.push(ballot);
89831
90151
  }
89832
90152
  return ballots.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
@@ -89893,13 +90213,16 @@ function createTaskV2Jury(options) {
89893
90213
  };
89894
90214
  async function voteCase(id2, i2) {
89895
90215
  taskV2IndexSchema.parse(i2);
89896
- const deployment = await client.deployment();
89897
- if (!deployment.configured)
89898
- throw new TaskOperationError("v2_resolver_unavailable", "Hosted Tasks V2 is not configured.");
90216
+ const chainId = (await readTasksReadiness(client))?.chainId ?? (await options.pending.v2Target?.(id2))?.chainId;
90217
+ if (chainId === void 0)
90218
+ throw new TaskOperationError(
90219
+ "v2_resolver_unavailable",
90220
+ "vAPI's Tasks status could not be read, so the chain of this dispute is unknown. Nothing was signed. Try again later."
90221
+ );
89899
90222
  const view = await client.getOrder(id2);
89900
90223
  if (view.workOrder.id !== id2)
89901
90224
  throw new TaskOperationError("invalid_response", "The order view belongs to another task.");
89902
- const target = await verifyV2Target(options, { chainId: deployment.chainId }, view, {
90225
+ const target = await verifyV2Target(options, { chainId }, view, {
89903
90226
  action: "open-jury",
89904
90227
  i: i2
89905
90228
  });
@@ -90310,7 +90633,9 @@ function createTasksChain(options) {
90310
90633
  });
90311
90634
  async function deployment() {
90312
90635
  const value = await client.deployment();
90313
- if (!value.configured || value.network !== `eip155:${value.chainId}`)
90636
+ if (!value.configured)
90637
+ throw new TasksValidationError(tasksUnavailableError(value.chainId).message);
90638
+ if (value.network !== `eip155:${value.chainId}`)
90314
90639
  throw new TasksValidationError("The Tasks chain deployment is unavailable.");
90315
90640
  if (!getTrustedTasksFactory(value.chainId, options.trustedFactories))
90316
90641
  throw new TasksChainError(
@@ -91265,7 +91590,7 @@ function createTasksRpcFor(config2, options = {}) {
91265
91590
 
91266
91591
  // ../core/src/tasks/pending-transactions.ts
91267
91592
  import { readFile as readFile20 } from "node:fs/promises";
91268
- import { join as join17 } from "node:path";
91593
+ import { join as join18 } from "node:path";
91269
91594
  var hex4 = external_exports.string().regex(/^0x(?:[0-9a-fA-F]{2})+$/).transform((v) => v);
91270
91595
  var hash8 = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/).transform((v) => v);
91271
91596
  var step = external_exports.union([
@@ -91330,7 +91655,8 @@ var stateSchema2 = external_exports.object({
91330
91655
  idempotencyKey: external_exports.uuid(),
91331
91656
  inputs: external_exports.unknown(),
91332
91657
  operationId: external_exports.uuid().optional(),
91333
- preparedV2: taskV2PreparedSchema.optional()
91658
+ preparedV2: taskV2PreparedSchema.optional(),
91659
+ signed: external_exports.boolean().optional()
91334
91660
  }).strict()
91335
91661
  ).default({})
91336
91662
  }).strict();
@@ -91354,7 +91680,7 @@ function validCheckpointStep(storedStep, response) {
91354
91680
  }[response.operation.kind];
91355
91681
  }
91356
91682
  function createPendingTransactions(home) {
91357
- const path = join17(home, "tasks", "pending.json");
91683
+ const path = join18(home, "tasks", "pending.json");
91358
91684
  const lockPath = `${path}.lock`;
91359
91685
  const read = async () => {
91360
91686
  try {
@@ -91441,7 +91767,7 @@ function createPendingTransactions(home) {
91441
91767
  },
91442
91768
  withStepLock(operationId, step2, fn) {
91443
91769
  return withFileLock(
91444
- join17(
91770
+ join18(
91445
91771
  home,
91446
91772
  "tasks",
91447
91773
  `step-${encodeURIComponent(operationId)}-${encodeURIComponent(step2)}.lock`
@@ -91453,13 +91779,13 @@ function createPendingTransactions(home) {
91453
91779
  external_exports.number().int().positive().parse(chainId);
91454
91780
  address8.parse(signer);
91455
91781
  return withFileLock(
91456
- join17(home, "tasks", `signer-${chainId}-${signer.toLowerCase()}.lock`),
91782
+ join18(home, "tasks", `signer-${chainId}-${signer.toLowerCase()}.lock`),
91457
91783
  fn
91458
91784
  );
91459
91785
  },
91460
91786
  withFundingLock(milestoneId2, fn) {
91461
91787
  milestoneKey(milestoneId2);
91462
- return withFileLock(join17(home, "tasks", `fund-${milestoneId2}.lock`), fn);
91788
+ return withFileLock(join18(home, "tasks", `fund-${milestoneId2}.lock`), fn);
91463
91789
  },
91464
91790
  async nextNonce(chainId, signer) {
91465
91791
  external_exports.number().int().positive().parse(chainId);
@@ -91520,7 +91846,8 @@ function createPendingTransactions(home) {
91520
91846
  idempotencyKey: external_exports.uuid(),
91521
91847
  inputs: external_exports.unknown(),
91522
91848
  operationId: external_exports.uuid().optional(),
91523
- preparedV2: taskV2PreparedSchema.optional()
91849
+ preparedV2: taskV2PreparedSchema.optional(),
91850
+ signed: external_exports.boolean().optional()
91524
91851
  }).strict().parse(preparation);
91525
91852
  const existing = state.preparations[key2];
91526
91853
  if (existing && (existing.idempotencyKey !== parsed.idempotencyKey || canonicalJson(existing.inputs) !== canonicalJson(parsed.inputs)))
@@ -91562,6 +91889,14 @@ function createPendingTransactions(home) {
91562
91889
  }
91563
91890
  });
91564
91891
  },
91892
+ async markPreparationSigned(milestoneId2, verb) {
91893
+ await locked(async (state) => {
91894
+ const existing = state.preparations[preparationKey(milestoneId2, verb)];
91895
+ if (!existing || existing.signed) return;
91896
+ existing.signed = true;
91897
+ await save(state);
91898
+ });
91899
+ },
91565
91900
  async completePreparation(milestoneId2, verb) {
91566
91901
  await locked(async (state) => {
91567
91902
  const key2 = preparationKey(milestoneId2, verb);
@@ -91701,7 +92036,7 @@ function validateAmount(amountUsd) {
91701
92036
  // ../core/src/tasks/funding-attempts.ts
91702
92037
  import { createHash as createHash5 } from "node:crypto";
91703
92038
  import { readFile as readFile21, unlink as unlink13 } from "node:fs/promises";
91704
- import { dirname as dirname10, join as join18 } from "node:path";
92039
+ import { dirname as dirname10, join as join19 } from "node:path";
91705
92040
  var coordinates = external_exports.object({
91706
92041
  network: external_exports.string().regex(/^eip155:[1-9][0-9]*$/u),
91707
92042
  asset: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u),
@@ -91729,7 +92064,7 @@ var attemptSchema = external_exports.object({
91729
92064
  );
91730
92065
  async function withFundingAttempt(input2, operation) {
91731
92066
  const key2 = createHash5("sha256").update(`${input2.taskId}:${input2.milestoneId}`).digest("hex");
91732
- const path = join18(dirname10(input2.ledgerPath), "tasks", `funding-${key2}.json`);
92067
+ const path = join19(dirname10(input2.ledgerPath), "tasks", `funding-${key2}.json`);
91733
92068
  return withFileLock(
91734
92069
  `${path}.lock`,
91735
92070
  async () => {
@@ -92509,7 +92844,14 @@ async function postTask(context, input2) {
92509
92844
  "The Tasks deployment is unavailable, so the market network cannot be selected."
92510
92845
  );
92511
92846
  }
92512
- const feeBp = parseFeeBp(deployment);
92847
+ if (input2.fund)
92848
+ requireTasksAvailable("fund", deployment, "Nothing was posted or signed and no money moved.");
92849
+ const declared = input2.order;
92850
+ const shape = declared.shape ?? (input2.intake === "submissions" ? "bounty" : "task");
92851
+ const total = input2.amount * BigInt(shape === "bounty" ? declared.bounty?.winners ?? input2.maxAwards ?? 1 : 1);
92852
+ const limits = typeof deployment.chainId === "number" ? await context.limitsV2?.(deployment.chainId, shape).catch(() => void 0) : void 0;
92853
+ if (limits) assertWithinTaskV2Limit(total, limits, "Nothing was posted and no money moved.");
92854
+ const feeBp = limits?.feeBp ?? parseFeeBp(deployment);
92513
92855
  const feeUnavailable = feeBp === null;
92514
92856
  if (feeUnavailable) input2.onFeeUnavailable?.();
92515
92857
  const money2 = taskMoney(input2.amount, feeBp);
@@ -92588,7 +92930,11 @@ async function proposeTask(context, input2) {
92588
92930
  context
92589
92931
  );
92590
92932
  if (!deployment.configured)
92591
- throw new TaskOperationError("not_available", "Task escrow deployment is unavailable.");
92933
+ throw tasksUnavailableError(
92934
+ deployment.chainId,
92935
+ "No proposal was signed or sent.",
92936
+ "not_available"
92937
+ );
92592
92938
  const account = await input2.unlock();
92593
92939
  const terms = {
92594
92940
  title: workOrder.title,
@@ -92669,7 +93015,11 @@ async function submitTask(context, input2) {
92669
93015
  context
92670
93016
  );
92671
93017
  if (!deployment.configured)
92672
- throw new TaskOperationError("not_available", "Task escrow deployment is unavailable.");
93018
+ throw tasksUnavailableError(
93019
+ deployment.chainId,
93020
+ "No entry was signed or sent.",
93021
+ "not_available"
93022
+ );
92673
93023
  if (task.amount === null) {
92674
93024
  throw new TaskInputError("Task amount is unavailable.");
92675
93025
  }
@@ -93169,6 +93519,9 @@ async function resolveUnmatchedTaskOperation(context, input2) {
93169
93519
  }
93170
93520
 
93171
93521
  // ../core/src/tasks/post-options.ts
93522
+ var TASK_POST_DEADLINE_LEAD_MS = 3 * 36e5;
93523
+ var TASK_POST_DEADLINE_MARGIN_MS = 6e4;
93524
+ 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.";
93172
93525
  function positive(text, name) {
93173
93526
  if (text === void 0) throw new TaskInputError(`${name} is required.`);
93174
93527
  try {
@@ -93266,17 +93619,16 @@ function prepareTaskPost(input2, now) {
93266
93619
  "An open pool requires --open-check allowlist|invite (configure participants separately)."
93267
93620
  );
93268
93621
  } else {
93269
- if (!input2.milestones?.length && duration3 < 36e5)
93270
- throw new TaskInputError(
93271
- "Task deadlines must leave at least one hour for work before award."
93272
- );
93622
+ 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;
93623
+ if (!input2.milestones?.length && duration3 < lead)
93624
+ throw new TaskInputError(`Task deadlines ${TASK_DEADLINE_TOO_SOON}`);
93273
93625
  const sum = input2.milestones?.reduce((total, item) => total + BigInt(item.amountBaseUnits), 0n);
93274
93626
  amount4 = input2.amountUsd === void 0 && sum !== void 0 ? sum : positive(input2.amountUsd, "--amount");
93275
93627
  if (sum !== void 0 && sum !== amount4)
93276
93628
  throw new TaskInputError("Milestone amounts must sum to --amount.");
93277
- if (input2.milestones?.some((item) => Date.parse(item.deadlineAt) - now.getTime() < 36e5))
93629
+ if (input2.milestones?.some((item) => Date.parse(item.deadlineAt) - now.getTime() < lead))
93278
93630
  throw new TaskInputError(
93279
- "Milestone deadlines must leave at least one hour for work; creation and funding also check the verified MIN_WORK_TIME against the chain clock."
93631
+ `Milestone deadlines ${TASK_DEADLINE_TOO_SOON} Creation and funding also check the contract's MIN_WORK_TIME against the chain clock.`
93280
93632
  );
93281
93633
  }
93282
93634
  if (input2.amountUsd !== void 0 && positive(input2.amountUsd, "--amount") !== amount4)
@@ -94690,7 +95042,7 @@ function csvCell(value) {
94690
95042
  // ../core/src/swarm-capital.ts
94691
95043
  import { createHash as createHash6, randomBytes as randomBytes16 } from "node:crypto";
94692
95044
  import { readFile as readFile24, unlink as unlink14 } from "node:fs/promises";
94693
- import { join as join20 } from "node:path";
95045
+ import { join as join21 } from "node:path";
94694
95046
 
94695
95047
  // ../core/src/payment-warning.ts
94696
95048
  var PAYMENT_WARNING_CODES = [
@@ -94707,7 +95059,7 @@ var PAYMENT_WARNING_CODES = [
94707
95059
 
94708
95060
  // ../core/src/swarm-workers.ts
94709
95061
  import { readFile as readFile23, readdir as readdir8 } from "node:fs/promises";
94710
- import { join as join19 } from "node:path";
95062
+ import { join as join20 } from "node:path";
94711
95063
  var runSchema = external_exports.object({
94712
95064
  v: external_exports.literal(1),
94713
95065
  runId: external_exports.string(),
@@ -94737,7 +95089,7 @@ var sidecarSchema = external_exports.object({
94737
95089
  state: external_exports.string().optional()
94738
95090
  });
94739
95091
  async function assertSwarmWorkersStopped(home, swarm) {
94740
- const directory = join19(home, "runs");
95092
+ const directory = join20(home, "runs");
94741
95093
  let files;
94742
95094
  try {
94743
95095
  files = await readdir8(directory);
@@ -94753,7 +95105,7 @@ async function assertSwarmWorkersStopped(home, swarm) {
94753
95105
  for (const file2 of files.sort()) {
94754
95106
  const match = /^(run_[0-9a-f]{24})\.json$/u.exec(file2);
94755
95107
  if (match === null) continue;
94756
- const value = await readWorkerFile(join19(directory, file2));
95108
+ const value = await readWorkerFile(join20(directory, file2));
94757
95109
  if (value === void 0) continue;
94758
95110
  const parsed = runSchema.safeParse(value);
94759
95111
  if (!parsed.success || parsed.data.runId !== match[1]) {
@@ -94775,7 +95127,7 @@ async function assertSwarmWorkersStopped(home, swarm) {
94775
95127
  for (const file2 of files) {
94776
95128
  const match = /^(run_[0-9a-f]{24})\.railway\.json$/u.exec(file2);
94777
95129
  if (match === null) continue;
94778
- const value = await readWorkerFile(join19(directory, file2));
95130
+ const value = await readWorkerFile(join20(directory, file2));
94779
95131
  if (value === void 0) continue;
94780
95132
  const parsed = sidecarSchema.safeParse(value);
94781
95133
  if (!parsed.success) {
@@ -95772,13 +96124,13 @@ function runRecordMovementId(value) {
95772
96124
  return parsed.data;
95773
96125
  }
95774
96126
  function treasuryRequestRecordPath(home, movementId) {
95775
- return join20(home, "runs", "requests", `${movementId}.json`);
96127
+ return join21(home, "runs", "requests", `${movementId}.json`);
95776
96128
  }
95777
96129
  function delegationRecordPath(home, movementId) {
95778
- return join20(home, "runs", "delegations", `${movementId}.json`);
96130
+ return join21(home, "runs", "delegations", `${movementId}.json`);
95779
96131
  }
95780
96132
  function legacyFundingProgressPath(home, name) {
95781
- return join20(home, "swarms", `.${name}.funding`);
96133
+ return join21(home, "swarms", `.${name}.funding`);
95782
96134
  }
95783
96135
  async function readLegacyFundingProgress(home, name) {
95784
96136
  try {
@@ -96428,7 +96780,7 @@ async function removeMemberLocked(home, swarm, account) {
96428
96780
  }
96429
96781
 
96430
96782
  // ../core/src/status.ts
96431
- import { join as join21 } from "node:path";
96783
+ import { join as join22 } from "node:path";
96432
96784
  var STATUS_TIMEOUT_MS = 2e3;
96433
96785
  async function buildStatus(deps) {
96434
96786
  const timers = deps.timers ?? { setTimeout, clearTimeout };
@@ -96484,7 +96836,7 @@ function formatUsdAmount(value) {
96484
96836
  }
96485
96837
  async function readVaultStatus(deps) {
96486
96838
  const store = deps.secrets.description.replace(/^the /u, "");
96487
- const path = join21(deps.home, "vault.json");
96839
+ const path = join22(deps.home, "vault.json");
96488
96840
  let file2;
96489
96841
  try {
96490
96842
  file2 = await readVaultFileUnlocked(path);
@@ -96918,7 +97270,7 @@ function isRecord4(value) {
96918
97270
 
96919
97271
  // ../core/src/vault-setup.ts
96920
97272
  import { rm as rm2 } from "node:fs/promises";
96921
- import { join as join22 } from "node:path";
97273
+ import { join as join23 } from "node:path";
96922
97274
  async function createVault2(home, options) {
96923
97275
  if (options.password === "") {
96924
97276
  throw new KeystoreError("A password cannot be empty.");
@@ -96930,7 +97282,7 @@ async function createVault2(home, options) {
96930
97282
  const hadDeviceKey = options.password !== void 0 && await options.secrets.has(VAULT_KEY_ACCOUNT);
96931
97283
  await store.createEmptyVault();
96932
97284
  if (options.password !== void 0) {
96933
- const path = join22(home, "vault.json");
97285
+ const path = join23(home, "vault.json");
96934
97286
  try {
96935
97287
  await protectVault({
96936
97288
  path,
@@ -97070,7 +97422,7 @@ function output2(io, json2, value, human) {
97070
97422
  }
97071
97423
 
97072
97424
  // ../cli/src/wallet-session.ts
97073
- import { join as join23 } from "node:path";
97425
+ import { join as join24 } from "node:path";
97074
97426
 
97075
97427
  // ../cli/src/args.ts
97076
97428
  var UsageError = class extends Error {
@@ -97319,7 +97671,7 @@ async function confirmWalletName(name, prompt, refusal, dependencies) {
97319
97671
  if (typed.trim() !== name) throw new KeystoreError(refusal);
97320
97672
  }
97321
97673
  async function deviceVaultKey(store, dependencies) {
97322
- const path = join23(store.home, "vault.json");
97674
+ const path = join24(store.home, "vault.json");
97323
97675
  const metadata = await readVaultFileUnlocked(path);
97324
97676
  const secrets = getSecretStore(dependencies);
97325
97677
  const key2 = metadata.protected ? await unlockProtectedVault({
@@ -100521,7 +100873,7 @@ function exactPriceFact(value) {
100521
100873
 
100522
100874
  // ../mcp/src/agent/runtime.ts
100523
100875
  import { mkdir as mkdir17, readFile as readFile26, readdir as readdir9, rm as rm3 } from "node:fs/promises";
100524
- import { join as join24 } from "node:path";
100876
+ import { join as join25 } from "node:path";
100525
100877
 
100526
100878
  // ../mcp/src/agent/run.ts
100527
100879
  var loopSearchResultSchema = external_exports.array(
@@ -101860,19 +102212,19 @@ var runRecordSchema = external_exports.strictObject({
101860
102212
  }
101861
102213
  );
101862
102214
  function runsDirectory(home) {
101863
- return join24(home, "runs");
102215
+ return join25(home, "runs");
101864
102216
  }
101865
102217
  function runRecordPath(home, runId) {
101866
102218
  assertRunId(runId);
101867
- return join24(runsDirectory(home), `${runId}.json`);
102219
+ return join25(runsDirectory(home), `${runId}.json`);
101868
102220
  }
101869
102221
  function runLogPath(home, runId) {
101870
102222
  assertRunId(runId);
101871
- return join24(runsDirectory(home), `${runId}.log`);
102223
+ return join25(runsDirectory(home), `${runId}.log`);
101872
102224
  }
101873
102225
  function runResultPath(home, runId) {
101874
102226
  assertRunId(runId);
101875
- return join24(runsDirectory(home), `${runId}.result.json`);
102227
+ return join25(runsDirectory(home), `${runId}.result.json`);
101876
102228
  }
101877
102229
  async function writeRunRecord(home, record3) {
101878
102230
  const path = runRecordPath(home, record3.runId);
@@ -101903,7 +102255,7 @@ async function listRunRecords(home, filter = {}) {
101903
102255
  if (match === null) continue;
101904
102256
  try {
101905
102257
  const record3 = runRecordSchema.parse(
101906
- JSON.parse(await readFile26(join24(runsDirectory(home), file2), "utf8"))
102258
+ JSON.parse(await readFile26(join25(runsDirectory(home), file2), "utf8"))
101907
102259
  );
101908
102260
  if (record3.runId !== match[1]) continue;
101909
102261
  if (filter.swarm !== void 0 && record3.member.swarm !== filter.swarm) continue;
@@ -102282,7 +102634,7 @@ async function stopRun(args) {
102282
102634
  }
102283
102635
  }
102284
102636
  function memberRunLockPath(home, account) {
102285
- return join24(runsDirectory(home), `.member-${account}.lock`);
102637
+ return join25(runsDirectory(home), `.member-${account}.lock`);
102286
102638
  }
102287
102639
  async function withMemberRunLock(home, account, operation) {
102288
102640
  if (!WALLET_NAME_PATTERN.test(account))
@@ -103701,6 +104053,11 @@ function createTasksTools(options) {
103701
104053
  const client = typeof injected === "function" ? injected(clientOptions) : injected ?? createHostedTasksClient(clientOptions);
103702
104054
  return {
103703
104055
  client,
104056
+ limitsV2: (async (chainId, shape) => readTaskV2Limits({
104057
+ chainId,
104058
+ shape,
104059
+ rpcFor: options.rpcFor ?? createTasksRpcFor(await loadConfig(getVapiPaths(home).config), { fetch: guardedFetch2 })
104060
+ })),
103704
104061
  chain: options.chain ?? (selected === void 0 ? missingTasksChain : lazyTasksChain(async () => {
103705
104062
  const { account } = await options.session.payment(selected.name);
103706
104063
  const config2 = await loadConfig(getVapiPaths(home).config);
@@ -106765,7 +107122,7 @@ function assertKeyMatchesAddress(bundle) {
106765
107122
  }
106766
107123
 
106767
107124
  // ../cli/src/vault.ts
106768
- import { join as join29 } from "node:path";
107125
+ import { join as join30 } from "node:path";
106769
107126
 
106770
107127
  // ../cli/src/balance-reader.ts
106771
107128
  function baseUsdcBalanceReader(config2, dependencies) {
@@ -106789,10 +107146,10 @@ function baseUsdcBalanceReader(config2, dependencies) {
106789
107146
  }
106790
107147
 
106791
107148
  // ../cli/src/cloud-backup.ts
106792
- import { join as join27 } from "node:path";
107149
+ import { join as join28 } from "node:path";
106793
107150
 
106794
107151
  // ../core/src/cloud-backup.ts
106795
- import { join as join26 } from "node:path";
107152
+ import { join as join27 } from "node:path";
106796
107153
 
106797
107154
  // ../core/src/backup.ts
106798
107155
  import {
@@ -106819,7 +107176,7 @@ import {
106819
107176
  readdir as readdir10,
106820
107177
  rm as rm4
106821
107178
  } from "node:fs/promises";
106822
- import { dirname as dirname12, join as join25 } from "node:path";
107179
+ import { dirname as dirname12, join as join26 } from "node:path";
106823
107180
  var ERROR_MESSAGES = {
106824
107181
  backup_too_large: "Backup envelope exceeds 65,536 bytes.",
106825
107182
  backup_open_failed: "Unable to open backup.",
@@ -107297,7 +107654,7 @@ async function exportBackupSource(options) {
107297
107654
  var BackupSnapshotChangedError = class extends Error {
107298
107655
  };
107299
107656
  async function exportBackupSourceAttempt(options, networks) {
107300
- const path = join25(options.store.home, "vault.json");
107657
+ const path = join26(options.store.home, "vault.json");
107301
107658
  const { phrase, file: file2, accounts } = await withVaultLock(path, async () => {
107302
107659
  const [phrase2, vault, file3] = await Promise.all([
107303
107660
  exportVaultPhrase({ path, key: options.vaultKey }),
@@ -107433,16 +107790,16 @@ async function restoreBackupPlaintext(options) {
107433
107790
  } catch {
107434
107791
  throw new BackupError("backup_invalid_input");
107435
107792
  }
107436
- const vaultPath2 = join25(options.home, "vault.json");
107437
- const registryPath = join25(options.home, "wallets.json");
107793
+ const vaultPath2 = join26(options.home, "vault.json");
107794
+ const registryPath = join26(options.home, "wallets.json");
107438
107795
  let stagingHome;
107439
107796
  let beforePublishError;
107440
107797
  let afterPublishError;
107441
107798
  try {
107442
107799
  await mkdir18(options.home, { recursive: true, mode: 448 });
107443
- stagingHome = await mkdtemp(join25(options.home, ".backup-restore-"));
107444
- const stagedVaultPath = join25(stagingHome, "vault.json");
107445
- const stagedRegistryPath = join25(stagingHome, "wallets.json");
107800
+ stagingHome = await mkdtemp(join26(options.home, ".backup-restore-"));
107801
+ const stagedVaultPath = join26(stagingHome, "vault.json");
107802
+ const stagedRegistryPath = join26(stagingHome, "wallets.json");
107446
107803
  await createVault({
107447
107804
  path: stagedVaultPath,
107448
107805
  key: options.vaultKey,
@@ -107501,7 +107858,7 @@ async function restoreBackupPlaintext(options) {
107501
107858
  protected: plaintext.protected,
107502
107859
  networks: [...plaintext.registry.networks]
107503
107860
  };
107504
- const markerPath = join25(options.home, RESTORE_MARKER_FILE);
107861
+ const markerPath = join26(options.home, RESTORE_MARKER_FILE);
107505
107862
  const fingerprint = restoreFingerprint(
107506
107863
  plaintext,
107507
107864
  stagedV2?.restoreDevice ?? options.device,
@@ -107712,13 +108069,13 @@ async function stageV2Restore(options) {
107712
108069
  }
107713
108070
  const agents = [];
107714
108071
  for (const profile of validAgents) {
107715
- const stagedPath = join25(options.stagingHome, "agents", `${profile.name}.json`);
108072
+ const stagedPath = join26(options.stagingHome, "agents", `${profile.name}.json`);
107716
108073
  if (await stageRestoreBytes(stagedPath, prettyJson(profile))) {
107717
108074
  agents.push({
107718
108075
  kind: "agent",
107719
108076
  name: profile.name,
107720
108077
  stagedPath,
107721
- targetPath: join25(options.home, "agents", `${profile.name}.json`)
108078
+ targetPath: join26(options.home, "agents", `${profile.name}.json`)
107722
108079
  });
107723
108080
  } else {
107724
108081
  skipped2.push({ kind: "agent", name: profile.name, reason: "write_failed" });
@@ -107738,13 +108095,13 @@ async function stageV2Restore(options) {
107738
108095
  if (restoreDevice !== void 0) {
107739
108096
  for (const value of validSwarms) {
107740
108097
  const swarm = swarmFileSchema.parse({ ...value, device: restoreDevice });
107741
- const stagedPath = join25(options.stagingHome, "swarms", `${swarm.name}.json`);
108098
+ const stagedPath = join26(options.stagingHome, "swarms", `${swarm.name}.json`);
107742
108099
  if (await stageRestoreBytes(stagedPath, prettyJson(swarm))) {
107743
108100
  swarms.push({
107744
108101
  kind: "swarm",
107745
108102
  name: swarm.name,
107746
108103
  stagedPath,
107747
- targetPath: join25(options.home, "swarms", `${swarm.name}.json`)
108104
+ targetPath: join26(options.home, "swarms", `${swarm.name}.json`)
107748
108105
  });
107749
108106
  } else {
107750
108107
  skipped2.push({ kind: "swarm", name: swarm.name, reason: "write_failed" });
@@ -107754,13 +108111,13 @@ async function stageV2Restore(options) {
107754
108111
  const movements = [];
107755
108112
  for (const movement of validMovements) {
107756
108113
  const restored = reconcileRestoredMovement(movement, assumedReceiptKeys);
107757
- const stagedPath = join25(options.stagingHome, "movements", `${restored.id}.json`);
108114
+ const stagedPath = join26(options.stagingHome, "movements", `${restored.id}.json`);
107758
108115
  if (await stageRestoreBytes(stagedPath, serializeMovement(restored))) {
107759
108116
  movements.push({
107760
108117
  kind: "movement",
107761
108118
  name: restored.id,
107762
108119
  stagedPath,
107763
- targetPath: join25(options.home, "movements", `${restored.id}.json`),
108120
+ targetPath: join26(options.home, "movements", `${restored.id}.json`),
107764
108121
  movement: restored
107765
108122
  });
107766
108123
  } else {
@@ -107919,7 +108276,7 @@ async function reconcilePublishedMovements(staged, home, requireDurableSafety =
107919
108276
  const unjournaledKeys = new Set([...signedKeys].filter((key2) => !journaledKeys.has(key2)));
107920
108277
  let files;
107921
108278
  try {
107922
- files = await readdir10(join25(home, "movements"));
108279
+ files = await readdir10(join26(home, "movements"));
107923
108280
  } catch (error61) {
107924
108281
  if (isMissingFile4(error61)) return;
107925
108282
  if (requireDurableSafety && unjournaledKeys.size > 0) throw error61;
@@ -108828,7 +109185,7 @@ async function uploadBackupLocked(options, signal) {
108828
109185
  try {
108829
109186
  let vaultFile;
108830
109187
  try {
108831
- vaultFile = await readVaultFileUnlocked(join26(options.store.home, "vault.json"));
109188
+ vaultFile = await readVaultFileUnlocked(join27(options.store.home, "vault.json"));
108832
109189
  } catch (error61) {
108833
109190
  if (error61 instanceof VaultError && error61.code === "not_found") {
108834
109191
  return { status: "skipped", reason: "no_vault" };
@@ -108837,7 +109194,7 @@ async function uploadBackupLocked(options, signal) {
108837
109194
  }
108838
109195
  try {
108839
109196
  vaultKey = vaultFile.protected ? await unlockProtectedVault({
108840
- path: join26(options.store.home, "vault.json"),
109197
+ path: join27(options.store.home, "vault.json"),
108841
109198
  secrets: options.secrets,
108842
109199
  env: options.env,
108843
109200
  ...options.now === void 0 ? {} : { now: options.now }
@@ -110358,7 +110715,7 @@ async function cloudBackupCommand(argv, json2, io, dependencies) {
110358
110715
  }
110359
110716
  async function enrollCloudBackup(json2, io, dependencies) {
110360
110717
  const paths = getVapiPaths();
110361
- if (!await fileExists3(join27(paths.directory, "vault.json"))) {
110718
+ if (!await fileExists3(join28(paths.directory, "vault.json"))) {
110362
110719
  throw new Error("No vault on this device. Run vapi setup first.");
110363
110720
  }
110364
110721
  const context = await cloudContext(io, dependencies);
@@ -110470,7 +110827,7 @@ async function restoreFromOwnerCommand(argv, json2, io, dependencies) {
110470
110827
  }
110471
110828
  const expectedOwner = ownerValue?.toLowerCase();
110472
110829
  const paths = getVapiPaths();
110473
- if (await fileExists3(join27(paths.directory, "vault.json")) && !await fileExists3(join27(paths.directory, ".backup-restore.json"))) {
110830
+ if (await fileExists3(join28(paths.directory, "vault.json")) && !await fileExists3(join28(paths.directory, ".backup-restore.json"))) {
110474
110831
  throw new Error(
110475
110832
  `A vault already exists in ${paths.directory}. Move it aside before restoring.`
110476
110833
  );
@@ -110861,7 +111218,7 @@ function writeSkippedWarnings(io, skipped2) {
110861
111218
 
110862
111219
  // ../cli/src/setup.ts
110863
111220
  import { rm as rm5 } from "node:fs/promises";
110864
- import { join as join28 } from "node:path";
111221
+ import { join as join29 } from "node:path";
110865
111222
 
110866
111223
  // ../cli/src/identity.ts
110867
111224
  async function fetchWalletIdentity(options) {
@@ -111641,7 +111998,7 @@ async function readProcessStdin() {
111641
111998
  }
111642
111999
 
111643
112000
  // ../cli/src/version.ts
111644
- var CLI_VERSION = "0.16.0";
112001
+ var CLI_VERSION = "0.16.2";
111645
112002
 
111646
112003
  // ../cli/src/status.ts
111647
112004
  async function statusCommand(argv, json2, io, dependencies) {
@@ -111856,7 +112213,7 @@ async function setupCommand(argv, json2, io, dependencies) {
111856
112213
  steps.push("config");
111857
112214
  }
111858
112215
  const config2 = await readConfig(paths.config, humanIo);
111859
- if (!await fileExists3(join28(paths.directory, "vault.json"))) {
112216
+ if (!await fileExists3(join29(paths.directory, "vault.json"))) {
111860
112217
  const os = dependencies.secretBackendProbe ?? (dependencies.secretStore === void 0 ? osSecretStore() : void 0);
111861
112218
  if (os !== void 0) {
111862
112219
  await chooseSecretBackend({ home: paths.directory, os, env: getEnvironment(dependencies) });
@@ -111868,7 +112225,7 @@ async function setupCommand(argv, json2, io, dependencies) {
111868
112225
  let changedAccount = false;
111869
112226
  let changedLink = false;
111870
112227
  let scannedAddresses;
111871
- if (!await fileExists3(join28(paths.directory, "vault.json"))) {
112228
+ if (!await fileExists3(join29(paths.directory, "vault.json"))) {
111872
112229
  const choice = await vaultChoice(dependencies);
111873
112230
  if (choice === "restore") {
111874
112231
  if (!isInteractive(dependencies)) {
@@ -111956,7 +112313,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
111956
112313
  let scannedAddresses = 0;
111957
112314
  try {
111958
112315
  const restored = await restoreVault({
111959
- path: join28(paths.directory, "vault.json"),
112316
+ path: join29(paths.directory, "vault.json"),
111960
112317
  key: key2,
111961
112318
  phrase: validatedPhrase,
111962
112319
  probe: async (address10) => await readBalance3(address10) > 0n,
@@ -111967,7 +112324,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
111967
112324
  ...dependencies.now === void 0 ? {} : { now: dependencies.now }
111968
112325
  });
111969
112326
  names = restored.accounts().map((account) => account.name);
111970
- await rm5(join28(paths.directory, "wallets.json"), { force: true });
112327
+ await rm5(join29(paths.directory, "wallets.json"), { force: true });
111971
112328
  } finally {
111972
112329
  key2.fill(0);
111973
112330
  }
@@ -112050,7 +112407,7 @@ async function restoreCommand(argv, json2, io, dependencies) {
112050
112407
  }
112051
112408
  const accountCount = parseRestoreAccountCount(parsed.one("--accounts"));
112052
112409
  const paths = getVapiPaths();
112053
- const path = join29(paths.directory, "vault.json");
112410
+ const path = join30(paths.directory, "vault.json");
112054
112411
  if (await fileExists3(path)) {
112055
112412
  throw new Error(
112056
112413
  `A vault already exists in ${paths.directory}. Move it aside before restoring.`
@@ -112207,7 +112564,7 @@ function requireNoArguments2(argv) {
112207
112564
  parseArguments(argv, { valueOptions: /* @__PURE__ */ new Set(), maximumPositionals: 0 });
112208
112565
  }
112209
112566
  function vaultPath() {
112210
- return join29(getVapiPaths().directory, "vault.json");
112567
+ return join30(getVapiPaths().directory, "vault.json");
112211
112568
  }
112212
112569
  function quietIo(io) {
112213
112570
  return { stdout: () => void 0, stderr: io.stderr };
@@ -112301,7 +112658,7 @@ async function backupCommand(argv, json2, io, dependencies) {
112301
112658
  const target = await targetWallet(parsed, dependencies);
112302
112659
  const vaultAccount = await target.store.hasVaultAccount(target.name);
112303
112660
  if (vaultAccount) {
112304
- const vault = await readVaultFileUnlocked(join29(target.store.home, "vault.json"));
112661
+ const vault = await readVaultFileUnlocked(join30(target.store.home, "vault.json"));
112305
112662
  if (vault.accounts.some((account) => account.name === target.name && account.kind === "imported")) {
112306
112663
  throw new KeystoreError(
112307
112664
  `Account ${target.name} was imported and is not recoverable from the vault phrase. Back it up with vapi export-key --account ${target.name}.`
@@ -112378,7 +112735,7 @@ async function importCommand(argv, json2, io, dependencies) {
112378
112735
  const existed = store.has(name);
112379
112736
  if (existed && !parsed.has("--replace")) {
112380
112737
  const address10 = await store.readAddress(name);
112381
- const location = await store.hasVaultAccount(name) ? join29(store.home, "vault.json") : store.pathFor(name);
112738
+ const location = await store.hasVaultAccount(name) ? join30(store.home, "vault.json") : store.pathFor(name);
112382
112739
  throw new Error(
112383
112740
  [
112384
112741
  `Wallet ${name} already exists at ${location}.`,
@@ -112414,7 +112771,7 @@ async function importCommand(argv, json2, io, dependencies) {
112414
112771
  const result = {
112415
112772
  address: account.address,
112416
112773
  ...account.solana ? { solanaAddress: account.solana.address } : {},
112417
- vault: join29(paths.directory, "vault.json"),
112774
+ vault: join30(paths.directory, "vault.json"),
112418
112775
  ...previousKeystore ? { previousKeystore } : {},
112419
112776
  message: "Wallet imported. Its encrypted key stays on this machine."
112420
112777
  };
@@ -112615,7 +112972,8 @@ async function retireStoredPassphrase(target, dependencies, io) {
112615
112972
 
112616
112973
  // ../cli/src/accounts.ts
112617
112974
  import { readFile as readFile29, stat as stat18 } from "node:fs/promises";
112618
- import { join as join30 } from "node:path";
112975
+ import { join as join31 } from "node:path";
112976
+ import { createInterface as createInterface3 } from "node:readline/promises";
112619
112977
 
112620
112978
  // ../cli/src/dashboard.ts
112621
112979
  import { resolve as resolve3 } from "node:path";
@@ -113010,10 +113368,10 @@ async function accountsRenameCommand(argv, json2, io, dependencies) {
113010
113368
  {
113011
113369
  previous: from16,
113012
113370
  ...address10 === void 0 ? {} : { address: address10 },
113013
- vault: join30(store.home, "vault.json"),
113371
+ vault: join31(store.home, "vault.json"),
113014
113372
  message: `Wallet ${from16} is now ${renamed.name}.`
113015
113373
  },
113016
- [`Wallet ${from16} is now ${renamed.name}.`, `Vault: ${join30(store.home, "vault.json")}`].join(
113374
+ [`Wallet ${from16} is now ${renamed.name}.`, `Vault: ${join31(store.home, "vault.json")}`].join(
113017
113375
  "\n"
113018
113376
  )
113019
113377
  );
@@ -113122,33 +113480,44 @@ async function accountsRestoreCommand(argv, json2, io, dependencies) {
113122
113480
  { name: restored.name, ...address10 === void 0 ? {} : { address: address10 } },
113123
113481
  {
113124
113482
  ...address10 === void 0 ? {} : { address: address10 },
113125
- vault: join30(store.home, "vault.json"),
113483
+ vault: join31(store.home, "vault.json"),
113126
113484
  spendCaps: restored.entry.spendCaps,
113127
113485
  message: `Wallet ${restored.name} restored to the device vault.`
113128
113486
  },
113129
113487
  [
113130
113488
  `Wallet ${restored.name} restored to the device vault.`,
113131
- `Vault: ${join30(store.home, "vault.json")}`
113489
+ `Vault: ${join31(store.home, "vault.json")}`
113132
113490
  ].join("\n")
113133
113491
  );
113134
113492
  }
113135
113493
  async function accountsCapsCommand(argv, json2, io, dependencies) {
113136
113494
  const parsed = parseArguments(argv, {
113137
- valueOptions: /* @__PURE__ */ new Set(["--per-call", "--per-day", "--ceiling"]),
113495
+ valueOptions: /* @__PURE__ */ new Set([
113496
+ "--per-call",
113497
+ "--per-day",
113498
+ "--ceiling",
113499
+ "--max-per-task",
113500
+ "--approve-above"
113501
+ ]),
113502
+ booleanOptions: /* @__PURE__ */ new Set(["--yes"]),
113138
113503
  maximumPositionals: 1
113139
113504
  });
113140
- const name = requiredPositional(
113141
- parsed.positionals[0],
113142
- "<name>",
113143
- "Usage: vapi accounts caps <name> [--per-call <usd>] [--per-day <usd>] [--ceiling <usd|off>] [--json]"
113144
- );
113505
+ const name = requiredPositional(parsed.positionals[0], "<name>", CAPS_USAGE);
113145
113506
  const perCall = parsed.one("--per-call");
113146
113507
  const perDay = parsed.one("--per-day");
113147
113508
  const ceiling = parsed.one("--ceiling");
113509
+ const maxPerTask = parsed.one("--max-per-task");
113510
+ const approveAbove = parsed.one("--approve-above");
113148
113511
  const store = await openWalletStore(dependencies);
113149
113512
  const account = store.resolve({ name, env: {} });
113150
113513
  const address10 = await store.readAddress(account.name);
113151
- if (perCall === void 0 && perDay === void 0 && ceiling === void 0) {
113514
+ let taskPolicy = await taskPolicyForWallet({
113515
+ directory: store.home,
113516
+ wallet: account.name,
113517
+ schema: registeredAgentProfileSchema,
113518
+ warn: io.stderr
113519
+ });
113520
+ if (perCall === void 0 && perDay === void 0 && ceiling === void 0 && maxPerTask === void 0 && approveAbove === void 0) {
113152
113521
  const caps2 = capsOutput(account.entry.spendCaps, store.ceilingCaps(account.name));
113153
113522
  outputForWallet2(
113154
113523
  io,
@@ -113157,13 +113526,15 @@ async function accountsCapsCommand(argv, json2, io, dependencies) {
113157
113526
  {
113158
113527
  ...address10 === void 0 ? {} : { address: address10 },
113159
113528
  spendCaps: account.entry.spendCaps,
113160
- ...caps2
113529
+ ...caps2,
113530
+ taskLimits: taskLimitsJson(taskPolicy)
113161
113531
  },
113162
113532
  [
113163
113533
  walletHeader2({ name: account.name, ...address10 === void 0 ? {} : { address: address10 } }),
113164
113534
  `Spend caps: ${formatCaps(account.entry.spendCaps)}`,
113165
113535
  `Ceiling: ${caps2.ceilingUsd === "off" ? "off" : `${caps2.ceilingUsd} USDC`}`,
113166
- "Change them with --per-call <usd>, --per-day <usd>, or --ceiling <usd|off>."
113536
+ `Task limits: ${formatTaskLimits(taskPolicy)}`,
113537
+ "Change them with --per-call <usd>, --per-day <usd>, --ceiling <usd|off>, --max-per-task <usd>, or --approve-above <usd>."
113167
113538
  ].join("\n")
113168
113539
  );
113169
113540
  return;
@@ -113176,17 +113547,72 @@ async function accountsCapsCommand(argv, json2, io, dependencies) {
113176
113547
  throw new UsageError("The per-call cap cannot be larger than the per-day cap.");
113177
113548
  }
113178
113549
  const ceilingAtomic = ceiling === void 0 ? void 0 : ceiling === "off" ? null : BigInt(capAtomic(ceiling, "--ceiling"));
113550
+ const taskLimits = maxPerTask === void 0 && approveAbove === void 0 ? void 0 : {
113551
+ maxPerTaskUsd: maxPerTask === void 0 ? taskPolicy.maxPerTaskUsd : taskLimitUsd(maxPerTask, "--max-per-task"),
113552
+ approveAboveUsd: approveAbove === void 0 ? taskPolicy.approveAboveUsd : taskLimitUsd(approveAbove, "--approve-above")
113553
+ };
113554
+ const profile = taskLimits === void 0 || taskPolicy.source !== "agent-profile" ? void 0 : (await listAgentProfiles(store.home, {
113555
+ schema: registeredAgentProfileSchema,
113556
+ warn: () => {
113557
+ }
113558
+ })).find((candidate) => candidate.wallet === account.name);
113559
+ if (taskLimits !== void 0 && taskPolicy.source === "agent-profile" && !profile)
113560
+ throw new Error(`The agent profile of ${account.name} is unreadable.`);
113561
+ if (taskLimits !== void 0 && (taskLimits.maxPerTaskUsd > taskPolicy.maxPerTaskUsd || taskLimits.approveAboveUsd > taskPolicy.approveAboveUsd)) {
113562
+ const command = `vapi accounts caps ${account.name}${maxPerTask === void 0 ? "" : ` --max-per-task ${maxPerTask}`}${approveAbove === void 0 ? "" : ` --approve-above ${approveAbove}`}`;
113563
+ const marker = activeAgentMarker(getEnvironment(dependencies));
113564
+ if (marker !== void 0 || !isStdinInteractive(dependencies))
113565
+ throw new UsageError(
113566
+ `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}`
113567
+ );
113568
+ if (maxPerTask !== void 0 && taskLimits.maxPerTaskUsd > taskPolicy.maxPerTaskUsd) {
113569
+ const liveUsd = await liveTaskLimitUsd(dependencies);
113570
+ if (liveUsd !== void 0 && taskLimits.maxPerTaskUsd > liveUsd)
113571
+ io.stderr(
113572
+ `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.`
113573
+ );
113574
+ }
113575
+ if (!parsed.has("--yes")) {
113576
+ const question = `Raise the task limits of ${account.name} from ${formatTaskLimits(taskPolicy, false)} to ${formatTaskLimits(taskLimits, false)}? Type yes to confirm: `;
113577
+ if (json2 || !isInteractive(dependencies))
113578
+ throw new UsageError(
113579
+ `Raising a task limit needs your confirmation. Nothing was changed. Run it again with --yes: ${command} --yes`
113580
+ );
113581
+ if ((await visibleLine(question, dependencies)).trim().toLowerCase() !== "yes")
113582
+ throw new UsageError("Not confirmed. Nothing was changed.");
113583
+ }
113584
+ }
113179
113585
  let entry = account.entry;
113180
113586
  if (perCall !== void 0 || perDay !== void 0) {
113181
113587
  entry = await store.setSpendCaps(account.name, spendCaps);
113182
113588
  }
113183
113589
  if (ceilingAtomic !== void 0) entry = await store.setCeiling(account.name, ceilingAtomic);
113590
+ if (taskLimits !== void 0) {
113591
+ if (profile) {
113592
+ await writeAgentProfile(
113593
+ store.home,
113594
+ { ...profile, ...taskLimits },
113595
+ { schema: registeredAgentProfileSchema }
113596
+ );
113597
+ taskPolicy = { ...taskPolicy, ...taskLimits };
113598
+ } else {
113599
+ entry = await store.updateTaskPolicy(account.name, (current) => ({
113600
+ ...current,
113601
+ ...maxPerTask === void 0 ? {} : { maxPerTaskUsd: taskLimits.maxPerTaskUsd },
113602
+ ...approveAbove === void 0 ? {} : { approveAboveUsd: taskLimits.approveAboveUsd }
113603
+ }));
113604
+ taskPolicy = { ...taskPolicy, ...taskLimits, source: "account" };
113605
+ }
113606
+ }
113607
+ const taskLimitsChanged = taskLimits !== void 0;
113184
113608
  const caps = capsOutput(entry.spendCaps, store.ceilingCaps(account.name));
113185
113609
  await recordAudit(dependencies, "wallet.caps", {
113186
113610
  wallet: account.name,
113187
- detail: `${formatCaps(entry.spendCaps)}, ceiling ${caps.ceilingUsd === "off" ? "off" : `${caps.ceilingUsd} USDC`}`
113611
+ detail: `${formatCaps(entry.spendCaps)}, ceiling ${caps.ceilingUsd === "off" ? "off" : `${caps.ceilingUsd} USDC`}${taskLimitsChanged ? `, task limits ${formatTaskLimits(taskPolicy, false)}` : ""}`
113188
113612
  });
113189
- const message = perCall !== void 0 || perDay !== void 0 ? `Spend caps updated for ${account.name}.` : `Ceiling updated for ${account.name}.`;
113613
+ 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}.`;
113614
+ const perDayUsd = Number(formatUsdc(BigInt(entry.spendCaps.perDayAtomic)));
113615
+ 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;
113190
113616
  outputForWallet2(
113191
113617
  io,
113192
113618
  json2,
@@ -113195,15 +113621,67 @@ async function accountsCapsCommand(argv, json2, io, dependencies) {
113195
113621
  ...address10 === void 0 ? {} : { address: address10 },
113196
113622
  spendCaps: entry.spendCaps,
113197
113623
  ...caps,
113198
- message
113624
+ taskLimits: taskLimitsJson(taskPolicy),
113625
+ message,
113626
+ ...perDayHint === void 0 ? {} : { hint: perDayHint }
113199
113627
  },
113200
113628
  [
113201
113629
  message,
113202
113630
  `Spend caps: ${formatCaps(entry.spendCaps)}`,
113203
- `Ceiling: ${caps.ceilingUsd === "off" ? "off" : `${caps.ceilingUsd} USDC`}`
113631
+ `Ceiling: ${caps.ceilingUsd === "off" ? "off" : `${caps.ceilingUsd} USDC`}`,
113632
+ `Task limits: ${formatTaskLimits(taskPolicy)}`,
113633
+ ...perDayHint === void 0 ? [] : [perDayHint]
113204
113634
  ].join("\n")
113205
113635
  );
113206
113636
  }
113637
+ 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]";
113638
+ function taskLimitsJson(policy) {
113639
+ return {
113640
+ maxPerTaskUsd: policy.maxPerTaskUsd,
113641
+ approveAboveUsd: policy.approveAboveUsd,
113642
+ source: policy.source
113643
+ };
113644
+ }
113645
+ function formatTaskLimits(policy, withSource = true) {
113646
+ const source = policy.source === "agent-profile" ? "agent profile" : policy.source === "account" ? "set for this account" : "defaults";
113647
+ return `${policy.maxPerTaskUsd} USD per task, approval above ${policy.approveAboveUsd} USD${withSource && policy.source ? ` (${source})` : ""}`;
113648
+ }
113649
+ async function visibleLine(prompt, dependencies) {
113650
+ const line = getPrompts(dependencies).line;
113651
+ if (line) return await line(prompt);
113652
+ const reader = createInterface3({ input: process.stdin, output: process.stderr });
113653
+ try {
113654
+ return await reader.question(prompt);
113655
+ } finally {
113656
+ reader.close();
113657
+ }
113658
+ }
113659
+ var MAX_TASK_LIMIT_USD = 1e6;
113660
+ function taskLimitUsd(value, option) {
113661
+ const usd3 = Number(formatUsdc(BigInt(capAtomic(value, option))));
113662
+ if (!Number.isFinite(usd3) || usd3 > MAX_TASK_LIMIT_USD)
113663
+ throw new UsageError(`${option} must be at most ${MAX_TASK_LIMIT_USD} USD.`);
113664
+ return usd3;
113665
+ }
113666
+ async function liveTaskLimitUsd(dependencies) {
113667
+ try {
113668
+ const env = getEnvironment(dependencies);
113669
+ const rpcFor = dependencies.tasks?.rpcFor ?? createTasksRpcFor(await accountsConfig(dependencies), {
113670
+ env,
113671
+ ...dependencies.fetchImpl === void 0 ? {} : { fetch: dependencies.fetchImpl }
113672
+ });
113673
+ const limits = await readTaskV2Limits({
113674
+ chainId: 8453,
113675
+ shape: "task",
113676
+ rpcFor,
113677
+ env,
113678
+ timeoutMs: 2e3
113679
+ });
113680
+ return limits === void 0 ? void 0 : Number(formatUsdc(limits.maxBaseUnits));
113681
+ } catch {
113682
+ return void 0;
113683
+ }
113684
+ }
113207
113685
  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]";
113208
113686
  async function accountsDistributeCommand(argv, json2, io, dependencies) {
113209
113687
  const parsed = parseArguments(argv, {
@@ -113459,19 +113937,19 @@ function formatNetworkAccounts(accounts) {
113459
113937
 
113460
113938
  // ../cli/src/agent.ts
113461
113939
  import { readFile as readFile31, stat as stat19 } from "node:fs/promises";
113462
- import { join as join33 } from "node:path";
113463
- import { createInterface as createInterface3 } from "node:readline/promises";
113940
+ import { join as join34 } from "node:path";
113941
+ import { createInterface as createInterface4 } from "node:readline/promises";
113464
113942
 
113465
113943
  // ../cli/src/headless.ts
113466
113944
  import { rmSync } from "node:fs";
113467
113945
  import { chmod as chmod7, mkdtemp as mkdtemp2, rm as rm6, writeFile as writeFile9 } from "node:fs/promises";
113468
113946
  import { tmpdir as osTmpdir } from "node:os";
113469
- import { join as join31 } from "node:path";
113947
+ import { join as join32 } from "node:path";
113470
113948
  var BUNDLE_VARIABLE_PATTERN = /^[A-Z_][A-Z0-9_]*$/u;
113471
113949
  var REMOTE_BLOCKED_GRANTS2 = /* @__PURE__ */ new Set(["delegate", "allocate"]);
113472
113950
  var agentProfileOptions = { schema: registeredAgentProfileSchema };
113473
113951
  async function createHeadlessHome(bundle, options = {}) {
113474
- const home = await mkdtemp2(join31(options.tmpdir ?? osTmpdir(), "vapi-headless-"));
113952
+ const home = await mkdtemp2(join32(options.tmpdir ?? osTmpdir(), "vapi-headless-"));
113475
113953
  const cleanup = async () => {
113476
113954
  await rm6(home, { recursive: true, force: true });
113477
113955
  };
@@ -113683,7 +114161,7 @@ import {
113683
114161
  writeFile as nodeWriteFile
113684
114162
  } from "node:fs/promises";
113685
114163
  import { tmpdir as osTmpdir2 } from "node:os";
113686
- import { basename as basename4, dirname as dirname14, join as join32 } from "node:path";
114164
+ import { basename as basename4, dirname as dirname14, join as join33 } from "node:path";
113687
114165
  var RAILWAY_CLI = {
113688
114166
  binary: "railway",
113689
114167
  create: (options) => [
@@ -113874,7 +114352,7 @@ async function assertRemoteSafeMember(args) {
113874
114352
  }
113875
114353
  function railwaySidecarPath(home, runId) {
113876
114354
  if (!isRunId(runId)) throw new RuntimeError("invalid_run_id", `Invalid run id: ${runId}.`);
113877
- return join32(runsDirectory(home), `${runId}.railway.json`);
114355
+ return join33(runsDirectory(home), `${runId}.railway.json`);
113878
114356
  }
113879
114357
  function createRailwayRuntime(options) {
113880
114358
  const { home } = options;
@@ -114235,10 +114713,10 @@ ${destroyedInstruction}
114235
114713
  let createError;
114236
114714
  let cleanupError;
114237
114715
  try {
114238
- directory = await fs.mkdtemp(join32(options.tmpdir ?? osTmpdir2(), "vapi-railway-"));
114716
+ directory = await fs.mkdtemp(join33(options.tmpdir ?? osTmpdir2(), "vapi-railway-"));
114239
114717
  assertNotInterrupted();
114240
114718
  await assertMode(fs, directory, 448, "env-file directory");
114241
- envFile = join32(directory, "member.env");
114719
+ envFile = join33(directory, "member.env");
114242
114720
  await fs.writeFile(envFile, `${RAILWAY_CLI.bundleVariable}=${bundle}
114243
114721
  `, {
114244
114722
  encoding: "utf8",
@@ -114599,7 +115077,7 @@ Destroy it yourself with: railway sandbox destroy ${id2}`
114599
115077
  return { runId, sandboxId: id2, destroyed: true };
114600
115078
  };
114601
115079
  if (account !== void 0) return await withMemberRunLock(home, account, destroy);
114602
- return await withFileLock(join32(runsDirectory(home), `.sidecar-${runId}.lock`), destroy, {
115080
+ return await withFileLock(join33(runsDirectory(home), `.sidecar-${runId}.lock`), destroy, {
114603
115081
  timeoutMs: 5e3,
114604
115082
  lockedMessage: `Run ${runId} is changing sidecar state.`
114605
115083
  });
@@ -114821,7 +115299,7 @@ async function writeSidecar(home, runId, sidecar) {
114821
115299
  function writeSidecarSync(path, sidecar) {
114822
115300
  const directory = dirname14(path);
114823
115301
  mkdirSync(directory, { recursive: true, mode: 448 });
114824
- const temporary = join32(
115302
+ const temporary = join33(
114825
115303
  directory,
114826
115304
  `.${basename4(path)}.${process.pid}.${randomBytes17(6).toString("hex")}.tmp`
114827
115305
  );
@@ -114919,7 +115397,7 @@ async function assertMode(fs, path, mode, what) {
114919
115397
  }
114920
115398
  }
114921
115399
  async function deviceVaultKey2(home, secrets, now) {
114922
- const path = join32(home, "vault.json");
115400
+ const path = join33(home, "vault.json");
114923
115401
  const metadata = await readVaultFileUnlocked(path);
114924
115402
  const key2 = metadata.protected ? await unlockProtectedVault({
114925
115403
  path,
@@ -115290,24 +115768,42 @@ async function createCommand(argv, json2, io, dependencies) {
115290
115768
  const callBudget = usdOption(parsed.one("--call-budget") ?? "1", "--call-budget", true);
115291
115769
  const maxPerCall = usdOption(parsed.one("--max-per-call") ?? "0.05", "--max-per-call");
115292
115770
  const routerBudget = usdOption(parsed.one("--router-budget") ?? "1", "--router-budget", true);
115293
- const approveAbove = usdOption(parsed.one("--approve-above") ?? "0.5", "--approve-above");
115771
+ const initialStore = await openWalletStore(dependencies);
115772
+ const owned = initialStore.entry(name);
115773
+ const stricter = accountTaskLimitsUnderProfile(owned?.taskPolicy);
115774
+ const defaultMaxPerTask = stricter?.maxPerTaskUsd ?? DEFAULT_MAX_PER_TASK_USD;
115775
+ const approveAbove = usdOption(
115776
+ parsed.one("--approve-above") ?? String(stricter?.approveAboveUsd ?? 0.5),
115777
+ "--approve-above"
115778
+ );
115294
115779
  const maxSteps = boundedInteger(parsed.one("--max-steps") ?? "12", "--max-steps", 1, 50);
115295
115780
  const interactive = !json2 && (dependencies.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY));
115296
115781
  const promptForTaskPolicy = interactive && !parsed.has("--yes");
115297
115782
  const maxPerTask = usdOption(
115298
- 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)),
115783
+ parsed.one("--max-per-task") ?? ((promptForTaskPolicy ? await visibleLine2(`Max per task in USD [${defaultMaxPerTask}]: `, dependencies) : "") || String(defaultMaxPerTask)),
115299
115784
  "--max-per-task"
115300
115785
  );
115301
115786
  const autoReleaseBelow = usdOption(
115302
- parsed.one("--auto-release-below") ?? ((promptForTaskPolicy ? await visibleLine(
115787
+ parsed.one("--auto-release-below") ?? ((promptForTaskPolicy ? await visibleLine2(
115303
115788
  `Auto-release below in USD [${DEFAULT_AUTO_RELEASE_BELOW_USD}]: `,
115304
115789
  dependencies
115305
115790
  ) : "") || String(DEFAULT_AUTO_RELEASE_BELOW_USD)),
115306
115791
  "--auto-release-below"
115307
115792
  );
115793
+ if (owned !== void 0) {
115794
+ const raised = [
115795
+ ...maxPerTask.number > (owned.taskPolicy?.maxPerTaskUsd ?? DEFAULT_MAX_PER_TASK_USD) ? [`--max-per-task ${maxPerTask.text}`] : [],
115796
+ ...approveAbove.number > (owned.taskPolicy?.approveAboveUsd ?? 0.5) ? [`--approve-above ${approveAbove.text}`] : [],
115797
+ ...BigInt(callBudget.atomic) > BigInt(owned.spendCaps.perDayAtomic) ? [`--call-budget ${callBudget.text}`] : []
115798
+ ];
115799
+ const marker = activeAgentMarker(getEnvironment(dependencies));
115800
+ if (raised.length > 0 && (marker !== void 0 || !isStdinInteractive(dependencies)))
115801
+ throw new UsageError(
115802
+ `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.`
115803
+ );
115804
+ }
115308
115805
  const commandIo = json2 ? { stdout: () => void 0, stderr: io.stderr } : io;
115309
- const initialStore = await openWalletStore(dependencies);
115310
- if (!initialStore.has(name)) {
115806
+ if (owned === void 0) {
115311
115807
  await walletCreateCommand([name, "--label", name], json2, commandIo, dependencies);
115312
115808
  }
115313
115809
  await walletCapsCommand(
@@ -115332,6 +115828,20 @@ async function createCommand(argv, json2, io, dependencies) {
115332
115828
  paused: false,
115333
115829
  createdAt: (dependencies.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
115334
115830
  };
115831
+ let clearedAccountTaskLimits = false;
115832
+ const keptAccountTaskLimits = (await initialStore.updateTaskPolicy(name, (current) => {
115833
+ const kept = accountTaskLimitsUnderProfile(current);
115834
+ clearedAccountTaskLimits = JSON.stringify(kept) !== JSON.stringify(current);
115835
+ return kept;
115836
+ })).taskPolicy;
115837
+ if (keptAccountTaskLimits)
115838
+ io.stderr(
115839
+ `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.`
115840
+ );
115841
+ else if (clearedAccountTaskLimits)
115842
+ io.stderr(
115843
+ `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.`
115844
+ );
115335
115845
  const writeProfile = dependencies.agent?.writeAgentProfile ?? writeAgentProfile;
115336
115846
  await writeProfile(paths.directory, profile, agentProfileOptions2);
115337
115847
  await runLoginFlow(["--account", name, "--label", name], json2, commandIo, dependencies, {
@@ -115359,6 +115869,7 @@ async function createCommand(argv, json2, io, dependencies) {
115359
115869
  perDayAtomic: callBudget.atomic
115360
115870
  },
115361
115871
  routerAllowanceUsd: routerBudget.number,
115872
+ ...clearedAccountTaskLimits ? { clearedAccountTaskLimits: true } : {},
115362
115873
  fundingHint
115363
115874
  })
115364
115875
  );
@@ -115611,7 +116122,7 @@ async function buildAgentRunDeps(input2) {
115611
116122
  };
115612
116123
  const approve2 = async ({ ref, priceUsd, reason }) => {
115613
116124
  if (approvals === "decline" || !tty) return false;
115614
- const answer = await visibleLine(
116125
+ const answer = await visibleLine2(
115615
116126
  `Pay ${usd(priceUsd)} to ${ref}? ${reason} [y/N] `,
115616
116127
  dependencies
115617
116128
  );
@@ -115884,10 +116395,10 @@ function searchQuery(argumentsJson) {
115884
116395
  return void 0;
115885
116396
  }
115886
116397
  }
115887
- async function visibleLine(prompt, dependencies) {
116398
+ async function visibleLine2(prompt, dependencies) {
115888
116399
  if (dependencies.prompts?.line)
115889
116400
  return (await dependencies.prompts.line(prompt)).trim().toLowerCase();
115890
- const reader = createInterface3({ input: process.stdin, output: process.stderr });
116401
+ const reader = createInterface4({ input: process.stdin, output: process.stderr });
115891
116402
  try {
115892
116403
  return (await reader.question(prompt)).trim().toLowerCase();
115893
116404
  } finally {
@@ -115899,7 +116410,7 @@ function explicitWallet(name) {
115899
116410
  }
115900
116411
  async function profileFileExists(directory, name) {
115901
116412
  try {
115902
- await stat19(join33(directory, `${name}.json`));
116413
+ await stat19(join34(directory, `${name}.json`));
115903
116414
  return true;
115904
116415
  } catch (error61) {
115905
116416
  if (isMissingFile(error61)) return false;
@@ -116616,7 +117127,7 @@ import { constants as constants3, homedir as homedir4 } from "node:os";
116616
117127
  import { constants as constants2 } from "node:fs";
116617
117128
  import { access, mkdir as mkdir20, readFile as readFile32, realpath, unlink as unlink15, writeFile as writeFile10 } from "node:fs/promises";
116618
117129
  import { homedir as homedir3 } from "node:os";
116619
- import { basename as basename5, dirname as dirname15, join as join34, posix, win32 as win322 } from "node:path";
117130
+ import { basename as basename5, dirname as dirname15, join as join35, posix, win32 as win322 } from "node:path";
116620
117131
 
116621
117132
  // ../cli/src/toml-config.ts
116622
117133
  function removeTomlTables(contents, isTarget) {
@@ -116696,7 +117207,7 @@ var VAPI_CODEX_PROFILE = "vapi";
116696
117207
  var VAPI_CODEX_DEFAULT_MODEL = "venice/openai-gpt-61-sol";
116697
117208
  var VAPI_ROUTER_KEY_ENV = "VAPI_ROUTER_KEY";
116698
117209
  function codexConfigPath(env, home) {
116699
- return join34(env.CODEX_HOME || join34(home, ".codex"), "config.toml");
117210
+ return join35(env.CODEX_HOME || join35(home, ".codex"), "config.toml");
116700
117211
  }
116701
117212
  function hasVapiCodexProfile(contents) {
116702
117213
  const roots = new Set(
@@ -116812,7 +117323,7 @@ async function codeCommand(argv, json2, io, dependencies) {
116812
117323
  const env = getEnvironment(dependencies);
116813
117324
  const home = dependencies.code?.homedir ?? homedir3();
116814
117325
  const config2 = codexConfigPath(env, home);
116815
- const rcPaths = [join34(home, ".zshrc"), join34(home, ".bashrc")];
117326
+ const rcPaths = [join35(home, ".zshrc"), join35(home, ".bashrc")];
116816
117327
  if (command === "uninstall") {
116817
117328
  const removed = [];
116818
117329
  const previous = await readOptional(config2);
@@ -119058,7 +119569,8 @@ async function taskV2Command(verb, id2, parsed, json2, io, dependencies) {
119058
119569
  const policy = await taskPolicyForWallet({
119059
119570
  directory: getVapiPaths().directory,
119060
119571
  wallet: target.name,
119061
- schema: registeredAgentProfileSchema
119572
+ schema: registeredAgentProfileSchema,
119573
+ warn: io.stderr
119062
119574
  });
119063
119575
  try {
119064
119576
  const result = await executeTaskV2(context, {
@@ -119160,7 +119672,8 @@ async function taskJuryCommand(verb, id2, parsed, json2, io, dependencies) {
119160
119672
  policy: await taskPolicyForWallet({
119161
119673
  directory: getVapiPaths().directory,
119162
119674
  wallet: target.name,
119163
- schema: registeredAgentProfileSchema
119675
+ schema: registeredAgentProfileSchema,
119676
+ warn: io.stderr
119164
119677
  }),
119165
119678
  caps: await spendCapsForWallet(target.store, target.name),
119166
119679
  wallet: target.name,
@@ -119259,12 +119772,13 @@ var TASK_HELP = `Usage:
119259
119772
  vapi task watch <id> [--until <state>] [--auto-release] [--timeout 7d] [--interval 5s] [--counterparty <0x\u2026>] [--account <name>] [--json]
119260
119773
  vapi task status <id> [--operation <uuid> --step <v2-step> --recover|--abandon] [--account <name>] [--json]
119261
119774
 
119262
- 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.
119775
+ 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.
119263
119776
  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.
119264
119777
  Jury: ${TASK_V2_JURY_RULES} ${TASK_V2_REVIEWER_GUIDANCE} Jury open repeats while the case is Snapshotting.
119265
119778
  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.
119266
119779
  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.
119267
- 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.
119780
+ 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>].
119781
+ 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.
119268
119782
  The thread cursor is the previous page's nextBeforeSeq; --after reads older messages using beforeSeq.
119269
119783
  Every command accepts --json. Watch and a partially completed sign may write more than one JSON value. Human diagnostics go to stderr.
119270
119784
 
@@ -119447,6 +119961,10 @@ async function taskContext(parsed, io, dependencies, publicOnly = false) {
119447
119961
  const injected = dependencies.tasks?.client;
119448
119962
  const client = typeof injected === "function" ? injected(options) : injected ?? createHostedTasksClient(options);
119449
119963
  const pending = createPendingTransactions(getVapiPaths().directory);
119964
+ const readRpcFor = dependencies.tasks?.rpcFor ?? createTasksRpcFor(config2, {
119965
+ env,
119966
+ ...dependencies.fetchImpl === void 0 ? {} : { fetch: dependencies.fetchImpl }
119967
+ });
119450
119968
  const chain2 = dependencies.tasks?.chain ?? (publicOnly || target === void 0 ? missingTasksChain : lazyTasksChain2(
119451
119969
  async () => {
119452
119970
  const { account } = await unlockTarget(target, dependencies);
@@ -119473,6 +119991,7 @@ async function taskContext(parsed, io, dependencies, publicOnly = false) {
119473
119991
  ));
119474
119992
  return {
119475
119993
  client,
119994
+ limitsV2: (chainId, shape) => readTaskV2Limits({ chainId, shape, rpcFor: readRpcFor, env }),
119476
119995
  baseUrl,
119477
119996
  ...target === void 0 ? {} : { target },
119478
119997
  ...token === void 0 ? {} : { token },
@@ -119686,7 +120205,8 @@ async function taskCommandInner(argv, json2, io, dependencies) {
119686
120205
  budget: parsed.one("--budget"),
119687
120206
  gate: enumOption(parsed.one("--gate"), ["open", "proven"], "--gate"),
119688
120207
  verifier: enumOption(parsed.one("--verifier"), ["poster", "vapi"], "--verifier"),
119689
- openCheck: enumOption(parsed.one("--open-check"), ["allowlist", "invite"], "--open-check")
120208
+ openCheck: enumOption(parsed.one("--open-check"), ["allowlist", "invite"], "--open-check"),
120209
+ intake: enumOption(parsed.one("--intake"), ["proposals", "submissions"], "--intake")
119690
120210
  },
119691
120211
  now
119692
120212
  );
@@ -119719,7 +120239,9 @@ async function taskCommandInner(argv, json2, io, dependencies) {
119719
120239
  ...intake === void 0 ? {} : { intake },
119720
120240
  ...maxAwards === void 0 ? {} : { maxAwards },
119721
120241
  ...parsed.one("--webhook") === void 0 ? {} : { webhook: parsed.one("--webhook") },
119722
- onFeeUnavailable: () => io.stderr("The deployed fee is unavailable.")
120242
+ onFeeUnavailable: () => io.stderr(
120243
+ "The fee could not be read from the Tasks contract or from vAPI. Funding shows it before anything is signed."
120244
+ )
119723
120245
  });
119724
120246
  if (parsed.has("--fund")) {
119725
120247
  if (outcome.funding?.error) {
@@ -120586,7 +121108,7 @@ Usage:
120586
121108
  vapi accounts use <name> [--json]
120587
121109
  vapi accounts remove <name> [--force] [--json]
120588
121110
  vapi accounts restore <name> [--json]
120589
- vapi accounts caps <name> [--per-call <usd>] [--per-day <usd>] [--ceiling <usd|off>] [--json]
121111
+ vapi accounts caps <name> [--per-call <usd>] [--per-day <usd>] [--ceiling <usd|off>] [--max-per-task <usd>] [--approve-above <usd>] [--yes] [--json]
120590
121112
  vapi accounts distribute <amount> --from <account> [--to <a,b,c>] [--network base|arc] [--json]
120591
121113
  vapi accounts distribute --resume <id> [--replace-expired-restored] [--bind-legacy-addresses] [--json]
120592
121114
  vapi accounts distribute --cancel <id> [--replace-expired-restored] [--json]
@@ -120902,7 +121424,7 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
120902
121424
  break;
120903
121425
  case "unlock":
120904
121426
  io.stderr("vapi unlock is now vapi vault unlock; the old name works for one release.");
120905
- if (await fileExists3(join35(getVapiPaths().directory, "vault.json"))) {
121427
+ if (await fileExists3(join36(getVapiPaths().directory, "vault.json"))) {
120906
121428
  parseArguments(args.slice(1), {
120907
121429
  valueOptions: /* @__PURE__ */ new Set([WALLET_OPTION]),
120908
121430
  maximumPositionals: 0
@@ -121102,7 +121624,7 @@ async function initCommand(argv, json2, io, dependencies) {
121102
121624
  address: account.address,
121103
121625
  accounts,
121104
121626
  config: paths.config,
121105
- vault: join35(paths.directory, "vault.json"),
121627
+ vault: join36(paths.directory, "vault.json"),
121106
121628
  ...configRewrites.length > 0 ? { configRewrites } : {},
121107
121629
  custody: "self",
121108
121630
  warning: CUSTODY_NOTICE,
@@ -121241,7 +121763,7 @@ async function walletCreateCommand(argv, json2, io, dependencies) {
121241
121763
  const result = {
121242
121764
  address: account.address,
121243
121765
  ...account.solana ? { solanaAddress: account.solana.address } : {},
121244
- vault: join35(paths.directory, "vault.json"),
121766
+ vault: join36(paths.directory, "vault.json"),
121245
121767
  ...label2 === void 0 ? {} : { label: label2 },
121246
121768
  spendCaps: created.entry.spendCaps,
121247
121769
  isDefault,
@@ -121281,7 +121803,7 @@ function formatCaps2(caps) {
121281
121803
  function walletListResult(store, wallets, unlocked) {
121282
121804
  return {
121283
121805
  default: store.defaultName ?? null,
121284
- vault: join35(store.home, "vault.json"),
121806
+ vault: join36(store.home, "vault.json"),
121285
121807
  wallets: wallets.map((wallet) => ({
121286
121808
  name: wallet.name,
121287
121809
  ...wallet.address === void 0 ? {} : { address: wallet.address },
@@ -122335,14 +122857,14 @@ function isNewerVersion(latest, current) {
122335
122857
 
122336
122858
  // src/client.ts
122337
122859
  import { homedir as homedir5 } from "node:os";
122338
- import { join as join36 } from "node:path";
122860
+ import { join as join37 } from "node:path";
122339
122861
  var ACCOUNT_NOT_LINKED = "Not linked. Run vapi login on this machine, or set VAPI_HOME to a linked home.";
122340
122862
  var DISCOVERY_PATH2 = "/api/call/discovery";
122341
122863
  var warnedWalletOption = false;
122342
122864
  async function createVapiClient(options = {}) {
122343
122865
  if (options.wallet !== void 0) warnWalletOption();
122344
122866
  const env = options.env ?? process.env;
122345
- const home = options.home ?? (env.VAPI_HOME?.trim() || join36(homedir5(), ".vapi"));
122867
+ const home = options.home ?? (env.VAPI_HOME?.trim() || join37(homedir5(), ".vapi"));
122346
122868
  const paths = getVapiPaths(home);
122347
122869
  const requestedName = typeof options.account === "string" ? options.account : options.wallet;
122348
122870
  const injected = typeof options.account === "object" ? options.account : void 0;